MyMesh.cpp 77 KB

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