main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. #ifndef LORA_FREQ
  18. #define LORA_FREQ 915.0
  19. #endif
  20. #ifndef LORA_BW
  21. #define LORA_BW 250
  22. #endif
  23. #ifndef LORA_SF
  24. #define LORA_SF 10
  25. #endif
  26. #ifndef LORA_CR
  27. #define LORA_CR 5
  28. #endif
  29. #ifndef LORA_TX_POWER
  30. #define LORA_TX_POWER 20
  31. #endif
  32. #ifndef MAX_CONTACTS
  33. #define MAX_CONTACTS 100
  34. #endif
  35. #include <helpers/BaseChatMesh.h>
  36. #define SEND_TIMEOUT_BASE_MILLIS 300
  37. #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f
  38. #define DIRECT_SEND_PERHOP_FACTOR 4.0f
  39. #define DIRECT_SEND_PERHOP_EXTRA_MILLIS 200
  40. #define PUBLIC_GROUP_PSK "izOH6cXN6mrJ5e26oRXNcg=="
  41. #if defined(HELTEC_LORA_V3)
  42. #include <helpers/HeltecV3Board.h>
  43. #include <helpers/CustomSX1262Wrapper.h>
  44. static HeltecV3Board board;
  45. #elif defined(ARDUINO_XIAO_ESP32C3)
  46. #include <helpers/XiaoC3Board.h>
  47. #include <helpers/CustomSX1262Wrapper.h>
  48. #include <helpers/CustomSX1268Wrapper.h>
  49. static XiaoC3Board board;
  50. #elif defined(SEEED_XIAO_S3) || defined(LILYGO_T3S3)
  51. #include <helpers/ESP32Board.h>
  52. #include <helpers/CustomSX1262Wrapper.h>
  53. static ESP32Board board;
  54. #elif defined(RAK_4631)
  55. #include <helpers/RAK4631Board.h>
  56. #include <helpers/CustomSX1262Wrapper.h>
  57. static RAK4631Board board;
  58. #else
  59. #error "need to provide a 'board' object"
  60. #endif
  61. // Believe it or not, this std C function is busted on some platforms!
  62. static uint32_t _atoi(const char* sp) {
  63. uint32_t n = 0;
  64. while (*sp && *sp >= '0' && *sp <= '9') {
  65. n *= 10;
  66. n += (*sp++ - '0');
  67. }
  68. return n;
  69. }
  70. /* -------------------------------------------------------------------------------------- */
  71. class MyMesh : public BaseChatMesh, ContactVisitor {
  72. FILESYSTEM* _fs;
  73. uint32_t expected_ack_crc;
  74. mesh::GroupChannel* _public;
  75. unsigned long last_msg_sent;
  76. ContactInfo* curr_recipient;
  77. char command[MAX_TEXT_LEN+1];
  78. const char* getTypeName(uint8_t type) const {
  79. if (type == ADV_TYPE_CHAT) return "Chat";
  80. if (type == ADV_TYPE_REPEATER) return "Repeater";
  81. if (type == ADV_TYPE_ROOM) return "Room";
  82. return "??"; // unknown
  83. }
  84. void loadContacts() {
  85. if (_fs->exists("/contacts")) {
  86. File file = _fs->open("/contacts");
  87. if (file) {
  88. bool full = false;
  89. while (!full) {
  90. ContactInfo c;
  91. uint8_t pub_key[32];
  92. uint8_t unused;
  93. uint32_t reserved;
  94. bool success = (file.read(pub_key, 32) == 32);
  95. success = success && (file.read((uint8_t *) &c.name, 32) == 32);
  96. success = success && (file.read(&c.type, 1) == 1);
  97. success = success && (file.read(&c.flags, 1) == 1);
  98. success = success && (file.read(&unused, 1) == 1);
  99. success = success && (file.read((uint8_t *) &reserved, 4) == 4);
  100. success = success && (file.read((uint8_t *) &c.out_path_len, 1) == 1);
  101. success = success && (file.read((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  102. success = success && (file.read(c.out_path, 64) == 64);
  103. c.gps_lat = c.gps_lon = 0; // not yet supported
  104. if (!success) break; // EOF
  105. c.id = mesh::Identity(pub_key);
  106. c.lastmod = 0;
  107. if (!addContact(c)) full = true;
  108. }
  109. file.close();
  110. }
  111. }
  112. }
  113. void saveContacts() {
  114. #if defined(NRF52_PLATFORM)
  115. File file = _fs->open("/contacts", FILE_O_WRITE);
  116. if (file) { file.seek(0); file.truncate(); }
  117. #else
  118. File file = _fs->open("/contacts", "w", true);
  119. #endif
  120. if (file) {
  121. ContactsIterator iter;
  122. ContactInfo c;
  123. uint8_t unused = 0;
  124. uint32_t reserved = 0;
  125. while (iter.hasNext(this, c)) {
  126. bool success = (file.write(c.id.pub_key, 32) == 32);
  127. success = success && (file.write((uint8_t *) &c.name, 32) == 32);
  128. success = success && (file.write(&c.type, 1) == 1);
  129. success = success && (file.write(&c.flags, 1) == 1);
  130. success = success && (file.write(&unused, 1) == 1);
  131. success = success && (file.write((uint8_t *) &reserved, 4) == 4);
  132. success = success && (file.write((uint8_t *) &c.out_path_len, 1) == 1);
  133. success = success && (file.write((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  134. success = success && (file.write(c.out_path, 64) == 64);
  135. if (!success) break; // write failed
  136. }
  137. file.close();
  138. }
  139. }
  140. void setClock(uint32_t timestamp) {
  141. uint32_t curr = getRTCClock()->getCurrentTime();
  142. if (timestamp > curr) {
  143. getRTCClock()->setCurrentTime(timestamp);
  144. Serial.println(" (OK - clock set!)");
  145. } else {
  146. Serial.println(" (ERR: clock cannot go backwards)");
  147. }
  148. }
  149. protected:
  150. void onDiscoveredContact(ContactInfo& contact, bool is_new) override {
  151. // TODO: if not in favs, prompt to add as fav(?)
  152. Serial.printf("ADVERT from -> %s\n", contact.name);
  153. Serial.printf(" type: %s\n", getTypeName(contact.type));
  154. Serial.print(" public key: "); mesh::Utils::printHex(Serial, contact.id.pub_key, PUB_KEY_SIZE); Serial.println();
  155. saveContacts();
  156. }
  157. void onContactPathUpdated(const ContactInfo& contact) override {
  158. Serial.printf("PATH to: %s, path_len=%d\n", contact.name, (int32_t) contact.out_path_len);
  159. saveContacts();
  160. }
  161. bool processAck(const uint8_t *data) override {
  162. if (memcmp(data, &expected_ack_crc, 4) == 0) { // got an ACK from recipient
  163. Serial.printf(" Got ACK! (round trip: %d millis)\n", _ms->getMillis() - last_msg_sent);
  164. // NOTE: the same ACK can be received multiple times!
  165. expected_ack_crc = 0; // reset our expected hash, now that we have received ACK
  166. return true;
  167. }
  168. //uint32_t crc;
  169. //memcpy(&crc, data, 4);
  170. //MESH_DEBUG_PRINTLN("unknown ACK received: %08X (expected: %08X)", crc, expected_ack_crc);
  171. return false;
  172. }
  173. void onMessageRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const char *text) override {
  174. Serial.printf("(%s) MSG -> from %s\n", path_len == 0xFF ? "DIRECT" : "FLOOD", from.name);
  175. Serial.printf(" %s\n", text);
  176. if (strcmp(text, "clock sync") == 0) { // special text command
  177. setClock(sender_timestamp + 1);
  178. }
  179. }
  180. void onChannelMessageRecv(const mesh::GroupChannel& channel, int in_path_len, uint32_t timestamp, const char *text) override {
  181. if (in_path_len < 0) {
  182. Serial.printf("PUBLIC CHANNEL MSG -> (Direct!)\n");
  183. } else {
  184. Serial.printf("PUBLIC CHANNEL MSG -> (Flood) hops %d\n", in_path_len);
  185. }
  186. Serial.printf(" %s\n", text);
  187. }
  188. uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const override {
  189. return SEND_TIMEOUT_BASE_MILLIS + (FLOOD_SEND_TIMEOUT_FACTOR * pkt_airtime_millis);
  190. }
  191. uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const override {
  192. return SEND_TIMEOUT_BASE_MILLIS +
  193. ( (pkt_airtime_millis*DIRECT_SEND_PERHOP_FACTOR + DIRECT_SEND_PERHOP_EXTRA_MILLIS) * (path_len + 1));
  194. }
  195. void onSendTimeout() override {
  196. Serial.println(" ERROR: timed out, no ACK.");
  197. }
  198. public:
  199. char self_name[sizeof(ContactInfo::name)];
  200. MyMesh(RadioLibWrapper& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
  201. : BaseChatMesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables)
  202. {
  203. command[0] = 0;
  204. curr_recipient = NULL;
  205. }
  206. void begin(FILESYSTEM& fs) {
  207. _fs = &fs;
  208. BaseChatMesh::begin();
  209. strcpy(self_name, "UNSET");
  210. IdentityStore store(fs, "/identity");
  211. if (!store.load("_main", self_id, self_name, sizeof(self_name))) {
  212. self_id = mesh::LocalIdentity(getRNG()); // create new random identity
  213. store.save("_main", self_id);
  214. }
  215. loadContacts();
  216. _public = addChannel(PUBLIC_GROUP_PSK); // pre-configure Andy's public channel
  217. }
  218. void showWelcome() {
  219. Serial.println("===== MeshCore Chat Terminal =====");
  220. Serial.println();
  221. Serial.printf("WELCOME %s\n", self_name);
  222. Serial.println(" (enter 'help' for basic commands)");
  223. Serial.println();
  224. }
  225. // ContactVisitor
  226. void onContactVisit(const ContactInfo& contact) override {
  227. Serial.printf(" %s - ", contact.name);
  228. char tmp[40];
  229. int32_t secs = contact.last_advert_timestamp - getRTCClock()->getCurrentTime();
  230. AdvertTimeHelper::formatRelativeTimeDiff(tmp, secs, false);
  231. Serial.println(tmp);
  232. }
  233. void handleCommand(const char* command) {
  234. while (*command == ' ') command++; // skip leading spaces
  235. if (memcmp(command, "send ", 5) == 0) {
  236. if (curr_recipient) {
  237. const char *text = &command[5];
  238. uint32_t est_timeout;
  239. int result = sendMessage(*curr_recipient, getRTCClock()->getCurrentTime(), 0, text, expected_ack_crc, est_timeout);
  240. if (result == MSG_SEND_FAILED) {
  241. Serial.println(" ERROR: unable to send.");
  242. } else {
  243. last_msg_sent = _ms->getMillis();
  244. Serial.printf(" (message sent - %s)\n", result == MSG_SEND_SENT_FLOOD ? "FLOOD" : "DIRECT");
  245. }
  246. } else {
  247. Serial.println(" ERROR: no recipient selected (use 'to' cmd).");
  248. }
  249. } else if (memcmp(command, "public ", 7) == 0) { // send GroupChannel msg
  250. uint8_t temp[5+MAX_TEXT_LEN+32];
  251. uint32_t timestamp = getRTCClock()->getCurrentTime();
  252. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  253. temp[4] = 0; // attempt and flags
  254. sprintf((char *) &temp[5], "%s: %s", self_name, &command[7]); // <sender>: <msg>
  255. temp[5 + MAX_TEXT_LEN] = 0; // truncate if too long
  256. int len = strlen((char *) &temp[5]);
  257. auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, *_public, temp, 5 + len);
  258. if (pkt) {
  259. sendFlood(pkt);
  260. Serial.println(" Sent.");
  261. } else {
  262. Serial.println(" ERROR: unable to send");
  263. }
  264. } else if (memcmp(command, "list", 4) == 0) { // show Contact list, by most recent
  265. int n = 0;
  266. if (command[4] == ' ') { // optional param, last 'N'
  267. n = atoi(&command[5]);
  268. }
  269. scanRecentContacts(n, this);
  270. } else if (strcmp(command, "clock") == 0) { // show current time
  271. uint32_t now = getRTCClock()->getCurrentTime();
  272. DateTime dt = DateTime(now);
  273. Serial.printf( "%02d:%02d - %d/%d/%d UTC\n", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
  274. } else if (memcmp(command, "name ", 5) == 0) { // set name
  275. strncpy(self_name, &command[5], sizeof(self_name)-1);
  276. self_name[sizeof(self_name)-1] = 0;
  277. IdentityStore store(*_fs, "/identity"); // update IdentityStore
  278. store.save("_main", self_id, self_name);
  279. } else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds)
  280. uint32_t secs = _atoi(&command[5]);
  281. setClock(secs);
  282. } else if (memcmp(command, "to ", 3) == 0) { // set current recipient
  283. curr_recipient = searchContactsByPrefix(&command[3]);
  284. if (curr_recipient) {
  285. Serial.printf(" Recipient %s now selected.\n", curr_recipient->name);
  286. } else {
  287. Serial.println(" Error: Name prefix not found.");
  288. }
  289. } else if (strcmp(command, "to") == 0) { // show current recipient
  290. if (curr_recipient) {
  291. Serial.printf(" Current: %s\n", curr_recipient->name);
  292. } else {
  293. Serial.println(" Err: no recipient selected");
  294. }
  295. } else if (strcmp(command, "advert") == 0) {
  296. auto pkt = createSelfAdvert(self_name);
  297. if (pkt) {
  298. sendZeroHop(pkt);
  299. Serial.println(" (advert sent, zero hop).");
  300. } else {
  301. Serial.println(" ERR: unable to send");
  302. }
  303. } else if (strcmp(command, "reset path") == 0) {
  304. if (curr_recipient) {
  305. resetPathTo(*curr_recipient);
  306. saveContacts();
  307. Serial.println(" Done.");
  308. }
  309. } else if (memcmp(command, "help", 4) == 0) {
  310. Serial.printf("Hello %s, Commands:\n", self_name);
  311. Serial.println(" name <your name>");
  312. Serial.println(" clock");
  313. Serial.println(" time <epoch-seconds>");
  314. Serial.println(" list {n}");
  315. Serial.println(" to <recipient name or prefix>");
  316. Serial.println(" to");
  317. Serial.println(" send <text>");
  318. Serial.println(" advert");
  319. Serial.println(" reset path");
  320. Serial.println(" public <text>");
  321. } else {
  322. Serial.print(" ERROR: unknown command: "); Serial.println(command);
  323. }
  324. }
  325. void loop() {
  326. BaseChatMesh::loop();
  327. int len = strlen(command);
  328. while (Serial.available() && len < sizeof(command)-1) {
  329. char c = Serial.read();
  330. if (c != '\n') {
  331. command[len++] = c;
  332. command[len] = 0;
  333. }
  334. Serial.print(c);
  335. }
  336. if (len == sizeof(command)-1) { // command buffer full
  337. command[sizeof(command)-1] = '\r';
  338. }
  339. if (len > 0 && command[len - 1] == '\r') { // received complete line
  340. command[len - 1] = 0; // replace newline with C string null terminator
  341. handleCommand(command);
  342. command[0] = 0; // reset command buffer
  343. }
  344. }
  345. };
  346. #if defined(NRF52_PLATFORM)
  347. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI);
  348. #elif defined(P_LORA_SCLK)
  349. SPIClass spi;
  350. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  351. #else
  352. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  353. #endif
  354. StdRNG fast_rng;
  355. SimpleMeshTables tables;
  356. MyMesh the_mesh(*new WRAPPER_CLASS(radio, board), fast_rng, *new VolatileRTCClock(), tables);
  357. void halt() {
  358. while (1) ;
  359. }
  360. void setup() {
  361. Serial.begin(115200);
  362. board.begin();
  363. #ifdef SX126X_DIO3_TCXO_VOLTAGE
  364. float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
  365. #else
  366. float tcxo = 1.6f;
  367. #endif
  368. #if defined(NRF52_PLATFORM)
  369. SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);
  370. SPI.begin();
  371. #elif defined(P_LORA_SCLK)
  372. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  373. #endif
  374. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, 8, tcxo);
  375. if (status != RADIOLIB_ERR_NONE) {
  376. Serial.print("ERROR: radio init failed: ");
  377. Serial.println(status);
  378. halt();
  379. }
  380. radio.setCRC(0);
  381. #ifdef SX126X_CURRENT_LIMIT
  382. radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
  383. #endif
  384. #ifdef SX126X_DIO2_AS_RF_SWITCH
  385. radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
  386. #endif
  387. fast_rng.begin(radio.random(0x7FFFFFFF));
  388. #if defined(NRF52_PLATFORM)
  389. InternalFS.begin();
  390. the_mesh.begin(InternalFS);
  391. #elif defined(ESP32)
  392. SPIFFS.begin(true);
  393. the_mesh.begin(SPIFFS);
  394. #else
  395. #error "need to define filesystem"
  396. #endif
  397. the_mesh.showWelcome();
  398. // send out initial Advertisement to the mesh
  399. auto pkt = the_mesh.createSelfAdvert(the_mesh.self_name);
  400. if (pkt) {
  401. the_mesh.sendFlood(pkt, 1200); // add slight delay
  402. }
  403. }
  404. void loop() {
  405. the_mesh.loop();
  406. }