main.cpp 46 KB

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