main.cpp 18 KB

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