MyMesh.cpp 80 KB

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