main.cpp 22 KB

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