main.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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/AdvertDataHelpers.h>
  15. #include <RTClib.h>
  16. /* ------------------------------ Config -------------------------------- */
  17. #define FIRMWARE_VER_TEXT "v1 (build: 24 Jan 2025)"
  18. #ifndef LORA_FREQ
  19. #define LORA_FREQ 915.0
  20. #endif
  21. #ifndef LORA_BW
  22. #define LORA_BW 250
  23. #endif
  24. #ifndef LORA_SF
  25. #define LORA_SF 10
  26. #endif
  27. #ifndef LORA_CR
  28. #define LORA_CR 5
  29. #endif
  30. #ifndef LORA_TX_POWER
  31. #define LORA_TX_POWER 20
  32. #endif
  33. #ifndef ADVERT_NAME
  34. #define ADVERT_NAME "Test BBS"
  35. #endif
  36. #ifndef ADVERT_LAT
  37. #define ADVERT_LAT 0.0
  38. #endif
  39. #ifndef ADVERT_LON
  40. #define ADVERT_LON 0.0
  41. #endif
  42. #ifndef ADMIN_PASSWORD
  43. #define ADMIN_PASSWORD "password"
  44. #endif
  45. #ifndef MAX_CLIENTS
  46. #define MAX_CLIENTS 32
  47. #endif
  48. #ifndef MAX_UNSYNCED_POSTS
  49. #define MAX_UNSYNCED_POSTS 16
  50. #endif
  51. #if defined(HELTEC_LORA_V3)
  52. #include <helpers/HeltecV3Board.h>
  53. #include <helpers/CustomSX1262Wrapper.h>
  54. static HeltecV3Board board;
  55. #elif defined(ARDUINO_XIAO_ESP32C3)
  56. #include <helpers/XiaoC3Board.h>
  57. #include <helpers/CustomSX1262Wrapper.h>
  58. #include <helpers/CustomSX1268Wrapper.h>
  59. static XiaoC3Board board;
  60. #elif defined(SEEED_XIAO_S3)
  61. #include <helpers/ESP32Board.h>
  62. #include <helpers/CustomSX1262Wrapper.h>
  63. static ESP32Board board;
  64. #elif defined(RAK_4631)
  65. #include <helpers/RAK4631Board.h>
  66. #include <helpers/CustomSX1262Wrapper.h>
  67. static RAK4631Board board;
  68. #else
  69. #error "need to provide a 'board' object"
  70. #endif
  71. /* ------------------------------ Code -------------------------------- */
  72. struct ClientInfo {
  73. mesh::Identity id;
  74. uint32_t last_timestamp; // by THEIR clock
  75. uint32_t last_activity; // by OUR clock
  76. uint32_t sync_since; // sync messages SINCE this timestamp (by OUR clock)
  77. uint32_t pending_ack;
  78. uint32_t push_post_timestamp;
  79. unsigned long ack_timeout;
  80. bool is_admin;
  81. uint8_t push_failures;
  82. uint8_t secret[PUB_KEY_SIZE];
  83. int out_path_len;
  84. uint8_t out_path[MAX_PATH_SIZE];
  85. };
  86. #define MAX_POST_TEXT_LEN (160-9)
  87. struct PostInfo {
  88. mesh::Identity author;
  89. uint32_t post_timestamp; // by OUR clock
  90. char text[MAX_POST_TEXT_LEN+1];
  91. };
  92. #define REPLY_DELAY_MILLIS 1500
  93. #define PUSH_NOTIFY_DELAY_MILLIS 1000
  94. #define SYNC_PUSH_INTERVAL 1000
  95. #define PUSH_ACK_TIMEOUT_FLOOD 12000
  96. #define PUSH_TIMEOUT_BASE 4000
  97. #define PUSH_ACK_TIMEOUT_FACTOR 2000
  98. class MyMesh : public mesh::Mesh {
  99. RadioLibWrapper* my_radio;
  100. float airtime_factor;
  101. uint8_t reply_data[MAX_PACKET_PAYLOAD];
  102. int num_clients;
  103. ClientInfo known_clients[MAX_CLIENTS];
  104. unsigned long next_push;
  105. int next_client_idx; // for round-robin polling
  106. int next_post_idx;
  107. PostInfo posts[MAX_UNSYNCED_POSTS]; // cyclic queue
  108. ClientInfo* putClient(const mesh::Identity& id) {
  109. for (int i = 0; i < num_clients; i++) {
  110. if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
  111. }
  112. ClientInfo* newClient;
  113. if (num_clients < MAX_CLIENTS) {
  114. newClient = &known_clients[num_clients++];
  115. } else { // table is currently full
  116. // evict least active client
  117. uint32_t oldest_timestamp = 0xFFFFFFFF;
  118. newClient = &known_clients[0];
  119. for (int i = 0; i < num_clients; i++) {
  120. auto c = &known_clients[i];
  121. if (c->last_activity < oldest_timestamp) {
  122. oldest_timestamp = c->last_activity;
  123. newClient = c;
  124. }
  125. }
  126. }
  127. newClient->id = id;
  128. newClient->out_path_len = -1; // initially out_path is unknown
  129. newClient->last_timestamp = 0;
  130. self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
  131. return newClient;
  132. }
  133. void evict(ClientInfo* client) {
  134. client->last_activity = 0; // this slot will now be re-used (will be oldest)
  135. memset(client->id.pub_key, 0, sizeof(client->id.pub_key));
  136. memset(client->secret, 0, sizeof(client->secret));
  137. client->pending_ack = 0;
  138. }
  139. void addPost(ClientInfo* client, const char* postData, char reply[]) {
  140. // TODO: suggested postData format: <title>/<descrption>
  141. posts[next_post_idx].author = client->id; // add to cyclic queue
  142. strncpy(posts[next_post_idx].text, postData, MAX_POST_TEXT_LEN);
  143. posts[next_post_idx].text[MAX_POST_TEXT_LEN] = 0;
  144. posts[next_post_idx].post_timestamp = getRTCClock()->getCurrentTime();
  145. // TODO: only post at maximum of ONE PER SECOND, so that post_timestamps are UNIQUE!!
  146. next_post_idx = (next_post_idx + 1) % MAX_UNSYNCED_POSTS;
  147. strcpy(reply, "[Posted]");
  148. next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS);
  149. }
  150. void handleCommand(ClientInfo* client, const char* command, char reply[]) {
  151. if (*command == '+') {
  152. addPost(client, &command[1], reply);
  153. } else {
  154. strcpy(reply, "?"); // unknown command
  155. }
  156. }
  157. void pushPostToClient(ClientInfo* client, PostInfo& post) {
  158. int len = 0;
  159. memcpy(&reply_data[len], &post.post_timestamp, 4); len += 4; // this is a PAST timestamp... but should be accepted by client
  160. reply_data[len++] = 0; // plain text
  161. // encode prefix of post.author.pub_key (in hex)
  162. mesh::Utils::toHex((char *) &reply_data[len], post.author.pub_key, 4); len += 8; // just first 4 bytes (8 hex chars)
  163. reply_data[len++] = ':';
  164. int text_len = strlen(post.text);
  165. memcpy(&reply_data[len], post.text, text_len); len += text_len;
  166. // calc expected ACK reply
  167. mesh::Utils::sha256((uint8_t *)&client->pending_ack, 4, reply_data, len, self_id.pub_key, PUB_KEY_SIZE);
  168. client->push_post_timestamp = post.post_timestamp;
  169. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, client->secret, reply_data, len);
  170. if (reply) {
  171. if (client->out_path_len < 0) {
  172. sendFlood(reply);
  173. client->ack_timeout = futureMillis(PUSH_ACK_TIMEOUT_FLOOD);
  174. } else {
  175. sendDirect(reply, client->out_path, client->out_path_len);
  176. client->ack_timeout = futureMillis(PUSH_TIMEOUT_BASE + PUSH_ACK_TIMEOUT_FACTOR * (client->out_path_len + 1));
  177. }
  178. } else {
  179. client->pending_ack = 0;
  180. MESH_DEBUG_PRINTLN("Unable to push post to client");
  181. }
  182. }
  183. bool processAck(const uint8_t *data) {
  184. for (int i = 0; i < num_clients; i++) {
  185. auto client = &known_clients[i];
  186. if (client->pending_ack && memcmp(data, &client->pending_ack, 4) == 0) { // got an ACK from Client!
  187. client->pending_ack = 0; // clear this, so next push can happen
  188. client->push_failures = 0;
  189. client->sync_since = client->push_post_timestamp; // advance Client's SINCE timestamp, to sync next post
  190. return true;
  191. }
  192. }
  193. return false;
  194. }
  195. protected:
  196. float getAirtimeBudgetFactor() const override {
  197. return airtime_factor;
  198. }
  199. #if ROOM_IS_ALSO_REPEATER
  200. bool allowPacketForward(const mesh::Packet* packet) override {
  201. return true; // Yes, allow packet to be forwarded
  202. }
  203. #endif
  204. void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
  205. if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
  206. uint32_t sender_timestamp, sender_sync_since;
  207. memcpy(&sender_timestamp, data, 4);
  208. memcpy(&sender_sync_since, &data[4], 4); // sender's "sync messags SINCE x" timestamp
  209. bool is_admin;
  210. if (memcmp(&data[8], ADMIN_PASSWORD, strlen(ADMIN_PASSWORD)) == 0) { // check for valid admin password
  211. is_admin = true;
  212. } else {
  213. is_admin = false;
  214. #ifdef ROOM_PASSWORD
  215. if (memcmp(&data[8], ROOM_PASSWORD, strlen(ROOM_PASSWORD)) != 0) { // check the room/public password
  216. MESH_DEBUG_PRINTLN("Incorrect room password");
  217. return; // no response. Client will timeout
  218. }
  219. #endif
  220. }
  221. auto client = putClient(sender); // add to known clients (if not already known)
  222. if (sender_timestamp <= client->last_timestamp) {
  223. MESH_DEBUG_PRINTLN("possible replay attack!");
  224. return;
  225. }
  226. MESH_DEBUG_PRINTLN("Login success!");
  227. client->is_admin = is_admin;
  228. client->last_timestamp = sender_timestamp;
  229. client->sync_since = sender_sync_since;
  230. client->pending_ack = 0;
  231. client->push_failures = 0;
  232. uint32_t now = getRTCClock()->getCurrentTime();
  233. client->last_activity = now;
  234. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  235. // TODO: maybe reply with count of messages waiting to be synced for THIS client?
  236. memset(&reply_data[4], 0, 4); // FUTURE: reserve 4 bytes
  237. memcpy(&reply_data[8], "OK", 2);
  238. if (packet->isRouteFlood()) {
  239. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  240. mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
  241. PAYLOAD_TYPE_RESPONSE, reply_data, 8 + 2);
  242. if (path) sendFlood(path);
  243. } else {
  244. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 8 + 2);
  245. if (reply) {
  246. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  247. sendDirect(reply, client->out_path, client->out_path_len);
  248. } else {
  249. sendFlood(reply);
  250. }
  251. }
  252. }
  253. }
  254. }
  255. int matching_peer_indexes[MAX_CLIENTS];
  256. int searchPeersByHash(const uint8_t* hash) override {
  257. int n = 0;
  258. for (int i = 0; i < num_clients; i++) {
  259. if (known_clients[i].id.isHashMatch(hash)) {
  260. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  261. }
  262. }
  263. return n;
  264. }
  265. void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
  266. int i = matching_peer_indexes[peer_idx];
  267. if (i >= 0 && i < num_clients) {
  268. // lookup pre-calculated shared_secret
  269. memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
  270. } else {
  271. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  272. }
  273. }
  274. void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override {
  275. int i = matching_peer_indexes[sender_idx];
  276. if (i < 0 || i >= num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  277. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  278. return;
  279. }
  280. auto client = &known_clients[i];
  281. if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) { // a CLI command
  282. uint32_t sender_timestamp;
  283. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  284. uint flags = data[4]; // message attempt number, and other flags
  285. if (flags != 0) {
  286. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported command type received: flags=%02x", (uint32_t)flags);
  287. } else if (sender_timestamp > client->last_timestamp) { // prevent replay attacks
  288. client->last_timestamp = sender_timestamp;
  289. uint32_t now = getRTCClock()->getCurrentTime();
  290. client->last_activity = now;
  291. // len can be > original length, but 'text' will be padded with zeroes
  292. data[len] = 0; // need to make a C string again, with null terminator
  293. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
  294. mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key, PUB_KEY_SIZE);
  295. mesh::Packet* ack = createAck(ack_hash);
  296. if (ack) {
  297. if (client->out_path_len < 0) {
  298. sendFlood(ack);
  299. } else {
  300. sendDirect(ack, client->out_path, client->out_path_len);
  301. }
  302. }
  303. uint8_t temp[166];
  304. if (client->is_admin) {
  305. if (!handleAdminCommand(sender_timestamp, (const char *) &data[5], (char *) &temp[5])) {
  306. handleCommand(client, (const char *) &data[5], (char *) &temp[5]);
  307. }
  308. } else {
  309. handleCommand(client, (const char *) &data[5], (char *) &temp[5]);
  310. }
  311. int text_len = strlen((char *) &temp[5]);
  312. if (text_len > 0) {
  313. if (now == sender_timestamp) {
  314. // WORKAROUND: the two timestamps need to be different, in the CLI view
  315. now++;
  316. }
  317. memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
  318. temp[4] = 0; // attempt and flags
  319. // calc expected ACK reply
  320. //mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, temp, 5 + text_len, self_id.pub_key, PUB_KEY_SIZE);
  321. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  322. if (reply) {
  323. if (client->out_path_len < 0) {
  324. sendFlood(reply, REPLY_DELAY_MILLIS);
  325. } else {
  326. sendDirect(reply, client->out_path, client->out_path_len, REPLY_DELAY_MILLIS);
  327. }
  328. }
  329. }
  330. } else {
  331. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  332. }
  333. }
  334. }
  335. 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 {
  336. // TODO: prevent replay attacks
  337. int i = matching_peer_indexes[sender_idx];
  338. if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  339. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t) path_len);
  340. auto client = &known_clients[i];
  341. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  342. } else {
  343. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  344. }
  345. if (extra_type == PAYLOAD_TYPE_ACK && extra_len >= 4) {
  346. // also got an encoded ACK!
  347. processAck(extra);
  348. }
  349. // NOTE: no reciprocal path send!!
  350. return false;
  351. }
  352. void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override {
  353. if (processAck((uint8_t *)&ack_crc)) {
  354. packet->markDoNotRetransmit(); // ACK was for this node, so don't retransmit
  355. }
  356. }
  357. public:
  358. MyMesh(RadioLibWrapper& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  359. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables)
  360. {
  361. my_radio = &radio;
  362. airtime_factor = 1.0; // one half
  363. num_clients = 0;
  364. next_post_idx = 0;
  365. next_client_idx = 0;
  366. next_push = 0;
  367. memset(posts, 0, sizeof(posts));
  368. }
  369. void sendSelfAdvertisement() {
  370. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  371. uint8_t app_data_len;
  372. {
  373. AdvertDataBuilder builder(ADV_TYPE_ROOM, ADVERT_NAME, ADVERT_LAT, ADVERT_LON);
  374. app_data_len = builder.encodeTo(app_data);
  375. }
  376. mesh::Packet* pkt = createAdvert(self_id, app_data, app_data_len);
  377. if (pkt) {
  378. sendFlood(pkt, 1200); // add slight delay
  379. } else {
  380. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  381. }
  382. }
  383. bool handleAdminCommand(uint32_t sender_timestamp, const char* command, char reply[]) {
  384. while (*command == ' ') command++; // skip leading spaces
  385. if (memcmp(command, "reboot", 6) == 0) {
  386. board.reboot(); // doesn't return
  387. } else if (memcmp(command, "advert", 6) == 0) {
  388. sendSelfAdvertisement();
  389. strcpy(reply, "OK - Advert sent");
  390. } else if (memcmp(command, "clock sync", 10) == 0) {
  391. uint32_t curr = getRTCClock()->getCurrentTime();
  392. if (sender_timestamp > curr) {
  393. getRTCClock()->setCurrentTime(sender_timestamp + 1);
  394. strcpy(reply, "OK - clock set");
  395. } else {
  396. strcpy(reply, "ERR: clock cannot go backwards");
  397. }
  398. } else if (memcmp(command, "clock", 5) == 0) {
  399. uint32_t now = getRTCClock()->getCurrentTime();
  400. DateTime dt = DateTime(now);
  401. sprintf(reply, "%02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
  402. } else if (memcmp(command, "set ", 4) == 0) {
  403. if (memcmp(&command[4], "AF", 2) == 0 || memcmp(&command[4], "af=", 2) == 0) {
  404. airtime_factor = atof(&command[7]);
  405. strcpy(reply, "OK");
  406. } else {
  407. sprintf(reply, "unknown config: %s", &command[4]);
  408. }
  409. } else if (memcmp(command, "ver", 3) == 0) {
  410. strcpy(reply, FIRMWARE_VER_TEXT);
  411. } else {
  412. // unknown command
  413. reply[0] = 0;
  414. return false;
  415. }
  416. return true;
  417. }
  418. void loop() {
  419. mesh::Mesh::loop();
  420. if (millisHasNowPassed(next_push) && num_clients > 0) {
  421. // check for ACK timeouts
  422. for (int i = 0; i < num_clients; i++) {
  423. auto c = &known_clients[i];
  424. if (c->pending_ack && millisHasNowPassed(c->ack_timeout)) {
  425. c->push_failures++;
  426. c->pending_ack = 0; // reset (TODO: keep prev expected_ack's in a list, incase they arrive LATER, after we retry)
  427. MESH_DEBUG_PRINTLN("pending ACK timed out: push_failures: %d", (uint32_t)c->push_failures);
  428. if (c->push_failures >= 3) {
  429. evict(c);
  430. }
  431. }
  432. }
  433. // check next Round-Robin client, and sync next new post
  434. auto client = &known_clients[next_client_idx];
  435. if (client->pending_ack == 0 && client->last_activity != 0) { // not already waiting for ACK, AND not evicted
  436. for (int k = 0, idx = next_post_idx; k < MAX_UNSYNCED_POSTS; k++) {
  437. if (posts[idx].post_timestamp > client->sync_since // is new post for this Client?
  438. && !posts[idx].author.matches(client->id)) { // don't push posts to the author
  439. // push this post to Client, then wait for ACK
  440. pushPostToClient(client, posts[idx]);
  441. break;
  442. }
  443. idx = (idx + 1) % MAX_UNSYNCED_POSTS; // wrap to start of cyclic queue
  444. }
  445. }
  446. next_client_idx = (next_client_idx + 1) % num_clients; // round robin polling for each client
  447. next_push = futureMillis(SYNC_PUSH_INTERVAL);
  448. }
  449. // TODO: periodically check for OLD/inactive entries in known_clients[], and evict
  450. }
  451. };
  452. #if defined(NRF52_PLATFORM)
  453. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI);
  454. #elif defined(P_LORA_SCLK)
  455. SPIClass spi;
  456. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  457. #else
  458. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  459. #endif
  460. StdRNG fast_rng;
  461. SimpleMeshTables tables;
  462. #ifdef ESP32
  463. ESP32RTCClock rtc_clock;
  464. #else
  465. VolatileRTCClock rtc_clock;
  466. #endif
  467. MyMesh the_mesh(*new WRAPPER_CLASS(radio, board), *new ArduinoMillis(), fast_rng, rtc_clock, tables);
  468. void halt() {
  469. while (1) ;
  470. }
  471. static char command[MAX_POST_TEXT_LEN+1];
  472. void setup() {
  473. Serial.begin(115200);
  474. delay(1000);
  475. board.begin();
  476. #ifdef ESP32
  477. rtc_clock.begin();
  478. #endif
  479. #ifdef SX126X_DIO3_TCXO_VOLTAGE
  480. float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
  481. #else
  482. float tcxo = 1.6f;
  483. #endif
  484. #if defined(NRF52_PLATFORM)
  485. SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);
  486. SPI.begin();
  487. #elif defined(P_LORA_SCLK)
  488. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  489. #endif
  490. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, 8, tcxo);
  491. if (status != RADIOLIB_ERR_NONE) {
  492. delay(5000);
  493. Serial.print("ERROR: radio init failed: ");
  494. Serial.println(status);
  495. halt();
  496. }
  497. radio.setCRC(0);
  498. #ifdef SX126X_CURRENT_LIMIT
  499. radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
  500. #endif
  501. #ifdef SX126X_DIO2_AS_RF_SWITCH
  502. radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
  503. #endif
  504. #if defined(NRF52_PLATFORM)
  505. InternalFS.begin();
  506. IdentityStore store(InternalFS, "/identity");
  507. #elif defined(ESP32)
  508. SPIFFS.begin(true);
  509. IdentityStore store(SPIFFS, "/identity");
  510. #else
  511. #error "need to define filesystem"
  512. #endif
  513. if (!store.load("_main", the_mesh.self_id)) {
  514. the_mesh.self_id = mesh::LocalIdentity(the_mesh.getRNG()); // create new random identity
  515. store.save("_main", the_mesh.self_id);
  516. }
  517. Serial.print("Room ID: ");
  518. mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println();
  519. command[0] = 0;
  520. the_mesh.begin();
  521. // send out initial Advertisement to the mesh
  522. the_mesh.sendSelfAdvertisement();
  523. }
  524. void loop() {
  525. int len = strlen(command);
  526. while (Serial.available() && len < sizeof(command)-1) {
  527. char c = Serial.read();
  528. if (c != '\n') {
  529. command[len++] = c;
  530. command[len] = 0;
  531. }
  532. Serial.print(c);
  533. }
  534. if (len == sizeof(command)-1) { // command buffer full
  535. command[sizeof(command)-1] = '\r';
  536. }
  537. if (len > 0 && command[len - 1] == '\r') { // received complete line
  538. command[len - 1] = 0; // replace newline with C string null terminator
  539. char reply[160];
  540. the_mesh.handleAdminCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial!
  541. if (reply[0]) {
  542. Serial.print(" -> "); Serial.println(reply);
  543. }
  544. command[0] = 0; // reset command buffer
  545. }
  546. the_mesh.loop();
  547. }