main.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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/RadioLibWrappers.h>
  11. #include <helpers/ArduinoHelpers.h>
  12. #include <helpers/StaticPoolPacketManager.h>
  13. #include <helpers/SimpleMeshTables.h>
  14. #include <helpers/IdentityStore.h>
  15. #include <RTClib.h>
  16. /* ---------------------------------- CONFIGURATION ------------------------------------- */
  17. #define FIRMWARE_VER_TEXT "v2 (build: 4 Feb 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 MAX_CONTACTS
  34. #define MAX_CONTACTS 100
  35. #endif
  36. #include <helpers/BaseChatMesh.h>
  37. #define SEND_TIMEOUT_BASE_MILLIS 500
  38. #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f
  39. #define DIRECT_SEND_PERHOP_FACTOR 6.0f
  40. #define DIRECT_SEND_PERHOP_EXTRA_MILLIS 250
  41. #define PUBLIC_GROUP_PSK "izOH6cXN6mrJ5e26oRXNcg=="
  42. #if defined(HELTEC_LORA_V3)
  43. #include <helpers/HeltecV3Board.h>
  44. #include <helpers/CustomSX1262Wrapper.h>
  45. static HeltecV3Board board;
  46. #elif defined(HELTEC_LORA_V2)
  47. #include <helpers/HeltecV2Board.h>
  48. #include <helpers/CustomSX1276Wrapper.h>
  49. static HeltecV2Board board;
  50. #elif defined(ARDUINO_XIAO_ESP32C3)
  51. #include <helpers/XiaoC3Board.h>
  52. #include <helpers/CustomSX1262Wrapper.h>
  53. #include <helpers/CustomSX1268Wrapper.h>
  54. static XiaoC3Board board;
  55. #elif defined(SEEED_XIAO_S3) || defined(LILYGO_T3S3)
  56. #include <helpers/ESP32Board.h>
  57. #include <helpers/CustomSX1262Wrapper.h>
  58. static ESP32Board board;
  59. #elif defined(RAK_4631)
  60. #include <helpers/nrf52/RAK4631Board.h>
  61. #include <helpers/CustomSX1262Wrapper.h>
  62. static RAK4631Board board;
  63. #elif defined(T1000_E)
  64. #include <helpers/nrf52/T1000eBoard.h>
  65. #include <helpers/CustomLR1110Wrapper.h>
  66. static T1000eBoard board;
  67. #else
  68. #error "need to provide a 'board' object"
  69. #endif
  70. // Believe it or not, this std C function is busted on some platforms!
  71. static uint32_t _atoi(const char* sp) {
  72. uint32_t n = 0;
  73. while (*sp && *sp >= '0' && *sp <= '9') {
  74. n *= 10;
  75. n += (*sp++ - '0');
  76. }
  77. return n;
  78. }
  79. /* -------------------------------------------------------------------------------------- */
  80. struct NodePrefs { // persisted to file
  81. float airtime_factor;
  82. char node_name[32];
  83. double node_lat, node_lon;
  84. float freq;
  85. uint8_t tx_power_dbm;
  86. uint8_t unused[3];
  87. };
  88. class MyMesh : public BaseChatMesh, ContactVisitor {
  89. FILESYSTEM* _fs;
  90. NodePrefs _prefs;
  91. uint32_t expected_ack_crc;
  92. mesh::GroupChannel* _public;
  93. unsigned long last_msg_sent;
  94. ContactInfo* curr_recipient;
  95. char command[512+10];
  96. uint8_t tmp_buf[256];
  97. char hex_buf[512];
  98. const char* getTypeName(uint8_t type) const {
  99. if (type == ADV_TYPE_CHAT) return "Chat";
  100. if (type == ADV_TYPE_REPEATER) return "Repeater";
  101. if (type == ADV_TYPE_ROOM) return "Room";
  102. return "??"; // unknown
  103. }
  104. void loadContacts() {
  105. if (_fs->exists("/contacts")) {
  106. File file = _fs->open("/contacts");
  107. if (file) {
  108. bool full = false;
  109. while (!full) {
  110. ContactInfo c;
  111. uint8_t pub_key[32];
  112. uint8_t unused;
  113. uint32_t reserved;
  114. bool success = (file.read(pub_key, 32) == 32);
  115. success = success && (file.read((uint8_t *) &c.name, 32) == 32);
  116. success = success && (file.read(&c.type, 1) == 1);
  117. success = success && (file.read(&c.flags, 1) == 1);
  118. success = success && (file.read(&unused, 1) == 1);
  119. success = success && (file.read((uint8_t *) &reserved, 4) == 4);
  120. success = success && (file.read((uint8_t *) &c.out_path_len, 1) == 1);
  121. success = success && (file.read((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  122. success = success && (file.read(c.out_path, 64) == 64);
  123. c.gps_lat = c.gps_lon = 0; // not yet supported
  124. if (!success) break; // EOF
  125. c.id = mesh::Identity(pub_key);
  126. c.lastmod = 0;
  127. if (!addContact(c)) full = true;
  128. }
  129. file.close();
  130. }
  131. }
  132. }
  133. void saveContacts() {
  134. #if defined(NRF52_PLATFORM)
  135. File file = _fs->open("/contacts", FILE_O_WRITE);
  136. if (file) { file.seek(0); file.truncate(); }
  137. #else
  138. File file = _fs->open("/contacts", "w", true);
  139. #endif
  140. if (file) {
  141. ContactsIterator iter;
  142. ContactInfo c;
  143. uint8_t unused = 0;
  144. uint32_t reserved = 0;
  145. while (iter.hasNext(this, c)) {
  146. bool success = (file.write(c.id.pub_key, 32) == 32);
  147. success = success && (file.write((uint8_t *) &c.name, 32) == 32);
  148. success = success && (file.write(&c.type, 1) == 1);
  149. success = success && (file.write(&c.flags, 1) == 1);
  150. success = success && (file.write(&unused, 1) == 1);
  151. success = success && (file.write((uint8_t *) &reserved, 4) == 4);
  152. success = success && (file.write((uint8_t *) &c.out_path_len, 1) == 1);
  153. success = success && (file.write((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  154. success = success && (file.write(c.out_path, 64) == 64);
  155. if (!success) break; // write failed
  156. }
  157. file.close();
  158. }
  159. }
  160. void setClock(uint32_t timestamp) {
  161. uint32_t curr = getRTCClock()->getCurrentTime();
  162. if (timestamp > curr) {
  163. getRTCClock()->setCurrentTime(timestamp);
  164. Serial.println(" (OK - clock set!)");
  165. } else {
  166. Serial.println(" (ERR: clock cannot go backwards)");
  167. }
  168. }
  169. void importCard(const char* command) {
  170. while (*command == ' ') command++; // skip leading spaces
  171. if (memcmp(command, "meshcore://", 11) == 0) {
  172. command += 11; // skip the prefix
  173. char *ep = strchr(command, 0); // find end of string
  174. while (ep > command) {
  175. ep--;
  176. if (mesh::Utils::isHexChar(*ep)) break; // found tail end of card
  177. *ep = 0; // remove trailing spaces and other junk
  178. }
  179. int len = strlen(command);
  180. if (len % 2 == 0) {
  181. len >>= 1; // halve, for num bytes
  182. if (mesh::Utils::fromHex(tmp_buf, len, command)) {
  183. importContact(tmp_buf, len);
  184. return;
  185. }
  186. }
  187. }
  188. Serial.println(" error: invalid format");
  189. }
  190. protected:
  191. float getAirtimeBudgetFactor() const override {
  192. return _prefs.airtime_factor;
  193. }
  194. int calcRxDelay(float score, uint32_t air_time) const override {
  195. return 0; // disable rxdelay
  196. }
  197. void onDiscoveredContact(ContactInfo& contact, bool is_new) override {
  198. // TODO: if not in favs, prompt to add as fav(?)
  199. Serial.printf("ADVERT from -> %s\n", contact.name);
  200. Serial.printf(" type: %s\n", getTypeName(contact.type));
  201. Serial.print(" public key: "); mesh::Utils::printHex(Serial, contact.id.pub_key, PUB_KEY_SIZE); Serial.println();
  202. saveContacts();
  203. }
  204. void onContactPathUpdated(const ContactInfo& contact) override {
  205. Serial.printf("PATH to: %s, path_len=%d\n", contact.name, (int32_t) contact.out_path_len);
  206. saveContacts();
  207. }
  208. bool processAck(const uint8_t *data) override {
  209. if (memcmp(data, &expected_ack_crc, 4) == 0) { // got an ACK from recipient
  210. Serial.printf(" Got ACK! (round trip: %d millis)\n", _ms->getMillis() - last_msg_sent);
  211. // NOTE: the same ACK can be received multiple times!
  212. expected_ack_crc = 0; // reset our expected hash, now that we have received ACK
  213. return true;
  214. }
  215. //uint32_t crc;
  216. //memcpy(&crc, data, 4);
  217. //MESH_DEBUG_PRINTLN("unknown ACK received: %08X (expected: %08X)", crc, expected_ack_crc);
  218. return false;
  219. }
  220. void onMessageRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const char *text) override {
  221. Serial.printf("(%s) MSG -> from %s\n", path_len == 0xFF ? "DIRECT" : "FLOOD", from.name);
  222. Serial.printf(" %s\n", text);
  223. if (strcmp(text, "clock sync") == 0) { // special text command
  224. setClock(sender_timestamp + 1);
  225. }
  226. }
  227. void onCommandDataRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const char *text) override {
  228. }
  229. void onSignedMessageRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) override {
  230. }
  231. void onChannelMessageRecv(const mesh::GroupChannel& channel, int in_path_len, uint32_t timestamp, const char *text) override {
  232. if (in_path_len < 0) {
  233. Serial.printf("PUBLIC CHANNEL MSG -> (Direct!)\n");
  234. } else {
  235. Serial.printf("PUBLIC CHANNEL MSG -> (Flood) hops %d\n", in_path_len);
  236. }
  237. Serial.printf(" %s\n", text);
  238. }
  239. void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) override {
  240. // not supported
  241. }
  242. uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const override {
  243. return SEND_TIMEOUT_BASE_MILLIS + (FLOOD_SEND_TIMEOUT_FACTOR * pkt_airtime_millis);
  244. }
  245. uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const override {
  246. return SEND_TIMEOUT_BASE_MILLIS +
  247. ( (pkt_airtime_millis*DIRECT_SEND_PERHOP_FACTOR + DIRECT_SEND_PERHOP_EXTRA_MILLIS) * (path_len + 1));
  248. }
  249. void onSendTimeout() override {
  250. Serial.println(" ERROR: timed out, no ACK.");
  251. }
  252. public:
  253. MyMesh(RadioLibWrapper& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
  254. : BaseChatMesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables)
  255. {
  256. // defaults
  257. memset(&_prefs, 0, sizeof(_prefs));
  258. _prefs.airtime_factor = 2.0; // one third
  259. strcpy(_prefs.node_name, "NONAME");
  260. _prefs.freq = LORA_FREQ;
  261. _prefs.tx_power_dbm = LORA_TX_POWER;
  262. command[0] = 0;
  263. curr_recipient = NULL;
  264. }
  265. float getFreqPref() const { return _prefs.freq; }
  266. uint8_t getTxPowerPref() const { return _prefs.tx_power_dbm; }
  267. void begin(FILESYSTEM& fs) {
  268. _fs = &fs;
  269. BaseChatMesh::begin();
  270. #if defined(NRF52_PLATFORM)
  271. IdentityStore store(fs, "");
  272. #else
  273. IdentityStore store(fs, "/identity");
  274. #endif
  275. if (!store.load("_main", self_id, _prefs.node_name, sizeof(_prefs.node_name))) { // legacy: node_name was from identity file
  276. self_id = mesh::LocalIdentity(getRNG()); // create new random identity
  277. store.save("_main", self_id);
  278. }
  279. // load persisted prefs
  280. if (_fs->exists("/node_prefs")) {
  281. File file = _fs->open("/node_prefs");
  282. if (file) {
  283. file.read((uint8_t *) &_prefs, sizeof(_prefs));
  284. file.close();
  285. }
  286. }
  287. loadContacts();
  288. _public = addChannel(PUBLIC_GROUP_PSK); // pre-configure Andy's public channel
  289. }
  290. void savePrefs() {
  291. #if defined(NRF52_PLATFORM)
  292. File file = _fs->open("/node_prefs", FILE_O_WRITE);
  293. if (file) { file.seek(0); file.truncate(); }
  294. #else
  295. File file = _fs->open("/node_prefs", "w", true);
  296. #endif
  297. if (file) {
  298. file.write((const uint8_t *)&_prefs, sizeof(_prefs));
  299. file.close();
  300. }
  301. }
  302. void showWelcome() {
  303. Serial.println("===== MeshCore Chat Terminal =====");
  304. Serial.println();
  305. Serial.printf("WELCOME %s\n", _prefs.node_name);
  306. Serial.println(" (enter 'help' for basic commands)");
  307. Serial.println();
  308. }
  309. void sendSelfAdvert(int delay_millis) {
  310. auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  311. if (pkt) {
  312. sendFlood(pkt, delay_millis);
  313. }
  314. }
  315. // ContactVisitor
  316. void onContactVisit(const ContactInfo& contact) override {
  317. Serial.printf(" %s - ", contact.name);
  318. char tmp[40];
  319. int32_t secs = contact.last_advert_timestamp - getRTCClock()->getCurrentTime();
  320. AdvertTimeHelper::formatRelativeTimeDiff(tmp, secs, false);
  321. Serial.println(tmp);
  322. }
  323. void handleCommand(const char* command) {
  324. while (*command == ' ') command++; // skip leading spaces
  325. if (memcmp(command, "send ", 5) == 0) {
  326. if (curr_recipient) {
  327. const char *text = &command[5];
  328. uint32_t est_timeout;
  329. int result = sendMessage(*curr_recipient, getRTCClock()->getCurrentTime(), 0, text, expected_ack_crc, est_timeout);
  330. if (result == MSG_SEND_FAILED) {
  331. Serial.println(" ERROR: unable to send.");
  332. } else {
  333. last_msg_sent = _ms->getMillis();
  334. Serial.printf(" (message sent - %s)\n", result == MSG_SEND_SENT_FLOOD ? "FLOOD" : "DIRECT");
  335. }
  336. } else {
  337. Serial.println(" ERROR: no recipient selected (use 'to' cmd).");
  338. }
  339. } else if (memcmp(command, "public ", 7) == 0) { // send GroupChannel msg
  340. uint8_t temp[5+MAX_TEXT_LEN+32];
  341. uint32_t timestamp = getRTCClock()->getCurrentTime();
  342. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  343. temp[4] = 0; // attempt and flags
  344. sprintf((char *) &temp[5], "%s: %s", _prefs.node_name, &command[7]); // <sender>: <msg>
  345. temp[5 + MAX_TEXT_LEN] = 0; // truncate if too long
  346. int len = strlen((char *) &temp[5]);
  347. auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, *_public, temp, 5 + len);
  348. if (pkt) {
  349. sendFlood(pkt);
  350. Serial.println(" Sent.");
  351. } else {
  352. Serial.println(" ERROR: unable to send");
  353. }
  354. } else if (memcmp(command, "list", 4) == 0) { // show Contact list, by most recent
  355. int n = 0;
  356. if (command[4] == ' ') { // optional param, last 'N'
  357. n = atoi(&command[5]);
  358. }
  359. scanRecentContacts(n, this);
  360. } else if (strcmp(command, "clock") == 0) { // show current time
  361. uint32_t now = getRTCClock()->getCurrentTime();
  362. DateTime dt = DateTime(now);
  363. Serial.printf( "%02d:%02d - %d/%d/%d UTC\n", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
  364. } else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds)
  365. uint32_t secs = _atoi(&command[5]);
  366. setClock(secs);
  367. } else if (memcmp(command, "to ", 3) == 0) { // set current recipient
  368. curr_recipient = searchContactsByPrefix(&command[3]);
  369. if (curr_recipient) {
  370. Serial.printf(" Recipient %s now selected.\n", curr_recipient->name);
  371. } else {
  372. Serial.println(" Error: Name prefix not found.");
  373. }
  374. } else if (strcmp(command, "to") == 0) { // show current recipient
  375. if (curr_recipient) {
  376. Serial.printf(" Current: %s\n", curr_recipient->name);
  377. } else {
  378. Serial.println(" Err: no recipient selected");
  379. }
  380. } else if (strcmp(command, "advert") == 0) {
  381. auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  382. if (pkt) {
  383. sendZeroHop(pkt);
  384. Serial.println(" (advert sent, zero hop).");
  385. } else {
  386. Serial.println(" ERR: unable to send");
  387. }
  388. } else if (strcmp(command, "reset path") == 0) {
  389. if (curr_recipient) {
  390. resetPathTo(*curr_recipient);
  391. saveContacts();
  392. Serial.println(" Done.");
  393. }
  394. } else if (memcmp(command, "card", 4) == 0) {
  395. Serial.printf("Hello %s\n", _prefs.node_name);
  396. auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  397. if (pkt) {
  398. uint8_t len = pkt->writeTo(tmp_buf);
  399. releasePacket(pkt); // undo the obtainNewPacket()
  400. mesh::Utils::toHex(hex_buf, tmp_buf, len);
  401. Serial.println("Your MeshCore biz card:");
  402. Serial.print("meshcore://"); Serial.println(hex_buf);
  403. Serial.println();
  404. } else {
  405. Serial.println(" Error");
  406. }
  407. } else if (memcmp(command, "import ", 7) == 0) {
  408. importCard(&command[7]);
  409. } else if (memcmp(command, "set ", 4) == 0) {
  410. const char* config = &command[4];
  411. if (memcmp(config, "af ", 3) == 0) {
  412. _prefs.airtime_factor = atof(&config[3]);
  413. savePrefs();
  414. Serial.println(" OK");
  415. } else if (memcmp(config, "name ", 5) == 0) {
  416. StrHelper::strncpy(_prefs.node_name, &config[5], sizeof(_prefs.node_name));
  417. savePrefs();
  418. Serial.println(" OK");
  419. } else if (memcmp(config, "lat ", 4) == 0) {
  420. _prefs.node_lat = atof(&config[4]);
  421. savePrefs();
  422. Serial.println(" OK");
  423. } else if (memcmp(config, "lon ", 4) == 0) {
  424. _prefs.node_lon = atof(&config[4]);
  425. savePrefs();
  426. Serial.println(" OK");
  427. } else if (memcmp(config, "tx ", 3) == 0) {
  428. _prefs.tx_power_dbm = atoi(&config[3]);
  429. savePrefs();
  430. Serial.println(" OK - reboot to apply");
  431. } else if (memcmp(config, "freq ", 5) == 0) {
  432. _prefs.freq = atof(&config[5]);
  433. savePrefs();
  434. Serial.println(" OK - reboot to apply");
  435. } else {
  436. Serial.printf(" ERROR: unknown config: %s\n", config);
  437. }
  438. } else if (memcmp(command, "ver", 3) == 0) {
  439. Serial.println(FIRMWARE_VER_TEXT);
  440. } else if (memcmp(command, "help", 4) == 0) {
  441. Serial.println("Commands:");
  442. Serial.println(" set {name|lat|lon|freq|tx|af} {value}");
  443. Serial.println(" card");
  444. Serial.println(" import {biz card}");
  445. Serial.println(" clock");
  446. Serial.println(" time <epoch-seconds>");
  447. Serial.println(" list {n}");
  448. Serial.println(" to <recipient name or prefix>");
  449. Serial.println(" to");
  450. Serial.println(" send <text>");
  451. Serial.println(" advert");
  452. Serial.println(" reset path");
  453. Serial.println(" public <text>");
  454. } else {
  455. Serial.print(" ERROR: unknown command: "); Serial.println(command);
  456. }
  457. }
  458. void loop() {
  459. BaseChatMesh::loop();
  460. int len = strlen(command);
  461. while (Serial.available() && len < sizeof(command)-1) {
  462. char c = Serial.read();
  463. if (c != '\n') {
  464. command[len++] = c;
  465. command[len] = 0;
  466. }
  467. Serial.print(c);
  468. }
  469. if (len == sizeof(command)-1) { // command buffer full
  470. command[sizeof(command)-1] = '\r';
  471. }
  472. if (len > 0 && command[len - 1] == '\r') { // received complete line
  473. command[len - 1] = 0; // replace newline with C string null terminator
  474. handleCommand(command);
  475. command[0] = 0; // reset command buffer
  476. }
  477. }
  478. };
  479. #if defined(NRF52_PLATFORM)
  480. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI);
  481. #elif defined(P_LORA_SCLK)
  482. SPIClass spi;
  483. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  484. #else
  485. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  486. #endif
  487. StdRNG fast_rng;
  488. SimpleMeshTables tables;
  489. MyMesh the_mesh(*new WRAPPER_CLASS(radio, board), fast_rng, *new VolatileRTCClock(), tables);
  490. void halt() {
  491. while (1) ;
  492. }
  493. void setup() {
  494. Serial.begin(115200);
  495. board.begin();
  496. #ifdef SX126X_DIO3_TCXO_VOLTAGE
  497. float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
  498. #else
  499. float tcxo = 1.6f;
  500. #endif
  501. #if defined(NRF52_PLATFORM)
  502. SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);
  503. SPI.begin();
  504. #elif defined(P_LORA_SCLK)
  505. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  506. #endif
  507. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, 8, tcxo);
  508. if (status != RADIOLIB_ERR_NONE) {
  509. Serial.print("ERROR: radio init failed: ");
  510. Serial.println(status);
  511. halt();
  512. }
  513. radio.setCRC(0);
  514. #ifdef SX126X_CURRENT_LIMIT
  515. radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
  516. #endif
  517. #ifdef SX126X_DIO2_AS_RF_SWITCH
  518. radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
  519. #endif
  520. fast_rng.begin(radio.random(0x7FFFFFFF));
  521. #if defined(NRF52_PLATFORM)
  522. InternalFS.begin();
  523. the_mesh.begin(InternalFS);
  524. #elif defined(ESP32)
  525. SPIFFS.begin(true);
  526. the_mesh.begin(SPIFFS);
  527. #else
  528. #error "need to define filesystem"
  529. #endif
  530. if (LORA_FREQ != the_mesh.getFreqPref()) {
  531. radio.setFrequency(the_mesh.getFreqPref());
  532. }
  533. if (LORA_TX_POWER != the_mesh.getTxPowerPref()) {
  534. radio.setOutputPower(the_mesh.getTxPowerPref());
  535. }
  536. the_mesh.showWelcome();
  537. // send out initial Advertisement to the mesh
  538. the_mesh.sendSelfAdvert(1200); // add slight delay
  539. }
  540. void loop() {
  541. the_mesh.loop();
  542. }