MyMesh.cpp 55 KB

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