MyMesh.cpp 53 KB

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