main.cpp 25 KB

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