main.cpp 61 KB

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