MyMesh.cpp 62 KB

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