main.cpp 27 KB

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