main.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744
  1. #include <Arduino.h> // needed for PlatformIO
  2. #include <Mesh.h>
  3. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  4. #include <InternalFileSystem.h>
  5. #elif defined(RP2040_PLATFORM)
  6. #include <LittleFS.h>
  7. #elif defined(ESP32)
  8. #include <SPIFFS.h>
  9. #endif
  10. #include <helpers/ArduinoHelpers.h>
  11. #include <helpers/StaticPoolPacketManager.h>
  12. #include <helpers/SimpleMeshTables.h>
  13. #include <helpers/IdentityStore.h>
  14. #include <helpers/BaseSerialInterface.h>
  15. #include "NodePrefs.h"
  16. #include <RTClib.h>
  17. #include <target.h>
  18. /* ---------------------------------- CONFIGURATION ------------------------------------- */
  19. #ifndef LORA_FREQ
  20. #define LORA_FREQ 915.0
  21. #endif
  22. #ifndef LORA_BW
  23. #define LORA_BW 250
  24. #endif
  25. #ifndef LORA_SF
  26. #define LORA_SF 10
  27. #endif
  28. #ifndef LORA_CR
  29. #define LORA_CR 5
  30. #endif
  31. #ifndef LORA_TX_POWER
  32. #define LORA_TX_POWER 20
  33. #endif
  34. #ifndef MAX_LORA_TX_POWER
  35. #define MAX_LORA_TX_POWER LORA_TX_POWER
  36. #endif
  37. #ifndef MAX_CONTACTS
  38. #define MAX_CONTACTS 100
  39. #endif
  40. #ifndef OFFLINE_QUEUE_SIZE
  41. #define OFFLINE_QUEUE_SIZE 16
  42. #endif
  43. #ifndef BLE_NAME_PREFIX
  44. #define BLE_NAME_PREFIX "MeshCore-"
  45. #endif
  46. #include <helpers/BaseChatMesh.h>
  47. #define SEND_TIMEOUT_BASE_MILLIS 500
  48. #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f
  49. #define DIRECT_SEND_PERHOP_FACTOR 6.0f
  50. #define DIRECT_SEND_PERHOP_EXTRA_MILLIS 250
  51. #define PUBLIC_GROUP_PSK "izOH6cXN6mrJ5e26oRXNcg=="
  52. #ifdef DISPLAY_CLASS // TODO: refactor this -- move to variants/*/target
  53. #include "UITask.h"
  54. #ifdef ST7735
  55. #include <helpers/ui/ST7735Display.h>
  56. #elif ST7789
  57. #include <helpers/ui/ST7789Display.h>
  58. #elif SH1106
  59. #include <helpers/ui/SH1106Display.h>
  60. #elif defined(HAS_GxEPD)
  61. #include <helpers/ui/GxEPDDisplay.h>
  62. #else
  63. #include <helpers/ui/SSD1306Display.h>
  64. #endif
  65. #if defined(HELTEC_LORA_V3) && defined(ST7735)
  66. static DISPLAY_CLASS display(&board.periph_power); // peripheral power pin is shared
  67. #else
  68. static DISPLAY_CLASS display;
  69. #endif
  70. #define HAS_UI
  71. #endif
  72. #if defined(HAS_UI)
  73. #include "UITask.h"
  74. static UITask ui_task(&board);
  75. #endif
  76. // Believe it or not, this std C function is busted on some platforms!
  77. static uint32_t _atoi(const char* sp) {
  78. uint32_t n = 0;
  79. while (*sp && *sp >= '0' && *sp <= '9') {
  80. n *= 10;
  81. n += (*sp++ - '0');
  82. }
  83. return n;
  84. }
  85. /*------------ Frame Protocol --------------*/
  86. #define FIRMWARE_VER_CODE 5
  87. #ifndef FIRMWARE_BUILD_DATE
  88. #define FIRMWARE_BUILD_DATE "17 May 2025"
  89. #endif
  90. #ifndef FIRMWARE_VERSION
  91. #define FIRMWARE_VERSION "v1.6.1"
  92. #endif
  93. #define CMD_APP_START 1
  94. #define CMD_SEND_TXT_MSG 2
  95. #define CMD_SEND_CHANNEL_TXT_MSG 3
  96. #define CMD_GET_CONTACTS 4 // with optional 'since' (for efficient sync)
  97. #define CMD_GET_DEVICE_TIME 5
  98. #define CMD_SET_DEVICE_TIME 6
  99. #define CMD_SEND_SELF_ADVERT 7
  100. #define CMD_SET_ADVERT_NAME 8
  101. #define CMD_ADD_UPDATE_CONTACT 9
  102. #define CMD_SYNC_NEXT_MESSAGE 10
  103. #define CMD_SET_RADIO_PARAMS 11
  104. #define CMD_SET_RADIO_TX_POWER 12
  105. #define CMD_RESET_PATH 13
  106. #define CMD_SET_ADVERT_LATLON 14
  107. #define CMD_REMOVE_CONTACT 15
  108. #define CMD_SHARE_CONTACT 16
  109. #define CMD_EXPORT_CONTACT 17
  110. #define CMD_IMPORT_CONTACT 18
  111. #define CMD_REBOOT 19
  112. #define CMD_GET_BATTERY_VOLTAGE 20
  113. #define CMD_SET_TUNING_PARAMS 21
  114. #define CMD_DEVICE_QEURY 22
  115. #define CMD_EXPORT_PRIVATE_KEY 23
  116. #define CMD_IMPORT_PRIVATE_KEY 24
  117. #define CMD_SEND_RAW_DATA 25
  118. #define CMD_SEND_LOGIN 26
  119. #define CMD_SEND_STATUS_REQ 27
  120. #define CMD_HAS_CONNECTION 28
  121. #define CMD_LOGOUT 29 // 'Disconnect'
  122. #define CMD_GET_CONTACT_BY_KEY 30
  123. #define CMD_GET_CHANNEL 31
  124. #define CMD_SET_CHANNEL 32
  125. #define CMD_SIGN_START 33
  126. #define CMD_SIGN_DATA 34
  127. #define CMD_SIGN_FINISH 35
  128. #define CMD_SEND_TRACE_PATH 36
  129. #define CMD_SET_DEVICE_PIN 37
  130. #define CMD_SET_OTHER_PARAMS 38
  131. #define CMD_SEND_TELEMETRY_REQ 39
  132. #define CMD_GET_CUSTOM_VARS 40
  133. #define CMD_SET_CUSTOM_VAR 41
  134. #define RESP_CODE_OK 0
  135. #define RESP_CODE_ERR 1
  136. #define RESP_CODE_CONTACTS_START 2 // first reply to CMD_GET_CONTACTS
  137. #define RESP_CODE_CONTACT 3 // multiple of these (after CMD_GET_CONTACTS)
  138. #define RESP_CODE_END_OF_CONTACTS 4 // last reply to CMD_GET_CONTACTS
  139. #define RESP_CODE_SELF_INFO 5 // reply to CMD_APP_START
  140. #define RESP_CODE_SENT 6 // reply to CMD_SEND_TXT_MSG
  141. #define RESP_CODE_CONTACT_MSG_RECV 7 // a reply to CMD_SYNC_NEXT_MESSAGE (ver < 3)
  142. #define RESP_CODE_CHANNEL_MSG_RECV 8 // a reply to CMD_SYNC_NEXT_MESSAGE (ver < 3)
  143. #define RESP_CODE_CURR_TIME 9 // a reply to CMD_GET_DEVICE_TIME
  144. #define RESP_CODE_NO_MORE_MESSAGES 10 // a reply to CMD_SYNC_NEXT_MESSAGE
  145. #define RESP_CODE_EXPORT_CONTACT 11
  146. #define RESP_CODE_BATTERY_VOLTAGE 12 // a reply to a CMD_GET_BATTERY_VOLTAGE
  147. #define RESP_CODE_DEVICE_INFO 13 // a reply to CMD_DEVICE_QEURY
  148. #define RESP_CODE_PRIVATE_KEY 14 // a reply to CMD_EXPORT_PRIVATE_KEY
  149. #define RESP_CODE_DISABLED 15
  150. #define RESP_CODE_CONTACT_MSG_RECV_V3 16 // a reply to CMD_SYNC_NEXT_MESSAGE (ver >= 3)
  151. #define RESP_CODE_CHANNEL_MSG_RECV_V3 17 // a reply to CMD_SYNC_NEXT_MESSAGE (ver >= 3)
  152. #define RESP_CODE_CHANNEL_INFO 18 // a reply to CMD_GET_CHANNEL
  153. #define RESP_CODE_SIGN_START 19
  154. #define RESP_CODE_SIGNATURE 20
  155. #define RESP_CODE_CUSTOM_VARS 21
  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. #define PUSH_CODE_LOG_RX_DATA 0x88
  166. #define PUSH_CODE_TRACE_DATA 0x89
  167. #define PUSH_CODE_NEW_ADVERT 0x8A
  168. #define PUSH_CODE_TELEMETRY_RESPONSE 0x8B
  169. #define ERR_CODE_UNSUPPORTED_CMD 1
  170. #define ERR_CODE_NOT_FOUND 2
  171. #define ERR_CODE_TABLE_FULL 3
  172. #define ERR_CODE_BAD_STATE 4
  173. #define ERR_CODE_FILE_IO_ERROR 5
  174. #define ERR_CODE_ILLEGAL_ARG 6
  175. /* -------------------------------------------------------------------------------------- */
  176. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  177. #define REQ_TYPE_KEEP_ALIVE 0x02
  178. #define REQ_TYPE_GET_TELEMETRY_DATA 0x03
  179. #define MAX_SIGN_DATA_LEN (8*1024) // 8K
  180. class MyMesh : public BaseChatMesh {
  181. FILESYSTEM* _fs;
  182. IdentityStore* _identity_store;
  183. NodePrefs _prefs;
  184. uint32_t pending_login;
  185. uint32_t pending_status;
  186. uint32_t pending_telemetry;
  187. BaseSerialInterface* _serial;
  188. ContactsIterator _iter;
  189. uint32_t _iter_filter_since;
  190. uint32_t _most_recent_lastmod;
  191. uint32_t _active_ble_pin;
  192. bool _iter_started;
  193. uint8_t app_target_ver;
  194. uint8_t* sign_data;
  195. uint32_t sign_data_len;
  196. uint8_t cmd_frame[MAX_FRAME_SIZE+1];
  197. uint8_t out_frame[MAX_FRAME_SIZE+1];
  198. CayenneLPP telemetry;
  199. struct Frame {
  200. uint8_t len;
  201. uint8_t buf[MAX_FRAME_SIZE];
  202. };
  203. int offline_queue_len;
  204. Frame offline_queue[OFFLINE_QUEUE_SIZE];
  205. struct AckTableEntry {
  206. unsigned long msg_sent;
  207. uint32_t ack;
  208. };
  209. #define EXPECTED_ACK_TABLE_SIZE 8
  210. AckTableEntry expected_ack_table[EXPECTED_ACK_TABLE_SIZE]; // circular table
  211. int next_ack_idx;
  212. void loadMainIdentity() {
  213. if (!_identity_store->load("_main", self_id)) {
  214. self_id = radio_new_identity(); // create new random identity
  215. int count = 0;
  216. while (count < 10 && (self_id.pub_key[0] == 0x00 || self_id.pub_key[0] == 0xFF)) { // reserved id hashes
  217. self_id = radio_new_identity(); count++;
  218. }
  219. saveMainIdentity(self_id);
  220. }
  221. }
  222. bool saveMainIdentity(const mesh::LocalIdentity& identity) {
  223. return _identity_store->save("_main", identity);
  224. }
  225. void loadContacts() {
  226. if (_fs->exists("/contacts3")) {
  227. #if defined(RP2040_PLATFORM)
  228. File file = _fs->open("/contacts3", "r");
  229. #else
  230. File file = _fs->open("/contacts3");
  231. #endif
  232. if (file) {
  233. bool full = false;
  234. while (!full) {
  235. ContactInfo c;
  236. uint8_t pub_key[32];
  237. uint8_t unused;
  238. bool success = (file.read(pub_key, 32) == 32);
  239. success = success && (file.read((uint8_t *) &c.name, 32) == 32);
  240. success = success && (file.read(&c.type, 1) == 1);
  241. success = success && (file.read(&c.flags, 1) == 1);
  242. success = success && (file.read(&unused, 1) == 1);
  243. success = success && (file.read((uint8_t *) &c.sync_since, 4) == 4); // was 'reserved'
  244. success = success && (file.read((uint8_t *) &c.out_path_len, 1) == 1);
  245. success = success && (file.read((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  246. success = success && (file.read(c.out_path, 64) == 64);
  247. success = success && (file.read((uint8_t *) &c.lastmod, 4) == 4);
  248. success = success && (file.read((uint8_t *) &c.gps_lat, 4) == 4);
  249. success = success && (file.read((uint8_t *) &c.gps_lon, 4) == 4);
  250. if (!success) break; // EOF
  251. c.id = mesh::Identity(pub_key);
  252. if (!addContact(c)) full = true;
  253. }
  254. file.close();
  255. }
  256. }
  257. }
  258. void saveContacts() {
  259. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  260. File file = _fs->open("/contacts3", FILE_O_WRITE);
  261. if (file) { file.seek(0); file.truncate(); }
  262. #elif defined(RP2040_PLATFORM)
  263. File file = _fs->open("/contacts3", "w");
  264. #else
  265. File file = _fs->open("/contacts3", "w", true);
  266. #endif
  267. if (file) {
  268. ContactsIterator iter;
  269. ContactInfo c;
  270. uint8_t unused = 0;
  271. while (iter.hasNext(this, c)) {
  272. bool success = (file.write(c.id.pub_key, 32) == 32);
  273. success = success && (file.write((uint8_t *) &c.name, 32) == 32);
  274. success = success && (file.write(&c.type, 1) == 1);
  275. success = success && (file.write(&c.flags, 1) == 1);
  276. success = success && (file.write(&unused, 1) == 1);
  277. success = success && (file.write((uint8_t *) &c.sync_since, 4) == 4);
  278. success = success && (file.write((uint8_t *) &c.out_path_len, 1) == 1);
  279. success = success && (file.write((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  280. success = success && (file.write(c.out_path, 64) == 64);
  281. success = success && (file.write((uint8_t *) &c.lastmod, 4) == 4);
  282. success = success && (file.write((uint8_t *) &c.gps_lat, 4) == 4);
  283. success = success && (file.write((uint8_t *) &c.gps_lon, 4) == 4);
  284. if (!success) break; // write failed
  285. }
  286. file.close();
  287. }
  288. }
  289. void loadChannels() {
  290. if (_fs->exists("/channels2")) {
  291. #if defined(RP2040_PLATFORM)
  292. File file = _fs->open("/channels2", "r");
  293. #else
  294. File file = _fs->open("/channels2");
  295. #endif
  296. if (file) {
  297. bool full = false;
  298. uint8_t channel_idx = 0;
  299. while (!full) {
  300. ChannelDetails ch;
  301. uint8_t unused[4];
  302. bool success = (file.read(unused, 4) == 4);
  303. success = success && (file.read((uint8_t *) ch.name, 32) == 32);
  304. success = success && (file.read((uint8_t *) ch.channel.secret, 32) == 32);
  305. if (!success) break; // EOF
  306. if (setChannel(channel_idx, ch)) {
  307. channel_idx++;
  308. } else {
  309. full = true;
  310. }
  311. }
  312. file.close();
  313. }
  314. }
  315. }
  316. void saveChannels() {
  317. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  318. File file = _fs->open("/channels2", FILE_O_WRITE);
  319. if (file) { file.seek(0); file.truncate(); }
  320. #elif defined(RP2040_PLATFORM)
  321. File file = _fs->open("/channels2", "w");
  322. #else
  323. File file = _fs->open("/channels2", "w", true);
  324. #endif
  325. if (file) {
  326. uint8_t channel_idx = 0;
  327. ChannelDetails ch;
  328. uint8_t unused[4];
  329. memset(unused, 0, 4);
  330. while (getChannel(channel_idx, ch)) {
  331. bool success = (file.write(unused, 4) == 4);
  332. success = success && (file.write((uint8_t *) ch.name, 32) == 32);
  333. success = success && (file.write((uint8_t *) ch.channel.secret, 32) == 32);
  334. if (!success) break; // write failed
  335. channel_idx++;
  336. }
  337. file.close();
  338. }
  339. }
  340. int getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) override {
  341. char path[64];
  342. char fname[18];
  343. if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
  344. mesh::Utils::toHex(fname, key, key_len);
  345. sprintf(path, "/bl/%s", fname);
  346. if (_fs->exists(path)) {
  347. #if defined(RP2040_PLATFORM)
  348. File f = _fs->open(path, "r");
  349. #else
  350. File f = _fs->open(path);
  351. #endif
  352. if (f) {
  353. int len = f.read(dest_buf, 255); // currently MAX 255 byte blob len supported!!
  354. f.close();
  355. return len;
  356. }
  357. }
  358. return 0; // not found
  359. }
  360. bool putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], int len) override {
  361. char path[64];
  362. char fname[18];
  363. if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
  364. mesh::Utils::toHex(fname, key, key_len);
  365. sprintf(path, "/bl/%s", fname);
  366. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  367. File f = _fs->open(path, FILE_O_WRITE);
  368. if (f) { f.seek(0); f.truncate(); }
  369. #elif defined(RP2040_PLATFORM)
  370. File f = _fs->open(path, "w");
  371. #else
  372. File f = _fs->open(path, "w", true);
  373. #endif
  374. if (f) {
  375. int n = f.write(src_buf, len);
  376. f.close();
  377. if (n == len) return true; // success!
  378. _fs->remove(path); // blob was only partially written!
  379. }
  380. return false; // error
  381. }
  382. void writeOKFrame() {
  383. uint8_t buf[1];
  384. buf[0] = RESP_CODE_OK;
  385. _serial->writeFrame(buf, 1);
  386. }
  387. void writeErrFrame(uint8_t err_code) {
  388. uint8_t buf[2];
  389. buf[0] = RESP_CODE_ERR;
  390. buf[1] = err_code;
  391. _serial->writeFrame(buf, 2);
  392. }
  393. void writeDisabledFrame() {
  394. uint8_t buf[1];
  395. buf[0] = RESP_CODE_DISABLED;
  396. _serial->writeFrame(buf, 1);
  397. }
  398. void writeContactRespFrame(uint8_t code, const ContactInfo& contact) {
  399. int i = 0;
  400. out_frame[i++] = code;
  401. memcpy(&out_frame[i], contact.id.pub_key, PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  402. out_frame[i++] = contact.type;
  403. out_frame[i++] = contact.flags;
  404. out_frame[i++] = contact.out_path_len;
  405. memcpy(&out_frame[i], contact.out_path, MAX_PATH_SIZE); i += MAX_PATH_SIZE;
  406. StrHelper::strzcpy((char *) &out_frame[i], contact.name, 32); i += 32;
  407. memcpy(&out_frame[i], &contact.last_advert_timestamp, 4); i += 4;
  408. memcpy(&out_frame[i], &contact.gps_lat, 4); i += 4;
  409. memcpy(&out_frame[i], &contact.gps_lon, 4); i += 4;
  410. memcpy(&out_frame[i], &contact.lastmod, 4); i += 4;
  411. _serial->writeFrame(out_frame, i);
  412. }
  413. void updateContactFromFrame(ContactInfo& contact, const uint8_t* frame, int len) {
  414. int i = 0;
  415. uint8_t code = frame[i++]; // eg. CMD_ADD_UPDATE_CONTACT
  416. memcpy(contact.id.pub_key, &frame[i], PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  417. contact.type = frame[i++];
  418. contact.flags = frame[i++];
  419. contact.out_path_len = frame[i++];
  420. memcpy(contact.out_path, &frame[i], MAX_PATH_SIZE); i += MAX_PATH_SIZE;
  421. memcpy(contact.name, &frame[i], 32); i += 32;
  422. memcpy(&contact.last_advert_timestamp, &frame[i], 4); i += 4;
  423. if (i + 8 >= len) { // optional fields
  424. memcpy(&contact.gps_lat, &frame[i], 4); i += 4;
  425. memcpy(&contact.gps_lon, &frame[i], 4); i += 4;
  426. }
  427. }
  428. void addToOfflineQueue(const uint8_t frame[], int len) {
  429. if (offline_queue_len >= OFFLINE_QUEUE_SIZE) {
  430. MESH_DEBUG_PRINTLN("ERROR: offline_queue is full!");
  431. } else {
  432. offline_queue[offline_queue_len].len = len;
  433. memcpy(offline_queue[offline_queue_len].buf, frame, len);
  434. offline_queue_len++;
  435. }
  436. }
  437. int getFromOfflineQueue(uint8_t frame[]) {
  438. if (offline_queue_len > 0) { // check offline queue
  439. size_t len = offline_queue[0].len; // take from top of queue
  440. memcpy(frame, offline_queue[0].buf, len);
  441. offline_queue_len--;
  442. for (int i = 0; i < offline_queue_len; i++) { // delete top item from queue
  443. offline_queue[i] = offline_queue[i + 1];
  444. }
  445. return len;
  446. }
  447. return 0; // queue is empty
  448. }
  449. void soundBuzzer() {
  450. // TODO
  451. }
  452. protected:
  453. float getAirtimeBudgetFactor() const override {
  454. return _prefs.airtime_factor;
  455. }
  456. int calcRxDelay(float score, uint32_t air_time) const override {
  457. if (_prefs.rx_delay_base <= 0.0f) return 0;
  458. return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  459. }
  460. void logRxRaw(float snr, float rssi, const uint8_t raw[], int len) override {
  461. if (_serial->isConnected() && len+3 <= MAX_FRAME_SIZE) {
  462. int i = 0;
  463. out_frame[i++] = PUSH_CODE_LOG_RX_DATA;
  464. out_frame[i++] = (int8_t)(snr * 4);
  465. out_frame[i++] = (int8_t)(rssi);
  466. memcpy(&out_frame[i], raw, len); i += len;
  467. _serial->writeFrame(out_frame, i);
  468. }
  469. }
  470. bool isAutoAddEnabled() const override {
  471. return (_prefs.manual_add_contacts & 1) == 0;
  472. }
  473. void onDiscoveredContact(ContactInfo& contact, bool is_new) override {
  474. if (_serial->isConnected()) {
  475. if (!isAutoAddEnabled() && is_new) {
  476. writeContactRespFrame(PUSH_CODE_NEW_ADVERT, contact);
  477. } else {
  478. out_frame[0] = PUSH_CODE_ADVERT;
  479. memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE);
  480. _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE);
  481. }
  482. } else {
  483. soundBuzzer();
  484. }
  485. saveContacts();
  486. }
  487. void onContactPathUpdated(const ContactInfo& contact) override {
  488. out_frame[0] = PUSH_CODE_PATH_UPDATED;
  489. memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE);
  490. _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE); // NOTE: app may not be connected
  491. saveContacts();
  492. }
  493. bool processAck(const uint8_t *data) override {
  494. // see if matches any in a table
  495. for (int i = 0; i < EXPECTED_ACK_TABLE_SIZE; i++) {
  496. if (memcmp(data, &expected_ack_table[i].ack, 4) == 0) { // got an ACK from recipient
  497. out_frame[0] = PUSH_CODE_SEND_CONFIRMED;
  498. memcpy(&out_frame[1], data, 4);
  499. uint32_t trip_time = _ms->getMillis() - expected_ack_table[i].msg_sent;
  500. memcpy(&out_frame[5], &trip_time, 4);
  501. _serial->writeFrame(out_frame, 9);
  502. // NOTE: the same ACK can be received multiple times!
  503. expected_ack_table[i].ack = 0; // clear expected hash, now that we have received ACK
  504. return true;
  505. }
  506. }
  507. return checkConnectionsAck(data);
  508. }
  509. void queueMessage(const ContactInfo& from, uint8_t txt_type, mesh::Packet* pkt, uint32_t sender_timestamp, const uint8_t* extra, int extra_len, const char *text) {
  510. int i = 0;
  511. if (app_target_ver >= 3) {
  512. out_frame[i++] = RESP_CODE_CONTACT_MSG_RECV_V3;
  513. out_frame[i++] = (int8_t)(pkt->getSNR() * 4);
  514. out_frame[i++] = 0; // reserved1
  515. out_frame[i++] = 0; // reserved2
  516. } else {
  517. out_frame[i++] = RESP_CODE_CONTACT_MSG_RECV;
  518. }
  519. memcpy(&out_frame[i], from.id.pub_key, 6); i += 6; // just 6-byte prefix
  520. uint8_t path_len = out_frame[i++] = pkt->isRouteFlood() ? pkt->path_len : 0xFF;
  521. out_frame[i++] = txt_type;
  522. memcpy(&out_frame[i], &sender_timestamp, 4); i += 4;
  523. if (extra_len > 0) {
  524. memcpy(&out_frame[i], extra, extra_len); i += extra_len;
  525. }
  526. int tlen = strlen(text); // TODO: UTF-8 ??
  527. if (i + tlen > MAX_FRAME_SIZE) {
  528. tlen = MAX_FRAME_SIZE - i;
  529. }
  530. memcpy(&out_frame[i], text, tlen); i += tlen;
  531. addToOfflineQueue(out_frame, i);
  532. if (_serial->isConnected()) {
  533. uint8_t frame[1];
  534. frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle'
  535. _serial->writeFrame(frame, 1);
  536. } else {
  537. soundBuzzer();
  538. }
  539. #ifdef HAS_UI
  540. ui_task.newMsg(path_len, from.name, text, offline_queue_len);
  541. #endif
  542. }
  543. void onMessageRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) override {
  544. markConnectionActive(from); // in case this is from a server, and we have a connection
  545. queueMessage(from, TXT_TYPE_PLAIN, pkt, sender_timestamp, NULL, 0, text);
  546. }
  547. void onCommandDataRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) override {
  548. markConnectionActive(from); // in case this is from a server, and we have a connection
  549. queueMessage(from, TXT_TYPE_CLI_DATA, pkt, sender_timestamp, NULL, 0, text);
  550. }
  551. void onSignedMessageRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) override {
  552. markConnectionActive(from);
  553. saveContacts(); // from.sync_since change needs to be persisted
  554. queueMessage(from, TXT_TYPE_SIGNED_PLAIN, pkt, sender_timestamp, sender_prefix, 4, text);
  555. }
  556. void onChannelMessageRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t timestamp, const char *text) override {
  557. int i = 0;
  558. if (app_target_ver >= 3) {
  559. out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV_V3;
  560. out_frame[i++] = (int8_t)(pkt->getSNR() * 4);
  561. out_frame[i++] = 0; // reserved1
  562. out_frame[i++] = 0; // reserved2
  563. } else {
  564. out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV;
  565. }
  566. out_frame[i++] = findChannelIdx(channel);
  567. uint8_t path_len = out_frame[i++] = pkt->isRouteFlood() ? pkt->path_len : 0xFF;
  568. out_frame[i++] = TXT_TYPE_PLAIN;
  569. memcpy(&out_frame[i], &timestamp, 4); i += 4;
  570. int tlen = strlen(text); // TODO: UTF-8 ??
  571. if (i + tlen > MAX_FRAME_SIZE) {
  572. tlen = MAX_FRAME_SIZE - i;
  573. }
  574. memcpy(&out_frame[i], text, tlen); i += tlen;
  575. addToOfflineQueue(out_frame, i);
  576. if (_serial->isConnected()) {
  577. uint8_t frame[1];
  578. frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle'
  579. _serial->writeFrame(frame, 1);
  580. } else {
  581. soundBuzzer();
  582. }
  583. #ifdef HAS_UI
  584. ui_task.newMsg(path_len, "Public", text, offline_queue_len);
  585. #endif
  586. }
  587. uint8_t onContactRequest(const ContactInfo& contact, uint32_t sender_timestamp, const uint8_t* data, uint8_t len, uint8_t* reply) override {
  588. if (data[0] == REQ_TYPE_GET_TELEMETRY_DATA) {
  589. uint8_t permissions = 0;
  590. uint8_t cp = contact.flags >> 1; // LSB used as 'favourite' bit (so only use upper bits)
  591. if (_prefs.telemetry_mode_base == TELEM_MODE_ALLOW_ALL) {
  592. permissions = TELEM_PERM_BASE;
  593. } else if (_prefs.telemetry_mode_base == TELEM_MODE_ALLOW_FLAGS) {
  594. permissions = cp & TELEM_PERM_BASE;
  595. }
  596. if (_prefs.telemetry_mode_loc == TELEM_MODE_ALLOW_ALL) {
  597. permissions |= TELEM_PERM_LOCATION;
  598. } else if (_prefs.telemetry_mode_loc == TELEM_MODE_ALLOW_FLAGS) {
  599. permissions |= cp & TELEM_PERM_LOCATION;
  600. }
  601. if (permissions & TELEM_PERM_BASE) { // only respond if base permission bit is set
  602. telemetry.reset();
  603. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  604. // query other sensors -- target specific
  605. sensors.querySensors(permissions, telemetry);
  606. memcpy(reply, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  607. uint8_t tlen = telemetry.getSize();
  608. memcpy(&reply[4], telemetry.getBuffer(), tlen);
  609. return 4 + tlen;
  610. }
  611. }
  612. return 0; // unknown
  613. }
  614. void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) override {
  615. uint32_t tag;
  616. memcpy(&tag, data, 4);
  617. if (pending_login && memcmp(&pending_login, contact.id.pub_key, 4) == 0) { // check for login response
  618. // yes, is response to pending sendLogin()
  619. pending_login = 0;
  620. int i = 0;
  621. if (memcmp(&data[4], "OK", 2) == 0) { // legacy Repeater login OK response
  622. out_frame[i++] = PUSH_CODE_LOGIN_SUCCESS;
  623. out_frame[i++] = 0; // legacy: is_admin = false
  624. } else if (data[4] == RESP_SERVER_LOGIN_OK) { // new login response
  625. uint16_t keep_alive_secs = ((uint16_t)data[5]) * 16;
  626. if (keep_alive_secs > 0) {
  627. startConnection(contact, keep_alive_secs);
  628. }
  629. out_frame[i++] = PUSH_CODE_LOGIN_SUCCESS;
  630. out_frame[i++] = data[6]; // permissions (eg. is_admin)
  631. } else {
  632. out_frame[i++] = PUSH_CODE_LOGIN_FAIL;
  633. out_frame[i++] = 0; // reserved
  634. }
  635. memcpy(&out_frame[i], contact.id.pub_key, 6); i += 6; // pub_key_prefix
  636. _serial->writeFrame(out_frame, i);
  637. } else if (len > 4 && // check for status response
  638. pending_status && memcmp(&pending_status, contact.id.pub_key, 4) == 0 // legacy matching scheme
  639. // FUTURE: tag == pending_status
  640. ) {
  641. pending_status = 0;
  642. int i = 0;
  643. out_frame[i++] = PUSH_CODE_STATUS_RESPONSE;
  644. out_frame[i++] = 0; // reserved
  645. memcpy(&out_frame[i], contact.id.pub_key, 6); i += 6; // pub_key_prefix
  646. memcpy(&out_frame[i], &data[4], len - 4); i += (len - 4);
  647. _serial->writeFrame(out_frame, i);
  648. } else if (len > 4 && tag == pending_telemetry) { // check for telemetry response
  649. pending_telemetry = 0;
  650. int i = 0;
  651. out_frame[i++] = PUSH_CODE_TELEMETRY_RESPONSE;
  652. out_frame[i++] = 0; // reserved
  653. memcpy(&out_frame[i], contact.id.pub_key, 6); i += 6; // pub_key_prefix
  654. memcpy(&out_frame[i], &data[4], len - 4); i += (len - 4);
  655. _serial->writeFrame(out_frame, i);
  656. }
  657. }
  658. void onRawDataRecv(mesh::Packet* packet) override {
  659. if (packet->payload_len + 4 > sizeof(out_frame)) {
  660. MESH_DEBUG_PRINTLN("onRawDataRecv(), payload_len too long: %d", packet->payload_len);
  661. return;
  662. }
  663. int i = 0;
  664. out_frame[i++] = PUSH_CODE_RAW_DATA;
  665. out_frame[i++] = (int8_t)(_radio->getLastSNR() * 4);
  666. out_frame[i++] = (int8_t)(_radio->getLastRSSI());
  667. out_frame[i++] = 0xFF; // reserved (possibly path_len in future)
  668. memcpy(&out_frame[i], packet->payload, packet->payload_len); i += packet->payload_len;
  669. if (_serial->isConnected()) {
  670. _serial->writeFrame(out_frame, i);
  671. } else {
  672. MESH_DEBUG_PRINTLN("onRawDataRecv(), data received while app offline");
  673. }
  674. }
  675. void onTraceRecv(mesh::Packet* packet, uint32_t tag, uint32_t auth_code, uint8_t flags, const uint8_t* path_snrs, const uint8_t* path_hashes, uint8_t path_len) override {
  676. int i = 0;
  677. out_frame[i++] = PUSH_CODE_TRACE_DATA;
  678. out_frame[i++] = 0; // reserved
  679. out_frame[i++] = path_len;
  680. out_frame[i++] = flags;
  681. memcpy(&out_frame[i], &tag, 4); i += 4;
  682. memcpy(&out_frame[i], &auth_code, 4); i += 4;
  683. memcpy(&out_frame[i], path_hashes, path_len); i += path_len;
  684. memcpy(&out_frame[i], path_snrs, path_len); i += path_len;
  685. out_frame[i++] = (int8_t)(packet->getSNR() * 4); // extra/final SNR (to this node)
  686. if (_serial->isConnected()) {
  687. _serial->writeFrame(out_frame, i);
  688. } else {
  689. MESH_DEBUG_PRINTLN("onTraceRecv(), data received while app offline");
  690. }
  691. }
  692. uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const override {
  693. return SEND_TIMEOUT_BASE_MILLIS + (FLOOD_SEND_TIMEOUT_FACTOR * pkt_airtime_millis);
  694. }
  695. uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const override {
  696. return SEND_TIMEOUT_BASE_MILLIS +
  697. ( (pkt_airtime_millis*DIRECT_SEND_PERHOP_FACTOR + DIRECT_SEND_PERHOP_EXTRA_MILLIS) * (path_len + 1));
  698. }
  699. void onSendTimeout() override {
  700. }
  701. public:
  702. MyMesh(mesh::Radio& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
  703. : BaseChatMesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables), _serial(NULL),
  704. telemetry(MAX_PACKET_PAYLOAD - 4)
  705. {
  706. _iter_started = false;
  707. offline_queue_len = 0;
  708. app_target_ver = 0;
  709. _identity_store = NULL;
  710. pending_login = pending_status = pending_telemetry = 0;
  711. next_ack_idx = 0;
  712. sign_data = NULL;
  713. // defaults
  714. memset(&_prefs, 0, sizeof(_prefs));
  715. _prefs.airtime_factor = 1.0; // one half
  716. strcpy(_prefs.node_name, "NONAME");
  717. _prefs.freq = LORA_FREQ;
  718. _prefs.sf = LORA_SF;
  719. _prefs.bw = LORA_BW;
  720. _prefs.cr = LORA_CR;
  721. _prefs.tx_power_dbm = LORA_TX_POWER;
  722. //_prefs.rx_delay_base = 10.0f; enable once new algo fixed
  723. }
  724. void loadPrefsInt(const char* filename) {
  725. #if defined(RP2040_PLATFORM)
  726. File file = _fs->open(filename, "r");
  727. #else
  728. File file = _fs->open(filename);
  729. #endif
  730. if (file) {
  731. uint8_t pad[8];
  732. file.read((uint8_t *) &_prefs.airtime_factor, sizeof(float)); // 0
  733. file.read((uint8_t *) _prefs.node_name, sizeof(_prefs.node_name)); // 4
  734. file.read(pad, 4); // 36
  735. file.read((uint8_t *) &sensors.node_lat, sizeof(sensors.node_lat)); // 40
  736. file.read((uint8_t *) &sensors.node_lon, sizeof(sensors.node_lon)); // 48
  737. file.read((uint8_t *) &_prefs.freq, sizeof(_prefs.freq)); // 56
  738. file.read((uint8_t *) &_prefs.sf, sizeof(_prefs.sf)); // 60
  739. file.read((uint8_t *) &_prefs.cr, sizeof(_prefs.cr)); // 61
  740. file.read((uint8_t *) &_prefs.reserved1, sizeof(_prefs.reserved1)); // 62
  741. file.read((uint8_t *) &_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63
  742. file.read((uint8_t *) &_prefs.bw, sizeof(_prefs.bw)); // 64
  743. file.read((uint8_t *) &_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
  744. file.read((uint8_t *) &_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69
  745. file.read((uint8_t *) &_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70
  746. file.read(pad, 1); // 71
  747. file.read((uint8_t *) &_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
  748. file.read(pad, 4); // 76
  749. file.read((uint8_t *) &_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
  750. // sanitise bad pref values
  751. _prefs.rx_delay_base = constrain(_prefs.rx_delay_base, 0, 20.0f);
  752. _prefs.airtime_factor = constrain(_prefs.airtime_factor, 0, 9.0f);
  753. _prefs.freq = constrain(_prefs.freq, 400.0f, 2500.0f);
  754. _prefs.bw = constrain(_prefs.bw, 62.5f, 500.0f);
  755. _prefs.sf = constrain(_prefs.sf, 7, 12);
  756. _prefs.cr = constrain(_prefs.cr, 5, 8);
  757. _prefs.tx_power_dbm = constrain(_prefs.tx_power_dbm, 1, MAX_LORA_TX_POWER);
  758. file.close();
  759. }
  760. }
  761. void begin(FILESYSTEM& fs, bool has_display) {
  762. _fs = &fs;
  763. BaseChatMesh::begin();
  764. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  765. _identity_store = new IdentityStore(fs, "");
  766. #elif defined(RP2040_PLATFORM)
  767. _identity_store = new IdentityStore(fs, "/identity");
  768. _identity_store->begin();
  769. #else
  770. _identity_store = new IdentityStore(fs, "/identity");
  771. #endif
  772. loadMainIdentity();
  773. // use hex of first 4 bytes of identity public key as default node name
  774. char pub_key_hex[10];
  775. mesh::Utils::toHex(pub_key_hex, self_id.pub_key, 4);
  776. strcpy(_prefs.node_name, pub_key_hex);
  777. // load persisted prefs
  778. if (_fs->exists("/new_prefs")) {
  779. loadPrefsInt("/new_prefs"); // new filename
  780. } else if (_fs->exists("/node_prefs")) {
  781. loadPrefsInt("/node_prefs");
  782. savePrefs(); // save to new filename
  783. _fs->remove("/node_prefs"); // remove old
  784. }
  785. #ifdef BLE_PIN_CODE
  786. if (_prefs.ble_pin == 0) {
  787. #ifdef HAS_UI
  788. if (has_display) {
  789. StdRNG rng;
  790. _active_ble_pin = rng.nextInt(100000, 999999); // random pin each session
  791. } else {
  792. _active_ble_pin = BLE_PIN_CODE; // otherwise static pin
  793. }
  794. #else
  795. _active_ble_pin = BLE_PIN_CODE; // otherwise static pin
  796. #endif
  797. } else {
  798. _active_ble_pin = _prefs.ble_pin;
  799. }
  800. #else
  801. _active_ble_pin = 0;
  802. #endif
  803. // init 'blob store' support
  804. _fs->mkdir("/bl");
  805. loadContacts();
  806. addChannel("Public", PUBLIC_GROUP_PSK); // pre-configure Andy's public channel
  807. loadChannels();
  808. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  809. radio_set_tx_power(_prefs.tx_power_dbm);
  810. }
  811. const char* getNodeName() { return _prefs.node_name; }
  812. NodePrefs* getNodePrefs() {
  813. return &_prefs;
  814. }
  815. uint32_t getBLEPin() { return _active_ble_pin; }
  816. void startInterface(BaseSerialInterface& serial) {
  817. _serial = &serial;
  818. serial.enable();
  819. }
  820. void savePrefs() {
  821. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  822. File file = _fs->open("/new_prefs", FILE_O_WRITE);
  823. if (file) { file.seek(0); file.truncate(); }
  824. #elif defined(RP2040_PLATFORM)
  825. File file = _fs->open("/new_prefs", "w");
  826. #else
  827. File file = _fs->open("/new_prefs", "w", true);
  828. #endif
  829. if (file) {
  830. uint8_t pad[8];
  831. memset(pad, 0, sizeof(pad));
  832. file.write((uint8_t *) &_prefs.airtime_factor, sizeof(float)); // 0
  833. file.write((uint8_t *) _prefs.node_name, sizeof(_prefs.node_name)); // 4
  834. file.write(pad, 4); // 36
  835. file.write((uint8_t *) &sensors.node_lat, sizeof(sensors.node_lat)); // 40
  836. file.write((uint8_t *) &sensors.node_lon, sizeof(sensors.node_lon)); // 48
  837. file.write((uint8_t *) &_prefs.freq, sizeof(_prefs.freq)); // 56
  838. file.write((uint8_t *) &_prefs.sf, sizeof(_prefs.sf)); // 60
  839. file.write((uint8_t *) &_prefs.cr, sizeof(_prefs.cr)); // 61
  840. file.write((uint8_t *) &_prefs.reserved1, sizeof(_prefs.reserved1)); // 62
  841. file.write((uint8_t *) &_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63
  842. file.write((uint8_t *) &_prefs.bw, sizeof(_prefs.bw)); // 64
  843. file.write((uint8_t *) &_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
  844. file.write((uint8_t *) &_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69
  845. file.write((uint8_t *) &_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70
  846. file.write(pad, 1); // 71
  847. file.write((uint8_t *) &_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
  848. file.write(pad, 4); // 76
  849. file.write((uint8_t *) &_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
  850. file.close();
  851. }
  852. }
  853. void handleCmdFrame(size_t len) {
  854. if (cmd_frame[0] == CMD_DEVICE_QEURY && len >= 2) { // sent when app establishes connection
  855. app_target_ver = cmd_frame[1]; // which version of protocol does app understand
  856. int i = 0;
  857. out_frame[i++] = RESP_CODE_DEVICE_INFO;
  858. out_frame[i++] = FIRMWARE_VER_CODE;
  859. out_frame[i++] = MAX_CONTACTS / 2; // v3+
  860. out_frame[i++] = MAX_GROUP_CHANNELS; // v3+
  861. memcpy(&out_frame[i], &_prefs.ble_pin, 4); i += 4;
  862. memset(&out_frame[i], 0, 12);
  863. strcpy((char *) &out_frame[i], FIRMWARE_BUILD_DATE); i += 12;
  864. StrHelper::strzcpy((char *) &out_frame[i], board.getManufacturerName(), 40); i += 40;
  865. StrHelper::strzcpy((char *) &out_frame[i], FIRMWARE_VERSION, 20); i += 20;
  866. _serial->writeFrame(out_frame, i);
  867. } else if (cmd_frame[0] == CMD_APP_START && len >= 8) { // sent when app establishes connection, respond with node ID
  868. // cmd_frame[1..7] reserved future
  869. char* app_name = (char *) &cmd_frame[8];
  870. cmd_frame[len] = 0; // make app_name null terminated
  871. MESH_DEBUG_PRINTLN("App %s connected", app_name);
  872. _iter_started = false; // stop any left-over ContactsIterator
  873. int i = 0;
  874. out_frame[i++] = RESP_CODE_SELF_INFO;
  875. out_frame[i++] = ADV_TYPE_CHAT; // what this node Advert identifies as (maybe node's pronouns too?? :-)
  876. out_frame[i++] = _prefs.tx_power_dbm;
  877. out_frame[i++] = MAX_LORA_TX_POWER;
  878. memcpy(&out_frame[i], self_id.pub_key, PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  879. int32_t lat, lon;
  880. lat = (sensors.node_lat * 1000000.0);
  881. lon = (sensors.node_lon * 1000000.0);
  882. memcpy(&out_frame[i], &lat, 4); i += 4;
  883. memcpy(&out_frame[i], &lon, 4); i += 4;
  884. out_frame[i++] = 0; // reserved
  885. out_frame[i++] = 0; // reserved
  886. out_frame[i++] = (_prefs.telemetry_mode_loc << 2) | (_prefs.telemetry_mode_base); // v5+
  887. out_frame[i++] = _prefs.manual_add_contacts;
  888. uint32_t freq = _prefs.freq * 1000;
  889. memcpy(&out_frame[i], &freq, 4); i += 4;
  890. uint32_t bw = _prefs.bw*1000;
  891. memcpy(&out_frame[i], &bw, 4); i += 4;
  892. out_frame[i++] = _prefs.sf;
  893. out_frame[i++] = _prefs.cr;
  894. int tlen = strlen(_prefs.node_name); // revisit: UTF_8 ??
  895. memcpy(&out_frame[i], _prefs.node_name, tlen); i += tlen;
  896. _serial->writeFrame(out_frame, i);
  897. } else if (cmd_frame[0] == CMD_SEND_TXT_MSG && len >= 14) {
  898. int i = 1;
  899. uint8_t txt_type = cmd_frame[i++];
  900. uint8_t attempt = cmd_frame[i++];
  901. uint32_t msg_timestamp;
  902. memcpy(&msg_timestamp, &cmd_frame[i], 4); i += 4;
  903. uint8_t* pub_key_prefix = &cmd_frame[i]; i += 6;
  904. ContactInfo* recipient = lookupContactByPubKey(pub_key_prefix, 6);
  905. if (recipient && (txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_CLI_DATA)) {
  906. char *text = (char *) &cmd_frame[i];
  907. int tlen = len - i;
  908. uint32_t est_timeout;
  909. text[tlen] = 0; // ensure null
  910. int result;
  911. uint32_t expected_ack;
  912. if (txt_type == TXT_TYPE_CLI_DATA) {
  913. result = sendCommandData(*recipient, msg_timestamp, attempt, text, est_timeout);
  914. expected_ack = 0; // no Ack expected
  915. } else {
  916. result = sendMessage(*recipient, msg_timestamp, attempt, text, expected_ack, est_timeout);
  917. }
  918. // TODO: add expected ACK to table
  919. if (result == MSG_SEND_FAILED) {
  920. writeErrFrame(ERR_CODE_TABLE_FULL);
  921. } else {
  922. if (expected_ack) {
  923. expected_ack_table[next_ack_idx].msg_sent = _ms->getMillis(); // add to circular table
  924. expected_ack_table[next_ack_idx].ack = expected_ack;
  925. next_ack_idx = (next_ack_idx + 1) % EXPECTED_ACK_TABLE_SIZE;
  926. }
  927. out_frame[0] = RESP_CODE_SENT;
  928. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  929. memcpy(&out_frame[2], &expected_ack, 4);
  930. memcpy(&out_frame[6], &est_timeout, 4);
  931. _serial->writeFrame(out_frame, 10);
  932. }
  933. } else {
  934. writeErrFrame(recipient == NULL ? ERR_CODE_NOT_FOUND : ERR_CODE_UNSUPPORTED_CMD); // unknown recipient, or unsuported TXT_TYPE_*
  935. }
  936. } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel msg
  937. int i = 1;
  938. uint8_t txt_type = cmd_frame[i++]; // should be TXT_TYPE_PLAIN
  939. uint8_t channel_idx = cmd_frame[i++];
  940. uint32_t msg_timestamp;
  941. memcpy(&msg_timestamp, &cmd_frame[i], 4); i += 4;
  942. const char *text = (char *) &cmd_frame[i];
  943. if (txt_type != TXT_TYPE_PLAIN) {
  944. writeErrFrame(ERR_CODE_UNSUPPORTED_CMD);
  945. } else {
  946. ChannelDetails channel;
  947. bool success = getChannel(channel_idx, channel);
  948. if (success && sendGroupMessage(msg_timestamp, channel.channel, _prefs.node_name, text, len - i)) {
  949. writeOKFrame();
  950. } else {
  951. writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx
  952. }
  953. }
  954. } else if (cmd_frame[0] == CMD_GET_CONTACTS) { // get Contact list
  955. if (_iter_started) {
  956. writeErrFrame(ERR_CODE_BAD_STATE); // iterator is currently busy
  957. } else {
  958. if (len >= 5) { // has optional 'since' param
  959. memcpy(&_iter_filter_since, &cmd_frame[1], 4);
  960. } else {
  961. _iter_filter_since = 0;
  962. }
  963. uint8_t reply[5];
  964. reply[0] = RESP_CODE_CONTACTS_START;
  965. uint32_t count = getNumContacts(); // total, NOT filtered count
  966. memcpy(&reply[1], &count, 4);
  967. _serial->writeFrame(reply, 5);
  968. // start iterator
  969. _iter = startContactsIterator();
  970. _iter_started = true;
  971. _most_recent_lastmod = 0;
  972. }
  973. } else if (cmd_frame[0] == CMD_SET_ADVERT_NAME && len >= 2) {
  974. int nlen = len - 1;
  975. if (nlen > sizeof(_prefs.node_name)-1) nlen = sizeof(_prefs.node_name)-1; // max len
  976. memcpy(_prefs.node_name, &cmd_frame[1], nlen);
  977. _prefs.node_name[nlen] = 0; // null terminator
  978. savePrefs();
  979. writeOKFrame();
  980. } else if (cmd_frame[0] == CMD_SET_ADVERT_LATLON && len >= 9) {
  981. int32_t lat, lon, alt = 0;
  982. memcpy(&lat, &cmd_frame[1], 4);
  983. memcpy(&lon, &cmd_frame[5], 4);
  984. if (len >= 13) {
  985. memcpy(&alt, &cmd_frame[9], 4); // for FUTURE support
  986. }
  987. if (lat <= 90*1E6 && lat >= -90*1E6 && lon <= 180*1E6 && lon >= -180*1E6) {
  988. sensors.node_lat = ((double)lat) / 1000000.0;
  989. sensors.node_lon = ((double)lon) / 1000000.0;
  990. savePrefs();
  991. writeOKFrame();
  992. } else {
  993. writeErrFrame(ERR_CODE_ILLEGAL_ARG); // invalid geo coordinate
  994. }
  995. } else if (cmd_frame[0] == CMD_GET_DEVICE_TIME) {
  996. uint8_t reply[5];
  997. reply[0] = RESP_CODE_CURR_TIME;
  998. uint32_t now = getRTCClock()->getCurrentTime();
  999. memcpy(&reply[1], &now, 4);
  1000. _serial->writeFrame(reply, 5);
  1001. } else if (cmd_frame[0] == CMD_SET_DEVICE_TIME && len >= 5) {
  1002. uint32_t secs;
  1003. memcpy(&secs, &cmd_frame[1], 4);
  1004. uint32_t curr = getRTCClock()->getCurrentTime();
  1005. if (secs >= curr) {
  1006. getRTCClock()->setCurrentTime(secs);
  1007. writeOKFrame();
  1008. } else {
  1009. writeErrFrame(ERR_CODE_ILLEGAL_ARG);
  1010. }
  1011. } else if (cmd_frame[0] == CMD_SEND_SELF_ADVERT) {
  1012. auto pkt = createSelfAdvert(_prefs.node_name, sensors.node_lat, sensors.node_lon);
  1013. if (pkt) {
  1014. if (len >= 2 && cmd_frame[1] == 1) { // optional param (1 = flood, 0 = zero hop)
  1015. sendFlood(pkt);
  1016. } else {
  1017. sendZeroHop(pkt);
  1018. }
  1019. writeOKFrame();
  1020. } else {
  1021. writeErrFrame(ERR_CODE_TABLE_FULL);
  1022. }
  1023. } else if (cmd_frame[0] == CMD_RESET_PATH && len >= 1+32) {
  1024. uint8_t* pub_key = &cmd_frame[1];
  1025. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1026. if (recipient) {
  1027. recipient->out_path_len = -1;
  1028. //recipient->lastmod = ?? shouldn't be needed, app already has this version of contact
  1029. saveContacts();
  1030. writeOKFrame();
  1031. } else {
  1032. writeErrFrame(ERR_CODE_NOT_FOUND); // unknown contact
  1033. }
  1034. } else if (cmd_frame[0] == CMD_ADD_UPDATE_CONTACT && len >= 1+32+2+1) {
  1035. uint8_t* pub_key = &cmd_frame[1];
  1036. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1037. if (recipient) {
  1038. updateContactFromFrame(*recipient, cmd_frame, len);
  1039. //recipient->lastmod = ?? shouldn't be needed, app already has this version of contact
  1040. saveContacts();
  1041. writeOKFrame();
  1042. } else {
  1043. ContactInfo contact;
  1044. updateContactFromFrame(contact, cmd_frame, len);
  1045. contact.lastmod = getRTCClock()->getCurrentTime();
  1046. contact.sync_since = 0;
  1047. if (addContact(contact)) {
  1048. saveContacts();
  1049. writeOKFrame();
  1050. } else {
  1051. writeErrFrame(ERR_CODE_TABLE_FULL);
  1052. }
  1053. }
  1054. } else if (cmd_frame[0] == CMD_REMOVE_CONTACT) {
  1055. uint8_t* pub_key = &cmd_frame[1];
  1056. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1057. if (recipient && removeContact(*recipient)) {
  1058. saveContacts();
  1059. writeOKFrame();
  1060. } else {
  1061. writeErrFrame(ERR_CODE_NOT_FOUND); // not found, or unable to remove
  1062. }
  1063. } else if (cmd_frame[0] == CMD_SHARE_CONTACT) {
  1064. uint8_t* pub_key = &cmd_frame[1];
  1065. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1066. if (recipient) {
  1067. if (shareContactZeroHop(*recipient)) {
  1068. writeOKFrame();
  1069. } else {
  1070. writeErrFrame(ERR_CODE_TABLE_FULL); // unable to send
  1071. }
  1072. } else {
  1073. writeErrFrame(ERR_CODE_NOT_FOUND);
  1074. }
  1075. } else if (cmd_frame[0] == CMD_GET_CONTACT_BY_KEY) {
  1076. uint8_t* pub_key = &cmd_frame[1];
  1077. ContactInfo* contact = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1078. if (contact) {
  1079. writeContactRespFrame(RESP_CODE_CONTACT, *contact);
  1080. } else {
  1081. writeErrFrame(ERR_CODE_NOT_FOUND); // not found
  1082. }
  1083. } else if (cmd_frame[0] == CMD_EXPORT_CONTACT) {
  1084. if (len < 1 + PUB_KEY_SIZE) {
  1085. // export SELF
  1086. auto pkt = createSelfAdvert(_prefs.node_name, sensors.node_lat, sensors.node_lon);
  1087. if (pkt) {
  1088. pkt->header |= ROUTE_TYPE_FLOOD; // would normally be sent in this mode
  1089. out_frame[0] = RESP_CODE_EXPORT_CONTACT;
  1090. uint8_t out_len = pkt->writeTo(&out_frame[1]);
  1091. releasePacket(pkt); // undo the obtainNewPacket()
  1092. _serial->writeFrame(out_frame, out_len + 1);
  1093. } else {
  1094. writeErrFrame(ERR_CODE_TABLE_FULL); // Error
  1095. }
  1096. } else {
  1097. uint8_t* pub_key = &cmd_frame[1];
  1098. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1099. uint8_t out_len;
  1100. if (recipient && (out_len = exportContact(*recipient, &out_frame[1])) > 0) {
  1101. out_frame[0] = RESP_CODE_EXPORT_CONTACT;
  1102. _serial->writeFrame(out_frame, out_len + 1);
  1103. } else {
  1104. writeErrFrame(ERR_CODE_NOT_FOUND); // not found
  1105. }
  1106. }
  1107. } else if (cmd_frame[0] == CMD_IMPORT_CONTACT && len > 2+32+64) {
  1108. if (importContact(&cmd_frame[1], len - 1)) {
  1109. writeOKFrame();
  1110. } else {
  1111. writeErrFrame(ERR_CODE_ILLEGAL_ARG);
  1112. }
  1113. } else if (cmd_frame[0] == CMD_SYNC_NEXT_MESSAGE) {
  1114. int out_len;
  1115. if ((out_len = getFromOfflineQueue(out_frame)) > 0) {
  1116. _serial->writeFrame(out_frame, out_len);
  1117. #ifdef HAS_UI
  1118. ui_task.msgRead(offline_queue_len);
  1119. #endif
  1120. } else {
  1121. out_frame[0] = RESP_CODE_NO_MORE_MESSAGES;
  1122. _serial->writeFrame(out_frame, 1);
  1123. }
  1124. } else if (cmd_frame[0] == CMD_SET_RADIO_PARAMS) {
  1125. int i = 1;
  1126. uint32_t freq;
  1127. memcpy(&freq, &cmd_frame[i], 4); i += 4;
  1128. uint32_t bw;
  1129. memcpy(&bw, &cmd_frame[i], 4); i += 4;
  1130. uint8_t sf = cmd_frame[i++];
  1131. uint8_t cr = cmd_frame[i++];
  1132. if (freq >= 300000 && freq <= 2500000 && sf >= 7 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7000 && bw <= 500000) {
  1133. _prefs.sf = sf;
  1134. _prefs.cr = cr;
  1135. _prefs.freq = (float)freq / 1000.0;
  1136. _prefs.bw = (float)bw / 1000.0;
  1137. savePrefs();
  1138. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  1139. MESH_DEBUG_PRINTLN("OK: CMD_SET_RADIO_PARAMS: f=%d, bw=%d, sf=%d, cr=%d", freq, bw, (uint32_t)sf, (uint32_t)cr);
  1140. writeOKFrame();
  1141. } else {
  1142. MESH_DEBUG_PRINTLN("Error: CMD_SET_RADIO_PARAMS: f=%d, bw=%d, sf=%d, cr=%d", freq, bw, (uint32_t)sf, (uint32_t)cr);
  1143. writeErrFrame(ERR_CODE_ILLEGAL_ARG);
  1144. }
  1145. } else if (cmd_frame[0] == CMD_SET_RADIO_TX_POWER) {
  1146. if (cmd_frame[1] > MAX_LORA_TX_POWER) {
  1147. writeErrFrame(ERR_CODE_ILLEGAL_ARG);
  1148. } else {
  1149. _prefs.tx_power_dbm = cmd_frame[1];
  1150. savePrefs();
  1151. radio_set_tx_power(_prefs.tx_power_dbm);
  1152. writeOKFrame();
  1153. }
  1154. } else if (cmd_frame[0] == CMD_SET_TUNING_PARAMS) {
  1155. int i = 1;
  1156. uint32_t rx, af;
  1157. memcpy(&rx, &cmd_frame[i], 4); i += 4;
  1158. memcpy(&af, &cmd_frame[i], 4); i += 4;
  1159. _prefs.rx_delay_base = ((float)rx) / 1000.0f;
  1160. _prefs.airtime_factor = ((float)af) / 1000.0f;
  1161. savePrefs();
  1162. writeOKFrame();
  1163. } else if (cmd_frame[0] == CMD_SET_OTHER_PARAMS) {
  1164. _prefs.manual_add_contacts = cmd_frame[1];
  1165. if (len >= 3) {
  1166. _prefs.telemetry_mode_base = cmd_frame[2] & 0x03; // v5+
  1167. _prefs.telemetry_mode_loc = (cmd_frame[2] >> 2) & 0x03;
  1168. }
  1169. savePrefs();
  1170. writeOKFrame();
  1171. } else if (cmd_frame[0] == CMD_REBOOT && memcmp(&cmd_frame[1], "reboot", 6) == 0) {
  1172. board.reboot();
  1173. } else if (cmd_frame[0] == CMD_GET_BATTERY_VOLTAGE) {
  1174. uint8_t reply[3];
  1175. reply[0] = RESP_CODE_BATTERY_VOLTAGE;
  1176. uint16_t battery_millivolts = board.getBattMilliVolts();
  1177. memcpy(&reply[1], &battery_millivolts, 2);
  1178. _serial->writeFrame(reply, 3);
  1179. } else if (cmd_frame[0] == CMD_EXPORT_PRIVATE_KEY) {
  1180. #if ENABLE_PRIVATE_KEY_EXPORT
  1181. uint8_t reply[65];
  1182. reply[0] = RESP_CODE_PRIVATE_KEY;
  1183. self_id.writeTo(&reply[1], 64);
  1184. _serial->writeFrame(reply, 65);
  1185. #else
  1186. writeDisabledFrame();
  1187. #endif
  1188. } else if (cmd_frame[0] == CMD_IMPORT_PRIVATE_KEY && len >= 65) {
  1189. #if ENABLE_PRIVATE_KEY_IMPORT
  1190. mesh::LocalIdentity identity;
  1191. identity.readFrom(&cmd_frame[1], 64);
  1192. if (saveMainIdentity(identity)) {
  1193. self_id = identity;
  1194. writeOKFrame();
  1195. } else {
  1196. writeErrFrame(ERR_CODE_FILE_IO_ERROR);
  1197. }
  1198. #else
  1199. writeDisabledFrame();
  1200. #endif
  1201. } else if (cmd_frame[0] == CMD_SEND_RAW_DATA && len >= 6) {
  1202. int i = 1;
  1203. int8_t path_len = cmd_frame[i++];
  1204. if (path_len >= 0 && i + path_len + 4 <= len) { // minimum 4 byte payload
  1205. uint8_t* path = &cmd_frame[i]; i += path_len;
  1206. auto pkt = createRawData(&cmd_frame[i], len - i);
  1207. if (pkt) {
  1208. sendDirect(pkt, path, path_len);
  1209. writeOKFrame();
  1210. } else {
  1211. writeErrFrame(ERR_CODE_TABLE_FULL);
  1212. }
  1213. } else {
  1214. writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); // flood, not supported (yet)
  1215. }
  1216. } else if (cmd_frame[0] == CMD_SEND_LOGIN && len >= 1+PUB_KEY_SIZE) {
  1217. uint8_t* pub_key = &cmd_frame[1];
  1218. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1219. char *password = (char *) &cmd_frame[1+PUB_KEY_SIZE];
  1220. cmd_frame[len] = 0; // ensure null terminator in password
  1221. if (recipient) {
  1222. uint32_t est_timeout;
  1223. int result = sendLogin(*recipient, password, est_timeout);
  1224. if (result == MSG_SEND_FAILED) {
  1225. writeErrFrame(ERR_CODE_TABLE_FULL);
  1226. } else {
  1227. pending_telemetry = pending_status = 0;
  1228. memcpy(&pending_login, recipient->id.pub_key, 4); // match this to onContactResponse()
  1229. out_frame[0] = RESP_CODE_SENT;
  1230. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  1231. memcpy(&out_frame[2], &pending_login, 4);
  1232. memcpy(&out_frame[6], &est_timeout, 4);
  1233. _serial->writeFrame(out_frame, 10);
  1234. }
  1235. } else {
  1236. writeErrFrame(ERR_CODE_NOT_FOUND); // contact not found
  1237. }
  1238. } else if (cmd_frame[0] == CMD_SEND_STATUS_REQ && len >= 1+PUB_KEY_SIZE) {
  1239. uint8_t* pub_key = &cmd_frame[1];
  1240. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1241. if (recipient) {
  1242. uint32_t tag, est_timeout;
  1243. int result = sendRequest(*recipient, REQ_TYPE_GET_STATUS, tag, est_timeout);
  1244. if (result == MSG_SEND_FAILED) {
  1245. writeErrFrame(ERR_CODE_TABLE_FULL);
  1246. } else {
  1247. pending_telemetry = pending_login = 0;
  1248. // FUTURE: pending_status = tag; // match this in onContactResponse()
  1249. memcpy(&pending_status, recipient->id.pub_key, 4); // legacy matching scheme
  1250. out_frame[0] = RESP_CODE_SENT;
  1251. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  1252. memcpy(&out_frame[2], &tag, 4);
  1253. memcpy(&out_frame[6], &est_timeout, 4);
  1254. _serial->writeFrame(out_frame, 10);
  1255. }
  1256. } else {
  1257. writeErrFrame(ERR_CODE_NOT_FOUND); // contact not found
  1258. }
  1259. } else if (cmd_frame[0] == CMD_SEND_TELEMETRY_REQ && len >= 4+PUB_KEY_SIZE) {
  1260. uint8_t* pub_key = &cmd_frame[4];
  1261. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  1262. if (recipient) {
  1263. uint32_t tag, est_timeout;
  1264. int result = sendRequest(*recipient, REQ_TYPE_GET_TELEMETRY_DATA, tag, est_timeout);
  1265. if (result == MSG_SEND_FAILED) {
  1266. writeErrFrame(ERR_CODE_TABLE_FULL);
  1267. } else {
  1268. pending_status = pending_login = 0;
  1269. pending_telemetry = tag; // match this in onContactResponse()
  1270. out_frame[0] = RESP_CODE_SENT;
  1271. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  1272. memcpy(&out_frame[2], &tag, 4);
  1273. memcpy(&out_frame[6], &est_timeout, 4);
  1274. _serial->writeFrame(out_frame, 10);
  1275. }
  1276. } else {
  1277. writeErrFrame(ERR_CODE_NOT_FOUND); // contact not found
  1278. }
  1279. } else if (cmd_frame[0] == CMD_HAS_CONNECTION && len >= 1+PUB_KEY_SIZE) {
  1280. uint8_t* pub_key = &cmd_frame[1];
  1281. if (hasConnectionTo(pub_key)) {
  1282. writeOKFrame();
  1283. } else {
  1284. writeErrFrame(ERR_CODE_NOT_FOUND);
  1285. }
  1286. } else if (cmd_frame[0] == CMD_LOGOUT && len >= 1+PUB_KEY_SIZE) {
  1287. uint8_t* pub_key = &cmd_frame[1];
  1288. stopConnection(pub_key);
  1289. writeOKFrame();
  1290. } else if (cmd_frame[0] == CMD_GET_CHANNEL && len >= 2) {
  1291. uint8_t channel_idx = cmd_frame[1];
  1292. ChannelDetails channel;
  1293. if (getChannel(channel_idx, channel)) {
  1294. int i = 0;
  1295. out_frame[i++] = RESP_CODE_CHANNEL_INFO;
  1296. out_frame[i++] = channel_idx;
  1297. strcpy((char *)&out_frame[i], channel.name); i += 32;
  1298. memcpy(&out_frame[i], channel.channel.secret, 16); i += 16; // NOTE: only 128-bit supported
  1299. _serial->writeFrame(out_frame, i);
  1300. } else {
  1301. writeErrFrame(ERR_CODE_NOT_FOUND);
  1302. }
  1303. } else if (cmd_frame[0] == CMD_SET_CHANNEL && len >= 2+32+32) {
  1304. writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); // not supported (yet)
  1305. } else if (cmd_frame[0] == CMD_SET_CHANNEL && len >= 2+32+16) {
  1306. uint8_t channel_idx = cmd_frame[1];
  1307. ChannelDetails channel;
  1308. StrHelper::strncpy(channel.name, (char *) &cmd_frame[2], 32);
  1309. memset(channel.channel.secret, 0, sizeof(channel.channel.secret));
  1310. memcpy(channel.channel.secret, &cmd_frame[2+32], 16); // NOTE: only 128-bit supported
  1311. if (setChannel(channel_idx, channel)) {
  1312. saveChannels();
  1313. writeOKFrame();
  1314. } else {
  1315. writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx
  1316. }
  1317. } else if (cmd_frame[0] == CMD_SIGN_START) {
  1318. out_frame[0] = RESP_CODE_SIGN_START;
  1319. out_frame[1] = 0; // reserved
  1320. uint32_t len = MAX_SIGN_DATA_LEN;
  1321. memcpy(&out_frame[2], &len, 4);
  1322. _serial->writeFrame(out_frame, 6);
  1323. if (sign_data) {
  1324. free(sign_data);
  1325. }
  1326. sign_data = (uint8_t *) malloc(MAX_SIGN_DATA_LEN);
  1327. sign_data_len = 0;
  1328. } else if (cmd_frame[0] == CMD_SIGN_DATA && len > 1) {
  1329. if (sign_data == NULL || sign_data_len + (len - 1) > MAX_SIGN_DATA_LEN) {
  1330. writeErrFrame(sign_data == NULL ? ERR_CODE_BAD_STATE : ERR_CODE_TABLE_FULL); // error: too long
  1331. } else {
  1332. memcpy(&sign_data[sign_data_len], &cmd_frame[1], len - 1);
  1333. sign_data_len += (len - 1);
  1334. writeOKFrame();
  1335. }
  1336. } else if (cmd_frame[0] == CMD_SIGN_FINISH) {
  1337. if (sign_data) {
  1338. self_id.sign(&out_frame[1], sign_data, sign_data_len);
  1339. free(sign_data); // don't need sign_data now
  1340. sign_data = NULL;
  1341. out_frame[0] = RESP_CODE_SIGNATURE;
  1342. _serial->writeFrame(out_frame, 1 + SIGNATURE_SIZE);
  1343. } else {
  1344. writeErrFrame(ERR_CODE_BAD_STATE);
  1345. }
  1346. } else if (cmd_frame[0] == CMD_SEND_TRACE_PATH && len > 10 && len - 10 < MAX_PATH_SIZE) {
  1347. uint32_t tag, auth;
  1348. memcpy(&tag, &cmd_frame[1], 4);
  1349. memcpy(&auth, &cmd_frame[5], 4);
  1350. auto pkt = createTrace(tag, auth, cmd_frame[9]);
  1351. if (pkt) {
  1352. uint8_t path_len = len - 10;
  1353. sendDirect(pkt, &cmd_frame[10], path_len);
  1354. uint32_t t = _radio->getEstAirtimeFor(pkt->payload_len + pkt->path_len + 2);
  1355. uint32_t est_timeout = calcDirectTimeoutMillisFor(t, path_len);
  1356. out_frame[0] = RESP_CODE_SENT;
  1357. out_frame[1] = 0;
  1358. memcpy(&out_frame[2], &tag, 4);
  1359. memcpy(&out_frame[6], &est_timeout, 4);
  1360. _serial->writeFrame(out_frame, 10);
  1361. } else {
  1362. writeErrFrame(ERR_CODE_TABLE_FULL);
  1363. }
  1364. } else if (cmd_frame[0] == CMD_SET_DEVICE_PIN && len >= 5) {
  1365. // get pin from command frame
  1366. uint32_t pin;
  1367. memcpy(&pin, &cmd_frame[1], 4);
  1368. // ensure pin is zero, or a valid 6 digit pin
  1369. if(pin == 0 || (pin >= 100000 && pin <= 999999)){
  1370. _prefs.ble_pin = pin;
  1371. savePrefs();
  1372. writeOKFrame();
  1373. } else {
  1374. writeErrFrame(ERR_CODE_ILLEGAL_ARG);
  1375. }
  1376. } else if (cmd_frame[0] == CMD_GET_CUSTOM_VARS) {
  1377. out_frame[0] = RESP_CODE_CUSTOM_VARS;
  1378. char* dp = (char *) &out_frame[1];
  1379. for (int i = 0; i < sensors.getNumSettings() && dp - (char *) &out_frame[1] < 140; i++) {
  1380. if (i > 0) { *dp++ = ','; }
  1381. strcpy(dp, sensors.getSettingName(i)); dp = strchr(dp, 0);
  1382. *dp++ = ':';
  1383. strcpy(dp, sensors.getSettingValue(i)); dp = strchr(dp, 0);
  1384. }
  1385. _serial->writeFrame(out_frame, dp - (char *)out_frame);
  1386. } else if (cmd_frame[0] == CMD_SET_CUSTOM_VAR && len >= 4) {
  1387. cmd_frame[len] = 0;
  1388. char* sp = (char *) &cmd_frame[1];
  1389. char* np = strchr(sp, ':'); // look for separator char
  1390. if (np) {
  1391. *np++ = 0; // modify 'cmd_frame', replace ':' with null
  1392. bool success = sensors.setSettingValue(sp, np);
  1393. if (success) {
  1394. writeOKFrame();
  1395. } else {
  1396. writeErrFrame(ERR_CODE_ILLEGAL_ARG);
  1397. }
  1398. } else {
  1399. writeErrFrame(ERR_CODE_ILLEGAL_ARG);
  1400. }
  1401. } else {
  1402. writeErrFrame(ERR_CODE_UNSUPPORTED_CMD);
  1403. MESH_DEBUG_PRINTLN("ERROR: unknown command: %02X", cmd_frame[0]);
  1404. }
  1405. }
  1406. void loop() {
  1407. BaseChatMesh::loop();
  1408. size_t len = _serial->checkRecvFrame(cmd_frame);
  1409. if (len > 0) {
  1410. handleCmdFrame(len);
  1411. } else if (_iter_started // check if our ContactsIterator is 'running'
  1412. && !_serial->isWriteBusy() // don't spam the Serial Interface too quickly!
  1413. ) {
  1414. ContactInfo contact;
  1415. if (_iter.hasNext(this, contact)) {
  1416. if (contact.lastmod > _iter_filter_since) { // apply the 'since' filter
  1417. writeContactRespFrame(RESP_CODE_CONTACT, contact);
  1418. if (contact.lastmod > _most_recent_lastmod) {
  1419. _most_recent_lastmod = contact.lastmod; // save for the RESP_CODE_END_OF_CONTACTS frame
  1420. }
  1421. }
  1422. } else { // EOF
  1423. out_frame[0] = RESP_CODE_END_OF_CONTACTS;
  1424. memcpy(&out_frame[1], &_most_recent_lastmod, 4); // include the most recent lastmod, so app can update their 'since'
  1425. _serial->writeFrame(out_frame, 5);
  1426. _iter_started = false;
  1427. }
  1428. } else if (!_serial->isWriteBusy()) {
  1429. checkConnections();
  1430. }
  1431. #ifdef HAS_UI
  1432. ui_task.setHasConnection(_serial->isConnected());
  1433. ui_task.loop();
  1434. #endif
  1435. }
  1436. };
  1437. #ifdef ESP32
  1438. #ifdef WIFI_SSID
  1439. #include <helpers/esp32/SerialWifiInterface.h>
  1440. SerialWifiInterface serial_interface;
  1441. #ifndef TCP_PORT
  1442. #define TCP_PORT 5000
  1443. #endif
  1444. #elif defined(BLE_PIN_CODE)
  1445. #include <helpers/esp32/SerialBLEInterface.h>
  1446. SerialBLEInterface serial_interface;
  1447. #elif defined(SERIAL_RX)
  1448. #include <helpers/ArduinoSerialInterface.h>
  1449. ArduinoSerialInterface serial_interface;
  1450. HardwareSerial companion_serial(1);
  1451. #else
  1452. #include <helpers/ArduinoSerialInterface.h>
  1453. ArduinoSerialInterface serial_interface;
  1454. #endif
  1455. #elif defined(RP2040_PLATFORM)
  1456. //#ifdef WIFI_SSID
  1457. // #include <helpers/rp2040/SerialWifiInterface.h>
  1458. // SerialWifiInterface serial_interface;
  1459. // #ifndef TCP_PORT
  1460. // #define TCP_PORT 5000
  1461. // #endif
  1462. // #elif defined(BLE_PIN_CODE)
  1463. // #include <helpers/rp2040/SerialBLEInterface.h>
  1464. // SerialBLEInterface serial_interface;
  1465. #if defined(SERIAL_RX)
  1466. #include <helpers/ArduinoSerialInterface.h>
  1467. ArduinoSerialInterface serial_interface;
  1468. HardwareSerial companion_serial(1);
  1469. #else
  1470. #include <helpers/ArduinoSerialInterface.h>
  1471. ArduinoSerialInterface serial_interface;
  1472. #endif
  1473. #elif defined(NRF52_PLATFORM)
  1474. #ifdef BLE_PIN_CODE
  1475. #include <helpers/nrf52/SerialBLEInterface.h>
  1476. SerialBLEInterface serial_interface;
  1477. #else
  1478. #include <helpers/ArduinoSerialInterface.h>
  1479. ArduinoSerialInterface serial_interface;
  1480. #endif
  1481. #elif defined(STM32_PLATFORM)
  1482. #include <helpers/ArduinoSerialInterface.h>
  1483. ArduinoSerialInterface serial_interface;
  1484. #else
  1485. #error "need to define a serial interface"
  1486. #endif
  1487. StdRNG fast_rng;
  1488. SimpleMeshTables tables;
  1489. MyMesh the_mesh(radio_driver, fast_rng, *new VolatileRTCClock(), tables); // TODO: test with 'rtc_clock' in target.cpp
  1490. void halt() {
  1491. while (1) ;
  1492. }
  1493. void setup() {
  1494. Serial.begin(115200);
  1495. board.begin();
  1496. #ifdef HAS_UI
  1497. DisplayDriver* disp = NULL;
  1498. #ifdef DISPLAY_CLASS
  1499. if (display.begin()) {
  1500. disp = &display;
  1501. disp->startFrame();
  1502. disp->print("Please wait...");
  1503. disp->endFrame();
  1504. }
  1505. #endif
  1506. #endif
  1507. if (!radio_init()) { halt(); }
  1508. fast_rng.begin(radio_get_rng_seed());
  1509. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  1510. InternalFS.begin();
  1511. the_mesh.begin(InternalFS,
  1512. #ifdef HAS_UI
  1513. disp != NULL
  1514. #else
  1515. false
  1516. #endif
  1517. );
  1518. #ifdef BLE_PIN_CODE
  1519. char dev_name[32+16];
  1520. sprintf(dev_name, "%s%s", BLE_NAME_PREFIX, the_mesh.getNodeName());
  1521. serial_interface.begin(dev_name, the_mesh.getBLEPin());
  1522. #else
  1523. serial_interface.begin(Serial);
  1524. #endif
  1525. the_mesh.startInterface(serial_interface);
  1526. #elif defined(RP2040_PLATFORM)
  1527. LittleFS.begin();
  1528. the_mesh.begin(LittleFS,
  1529. #ifdef HAS_UI
  1530. disp != NULL
  1531. #else
  1532. false
  1533. #endif
  1534. );
  1535. //#ifdef WIFI_SSID
  1536. // WiFi.begin(WIFI_SSID, WIFI_PWD);
  1537. // serial_interface.begin(TCP_PORT);
  1538. // #elif defined(BLE_PIN_CODE)
  1539. // char dev_name[32+16];
  1540. // sprintf(dev_name, "%s%s", BLE_NAME_PREFIX, the_mesh.getNodeName());
  1541. // serial_interface.begin(dev_name, the_mesh.getBLEPin());
  1542. #if defined(SERIAL_RX)
  1543. companion_serial.setPins(SERIAL_RX, SERIAL_TX);
  1544. companion_serial.begin(115200);
  1545. serial_interface.begin(companion_serial);
  1546. #else
  1547. serial_interface.begin(Serial);
  1548. #endif
  1549. the_mesh.startInterface(serial_interface);
  1550. #elif defined(ESP32)
  1551. SPIFFS.begin(true);
  1552. the_mesh.begin(SPIFFS,
  1553. #ifdef HAS_UI
  1554. disp != NULL
  1555. #else
  1556. false
  1557. #endif
  1558. );
  1559. #ifdef WIFI_SSID
  1560. WiFi.begin(WIFI_SSID, WIFI_PWD);
  1561. serial_interface.begin(TCP_PORT);
  1562. #elif defined(BLE_PIN_CODE)
  1563. char dev_name[32+16];
  1564. sprintf(dev_name, "%s%s", BLE_NAME_PREFIX, the_mesh.getNodeName());
  1565. serial_interface.begin(dev_name, the_mesh.getBLEPin());
  1566. #elif defined(SERIAL_RX)
  1567. companion_serial.setPins(SERIAL_RX, SERIAL_TX);
  1568. companion_serial.begin(115200);
  1569. serial_interface.begin(companion_serial);
  1570. #else
  1571. serial_interface.begin(Serial);
  1572. #endif
  1573. the_mesh.startInterface(serial_interface);
  1574. #else
  1575. #error "need to define filesystem"
  1576. #endif
  1577. sensors.begin();
  1578. #ifdef HAS_UI
  1579. ui_task.begin(disp, the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION, the_mesh.getBLEPin());
  1580. #endif
  1581. }
  1582. void loop() {
  1583. the_mesh.loop();
  1584. sensors.loop();
  1585. }