main.cpp 22 KB

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