MyMesh.cpp 58 KB

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