main.cpp 28 KB

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