main.cpp 24 KB

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