main.cpp 45 KB

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