main.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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 "Test BBS"
  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. #ifndef MAX_CLIENTS
  54. #define MAX_CLIENTS 32
  55. #endif
  56. #ifndef MAX_UNSYNCED_POSTS
  57. #define MAX_UNSYNCED_POSTS 16
  58. #endif
  59. #if defined(HELTEC_LORA_V3)
  60. #include <helpers/HeltecV3Board.h>
  61. #include <helpers/CustomSX1262Wrapper.h>
  62. static HeltecV3Board board;
  63. #elif defined(ARDUINO_XIAO_ESP32C3)
  64. #include <helpers/XiaoC3Board.h>
  65. #include <helpers/CustomSX1262Wrapper.h>
  66. #include <helpers/CustomSX1268Wrapper.h>
  67. static XiaoC3Board board;
  68. #elif defined(SEEED_XIAO_S3)
  69. #include <helpers/ESP32Board.h>
  70. #include <helpers/CustomSX1262Wrapper.h>
  71. static ESP32Board board;
  72. #elif defined(RAK_4631)
  73. #include <helpers/nrf52/RAK4631Board.h>
  74. #include <helpers/CustomSX1262Wrapper.h>
  75. static RAK4631Board board;
  76. #else
  77. #error "need to provide a 'board' object"
  78. #endif
  79. /* ------------------------------ Code -------------------------------- */
  80. struct ClientInfo {
  81. mesh::Identity id;
  82. uint32_t last_timestamp; // by THEIR clock
  83. uint32_t last_activity; // by OUR clock
  84. uint32_t sync_since; // sync messages SINCE this timestamp (by OUR clock)
  85. uint32_t pending_ack;
  86. uint32_t push_post_timestamp;
  87. unsigned long ack_timeout;
  88. bool is_admin;
  89. uint8_t push_failures;
  90. uint8_t secret[PUB_KEY_SIZE];
  91. int out_path_len;
  92. uint8_t out_path[MAX_PATH_SIZE];
  93. };
  94. #define MAX_POST_TEXT_LEN (160-9)
  95. struct PostInfo {
  96. mesh::Identity author;
  97. uint32_t post_timestamp; // by OUR clock
  98. char text[MAX_POST_TEXT_LEN+1];
  99. };
  100. #define REPLY_DELAY_MILLIS 1500
  101. #define PUSH_NOTIFY_DELAY_MILLIS 2000
  102. #define SYNC_PUSH_INTERVAL 2000
  103. #define PUSH_ACK_TIMEOUT_FLOOD 12000
  104. #define PUSH_TIMEOUT_BASE 4000
  105. #define PUSH_ACK_TIMEOUT_FACTOR 2000
  106. #define CLIENT_KEEP_ALIVE_SECS 128
  107. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  108. #define REQ_TYPE_KEEP_ALIVE 0x02
  109. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  110. class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
  111. RadioLibWrapper* my_radio;
  112. FILESYSTEM* _fs;
  113. RADIO_CLASS* _phy;
  114. mesh::MainBoard* _board;
  115. unsigned long next_local_advert;
  116. NodePrefs _prefs;
  117. CommonCLI _cli;
  118. uint8_t reply_data[MAX_PACKET_PAYLOAD];
  119. int num_clients;
  120. ClientInfo known_clients[MAX_CLIENTS];
  121. unsigned long next_push;
  122. int next_client_idx; // for round-robin polling
  123. int next_post_idx;
  124. PostInfo posts[MAX_UNSYNCED_POSTS]; // cyclic queue
  125. ClientInfo* putClient(const mesh::Identity& id) {
  126. for (int i = 0; i < num_clients; i++) {
  127. if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
  128. }
  129. ClientInfo* newClient;
  130. if (num_clients < MAX_CLIENTS) {
  131. newClient = &known_clients[num_clients++];
  132. } else { // table is currently full
  133. // evict least active client
  134. uint32_t oldest_timestamp = 0xFFFFFFFF;
  135. newClient = &known_clients[0];
  136. for (int i = 0; i < num_clients; i++) {
  137. auto c = &known_clients[i];
  138. if (c->last_activity < oldest_timestamp) {
  139. oldest_timestamp = c->last_activity;
  140. newClient = c;
  141. }
  142. }
  143. }
  144. newClient->id = id;
  145. newClient->out_path_len = -1; // initially out_path is unknown
  146. newClient->last_timestamp = 0;
  147. self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
  148. return newClient;
  149. }
  150. void evict(ClientInfo* client) {
  151. client->last_activity = 0; // this slot will now be re-used (will be oldest)
  152. memset(client->id.pub_key, 0, sizeof(client->id.pub_key));
  153. memset(client->secret, 0, sizeof(client->secret));
  154. client->pending_ack = 0;
  155. }
  156. void addPost(ClientInfo* client, const char* postData) {
  157. // TODO: suggested postData format: <title>/<descrption>
  158. posts[next_post_idx].author = client->id; // add to cyclic queue
  159. StrHelper::strncpy(posts[next_post_idx].text, postData, MAX_POST_TEXT_LEN);
  160. posts[next_post_idx].post_timestamp = getRTCClock()->getCurrentTimeUnique();
  161. next_post_idx = (next_post_idx + 1) % MAX_UNSYNCED_POSTS;
  162. next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS);
  163. }
  164. void pushPostToClient(ClientInfo* client, PostInfo& post) {
  165. int len = 0;
  166. memcpy(&reply_data[len], &post.post_timestamp, 4); len += 4; // this is a PAST timestamp... but should be accepted by client
  167. reply_data[len++] = (TXT_TYPE_SIGNED_PLAIN << 2); // 'signed' plain text
  168. // encode prefix of post.author.pub_key
  169. memcpy(&reply_data[len], post.author.pub_key, 4); len += 4; // just first 4 bytes
  170. int text_len = strlen(post.text);
  171. memcpy(&reply_data[len], post.text, text_len); len += text_len;
  172. // calc expected ACK reply
  173. mesh::Utils::sha256((uint8_t *)&client->pending_ack, 4, reply_data, len, self_id.pub_key, PUB_KEY_SIZE);
  174. client->push_post_timestamp = post.post_timestamp;
  175. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, client->secret, reply_data, len);
  176. if (reply) {
  177. if (client->out_path_len < 0) {
  178. sendFlood(reply);
  179. client->ack_timeout = futureMillis(PUSH_ACK_TIMEOUT_FLOOD);
  180. } else {
  181. sendDirect(reply, client->out_path, client->out_path_len);
  182. client->ack_timeout = futureMillis(PUSH_TIMEOUT_BASE + PUSH_ACK_TIMEOUT_FACTOR * (client->out_path_len + 1));
  183. }
  184. } else {
  185. client->pending_ack = 0;
  186. MESH_DEBUG_PRINTLN("Unable to push post to client");
  187. }
  188. }
  189. bool processAck(const uint8_t *data) {
  190. for (int i = 0; i < num_clients; i++) {
  191. auto client = &known_clients[i];
  192. if (client->pending_ack && memcmp(data, &client->pending_ack, 4) == 0) { // got an ACK from Client!
  193. client->pending_ack = 0; // clear this, so next push can happen
  194. client->push_failures = 0;
  195. client->sync_since = client->push_post_timestamp; // advance Client's SINCE timestamp, to sync next post
  196. return true;
  197. }
  198. }
  199. return false;
  200. }
  201. mesh::Packet* createSelfAdvert() {
  202. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  203. uint8_t app_data_len;
  204. {
  205. AdvertDataBuilder builder(ADV_TYPE_ROOM, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  206. app_data_len = builder.encodeTo(app_data);
  207. }
  208. return createAdvert(self_id, app_data, app_data_len);
  209. }
  210. protected:
  211. float getAirtimeBudgetFactor() const override {
  212. return _prefs.airtime_factor;
  213. }
  214. int calcRxDelay(float score, uint32_t air_time) const override {
  215. if (_prefs.rx_delay_base <= 0.0f) return 0;
  216. return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  217. }
  218. const char* getLogDateTime() override {
  219. static char tmp[32];
  220. uint32_t now = getRTCClock()->getCurrentTime();
  221. DateTime dt = DateTime(now);
  222. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(), dt.year());
  223. return tmp;
  224. }
  225. uint32_t getRetransmitDelay(const mesh::Packet* packet) override {
  226. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  227. return getRNG()->nextInt(0, 6)*t;
  228. }
  229. uint32_t getDirectRetransmitDelay(const mesh::Packet* packet) override {
  230. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  231. return getRNG()->nextInt(0, 6)*t;
  232. }
  233. bool allowPacketForward(const mesh::Packet* packet) override {
  234. return !_prefs.disable_fwd;
  235. }
  236. void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
  237. if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
  238. uint32_t sender_timestamp, sender_sync_since;
  239. memcpy(&sender_timestamp, data, 4);
  240. memcpy(&sender_sync_since, &data[4], 4); // sender's "sync messags SINCE x" timestamp
  241. bool is_admin;
  242. data[len] = 0; // ensure null terminator
  243. if (strcmp((char *) &data[8], _prefs.password) == 0) { // check for valid admin password
  244. is_admin = true;
  245. } else {
  246. is_admin = false;
  247. if (strcmp((char *) &data[8], _prefs.guest_password) != 0) { // check the room/public password
  248. MESH_DEBUG_PRINTLN("Incorrect room password");
  249. return; // no response. Client will timeout
  250. }
  251. }
  252. auto client = putClient(sender); // add to known clients (if not already known)
  253. if (sender_timestamp <= client->last_timestamp) {
  254. MESH_DEBUG_PRINTLN("possible replay attack!");
  255. return;
  256. }
  257. MESH_DEBUG_PRINTLN("Login success!");
  258. client->is_admin = is_admin;
  259. client->last_timestamp = sender_timestamp;
  260. client->sync_since = sender_sync_since;
  261. client->pending_ack = 0;
  262. client->push_failures = 0;
  263. uint32_t now = getRTCClock()->getCurrentTime();
  264. client->last_activity = now;
  265. now = getRTCClock()->getCurrentTimeUnique();
  266. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  267. // TODO: maybe reply with count of messages waiting to be synced for THIS client?
  268. reply_data[4] = RESP_SERVER_LOGIN_OK;
  269. reply_data[5] = (CLIENT_KEEP_ALIVE_SECS >> 4); // NEW: recommended keep-alive interval (secs / 16)
  270. reply_data[6] = is_admin ? 1 : 0;
  271. reply_data[7] = 0; // FUTURE: reserved
  272. memcpy(&reply_data[8], "OK", 2); // REVISIT: not really needed
  273. next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS); // delay next push, give RESPONSE packet time to arrive first
  274. if (packet->isRouteFlood()) {
  275. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  276. mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
  277. PAYLOAD_TYPE_RESPONSE, reply_data, 8 + 2);
  278. if (path) sendFlood(path);
  279. } else {
  280. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 8 + 2);
  281. if (reply) {
  282. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  283. sendDirect(reply, client->out_path, client->out_path_len);
  284. } else {
  285. sendFlood(reply);
  286. }
  287. }
  288. }
  289. }
  290. }
  291. int matching_peer_indexes[MAX_CLIENTS];
  292. int searchPeersByHash(const uint8_t* hash) override {
  293. int n = 0;
  294. for (int i = 0; i < num_clients; i++) {
  295. if (known_clients[i].id.isHashMatch(hash)) {
  296. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  297. }
  298. }
  299. return n;
  300. }
  301. void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
  302. int i = matching_peer_indexes[peer_idx];
  303. if (i >= 0 && i < num_clients) {
  304. // lookup pre-calculated shared_secret
  305. memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
  306. } else {
  307. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  308. }
  309. }
  310. void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override {
  311. int i = matching_peer_indexes[sender_idx];
  312. if (i < 0 || i >= num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  313. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  314. return;
  315. }
  316. auto client = &known_clients[i];
  317. if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) { // a CLI command or new Post
  318. uint32_t sender_timestamp;
  319. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  320. uint flags = (data[4] >> 2); // message attempt number, and other flags
  321. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  322. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported command flags received: flags=%02x", (uint32_t)flags);
  323. } else if (sender_timestamp > client->last_timestamp) { // prevent replay attacks
  324. client->last_timestamp = sender_timestamp;
  325. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  326. client->last_activity = now;
  327. client->push_failures = 0; // reset so push can resume (if prev failed)
  328. // len can be > original length, but 'text' will be padded with zeroes
  329. data[len] = 0; // need to make a C string again, with null terminator
  330. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
  331. mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key, PUB_KEY_SIZE);
  332. uint8_t temp[166];
  333. bool send_ack;
  334. if (flags == TXT_TYPE_CLI_DATA) {
  335. if (client->is_admin) {
  336. _cli.handleCommand(sender_timestamp, (const char *) &data[5], (char *) &temp[5]);
  337. temp[4] = (TXT_TYPE_CLI_DATA << 2); // attempt and flags, (NOTE: legacy was: TXT_TYPE_PLAIN)
  338. send_ack = true;
  339. } else {
  340. temp[5] = 0; // no reply
  341. send_ack = false; // and no ACK... user shoudn't be sending these
  342. }
  343. } else { // TXT_TYPE_PLAIN
  344. addPost(client, (const char *) &data[5]);
  345. temp[5] = 0; // no reply (ACK is enough)
  346. send_ack = true;
  347. }
  348. if (send_ack) {
  349. mesh::Packet* ack = createAck(ack_hash);
  350. if (ack) {
  351. if (client->out_path_len < 0) {
  352. sendFlood(ack);
  353. } else {
  354. sendDirect(ack, client->out_path, client->out_path_len);
  355. }
  356. }
  357. }
  358. int text_len = strlen((char *) &temp[5]);
  359. if (text_len > 0) {
  360. if (now == sender_timestamp) {
  361. // WORKAROUND: the two timestamps need to be different, in the CLI view
  362. now++;
  363. }
  364. memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
  365. // calc expected ACK reply
  366. //mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, temp, 5 + text_len, self_id.pub_key, PUB_KEY_SIZE);
  367. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  368. if (reply) {
  369. if (client->out_path_len < 0) {
  370. sendFlood(reply, REPLY_DELAY_MILLIS);
  371. } else {
  372. sendDirect(reply, client->out_path, client->out_path_len, REPLY_DELAY_MILLIS);
  373. }
  374. }
  375. }
  376. } else {
  377. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  378. }
  379. } else if (type == PAYLOAD_TYPE_REQ && len >= 5) {
  380. uint32_t sender_timestamp;
  381. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  382. if (data[4] == REQ_TYPE_KEEP_ALIVE && packet->isRouteDirect()) { // request type
  383. uint32_t forceSince = 0;
  384. if (len >= 9) { // optional - last post_timestamp client received
  385. memcpy(&forceSince, &data[5], 4); // NOTE: this may be 0, if part of decrypted PADDING!
  386. } else {
  387. memcpy(&data[5], &forceSince, 4); // make sure there are zeroes in payload (for ack_hash calc below)
  388. }
  389. if (forceSince > 0) {
  390. client->sync_since = forceSince; // force-update the 'sync since'
  391. }
  392. uint32_t now = getRTCClock()->getCurrentTime();
  393. client->last_activity = now; // <-- THIS will keep client connection alive
  394. client->push_failures = 0; // reset so push can resume (if prev failed)
  395. client->pending_ack = 0;
  396. // TODO: Throttle KEEP_ALIVE requests!
  397. // if client sends too quickly, evict()
  398. // RULE: only send keep_alive response DIRECT!
  399. if (client->out_path_len >= 0) {
  400. uint32_t ack_hash; // calc ACK to prove to sender that we got request
  401. mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 9, client->id.pub_key, PUB_KEY_SIZE);
  402. auto reply = createAck(ack_hash);
  403. if (reply) {
  404. sendDirect(reply, client->out_path, client->out_path_len);
  405. }
  406. }
  407. }
  408. }
  409. }
  410. 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 {
  411. // TODO: prevent replay attacks
  412. int i = matching_peer_indexes[sender_idx];
  413. if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  414. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t) path_len);
  415. auto client = &known_clients[i];
  416. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  417. } else {
  418. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  419. }
  420. if (extra_type == PAYLOAD_TYPE_ACK && extra_len >= 4) {
  421. // also got an encoded ACK!
  422. processAck(extra);
  423. }
  424. // NOTE: no reciprocal path send!!
  425. return false;
  426. }
  427. void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override {
  428. if (processAck((uint8_t *)&ack_crc)) {
  429. packet->markDoNotRetransmit(); // ACK was for this node, so don't retransmit
  430. }
  431. }
  432. public:
  433. MyMesh(RADIO_CLASS& phy, mesh::MainBoard& board, RadioLibWrapper& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  434. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  435. _phy(&phy), _board(&board), _cli(board, this, &_prefs, this)
  436. {
  437. my_radio = &radio;
  438. next_local_advert = 0;
  439. // defaults
  440. memset(&_prefs, 0, sizeof(_prefs));
  441. _prefs.airtime_factor = 1.0; // one half
  442. _prefs.rx_delay_base = 0.0f; // off by default, was 10.0
  443. _prefs.tx_delay_factor = 0.5f; // was 0.25f;
  444. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  445. _prefs.node_lat = ADVERT_LAT;
  446. _prefs.node_lon = ADVERT_LON;
  447. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  448. _prefs.freq = LORA_FREQ;
  449. _prefs.sf = LORA_SF;
  450. _prefs.bw = LORA_BW;
  451. _prefs.cr = LORA_CR;
  452. _prefs.tx_power_dbm = LORA_TX_POWER;
  453. _prefs.disable_fwd = 1;
  454. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  455. #ifdef ROOM_PASSWORD
  456. StrHelper::strncpy(_prefs.guest_password, ROOM_PASSWORD, sizeof(_prefs.guest_password));
  457. #endif
  458. num_clients = 0;
  459. next_post_idx = 0;
  460. next_client_idx = 0;
  461. next_push = 0;
  462. memset(posts, 0, sizeof(posts));
  463. }
  464. CommonCLI* getCLI() { return &_cli; }
  465. void begin(FILESYSTEM* fs) {
  466. mesh::Mesh::begin();
  467. _fs = fs;
  468. // load persisted prefs
  469. if (_fs->exists("/node_prefs")) {
  470. File file = _fs->open("/node_prefs");
  471. if (file) {
  472. file.read((uint8_t *) &_prefs, sizeof(_prefs));
  473. file.close();
  474. }
  475. }
  476. _phy->setFrequency(_prefs.freq);
  477. _phy->setSpreadingFactor(_prefs.sf);
  478. _phy->setBandwidth(_prefs.bw);
  479. _phy->setCodingRate(_prefs.cr);
  480. _phy->setOutputPower(_prefs.tx_power_dbm);
  481. updateAdvertTimer();
  482. }
  483. const char* getFirmwareVer() override { return FIRMWARE_VERSION; }
  484. const char* getBuildDate() override { return FIRMWARE_BUILD_DATE; }
  485. void savePrefs() override {
  486. #if defined(NRF52_PLATFORM)
  487. File file = _fs->open("/node_prefs", FILE_O_WRITE);
  488. if (file) { file.seek(0); file.truncate(); }
  489. #else
  490. File file = _fs->open("/node_prefs", "w", true);
  491. #endif
  492. if (file) {
  493. file.write((const uint8_t *)&_prefs, sizeof(_prefs));
  494. file.close();
  495. }
  496. }
  497. bool formatFileSystem() override {
  498. #if defined(NRF52_PLATFORM)
  499. return InternalFS.format();
  500. #elif defined(ESP32)
  501. return SPIFFS.format();
  502. #else
  503. #error "need to implement file system erase"
  504. return false;
  505. #endif
  506. }
  507. void sendSelfAdvertisement(int delay_millis) override {
  508. mesh::Packet* pkt = createSelfAdvert();
  509. if (pkt) {
  510. sendFlood(pkt, delay_millis);
  511. } else {
  512. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  513. }
  514. }
  515. void updateAdvertTimer() override {
  516. if (_prefs.advert_interval > 0) { // schedule local advert timer
  517. next_local_advert = futureMillis((uint32_t)_prefs.advert_interval * 2 * 60 * 1000);
  518. } else {
  519. next_local_advert = 0; // stop the timer
  520. }
  521. }
  522. void setLoggingOn(bool enable) override { /* no-op */ }
  523. void eraseLogFile() override { /* no-op */ }
  524. void dumpLogFile() override { /* no-op */ }
  525. void setTxPower(uint8_t power_dbm) override {
  526. _phy->setOutputPower(power_dbm);
  527. }
  528. void loop() {
  529. mesh::Mesh::loop();
  530. if (millisHasNowPassed(next_push) && num_clients > 0) {
  531. // check for ACK timeouts
  532. for (int i = 0; i < num_clients; i++) {
  533. auto c = &known_clients[i];
  534. if (c->pending_ack && millisHasNowPassed(c->ack_timeout)) {
  535. c->push_failures++;
  536. c->pending_ack = 0; // reset (TODO: keep prev expected_ack's in a list, incase they arrive LATER, after we retry)
  537. MESH_DEBUG_PRINTLN("pending ACK timed out: push_failures: %d", (uint32_t)c->push_failures);
  538. }
  539. }
  540. // check next Round-Robin client, and sync next new post
  541. auto client = &known_clients[next_client_idx];
  542. if (client->pending_ack == 0 && client->last_activity != 0 && client->push_failures < 3) { // not already waiting for ACK, AND not evicted, AND retries not max
  543. MESH_DEBUG_PRINTLN("loop - checking for client %02X", (uint32_t) client->id.pub_key[0]);
  544. for (int k = 0, idx = next_post_idx; k < MAX_UNSYNCED_POSTS; k++) {
  545. if (posts[idx].post_timestamp > client->sync_since // is new post for this Client?
  546. && !posts[idx].author.matches(client->id)) { // don't push posts to the author
  547. // push this post to Client, then wait for ACK
  548. pushPostToClient(client, posts[idx]);
  549. MESH_DEBUG_PRINTLN("loop - pushed to client %02X: %s", (uint32_t) client->id.pub_key[0], posts[idx].text);
  550. break;
  551. }
  552. idx = (idx + 1) % MAX_UNSYNCED_POSTS; // wrap to start of cyclic queue
  553. }
  554. } else {
  555. MESH_DEBUG_PRINTLN("loop - skipping busy (or evicted) client %02X", (uint32_t) client->id.pub_key[0]);
  556. }
  557. next_client_idx = (next_client_idx + 1) % num_clients; // round robin polling for each client
  558. next_push = futureMillis(SYNC_PUSH_INTERVAL);
  559. }
  560. if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  561. mesh::Packet* pkt = createSelfAdvert();
  562. if (pkt) {
  563. sendZeroHop(pkt);
  564. }
  565. updateAdvertTimer(); // schedule next local advert
  566. }
  567. // TODO: periodically check for OLD/inactive entries in known_clients[], and evict
  568. }
  569. };
  570. #if defined(NRF52_PLATFORM)
  571. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI);
  572. #elif defined(P_LORA_SCLK)
  573. SPIClass spi;
  574. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  575. #else
  576. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  577. #endif
  578. StdRNG fast_rng;
  579. SimpleMeshTables tables;
  580. #ifdef ESP32
  581. ESP32RTCClock fallback_clock;
  582. #else
  583. VolatileRTCClock fallback_clock;
  584. #endif
  585. AutoDiscoverRTCClock rtc_clock(fallback_clock);
  586. MyMesh the_mesh(radio, board, *new WRAPPER_CLASS(radio, board), *new ArduinoMillis(), fast_rng, rtc_clock, tables);
  587. void halt() {
  588. while (1) ;
  589. }
  590. static char command[MAX_POST_TEXT_LEN+1];
  591. void setup() {
  592. Serial.begin(115200);
  593. delay(1000);
  594. board.begin();
  595. #ifdef ESP32
  596. fallback_clock.begin();
  597. #endif
  598. rtc_clock.begin(Wire);
  599. #ifdef SX126X_DIO3_TCXO_VOLTAGE
  600. float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
  601. #else
  602. float tcxo = 1.6f;
  603. #endif
  604. #if defined(NRF52_PLATFORM)
  605. SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);
  606. SPI.begin();
  607. #elif defined(P_LORA_SCLK)
  608. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  609. #endif
  610. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, 8, tcxo);
  611. if (status != RADIOLIB_ERR_NONE) {
  612. delay(5000);
  613. Serial.print("ERROR: radio init failed: ");
  614. Serial.println(status);
  615. halt();
  616. }
  617. radio.setCRC(0);
  618. #ifdef SX126X_CURRENT_LIMIT
  619. radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
  620. #endif
  621. #ifdef SX126X_DIO2_AS_RF_SWITCH
  622. radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
  623. #endif
  624. fast_rng.begin(radio.random(0x7FFFFFFF));
  625. FILESYSTEM* fs;
  626. #if defined(NRF52_PLATFORM)
  627. InternalFS.begin();
  628. fs = &InternalFS;
  629. IdentityStore store(InternalFS, "");
  630. #elif defined(ESP32)
  631. SPIFFS.begin(true);
  632. fs = &SPIFFS;
  633. IdentityStore store(SPIFFS, "/identity");
  634. #else
  635. #error "need to define filesystem"
  636. #endif
  637. if (!store.load("_main", the_mesh.self_id)) {
  638. RadioNoiseListener rng(radio);
  639. the_mesh.self_id = mesh::LocalIdentity(&rng); // create new random identity
  640. store.save("_main", the_mesh.self_id);
  641. }
  642. Serial.print("Room ID: ");
  643. mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println();
  644. command[0] = 0;
  645. the_mesh.begin(fs);
  646. // send out initial Advertisement to the mesh
  647. the_mesh.sendSelfAdvertisement(2000);
  648. }
  649. void loop() {
  650. int len = strlen(command);
  651. while (Serial.available() && len < sizeof(command)-1) {
  652. char c = Serial.read();
  653. if (c != '\n') {
  654. command[len++] = c;
  655. command[len] = 0;
  656. }
  657. Serial.print(c);
  658. }
  659. if (len == sizeof(command)-1) { // command buffer full
  660. command[sizeof(command)-1] = '\r';
  661. }
  662. if (len > 0 && command[len - 1] == '\r') { // received complete line
  663. command[len - 1] = 0; // replace newline with C string null terminator
  664. char reply[160];
  665. the_mesh.getCLI()->handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial!
  666. if (reply[0]) {
  667. Serial.print(" -> "); Serial.println(reply);
  668. }
  669. command[0] = 0; // reset command buffer
  670. }
  671. the_mesh.loop();
  672. }