main.cpp 29 KB

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