main.cpp 27 KB

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