main.cpp 29 KB

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