MyMesh.cpp 63 KB

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