main.cpp 23 KB

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