MyMesh.cpp 55 KB

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