main.cpp 25 KB

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