MyMesh.cpp 72 KB

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