main.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. #include <Arduino.h> // needed for PlatformIO
  2. #include <Mesh.h>
  3. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  4. #include <InternalFileSystem.h>
  5. #elif defined(RP2040_PLATFORM)
  6. #include <LittleFS.h>
  7. #elif defined(ESP32)
  8. #include <SPIFFS.h>
  9. #endif
  10. #include <helpers/ArduinoHelpers.h>
  11. #include <helpers/StaticPoolPacketManager.h>
  12. #include <helpers/SimpleMeshTables.h>
  13. #include <helpers/IdentityStore.h>
  14. #include <helpers/AdvertDataHelpers.h>
  15. #include <helpers/TxtDataHelpers.h>
  16. #include <helpers/CommonCLI.h>
  17. #include <RTClib.h>
  18. #include <target.h>
  19. /* ------------------------------ Config -------------------------------- */
  20. #ifndef FIRMWARE_BUILD_DATE
  21. #define FIRMWARE_BUILD_DATE "1 Sep 2025"
  22. #endif
  23. #ifndef FIRMWARE_VERSION
  24. #define FIRMWARE_VERSION "v1.8.1"
  25. #endif
  26. #ifndef LORA_FREQ
  27. #define LORA_FREQ 915.0
  28. #endif
  29. #ifndef LORA_BW
  30. #define LORA_BW 250
  31. #endif
  32. #ifndef LORA_SF
  33. #define LORA_SF 10
  34. #endif
  35. #ifndef LORA_CR
  36. #define LORA_CR 5
  37. #endif
  38. #ifndef LORA_TX_POWER
  39. #define LORA_TX_POWER 20
  40. #endif
  41. #ifndef ADVERT_NAME
  42. #define ADVERT_NAME "repeater"
  43. #endif
  44. #ifndef ADVERT_LAT
  45. #define ADVERT_LAT 0.0
  46. #endif
  47. #ifndef ADVERT_LON
  48. #define ADVERT_LON 0.0
  49. #endif
  50. #ifndef ADMIN_PASSWORD
  51. #define ADMIN_PASSWORD "password"
  52. #endif
  53. #ifndef SERVER_RESPONSE_DELAY
  54. #define SERVER_RESPONSE_DELAY 300
  55. #endif
  56. #ifndef TXT_ACK_DELAY
  57. #define TXT_ACK_DELAY 200
  58. #endif
  59. #ifdef DISPLAY_CLASS
  60. #include "UITask.h"
  61. static UITask ui_task(display);
  62. #endif
  63. #define FIRMWARE_ROLE "repeater"
  64. #define PACKET_LOG_FILE "/packet_log"
  65. /* ------------------------------ Code -------------------------------- */
  66. #ifdef WITH_RS232_BRIDGE
  67. #include "helpers/bridges/RS232Bridge.h"
  68. #define WITH_BRIDGE
  69. #endif
  70. #ifdef WITH_ESPNOW_BRIDGE
  71. #include "helpers/bridges/ESPNowBridge.h"
  72. #define WITH_BRIDGE
  73. #endif
  74. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  75. #define REQ_TYPE_KEEP_ALIVE 0x02
  76. #define REQ_TYPE_GET_TELEMETRY_DATA 0x03
  77. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  78. struct RepeaterStats {
  79. uint16_t batt_milli_volts;
  80. uint16_t curr_tx_queue_len;
  81. int16_t noise_floor;
  82. int16_t last_rssi;
  83. uint32_t n_packets_recv;
  84. uint32_t n_packets_sent;
  85. uint32_t total_air_time_secs;
  86. uint32_t total_up_time_secs;
  87. uint32_t n_sent_flood, n_sent_direct;
  88. uint32_t n_recv_flood, n_recv_direct;
  89. uint16_t err_events; // was 'n_full_events'
  90. int16_t last_snr; // x 4
  91. uint16_t n_direct_dups, n_flood_dups;
  92. uint32_t total_rx_air_time_secs;
  93. };
  94. struct ClientInfo {
  95. mesh::Identity id;
  96. uint32_t last_timestamp, last_activity;
  97. uint8_t secret[PUB_KEY_SIZE];
  98. bool is_admin;
  99. int8_t out_path_len;
  100. uint8_t out_path[MAX_PATH_SIZE];
  101. };
  102. #ifndef MAX_CLIENTS
  103. #define MAX_CLIENTS 32
  104. #endif
  105. struct NeighbourInfo {
  106. mesh::Identity id;
  107. uint32_t advert_timestamp;
  108. uint32_t heard_timestamp;
  109. int8_t snr; // multiplied by 4, user should divide to get float value
  110. };
  111. #define CLI_REPLY_DELAY_MILLIS 600
  112. class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
  113. FILESYSTEM* _fs;
  114. unsigned long next_local_advert, next_flood_advert;
  115. bool _logging;
  116. NodePrefs _prefs;
  117. CommonCLI _cli;
  118. uint8_t reply_data[MAX_PACKET_PAYLOAD];
  119. ClientInfo known_clients[MAX_CLIENTS];
  120. #if MAX_NEIGHBOURS
  121. NeighbourInfo neighbours[MAX_NEIGHBOURS];
  122. #endif
  123. CayenneLPP telemetry;
  124. unsigned long set_radio_at, revert_radio_at;
  125. float pending_freq;
  126. float pending_bw;
  127. uint8_t pending_sf;
  128. uint8_t pending_cr;
  129. #if defined(WITH_RS232_BRIDGE)
  130. RS232Bridge bridge;
  131. #elif defined(WITH_ESPNOW_BRIDGE)
  132. ESPNowBridge bridge;
  133. #endif
  134. ClientInfo* putClient(const mesh::Identity& id) {
  135. uint32_t min_time = 0xFFFFFFFF;
  136. ClientInfo* oldest = &known_clients[0];
  137. for (int i = 0; i < MAX_CLIENTS; i++) {
  138. if (known_clients[i].last_activity < min_time) {
  139. oldest = &known_clients[i];
  140. min_time = oldest->last_activity;
  141. }
  142. if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
  143. }
  144. oldest->id = id;
  145. oldest->out_path_len = -1; // initially out_path is unknown
  146. oldest->last_timestamp = 0;
  147. return oldest;
  148. }
  149. void putNeighbour(const mesh::Identity& id, uint32_t timestamp, float snr) {
  150. #if MAX_NEIGHBOURS // check if neighbours enabled
  151. // find existing neighbour, else use least recently updated
  152. uint32_t oldest_timestamp = 0xFFFFFFFF;
  153. NeighbourInfo* neighbour = &neighbours[0];
  154. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  155. // if neighbour already known, we should update it
  156. if (id.matches(neighbours[i].id)) {
  157. neighbour = &neighbours[i];
  158. break;
  159. }
  160. // otherwise we should update the least recently updated neighbour
  161. if (neighbours[i].heard_timestamp < oldest_timestamp) {
  162. neighbour = &neighbours[i];
  163. oldest_timestamp = neighbour->heard_timestamp;
  164. }
  165. }
  166. // update neighbour info
  167. neighbour->id = id;
  168. neighbour->advert_timestamp = timestamp;
  169. neighbour->heard_timestamp = getRTCClock()->getCurrentTime();
  170. neighbour->snr = (int8_t) (snr * 4);
  171. #endif
  172. }
  173. int handleRequest(ClientInfo* sender, uint32_t sender_timestamp, uint8_t* payload, size_t payload_len) {
  174. // uint32_t now = getRTCClock()->getCurrentTimeUnique();
  175. // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  176. memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  177. switch (payload[0]) {
  178. case REQ_TYPE_GET_STATUS: { // guests can also access this now
  179. RepeaterStats stats;
  180. stats.batt_milli_volts = board.getBattMilliVolts();
  181. stats.curr_tx_queue_len = _mgr->getOutboundCount(0xFFFFFFFF);
  182. stats.noise_floor = (int16_t)_radio->getNoiseFloor();
  183. stats.last_rssi = (int16_t) radio_driver.getLastRSSI();
  184. stats.n_packets_recv = radio_driver.getPacketsRecv();
  185. stats.n_packets_sent = radio_driver.getPacketsSent();
  186. stats.total_air_time_secs = getTotalAirTime() / 1000;
  187. stats.total_up_time_secs = _ms->getMillis() / 1000;
  188. stats.n_sent_flood = getNumSentFlood();
  189. stats.n_sent_direct = getNumSentDirect();
  190. stats.n_recv_flood = getNumRecvFlood();
  191. stats.n_recv_direct = getNumRecvDirect();
  192. stats.err_events = _err_flags;
  193. stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
  194. stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
  195. stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
  196. stats.total_rx_air_time_secs = getReceiveAirTime() / 1000;
  197. memcpy(&reply_data[4], &stats, sizeof(stats));
  198. return 4 + sizeof(stats); // reply_len
  199. }
  200. case REQ_TYPE_GET_TELEMETRY_DATA: {
  201. uint8_t perm_mask = ~(payload[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions
  202. telemetry.reset();
  203. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  204. // query other sensors -- target specific
  205. sensors.querySensors((sender->is_admin ? 0xFF : 0x00) & perm_mask, telemetry);
  206. uint8_t tlen = telemetry.getSize();
  207. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  208. return 4 + tlen; // reply_len
  209. }
  210. }
  211. return 0; // unknown command
  212. }
  213. mesh::Packet* createSelfAdvert() {
  214. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  215. uint8_t app_data_len;
  216. {
  217. AdvertDataBuilder builder(ADV_TYPE_REPEATER, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  218. app_data_len = builder.encodeTo(app_data);
  219. }
  220. return createAdvert(self_id, app_data, app_data_len);
  221. }
  222. File openAppend(const char* fname) {
  223. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  224. return _fs->open(fname, FILE_O_WRITE);
  225. #elif defined(RP2040_PLATFORM)
  226. return _fs->open(fname, "a");
  227. #else
  228. return _fs->open(fname, "a", true);
  229. #endif
  230. }
  231. protected:
  232. float getAirtimeBudgetFactor() const override {
  233. return _prefs.airtime_factor;
  234. }
  235. bool allowPacketForward(const mesh::Packet* packet) override {
  236. if (_prefs.disable_fwd) return false;
  237. if (packet->isRouteFlood() && packet->path_len >= _prefs.flood_max) return false;
  238. return true;
  239. }
  240. const char* getLogDateTime() override {
  241. static char tmp[32];
  242. uint32_t now = getRTCClock()->getCurrentTime();
  243. DateTime dt = DateTime(now);
  244. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(), dt.year());
  245. return tmp;
  246. }
  247. void logRxRaw(float snr, float rssi, const uint8_t raw[], int len) override {
  248. #if MESH_PACKET_LOGGING
  249. Serial.print(getLogDateTime());
  250. Serial.print(" RAW: ");
  251. mesh::Utils::printHex(Serial, raw, len);
  252. Serial.println();
  253. #endif
  254. }
  255. void logRx(mesh::Packet* pkt, int len, float score) override {
  256. if (_logging) {
  257. File f = openAppend(PACKET_LOG_FILE);
  258. if (f) {
  259. f.print(getLogDateTime());
  260. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d",
  261. len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  262. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score*1000));
  263. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ
  264. || pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  265. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  266. } else {
  267. f.printf("\n");
  268. }
  269. f.close();
  270. }
  271. }
  272. }
  273. void logTx(mesh::Packet* pkt, int len) override {
  274. #ifdef WITH_BRIDGE
  275. bridge.onPacketTransmitted(pkt);
  276. #endif
  277. if (_logging) {
  278. File f = openAppend(PACKET_LOG_FILE);
  279. if (f) {
  280. f.print(getLogDateTime());
  281. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)",
  282. len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  283. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ
  284. || pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  285. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  286. } else {
  287. f.printf("\n");
  288. }
  289. f.close();
  290. }
  291. }
  292. }
  293. void logTxFail(mesh::Packet* pkt, int len) override {
  294. if (_logging) {
  295. File f = openAppend(PACKET_LOG_FILE);
  296. if (f) {
  297. f.print(getLogDateTime());
  298. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n",
  299. len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  300. f.close();
  301. }
  302. }
  303. }
  304. int calcRxDelay(float score, uint32_t air_time) const override {
  305. if (_prefs.rx_delay_base <= 0.0f) return 0;
  306. return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  307. }
  308. uint32_t getRetransmitDelay(const mesh::Packet* packet) override {
  309. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  310. return getRNG()->nextInt(0, 6)*t;
  311. }
  312. uint32_t getDirectRetransmitDelay(const mesh::Packet* packet) override {
  313. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  314. return getRNG()->nextInt(0, 6)*t;
  315. }
  316. int getInterferenceThreshold() const override {
  317. return _prefs.interference_threshold;
  318. }
  319. int getAGCResetInterval() const override {
  320. return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds
  321. }
  322. uint8_t getExtraAckTransmitCount() const override {
  323. return _prefs.multi_acks;
  324. }
  325. void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override {
  326. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
  327. uint32_t timestamp;
  328. memcpy(&timestamp, data, 4);
  329. bool is_admin;
  330. data[len] = 0; // ensure null terminator
  331. if (strcmp((char *) &data[4], _prefs.password) == 0) { // check for valid password
  332. is_admin = true;
  333. } else if (strcmp((char *) &data[4], _prefs.guest_password) == 0) { // check guest password
  334. is_admin = false;
  335. } else {
  336. #if MESH_DEBUG
  337. MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]);
  338. #endif
  339. return;
  340. }
  341. auto client = putClient(sender); // add to known clients (if not already known)
  342. if (timestamp <= client->last_timestamp) {
  343. MESH_DEBUG_PRINTLN("Possible login replay attack!");
  344. return; // FATAL: client table is full -OR- replay attack
  345. }
  346. MESH_DEBUG_PRINTLN("Login success!");
  347. client->last_timestamp = timestamp;
  348. client->last_activity = getRTCClock()->getCurrentTime();
  349. client->is_admin = is_admin;
  350. memcpy(client->secret, secret, PUB_KEY_SIZE);
  351. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  352. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  353. #if 0
  354. memcpy(&reply_data[4], "OK", 2); // legacy response
  355. #else
  356. reply_data[4] = RESP_SERVER_LOGIN_OK;
  357. reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16)
  358. reply_data[6] = is_admin ? 1 : 0;
  359. reply_data[7] = 0; // FUTURE: reserved
  360. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  361. #endif
  362. if (packet->isRouteFlood()) {
  363. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  364. mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
  365. PAYLOAD_TYPE_RESPONSE, reply_data, 12);
  366. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  367. } else {
  368. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 12);
  369. if (reply) {
  370. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  371. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  372. } else {
  373. sendFlood(reply, SERVER_RESPONSE_DELAY);
  374. }
  375. }
  376. }
  377. }
  378. }
  379. int matching_peer_indexes[MAX_CLIENTS];
  380. int searchPeersByHash(const uint8_t* hash) override {
  381. int n = 0;
  382. for (int i = 0; i < MAX_CLIENTS; i++) {
  383. if (known_clients[i].id.isHashMatch(hash)) {
  384. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  385. }
  386. }
  387. return n;
  388. }
  389. void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
  390. int i = matching_peer_indexes[peer_idx];
  391. if (i >= 0 && i < MAX_CLIENTS) {
  392. // lookup pre-calculated shared_secret
  393. memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
  394. } else {
  395. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  396. }
  397. }
  398. void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) {
  399. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  400. // if this a zero hop advert, add it to neighbours
  401. if (packet->path_len == 0) {
  402. AdvertDataParser parser(app_data, app_data_len);
  403. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  404. putNeighbour(id, timestamp, packet->getSNR());
  405. }
  406. }
  407. }
  408. void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override {
  409. int i = matching_peer_indexes[sender_idx];
  410. if (i < 0 || i >= MAX_CLIENTS) { // get from our known_clients table (sender SHOULD already be known in this context)
  411. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  412. return;
  413. }
  414. auto client = &known_clients[i];
  415. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  416. uint32_t timestamp;
  417. memcpy(&timestamp, data, 4);
  418. if (timestamp > client->last_timestamp) { // prevent replay attacks
  419. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  420. if (reply_len == 0) return; // invalid command
  421. client->last_timestamp = timestamp;
  422. client->last_activity = getRTCClock()->getCurrentTime();
  423. if (packet->isRouteFlood()) {
  424. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  425. mesh::Packet* path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  426. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  427. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  428. } else {
  429. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  430. if (reply) {
  431. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  432. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  433. } else {
  434. sendFlood(reply, SERVER_RESPONSE_DELAY);
  435. }
  436. }
  437. }
  438. } else {
  439. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  440. }
  441. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->is_admin) { // a CLI command
  442. uint32_t sender_timestamp;
  443. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  444. uint flags = (data[4] >> 2); // message attempt number, and other flags
  445. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  446. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  447. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  448. bool is_retry = (sender_timestamp == client->last_timestamp);
  449. client->last_timestamp = sender_timestamp;
  450. client->last_activity = getRTCClock()->getCurrentTime();
  451. // len can be > original length, but 'text' will be padded with zeroes
  452. data[len] = 0; // need to make a C string again, with null terminator
  453. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  454. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
  455. mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key, PUB_KEY_SIZE);
  456. mesh::Packet* ack = createAck(ack_hash);
  457. if (ack) {
  458. if (client->out_path_len < 0) {
  459. sendFlood(ack, TXT_ACK_DELAY);
  460. } else {
  461. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  462. }
  463. }
  464. }
  465. uint8_t temp[166];
  466. char *command = (char *) &data[5];
  467. char *reply = (char *) &temp[5];
  468. if (is_retry) {
  469. *reply = 0;
  470. } else {
  471. handleCommand(sender_timestamp, command, reply);
  472. }
  473. int text_len = strlen(reply);
  474. if (text_len > 0) {
  475. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  476. if (timestamp == sender_timestamp) {
  477. // WORKAROUND: the two timestamps need to be different, in the CLI view
  478. timestamp++;
  479. }
  480. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  481. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  482. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  483. if (reply) {
  484. if (client->out_path_len < 0) {
  485. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  486. } else {
  487. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  488. }
  489. }
  490. }
  491. } else {
  492. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  493. }
  494. }
  495. }
  496. bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
  497. // TODO: prevent replay attacks
  498. int i = matching_peer_indexes[sender_idx];
  499. if (i >= 0 && i < MAX_CLIENTS) { // get from our known_clients table (sender SHOULD already be known in this context)
  500. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t) path_len);
  501. auto client = &known_clients[i];
  502. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  503. } else {
  504. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  505. }
  506. // NOTE: no reciprocal path send!!
  507. return false;
  508. }
  509. public:
  510. MyMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  511. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  512. _cli(board, rtc, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4)
  513. #if defined(WITH_RS232_BRIDGE)
  514. , bridge(WITH_RS232_BRIDGE, _mgr, &rtc)
  515. #elif defined(WITH_ESPNOW_BRIDGE)
  516. , bridge(_mgr, &rtc)
  517. #endif
  518. {
  519. memset(known_clients, 0, sizeof(known_clients));
  520. next_local_advert = next_flood_advert = 0;
  521. set_radio_at = revert_radio_at = 0;
  522. _logging = false;
  523. #if MAX_NEIGHBOURS
  524. memset(neighbours, 0, sizeof(neighbours));
  525. #endif
  526. // defaults
  527. memset(&_prefs, 0, sizeof(_prefs));
  528. _prefs.airtime_factor = 1.0; // one half
  529. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  530. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  531. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  532. _prefs.node_lat = ADVERT_LAT;
  533. _prefs.node_lon = ADVERT_LON;
  534. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  535. _prefs.freq = LORA_FREQ;
  536. _prefs.sf = LORA_SF;
  537. _prefs.bw = LORA_BW;
  538. _prefs.cr = LORA_CR;
  539. _prefs.tx_power_dbm = LORA_TX_POWER;
  540. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  541. _prefs.flood_advert_interval = 12; // 12 hours
  542. _prefs.flood_max = 64;
  543. _prefs.interference_threshold = 0; // disabled
  544. }
  545. void begin(FILESYSTEM* fs) {
  546. mesh::Mesh::begin();
  547. _fs = fs;
  548. // load persisted prefs
  549. _cli.loadPrefs(_fs);
  550. #ifdef WITH_BRIDGE
  551. bridge.begin();
  552. #endif
  553. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  554. radio_set_tx_power(_prefs.tx_power_dbm);
  555. updateAdvertTimer();
  556. updateFloodAdvertTimer();
  557. }
  558. const char* getFirmwareVer() override { return FIRMWARE_VERSION; }
  559. const char* getBuildDate() override { return FIRMWARE_BUILD_DATE; }
  560. const char* getRole() override { return FIRMWARE_ROLE; }
  561. const char* getNodeName() { return _prefs.node_name; }
  562. NodePrefs* getNodePrefs() {
  563. return &_prefs;
  564. }
  565. void savePrefs() override {
  566. _cli.savePrefs(_fs);
  567. }
  568. void applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) override {
  569. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  570. pending_freq = freq;
  571. pending_bw = bw;
  572. pending_sf = sf;
  573. pending_cr = cr;
  574. revert_radio_at = futureMillis(2000 + timeout_mins*60*1000); // schedule when to revert radio params
  575. }
  576. bool formatFileSystem() override {
  577. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  578. return InternalFS.format();
  579. #elif defined(RP2040_PLATFORM)
  580. return LittleFS.format();
  581. #elif defined(ESP32)
  582. return SPIFFS.format();
  583. #else
  584. #error "need to implement file system erase"
  585. return false;
  586. #endif
  587. }
  588. void sendSelfAdvertisement(int delay_millis) override {
  589. mesh::Packet* pkt = createSelfAdvert();
  590. if (pkt) {
  591. sendFlood(pkt, delay_millis);
  592. } else {
  593. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  594. }
  595. }
  596. void updateAdvertTimer() override {
  597. if (_prefs.advert_interval > 0) { // schedule local advert timer
  598. next_local_advert = futureMillis( ((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  599. } else {
  600. next_local_advert = 0; // stop the timer
  601. }
  602. }
  603. void updateFloodAdvertTimer() override {
  604. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  605. next_flood_advert = futureMillis( ((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  606. } else {
  607. next_flood_advert = 0; // stop the timer
  608. }
  609. }
  610. void setLoggingOn(bool enable) override { _logging = enable; }
  611. void eraseLogFile() override {
  612. _fs->remove(PACKET_LOG_FILE);
  613. }
  614. void dumpLogFile() override {
  615. #if defined(RP2040_PLATFORM)
  616. File f = _fs->open(PACKET_LOG_FILE, "r");
  617. #else
  618. File f = _fs->open(PACKET_LOG_FILE);
  619. #endif
  620. if (f) {
  621. while (f.available()) {
  622. int c = f.read();
  623. if (c < 0) break;
  624. Serial.print((char)c);
  625. }
  626. f.close();
  627. }
  628. }
  629. void setTxPower(uint8_t power_dbm) override {
  630. radio_set_tx_power(power_dbm);
  631. }
  632. void formatNeighborsReply(char *reply) override {
  633. char *dp = reply;
  634. #if MAX_NEIGHBOURS
  635. for (int i = 0; i < MAX_NEIGHBOURS && dp - reply < 134; i++) {
  636. NeighbourInfo* neighbour = &neighbours[i];
  637. if (neighbour->heard_timestamp == 0) continue; // skip empty slots
  638. // add new line if not first item
  639. if (i > 0) *dp++ = '\n';
  640. char hex[10];
  641. // get 4 bytes of neighbour id as hex
  642. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  643. // add next neighbour
  644. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  645. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  646. while (*dp) dp++; // find end of string
  647. }
  648. #endif
  649. if (dp == reply) { // no neighbours, need empty response
  650. strcpy(dp, "-none-"); dp += 6;
  651. }
  652. *dp = 0; // null terminator
  653. }
  654. void removeNeighbor(const uint8_t* pubkey, int key_len) override {
  655. #if MAX_NEIGHBOURS
  656. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  657. NeighbourInfo* neighbour = &neighbours[i];
  658. if(memcmp(neighbour->id.pub_key, pubkey, key_len) == 0){
  659. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  660. }
  661. }
  662. #endif
  663. }
  664. mesh::LocalIdentity& getSelfId() override { return self_id; }
  665. void saveIdentity(const mesh::LocalIdentity& new_id) override {
  666. self_id = new_id;
  667. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  668. IdentityStore store(*_fs, "");
  669. #elif defined(ESP32)
  670. IdentityStore store(*_fs, "/identity");
  671. #elif defined(RP2040_PLATFORM)
  672. IdentityStore store(*_fs, "/identity");
  673. #else
  674. #error "need to define saveIdentity()"
  675. #endif
  676. store.save("_main", self_id);
  677. }
  678. void clearStats() override {
  679. radio_driver.resetStats();
  680. resetStats();
  681. ((SimpleMeshTables *)getTables())->resetStats();
  682. }
  683. void handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
  684. while (*command == ' ') command++; // skip leading spaces
  685. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  686. memcpy(reply, command, 3); // reflect the prefix back
  687. reply += 3;
  688. command += 3;
  689. }
  690. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  691. }
  692. void loop() {
  693. #ifdef WITH_BRIDGE
  694. bridge.loop();
  695. #endif
  696. mesh::Mesh::loop();
  697. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  698. mesh::Packet* pkt = createSelfAdvert();
  699. if (pkt) sendFlood(pkt);
  700. updateFloodAdvertTimer(); // schedule next flood advert
  701. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  702. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  703. mesh::Packet* pkt = createSelfAdvert();
  704. if (pkt) sendZeroHop(pkt);
  705. updateAdvertTimer(); // schedule next local advert
  706. }
  707. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  708. set_radio_at = 0; // clear timer
  709. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  710. MESH_DEBUG_PRINTLN("Temp radio params");
  711. }
  712. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  713. revert_radio_at = 0; // clear timer
  714. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  715. MESH_DEBUG_PRINTLN("Radio params restored");
  716. }
  717. #ifdef DISPLAY_CLASS
  718. ui_task.loop();
  719. #endif
  720. }
  721. };
  722. StdRNG fast_rng;
  723. SimpleMeshTables tables;
  724. MyMesh the_mesh(board, radio_driver, *new ArduinoMillis(), fast_rng, rtc_clock, tables);
  725. void halt() {
  726. while (1) ;
  727. }
  728. static char command[160];
  729. void setup() {
  730. Serial.begin(115200);
  731. delay(1000);
  732. board.begin();
  733. #ifdef DISPLAY_CLASS
  734. if (display.begin()) {
  735. display.startFrame();
  736. display.setCursor(0, 0);
  737. display.print("Please wait...");
  738. display.endFrame();
  739. }
  740. #endif
  741. if (!radio_init()) {
  742. halt();
  743. }
  744. fast_rng.begin(radio_get_rng_seed());
  745. FILESYSTEM* fs;
  746. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  747. InternalFS.begin();
  748. fs = &InternalFS;
  749. IdentityStore store(InternalFS, "");
  750. #elif defined(ESP32)
  751. SPIFFS.begin(true);
  752. fs = &SPIFFS;
  753. IdentityStore store(SPIFFS, "/identity");
  754. #elif defined(RP2040_PLATFORM)
  755. LittleFS.begin();
  756. fs = &LittleFS;
  757. IdentityStore store(LittleFS, "/identity");
  758. store.begin();
  759. #else
  760. #error "need to define filesystem"
  761. #endif
  762. if (!store.load("_main", the_mesh.self_id)) {
  763. MESH_DEBUG_PRINTLN("Generating new keypair");
  764. the_mesh.self_id = radio_new_identity(); // create new random identity
  765. int count = 0;
  766. while (count < 10 && (the_mesh.self_id.pub_key[0] == 0x00 || the_mesh.self_id.pub_key[0] == 0xFF)) { // reserved id hashes
  767. the_mesh.self_id = radio_new_identity(); count++;
  768. }
  769. store.save("_main", the_mesh.self_id);
  770. }
  771. Serial.print("Repeater ID: ");
  772. mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println();
  773. command[0] = 0;
  774. sensors.begin();
  775. the_mesh.begin(fs);
  776. #ifdef DISPLAY_CLASS
  777. ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION);
  778. #endif
  779. // send out initial Advertisement to the mesh
  780. the_mesh.sendSelfAdvertisement(16000);
  781. }
  782. void loop() {
  783. int len = strlen(command);
  784. while (Serial.available() && len < sizeof(command)-1) {
  785. char c = Serial.read();
  786. if (c != '\n') {
  787. command[len++] = c;
  788. command[len] = 0;
  789. }
  790. Serial.print(c);
  791. }
  792. if (len == sizeof(command)-1) { // command buffer full
  793. command[sizeof(command)-1] = '\r';
  794. }
  795. if (len > 0 && command[len - 1] == '\r') { // received complete line
  796. command[len - 1] = 0; // replace newline with C string null terminator
  797. char reply[160];
  798. the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial!
  799. if (reply[0]) {
  800. Serial.print(" -> "); Serial.println(reply);
  801. }
  802. command[0] = 0; // reset command buffer
  803. }
  804. the_mesh.loop();
  805. sensors.loop();
  806. }