main.cpp 28 KB

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