main.cpp 28 KB

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