main.cpp 28 KB

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