main.cpp 36 KB

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