MyMesh.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  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 2
  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 REQ_TYPE_GET_OWNER_INFO 0x07 // FIRMWARE_VER_LEVEL >= 2
  44. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  45. #define ANON_REQ_TYPE_REGIONS 0x01
  46. #define ANON_REQ_TYPE_OWNER 0x02
  47. #define ANON_REQ_TYPE_BASIC 0x03 // just remote clock
  48. #define CLI_REPLY_DELAY_MILLIS 600
  49. #define LAZY_CONTACTS_WRITE_DELAY 5000
  50. void MyMesh::putNeighbour(const mesh::Identity &id, uint32_t timestamp, float snr) {
  51. #if MAX_NEIGHBOURS // check if neighbours enabled
  52. // find existing neighbour, else use least recently updated
  53. uint32_t oldest_timestamp = 0xFFFFFFFF;
  54. NeighbourInfo *neighbour = &neighbours[0];
  55. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  56. // if neighbour already known, we should update it
  57. if (id.matches(neighbours[i].id)) {
  58. neighbour = &neighbours[i];
  59. break;
  60. }
  61. // otherwise we should update the least recently updated neighbour
  62. if (neighbours[i].heard_timestamp < oldest_timestamp) {
  63. neighbour = &neighbours[i];
  64. oldest_timestamp = neighbour->heard_timestamp;
  65. }
  66. }
  67. // update neighbour info
  68. neighbour->id = id;
  69. neighbour->advert_timestamp = timestamp;
  70. neighbour->heard_timestamp = getRTCClock()->getCurrentTime();
  71. neighbour->snr = (int8_t)(snr * 4);
  72. #endif
  73. }
  74. uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood) {
  75. ClientInfo* client = NULL;
  76. if (data[0] == 0) { // blank password, just check if sender is in ACL
  77. client = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
  78. if (client == NULL) {
  79. #if MESH_DEBUG
  80. MESH_DEBUG_PRINTLN("Login, sender not in ACL");
  81. #endif
  82. }
  83. }
  84. if (client == NULL) {
  85. uint8_t perms;
  86. if (strcmp((char *)data, _prefs.password) == 0) { // check for valid admin password
  87. perms = PERM_ACL_ADMIN;
  88. } else if (strcmp((char *)data, _prefs.guest_password) == 0) { // check guest password
  89. perms = PERM_ACL_GUEST;
  90. } else {
  91. #if MESH_DEBUG
  92. MESH_DEBUG_PRINTLN("Invalid password: %s", data);
  93. #endif
  94. return 0;
  95. }
  96. client = acl.putClient(sender, 0); // add to contacts (if not already known)
  97. if (sender_timestamp <= client->last_timestamp) {
  98. MESH_DEBUG_PRINTLN("Possible login replay attack!");
  99. return 0; // FATAL: client table is full -OR- replay attack
  100. }
  101. MESH_DEBUG_PRINTLN("Login success!");
  102. client->last_timestamp = sender_timestamp;
  103. client->last_activity = getRTCClock()->getCurrentTime();
  104. client->permissions &= ~0x03;
  105. client->permissions |= perms;
  106. memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
  107. if (perms != PERM_ACL_GUEST) { // keep number of FS writes to a minimum
  108. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  109. }
  110. }
  111. if (is_flood) {
  112. client->out_path_len = OUT_PATH_UNKNOWN; // need to rediscover out_path
  113. }
  114. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  115. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  116. reply_data[4] = RESP_SERVER_LOGIN_OK;
  117. reply_data[5] = 0; // Legacy: was recommended keep-alive interval (secs / 16)
  118. reply_data[6] = client->isAdmin() ? 1 : 0;
  119. reply_data[7] = client->permissions;
  120. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  121. reply_data[12] = FIRMWARE_VER_LEVEL; // New field
  122. return 13; // reply length
  123. }
  124. uint8_t MyMesh::handleAnonRegionsReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
  125. if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
  126. // request data has: {reply-path-len}{reply-path}
  127. reply_path_len = *data & 63;
  128. reply_path_hash_size = (*data >> 6) + 1;
  129. data++;
  130. memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size);
  131. // data += (uint8_t)reply_path_len * reply_path_hash_size;
  132. memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
  133. uint32_t now = getRTCClock()->getCurrentTime();
  134. memcpy(&reply_data[4], &now, 4); // include our clock (for easy clock sync, and packet hash uniqueness)
  135. return 8 + region_map.exportNamesTo((char *) &reply_data[8], sizeof(reply_data) - 12, REGION_DENY_FLOOD); // reply length
  136. }
  137. return 0;
  138. }
  139. uint8_t MyMesh::handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
  140. if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
  141. // request data has: {reply-path-len}{reply-path}
  142. reply_path_len = *data & 63;
  143. reply_path_hash_size = (*data >> 6) + 1;
  144. data++;
  145. memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size);
  146. // data += (uint8_t)reply_path_len * reply_path_hash_size;
  147. memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
  148. uint32_t now = getRTCClock()->getCurrentTime();
  149. memcpy(&reply_data[4], &now, 4); // include our clock (for easy clock sync, and packet hash uniqueness)
  150. sprintf((char *) &reply_data[8], "%s\n%s", _prefs.node_name, _prefs.owner_info);
  151. return 8 + strlen((char *) &reply_data[8]); // reply length
  152. }
  153. return 0;
  154. }
  155. uint8_t MyMesh::handleAnonClockReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
  156. if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
  157. // request data has: {reply-path-len}{reply-path}
  158. reply_path_len = *data & 63;
  159. reply_path_hash_size = (*data >> 6) + 1;
  160. data++;
  161. memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size);
  162. // data += (uint8_t)reply_path_len * reply_path_hash_size;
  163. memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
  164. uint32_t now = getRTCClock()->getCurrentTime();
  165. memcpy(&reply_data[4], &now, 4); // include our clock (for easy clock sync, and packet hash uniqueness)
  166. reply_data[8] = 0; // features
  167. #ifdef WITH_RS232_BRIDGE
  168. reply_data[8] |= 0x01; // is bridge, type UART
  169. #elif WITH_ESPNOW_BRIDGE
  170. reply_data[8] |= 0x03; // is bridge, type ESP-NOW
  171. #endif
  172. if (_prefs.disable_fwd) { // is this repeater currently disabled
  173. reply_data[8] |= 0x80; // is disabled
  174. }
  175. // TODO: add some kind of moving-window utilisation metric, so can query 'how busy' is this repeater
  176. return 9; // reply length
  177. }
  178. return 0;
  179. }
  180. int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) {
  181. // uint32_t now = getRTCClock()->getCurrentTimeUnique();
  182. // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  183. memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  184. if (payload[0] == REQ_TYPE_GET_STATUS) { // guests can also access this now
  185. RepeaterStats stats;
  186. stats.batt_milli_volts = board.getBattMilliVolts();
  187. stats.curr_tx_queue_len = _mgr->getOutboundTotal();
  188. stats.noise_floor = (int16_t)_radio->getNoiseFloor();
  189. stats.last_rssi = (int16_t)radio_driver.getLastRSSI();
  190. stats.n_packets_recv = radio_driver.getPacketsRecv();
  191. stats.n_packets_sent = radio_driver.getPacketsSent();
  192. stats.total_air_time_secs = getTotalAirTime() / 1000;
  193. stats.total_up_time_secs = uptime_millis / 1000;
  194. stats.n_sent_flood = getNumSentFlood();
  195. stats.n_sent_direct = getNumSentDirect();
  196. stats.n_recv_flood = getNumRecvFlood();
  197. stats.n_recv_direct = getNumRecvDirect();
  198. stats.err_events = _err_flags;
  199. stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
  200. stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
  201. stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
  202. stats.total_rx_air_time_secs = getReceiveAirTime() / 1000;
  203. stats.n_recv_errors = radio_driver.getPacketsRecvErrors();
  204. memcpy(&reply_data[4], &stats, sizeof(stats));
  205. return 4 + sizeof(stats); // reply_len
  206. }
  207. if (payload[0] == REQ_TYPE_GET_TELEMETRY_DATA) {
  208. uint8_t perm_mask = ~(payload[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions
  209. telemetry.reset();
  210. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  211. // query other sensors -- target specific
  212. if ((sender->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) {
  213. perm_mask = 0x00; // just base telemetry allowed
  214. }
  215. sensors.querySensors(perm_mask, telemetry);
  216. // This default temperature will be overridden by external sensors (if any)
  217. float temperature = board.getMCUTemperature();
  218. if(!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN
  219. telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature
  220. }
  221. uint8_t tlen = telemetry.getSize();
  222. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  223. return 4 + tlen; // reply_len
  224. }
  225. if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) {
  226. uint8_t res1 = payload[1]; // reserved for future (extra query params)
  227. uint8_t res2 = payload[2];
  228. if (res1 == 0 && res2 == 0) {
  229. uint8_t ofs = 4;
  230. for (int i = 0; i < acl.getNumClients() && ofs + 7 <= sizeof(reply_data) - 4; i++) {
  231. auto c = acl.getClientByIdx(i);
  232. if (c->permissions == 0) continue; // skip deleted entries
  233. memcpy(&reply_data[ofs], c->id.pub_key, 6); ofs += 6; // just 6-byte pub_key prefix
  234. reply_data[ofs++] = c->permissions;
  235. }
  236. return ofs;
  237. }
  238. }
  239. if (payload[0] == REQ_TYPE_GET_NEIGHBOURS) {
  240. uint8_t request_version = payload[1];
  241. if (request_version == 0) {
  242. // reply data offset (after response sender_timestamp/tag)
  243. int reply_offset = 4;
  244. // get request params
  245. uint8_t count = payload[2]; // how many neighbours to fetch (0-255)
  246. uint16_t offset;
  247. memcpy(&offset, &payload[3], 2); // offset from start of neighbours list (0-65535)
  248. 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
  249. uint8_t pubkey_prefix_length = payload[6]; // how many bytes of neighbour pub key we want
  250. // we also send a 4 byte random blob in payload[7...10] to help packet uniqueness
  251. 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);
  252. // clamp pub key prefix length to max pub key length
  253. if(pubkey_prefix_length > PUB_KEY_SIZE){
  254. pubkey_prefix_length = PUB_KEY_SIZE;
  255. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS invalid pubkey_prefix_length=%d clamping to %d", pubkey_prefix_length, PUB_KEY_SIZE);
  256. }
  257. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  258. int16_t neighbours_count = 0;
  259. #if MAX_NEIGHBOURS
  260. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  261. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  262. auto neighbour = &neighbours[i];
  263. if (neighbour->heard_timestamp > 0) {
  264. sorted_neighbours[neighbours_count] = neighbour;
  265. neighbours_count++;
  266. }
  267. }
  268. // sort neighbours based on order
  269. if (order_by == 0) {
  270. // sort by newest to oldest
  271. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting newest to oldest");
  272. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  273. return a->heard_timestamp > b->heard_timestamp; // desc
  274. });
  275. } else if (order_by == 1) {
  276. // sort by oldest to newest
  277. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting oldest to newest");
  278. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  279. return a->heard_timestamp < b->heard_timestamp; // asc
  280. });
  281. } else if (order_by == 2) {
  282. // sort by strongest to weakest
  283. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting strongest to weakest");
  284. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  285. return a->snr > b->snr; // desc
  286. });
  287. } else if (order_by == 3) {
  288. // sort by weakest to strongest
  289. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting weakest to strongest");
  290. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  291. return a->snr < b->snr; // asc
  292. });
  293. }
  294. #endif
  295. // build results buffer
  296. int results_count = 0;
  297. int results_offset = 0;
  298. uint8_t results_buffer[130];
  299. for(int index = 0; index < count && index + offset < neighbours_count; index++){
  300. // stop if we can't fit another entry in results
  301. int entry_size = pubkey_prefix_length + 4 + 1;
  302. if(results_offset + entry_size > sizeof(results_buffer)){
  303. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS no more entries can fit in results buffer");
  304. break;
  305. }
  306. #if MAX_NEIGHBOURS
  307. // add next neighbour to results
  308. auto neighbour = sorted_neighbours[index + offset];
  309. uint32_t heard_seconds_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  310. memcpy(&results_buffer[results_offset], neighbour->id.pub_key, pubkey_prefix_length); results_offset += pubkey_prefix_length;
  311. memcpy(&results_buffer[results_offset], &heard_seconds_ago, 4); results_offset += 4;
  312. memcpy(&results_buffer[results_offset], &neighbour->snr, 1); results_offset += 1;
  313. results_count++;
  314. #endif
  315. }
  316. // build reply
  317. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS neighbours_count=%d results_count=%d", neighbours_count, results_count);
  318. memcpy(&reply_data[reply_offset], &neighbours_count, 2); reply_offset += 2;
  319. memcpy(&reply_data[reply_offset], &results_count, 2); reply_offset += 2;
  320. memcpy(&reply_data[reply_offset], &results_buffer, results_offset); reply_offset += results_offset;
  321. return reply_offset;
  322. }
  323. } else if (payload[0] == REQ_TYPE_GET_OWNER_INFO) {
  324. sprintf((char *) &reply_data[4], "%s\n%s\n%s", FIRMWARE_VERSION, _prefs.node_name, _prefs.owner_info);
  325. return 4 + strlen((char *) &reply_data[4]);
  326. }
  327. return 0; // unknown command
  328. }
  329. mesh::Packet *MyMesh::createSelfAdvert() {
  330. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  331. uint8_t app_data_len = _cli.buildAdvertData(ADV_TYPE_REPEATER, app_data);
  332. return createAdvert(self_id, app_data, app_data_len);
  333. }
  334. File MyMesh::openAppend(const char *fname) {
  335. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  336. return _fs->open(fname, FILE_O_WRITE);
  337. #elif defined(RP2040_PLATFORM)
  338. return _fs->open(fname, "a");
  339. #else
  340. return _fs->open(fname, "a", true);
  341. #endif
  342. }
  343. static uint8_t max_loop_minimal[] = { 0, /* 1-byte */ 4, /* 2-byte */ 2, /* 3-byte */ 1 };
  344. static uint8_t max_loop_moderate[] = { 0, /* 1-byte */ 2, /* 2-byte */ 1, /* 3-byte */ 1 };
  345. static uint8_t max_loop_strict[] = { 0, /* 1-byte */ 1, /* 2-byte */ 1, /* 3-byte */ 1 };
  346. bool MyMesh::isLooped(const mesh::Packet* packet, const uint8_t max_counters[]) {
  347. uint8_t hash_size = packet->getPathHashSize();
  348. uint8_t hash_count = packet->getPathHashCount();
  349. uint8_t n = 0;
  350. const uint8_t* path = packet->path;
  351. while (hash_count > 0) { // count how many times this node is already in the path
  352. if (self_id.isHashMatch(path, hash_size)) n++;
  353. hash_count--;
  354. path += hash_size;
  355. }
  356. return n >= max_counters[hash_size];
  357. }
  358. bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
  359. if (_prefs.disable_fwd) return false;
  360. if (packet->isRouteFlood() && packet->getPathHashCount() >= _prefs.flood_max) return false;
  361. if (packet->isRouteFlood() && recv_pkt_region == NULL) {
  362. MESH_DEBUG_PRINTLN("allowPacketForward: unknown transport code, or wildcard not allowed for FLOOD packet");
  363. return false;
  364. }
  365. if (packet->isRouteFlood() && _prefs.loop_detect != LOOP_DETECT_OFF) {
  366. const uint8_t* maximums;
  367. if (_prefs.loop_detect == LOOP_DETECT_MINIMAL) {
  368. maximums = max_loop_minimal;
  369. } else if (_prefs.loop_detect == LOOP_DETECT_MODERATE) {
  370. maximums = max_loop_moderate;
  371. } else {
  372. maximums = max_loop_strict;
  373. }
  374. if (isLooped(packet, maximums)) {
  375. MESH_DEBUG_PRINTLN("allowPacketForward: FLOOD packet loop detected!");
  376. return false;
  377. }
  378. }
  379. return true;
  380. }
  381. const char *MyMesh::getLogDateTime() {
  382. static char tmp[32];
  383. uint32_t now = getRTCClock()->getCurrentTime();
  384. DateTime dt = DateTime(now);
  385. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
  386. dt.year());
  387. return tmp;
  388. }
  389. void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
  390. #if MESH_PACKET_LOGGING
  391. Serial.print(getLogDateTime());
  392. Serial.print(" RAW: ");
  393. mesh::Utils::printHex(Serial, raw, len);
  394. Serial.println();
  395. #endif
  396. }
  397. void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
  398. #ifdef WITH_BRIDGE
  399. if (_prefs.bridge_pkt_src == 1) {
  400. bridge.sendPacket(pkt);
  401. }
  402. #endif
  403. #ifdef WITH_MQTT_UPLINK
  404. mqtt.publishPacket(*pkt, false, (int)_radio->getLastRSSI(), _radio->getLastSNR());
  405. #endif
  406. if (_logging) {
  407. File f = openAppend(PACKET_LOG_FILE);
  408. if (f) {
  409. f.print(getLogDateTime());
  410. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
  411. pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  412. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
  413. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  414. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  415. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  416. } else {
  417. f.printf("\n");
  418. }
  419. f.close();
  420. }
  421. }
  422. }
  423. void MyMesh::logTx(mesh::Packet *pkt, int len) {
  424. #ifdef WITH_BRIDGE
  425. if (_prefs.bridge_pkt_src == 0) {
  426. bridge.sendPacket(pkt);
  427. }
  428. #endif
  429. #ifdef WITH_MQTT_UPLINK
  430. mqtt.publishPacket(*pkt, true, (int)_radio->getLastRSSI(), _radio->getLastSNR());
  431. #endif
  432. if (_logging) {
  433. File f = openAppend(PACKET_LOG_FILE);
  434. if (f) {
  435. f.print(getLogDateTime());
  436. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  437. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  438. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  439. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  440. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  441. } else {
  442. f.printf("\n");
  443. }
  444. f.close();
  445. }
  446. }
  447. }
  448. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  449. if (_logging) {
  450. File f = openAppend(PACKET_LOG_FILE);
  451. if (f) {
  452. f.print(getLogDateTime());
  453. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  454. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  455. f.close();
  456. }
  457. }
  458. }
  459. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  460. if (_prefs.rx_delay_base <= 0.0f) return 0;
  461. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  462. }
  463. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  464. uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.tx_delay_factor);
  465. return getRNG()->nextInt(0, 5*t + 1);
  466. }
  467. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  468. uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  469. return getRNG()->nextInt(0, 5*t + 1);
  470. }
  471. bool MyMesh::filterRecvFloodPacket(mesh::Packet* pkt) {
  472. // just try to determine region for packet (apply later in allowPacketForward())
  473. if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
  474. recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
  475. } else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
  476. if (region_map.getWildcard().flags & REGION_DENY_FLOOD) {
  477. recv_pkt_region = NULL;
  478. } else {
  479. recv_pkt_region = &region_map.getWildcard();
  480. }
  481. } else {
  482. recv_pkt_region = NULL;
  483. }
  484. // do normal processing
  485. return false;
  486. }
  487. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  488. uint8_t *data, size_t len) {
  489. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  490. // client (unknown at this stage)
  491. uint32_t timestamp;
  492. memcpy(&timestamp, data, 4);
  493. data[len] = 0; // ensure null terminator
  494. uint8_t reply_len;
  495. reply_path_len = -1;
  496. if (data[4] == 0 || data[4] >= ' ') { // is password, ie. a login request
  497. reply_len = handleLoginReq(sender, secret, timestamp, &data[4], packet->isRouteFlood());
  498. } else if (data[4] == ANON_REQ_TYPE_REGIONS && packet->isRouteDirect()) {
  499. reply_len = handleAnonRegionsReq(sender, timestamp, &data[5]);
  500. } else if (data[4] == ANON_REQ_TYPE_OWNER && packet->isRouteDirect()) {
  501. reply_len = handleAnonOwnerReq(sender, timestamp, &data[5]);
  502. } else if (data[4] == ANON_REQ_TYPE_BASIC && packet->isRouteDirect()) {
  503. reply_len = handleAnonClockReq(sender, timestamp, &data[5]);
  504. } else {
  505. reply_len = 0; // unknown/invalid request type
  506. }
  507. if (reply_len == 0) return; // invalid request
  508. if (packet->isRouteFlood()) {
  509. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  510. mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
  511. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  512. if (path) sendFlood(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  513. } else if (reply_path_len < 0) {
  514. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  515. if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  516. } else {
  517. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  518. uint8_t path_len = ((reply_path_hash_size - 1) << 6) | (reply_path_len & 63);
  519. if (reply) sendDirect(reply, reply_path, path_len, SERVER_RESPONSE_DELAY);
  520. }
  521. }
  522. }
  523. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  524. int n = 0;
  525. for (int i = 0; i < acl.getNumClients(); i++) {
  526. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  527. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  528. }
  529. }
  530. return n;
  531. }
  532. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  533. int i = matching_peer_indexes[peer_idx];
  534. if (i >= 0 && i < acl.getNumClients()) {
  535. // lookup pre-calculated shared_secret
  536. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  537. } else {
  538. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  539. }
  540. }
  541. static bool isShare(const mesh::Packet *packet) {
  542. if (packet->hasTransportCodes()) {
  543. return packet->transport_codes[0] == 0 && packet->transport_codes[1] == 0; // codes { 0, 0 } means 'send to nowhere'
  544. }
  545. return false;
  546. }
  547. void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
  548. const uint8_t *app_data, size_t app_data_len) {
  549. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  550. // if this a zero hop advert (and not via 'Share'), add it to neighbours
  551. if (packet->path_len == 0 && !isShare(packet)) {
  552. AdvertDataParser parser(app_data, app_data_len);
  553. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  554. putNeighbour(id, timestamp, packet->getSNR());
  555. }
  556. }
  557. }
  558. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  559. uint8_t *data, size_t len) {
  560. int i = matching_peer_indexes[sender_idx];
  561. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  562. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  563. return;
  564. }
  565. ClientInfo* client = acl.getClientByIdx(i);
  566. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  567. uint32_t timestamp;
  568. memcpy(&timestamp, data, 4);
  569. if (timestamp > client->last_timestamp) { // prevent replay attacks
  570. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  571. if (reply_len == 0) return; // invalid command
  572. client->last_timestamp = timestamp;
  573. client->last_activity = getRTCClock()->getCurrentTime();
  574. if (packet->isRouteFlood()) {
  575. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  576. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  577. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  578. if (path) sendFlood(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  579. } else {
  580. mesh::Packet *reply =
  581. createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  582. if (reply) {
  583. if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
  584. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  585. } else {
  586. sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  587. }
  588. }
  589. }
  590. } else {
  591. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  592. }
  593. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->isAdmin()) { // a CLI command
  594. uint32_t sender_timestamp;
  595. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  596. uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
  597. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  598. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  599. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  600. bool is_retry = (sender_timestamp == client->last_timestamp);
  601. client->last_timestamp = sender_timestamp;
  602. client->last_activity = getRTCClock()->getCurrentTime();
  603. // len can be > original length, but 'text' will be padded with zeroes
  604. data[len] = 0; // need to make a C string again, with null terminator
  605. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  606. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
  607. // to sender that we got it
  608. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  609. PUB_KEY_SIZE);
  610. mesh::Packet *ack = createAck(ack_hash);
  611. if (ack) {
  612. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  613. sendFlood(ack, TXT_ACK_DELAY, packet->getPathHashSize());
  614. } else {
  615. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  616. }
  617. }
  618. }
  619. uint8_t temp[166];
  620. char *command = (char *)&data[5];
  621. char *reply = (char *)&temp[5];
  622. if (is_retry) {
  623. *reply = 0;
  624. } else {
  625. handleCommand(sender_timestamp, command, reply);
  626. }
  627. int text_len = strlen(reply);
  628. if (text_len > 0) {
  629. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  630. if (timestamp == sender_timestamp) {
  631. // WORKAROUND: the two timestamps need to be different, in the CLI view
  632. timestamp++;
  633. }
  634. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  635. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  636. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  637. if (reply) {
  638. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  639. sendFlood(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize());
  640. } else {
  641. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  642. }
  643. }
  644. }
  645. } else {
  646. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  647. }
  648. }
  649. }
  650. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  651. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  652. // TODO: prevent replay attacks
  653. int i = matching_peer_indexes[sender_idx];
  654. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  655. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  656. auto client = acl.getClientByIdx(i);
  657. // store a copy of path, for sendDirect()
  658. client->out_path_len = mesh::Packet::copyPath(client->out_path, path, path_len);
  659. client->last_activity = getRTCClock()->getCurrentTime();
  660. } else {
  661. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  662. }
  663. // NOTE: no reciprocal path send!!
  664. return false;
  665. }
  666. #define CTL_TYPE_NODE_DISCOVER_REQ 0x80
  667. #define CTL_TYPE_NODE_DISCOVER_RESP 0x90
  668. void MyMesh::onControlDataRecv(mesh::Packet* packet) {
  669. uint8_t type = packet->payload[0] & 0xF0; // just test upper 4 bits
  670. if (type == CTL_TYPE_NODE_DISCOVER_REQ && packet->payload_len >= 6
  671. && !_prefs.disable_fwd && discover_limiter.allow(rtc_clock.getCurrentTime())
  672. ) {
  673. int i = 1;
  674. uint8_t filter = packet->payload[i++];
  675. uint32_t tag;
  676. memcpy(&tag, &packet->payload[i], 4); i += 4;
  677. uint32_t since;
  678. if (packet->payload_len >= i+4) { // optional since field
  679. memcpy(&since, &packet->payload[i], 4); i += 4;
  680. } else {
  681. since = 0;
  682. }
  683. if ((filter & (1 << ADV_TYPE_REPEATER)) != 0 && _prefs.discovery_mod_timestamp >= since) {
  684. bool prefix_only = packet->payload[0] & 1;
  685. uint8_t data[6 + PUB_KEY_SIZE];
  686. data[0] = CTL_TYPE_NODE_DISCOVER_RESP | ADV_TYPE_REPEATER; // low 4-bits for node type
  687. data[1] = packet->_snr; // let sender know the inbound SNR ( x 4)
  688. memcpy(&data[2], &tag, 4); // include tag from request, for client to match to
  689. memcpy(&data[6], self_id.pub_key, PUB_KEY_SIZE);
  690. auto resp = createControlData(data, prefix_only ? 6 + 8 : 6 + PUB_KEY_SIZE);
  691. if (resp) {
  692. sendZeroHop(resp, getRetransmitDelay(resp)*4); // apply random delay (widened x4), as multiple nodes can respond to this
  693. }
  694. }
  695. } else if (type == CTL_TYPE_NODE_DISCOVER_RESP && packet->payload_len >= 6) {
  696. uint8_t node_type = packet->payload[0] & 0x0F;
  697. if (node_type != ADV_TYPE_REPEATER) {
  698. return;
  699. }
  700. if (packet->payload_len < 6 + PUB_KEY_SIZE) {
  701. MESH_DEBUG_PRINTLN("onControlDataRecv: DISCOVER_RESP pubkey too short: %d", (uint32_t)packet->payload_len);
  702. return;
  703. }
  704. if (pending_discover_tag == 0 || millisHasNowPassed(pending_discover_until)) {
  705. pending_discover_tag = 0;
  706. return;
  707. }
  708. uint32_t tag;
  709. memcpy(&tag, &packet->payload[2], 4);
  710. if (tag != pending_discover_tag) {
  711. return;
  712. }
  713. mesh::Identity id(&packet->payload[6]);
  714. if (id.matches(self_id)) {
  715. return;
  716. }
  717. putNeighbour(id, rtc_clock.getCurrentTime(), packet->getSNR());
  718. }
  719. }
  720. void MyMesh::sendNodeDiscoverReq() {
  721. uint8_t data[10];
  722. data[0] = CTL_TYPE_NODE_DISCOVER_REQ; // prefix_only=0
  723. data[1] = (1 << ADV_TYPE_REPEATER);
  724. getRNG()->random(&data[2], 4); // tag
  725. memcpy(&pending_discover_tag, &data[2], 4);
  726. pending_discover_until = futureMillis(60000);
  727. uint32_t since = 0;
  728. memcpy(&data[6], &since, 4);
  729. auto pkt = createControlData(data, sizeof(data));
  730. if (pkt) {
  731. sendZeroHop(pkt);
  732. }
  733. }
  734. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  735. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  736. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  737. _cli(board, rtc, sensors, acl, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4), region_map(key_store), temp_map(key_store),
  738. discover_limiter(4, 120), // max 4 every 2 minutes
  739. anon_limiter(4, 180) // max 4 every 3 minutes
  740. #if defined(WITH_RS232_BRIDGE)
  741. , bridge(&_prefs, WITH_RS232_BRIDGE, _mgr, &rtc)
  742. #endif
  743. #if defined(WITH_ESPNOW_BRIDGE)
  744. , bridge(&_prefs, _mgr, &rtc)
  745. #endif
  746. #if defined(WITH_MQTT_UPLINK)
  747. , mqtt(rtc, self_id)
  748. #endif
  749. {
  750. last_millis = 0;
  751. uptime_millis = 0;
  752. next_local_advert = next_flood_advert = 0;
  753. dirty_contacts_expiry = 0;
  754. set_radio_at = revert_radio_at = 0;
  755. _logging = false;
  756. region_load_active = false;
  757. #if MAX_NEIGHBOURS
  758. memset(neighbours, 0, sizeof(neighbours));
  759. #endif
  760. // defaults
  761. memset(&_prefs, 0, sizeof(_prefs));
  762. _prefs.airtime_factor = 1.0;
  763. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  764. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  765. _prefs.direct_tx_delay_factor = 0.3f; // was 0.2
  766. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  767. _prefs.node_lat = ADVERT_LAT;
  768. _prefs.node_lon = ADVERT_LON;
  769. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  770. _prefs.freq = LORA_FREQ;
  771. _prefs.sf = LORA_SF;
  772. _prefs.bw = LORA_BW;
  773. _prefs.cr = LORA_CR;
  774. _prefs.tx_power_dbm = LORA_TX_POWER;
  775. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  776. _prefs.flood_advert_interval = 12; // 12 hours
  777. _prefs.flood_max = 64;
  778. _prefs.interference_threshold = 0; // disabled
  779. // bridge defaults
  780. _prefs.bridge_enabled = 1; // enabled
  781. _prefs.bridge_delay = 500; // milliseconds
  782. _prefs.bridge_pkt_src = 0; // logTx
  783. _prefs.bridge_baud = 115200; // baud rate
  784. _prefs.bridge_channel = 1; // channel 1
  785. StrHelper::strncpy(_prefs.bridge_secret, "LVSITANOS", sizeof(_prefs.bridge_secret));
  786. // GPS defaults
  787. _prefs.gps_enabled = 0;
  788. _prefs.gps_interval = 0;
  789. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  790. _prefs.adc_multiplier = 0.0f; // 0.0f means use default board multiplier
  791. #if defined(USE_SX1262) || defined(USE_SX1268)
  792. #ifdef SX126X_RX_BOOSTED_GAIN
  793. _prefs.rx_boosted_gain = SX126X_RX_BOOSTED_GAIN;
  794. #else
  795. _prefs.rx_boosted_gain = 1; // enabled by default;
  796. #endif
  797. #endif
  798. pending_discover_tag = 0;
  799. pending_discover_until = 0;
  800. }
  801. void MyMesh::begin(FILESYSTEM *fs) {
  802. mesh::Mesh::begin();
  803. _fs = fs;
  804. // load persisted prefs
  805. _cli.loadPrefs(_fs);
  806. acl.load(_fs, self_id);
  807. // TODO: key_store.begin();
  808. region_map.load(_fs);
  809. #if defined(WITH_BRIDGE)
  810. if (_prefs.bridge_enabled) {
  811. bridge.begin();
  812. }
  813. #endif
  814. #if defined(WITH_MQTT_UPLINK)
  815. board.setInhibitSleep(true);
  816. mqtt.setNodeNameSource(_prefs.node_name);
  817. mqtt.setWebCommandRunner(this);
  818. mqtt.begin(_fs);
  819. #endif
  820. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  821. radio_set_tx_power(_prefs.tx_power_dbm);
  822. radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);
  823. MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s",
  824. radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled");
  825. updateAdvertTimer();
  826. updateFloodAdvertTimer();
  827. board.setAdcMultiplier(_prefs.adc_multiplier);
  828. #if ENV_INCLUDE_GPS == 1
  829. applyGpsPrefs();
  830. #endif
  831. }
  832. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  833. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  834. pending_freq = freq;
  835. pending_bw = bw;
  836. pending_sf = sf;
  837. pending_cr = cr;
  838. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  839. }
  840. bool MyMesh::formatFileSystem() {
  841. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  842. return InternalFS.format();
  843. #elif defined(RP2040_PLATFORM)
  844. return LittleFS.format();
  845. #elif defined(ESP32)
  846. return SPIFFS.format();
  847. #else
  848. #error "need to implement file system erase"
  849. return false;
  850. #endif
  851. }
  852. void MyMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
  853. mesh::Packet *pkt = createSelfAdvert();
  854. if (pkt) {
  855. if (flood) {
  856. sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1);
  857. } else {
  858. sendZeroHop(pkt, delay_millis);
  859. }
  860. } else {
  861. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  862. }
  863. }
  864. void MyMesh::updateAdvertTimer() {
  865. if (_prefs.advert_interval > 0) { // schedule local advert timer
  866. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  867. } else {
  868. next_local_advert = 0; // stop the timer
  869. }
  870. }
  871. void MyMesh::updateFloodAdvertTimer() {
  872. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  873. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  874. } else {
  875. next_flood_advert = 0; // stop the timer
  876. }
  877. }
  878. void MyMesh::dumpLogFile() {
  879. #if defined(RP2040_PLATFORM)
  880. File f = _fs->open(PACKET_LOG_FILE, "r");
  881. #else
  882. File f = _fs->open(PACKET_LOG_FILE);
  883. #endif
  884. if (f) {
  885. while (f.available()) {
  886. int c = f.read();
  887. if (c < 0) break;
  888. Serial.print((char)c);
  889. }
  890. f.close();
  891. }
  892. }
  893. void MyMesh::setTxPower(int8_t power_dbm) {
  894. radio_set_tx_power(power_dbm);
  895. }
  896. #if defined(USE_SX1262) || defined(USE_SX1268)
  897. void MyMesh::setRxBoostedGain(bool enable) {
  898. radio_driver.setRxBoostedGainMode(enable);
  899. }
  900. #endif
  901. void MyMesh::formatNeighborsReply(char *reply) {
  902. char *dp = reply;
  903. #if MAX_NEIGHBOURS
  904. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  905. int16_t neighbours_count = 0;
  906. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  907. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  908. auto neighbour = &neighbours[i];
  909. if (neighbour->heard_timestamp > 0) {
  910. sorted_neighbours[neighbours_count] = neighbour;
  911. neighbours_count++;
  912. }
  913. }
  914. // sort neighbours newest to oldest
  915. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  916. return a->heard_timestamp > b->heard_timestamp; // desc
  917. });
  918. for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
  919. NeighbourInfo *neighbour = sorted_neighbours[i];
  920. // add new line if not first item
  921. if (i > 0) *dp++ = '\n';
  922. char hex[10];
  923. // get 4 bytes of neighbour id as hex
  924. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  925. // add next neighbour
  926. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  927. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  928. while (*dp)
  929. dp++; // find end of string
  930. }
  931. #endif
  932. if (dp == reply) { // no neighbours, need empty response
  933. strcpy(dp, "-none-");
  934. dp += 6;
  935. }
  936. *dp = 0; // null terminator
  937. }
  938. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  939. #if MAX_NEIGHBOURS
  940. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  941. NeighbourInfo *neighbour = &neighbours[i];
  942. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  943. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  944. }
  945. }
  946. #endif
  947. }
  948. void MyMesh::formatStatsReply(char *reply) {
  949. StatsFormatHelper::formatCoreStats(reply, board, *_ms, _err_flags, _mgr);
  950. }
  951. void MyMesh::formatRadioStatsReply(char *reply) {
  952. StatsFormatHelper::formatRadioStats(reply, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
  953. }
  954. void MyMesh::formatPacketStatsReply(char *reply) {
  955. StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
  956. getNumRecvFlood(), getNumRecvDirect());
  957. }
  958. void MyMesh::formatMemoryReply(char *reply, size_t reply_size) {
  959. StatsFormatHelper::formatMemoryStats(reply, reply_size);
  960. }
  961. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  962. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  963. IdentityStore store(*_fs, "");
  964. #elif defined(ESP32)
  965. IdentityStore store(*_fs, "/identity");
  966. #elif defined(RP2040_PLATFORM)
  967. IdentityStore store(*_fs, "/identity");
  968. #else
  969. #error "need to define saveIdentity()"
  970. #endif
  971. store.save("_main", new_id);
  972. }
  973. void MyMesh::clearStats() {
  974. radio_driver.resetStats();
  975. resetStats();
  976. ((SimpleMeshTables *)getTables())->resetStats();
  977. }
  978. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  979. if (region_load_active) {
  980. if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
  981. region_map = temp_map; // copy over the temp instance as new current map
  982. region_load_active = false;
  983. sprintf(reply, "OK - loaded %d regions", region_map.getCount());
  984. } else {
  985. char *np = command;
  986. while (*np == ' ') np++; // skip indent
  987. int indent = np - command;
  988. char *ep = np;
  989. while (RegionMap::is_name_char(*ep)) ep++;
  990. if (*ep) { *ep++ = 0; } // set null terminator for end of name
  991. while (*ep && *ep != 'F') ep++; // look for (optional) flags
  992. if (indent > 0 && indent < 8 && strlen(np) > 0) {
  993. auto parent = load_stack[indent - 1];
  994. if (parent) {
  995. auto old = region_map.findByName(np);
  996. auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists)
  997. if (nw) {
  998. nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr
  999. load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's
  1000. }
  1001. }
  1002. }
  1003. reply[0] = 0;
  1004. }
  1005. return;
  1006. }
  1007. while (*command == ' ') command++; // skip leading spaces
  1008. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  1009. memcpy(reply, command, 3); // reflect the prefix back
  1010. reply += 3;
  1011. command += 3;
  1012. }
  1013. // handle ACL related commands
  1014. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  1015. char* hex = &command[8];
  1016. char* sp = strchr(hex, ' '); // look for separator char
  1017. if (sp == NULL) {
  1018. strcpy(reply, "Err - bad params");
  1019. } else {
  1020. *sp++ = 0; // replace space with null terminator
  1021. uint8_t pubkey[PUB_KEY_SIZE];
  1022. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  1023. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  1024. uint8_t perms = atoi(sp);
  1025. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  1026. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  1027. strcpy(reply, "OK");
  1028. } else {
  1029. strcpy(reply, "Err - invalid params");
  1030. }
  1031. } else {
  1032. strcpy(reply, "Err - bad pubkey");
  1033. }
  1034. }
  1035. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  1036. Serial.println("ACL:");
  1037. for (int i = 0; i < acl.getNumClients(); i++) {
  1038. auto c = acl.getClientByIdx(i);
  1039. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  1040. Serial.printf("%02X ", c->permissions);
  1041. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  1042. Serial.printf("\n");
  1043. }
  1044. reply[0] = 0;
  1045. } else if (memcmp(command, "region", 6) == 0) {
  1046. reply[0] = 0;
  1047. const char* parts[4];
  1048. int n = mesh::Utils::parseTextParts(command, parts, 4, ' ');
  1049. if (n == 1) {
  1050. region_map.exportTo(reply, 160);
  1051. } else if (n >= 2 && strcmp(parts[1], "load") == 0) {
  1052. temp_map.resetFrom(region_map); // rebuild regions in a temp instance
  1053. memset(load_stack, 0, sizeof(load_stack));
  1054. load_stack[0] = &temp_map.getWildcard();
  1055. region_load_active = true;
  1056. } else if (n >= 2 && strcmp(parts[1], "save") == 0) {
  1057. _prefs.discovery_mod_timestamp = rtc_clock.getCurrentTime(); // this node is now 'modified' (for discovery info)
  1058. savePrefs();
  1059. bool success = region_map.save(_fs);
  1060. strcpy(reply, success ? "OK" : "Err - save failed");
  1061. } else if (n >= 3 && strcmp(parts[1], "allowf") == 0) {
  1062. auto region = region_map.findByNamePrefix(parts[2]);
  1063. if (region) {
  1064. region->flags &= ~REGION_DENY_FLOOD;
  1065. strcpy(reply, "OK");
  1066. } else {
  1067. strcpy(reply, "Err - unknown region");
  1068. }
  1069. } else if (n >= 3 && strcmp(parts[1], "denyf") == 0) {
  1070. auto region = region_map.findByNamePrefix(parts[2]);
  1071. if (region) {
  1072. region->flags |= REGION_DENY_FLOOD;
  1073. strcpy(reply, "OK");
  1074. } else {
  1075. strcpy(reply, "Err - unknown region");
  1076. }
  1077. } else if (n >= 3 && strcmp(parts[1], "get") == 0) {
  1078. auto region = region_map.findByNamePrefix(parts[2]);
  1079. if (region) {
  1080. auto parent = region_map.findById(region->parent);
  1081. if (parent && parent->id != 0) {
  1082. sprintf(reply, " %s (%s) %s", region->name, parent->name, (region->flags & REGION_DENY_FLOOD) ? "" : "F");
  1083. } else {
  1084. sprintf(reply, " %s %s", region->name, (region->flags & REGION_DENY_FLOOD) ? "" : "F");
  1085. }
  1086. } else {
  1087. strcpy(reply, "Err - unknown region");
  1088. }
  1089. } else if (n >= 3 && strcmp(parts[1], "home") == 0) {
  1090. auto home = region_map.findByNamePrefix(parts[2]);
  1091. if (home) {
  1092. region_map.setHomeRegion(home);
  1093. sprintf(reply, " home is now %s", home->name);
  1094. } else {
  1095. strcpy(reply, "Err - unknown region");
  1096. }
  1097. } else if (n == 2 && strcmp(parts[1], "home") == 0) {
  1098. auto home = region_map.getHomeRegion();
  1099. sprintf(reply, " home is %s", home ? home->name : "*");
  1100. } else if (n >= 3 && strcmp(parts[1], "put") == 0) {
  1101. auto parent = n >= 4 ? region_map.findByNamePrefix(parts[3]) : &region_map.getWildcard();
  1102. if (parent == NULL) {
  1103. strcpy(reply, "Err - unknown parent");
  1104. } else {
  1105. auto region = region_map.putRegion(parts[2], parent->id);
  1106. if (region == NULL) {
  1107. strcpy(reply, "Err - unable to put");
  1108. } else {
  1109. strcpy(reply, "OK");
  1110. }
  1111. }
  1112. } else if (n >= 3 && strcmp(parts[1], "remove") == 0) {
  1113. auto region = region_map.findByName(parts[2]);
  1114. if (region) {
  1115. if (region_map.removeRegion(*region)) {
  1116. strcpy(reply, "OK");
  1117. } else {
  1118. strcpy(reply, "Err - not empty");
  1119. }
  1120. } else {
  1121. strcpy(reply, "Err - not found");
  1122. }
  1123. } else if (n >= 3 && strcmp(parts[1], "list") == 0) {
  1124. uint8_t mask = 0;
  1125. bool invert = false;
  1126. if (strcmp(parts[2], "allowed") == 0) {
  1127. mask = REGION_DENY_FLOOD;
  1128. invert = false; // list regions that DON'T have DENY flag
  1129. } else if (strcmp(parts[2], "denied") == 0) {
  1130. mask = REGION_DENY_FLOOD;
  1131. invert = true; // list regions that DO have DENY flag
  1132. } else {
  1133. strcpy(reply, "Err - use 'allowed' or 'denied'");
  1134. return;
  1135. }
  1136. int len = region_map.exportNamesTo(reply, 160, mask, invert);
  1137. if (len == 0) {
  1138. strcpy(reply, "-none-");
  1139. }
  1140. } else {
  1141. strcpy(reply, "Err - ??");
  1142. }
  1143. } else if (memcmp(command, "discover.neighbors", 18) == 0) {
  1144. const char* sub = command + 18;
  1145. while (*sub == ' ') sub++;
  1146. if (*sub != 0) {
  1147. strcpy(reply, "Err - discover.neighbors has no options");
  1148. } else {
  1149. sendNodeDiscoverReq();
  1150. strcpy(reply, "OK - Discover sent");
  1151. }
  1152. #ifdef WITH_MQTT_UPLINK
  1153. } else if (memcmp(command, "mqtt.owner ", 11) == 0) {
  1154. if (mqtt.setOwnerPublicKey(&command[11])) {
  1155. strcpy(reply, "OK");
  1156. } else {
  1157. strcpy(reply, "Err - owner must be 64 hex chars");
  1158. }
  1159. } else if (memcmp(command, "mqtt.email ", 11) == 0) {
  1160. if (mqtt.setOwnerEmail(&command[11])) {
  1161. strcpy(reply, "OK");
  1162. } else {
  1163. strcpy(reply, "Err - bad mqtt.email");
  1164. }
  1165. } else if (memcmp(command, "get mqtt.status", 15) == 0) {
  1166. mqtt.formatStatusReply(reply, 160);
  1167. } else if (strcmp(command, "get web.status") == 0 || strcmp(command, "get web") == 0) {
  1168. mqtt.formatWebStatusReply(reply, 160);
  1169. } else if (memcmp(command, "get wifi.status", 15) == 0) {
  1170. mqtt.formatWifiStatusReply(reply, 160);
  1171. } else if (memcmp(command, "get wifi.ssid", 13) == 0) {
  1172. sprintf(reply, "> %s", mqtt.getWifiSSID()[0] ? mqtt.getWifiSSID() : "-");
  1173. } else if (memcmp(command, "get wifi.powersaving", 20) == 0) {
  1174. sprintf(reply, "> %s", mqtt.getWifiPowerSave());
  1175. } else if (memcmp(command, "get mqtt.iata", 13) == 0) {
  1176. sprintf(reply, "> %s", mqtt.getIata());
  1177. } else if (memcmp(command, "get mqtt.owner", 14) == 0) {
  1178. sprintf(reply, "> %s", mqtt.getOwnerPublicKey()[0] ? mqtt.getOwnerPublicKey() : "-");
  1179. } else if (memcmp(command, "get mqtt.email", 14) == 0) {
  1180. sprintf(reply, "> %s", mqtt.getOwnerEmail()[0] ? mqtt.getOwnerEmail() : "-");
  1181. } else if (memcmp(command, "get mqtt.packets", 16) == 0) {
  1182. sprintf(reply, "> %s", mqtt.isPacketsEnabled() ? "on" : "off");
  1183. } else if (memcmp(command, "get mqtt.raw", 12) == 0) {
  1184. sprintf(reply, "> %s", mqtt.isRawEnabled() ? "on" : "off");
  1185. } else if (memcmp(command, "get mqtt.tx", 11) == 0) {
  1186. sprintf(reply, "> %s", mqtt.isTxEnabled() ? "on" : "off");
  1187. } else if (memcmp(command, "get mqtt.eastmesh-au", 20) == 0 || memcmp(command, "get mqtt.eastmesh.au", 20) == 0) {
  1188. sprintf(reply, "> %s", mqtt.isEndpointEnabled(0x01) ? "on" : "off");
  1189. } else if (memcmp(command, "get mqtt.letsmesh-eu", 21) == 0 || memcmp(command, "get mqtt.letsmesh.eu", 21) == 0) {
  1190. sprintf(reply, "> %s", mqtt.isEndpointEnabled(0x02) ? "on" : "off");
  1191. } else if (memcmp(command, "get mqtt.letsmesh-us", 21) == 0 || memcmp(command, "get mqtt.letsmesh.us", 21) == 0) {
  1192. sprintf(reply, "> %s", mqtt.isEndpointEnabled(0x04) ? "on" : "off");
  1193. } else if (memcmp(command, "set mqtt.tx ", 12) == 0) {
  1194. mqtt.setTxEnabled(memcmp(&command[12], "on", 2) == 0);
  1195. strcpy(reply, "OK");
  1196. } else if (memcmp(command, "set web ", 8) == 0) {
  1197. mqtt.setWebEnabled(memcmp(&command[8], "on", 2) == 0);
  1198. strcpy(reply, "OK");
  1199. } else if (memcmp(command, "set.web ", 8) == 0) {
  1200. mqtt.setWebEnabled(memcmp(&command[8], "on", 2) == 0);
  1201. strcpy(reply, "OK");
  1202. } else if (memcmp(command, "set wifi.ssid ", 14) == 0) {
  1203. if (mqtt.setWifiSSID(&command[14])) {
  1204. strcpy(reply, "OK");
  1205. } else {
  1206. strcpy(reply, "Err - bad wifi.ssid");
  1207. }
  1208. } else if (memcmp(command, "set wifi.pwd ", 13) == 0) {
  1209. if (mqtt.setWifiPassword(&command[13])) {
  1210. strcpy(reply, "OK");
  1211. } else {
  1212. strcpy(reply, "Err - bad wifi.pwd");
  1213. }
  1214. } else if (memcmp(command, "set wifi.powersaving ", 21) == 0) {
  1215. if (mqtt.setWifiPowerSave(&command[21])) {
  1216. strcpy(reply, "OK");
  1217. } else {
  1218. strcpy(reply, "Err - use none|min|max");
  1219. }
  1220. } else if (memcmp(command, "set mqtt.iata ", 14) == 0) {
  1221. if (mqtt.setIata(&command[14])) {
  1222. strcpy(reply, "OK");
  1223. } else {
  1224. strcpy(reply, "Err - bad mqtt.iata");
  1225. }
  1226. } else if (memcmp(command, "set mqtt.owner ", 15) == 0) {
  1227. if (mqtt.setOwnerPublicKey(&command[15])) {
  1228. strcpy(reply, "OK");
  1229. } else {
  1230. strcpy(reply, "Err - owner must be 64 hex chars");
  1231. }
  1232. } else if (memcmp(command, "set mqtt.email ", 15) == 0) {
  1233. if (mqtt.setOwnerEmail(&command[15])) {
  1234. strcpy(reply, "OK");
  1235. } else {
  1236. strcpy(reply, "Err - bad mqtt.email");
  1237. }
  1238. } else if (memcmp(command, "set mqtt.packets ", 17) == 0) {
  1239. mqtt.setPacketsEnabled(memcmp(&command[17], "on", 2) == 0);
  1240. strcpy(reply, "OK");
  1241. } else if (memcmp(command, "set mqtt.raw ", 13) == 0) {
  1242. mqtt.setRawEnabled(memcmp(&command[13], "on", 2) == 0);
  1243. strcpy(reply, "OK");
  1244. } else if (memcmp(command, "set mqtt.eastmesh-au ", 21) == 0 || memcmp(command, "set mqtt.eastmesh.au ", 21) == 0) {
  1245. mqtt.setEndpointEnabled(0x01, memcmp(&command[21], "on", 2) == 0);
  1246. strcpy(reply, "OK");
  1247. } else if (memcmp(command, "set mqtt.letsmesh-eu ", 21) == 0 || memcmp(command, "set mqtt.letsmesh.eu ", 21) == 0) {
  1248. mqtt.setEndpointEnabled(0x02, memcmp(&command[21], "on", 2) == 0);
  1249. strcpy(reply, "OK");
  1250. } else if (memcmp(command, "set mqtt.letsmesh-us ", 21) == 0 || memcmp(command, "set mqtt.letsmesh.us ", 21) == 0) {
  1251. mqtt.setEndpointEnabled(0x04, memcmp(&command[21], "on", 2) == 0);
  1252. strcpy(reply, "OK");
  1253. #endif
  1254. } else{
  1255. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  1256. }
  1257. }
  1258. void MyMesh::runWebCommand(const char* command, char* reply, size_t reply_size) {
  1259. if (reply_size == 0) {
  1260. return;
  1261. }
  1262. reply[0] = 0;
  1263. if (command == nullptr) {
  1264. strncpy(reply, "Err - empty command", reply_size - 1);
  1265. reply[reply_size - 1] = 0;
  1266. return;
  1267. }
  1268. auto matches_exact = [command](const char* candidate) -> bool {
  1269. return strcmp(command, candidate) == 0;
  1270. };
  1271. auto matches_prefix = [command](const char* candidate) -> bool {
  1272. size_t len = strlen(candidate);
  1273. return strncmp(command, candidate, len) == 0;
  1274. };
  1275. bool allowed =
  1276. matches_exact("get mqtt.status") ||
  1277. matches_exact("get web.status") ||
  1278. matches_exact("get web") ||
  1279. matches_exact("advert") ||
  1280. matches_exact("reboot") ||
  1281. matches_exact("start ota") ||
  1282. matches_exact("get wifi.status") ||
  1283. matches_exact("get wifi.powersaving") ||
  1284. matches_exact("memory") ||
  1285. matches_exact("get mqtt.iata") ||
  1286. matches_exact("get mqtt.owner") ||
  1287. matches_exact("get mqtt.email") ||
  1288. matches_exact("get mqtt.packets") ||
  1289. matches_exact("get mqtt.raw") ||
  1290. matches_exact("get mqtt.tx") ||
  1291. matches_exact("get mqtt.eastmesh-au") ||
  1292. matches_exact("get mqtt.eastmesh.au") ||
  1293. matches_exact("get mqtt.letsmesh-eu") ||
  1294. matches_exact("get mqtt.letsmesh.eu") ||
  1295. matches_exact("get mqtt.letsmesh-us") ||
  1296. matches_exact("get mqtt.letsmesh.us") ||
  1297. matches_exact("get name") ||
  1298. matches_exact("get lat") ||
  1299. matches_exact("get lon") ||
  1300. matches_exact("get advert.interval") ||
  1301. matches_exact("get flood.advert.interval") ||
  1302. matches_exact("get flood.max") ||
  1303. matches_exact("get owner.info") ||
  1304. matches_exact("get guest.password") ||
  1305. matches_prefix("set wifi.ssid ") ||
  1306. matches_prefix("set wifi.pwd ") ||
  1307. matches_prefix("set wifi.powersaving ") ||
  1308. matches_prefix("set mqtt.iata ") ||
  1309. matches_prefix("set mqtt.owner ") ||
  1310. matches_prefix("set mqtt.email ") ||
  1311. matches_prefix("set mqtt.packets ") ||
  1312. matches_prefix("set mqtt.raw ") ||
  1313. matches_prefix("set mqtt.tx ") ||
  1314. matches_prefix("set web ") ||
  1315. matches_prefix("set.web ") ||
  1316. matches_prefix("set mqtt.eastmesh-au ") ||
  1317. matches_prefix("set mqtt.eastmesh.au ") ||
  1318. matches_prefix("set mqtt.letsmesh-eu ") ||
  1319. matches_prefix("set mqtt.letsmesh.eu ") ||
  1320. matches_prefix("set mqtt.letsmesh-us ") ||
  1321. matches_prefix("set mqtt.letsmesh.us ") ||
  1322. matches_prefix("set name ") ||
  1323. matches_prefix("set lat ") ||
  1324. matches_prefix("set lon ") ||
  1325. matches_prefix("set guest.password ") ||
  1326. matches_prefix("set prv.key ") ||
  1327. matches_prefix("set advert.interval ") ||
  1328. matches_prefix("set flood.advert.interval ") ||
  1329. matches_prefix("set flood.max ") ||
  1330. matches_prefix("set owner.info ");
  1331. if (!allowed) {
  1332. strncpy(reply, "Err - command not allowlisted for web access", reply_size - 1);
  1333. reply[reply_size - 1] = 0;
  1334. return;
  1335. }
  1336. char command_buf[192];
  1337. StrHelper::strncpy(command_buf, command, sizeof(command_buf));
  1338. handleCommand(0, command_buf, reply);
  1339. reply[reply_size - 1] = 0;
  1340. }
  1341. void MyMesh::loop() {
  1342. #ifdef WITH_BRIDGE
  1343. bridge.loop();
  1344. #endif
  1345. mesh::Mesh::loop();
  1346. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  1347. mesh::Packet *pkt = createSelfAdvert();
  1348. uint32_t delay_millis = 0;
  1349. if (pkt) sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1);
  1350. updateFloodAdvertTimer(); // schedule next flood advert
  1351. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  1352. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  1353. mesh::Packet *pkt = createSelfAdvert();
  1354. if (pkt) sendZeroHop(pkt);
  1355. updateAdvertTimer(); // schedule next local advert
  1356. }
  1357. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  1358. set_radio_at = 0; // clear timer
  1359. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  1360. MESH_DEBUG_PRINTLN("Temp radio params");
  1361. }
  1362. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  1363. revert_radio_at = 0; // clear timer
  1364. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  1365. MESH_DEBUG_PRINTLN("Radio params restored");
  1366. }
  1367. // is pending dirty contacts write needed?
  1368. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  1369. acl.save(_fs);
  1370. dirty_contacts_expiry = 0;
  1371. }
  1372. #ifdef WITH_MQTT_UPLINK
  1373. MQTTStatusSnapshot mqtt_status{};
  1374. mqtt_status.battery_mv = static_cast<int>(board.getBattMilliVolts());
  1375. mqtt_status.uptime_secs = static_cast<uint32_t>(uptime_millis / 1000);
  1376. mqtt_status.error_flags = _err_flags;
  1377. mqtt_status.queue_len = static_cast<uint16_t>(_mgr->getOutboundTotal());
  1378. mqtt_status.noise_floor = static_cast<int>(_radio->getNoiseFloor());
  1379. mqtt_status.tx_air_secs = static_cast<uint32_t>(getTotalAirTime() / 1000);
  1380. mqtt_status.rx_air_secs = static_cast<uint32_t>(getReceiveAirTime() / 1000);
  1381. mqtt_status.recv_errors = radio_driver.getPacketsRecvErrors();
  1382. mqtt_status.radio_freq = _prefs.freq;
  1383. mqtt_status.radio_bw = _prefs.bw;
  1384. mqtt_status.radio_sf = _prefs.sf;
  1385. mqtt_status.radio_cr = _prefs.cr;
  1386. mqtt.loop(mqtt_status);
  1387. #endif
  1388. // update uptime
  1389. uint32_t now = millis();
  1390. uptime_millis += now - last_millis;
  1391. last_millis = now;
  1392. }
  1393. // To check if there is pending work
  1394. bool MyMesh::hasPendingWork() const {
  1395. #if defined(WITH_BRIDGE)
  1396. if (bridge.isRunning()) return true; // bridge needs WiFi radio, can't sleep
  1397. #endif
  1398. #if defined(WITH_MQTT_UPLINK)
  1399. if (mqtt.isActive()) return true;
  1400. #endif
  1401. return _mgr->getOutboundTotal() > 0;
  1402. }