MyMesh.cpp 55 KB

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