main.cpp 18 KB

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