main.cpp 34 KB

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