main.cpp 35 KB

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