main.cpp 24 KB

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