main.cpp 47 KB

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