MyMesh.cpp 40 KB

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