MyMesh.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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. uint8_t data[6 + PUB_KEY_SIZE];
  559. data[0] = CTL_TYPE_NODE_DISCOVER_RESP | ADV_TYPE_REPEATER; // low 4-bits for node type
  560. data[1] = packet->_snr; // let sender know the inbound SNR ( x 4)
  561. memcpy(&data[2], &tag, 4); // include tag from request, for client to match to
  562. memcpy(&data[6], self_id.pub_key, PUB_KEY_SIZE);
  563. auto resp = createControlData(data, sizeof(data));
  564. if (resp) {
  565. sendZeroHop(resp, getRetransmitDelay(resp)*4); // apply random delay (widened x4), as multiple nodes can respond to this
  566. }
  567. }
  568. }
  569. }
  570. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  571. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  572. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  573. _cli(board, rtc, sensors, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4), region_map(key_store), temp_map(key_store),
  574. discover_limiter(4, 120) // max 4 every 2 minutes
  575. #if defined(WITH_RS232_BRIDGE)
  576. , bridge(&_prefs, WITH_RS232_BRIDGE, _mgr, &rtc)
  577. #endif
  578. #if defined(WITH_ESPNOW_BRIDGE)
  579. , bridge(&_prefs, _mgr, &rtc)
  580. #endif
  581. {
  582. last_millis = 0;
  583. uptime_millis = 0;
  584. next_local_advert = next_flood_advert = 0;
  585. dirty_contacts_expiry = 0;
  586. set_radio_at = revert_radio_at = 0;
  587. _logging = false;
  588. region_load_active = false;
  589. #if MAX_NEIGHBOURS
  590. memset(neighbours, 0, sizeof(neighbours));
  591. #endif
  592. // defaults
  593. memset(&_prefs, 0, sizeof(_prefs));
  594. _prefs.airtime_factor = 1.0; // one half
  595. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  596. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  597. _prefs.direct_tx_delay_factor = 0.2f; // was zero
  598. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  599. _prefs.node_lat = ADVERT_LAT;
  600. _prefs.node_lon = ADVERT_LON;
  601. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  602. _prefs.freq = LORA_FREQ;
  603. _prefs.sf = LORA_SF;
  604. _prefs.bw = LORA_BW;
  605. _prefs.cr = LORA_CR;
  606. _prefs.tx_power_dbm = LORA_TX_POWER;
  607. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  608. _prefs.flood_advert_interval = 12; // 12 hours
  609. _prefs.flood_max = 64;
  610. _prefs.interference_threshold = 0; // disabled
  611. // bridge defaults
  612. _prefs.bridge_enabled = 1; // enabled
  613. _prefs.bridge_delay = 500; // milliseconds
  614. _prefs.bridge_pkt_src = 0; // logTx
  615. _prefs.bridge_baud = 115200; // baud rate
  616. _prefs.bridge_channel = 1; // channel 1
  617. StrHelper::strncpy(_prefs.bridge_secret, "LVSITANOS", sizeof(_prefs.bridge_secret));
  618. // GPS defaults
  619. _prefs.gps_enabled = 0;
  620. _prefs.gps_interval = 0;
  621. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  622. }
  623. void MyMesh::begin(FILESYSTEM *fs) {
  624. mesh::Mesh::begin();
  625. _fs = fs;
  626. // load persisted prefs
  627. _cli.loadPrefs(_fs);
  628. acl.load(_fs);
  629. // TODO: key_store.begin();
  630. region_map.load(_fs);
  631. #if defined(WITH_BRIDGE)
  632. if (_prefs.bridge_enabled) {
  633. bridge.begin();
  634. }
  635. #endif
  636. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  637. radio_set_tx_power(_prefs.tx_power_dbm);
  638. updateAdvertTimer();
  639. updateFloodAdvertTimer();
  640. #if ENV_INCLUDE_GPS == 1
  641. applyGpsPrefs();
  642. #endif
  643. }
  644. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  645. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  646. pending_freq = freq;
  647. pending_bw = bw;
  648. pending_sf = sf;
  649. pending_cr = cr;
  650. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  651. }
  652. bool MyMesh::formatFileSystem() {
  653. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  654. return InternalFS.format();
  655. #elif defined(RP2040_PLATFORM)
  656. return LittleFS.format();
  657. #elif defined(ESP32)
  658. return SPIFFS.format();
  659. #else
  660. #error "need to implement file system erase"
  661. return false;
  662. #endif
  663. }
  664. void MyMesh::sendSelfAdvertisement(int delay_millis) {
  665. mesh::Packet *pkt = createSelfAdvert();
  666. if (pkt) {
  667. sendFlood(pkt, delay_millis);
  668. } else {
  669. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  670. }
  671. }
  672. void MyMesh::updateAdvertTimer() {
  673. if (_prefs.advert_interval > 0) { // schedule local advert timer
  674. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  675. } else {
  676. next_local_advert = 0; // stop the timer
  677. }
  678. }
  679. void MyMesh::updateFloodAdvertTimer() {
  680. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  681. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  682. } else {
  683. next_flood_advert = 0; // stop the timer
  684. }
  685. }
  686. void MyMesh::dumpLogFile() {
  687. #if defined(RP2040_PLATFORM)
  688. File f = _fs->open(PACKET_LOG_FILE, "r");
  689. #else
  690. File f = _fs->open(PACKET_LOG_FILE);
  691. #endif
  692. if (f) {
  693. while (f.available()) {
  694. int c = f.read();
  695. if (c < 0) break;
  696. Serial.print((char)c);
  697. }
  698. f.close();
  699. }
  700. }
  701. void MyMesh::setTxPower(uint8_t power_dbm) {
  702. radio_set_tx_power(power_dbm);
  703. }
  704. void MyMesh::formatNeighborsReply(char *reply) {
  705. char *dp = reply;
  706. #if MAX_NEIGHBOURS
  707. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  708. int16_t neighbours_count = 0;
  709. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  710. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  711. auto neighbour = &neighbours[i];
  712. if (neighbour->heard_timestamp > 0) {
  713. sorted_neighbours[neighbours_count] = neighbour;
  714. neighbours_count++;
  715. }
  716. }
  717. // sort neighbours newest to oldest
  718. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  719. return a->heard_timestamp > b->heard_timestamp; // desc
  720. });
  721. for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
  722. NeighbourInfo *neighbour = sorted_neighbours[i];
  723. // add new line if not first item
  724. if (i > 0) *dp++ = '\n';
  725. char hex[10];
  726. // get 4 bytes of neighbour id as hex
  727. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  728. // add next neighbour
  729. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  730. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  731. while (*dp)
  732. dp++; // find end of string
  733. }
  734. #endif
  735. if (dp == reply) { // no neighbours, need empty response
  736. strcpy(dp, "-none-");
  737. dp += 6;
  738. }
  739. *dp = 0; // null terminator
  740. }
  741. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  742. #if MAX_NEIGHBOURS
  743. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  744. NeighbourInfo *neighbour = &neighbours[i];
  745. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  746. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  747. }
  748. }
  749. #endif
  750. }
  751. void MyMesh::formatStatsReply(char *reply) {
  752. StatsFormatHelper::formatCoreStats(reply, board, *_ms, _err_flags, _mgr);
  753. }
  754. void MyMesh::formatRadioStatsReply(char *reply) {
  755. StatsFormatHelper::formatRadioStats(reply, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
  756. }
  757. void MyMesh::formatPacketStatsReply(char *reply) {
  758. StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
  759. getNumRecvFlood(), getNumRecvDirect());
  760. }
  761. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  762. self_id = new_id;
  763. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  764. IdentityStore store(*_fs, "");
  765. #elif defined(ESP32)
  766. IdentityStore store(*_fs, "/identity");
  767. #elif defined(RP2040_PLATFORM)
  768. IdentityStore store(*_fs, "/identity");
  769. #else
  770. #error "need to define saveIdentity()"
  771. #endif
  772. store.save("_main", self_id);
  773. }
  774. void MyMesh::clearStats() {
  775. radio_driver.resetStats();
  776. resetStats();
  777. ((SimpleMeshTables *)getTables())->resetStats();
  778. }
  779. static bool is_name_char(char c) {
  780. return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' || c == '#';
  781. }
  782. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  783. if (region_load_active) {
  784. if (*command == 0) { // empty line, signal to terminate 'load' operation
  785. region_map = temp_map; // copy over the temp instance as new current map
  786. region_load_active = false;
  787. sprintf(reply, "OK - loaded %d regions", region_map.getCount());
  788. } else {
  789. char *np = command;
  790. while (*np == ' ') np++; // skip indent
  791. int indent = np - command;
  792. char *ep = np;
  793. while (is_name_char(*ep)) ep++;
  794. if (*ep) { *ep++ = 0; } // set null terminator for end of name
  795. while (*ep && *ep != 'F') ep++; // look for (optional) flags
  796. if (indent > 0 && indent < 8) {
  797. auto parent = load_stack[indent - 1];
  798. if (parent) {
  799. auto old = region_map.findByName(np);
  800. auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists)
  801. if (nw) {
  802. nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr
  803. load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's
  804. }
  805. }
  806. }
  807. reply[0] = 0;
  808. }
  809. return;
  810. }
  811. while (*command == ' ') command++; // skip leading spaces
  812. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  813. memcpy(reply, command, 3); // reflect the prefix back
  814. reply += 3;
  815. command += 3;
  816. }
  817. // handle ACL related commands
  818. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  819. char* hex = &command[8];
  820. char* sp = strchr(hex, ' '); // look for separator char
  821. if (sp == NULL) {
  822. strcpy(reply, "Err - bad params");
  823. } else {
  824. *sp++ = 0; // replace space with null terminator
  825. uint8_t pubkey[PUB_KEY_SIZE];
  826. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  827. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  828. uint8_t perms = atoi(sp);
  829. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  830. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  831. strcpy(reply, "OK");
  832. } else {
  833. strcpy(reply, "Err - invalid params");
  834. }
  835. } else {
  836. strcpy(reply, "Err - bad pubkey");
  837. }
  838. }
  839. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  840. Serial.println("ACL:");
  841. for (int i = 0; i < acl.getNumClients(); i++) {
  842. auto c = acl.getClientByIdx(i);
  843. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  844. Serial.printf("%02X ", c->permissions);
  845. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  846. Serial.printf("\n");
  847. }
  848. reply[0] = 0;
  849. } else if (memcmp(command, "region", 6) == 0) {
  850. reply[0] = 0;
  851. const char* parts[4];
  852. int n = mesh::Utils::parseTextParts(command, parts, 4, ' ');
  853. if (n == 1 && sender_timestamp == 0) {
  854. region_map.exportTo(Serial);
  855. } else if (n >= 2 && strcmp(parts[1], "load") == 0) {
  856. temp_map.resetFrom(region_map); // rebuild regions in a temp instance
  857. memset(load_stack, 0, sizeof(load_stack));
  858. load_stack[0] = &temp_map.getWildcard();
  859. region_load_active = true;
  860. } else if (n >= 2 && strcmp(parts[1], "save") == 0) {
  861. _prefs.discovery_mod_timestamp = rtc_clock.getCurrentTime(); // this node is now 'modified' (for discovery info)
  862. savePrefs();
  863. bool success = region_map.save(_fs);
  864. strcpy(reply, success ? "OK" : "Err - save failed");
  865. } else if (n >= 3 && strcmp(parts[1], "allowf") == 0) {
  866. auto region = strcmp(parts[2], "*") == 0 ? &region_map.getWildcard() : region_map.findByNamePrefix(parts[2]);
  867. if (region) {
  868. region->flags &= ~REGION_DENY_FLOOD;
  869. strcpy(reply, "OK");
  870. } else {
  871. strcpy(reply, "Err - unknown region");
  872. }
  873. } else if (n >= 3 && strcmp(parts[1], "denyf") == 0) {
  874. auto region = strcmp(parts[2], "*") == 0 ? &region_map.getWildcard() : region_map.findByNamePrefix(parts[2]);
  875. if (region) {
  876. region->flags |= REGION_DENY_FLOOD;
  877. strcpy(reply, "OK");
  878. } else {
  879. strcpy(reply, "Err - unknown region");
  880. }
  881. } else if (n >= 3 && strcmp(parts[1], "get") == 0) {
  882. auto region = region_map.findByNamePrefix(parts[2]);
  883. if (region) {
  884. sprintf(reply, " %s %s", region->name, (region->flags & REGION_DENY_FLOOD) ? "" : "F");
  885. } else {
  886. strcpy(reply, "Err - unknown region");
  887. }
  888. } else if (n >= 3 && strcmp(parts[1], "home") == 0) {
  889. auto home = strcmp(parts[2], "*") == 0 ? &region_map.getWildcard() : region_map.findByNamePrefix(parts[2]);
  890. if (home) {
  891. region_map.setHomeRegion(home);
  892. sprintf(reply, " home is now %s", home->name);
  893. } else {
  894. strcpy(reply, "Err - unknown region");
  895. }
  896. } else if (n == 2 && strcmp(parts[1], "home") == 0) {
  897. auto home = region_map.getHomeRegion();
  898. sprintf(reply, " home is %s", home ? home->name : "*");
  899. } else {
  900. strcpy(reply, "Err - ??");
  901. }
  902. } else{
  903. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  904. }
  905. }
  906. void MyMesh::loop() {
  907. #ifdef WITH_BRIDGE
  908. bridge.loop();
  909. #endif
  910. mesh::Mesh::loop();
  911. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  912. mesh::Packet *pkt = createSelfAdvert();
  913. if (pkt) sendFlood(pkt);
  914. updateFloodAdvertTimer(); // schedule next flood advert
  915. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  916. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  917. mesh::Packet *pkt = createSelfAdvert();
  918. if (pkt) sendZeroHop(pkt);
  919. updateAdvertTimer(); // schedule next local advert
  920. }
  921. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  922. set_radio_at = 0; // clear timer
  923. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  924. MESH_DEBUG_PRINTLN("Temp radio params");
  925. }
  926. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  927. revert_radio_at = 0; // clear timer
  928. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  929. MESH_DEBUG_PRINTLN("Radio params restored");
  930. }
  931. // is pending dirty contacts write needed?
  932. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  933. acl.save(_fs);
  934. dirty_contacts_expiry = 0;
  935. }
  936. // update uptime
  937. uint32_t now = millis();
  938. uptime_millis += now - last_millis;
  939. last_millis = now;
  940. }