MyMesh.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. #include "MyMesh.h"
  2. #include <algorithm>
  3. /* ------------------------------ Config -------------------------------- */
  4. #ifndef LORA_FREQ
  5. #define LORA_FREQ 915.0
  6. #endif
  7. #ifndef LORA_BW
  8. #define LORA_BW 250
  9. #endif
  10. #ifndef LORA_SF
  11. #define LORA_SF 10
  12. #endif
  13. #ifndef LORA_CR
  14. #define LORA_CR 5
  15. #endif
  16. #ifndef LORA_TX_POWER
  17. #define LORA_TX_POWER 20
  18. #endif
  19. #ifndef ADVERT_NAME
  20. #define ADVERT_NAME "repeater"
  21. #endif
  22. #ifndef ADVERT_LAT
  23. #define ADVERT_LAT 0.0
  24. #endif
  25. #ifndef ADVERT_LON
  26. #define ADVERT_LON 0.0
  27. #endif
  28. #ifndef ADMIN_PASSWORD
  29. #define ADMIN_PASSWORD "password"
  30. #endif
  31. #ifndef SERVER_RESPONSE_DELAY
  32. #define SERVER_RESPONSE_DELAY 300
  33. #endif
  34. #ifndef TXT_ACK_DELAY
  35. #define TXT_ACK_DELAY 200
  36. #endif
  37. #define FIRMWARE_VER_LEVEL 1
  38. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  39. #define REQ_TYPE_KEEP_ALIVE 0x02
  40. #define REQ_TYPE_GET_TELEMETRY_DATA 0x03
  41. #define REQ_TYPE_GET_ACCESS_LIST 0x05
  42. #define REQ_TYPE_GET_NEIGHBOURS 0x06
  43. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  44. #define CLI_REPLY_DELAY_MILLIS 600
  45. #define LAZY_CONTACTS_WRITE_DELAY 5000
  46. void MyMesh::putNeighbour(const mesh::Identity &id, uint32_t timestamp, float snr) {
  47. #if MAX_NEIGHBOURS // check if neighbours enabled
  48. // find existing neighbour, else use least recently updated
  49. uint32_t oldest_timestamp = 0xFFFFFFFF;
  50. NeighbourInfo *neighbour = &neighbours[0];
  51. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  52. // if neighbour already known, we should update it
  53. if (id.matches(neighbours[i].id)) {
  54. neighbour = &neighbours[i];
  55. break;
  56. }
  57. // otherwise we should update the least recently updated neighbour
  58. if (neighbours[i].heard_timestamp < oldest_timestamp) {
  59. neighbour = &neighbours[i];
  60. oldest_timestamp = neighbour->heard_timestamp;
  61. }
  62. }
  63. // update neighbour info
  64. neighbour->id = id;
  65. neighbour->advert_timestamp = timestamp;
  66. neighbour->heard_timestamp = getRTCClock()->getCurrentTime();
  67. neighbour->snr = (int8_t)(snr * 4);
  68. #endif
  69. }
  70. uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data) {
  71. ClientInfo* client = NULL;
  72. if (data[0] == 0) { // blank password, just check if sender is in ACL
  73. client = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
  74. if (client == NULL) {
  75. #if MESH_DEBUG
  76. MESH_DEBUG_PRINTLN("Login, sender not in ACL");
  77. #endif
  78. }
  79. }
  80. if (client == NULL) {
  81. uint8_t perms;
  82. if (strcmp((char *)data, _prefs.password) == 0) { // check for valid admin password
  83. perms = PERM_ACL_ADMIN;
  84. } else if (strcmp((char *)data, _prefs.guest_password) == 0) { // check guest password
  85. perms = PERM_ACL_GUEST;
  86. } else {
  87. #if MESH_DEBUG
  88. MESH_DEBUG_PRINTLN("Invalid password: %s", data);
  89. #endif
  90. return 0;
  91. }
  92. client = acl.putClient(sender, 0); // add to contacts (if not already known)
  93. if (sender_timestamp <= client->last_timestamp) {
  94. MESH_DEBUG_PRINTLN("Possible login replay attack!");
  95. return 0; // FATAL: client table is full -OR- replay attack
  96. }
  97. MESH_DEBUG_PRINTLN("Login success!");
  98. client->last_timestamp = sender_timestamp;
  99. client->last_activity = getRTCClock()->getCurrentTime();
  100. client->permissions &= ~0x03;
  101. client->permissions |= perms;
  102. memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
  103. if (perms != PERM_ACL_GUEST) { // keep number of FS writes to a minimum
  104. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  105. }
  106. }
  107. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  108. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  109. reply_data[4] = RESP_SERVER_LOGIN_OK;
  110. reply_data[5] = 0; // Legacy: was recommended keep-alive interval (secs / 16)
  111. reply_data[6] = client->isAdmin() ? 1 : 0;
  112. reply_data[7] = client->permissions;
  113. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  114. reply_data[12] = FIRMWARE_VER_LEVEL; // New field
  115. return 13; // reply length
  116. }
  117. int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) {
  118. // uint32_t now = getRTCClock()->getCurrentTimeUnique();
  119. // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  120. memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  121. if (payload[0] == REQ_TYPE_GET_STATUS) { // guests can also access this now
  122. RepeaterStats stats;
  123. stats.batt_milli_volts = board.getBattMilliVolts();
  124. stats.curr_tx_queue_len = _mgr->getOutboundCount(0xFFFFFFFF);
  125. stats.noise_floor = (int16_t)_radio->getNoiseFloor();
  126. stats.last_rssi = (int16_t)radio_driver.getLastRSSI();
  127. stats.n_packets_recv = radio_driver.getPacketsRecv();
  128. stats.n_packets_sent = radio_driver.getPacketsSent();
  129. stats.total_air_time_secs = getTotalAirTime() / 1000;
  130. stats.total_up_time_secs = uptime_millis / 1000;
  131. stats.n_sent_flood = getNumSentFlood();
  132. stats.n_sent_direct = getNumSentDirect();
  133. stats.n_recv_flood = getNumRecvFlood();
  134. stats.n_recv_direct = getNumRecvDirect();
  135. stats.err_events = _err_flags;
  136. stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
  137. stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
  138. stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
  139. stats.total_rx_air_time_secs = getReceiveAirTime() / 1000;
  140. memcpy(&reply_data[4], &stats, sizeof(stats));
  141. return 4 + sizeof(stats); // reply_len
  142. }
  143. if (payload[0] == REQ_TYPE_GET_TELEMETRY_DATA) {
  144. uint8_t perm_mask = ~(payload[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions
  145. telemetry.reset();
  146. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  147. // query other sensors -- target specific
  148. sensors.querySensors((sender->isAdmin() ? 0xFF : 0x00) & perm_mask, telemetry);
  149. uint8_t tlen = telemetry.getSize();
  150. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  151. return 4 + tlen; // reply_len
  152. }
  153. if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) {
  154. uint8_t res1 = payload[1]; // reserved for future (extra query params)
  155. uint8_t res2 = payload[2];
  156. if (res1 == 0 && res2 == 0) {
  157. uint8_t ofs = 4;
  158. for (int i = 0; i < acl.getNumClients() && ofs + 7 <= sizeof(reply_data) - 4; i++) {
  159. auto c = acl.getClientByIdx(i);
  160. if (c->permissions == 0) continue; // skip deleted entries
  161. memcpy(&reply_data[ofs], c->id.pub_key, 6); ofs += 6; // just 6-byte pub_key prefix
  162. reply_data[ofs++] = c->permissions;
  163. }
  164. return ofs;
  165. }
  166. }
  167. if (payload[0] == REQ_TYPE_GET_NEIGHBOURS) {
  168. uint8_t request_version = payload[1];
  169. if (request_version == 0) {
  170. // reply data offset (after response sender_timestamp/tag)
  171. int reply_offset = 4;
  172. // get request params
  173. uint8_t count = payload[2]; // how many neighbours to fetch (0-255)
  174. uint16_t offset;
  175. memcpy(&offset, &payload[3], 2); // offset from start of neighbours list (0-65535)
  176. uint8_t order_by = payload[5]; // how to order neighbours. 0=newest_to_oldest, 1=oldest_to_newest, 2=strongest_to_weakest, 3=weakest_to_strongest
  177. uint8_t pubkey_prefix_length = payload[6]; // how many bytes of neighbour pub key we want
  178. // we also send a 4 byte random blob in payload[7...10] to help packet uniqueness
  179. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS count=%d, offset=%d, order_by=%d, pubkey_prefix_length=%d", count, offset, order_by, pubkey_prefix_length);
  180. // clamp pub key prefix length to max pub key length
  181. if(pubkey_prefix_length > PUB_KEY_SIZE){
  182. pubkey_prefix_length = PUB_KEY_SIZE;
  183. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS invalid pubkey_prefix_length=%d clamping to %d", pubkey_prefix_length, PUB_KEY_SIZE);
  184. }
  185. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  186. int16_t neighbours_count = 0;
  187. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  188. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  189. auto neighbour = &neighbours[i];
  190. if (neighbour->heard_timestamp > 0) {
  191. sorted_neighbours[neighbours_count] = neighbour;
  192. neighbours_count++;
  193. }
  194. }
  195. // sort neighbours based on order
  196. if (order_by == 0) {
  197. // sort by newest to oldest
  198. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting newest to oldest");
  199. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  200. return a->heard_timestamp > b->heard_timestamp; // desc
  201. });
  202. } else if (order_by == 1) {
  203. // sort by oldest to newest
  204. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting oldest to newest");
  205. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  206. return a->heard_timestamp < b->heard_timestamp; // asc
  207. });
  208. } else if (order_by == 2) {
  209. // sort by strongest to weakest
  210. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting strongest to weakest");
  211. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  212. return a->snr > b->snr; // desc
  213. });
  214. } else if (order_by == 3) {
  215. // sort by weakest to strongest
  216. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting weakest to strongest");
  217. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  218. return a->snr < b->snr; // asc
  219. });
  220. }
  221. // build results buffer
  222. int results_count = 0;
  223. int results_offset = 0;
  224. uint8_t results_buffer[130];
  225. for(int index = 0; index < count && index + offset < neighbours_count; index++){
  226. // stop if we can't fit another entry in results
  227. int entry_size = pubkey_prefix_length + 4 + 1;
  228. if(results_offset + entry_size > sizeof(results_buffer)){
  229. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS no more entries can fit in results buffer");
  230. break;
  231. }
  232. // add next neighbour to results
  233. auto neighbour = sorted_neighbours[index + offset];
  234. uint32_t heard_seconds_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  235. memcpy(&results_buffer[results_offset], neighbour->id.pub_key, pubkey_prefix_length); results_offset += pubkey_prefix_length;
  236. memcpy(&results_buffer[results_offset], &heard_seconds_ago, 4); results_offset += 4;
  237. memcpy(&results_buffer[results_offset], &neighbour->snr, 1); results_offset += 1;
  238. results_count++;
  239. }
  240. // build reply
  241. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS neighbours_count=%d results_count=%d", neighbours_count, results_count);
  242. memcpy(&reply_data[reply_offset], &neighbours_count, 2); reply_offset += 2;
  243. memcpy(&reply_data[reply_offset], &results_count, 2); reply_offset += 2;
  244. memcpy(&reply_data[reply_offset], &results_buffer, results_offset); reply_offset += results_offset;
  245. return reply_offset;
  246. }
  247. }
  248. return 0; // unknown command
  249. }
  250. mesh::Packet *MyMesh::createSelfAdvert() {
  251. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  252. uint8_t app_data_len = _cli.buildAdvertData(ADV_TYPE_REPEATER, app_data);
  253. return createAdvert(self_id, app_data, app_data_len);
  254. }
  255. File MyMesh::openAppend(const char *fname) {
  256. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  257. return _fs->open(fname, FILE_O_WRITE);
  258. #elif defined(RP2040_PLATFORM)
  259. return _fs->open(fname, "a");
  260. #else
  261. return _fs->open(fname, "a", true);
  262. #endif
  263. }
  264. bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
  265. if (_prefs.disable_fwd) return false;
  266. if (packet->isRouteFlood() && packet->path_len >= _prefs.flood_max) return false;
  267. if (packet->isRouteFlood() && recv_pkt_region == NULL) {
  268. MESH_DEBUG_PRINTLN("allowPacketForward: unknown transport code, or wildcard not allowed for FLOOD packet");
  269. return false;
  270. }
  271. return true;
  272. }
  273. const char *MyMesh::getLogDateTime() {
  274. static char tmp[32];
  275. uint32_t now = getRTCClock()->getCurrentTime();
  276. DateTime dt = DateTime(now);
  277. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
  278. dt.year());
  279. return tmp;
  280. }
  281. void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
  282. #if MESH_PACKET_LOGGING
  283. Serial.print(getLogDateTime());
  284. Serial.print(" RAW: ");
  285. mesh::Utils::printHex(Serial, raw, len);
  286. Serial.println();
  287. #endif
  288. }
  289. void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
  290. #ifdef WITH_BRIDGE
  291. if (_prefs.bridge_pkt_src == 1) {
  292. bridge.sendPacket(pkt);
  293. }
  294. #endif
  295. if (_logging) {
  296. File f = openAppend(PACKET_LOG_FILE);
  297. if (f) {
  298. f.print(getLogDateTime());
  299. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
  300. pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  301. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
  302. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  303. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  304. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  305. } else {
  306. f.printf("\n");
  307. }
  308. f.close();
  309. }
  310. }
  311. }
  312. void MyMesh::logTx(mesh::Packet *pkt, int len) {
  313. #ifdef WITH_BRIDGE
  314. if (_prefs.bridge_pkt_src == 0) {
  315. bridge.sendPacket(pkt);
  316. }
  317. #endif
  318. if (_logging) {
  319. File f = openAppend(PACKET_LOG_FILE);
  320. if (f) {
  321. f.print(getLogDateTime());
  322. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  323. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  324. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  325. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  326. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  327. } else {
  328. f.printf("\n");
  329. }
  330. f.close();
  331. }
  332. }
  333. }
  334. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  335. if (_logging) {
  336. File f = openAppend(PACKET_LOG_FILE);
  337. if (f) {
  338. f.print(getLogDateTime());
  339. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  340. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  341. f.close();
  342. }
  343. }
  344. }
  345. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  346. if (_prefs.rx_delay_base <= 0.0f) return 0;
  347. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  348. }
  349. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  350. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  351. return getRNG()->nextInt(0, 5*t + 1);
  352. }
  353. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  354. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  355. return getRNG()->nextInt(0, 5*t + 1);
  356. }
  357. bool MyMesh::filterRecvFloodPacket(mesh::Packet* pkt) {
  358. // just try to determine region for packet (apply later in allowPacketForward())
  359. if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
  360. recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
  361. } else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
  362. if (region_map.getWildcard().flags & REGION_DENY_FLOOD) {
  363. recv_pkt_region = NULL;
  364. } else {
  365. recv_pkt_region = &region_map.getWildcard();
  366. }
  367. } else {
  368. recv_pkt_region = NULL;
  369. }
  370. // do normal processing
  371. return false;
  372. }
  373. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  374. uint8_t *data, size_t len) {
  375. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  376. // client (unknown at this stage)
  377. uint32_t timestamp;
  378. memcpy(&timestamp, data, 4);
  379. data[len] = 0; // ensure null terminator
  380. uint8_t reply_len;
  381. if (data[4] == 0 || data[4] >= ' ') { // is password, ie. a login request
  382. reply_len = handleLoginReq(sender, secret, timestamp, &data[4]);
  383. //} else if (data[4] == ANON_REQ_TYPE_*) { // future type codes
  384. // TODO
  385. } else {
  386. reply_len = 0; // unknown request type
  387. }
  388. if (reply_len == 0) return; // invalid request
  389. if (packet->isRouteFlood()) {
  390. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  391. mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
  392. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  393. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  394. } else {
  395. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  396. if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY);
  397. }
  398. }
  399. }
  400. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  401. int n = 0;
  402. for (int i = 0; i < acl.getNumClients(); i++) {
  403. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  404. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  405. }
  406. }
  407. return n;
  408. }
  409. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  410. int i = matching_peer_indexes[peer_idx];
  411. if (i >= 0 && i < acl.getNumClients()) {
  412. // lookup pre-calculated shared_secret
  413. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  414. } else {
  415. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  416. }
  417. }
  418. static bool isShare(const mesh::Packet *packet) {
  419. if (packet->hasTransportCodes()) {
  420. return packet->transport_codes[0] == 0 && packet->transport_codes[1] == 0; // codes { 0, 0 } means 'send to nowhere'
  421. }
  422. return false;
  423. }
  424. void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
  425. const uint8_t *app_data, size_t app_data_len) {
  426. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  427. // if this a zero hop advert (and not via 'Share'), add it to neighbours
  428. if (packet->path_len == 0 && !isShare(packet)) {
  429. AdvertDataParser parser(app_data, app_data_len);
  430. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  431. putNeighbour(id, timestamp, packet->getSNR());
  432. }
  433. }
  434. }
  435. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  436. uint8_t *data, size_t len) {
  437. int i = matching_peer_indexes[sender_idx];
  438. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  439. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  440. return;
  441. }
  442. ClientInfo* client = acl.getClientByIdx(i);
  443. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  444. uint32_t timestamp;
  445. memcpy(&timestamp, data, 4);
  446. if (timestamp > client->last_timestamp) { // prevent replay attacks
  447. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  448. if (reply_len == 0) return; // invalid command
  449. client->last_timestamp = timestamp;
  450. client->last_activity = getRTCClock()->getCurrentTime();
  451. if (packet->isRouteFlood()) {
  452. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  453. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  454. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  455. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  456. } else {
  457. mesh::Packet *reply =
  458. createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  459. if (reply) {
  460. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  461. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  462. } else {
  463. sendFlood(reply, SERVER_RESPONSE_DELAY);
  464. }
  465. }
  466. }
  467. } else {
  468. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  469. }
  470. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->isAdmin()) { // a CLI command
  471. uint32_t sender_timestamp;
  472. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  473. uint flags = (data[4] >> 2); // message attempt number, and other flags
  474. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  475. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  476. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  477. bool is_retry = (sender_timestamp == client->last_timestamp);
  478. client->last_timestamp = sender_timestamp;
  479. client->last_activity = getRTCClock()->getCurrentTime();
  480. // len can be > original length, but 'text' will be padded with zeroes
  481. data[len] = 0; // need to make a C string again, with null terminator
  482. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  483. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
  484. // to sender that we got it
  485. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  486. PUB_KEY_SIZE);
  487. mesh::Packet *ack = createAck(ack_hash);
  488. if (ack) {
  489. if (client->out_path_len < 0) {
  490. sendFlood(ack, TXT_ACK_DELAY);
  491. } else {
  492. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  493. }
  494. }
  495. }
  496. uint8_t temp[166];
  497. char *command = (char *)&data[5];
  498. char *reply = (char *)&temp[5];
  499. if (is_retry) {
  500. *reply = 0;
  501. } else {
  502. handleCommand(sender_timestamp, command, reply);
  503. }
  504. int text_len = strlen(reply);
  505. if (text_len > 0) {
  506. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  507. if (timestamp == sender_timestamp) {
  508. // WORKAROUND: the two timestamps need to be different, in the CLI view
  509. timestamp++;
  510. }
  511. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  512. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  513. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  514. if (reply) {
  515. if (client->out_path_len < 0) {
  516. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  517. } else {
  518. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  519. }
  520. }
  521. }
  522. } else {
  523. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  524. }
  525. }
  526. }
  527. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  528. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  529. // TODO: prevent replay attacks
  530. int i = matching_peer_indexes[sender_idx];
  531. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  532. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  533. auto client = acl.getClientByIdx(i);
  534. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  535. client->last_activity = getRTCClock()->getCurrentTime();
  536. } else {
  537. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  538. }
  539. // NOTE: no reciprocal path send!!
  540. return false;
  541. }
  542. #define CTL_TYPE_NODE_DISCOVER_REQ 0x80
  543. #define CTL_TYPE_NODE_DISCOVER_RESP 0x90
  544. void MyMesh::onControlDataRecv(mesh::Packet* packet) {
  545. uint8_t type = packet->payload[0] & 0xF0; // just test upper 4 bits
  546. if (type == CTL_TYPE_NODE_DISCOVER_REQ && packet->payload_len >= 6 && discover_limiter.allow(rtc_clock.getCurrentTime())) {
  547. int i = 1;
  548. uint8_t filter = packet->payload[i++];
  549. uint32_t tag;
  550. memcpy(&tag, &packet->payload[i], 4); i += 4;
  551. uint32_t since;
  552. if (packet->payload_len >= i+4) { // optional since field
  553. memcpy(&since, &packet->payload[i], 4); i += 4;
  554. } else {
  555. since = 0;
  556. }
  557. if ((filter & (1 << ADV_TYPE_REPEATER)) != 0 && _prefs.discovery_mod_timestamp >= since) {
  558. bool prefix_only = packet->payload[0] & 1;
  559. uint8_t data[6 + PUB_KEY_SIZE];
  560. data[0] = CTL_TYPE_NODE_DISCOVER_RESP | ADV_TYPE_REPEATER; // low 4-bits for node type
  561. data[1] = packet->_snr; // let sender know the inbound SNR ( x 4)
  562. memcpy(&data[2], &tag, 4); // include tag from request, for client to match to
  563. memcpy(&data[6], self_id.pub_key, PUB_KEY_SIZE);
  564. auto resp = createControlData(data, prefix_only ? 6 + 8 : 6 + PUB_KEY_SIZE);
  565. if (resp) {
  566. sendZeroHop(resp, getRetransmitDelay(resp)*4); // apply random delay (widened x4), as multiple nodes can respond to this
  567. }
  568. }
  569. }
  570. }
  571. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  572. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  573. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  574. _cli(board, rtc, sensors, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4), region_map(key_store), temp_map(key_store),
  575. discover_limiter(4, 120) // max 4 every 2 minutes
  576. #if defined(WITH_RS232_BRIDGE)
  577. , bridge(&_prefs, WITH_RS232_BRIDGE, _mgr, &rtc)
  578. #endif
  579. #if defined(WITH_ESPNOW_BRIDGE)
  580. , bridge(&_prefs, _mgr, &rtc)
  581. #endif
  582. {
  583. last_millis = 0;
  584. uptime_millis = 0;
  585. next_local_advert = next_flood_advert = 0;
  586. dirty_contacts_expiry = 0;
  587. set_radio_at = revert_radio_at = 0;
  588. _logging = false;
  589. region_load_active = false;
  590. #if MAX_NEIGHBOURS
  591. memset(neighbours, 0, sizeof(neighbours));
  592. #endif
  593. // defaults
  594. memset(&_prefs, 0, sizeof(_prefs));
  595. _prefs.airtime_factor = 1.0; // one half
  596. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  597. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  598. _prefs.direct_tx_delay_factor = 0.2f; // was zero
  599. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  600. _prefs.node_lat = ADVERT_LAT;
  601. _prefs.node_lon = ADVERT_LON;
  602. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  603. _prefs.freq = LORA_FREQ;
  604. _prefs.sf = LORA_SF;
  605. _prefs.bw = LORA_BW;
  606. _prefs.cr = LORA_CR;
  607. _prefs.tx_power_dbm = LORA_TX_POWER;
  608. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  609. _prefs.flood_advert_interval = 12; // 12 hours
  610. _prefs.flood_max = 64;
  611. _prefs.interference_threshold = 0; // disabled
  612. // bridge defaults
  613. _prefs.bridge_enabled = 1; // enabled
  614. _prefs.bridge_delay = 500; // milliseconds
  615. _prefs.bridge_pkt_src = 0; // logTx
  616. _prefs.bridge_baud = 115200; // baud rate
  617. _prefs.bridge_channel = 1; // channel 1
  618. StrHelper::strncpy(_prefs.bridge_secret, "LVSITANOS", sizeof(_prefs.bridge_secret));
  619. // GPS defaults
  620. _prefs.gps_enabled = 0;
  621. _prefs.gps_interval = 0;
  622. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  623. }
  624. void MyMesh::begin(FILESYSTEM *fs) {
  625. mesh::Mesh::begin();
  626. _fs = fs;
  627. // load persisted prefs
  628. _cli.loadPrefs(_fs);
  629. acl.load(_fs);
  630. // TODO: key_store.begin();
  631. region_map.load(_fs);
  632. #if defined(WITH_BRIDGE)
  633. if (_prefs.bridge_enabled) {
  634. bridge.begin();
  635. }
  636. #endif
  637. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  638. radio_set_tx_power(_prefs.tx_power_dbm);
  639. updateAdvertTimer();
  640. updateFloodAdvertTimer();
  641. #if ENV_INCLUDE_GPS == 1
  642. applyGpsPrefs();
  643. #endif
  644. }
  645. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  646. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  647. pending_freq = freq;
  648. pending_bw = bw;
  649. pending_sf = sf;
  650. pending_cr = cr;
  651. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  652. }
  653. bool MyMesh::formatFileSystem() {
  654. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  655. return InternalFS.format();
  656. #elif defined(RP2040_PLATFORM)
  657. return LittleFS.format();
  658. #elif defined(ESP32)
  659. return SPIFFS.format();
  660. #else
  661. #error "need to implement file system erase"
  662. return false;
  663. #endif
  664. }
  665. void MyMesh::sendSelfAdvertisement(int delay_millis) {
  666. mesh::Packet *pkt = createSelfAdvert();
  667. if (pkt) {
  668. sendFlood(pkt, delay_millis);
  669. } else {
  670. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  671. }
  672. }
  673. void MyMesh::updateAdvertTimer() {
  674. if (_prefs.advert_interval > 0) { // schedule local advert timer
  675. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  676. } else {
  677. next_local_advert = 0; // stop the timer
  678. }
  679. }
  680. void MyMesh::updateFloodAdvertTimer() {
  681. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  682. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  683. } else {
  684. next_flood_advert = 0; // stop the timer
  685. }
  686. }
  687. void MyMesh::dumpLogFile() {
  688. #if defined(RP2040_PLATFORM)
  689. File f = _fs->open(PACKET_LOG_FILE, "r");
  690. #else
  691. File f = _fs->open(PACKET_LOG_FILE);
  692. #endif
  693. if (f) {
  694. while (f.available()) {
  695. int c = f.read();
  696. if (c < 0) break;
  697. Serial.print((char)c);
  698. }
  699. f.close();
  700. }
  701. }
  702. void MyMesh::setTxPower(uint8_t power_dbm) {
  703. radio_set_tx_power(power_dbm);
  704. }
  705. void MyMesh::formatNeighborsReply(char *reply) {
  706. char *dp = reply;
  707. #if MAX_NEIGHBOURS
  708. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  709. int16_t neighbours_count = 0;
  710. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  711. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  712. auto neighbour = &neighbours[i];
  713. if (neighbour->heard_timestamp > 0) {
  714. sorted_neighbours[neighbours_count] = neighbour;
  715. neighbours_count++;
  716. }
  717. }
  718. // sort neighbours newest to oldest
  719. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  720. return a->heard_timestamp > b->heard_timestamp; // desc
  721. });
  722. for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
  723. NeighbourInfo *neighbour = sorted_neighbours[i];
  724. // add new line if not first item
  725. if (i > 0) *dp++ = '\n';
  726. char hex[10];
  727. // get 4 bytes of neighbour id as hex
  728. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  729. // add next neighbour
  730. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  731. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  732. while (*dp)
  733. dp++; // find end of string
  734. }
  735. #endif
  736. if (dp == reply) { // no neighbours, need empty response
  737. strcpy(dp, "-none-");
  738. dp += 6;
  739. }
  740. *dp = 0; // null terminator
  741. }
  742. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  743. #if MAX_NEIGHBOURS
  744. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  745. NeighbourInfo *neighbour = &neighbours[i];
  746. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  747. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  748. }
  749. }
  750. #endif
  751. }
  752. void MyMesh::formatStatsReply(char *reply) {
  753. StatsFormatHelper::formatCoreStats(reply, board, *_ms, _err_flags, _mgr);
  754. }
  755. void MyMesh::formatRadioStatsReply(char *reply) {
  756. StatsFormatHelper::formatRadioStats(reply, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
  757. }
  758. void MyMesh::formatPacketStatsReply(char *reply) {
  759. StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
  760. getNumRecvFlood(), getNumRecvDirect());
  761. }
  762. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  763. self_id = new_id;
  764. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  765. IdentityStore store(*_fs, "");
  766. #elif defined(ESP32)
  767. IdentityStore store(*_fs, "/identity");
  768. #elif defined(RP2040_PLATFORM)
  769. IdentityStore store(*_fs, "/identity");
  770. #else
  771. #error "need to define saveIdentity()"
  772. #endif
  773. store.save("_main", self_id);
  774. }
  775. void MyMesh::clearStats() {
  776. radio_driver.resetStats();
  777. resetStats();
  778. ((SimpleMeshTables *)getTables())->resetStats();
  779. }
  780. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  781. if (region_load_active) {
  782. if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
  783. region_map = temp_map; // copy over the temp instance as new current map
  784. region_load_active = false;
  785. sprintf(reply, "OK - loaded %d regions", region_map.getCount());
  786. } else {
  787. char *np = command;
  788. while (*np == ' ') np++; // skip indent
  789. int indent = np - command;
  790. char *ep = np;
  791. while (RegionMap::is_name_char(*ep)) ep++;
  792. if (*ep) { *ep++ = 0; } // set null terminator for end of name
  793. while (*ep && *ep != 'F') ep++; // look for (optional) flags
  794. if (indent > 0 && indent < 8 && strlen(np) > 0) {
  795. auto parent = load_stack[indent - 1];
  796. if (parent) {
  797. auto old = region_map.findByName(np);
  798. auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists)
  799. if (nw) {
  800. nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr
  801. load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's
  802. }
  803. }
  804. }
  805. reply[0] = 0;
  806. }
  807. return;
  808. }
  809. while (*command == ' ') command++; // skip leading spaces
  810. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  811. memcpy(reply, command, 3); // reflect the prefix back
  812. reply += 3;
  813. command += 3;
  814. }
  815. // handle ACL related commands
  816. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  817. char* hex = &command[8];
  818. char* sp = strchr(hex, ' '); // look for separator char
  819. if (sp == NULL) {
  820. strcpy(reply, "Err - bad params");
  821. } else {
  822. *sp++ = 0; // replace space with null terminator
  823. uint8_t pubkey[PUB_KEY_SIZE];
  824. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  825. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  826. uint8_t perms = atoi(sp);
  827. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  828. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  829. strcpy(reply, "OK");
  830. } else {
  831. strcpy(reply, "Err - invalid params");
  832. }
  833. } else {
  834. strcpy(reply, "Err - bad pubkey");
  835. }
  836. }
  837. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  838. Serial.println("ACL:");
  839. for (int i = 0; i < acl.getNumClients(); i++) {
  840. auto c = acl.getClientByIdx(i);
  841. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  842. Serial.printf("%02X ", c->permissions);
  843. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  844. Serial.printf("\n");
  845. }
  846. reply[0] = 0;
  847. } else if (memcmp(command, "region", 6) == 0) {
  848. reply[0] = 0;
  849. const char* parts[4];
  850. int n = mesh::Utils::parseTextParts(command, parts, 4, ' ');
  851. if (n == 1 && sender_timestamp == 0) {
  852. region_map.exportTo(Serial);
  853. } else if (n >= 2 && strcmp(parts[1], "load") == 0) {
  854. temp_map.resetFrom(region_map); // rebuild regions in a temp instance
  855. memset(load_stack, 0, sizeof(load_stack));
  856. load_stack[0] = &temp_map.getWildcard();
  857. region_load_active = true;
  858. } else if (n >= 2 && strcmp(parts[1], "save") == 0) {
  859. _prefs.discovery_mod_timestamp = rtc_clock.getCurrentTime(); // this node is now 'modified' (for discovery info)
  860. savePrefs();
  861. bool success = region_map.save(_fs);
  862. strcpy(reply, success ? "OK" : "Err - save failed");
  863. } else if (n >= 3 && strcmp(parts[1], "allowf") == 0) {
  864. auto region = region_map.findByNamePrefix(parts[2]);
  865. if (region) {
  866. region->flags &= ~REGION_DENY_FLOOD;
  867. strcpy(reply, "OK");
  868. } else {
  869. strcpy(reply, "Err - unknown region");
  870. }
  871. } else if (n >= 3 && strcmp(parts[1], "denyf") == 0) {
  872. auto region = region_map.findByNamePrefix(parts[2]);
  873. if (region) {
  874. region->flags |= REGION_DENY_FLOOD;
  875. strcpy(reply, "OK");
  876. } else {
  877. strcpy(reply, "Err - unknown region");
  878. }
  879. } else if (n >= 3 && strcmp(parts[1], "get") == 0) {
  880. auto region = region_map.findByNamePrefix(parts[2]);
  881. if (region) {
  882. auto parent = region_map.findById(region->parent);
  883. if (parent && parent->id != 0) {
  884. sprintf(reply, " %s (%s) %s", region->name, parent->name, (region->flags & REGION_DENY_FLOOD) ? "" : "F");
  885. } else {
  886. sprintf(reply, " %s %s", region->name, (region->flags & REGION_DENY_FLOOD) ? "" : "F");
  887. }
  888. } else {
  889. strcpy(reply, "Err - unknown region");
  890. }
  891. } else if (n >= 3 && strcmp(parts[1], "home") == 0) {
  892. auto home = region_map.findByNamePrefix(parts[2]);
  893. if (home) {
  894. region_map.setHomeRegion(home);
  895. sprintf(reply, " home is now %s", home->name);
  896. } else {
  897. strcpy(reply, "Err - unknown region");
  898. }
  899. } else if (n == 2 && strcmp(parts[1], "home") == 0) {
  900. auto home = region_map.getHomeRegion();
  901. sprintf(reply, " home is %s", home ? home->name : "*");
  902. } else if (n >= 3 && strcmp(parts[1], "put") == 0) {
  903. auto parent = n >= 4 ? region_map.findByNamePrefix(parts[3]) : &region_map.getWildcard();
  904. if (parent == NULL) {
  905. strcpy(reply, "Err - unknown parent");
  906. } else {
  907. auto region = region_map.putRegion(parts[2], parent->id);
  908. if (region == NULL) {
  909. strcpy(reply, "Err - unable to put");
  910. } else {
  911. strcpy(reply, "OK");
  912. }
  913. }
  914. } else if (n >= 3 && strcmp(parts[1], "remove") == 0) {
  915. auto region = region_map.findByName(parts[2]);
  916. if (region) {
  917. if (region_map.removeRegion(*region)) {
  918. strcpy(reply, "OK");
  919. } else {
  920. strcpy(reply, "Err - not empty");
  921. }
  922. } else {
  923. strcpy(reply, "Err - not found");
  924. }
  925. } else {
  926. strcpy(reply, "Err - ??");
  927. }
  928. } else{
  929. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  930. }
  931. }
  932. void MyMesh::loop() {
  933. #ifdef WITH_BRIDGE
  934. bridge.loop();
  935. #endif
  936. mesh::Mesh::loop();
  937. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  938. mesh::Packet *pkt = createSelfAdvert();
  939. if (pkt) sendFlood(pkt);
  940. updateFloodAdvertTimer(); // schedule next flood advert
  941. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  942. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  943. mesh::Packet *pkt = createSelfAdvert();
  944. if (pkt) sendZeroHop(pkt);
  945. updateAdvertTimer(); // schedule next local advert
  946. }
  947. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  948. set_radio_at = 0; // clear timer
  949. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  950. MESH_DEBUG_PRINTLN("Temp radio params");
  951. }
  952. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  953. revert_radio_at = 0; // clear timer
  954. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  955. MESH_DEBUG_PRINTLN("Radio params restored");
  956. }
  957. // is pending dirty contacts write needed?
  958. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  959. acl.save(_fs);
  960. dirty_contacts_expiry = 0;
  961. }
  962. // update uptime
  963. uint32_t now = millis();
  964. uptime_millis += now - last_millis;
  965. last_millis = now;
  966. }