MyMesh.cpp 61 KB

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