main.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  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 <helpers/BaseSerialInterface.h>
  16. #include <RTClib.h>
  17. /* ---------------------------------- CONFIGURATION ------------------------------------- */
  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_LORA_TX_POWER
  34. #define MAX_LORA_TX_POWER LORA_TX_POWER
  35. #endif
  36. #ifndef MAX_CONTACTS
  37. #define MAX_CONTACTS 100
  38. #endif
  39. #ifndef OFFLINE_QUEUE_SIZE
  40. #define OFFLINE_QUEUE_SIZE 16
  41. #endif
  42. #include <helpers/BaseChatMesh.h>
  43. #define SEND_TIMEOUT_BASE_MILLIS 500
  44. #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f
  45. #define DIRECT_SEND_PERHOP_FACTOR 6.0f
  46. #define DIRECT_SEND_PERHOP_EXTRA_MILLIS 250
  47. #define PUBLIC_GROUP_PSK "izOH6cXN6mrJ5e26oRXNcg=="
  48. #if defined(HELTEC_LORA_V3)
  49. #include <helpers/HeltecV3Board.h>
  50. #include <helpers/CustomSX1262Wrapper.h>
  51. static HeltecV3Board board;
  52. #elif defined(HELTEC_LORA_V2)
  53. #include <helpers/HeltecV2Board.h>
  54. #include <helpers/CustomSX1276Wrapper.h>
  55. static HeltecV2Board board;
  56. #elif defined(ARDUINO_XIAO_ESP32C3)
  57. #include <helpers/XiaoC3Board.h>
  58. #include <helpers/CustomSX1262Wrapper.h>
  59. #include <helpers/CustomSX1268Wrapper.h>
  60. static XiaoC3Board board;
  61. #elif defined(SEEED_XIAO_S3) || defined(LILYGO_T3S3)
  62. #include <helpers/ESP32Board.h>
  63. #include <helpers/CustomSX1262Wrapper.h>
  64. static ESP32Board board;
  65. #elif defined(LILYGO_TLORA)
  66. #include <helpers/LilyGoTLoraBoard.h>
  67. #include <helpers/CustomSX1276Wrapper.h>
  68. static LilyGoTLoraBoard board;
  69. #elif defined(RAK_4631)
  70. #include <helpers/nrf52/RAK4631Board.h>
  71. #include <helpers/CustomSX1262Wrapper.h>
  72. static RAK4631Board board;
  73. #elif defined(T1000_E)
  74. #include <helpers/nrf52/T1000eBoard.h>
  75. #include <helpers/CustomLR1110Wrapper.h>
  76. static T1000eBoard board;
  77. #elif defined(HELTEC_T114)
  78. #include <helpers/nrf52/T114Board.h>
  79. #include <helpers/CustomSX1262Wrapper.h>
  80. static T114Board board;
  81. #elif defined(LILYGO_TECHO)
  82. #include <helpers/nrf52/TechoBoard.h>
  83. #include <helpers/CustomSX1262Wrapper.h>
  84. static TechoBoard board;
  85. #else
  86. #error "need to provide a 'board' object"
  87. #endif
  88. #ifdef DISPLAY_CLASS
  89. #include <helpers/ui/SSD1306Display.h>
  90. static DISPLAY_CLASS display;
  91. #include "UITask.h"
  92. static UITask ui_task(display);
  93. #endif
  94. // Believe it or not, this std C function is busted on some platforms!
  95. static uint32_t _atoi(const char* sp) {
  96. uint32_t n = 0;
  97. while (*sp && *sp >= '0' && *sp <= '9') {
  98. n *= 10;
  99. n += (*sp++ - '0');
  100. }
  101. return n;
  102. }
  103. /*------------ Frame Protocol --------------*/
  104. #define FIRMWARE_VER_CODE 2
  105. #ifndef FIRMWARE_BUILD_DATE
  106. #define FIRMWARE_BUILD_DATE "7 Mar 2025"
  107. #endif
  108. #ifndef FIRMWARE_VERSION
  109. #define FIRMWARE_VERSION "v1.2.1"
  110. #endif
  111. #define CMD_APP_START 1
  112. #define CMD_SEND_TXT_MSG 2
  113. #define CMD_SEND_CHANNEL_TXT_MSG 3
  114. #define CMD_GET_CONTACTS 4 // with optional 'since' (for efficient sync)
  115. #define CMD_GET_DEVICE_TIME 5
  116. #define CMD_SET_DEVICE_TIME 6
  117. #define CMD_SEND_SELF_ADVERT 7
  118. #define CMD_SET_ADVERT_NAME 8
  119. #define CMD_ADD_UPDATE_CONTACT 9
  120. #define CMD_SYNC_NEXT_MESSAGE 10
  121. #define CMD_SET_RADIO_PARAMS 11
  122. #define CMD_SET_RADIO_TX_POWER 12
  123. #define CMD_RESET_PATH 13
  124. #define CMD_SET_ADVERT_LATLON 14
  125. #define CMD_REMOVE_CONTACT 15
  126. #define CMD_SHARE_CONTACT 16
  127. #define CMD_EXPORT_CONTACT 17
  128. #define CMD_IMPORT_CONTACT 18
  129. #define CMD_REBOOT 19
  130. #define CMD_GET_BATTERY_VOLTAGE 20
  131. #define CMD_SET_TUNING_PARAMS 21
  132. #define CMD_DEVICE_QEURY 22
  133. #define CMD_EXPORT_PRIVATE_KEY 23
  134. #define CMD_IMPORT_PRIVATE_KEY 24
  135. #define CMD_SEND_RAW_DATA 25
  136. #define CMD_SEND_LOGIN 26
  137. #define CMD_SEND_STATUS_REQ 27
  138. #define CMD_HAS_CONNECTION 28
  139. #define CMD_LOGOUT 29 // 'Disconnect'
  140. #define CMD_GET_CONTACT_BY_KEY 30
  141. #define RESP_CODE_OK 0
  142. #define RESP_CODE_ERR 1
  143. #define RESP_CODE_CONTACTS_START 2 // first reply to CMD_GET_CONTACTS
  144. #define RESP_CODE_CONTACT 3 // multiple of these (after CMD_GET_CONTACTS)
  145. #define RESP_CODE_END_OF_CONTACTS 4 // last reply to CMD_GET_CONTACTS
  146. #define RESP_CODE_SELF_INFO 5 // reply to CMD_APP_START
  147. #define RESP_CODE_SENT 6 // reply to CMD_SEND_TXT_MSG
  148. #define RESP_CODE_CONTACT_MSG_RECV 7 // a reply to CMD_SYNC_NEXT_MESSAGE
  149. #define RESP_CODE_CHANNEL_MSG_RECV 8 // a reply to CMD_SYNC_NEXT_MESSAGE
  150. #define RESP_CODE_CURR_TIME 9 // a reply to CMD_GET_DEVICE_TIME
  151. #define RESP_CODE_NO_MORE_MESSAGES 10 // a reply to CMD_SYNC_NEXT_MESSAGE
  152. #define RESP_CODE_EXPORT_CONTACT 11
  153. #define RESP_CODE_BATTERY_VOLTAGE 12 // a reply to a CMD_GET_BATTERY_VOLTAGE
  154. #define RESP_CODE_DEVICE_INFO 13 // a reply to CMD_DEVICE_QEURY
  155. #define RESP_CODE_PRIVATE_KEY 14 // a reply to CMD_EXPORT_PRIVATE_KEY
  156. #define RESP_CODE_DISABLED 15
  157. // these are _pushed_ to client app at any time
  158. #define PUSH_CODE_ADVERT 0x80
  159. #define PUSH_CODE_PATH_UPDATED 0x81
  160. #define PUSH_CODE_SEND_CONFIRMED 0x82
  161. #define PUSH_CODE_MSG_WAITING 0x83
  162. #define PUSH_CODE_RAW_DATA 0x84
  163. #define PUSH_CODE_LOGIN_SUCCESS 0x85
  164. #define PUSH_CODE_LOGIN_FAIL 0x86
  165. #define PUSH_CODE_STATUS_RESPONSE 0x87
  166. #define PUSH_CODE_LOG_RX_DATA 0x88
  167. /* -------------------------------------------------------------------------------------- */
  168. struct NodePrefs { // persisted to file
  169. float airtime_factor;
  170. char node_name[32];
  171. double node_lat, node_lon;
  172. float freq;
  173. uint8_t sf;
  174. uint8_t cr;
  175. uint8_t reserved1;
  176. uint8_t reserved2;
  177. float bw;
  178. uint8_t tx_power_dbm;
  179. uint8_t unused[3];
  180. float rx_delay_base;
  181. uint32_t ble_pin;
  182. };
  183. class MyMesh : public BaseChatMesh {
  184. FILESYSTEM* _fs;
  185. RADIO_CLASS* _phy;
  186. IdentityStore* _identity_store;
  187. NodePrefs _prefs;
  188. uint32_t expected_ack_crc; // TODO: keep table of expected ACKs
  189. uint32_t pending_login;
  190. uint32_t pending_status;
  191. mesh::GroupChannel* _public;
  192. BaseSerialInterface* _serial;
  193. unsigned long last_msg_sent;
  194. ContactsIterator _iter;
  195. uint32_t _iter_filter_since;
  196. uint32_t _most_recent_lastmod;
  197. uint32_t _active_ble_pin;
  198. bool _iter_started;
  199. uint8_t app_target_ver;
  200. uint8_t cmd_frame[MAX_FRAME_SIZE+1];
  201. uint8_t out_frame[MAX_FRAME_SIZE+1];
  202. struct Frame {
  203. uint8_t len;
  204. uint8_t buf[MAX_FRAME_SIZE];
  205. };
  206. int offline_queue_len;
  207. Frame offline_queue[OFFLINE_QUEUE_SIZE];
  208. void loadMainIdentity(mesh::RNG& trng) {
  209. if (!_identity_store->load("_main", self_id)) {
  210. self_id = mesh::LocalIdentity(&trng); // create new random identity
  211. saveMainIdentity(self_id);
  212. }
  213. }
  214. bool saveMainIdentity(const mesh::LocalIdentity& identity) {
  215. return _identity_store->save("_main", identity);
  216. }
  217. void loadContacts() {
  218. if (_fs->exists("/contacts3")) {
  219. File file = _fs->open("/contacts3");
  220. if (file) {
  221. bool full = false;
  222. while (!full) {
  223. ContactInfo c;
  224. uint8_t pub_key[32];
  225. uint8_t unused;
  226. bool success = (file.read(pub_key, 32) == 32);
  227. success = success && (file.read((uint8_t *) &c.name, 32) == 32);
  228. success = success && (file.read(&c.type, 1) == 1);
  229. success = success && (file.read(&c.flags, 1) == 1);
  230. success = success && (file.read(&unused, 1) == 1);
  231. success = success && (file.read((uint8_t *) &c.sync_since, 4) == 4); // was 'reserved'
  232. success = success && (file.read((uint8_t *) &c.out_path_len, 1) == 1);
  233. success = success && (file.read((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  234. success = success && (file.read(c.out_path, 64) == 64);
  235. success = success && (file.read((uint8_t *) &c.lastmod, 4) == 4);
  236. success = success && (file.read((uint8_t *) &c.gps_lat, 4) == 4);
  237. success = success && (file.read((uint8_t *) &c.gps_lon, 4) == 4);
  238. if (!success) break; // EOF
  239. c.id = mesh::Identity(pub_key);
  240. if (!addContact(c)) full = true;
  241. }
  242. file.close();
  243. }
  244. }
  245. }
  246. void saveContacts() {
  247. #if defined(NRF52_PLATFORM)
  248. File file = _fs->open("/contacts3", FILE_O_WRITE);
  249. if (file) { file.seek(0); file.truncate(); }
  250. #else
  251. File file = _fs->open("/contacts3", "w", true);
  252. #endif
  253. if (file) {
  254. ContactsIterator iter;
  255. ContactInfo c;
  256. uint8_t unused = 0;
  257. while (iter.hasNext(this, c)) {
  258. bool success = (file.write(c.id.pub_key, 32) == 32);
  259. success = success && (file.write((uint8_t *) &c.name, 32) == 32);
  260. success = success && (file.write(&c.type, 1) == 1);
  261. success = success && (file.write(&c.flags, 1) == 1);
  262. success = success && (file.write(&unused, 1) == 1);
  263. success = success && (file.write((uint8_t *) &c.sync_since, 4) == 4);
  264. success = success && (file.write((uint8_t *) &c.out_path_len, 1) == 1);
  265. success = success && (file.write((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  266. success = success && (file.write(c.out_path, 64) == 64);
  267. success = success && (file.write((uint8_t *) &c.lastmod, 4) == 4);
  268. success = success && (file.write((uint8_t *) &c.gps_lat, 4) == 4);
  269. success = success && (file.write((uint8_t *) &c.gps_lon, 4) == 4);
  270. if (!success) break; // write failed
  271. }
  272. file.close();
  273. }
  274. }
  275. int getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) override {
  276. char path[64];
  277. char fname[18];
  278. if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
  279. mesh::Utils::toHex(fname, key, key_len);
  280. sprintf(path, "/bl/%s", fname);
  281. if (_fs->exists(path)) {
  282. File f = _fs->open(path);
  283. if (f) {
  284. int len = f.read(dest_buf, 255); // currently MAX 255 byte blob len supported!!
  285. f.close();
  286. return len;
  287. }
  288. }
  289. return 0; // not found
  290. }
  291. bool putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], int len) override {
  292. char path[64];
  293. char fname[18];
  294. if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
  295. mesh::Utils::toHex(fname, key, key_len);
  296. sprintf(path, "/bl/%s", fname);
  297. #if defined(NRF52_PLATFORM)
  298. File f = _fs->open(path, FILE_O_WRITE);
  299. if (f) { f.seek(0); f.truncate(); }
  300. #else
  301. File f = _fs->open(path, "w", true);
  302. #endif
  303. if (f) {
  304. int n = f.write(src_buf, len);
  305. f.close();
  306. if (n == len) return true; // success!
  307. _fs->remove(path); // blob was only partially written!
  308. }
  309. return false; // error
  310. }
  311. void writeOKFrame() {
  312. uint8_t buf[1];
  313. buf[0] = RESP_CODE_OK;
  314. _serial->writeFrame(buf, 1);
  315. }
  316. void writeErrFrame() {
  317. uint8_t buf[1];
  318. buf[0] = RESP_CODE_ERR;
  319. _serial->writeFrame(buf, 1);
  320. }
  321. void writeDisabledFrame() {
  322. uint8_t buf[1];
  323. buf[0] = RESP_CODE_DISABLED;
  324. _serial->writeFrame(buf, 1);
  325. }
  326. void writeContactRespFrame(uint8_t code, const ContactInfo& contact) {
  327. int i = 0;
  328. out_frame[i++] = code;
  329. memcpy(&out_frame[i], contact.id.pub_key, PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  330. out_frame[i++] = contact.type;
  331. out_frame[i++] = contact.flags;
  332. out_frame[i++] = contact.out_path_len;
  333. memcpy(&out_frame[i], contact.out_path, MAX_PATH_SIZE); i += MAX_PATH_SIZE;
  334. StrHelper::strzcpy((char *) &out_frame[i], contact.name, 32); i += 32;
  335. memcpy(&out_frame[i], &contact.last_advert_timestamp, 4); i += 4;
  336. memcpy(&out_frame[i], &contact.gps_lat, 4); i += 4;
  337. memcpy(&out_frame[i], &contact.gps_lon, 4); i += 4;
  338. memcpy(&out_frame[i], &contact.lastmod, 4); i += 4;
  339. _serial->writeFrame(out_frame, i);
  340. }
  341. void updateContactFromFrame(ContactInfo& contact, const uint8_t* frame, int len) {
  342. int i = 0;
  343. uint8_t code = frame[i++]; // eg. CMD_ADD_UPDATE_CONTACT
  344. memcpy(contact.id.pub_key, &frame[i], PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  345. contact.type = frame[i++];
  346. contact.flags = frame[i++];
  347. contact.out_path_len = frame[i++];
  348. memcpy(contact.out_path, &frame[i], MAX_PATH_SIZE); i += MAX_PATH_SIZE;
  349. memcpy(contact.name, &frame[i], 32); i += 32;
  350. memcpy(&contact.last_advert_timestamp, &frame[i], 4); i += 4;
  351. if (i + 8 >= len) { // optional fields
  352. memcpy(&contact.gps_lat, &frame[i], 4); i += 4;
  353. memcpy(&contact.gps_lon, &frame[i], 4); i += 4;
  354. }
  355. }
  356. void addToOfflineQueue(const uint8_t frame[], int len) {
  357. if (offline_queue_len >= OFFLINE_QUEUE_SIZE) {
  358. MESH_DEBUG_PRINTLN("ERROR: offline_queue is full!");
  359. } else {
  360. offline_queue[offline_queue_len].len = len;
  361. memcpy(offline_queue[offline_queue_len].buf, frame, len);
  362. offline_queue_len++;
  363. }
  364. }
  365. int getFromOfflineQueue(uint8_t frame[]) {
  366. if (offline_queue_len > 0) { // check offline queue
  367. size_t len = offline_queue[0].len; // take from top of queue
  368. memcpy(frame, offline_queue[0].buf, len);
  369. offline_queue_len--;
  370. for (int i = 0; i < offline_queue_len; i++) { // delete top item from queue
  371. offline_queue[i] = offline_queue[i + 1];
  372. }
  373. return len;
  374. }
  375. return 0; // queue is empty
  376. }
  377. void soundBuzzer() {
  378. // TODO
  379. }
  380. protected:
  381. float getAirtimeBudgetFactor() const override {
  382. return _prefs.airtime_factor;
  383. }
  384. int calcRxDelay(float score, uint32_t air_time) const override {
  385. if (_prefs.rx_delay_base <= 0.0f) return 0;
  386. return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  387. }
  388. void logRxRaw(float snr, float rssi, const uint8_t raw[], int len) override {
  389. if (_serial->isConnected()) {
  390. int i = 0;
  391. out_frame[i++] = PUSH_CODE_LOG_RX_DATA;
  392. out_frame[i++] = (int8_t)(snr * 4);
  393. out_frame[i++] = (int8_t)(rssi);
  394. memcpy(&out_frame[i], raw, len); i += len;
  395. _serial->writeFrame(out_frame, i);
  396. }
  397. }
  398. void onDiscoveredContact(ContactInfo& contact, bool is_new) override {
  399. if (_serial->isConnected()) {
  400. out_frame[0] = PUSH_CODE_ADVERT;
  401. memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE);
  402. _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE);
  403. } else {
  404. soundBuzzer();
  405. }
  406. saveContacts();
  407. }
  408. void onContactPathUpdated(const ContactInfo& contact) override {
  409. out_frame[0] = PUSH_CODE_PATH_UPDATED;
  410. memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE);
  411. _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE); // NOTE: app may not be connected
  412. saveContacts();
  413. }
  414. bool processAck(const uint8_t *data) override {
  415. // TODO: see if matches any in a table
  416. if (memcmp(data, &expected_ack_crc, 4) == 0) { // got an ACK from recipient
  417. out_frame[0] = PUSH_CODE_SEND_CONFIRMED;
  418. memcpy(&out_frame[1], data, 4);
  419. uint32_t trip_time = _ms->getMillis() - last_msg_sent;
  420. memcpy(&out_frame[5], &trip_time, 4);
  421. _serial->writeFrame(out_frame, 9);
  422. // NOTE: the same ACK can be received multiple times!
  423. expected_ack_crc = 0; // reset our expected hash, now that we have received ACK
  424. return true;
  425. }
  426. return checkConnectionsAck(data);
  427. }
  428. void queueMessage(const ContactInfo& from, uint8_t txt_type, uint8_t path_len, uint32_t sender_timestamp, const uint8_t* extra, int extra_len, const char *text) {
  429. int i = 0;
  430. out_frame[i++] = RESP_CODE_CONTACT_MSG_RECV;
  431. memcpy(&out_frame[i], from.id.pub_key, 6); i += 6; // just 6-byte prefix
  432. out_frame[i++] = path_len;
  433. out_frame[i++] = txt_type;
  434. memcpy(&out_frame[i], &sender_timestamp, 4); i += 4;
  435. if (extra_len > 0) {
  436. memcpy(&out_frame[i], extra, extra_len); i += extra_len;
  437. }
  438. int tlen = strlen(text); // TODO: UTF-8 ??
  439. if (i + tlen > MAX_FRAME_SIZE) {
  440. tlen = MAX_FRAME_SIZE - i;
  441. }
  442. memcpy(&out_frame[i], text, tlen); i += tlen;
  443. addToOfflineQueue(out_frame, i);
  444. if (_serial->isConnected()) {
  445. uint8_t frame[1];
  446. frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle'
  447. _serial->writeFrame(frame, 1);
  448. } else {
  449. soundBuzzer();
  450. }
  451. #ifdef DISPLAY_CLASS
  452. ui_task.showMsgPreview(path_len, from.name, text);
  453. #endif
  454. }
  455. void onMessageRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const char *text) override {
  456. markConnectionActive(from); // in case this is from a server, and we have a connection
  457. queueMessage(from, TXT_TYPE_PLAIN, path_len, sender_timestamp, NULL, 0, text);
  458. }
  459. void onCommandDataRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const char *text) override {
  460. markConnectionActive(from); // in case this is from a server, and we have a connection
  461. queueMessage(from, TXT_TYPE_CLI_DATA, path_len, sender_timestamp, NULL, 0, text);
  462. }
  463. void onSignedMessageRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) override {
  464. markConnectionActive(from);
  465. saveContacts(); // from.sync_since change needs to be persisted
  466. queueMessage(from, TXT_TYPE_SIGNED_PLAIN, path_len, sender_timestamp, sender_prefix, 4, text);
  467. }
  468. void onChannelMessageRecv(const mesh::GroupChannel& channel, int in_path_len, uint32_t timestamp, const char *text) override {
  469. int i = 0;
  470. out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV;
  471. out_frame[i++] = 0; // FUTURE: channel_idx (will just be 'public' for now)
  472. out_frame[i++] = in_path_len < 0 ? 0xFF : in_path_len;
  473. out_frame[i++] = TXT_TYPE_PLAIN;
  474. memcpy(&out_frame[i], &timestamp, 4); i += 4;
  475. int tlen = strlen(text); // TODO: UTF-8 ??
  476. if (i + tlen > MAX_FRAME_SIZE) {
  477. tlen = MAX_FRAME_SIZE - i;
  478. }
  479. memcpy(&out_frame[i], text, tlen); i += tlen;
  480. addToOfflineQueue(out_frame, i);
  481. if (_serial->isConnected()) {
  482. uint8_t frame[1];
  483. frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle'
  484. _serial->writeFrame(frame, 1);
  485. } else {
  486. soundBuzzer();
  487. }
  488. #ifdef DISPLAY_CLASS
  489. ui_task.showMsgPreview(in_path_len < 0 ? 0xFF : in_path_len, "Public", text);
  490. #endif
  491. }
  492. void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) override {
  493. uint32_t sender_timestamp;
  494. memcpy(&sender_timestamp, data, 4);
  495. if (pending_login && memcmp(&pending_login, contact.id.pub_key, 4) == 0) { // check for login response
  496. // yes, is response to pending sendLogin()
  497. pending_login = 0;
  498. int i = 0;
  499. if (memcmp(&data[4], "OK", 2) == 0) { // legacy Repeater login OK response
  500. out_frame[i++] = PUSH_CODE_LOGIN_SUCCESS;
  501. out_frame[i++] = 0; // legacy: is_admin = false
  502. } else if (data[4] == RESP_SERVER_LOGIN_OK) { // new login response
  503. uint16_t keep_alive_secs = ((uint16_t)data[5]) * 16;
  504. if (keep_alive_secs > 0) {
  505. startConnection(contact, keep_alive_secs);
  506. }
  507. out_frame[i++] = PUSH_CODE_LOGIN_SUCCESS;
  508. out_frame[i++] = data[6]; // permissions (eg. is_admin)
  509. } else {
  510. out_frame[i++] = PUSH_CODE_LOGIN_FAIL;
  511. out_frame[i++] = 0; // reserved
  512. }
  513. memcpy(&out_frame[i], contact.id.pub_key, 6); i += 6; // pub_key_prefix
  514. _serial->writeFrame(out_frame, i);
  515. } else if (len > 4 && pending_status && memcmp(&pending_status, contact.id.pub_key, 4) == 0) { // check for status response
  516. // yes, is response to pending sendStatusRequest()
  517. pending_status = 0;
  518. int i = 0;
  519. out_frame[i++] = PUSH_CODE_STATUS_RESPONSE;
  520. out_frame[i++] = 0; // reserved
  521. memcpy(&out_frame[i], contact.id.pub_key, 6); i += 6; // pub_key_prefix
  522. memcpy(&out_frame[i], &data[4], len - 4); i += (len - 4);
  523. _serial->writeFrame(out_frame, i);
  524. }
  525. }
  526. void onRawDataRecv(mesh::Packet* packet) override {
  527. int i = 0;
  528. out_frame[i++] = PUSH_CODE_RAW_DATA;
  529. out_frame[i++] = (int8_t)(_radio->getLastSNR() * 4);
  530. out_frame[i++] = (int8_t)(_radio->getLastRSSI());
  531. out_frame[i++] = 0xFF; // reserved (possibly path_len in future)
  532. memcpy(&out_frame[i], packet->payload, packet->payload_len); i += packet->payload_len;
  533. if (_serial->isConnected()) {
  534. _serial->writeFrame(out_frame, i);
  535. } else {
  536. MESH_DEBUG_PRINTLN("onRawDataRecv(), data received while app offline");
  537. }
  538. }
  539. uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const override {
  540. return SEND_TIMEOUT_BASE_MILLIS + (FLOOD_SEND_TIMEOUT_FACTOR * pkt_airtime_millis);
  541. }
  542. uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const override {
  543. return SEND_TIMEOUT_BASE_MILLIS +
  544. ( (pkt_airtime_millis*DIRECT_SEND_PERHOP_FACTOR + DIRECT_SEND_PERHOP_EXTRA_MILLIS) * (path_len + 1));
  545. }
  546. void onSendTimeout() override {
  547. }
  548. public:
  549. MyMesh(RADIO_CLASS& phy, RadioLibWrapper& rw, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
  550. : BaseChatMesh(rw, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables), _serial(NULL), _phy(&phy)
  551. {
  552. _iter_started = false;
  553. offline_queue_len = 0;
  554. app_target_ver = 0;
  555. _identity_store = NULL;
  556. pending_login = pending_status = 0;
  557. // defaults
  558. memset(&_prefs, 0, sizeof(_prefs));
  559. _prefs.airtime_factor = 1.0; // one half
  560. strcpy(_prefs.node_name, "NONAME");
  561. _prefs.freq = LORA_FREQ;
  562. _prefs.sf = LORA_SF;
  563. _prefs.bw = LORA_BW;
  564. _prefs.cr = LORA_CR;
  565. _prefs.tx_power_dbm = LORA_TX_POWER;
  566. //_prefs.rx_delay_base = 10.0f; enable once new algo fixed
  567. }
  568. void begin(FILESYSTEM& fs, mesh::RNG& trng) {
  569. _fs = &fs;
  570. BaseChatMesh::begin();
  571. #if defined(NRF52_PLATFORM)
  572. _identity_store = new IdentityStore(fs, "");
  573. #else
  574. _identity_store = new IdentityStore(fs, "/identity");
  575. #endif
  576. loadMainIdentity(trng);
  577. // load persisted prefs
  578. if (_fs->exists("/node_prefs")) {
  579. File file = _fs->open("/node_prefs");
  580. if (file) {
  581. uint8_t pad[8];
  582. file.read((uint8_t *) &_prefs.airtime_factor, sizeof(float)); // 0
  583. file.read((uint8_t *) _prefs.node_name, sizeof(_prefs.node_name)); // 4
  584. file.read(pad, 4); // 36
  585. file.read((uint8_t *) &_prefs.node_lat, sizeof(_prefs.node_lat)); // 40
  586. file.read((uint8_t *) &_prefs.node_lon, sizeof(_prefs.node_lon)); // 48
  587. file.read((uint8_t *) &_prefs.freq, sizeof(_prefs.freq)); // 56
  588. file.read((uint8_t *) &_prefs.sf, sizeof(_prefs.sf)); // 60
  589. file.read((uint8_t *) &_prefs.cr, sizeof(_prefs.cr)); // 61
  590. file.read((uint8_t *) &_prefs.reserved1, sizeof(_prefs.reserved1)); // 62
  591. file.read((uint8_t *) &_prefs.reserved2, sizeof(_prefs.reserved2)); // 63
  592. file.read((uint8_t *) &_prefs.bw, sizeof(_prefs.bw)); // 64
  593. file.read((uint8_t *) &_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
  594. file.read((uint8_t *) _prefs.unused, sizeof(_prefs.unused)); // 69
  595. file.read((uint8_t *) &_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
  596. file.read(pad, 4); // 76
  597. file.read((uint8_t *) &_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
  598. // sanitise bad pref values
  599. _prefs.rx_delay_base = constrain(_prefs.rx_delay_base, 0, 20.0f);
  600. _prefs.airtime_factor = constrain(_prefs.airtime_factor, 0, 9.0f);
  601. _prefs.freq = constrain(_prefs.freq, 400.0f, 2500.0f);
  602. _prefs.bw = constrain(_prefs.bw, 62.5f, 500.0f);
  603. _prefs.sf = constrain(_prefs.sf, 7, 12);
  604. _prefs.cr = constrain(_prefs.cr, 5, 8);
  605. _prefs.tx_power_dbm = constrain(_prefs.tx_power_dbm, 1, MAX_LORA_TX_POWER);
  606. file.close();
  607. }
  608. }
  609. #ifdef BLE_PIN_CODE
  610. if (_prefs.ble_pin == 0) {
  611. #ifdef DISPLAY_CLASS
  612. _active_ble_pin = trng.nextInt(100000, 999999); // random pin each session
  613. #else
  614. _active_ble_pin = BLE_PIN_CODE; // otherwise static pin
  615. #endif
  616. } else {
  617. _active_ble_pin = _prefs.ble_pin;
  618. }
  619. #else
  620. _active_ble_pin = 0;
  621. #endif
  622. // init 'blob store' support
  623. _fs->mkdir("/bl");
  624. loadContacts();
  625. _public = addChannel(PUBLIC_GROUP_PSK); // pre-configure Andy's public channel
  626. _phy->setFrequency(_prefs.freq);
  627. _phy->setSpreadingFactor(_prefs.sf);
  628. _phy->setBandwidth(_prefs.bw);
  629. _phy->setCodingRate(_prefs.cr);
  630. _phy->setOutputPower(_prefs.tx_power_dbm);
  631. }
  632. const char* getNodeName() { return _prefs.node_name; }
  633. uint32_t getBLEPin() { return _active_ble_pin; }
  634. void startInterface(BaseSerialInterface& serial) {
  635. _serial = &serial;
  636. serial.enable();
  637. }
  638. void savePrefs() {
  639. #if defined(NRF52_PLATFORM)
  640. File file = _fs->open("/node_prefs", FILE_O_WRITE);
  641. if (file) { file.seek(0); file.truncate(); }
  642. #else
  643. File file = _fs->open("/node_prefs", "w", true);
  644. #endif
  645. if (file) {
  646. uint8_t pad[8];
  647. memset(pad, 0, sizeof(pad));
  648. file.write((uint8_t *) &_prefs.airtime_factor, sizeof(float)); // 0
  649. file.write((uint8_t *) _prefs.node_name, sizeof(_prefs.node_name)); // 4
  650. file.write(pad, 4); // 36
  651. file.write((uint8_t *) &_prefs.node_lat, sizeof(_prefs.node_lat)); // 40
  652. file.write((uint8_t *) &_prefs.node_lon, sizeof(_prefs.node_lon)); // 48
  653. file.write((uint8_t *) &_prefs.freq, sizeof(_prefs.freq)); // 56
  654. file.write((uint8_t *) &_prefs.sf, sizeof(_prefs.sf)); // 60
  655. file.write((uint8_t *) &_prefs.cr, sizeof(_prefs.cr)); // 61
  656. file.write((uint8_t *) &_prefs.reserved1, sizeof(_prefs.reserved1)); // 62
  657. file.write((uint8_t *) &_prefs.reserved2, sizeof(_prefs.reserved2)); // 63
  658. file.write((uint8_t *) &_prefs.bw, sizeof(_prefs.bw)); // 64
  659. file.write((uint8_t *) &_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
  660. file.write((uint8_t *) _prefs.unused, sizeof(_prefs.unused)); // 69
  661. file.write((uint8_t *) &_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
  662. file.write(pad, 4); // 76
  663. file.write((uint8_t *) &_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
  664. file.close();
  665. }
  666. }
  667. void handleCmdFrame(size_t len) {
  668. if (cmd_frame[0] == CMD_DEVICE_QEURY && len >= 2) { // sent when app establishes connection
  669. app_target_ver = cmd_frame[1]; // which version of protocol does app understand
  670. int i = 0;
  671. out_frame[i++] = RESP_CODE_DEVICE_INFO;
  672. out_frame[i++] = FIRMWARE_VER_CODE;
  673. memset(&out_frame[i], 0, 6); i += 6; // reserved
  674. memset(&out_frame[i], 0, 12);
  675. strcpy((char *) &out_frame[i], FIRMWARE_BUILD_DATE); i += 12;
  676. StrHelper::strzcpy((char *) &out_frame[i], board.getManufacturerName(), 40); i += 40;
  677. StrHelper::strzcpy((char *) &out_frame[i], FIRMWARE_VERSION, 20); i += 20;
  678. _serial->writeFrame(out_frame, i);
  679. } else if (cmd_frame[0] == CMD_APP_START && len >= 8) { // sent when app establishes connection, respond with node ID
  680. // cmd_frame[1..7] reserved future
  681. char* app_name = (char *) &cmd_frame[8];
  682. cmd_frame[len] = 0; // make app_name null terminated
  683. MESH_DEBUG_PRINTLN("App %s connected", app_name);
  684. _iter_started = false; // stop any left-over ContactsIterator
  685. int i = 0;
  686. out_frame[i++] = RESP_CODE_SELF_INFO;
  687. out_frame[i++] = ADV_TYPE_CHAT; // what this node Advert identifies as (maybe node's pronouns too?? :-)
  688. out_frame[i++] = _prefs.tx_power_dbm;
  689. out_frame[i++] = MAX_LORA_TX_POWER;
  690. memcpy(&out_frame[i], self_id.pub_key, PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  691. int32_t lat, lon, alt = 0;
  692. lat = (_prefs.node_lat * 1000000.0);
  693. lon = (_prefs.node_lon * 1000000.0);
  694. memcpy(&out_frame[i], &lat, 4); i += 4;
  695. memcpy(&out_frame[i], &lon, 4); i += 4;
  696. memcpy(&out_frame[i], &alt, 4); i += 4;
  697. uint32_t freq = _prefs.freq * 1000;
  698. memcpy(&out_frame[i], &freq, 4); i += 4;
  699. uint32_t bw = _prefs.bw*1000;
  700. memcpy(&out_frame[i], &bw, 4); i += 4;
  701. out_frame[i++] = _prefs.sf;
  702. out_frame[i++] = _prefs.cr;
  703. int tlen = strlen(_prefs.node_name); // revisit: UTF_8 ??
  704. memcpy(&out_frame[i], _prefs.node_name, tlen); i += tlen;
  705. _serial->writeFrame(out_frame, i);
  706. } else if (cmd_frame[0] == CMD_SEND_TXT_MSG && len >= 14) {
  707. int i = 1;
  708. uint8_t txt_type = cmd_frame[i++];
  709. uint8_t attempt = cmd_frame[i++];
  710. uint32_t msg_timestamp;
  711. memcpy(&msg_timestamp, &cmd_frame[i], 4); i += 4;
  712. uint8_t* pub_key_prefix = &cmd_frame[i]; i += 6;
  713. ContactInfo* recipient = lookupContactByPubKey(pub_key_prefix, 6);
  714. if (recipient && attempt < 4 && (txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_CLI_DATA)) {
  715. char *text = (char *) &cmd_frame[i];
  716. int tlen = len - i;
  717. uint32_t est_timeout;
  718. text[tlen] = 0; // ensure null
  719. int result;
  720. if (txt_type == TXT_TYPE_CLI_DATA) {
  721. result = sendCommandData(*recipient, msg_timestamp, attempt, text, est_timeout);
  722. expected_ack_crc = 0; // no Ack expected
  723. } else {
  724. result = sendMessage(*recipient, msg_timestamp, attempt, text, expected_ack_crc, est_timeout);
  725. }
  726. // TODO: add expected ACK to table
  727. if (result == MSG_SEND_FAILED) {
  728. writeErrFrame();
  729. } else {
  730. last_msg_sent = _ms->getMillis();
  731. out_frame[0] = RESP_CODE_SENT;
  732. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  733. memcpy(&out_frame[2], &expected_ack_crc, 4);
  734. memcpy(&out_frame[6], &est_timeout, 4);
  735. _serial->writeFrame(out_frame, 10);
  736. }
  737. } else {
  738. writeErrFrame(); // unknown recipient, or unsuported TXT_TYPE_*
  739. }
  740. } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel msg
  741. int i = 1;
  742. uint8_t txt_type = cmd_frame[i++]; // should be TXT_TYPE_PLAIN
  743. uint8_t channel_idx = cmd_frame[i++]; // reserved future
  744. uint32_t msg_timestamp;
  745. memcpy(&msg_timestamp, &cmd_frame[i], 4); i += 4;
  746. const char *text = (char *) &cmd_frame[i];
  747. if (txt_type == TXT_TYPE_PLAIN && sendGroupMessage(msg_timestamp, *_public, _prefs.node_name, text, len - i)) { // hard-coded to 'public' channel for now
  748. writeOKFrame();
  749. } else {
  750. writeErrFrame();
  751. }
  752. } else if (cmd_frame[0] == CMD_GET_CONTACTS) { // get Contact list
  753. if (_iter_started) {
  754. writeErrFrame(); // iterator is currently busy
  755. } else {
  756. if (len >= 5) { // has optional 'since' param
  757. memcpy(&_iter_filter_since, &cmd_frame[1], 4);
  758. } else {
  759. _iter_filter_since = 0;
  760. }
  761. uint8_t reply[5];
  762. reply[0] = RESP_CODE_CONTACTS_START;
  763. uint32_t count = getNumContacts(); // total, NOT filtered count
  764. memcpy(&reply[1], &count, 4);
  765. _serial->writeFrame(reply, 5);
  766. // start iterator
  767. _iter = startContactsIterator();
  768. _iter_started = true;
  769. _most_recent_lastmod = 0;
  770. }
  771. } else if (cmd_frame[0] == CMD_SET_ADVERT_NAME && len >= 2) {
  772. int nlen = len - 1;
  773. if (nlen > sizeof(_prefs.node_name)-1) nlen = sizeof(_prefs.node_name)-1; // max len
  774. memcpy(_prefs.node_name, &cmd_frame[1], nlen);
  775. _prefs.node_name[nlen] = 0; // null terminator
  776. savePrefs();
  777. writeOKFrame();
  778. } else if (cmd_frame[0] == CMD_SET_ADVERT_LATLON && len >= 9) {
  779. int32_t lat, lon, alt = 0;
  780. memcpy(&lat, &cmd_frame[1], 4);
  781. memcpy(&lon, &cmd_frame[5], 4);
  782. if (len >= 13) {
  783. memcpy(&alt, &cmd_frame[9], 4); // for FUTURE support
  784. }
  785. if (lat <= 90*1E6 && lat >= -90*1E6 && lon <= 180*1E6 && lon >= -180*1E6) {
  786. _prefs.node_lat = ((double)lat) / 1000000.0;
  787. _prefs.node_lon = ((double)lon) / 1000000.0;
  788. savePrefs();
  789. writeOKFrame();
  790. } else {
  791. writeErrFrame(); // invalid geo coordinate
  792. }
  793. } else if (cmd_frame[0] == CMD_GET_DEVICE_TIME) {
  794. uint8_t reply[5];
  795. reply[0] = RESP_CODE_CURR_TIME;
  796. uint32_t now = getRTCClock()->getCurrentTime();
  797. memcpy(&reply[1], &now, 4);
  798. _serial->writeFrame(reply, 5);
  799. } else if (cmd_frame[0] == CMD_SET_DEVICE_TIME && len >= 5) {
  800. uint32_t secs;
  801. memcpy(&secs, &cmd_frame[1], 4);
  802. uint32_t curr = getRTCClock()->getCurrentTime();
  803. if (secs >= curr) {
  804. getRTCClock()->setCurrentTime(secs);
  805. writeOKFrame();
  806. } else {
  807. writeErrFrame();
  808. }
  809. } else if (cmd_frame[0] == CMD_SEND_SELF_ADVERT) {
  810. auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  811. if (pkt) {
  812. if (len >= 2 && cmd_frame[1] == 1) { // optional param (1 = flood, 0 = zero hop)
  813. sendFlood(pkt);
  814. } else {
  815. sendZeroHop(pkt);
  816. }
  817. writeOKFrame();
  818. } else {
  819. writeErrFrame();
  820. }
  821. } else if (cmd_frame[0] == CMD_RESET_PATH && len >= 1+32) {
  822. uint8_t* pub_key = &cmd_frame[1];
  823. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  824. if (recipient) {
  825. recipient->out_path_len = -1;
  826. //recipient->lastmod = ?? shouldn't be needed, app already has this version of contact
  827. saveContacts();
  828. writeOKFrame();
  829. } else {
  830. writeErrFrame(); // unknown contact
  831. }
  832. } else if (cmd_frame[0] == CMD_ADD_UPDATE_CONTACT && len >= 1+32+2+1) {
  833. uint8_t* pub_key = &cmd_frame[1];
  834. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  835. if (recipient) {
  836. updateContactFromFrame(*recipient, cmd_frame, len);
  837. //recipient->lastmod = ?? shouldn't be needed, app already has this version of contact
  838. saveContacts();
  839. writeOKFrame();
  840. } else {
  841. ContactInfo contact;
  842. updateContactFromFrame(contact, cmd_frame, len);
  843. contact.lastmod = getRTCClock()->getCurrentTime();
  844. contact.sync_since = 0;
  845. if (addContact(contact)) {
  846. saveContacts();
  847. writeOKFrame();
  848. } else {
  849. writeErrFrame(); // table is full!
  850. }
  851. }
  852. } else if (cmd_frame[0] == CMD_REMOVE_CONTACT) {
  853. uint8_t* pub_key = &cmd_frame[1];
  854. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  855. if (recipient && removeContact(*recipient)) {
  856. saveContacts();
  857. writeOKFrame();
  858. } else {
  859. writeErrFrame(); // not found, or unable to remove
  860. }
  861. } else if (cmd_frame[0] == CMD_SHARE_CONTACT) {
  862. uint8_t* pub_key = &cmd_frame[1];
  863. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  864. if (recipient && shareContactZeroHop(*recipient)) {
  865. writeOKFrame();
  866. } else {
  867. writeErrFrame(); // not found, or unable to send
  868. }
  869. } else if (cmd_frame[0] == CMD_GET_CONTACT_BY_KEY) {
  870. uint8_t* pub_key = &cmd_frame[1];
  871. ContactInfo* contact = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  872. if (contact) {
  873. writeContactRespFrame(RESP_CODE_CONTACT, *contact);
  874. } else {
  875. writeErrFrame(); // not found
  876. }
  877. } else if (cmd_frame[0] == CMD_EXPORT_CONTACT) {
  878. if (len < 1 + PUB_KEY_SIZE) {
  879. // export SELF
  880. auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  881. if (pkt) {
  882. out_frame[0] = RESP_CODE_EXPORT_CONTACT;
  883. uint8_t out_len = pkt->writeTo(&out_frame[1]);
  884. releasePacket(pkt); // undo the obtainNewPacket()
  885. _serial->writeFrame(out_frame, out_len + 1);
  886. } else {
  887. writeErrFrame(); // Error
  888. }
  889. } else {
  890. uint8_t* pub_key = &cmd_frame[1];
  891. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  892. uint8_t out_len;
  893. if (recipient && (out_len = exportContact(*recipient, &out_frame[1])) > 0) {
  894. out_frame[0] = RESP_CODE_EXPORT_CONTACT;
  895. _serial->writeFrame(out_frame, out_len + 1);
  896. } else {
  897. writeErrFrame(); // not found
  898. }
  899. }
  900. } else if (cmd_frame[0] == CMD_IMPORT_CONTACT && len > 2+32+64) {
  901. if (importContact(&cmd_frame[1], len - 1)) {
  902. writeOKFrame();
  903. } else {
  904. writeErrFrame();
  905. }
  906. } else if (cmd_frame[0] == CMD_SYNC_NEXT_MESSAGE) {
  907. int out_len;
  908. if ((out_len = getFromOfflineQueue(out_frame)) > 0) {
  909. _serial->writeFrame(out_frame, out_len);
  910. } else {
  911. out_frame[0] = RESP_CODE_NO_MORE_MESSAGES;
  912. _serial->writeFrame(out_frame, 1);
  913. }
  914. } else if (cmd_frame[0] == CMD_SET_RADIO_PARAMS) {
  915. int i = 1;
  916. uint32_t freq;
  917. memcpy(&freq, &cmd_frame[i], 4); i += 4;
  918. uint32_t bw;
  919. memcpy(&bw, &cmd_frame[i], 4); i += 4;
  920. uint8_t sf = cmd_frame[i++];
  921. uint8_t cr = cmd_frame[i++];
  922. if (freq >= 300000 && freq <= 2500000 && sf >= 7 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7000 && bw <= 500000) {
  923. _prefs.sf = sf;
  924. _prefs.cr = cr;
  925. _prefs.freq = (float)freq / 1000.0;
  926. _prefs.bw = (float)bw / 1000.0;
  927. savePrefs();
  928. _phy->setFrequency(_prefs.freq);
  929. _phy->setSpreadingFactor(_prefs.sf);
  930. _phy->setBandwidth(_prefs.bw);
  931. _phy->setCodingRate(_prefs.cr);
  932. MESH_DEBUG_PRINTLN("OK: CMD_SET_RADIO_PARAMS: f=%d, bw=%d, sf=%d, cr=%d", freq, bw, (uint32_t)sf, (uint32_t)cr);
  933. writeOKFrame();
  934. } else {
  935. MESH_DEBUG_PRINTLN("Error: CMD_SET_RADIO_PARAMS: f=%d, bw=%d, sf=%d, cr=%d", freq, bw, (uint32_t)sf, (uint32_t)cr);
  936. writeErrFrame();
  937. }
  938. } else if (cmd_frame[0] == CMD_SET_RADIO_TX_POWER) {
  939. if (cmd_frame[1] > MAX_LORA_TX_POWER) {
  940. writeErrFrame();
  941. } else {
  942. _prefs.tx_power_dbm = cmd_frame[1];
  943. savePrefs();
  944. _phy->setOutputPower(_prefs.tx_power_dbm);
  945. writeOKFrame();
  946. }
  947. } else if (cmd_frame[0] == CMD_SET_TUNING_PARAMS) {
  948. int i = 1;
  949. uint32_t rx, af;
  950. memcpy(&rx, &cmd_frame[i], 4); i += 4;
  951. memcpy(&af, &cmd_frame[i], 4); i += 4;
  952. _prefs.rx_delay_base = ((float)rx) / 1000.0f;
  953. _prefs.airtime_factor = ((float)af) / 1000.0f;
  954. savePrefs();
  955. writeOKFrame();
  956. } else if (cmd_frame[0] == CMD_REBOOT && memcmp(&cmd_frame[1], "reboot", 6) == 0) {
  957. board.reboot();
  958. } else if (cmd_frame[0] == CMD_GET_BATTERY_VOLTAGE) {
  959. uint8_t reply[3];
  960. reply[0] = RESP_CODE_BATTERY_VOLTAGE;
  961. uint16_t battery_millivolts = board.getBattMilliVolts();
  962. memcpy(&reply[1], &battery_millivolts, 2);
  963. _serial->writeFrame(reply, 3);
  964. } else if (cmd_frame[0] == CMD_EXPORT_PRIVATE_KEY) {
  965. #if ENABLE_PRIVATE_KEY_EXPORT
  966. uint8_t reply[65];
  967. reply[0] = RESP_CODE_PRIVATE_KEY;
  968. self_id.writeTo(&reply[1], 64);
  969. _serial->writeFrame(reply, 65);
  970. #else
  971. writeDisabledFrame();
  972. #endif
  973. } else if (cmd_frame[0] == CMD_IMPORT_PRIVATE_KEY && len >= 65) {
  974. #if ENABLE_PRIVATE_KEY_IMPORT
  975. mesh::LocalIdentity identity;
  976. identity.readFrom(&cmd_frame[1], 64);
  977. if (saveMainIdentity(identity)) {
  978. self_id = identity;
  979. writeOKFrame();
  980. } else {
  981. writeErrFrame();
  982. }
  983. #else
  984. writeDisabledFrame();
  985. #endif
  986. } else if (cmd_frame[0] == CMD_SEND_RAW_DATA && len >= 6) {
  987. int i = 1;
  988. int8_t path_len = cmd_frame[i++];
  989. if (path_len >= 0 && i + path_len + 4 <= len) { // minimum 4 byte payload
  990. uint8_t* path = &cmd_frame[i]; i += path_len;
  991. auto pkt = createRawData(&cmd_frame[i], len - i);
  992. if (pkt) {
  993. sendDirect(pkt, path, path_len);
  994. writeOKFrame();
  995. } else {
  996. writeErrFrame();
  997. }
  998. } else {
  999. writeErrFrame(); // flood, not supported (yet)
  1000. }
  1001. } else if (cmd_frame[0] == CMD_SEND_LOGIN && len >= 1+PUB_KEY_SIZE) {
  1002. uint8_t* pub_key = &cmd_frame[1];
  1003. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1004. char *password = (char *) &cmd_frame[1+PUB_KEY_SIZE];
  1005. cmd_frame[len] = 0; // ensure null terminator in password
  1006. if (recipient) {
  1007. uint32_t est_timeout;
  1008. int result = sendLogin(*recipient, password, est_timeout);
  1009. if (result == MSG_SEND_FAILED) {
  1010. writeErrFrame();
  1011. } else {
  1012. pending_status = 0;
  1013. memcpy(&pending_login, recipient->id.pub_key, 4); // match this to onContactResponse()
  1014. out_frame[0] = RESP_CODE_SENT;
  1015. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  1016. memcpy(&out_frame[2], &pending_login, 4);
  1017. memcpy(&out_frame[6], &est_timeout, 4);
  1018. _serial->writeFrame(out_frame, 10);
  1019. }
  1020. } else {
  1021. writeErrFrame(); // contact not found
  1022. }
  1023. } else if (cmd_frame[0] == CMD_SEND_STATUS_REQ && len >= 1+PUB_KEY_SIZE) {
  1024. uint8_t* pub_key = &cmd_frame[1];
  1025. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1026. if (recipient) {
  1027. uint32_t est_timeout;
  1028. int result = sendStatusRequest(*recipient, est_timeout);
  1029. if (result == MSG_SEND_FAILED) {
  1030. writeErrFrame();
  1031. } else {
  1032. pending_login = 0;
  1033. memcpy(&pending_status, recipient->id.pub_key, 4); // match this to onContactResponse()
  1034. out_frame[0] = RESP_CODE_SENT;
  1035. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  1036. memcpy(&out_frame[2], &pending_status, 4);
  1037. memcpy(&out_frame[6], &est_timeout, 4);
  1038. _serial->writeFrame(out_frame, 10);
  1039. }
  1040. } else {
  1041. writeErrFrame(); // contact not found
  1042. }
  1043. } else if (cmd_frame[0] == CMD_HAS_CONNECTION && len >= 1+PUB_KEY_SIZE) {
  1044. uint8_t* pub_key = &cmd_frame[1];
  1045. if (hasConnectionTo(pub_key)) {
  1046. writeOKFrame();
  1047. } else {
  1048. writeErrFrame();
  1049. }
  1050. } else if (cmd_frame[0] == CMD_LOGOUT && len >= 1+PUB_KEY_SIZE) {
  1051. uint8_t* pub_key = &cmd_frame[1];
  1052. stopConnection(pub_key);
  1053. writeOKFrame();
  1054. } else {
  1055. writeErrFrame();
  1056. MESH_DEBUG_PRINTLN("ERROR: unknown command: %02X", cmd_frame[0]);
  1057. }
  1058. }
  1059. void loop() {
  1060. BaseChatMesh::loop();
  1061. size_t len = _serial->checkRecvFrame(cmd_frame);
  1062. if (len > 0) {
  1063. handleCmdFrame(len);
  1064. } else if (_iter_started // check if our ContactsIterator is 'running'
  1065. && !_serial->isWriteBusy() // don't spam the Serial Interface too quickly!
  1066. ) {
  1067. ContactInfo contact;
  1068. if (_iter.hasNext(this, contact)) {
  1069. if (contact.lastmod > _iter_filter_since) { // apply the 'since' filter
  1070. writeContactRespFrame(RESP_CODE_CONTACT, contact);
  1071. if (contact.lastmod > _most_recent_lastmod) {
  1072. _most_recent_lastmod = contact.lastmod; // save for the RESP_CODE_END_OF_CONTACTS frame
  1073. }
  1074. }
  1075. } else { // EOF
  1076. out_frame[0] = RESP_CODE_END_OF_CONTACTS;
  1077. memcpy(&out_frame[1], &_most_recent_lastmod, 4); // include the most recent lastmod, so app can update their 'since'
  1078. _serial->writeFrame(out_frame, 5);
  1079. _iter_started = false;
  1080. }
  1081. } else if (!_serial->isWriteBusy()) {
  1082. checkConnections();
  1083. }
  1084. #ifdef DISPLAY_CLASS
  1085. ui_task.setHasConnection(_serial->isConnected());
  1086. ui_task.loop();
  1087. #endif
  1088. }
  1089. };
  1090. #ifdef ESP32
  1091. #ifdef WIFI_SSID
  1092. #include <helpers/esp32/SerialWifiInterface.h>
  1093. SerialWifiInterface serial_interface;
  1094. #ifndef TCP_PORT
  1095. #define TCP_PORT 5000
  1096. #endif
  1097. #elif defined(BLE_PIN_CODE)
  1098. #include <helpers/esp32/SerialBLEInterface.h>
  1099. SerialBLEInterface serial_interface;
  1100. #else
  1101. #include <helpers/ArduinoSerialInterface.h>
  1102. ArduinoSerialInterface serial_interface;
  1103. #endif
  1104. #elif defined(NRF52_PLATFORM)
  1105. #ifdef BLE_PIN_CODE
  1106. #include <helpers/nrf52/SerialBLEInterface.h>
  1107. SerialBLEInterface serial_interface;
  1108. #else
  1109. #include <helpers/ArduinoSerialInterface.h>
  1110. ArduinoSerialInterface serial_interface;
  1111. #endif
  1112. #else
  1113. #error "need to define a serial interface"
  1114. #endif
  1115. #if defined(NRF52_PLATFORM)
  1116. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI);
  1117. #elif defined(LILYGO_TLORA)
  1118. SPIClass spi;
  1119. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_0, P_LORA_RESET, P_LORA_DIO_1, spi);
  1120. #elif defined(P_LORA_SCLK)
  1121. SPIClass spi;
  1122. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  1123. #else
  1124. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  1125. #endif
  1126. StdRNG fast_rng;
  1127. SimpleMeshTables tables;
  1128. MyMesh the_mesh(radio, *new WRAPPER_CLASS(radio, board), fast_rng, *new VolatileRTCClock(), tables);
  1129. void halt() {
  1130. while (1) ;
  1131. }
  1132. void setup() {
  1133. Serial.begin(115200);
  1134. board.begin();
  1135. #ifdef SX126X_DIO3_TCXO_VOLTAGE
  1136. float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
  1137. #else
  1138. float tcxo = 1.6f;
  1139. #endif
  1140. #if defined(NRF52_PLATFORM)
  1141. SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);
  1142. SPI.begin();
  1143. #elif defined(P_LORA_SCLK)
  1144. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  1145. #endif
  1146. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, 8, tcxo);
  1147. if (status != RADIOLIB_ERR_NONE) {
  1148. Serial.print("ERROR: radio init failed: ");
  1149. Serial.println(status);
  1150. halt();
  1151. }
  1152. radio.setCRC(1);
  1153. #ifdef SX126X_CURRENT_LIMIT
  1154. radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
  1155. #endif
  1156. #ifdef SX126X_DIO2_AS_RF_SWITCH
  1157. radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
  1158. #endif
  1159. #ifdef SX126X_RX_BOOSTED_GAIN
  1160. radio.setRxBoostedGainMode(SX126X_RX_BOOSTED_GAIN);
  1161. #endif
  1162. fast_rng.begin(radio.random(0x7FFFFFFF));
  1163. RadioNoiseListener trng(radio);
  1164. #if defined(NRF52_PLATFORM)
  1165. InternalFS.begin();
  1166. the_mesh.begin(InternalFS, trng);
  1167. #ifdef BLE_PIN_CODE
  1168. char dev_name[32+10];
  1169. sprintf(dev_name, "MeshCore-%s", the_mesh.getNodeName());
  1170. serial_interface.begin(dev_name, the_mesh.getBLEPin());
  1171. #else
  1172. pinMode(WB_IO2, OUTPUT);
  1173. serial_interface.begin(Serial);
  1174. #endif
  1175. the_mesh.startInterface(serial_interface);
  1176. #elif defined(ESP32)
  1177. SPIFFS.begin(true);
  1178. the_mesh.begin(SPIFFS, trng);
  1179. #ifdef WIFI_SSID
  1180. WiFi.begin(WIFI_SSID, WIFI_PWD);
  1181. serial_interface.begin(TCP_PORT);
  1182. #elif defined(BLE_PIN_CODE)
  1183. char dev_name[32+10];
  1184. sprintf(dev_name, "MeshCore-%s", the_mesh.getNodeName());
  1185. serial_interface.begin(dev_name, the_mesh.getBLEPin());
  1186. #else
  1187. serial_interface.begin(Serial);
  1188. #endif
  1189. the_mesh.startInterface(serial_interface);
  1190. #else
  1191. #error "need to define filesystem"
  1192. #endif
  1193. #ifdef DISPLAY_CLASS
  1194. display.begin();
  1195. ui_task.begin(the_mesh.getNodeName(), FIRMWARE_BUILD_DATE, the_mesh.getBLEPin());
  1196. #endif
  1197. }
  1198. void loop() {
  1199. the_mesh.loop();
  1200. }