MyMesh.cpp 82 KB

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