MyMesh.cpp 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464
  1. #include "MyMesh.h"
  2. #include <algorithm>
  3. #if defined(ESP32) && WITH_WEB_PANEL
  4. #include <WiFi.h>
  5. #endif
  6. #ifndef ARCHIVE_DEBUG
  7. #if defined(MQTT_DEBUG) && MQTT_DEBUG
  8. #define ARCHIVE_DEBUG 1
  9. #else
  10. #define ARCHIVE_DEBUG 0
  11. #endif
  12. #endif
  13. #if ARCHIVE_DEBUG
  14. #define ARCHIVE_LOG(fmt, ...) Serial.printf("[ARCHIVE] " fmt "\n", ##__VA_ARGS__)
  15. #else
  16. #define ARCHIVE_LOG(...) do { } while (0)
  17. #endif
  18. namespace {
  19. constexpr unsigned long kArchiveNeighboursFlushIntervalMs = 60UL * 1000UL;
  20. constexpr const char* kArchiveNeighboursSnapshotPath = "/stats/neighbours.snapshot";
  21. File openArchiveWrite(FILESYSTEM* fs, const char* filename) {
  22. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  23. fs->remove(filename);
  24. return fs->open(filename, FILE_O_WRITE);
  25. #elif defined(RP2040_PLATFORM)
  26. return fs->open(filename, "w");
  27. #else
  28. fs->remove(filename);
  29. return fs->open(filename, FILE_WRITE);
  30. #endif
  31. }
  32. File openArchiveRead(FILESYSTEM* fs, const char* filename) {
  33. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) || defined(RP2040_PLATFORM)
  34. return fs->open(filename, "r");
  35. #else
  36. return fs->open(filename, FILE_READ);
  37. #endif
  38. }
  39. File openArchiveWriteWithRecovery(ArchiveStorage* archive, const char* filename) {
  40. if (archive == nullptr) {
  41. return File();
  42. }
  43. FILESYSTEM* fs = archive->getFS();
  44. if (fs == nullptr) {
  45. return File();
  46. }
  47. File file = openArchiveWrite(fs, filename);
  48. if (file) {
  49. return file;
  50. }
  51. if (!archive->recover()) {
  52. return File();
  53. }
  54. fs = archive->getFS();
  55. return fs != nullptr ? openArchiveWrite(fs, filename) : File();
  56. }
  57. File openArchiveReadWithRecovery(ArchiveStorage* archive, const char* filename) {
  58. if (archive == nullptr) {
  59. return File();
  60. }
  61. FILESYSTEM* fs = archive->getFS();
  62. if (fs == nullptr) {
  63. return File();
  64. }
  65. File file = openArchiveRead(fs, filename);
  66. if (file) {
  67. return file;
  68. }
  69. if (!archive->recover()) {
  70. return File();
  71. }
  72. fs = archive->getFS();
  73. return fs != nullptr ? openArchiveRead(fs, filename) : File();
  74. }
  75. void escapeJsonString(const char* input, char* output, size_t output_size) {
  76. if (output == nullptr || output_size == 0) {
  77. return;
  78. }
  79. size_t oi = 0;
  80. for (size_t i = 0; input != nullptr && input[i] != 0 && oi + 1 < output_size; ++i) {
  81. const char c = input[i];
  82. const char* escape = nullptr;
  83. switch (c) {
  84. case '\\':
  85. escape = "\\\\";
  86. break;
  87. case '"':
  88. escape = "\\\"";
  89. break;
  90. case '\n':
  91. escape = "\\n";
  92. break;
  93. case '\r':
  94. escape = "\\r";
  95. break;
  96. case '\t':
  97. escape = "\\t";
  98. break;
  99. default:
  100. break;
  101. }
  102. if (escape != nullptr) {
  103. while (*escape != 0 && oi + 1 < output_size) {
  104. output[oi++] = *escape++;
  105. }
  106. } else {
  107. output[oi++] = c;
  108. }
  109. }
  110. output[oi] = 0;
  111. }
  112. } // namespace
  113. /* ------------------------------ Config -------------------------------- */
  114. #ifndef LORA_FREQ
  115. #define LORA_FREQ 915.0
  116. #endif
  117. #ifndef LORA_BW
  118. #define LORA_BW 250
  119. #endif
  120. #ifndef LORA_SF
  121. #define LORA_SF 10
  122. #endif
  123. #ifndef LORA_CR
  124. #define LORA_CR 5
  125. #endif
  126. #ifndef LORA_TX_POWER
  127. #define LORA_TX_POWER 20
  128. #endif
  129. #ifndef ADVERT_NAME
  130. #define ADVERT_NAME "repeater"
  131. #endif
  132. #ifndef ADVERT_LAT
  133. #define ADVERT_LAT 0.0
  134. #endif
  135. #ifndef ADVERT_LON
  136. #define ADVERT_LON 0.0
  137. #endif
  138. #ifndef ADMIN_PASSWORD
  139. #define ADMIN_PASSWORD "password"
  140. #endif
  141. #ifndef SERVER_RESPONSE_DELAY
  142. #define SERVER_RESPONSE_DELAY 300
  143. #endif
  144. #ifndef TXT_ACK_DELAY
  145. #define TXT_ACK_DELAY 200
  146. #endif
  147. #define FIRMWARE_VER_LEVEL 2
  148. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  149. #define REQ_TYPE_KEEP_ALIVE 0x02
  150. #define REQ_TYPE_GET_TELEMETRY_DATA 0x03
  151. #define REQ_TYPE_GET_ACCESS_LIST 0x05
  152. #define REQ_TYPE_GET_NEIGHBOURS 0x06
  153. #define REQ_TYPE_GET_OWNER_INFO 0x07 // FIRMWARE_VER_LEVEL >= 2
  154. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  155. #define ANON_REQ_TYPE_REGIONS 0x01
  156. #define ANON_REQ_TYPE_OWNER 0x02
  157. #define ANON_REQ_TYPE_BASIC 0x03 // just remote clock
  158. #define CLI_REPLY_DELAY_MILLIS 600
  159. #define LAZY_CONTACTS_WRITE_DELAY 5000
  160. void MyMesh::putNeighbour(const mesh::Identity &id, uint32_t timestamp, float snr) {
  161. #if MAX_NEIGHBOURS // check if neighbours enabled
  162. // find existing neighbour, else use least recently updated
  163. uint32_t oldest_timestamp = 0xFFFFFFFF;
  164. NeighbourInfo *neighbour = &neighbours[0];
  165. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  166. // if neighbour already known, we should update it
  167. if (id.matches(neighbours[i].id)) {
  168. neighbour = &neighbours[i];
  169. break;
  170. }
  171. // otherwise we should update the least recently updated neighbour
  172. if (neighbours[i].heard_timestamp < oldest_timestamp) {
  173. neighbour = &neighbours[i];
  174. oldest_timestamp = neighbour->heard_timestamp;
  175. }
  176. }
  177. // update neighbour info
  178. neighbour->id = id;
  179. neighbour->advert_timestamp = timestamp;
  180. neighbour->heard_timestamp = getRTCClock()->getCurrentTime();
  181. neighbour->snr = (int8_t)(snr * 4);
  182. _archive_neighbours_dirty = true;
  183. #endif
  184. }
  185. uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood) {
  186. ClientInfo* client = NULL;
  187. if (data[0] == 0) { // blank password, just check if sender is in ACL
  188. client = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
  189. if (client == NULL) {
  190. #if MESH_DEBUG
  191. MESH_DEBUG_PRINTLN("Login, sender not in ACL");
  192. #endif
  193. }
  194. }
  195. if (client == NULL) {
  196. uint8_t perms;
  197. if (strcmp((char *)data, _prefs.password) == 0) { // check for valid admin password
  198. perms = PERM_ACL_ADMIN;
  199. } else if (strcmp((char *)data, _prefs.guest_password) == 0) { // check guest password
  200. perms = PERM_ACL_GUEST;
  201. } else {
  202. #if MESH_DEBUG
  203. MESH_DEBUG_PRINTLN("Invalid password: %s", data);
  204. #endif
  205. return 0;
  206. }
  207. client = acl.putClient(sender, 0); // add to contacts (if not already known)
  208. if (sender_timestamp <= client->last_timestamp) {
  209. MESH_DEBUG_PRINTLN("Possible login replay attack!");
  210. return 0; // FATAL: client table is full -OR- replay attack
  211. }
  212. MESH_DEBUG_PRINTLN("Login success!");
  213. client->last_timestamp = sender_timestamp;
  214. client->last_activity = getRTCClock()->getCurrentTime();
  215. client->permissions &= ~0x03;
  216. client->permissions |= perms;
  217. memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
  218. if (perms != PERM_ACL_GUEST) { // keep number of FS writes to a minimum
  219. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  220. }
  221. }
  222. if (is_flood) {
  223. client->out_path_len = OUT_PATH_UNKNOWN; // need to rediscover out_path
  224. }
  225. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  226. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  227. reply_data[4] = RESP_SERVER_LOGIN_OK;
  228. reply_data[5] = 0; // Legacy: was recommended keep-alive interval (secs / 16)
  229. reply_data[6] = client->isAdmin() ? 1 : 0;
  230. reply_data[7] = client->permissions;
  231. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  232. reply_data[12] = FIRMWARE_VER_LEVEL; // New field
  233. return 13; // reply length
  234. }
  235. uint8_t MyMesh::handleAnonRegionsReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
  236. if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
  237. // request data has: {reply-path-len}{reply-path}
  238. reply_path_len = *data & 63;
  239. reply_path_hash_size = (*data >> 6) + 1;
  240. data++;
  241. memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size);
  242. // data += (uint8_t)reply_path_len * reply_path_hash_size;
  243. memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
  244. uint32_t now = getRTCClock()->getCurrentTime();
  245. memcpy(&reply_data[4], &now, 4); // include our clock (for easy clock sync, and packet hash uniqueness)
  246. return 8 + region_map.exportNamesTo((char *) &reply_data[8], sizeof(reply_data) - 12, REGION_DENY_FLOOD); // reply length
  247. }
  248. return 0;
  249. }
  250. uint8_t MyMesh::handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
  251. if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
  252. // request data has: {reply-path-len}{reply-path}
  253. reply_path_len = *data & 63;
  254. reply_path_hash_size = (*data >> 6) + 1;
  255. data++;
  256. memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size);
  257. // data += (uint8_t)reply_path_len * reply_path_hash_size;
  258. memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
  259. uint32_t now = getRTCClock()->getCurrentTime();
  260. memcpy(&reply_data[4], &now, 4); // include our clock (for easy clock sync, and packet hash uniqueness)
  261. sprintf((char *) &reply_data[8], "%s\n%s", _prefs.node_name, _prefs.owner_info);
  262. return 8 + strlen((char *) &reply_data[8]); // reply length
  263. }
  264. return 0;
  265. }
  266. uint8_t MyMesh::handleAnonClockReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
  267. if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
  268. // request data has: {reply-path-len}{reply-path}
  269. reply_path_len = *data & 63;
  270. reply_path_hash_size = (*data >> 6) + 1;
  271. data++;
  272. memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size);
  273. // data += (uint8_t)reply_path_len * reply_path_hash_size;
  274. memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
  275. uint32_t now = getRTCClock()->getCurrentTime();
  276. memcpy(&reply_data[4], &now, 4); // include our clock (for easy clock sync, and packet hash uniqueness)
  277. reply_data[8] = 0; // features
  278. #ifdef WITH_RS232_BRIDGE
  279. reply_data[8] |= 0x01; // is bridge, type UART
  280. #elif WITH_ESPNOW_BRIDGE
  281. reply_data[8] |= 0x03; // is bridge, type ESP-NOW
  282. #endif
  283. if (_prefs.disable_fwd) { // is this repeater currently disabled
  284. reply_data[8] |= 0x80; // is disabled
  285. }
  286. // TODO: add some kind of moving-window utilisation metric, so can query 'how busy' is this repeater
  287. return 9; // reply length
  288. }
  289. return 0;
  290. }
  291. int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) {
  292. // uint32_t now = getRTCClock()->getCurrentTimeUnique();
  293. // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  294. memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  295. if (payload[0] == REQ_TYPE_GET_STATUS) { // guests can also access this now
  296. RepeaterStats stats;
  297. stats.batt_milli_volts = board.getBattMilliVolts();
  298. stats.curr_tx_queue_len = _mgr->getOutboundTotal();
  299. stats.noise_floor = (int16_t)_radio->getNoiseFloor();
  300. stats.last_rssi = (int16_t)radio_driver.getLastRSSI();
  301. stats.n_packets_recv = radio_driver.getPacketsRecv();
  302. stats.n_packets_sent = radio_driver.getPacketsSent();
  303. stats.total_air_time_secs = getTotalAirTime() / 1000;
  304. stats.total_up_time_secs = uptime_millis / 1000;
  305. stats.n_sent_flood = getNumSentFlood();
  306. stats.n_sent_direct = getNumSentDirect();
  307. stats.n_recv_flood = getNumRecvFlood();
  308. stats.n_recv_direct = getNumRecvDirect();
  309. stats.err_events = _err_flags;
  310. stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
  311. stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
  312. stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
  313. stats.total_rx_air_time_secs = getReceiveAirTime() / 1000;
  314. stats.n_recv_errors = radio_driver.getPacketsRecvErrors();
  315. memcpy(&reply_data[4], &stats, sizeof(stats));
  316. return 4 + sizeof(stats); // reply_len
  317. }
  318. if (payload[0] == REQ_TYPE_GET_TELEMETRY_DATA) {
  319. uint8_t perm_mask = ~(payload[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions
  320. telemetry.reset();
  321. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  322. // query other sensors -- target specific
  323. if ((sender->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) {
  324. perm_mask = 0x00; // just base telemetry allowed
  325. }
  326. sensors.querySensors(perm_mask, telemetry);
  327. // This default temperature will be overridden by external sensors (if any)
  328. float temperature = board.getMCUTemperature();
  329. if(!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN
  330. telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature
  331. }
  332. uint8_t tlen = telemetry.getSize();
  333. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  334. return 4 + tlen; // reply_len
  335. }
  336. if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) {
  337. uint8_t res1 = payload[1]; // reserved for future (extra query params)
  338. uint8_t res2 = payload[2];
  339. if (res1 == 0 && res2 == 0) {
  340. uint8_t ofs = 4;
  341. for (int i = 0; i < acl.getNumClients() && ofs + 7 <= sizeof(reply_data) - 4; i++) {
  342. auto c = acl.getClientByIdx(i);
  343. if (c->permissions == 0) continue; // skip deleted entries
  344. memcpy(&reply_data[ofs], c->id.pub_key, 6); ofs += 6; // just 6-byte pub_key prefix
  345. reply_data[ofs++] = c->permissions;
  346. }
  347. return ofs;
  348. }
  349. }
  350. if (payload[0] == REQ_TYPE_GET_NEIGHBOURS) {
  351. uint8_t request_version = payload[1];
  352. if (request_version == 0) {
  353. // reply data offset (after response sender_timestamp/tag)
  354. int reply_offset = 4;
  355. // get request params
  356. uint8_t count = payload[2]; // how many neighbours to fetch (0-255)
  357. uint16_t offset;
  358. memcpy(&offset, &payload[3], 2); // offset from start of neighbours list (0-65535)
  359. 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
  360. uint8_t pubkey_prefix_length = payload[6]; // how many bytes of neighbour pub key we want
  361. // we also send a 4 byte random blob in payload[7...10] to help packet uniqueness
  362. 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);
  363. // clamp pub key prefix length to max pub key length
  364. if(pubkey_prefix_length > PUB_KEY_SIZE){
  365. pubkey_prefix_length = PUB_KEY_SIZE;
  366. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS invalid pubkey_prefix_length=%d clamping to %d", pubkey_prefix_length, PUB_KEY_SIZE);
  367. }
  368. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  369. int16_t neighbours_count = 0;
  370. #if MAX_NEIGHBOURS
  371. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  372. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  373. auto neighbour = &neighbours[i];
  374. if (neighbour->heard_timestamp > 0) {
  375. sorted_neighbours[neighbours_count] = neighbour;
  376. neighbours_count++;
  377. }
  378. }
  379. // sort neighbours based on order
  380. if (order_by == 0) {
  381. // sort by newest to oldest
  382. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting newest to oldest");
  383. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  384. return a->heard_timestamp > b->heard_timestamp; // desc
  385. });
  386. } else if (order_by == 1) {
  387. // sort by oldest to newest
  388. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting oldest to newest");
  389. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  390. return a->heard_timestamp < b->heard_timestamp; // asc
  391. });
  392. } else if (order_by == 2) {
  393. // sort by strongest to weakest
  394. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting strongest to weakest");
  395. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  396. return a->snr > b->snr; // desc
  397. });
  398. } else if (order_by == 3) {
  399. // sort by weakest to strongest
  400. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting weakest to strongest");
  401. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  402. return a->snr < b->snr; // asc
  403. });
  404. }
  405. #endif
  406. // build results buffer
  407. int results_count = 0;
  408. int results_offset = 0;
  409. uint8_t results_buffer[130];
  410. for(int index = 0; index < count && index + offset < neighbours_count; index++){
  411. // stop if we can't fit another entry in results
  412. int entry_size = pubkey_prefix_length + 4 + 1;
  413. if(results_offset + entry_size > sizeof(results_buffer)){
  414. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS no more entries can fit in results buffer");
  415. break;
  416. }
  417. #if MAX_NEIGHBOURS
  418. // add next neighbour to results
  419. auto neighbour = sorted_neighbours[index + offset];
  420. uint32_t heard_seconds_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  421. memcpy(&results_buffer[results_offset], neighbour->id.pub_key, pubkey_prefix_length); results_offset += pubkey_prefix_length;
  422. memcpy(&results_buffer[results_offset], &heard_seconds_ago, 4); results_offset += 4;
  423. memcpy(&results_buffer[results_offset], &neighbour->snr, 1); results_offset += 1;
  424. results_count++;
  425. #endif
  426. }
  427. // build reply
  428. MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS neighbours_count=%d results_count=%d", neighbours_count, results_count);
  429. memcpy(&reply_data[reply_offset], &neighbours_count, 2); reply_offset += 2;
  430. memcpy(&reply_data[reply_offset], &results_count, 2); reply_offset += 2;
  431. memcpy(&reply_data[reply_offset], &results_buffer, results_offset); reply_offset += results_offset;
  432. return reply_offset;
  433. }
  434. } else if (payload[0] == REQ_TYPE_GET_OWNER_INFO) {
  435. sprintf((char *) &reply_data[4], "%s\n%s\n%s", FIRMWARE_VERSION, _prefs.node_name, _prefs.owner_info);
  436. return 4 + strlen((char *) &reply_data[4]);
  437. }
  438. return 0; // unknown command
  439. }
  440. mesh::Packet *MyMesh::createSelfAdvert() {
  441. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  442. uint8_t app_data_len = _cli.buildAdvertData(ADV_TYPE_REPEATER, app_data);
  443. return createAdvert(self_id, app_data, app_data_len);
  444. }
  445. File MyMesh::openAppend(const char *fname) {
  446. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  447. return _fs->open(fname, FILE_O_WRITE);
  448. #elif defined(RP2040_PLATFORM)
  449. return _fs->open(fname, "a");
  450. #else
  451. return _fs->open(fname, "a", true);
  452. #endif
  453. }
  454. static uint8_t max_loop_minimal[] = { 0, /* 1-byte */ 4, /* 2-byte */ 2, /* 3-byte */ 1 };
  455. static uint8_t max_loop_moderate[] = { 0, /* 1-byte */ 2, /* 2-byte */ 1, /* 3-byte */ 1 };
  456. static uint8_t max_loop_strict[] = { 0, /* 1-byte */ 1, /* 2-byte */ 1, /* 3-byte */ 1 };
  457. bool MyMesh::isLooped(const mesh::Packet* packet, const uint8_t max_counters[]) {
  458. uint8_t hash_size = packet->getPathHashSize();
  459. uint8_t hash_count = packet->getPathHashCount();
  460. uint8_t n = 0;
  461. const uint8_t* path = packet->path;
  462. while (hash_count > 0) { // count how many times this node is already in the path
  463. if (self_id.isHashMatch(path, hash_size)) n++;
  464. hash_count--;
  465. path += hash_size;
  466. }
  467. return n >= max_counters[hash_size];
  468. }
  469. bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
  470. if (_prefs.disable_fwd) return false;
  471. if (packet->isRouteFlood() && packet->getPathHashCount() >= _prefs.flood_max) return false;
  472. if (packet->isRouteFlood() && recv_pkt_region == NULL) {
  473. MESH_DEBUG_PRINTLN("allowPacketForward: unknown transport code, or wildcard not allowed for FLOOD packet");
  474. return false;
  475. }
  476. if (packet->isRouteFlood() && _prefs.loop_detect != LOOP_DETECT_OFF) {
  477. const uint8_t* maximums;
  478. if (_prefs.loop_detect == LOOP_DETECT_MINIMAL) {
  479. maximums = max_loop_minimal;
  480. } else if (_prefs.loop_detect == LOOP_DETECT_MODERATE) {
  481. maximums = max_loop_moderate;
  482. } else {
  483. maximums = max_loop_strict;
  484. }
  485. if (isLooped(packet, maximums)) {
  486. MESH_DEBUG_PRINTLN("allowPacketForward: FLOOD packet loop detected!");
  487. return false;
  488. }
  489. }
  490. return true;
  491. }
  492. const char *MyMesh::getLogDateTime() {
  493. static char tmp[32];
  494. uint32_t now = getRTCClock()->getCurrentTime();
  495. DateTime dt = DateTime(now);
  496. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
  497. dt.year());
  498. return tmp;
  499. }
  500. void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
  501. #if MESH_PACKET_LOGGING
  502. Serial.print(getLogDateTime());
  503. Serial.print(" RAW: ");
  504. mesh::Utils::printHex(Serial, raw, len);
  505. Serial.println();
  506. #endif
  507. }
  508. void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
  509. #ifdef WITH_BRIDGE
  510. if (_prefs.bridge_pkt_src == 1) {
  511. bridge.sendPacket(pkt);
  512. }
  513. #endif
  514. #ifdef WITH_MQTT_UPLINK
  515. mqtt.publishPacket(*pkt, false, (int)_radio->getLastRSSI(), _radio->getLastSNR(), (int)(score * 1000),
  516. (int)_radio->getEstAirtimeFor(len));
  517. #endif
  518. if (_logging) {
  519. File f = openAppend(PACKET_LOG_FILE);
  520. if (f) {
  521. f.print(getLogDateTime());
  522. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
  523. pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  524. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
  525. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  526. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  527. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  528. } else {
  529. f.printf("\n");
  530. }
  531. f.close();
  532. }
  533. }
  534. }
  535. void MyMesh::logTx(mesh::Packet *pkt, int len) {
  536. #ifdef WITH_BRIDGE
  537. if (_prefs.bridge_pkt_src == 0) {
  538. bridge.sendPacket(pkt);
  539. }
  540. #endif
  541. #ifdef WITH_MQTT_UPLINK
  542. mqtt.publishPacket(*pkt, true, (int)_radio->getLastRSSI(), _radio->getLastSNR());
  543. #endif
  544. if (_logging) {
  545. File f = openAppend(PACKET_LOG_FILE);
  546. if (f) {
  547. f.print(getLogDateTime());
  548. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  549. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  550. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  551. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  552. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  553. } else {
  554. f.printf("\n");
  555. }
  556. f.close();
  557. }
  558. }
  559. }
  560. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  561. if (_logging) {
  562. File f = openAppend(PACKET_LOG_FILE);
  563. if (f) {
  564. f.print(getLogDateTime());
  565. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  566. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  567. f.close();
  568. }
  569. }
  570. }
  571. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  572. if (_prefs.rx_delay_base <= 0.0f) return 0;
  573. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  574. }
  575. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  576. uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.tx_delay_factor);
  577. return getRNG()->nextInt(0, 5*t + 1);
  578. }
  579. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  580. uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  581. return getRNG()->nextInt(0, 5*t + 1);
  582. }
  583. bool MyMesh::filterRecvFloodPacket(mesh::Packet* pkt) {
  584. // just try to determine region for packet (apply later in allowPacketForward())
  585. if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
  586. recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
  587. } else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
  588. if (region_map.getWildcard().flags & REGION_DENY_FLOOD) {
  589. recv_pkt_region = NULL;
  590. } else {
  591. recv_pkt_region = &region_map.getWildcard();
  592. }
  593. } else {
  594. recv_pkt_region = NULL;
  595. }
  596. // do normal processing
  597. return false;
  598. }
  599. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  600. uint8_t *data, size_t len) {
  601. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  602. // client (unknown at this stage)
  603. uint32_t timestamp;
  604. memcpy(&timestamp, data, 4);
  605. data[len] = 0; // ensure null terminator
  606. uint8_t reply_len;
  607. reply_path_len = -1;
  608. if (data[4] == 0 || data[4] >= ' ') { // is password, ie. a login request
  609. reply_len = handleLoginReq(sender, secret, timestamp, &data[4], packet->isRouteFlood());
  610. } else if (data[4] == ANON_REQ_TYPE_REGIONS && packet->isRouteDirect()) {
  611. reply_len = handleAnonRegionsReq(sender, timestamp, &data[5]);
  612. } else if (data[4] == ANON_REQ_TYPE_OWNER && packet->isRouteDirect()) {
  613. reply_len = handleAnonOwnerReq(sender, timestamp, &data[5]);
  614. } else if (data[4] == ANON_REQ_TYPE_BASIC && packet->isRouteDirect()) {
  615. reply_len = handleAnonClockReq(sender, timestamp, &data[5]);
  616. } else {
  617. reply_len = 0; // unknown/invalid request type
  618. }
  619. if (reply_len == 0) return; // invalid request
  620. if (packet->isRouteFlood()) {
  621. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  622. mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
  623. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  624. if (path) sendFlood(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  625. } else if (reply_path_len < 0) {
  626. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  627. if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  628. } else {
  629. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  630. uint8_t path_len = ((reply_path_hash_size - 1) << 6) | (reply_path_len & 63);
  631. if (reply) sendDirect(reply, reply_path, path_len, SERVER_RESPONSE_DELAY);
  632. }
  633. }
  634. }
  635. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  636. int n = 0;
  637. for (int i = 0; i < acl.getNumClients(); i++) {
  638. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  639. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  640. }
  641. }
  642. return n;
  643. }
  644. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  645. int i = matching_peer_indexes[peer_idx];
  646. if (i >= 0 && i < acl.getNumClients()) {
  647. // lookup pre-calculated shared_secret
  648. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  649. } else {
  650. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  651. }
  652. }
  653. static bool isShare(const mesh::Packet *packet) {
  654. if (packet->hasTransportCodes()) {
  655. return packet->transport_codes[0] == 0 && packet->transport_codes[1] == 0; // codes { 0, 0 } means 'send to nowhere'
  656. }
  657. return false;
  658. }
  659. void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
  660. const uint8_t *app_data, size_t app_data_len) {
  661. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  662. // if this a zero hop advert (and not via 'Share'), add it to neighbours
  663. if (packet->path_len == 0 && !isShare(packet)) {
  664. AdvertDataParser parser(app_data, app_data_len);
  665. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  666. putNeighbour(id, timestamp, packet->getSNR());
  667. }
  668. }
  669. }
  670. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  671. uint8_t *data, size_t len) {
  672. int i = matching_peer_indexes[sender_idx];
  673. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  674. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  675. return;
  676. }
  677. ClientInfo* client = acl.getClientByIdx(i);
  678. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  679. uint32_t timestamp;
  680. memcpy(&timestamp, data, 4);
  681. if (timestamp > client->last_timestamp) { // prevent replay attacks
  682. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  683. if (reply_len == 0) return; // invalid command
  684. client->last_timestamp = timestamp;
  685. client->last_activity = getRTCClock()->getCurrentTime();
  686. if (packet->isRouteFlood()) {
  687. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  688. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  689. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  690. if (path) sendFlood(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  691. } else {
  692. mesh::Packet *reply =
  693. createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  694. if (reply) {
  695. if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
  696. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  697. } else {
  698. sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  699. }
  700. }
  701. }
  702. } else {
  703. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  704. }
  705. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->isAdmin()) { // a CLI command
  706. uint32_t sender_timestamp;
  707. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  708. uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
  709. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  710. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  711. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  712. bool is_retry = (sender_timestamp == client->last_timestamp);
  713. client->last_timestamp = sender_timestamp;
  714. client->last_activity = getRTCClock()->getCurrentTime();
  715. // len can be > original length, but 'text' will be padded with zeroes
  716. data[len] = 0; // need to make a C string again, with null terminator
  717. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  718. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
  719. // to sender that we got it
  720. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  721. PUB_KEY_SIZE);
  722. mesh::Packet *ack = createAck(ack_hash);
  723. if (ack) {
  724. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  725. sendFlood(ack, TXT_ACK_DELAY, packet->getPathHashSize());
  726. } else {
  727. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  728. }
  729. }
  730. }
  731. uint8_t temp[166];
  732. char *command = (char *)&data[5];
  733. char *reply = (char *)&temp[5];
  734. if (is_retry) {
  735. *reply = 0;
  736. } else {
  737. handleCommand(sender_timestamp, command, reply);
  738. }
  739. int text_len = strlen(reply);
  740. if (text_len > 0) {
  741. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  742. if (timestamp == sender_timestamp) {
  743. // WORKAROUND: the two timestamps need to be different, in the CLI view
  744. timestamp++;
  745. }
  746. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  747. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  748. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  749. if (reply) {
  750. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  751. sendFlood(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize());
  752. } else {
  753. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  754. }
  755. }
  756. }
  757. } else {
  758. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  759. }
  760. }
  761. }
  762. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  763. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  764. // TODO: prevent replay attacks
  765. int i = matching_peer_indexes[sender_idx];
  766. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  767. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  768. auto client = acl.getClientByIdx(i);
  769. // store a copy of path, for sendDirect()
  770. client->out_path_len = mesh::Packet::copyPath(client->out_path, path, path_len);
  771. client->last_activity = getRTCClock()->getCurrentTime();
  772. } else {
  773. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  774. }
  775. // NOTE: no reciprocal path send!!
  776. return false;
  777. }
  778. #define CTL_TYPE_NODE_DISCOVER_REQ 0x80
  779. #define CTL_TYPE_NODE_DISCOVER_RESP 0x90
  780. void MyMesh::onControlDataRecv(mesh::Packet* packet) {
  781. uint8_t type = packet->payload[0] & 0xF0; // just test upper 4 bits
  782. if (type == CTL_TYPE_NODE_DISCOVER_REQ && packet->payload_len >= 6
  783. && !_prefs.disable_fwd && discover_limiter.allow(rtc_clock.getCurrentTime())
  784. ) {
  785. int i = 1;
  786. uint8_t filter = packet->payload[i++];
  787. uint32_t tag;
  788. memcpy(&tag, &packet->payload[i], 4); i += 4;
  789. uint32_t since;
  790. if (packet->payload_len >= i+4) { // optional since field
  791. memcpy(&since, &packet->payload[i], 4); i += 4;
  792. } else {
  793. since = 0;
  794. }
  795. if ((filter & (1 << ADV_TYPE_REPEATER)) != 0 && _prefs.discovery_mod_timestamp >= since) {
  796. bool prefix_only = packet->payload[0] & 1;
  797. uint8_t data[6 + PUB_KEY_SIZE];
  798. data[0] = CTL_TYPE_NODE_DISCOVER_RESP | ADV_TYPE_REPEATER; // low 4-bits for node type
  799. data[1] = packet->_snr; // let sender know the inbound SNR ( x 4)
  800. memcpy(&data[2], &tag, 4); // include tag from request, for client to match to
  801. memcpy(&data[6], self_id.pub_key, PUB_KEY_SIZE);
  802. auto resp = createControlData(data, prefix_only ? 6 + 8 : 6 + PUB_KEY_SIZE);
  803. if (resp) {
  804. sendZeroHop(resp, getRetransmitDelay(resp)*4); // apply random delay (widened x4), as multiple nodes can respond to this
  805. }
  806. }
  807. } else if (type == CTL_TYPE_NODE_DISCOVER_RESP && packet->payload_len >= 6) {
  808. uint8_t node_type = packet->payload[0] & 0x0F;
  809. if (node_type != ADV_TYPE_REPEATER) {
  810. return;
  811. }
  812. if (packet->payload_len < 6 + PUB_KEY_SIZE) {
  813. MESH_DEBUG_PRINTLN("onControlDataRecv: DISCOVER_RESP pubkey too short: %d", (uint32_t)packet->payload_len);
  814. return;
  815. }
  816. if (pending_discover_tag == 0 || millisHasNowPassed(pending_discover_until)) {
  817. pending_discover_tag = 0;
  818. return;
  819. }
  820. uint32_t tag;
  821. memcpy(&tag, &packet->payload[2], 4);
  822. if (tag != pending_discover_tag) {
  823. return;
  824. }
  825. mesh::Identity id(&packet->payload[6]);
  826. if (id.matches(self_id)) {
  827. return;
  828. }
  829. putNeighbour(id, rtc_clock.getCurrentTime(), packet->getSNR());
  830. }
  831. }
  832. void MyMesh::sendNodeDiscoverReq() {
  833. uint8_t data[10];
  834. data[0] = CTL_TYPE_NODE_DISCOVER_REQ; // prefix_only=0
  835. data[1] = (1 << ADV_TYPE_REPEATER);
  836. getRNG()->random(&data[2], 4); // tag
  837. memcpy(&pending_discover_tag, &data[2], 4);
  838. pending_discover_until = futureMillis(60000);
  839. uint32_t since = 0;
  840. memcpy(&data[6], &since, 4);
  841. auto pkt = createControlData(data, sizeof(data));
  842. if (pkt) {
  843. sendZeroHop(pkt);
  844. }
  845. }
  846. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  847. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  848. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  849. _cli(board, rtc, sensors, acl, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4), region_map(key_store), temp_map(key_store),
  850. discover_limiter(4, 120), // max 4 every 2 minutes
  851. anon_limiter(4, 180) // max 4 every 3 minutes
  852. #if defined(WITH_RS232_BRIDGE)
  853. , bridge(&_prefs, WITH_RS232_BRIDGE, _mgr, &rtc)
  854. #endif
  855. #if defined(WITH_ESPNOW_BRIDGE)
  856. , bridge(&_prefs, _mgr, &rtc)
  857. #endif
  858. #if defined(WITH_MQTT_UPLINK)
  859. , mqtt(rtc, self_id)
  860. #endif
  861. {
  862. last_millis = 0;
  863. _archive = nullptr;
  864. uptime_millis = 0;
  865. next_archive_neighbours_flush_ms = 0;
  866. next_history_sample_ms = 0;
  867. next_local_advert = next_flood_advert = 0;
  868. dirty_contacts_expiry = 0;
  869. set_radio_at = revert_radio_at = 0;
  870. _logging = false;
  871. _archive_neighbours_dirty = false;
  872. region_load_active = false;
  873. memset(&_stats_state, 0, sizeof(_stats_state));
  874. #if MAX_NEIGHBOURS
  875. memset(neighbours, 0, sizeof(neighbours));
  876. #endif
  877. // defaults
  878. memset(&_prefs, 0, sizeof(_prefs));
  879. _prefs.airtime_factor = 1.0;
  880. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  881. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  882. _prefs.direct_tx_delay_factor = 0.3f; // was 0.2
  883. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  884. _prefs.node_lat = ADVERT_LAT;
  885. _prefs.node_lon = ADVERT_LON;
  886. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  887. _prefs.freq = LORA_FREQ;
  888. _prefs.sf = LORA_SF;
  889. _prefs.bw = LORA_BW;
  890. _prefs.cr = LORA_CR;
  891. _prefs.tx_power_dbm = LORA_TX_POWER;
  892. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  893. _prefs.flood_advert_interval = 12; // 12 hours
  894. _prefs.flood_max = 64;
  895. _prefs.interference_threshold = 0; // disabled
  896. // bridge defaults
  897. _prefs.bridge_enabled = 1; // enabled
  898. _prefs.bridge_delay = 500; // milliseconds
  899. _prefs.bridge_pkt_src = 0; // logTx
  900. _prefs.bridge_baud = 115200; // baud rate
  901. _prefs.bridge_channel = 1; // channel 1
  902. StrHelper::strncpy(_prefs.bridge_secret, "LVSITANOS", sizeof(_prefs.bridge_secret));
  903. // GPS defaults
  904. _prefs.gps_enabled = 0;
  905. _prefs.gps_interval = 0;
  906. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  907. _prefs.adc_multiplier = 0.0f; // 0.0f means use default board multiplier
  908. _prefs.battery_reporting_enabled = 1;
  909. #if defined(USE_SX1262) || defined(USE_SX1268)
  910. #ifdef SX126X_RX_BOOSTED_GAIN
  911. _prefs.rx_boosted_gain = SX126X_RX_BOOSTED_GAIN;
  912. #else
  913. _prefs.rx_boosted_gain = 1; // enabled by default;
  914. #endif
  915. #endif
  916. pending_discover_tag = 0;
  917. pending_discover_until = 0;
  918. }
  919. void MyMesh::begin(FILESYSTEM *fs, ArchiveStorage* archive) {
  920. mesh::Mesh::begin();
  921. _fs = fs;
  922. _archive = archive;
  923. last_millis = millis();
  924. // load persisted prefs
  925. _cli.loadPrefs(_fs);
  926. acl.load(_fs, self_id);
  927. // TODO: key_store.begin();
  928. region_map.load(_fs);
  929. #if defined(WITH_BRIDGE)
  930. if (_prefs.bridge_enabled) {
  931. bridge.begin();
  932. }
  933. #endif
  934. #if defined(ESP_PLATFORM)
  935. uint8_t legacy_wifi_powersave = 0;
  936. const char* legacy_wifi_ssid = nullptr;
  937. const char* legacy_wifi_pwd = nullptr;
  938. #ifdef WITH_MQTT_UPLINK
  939. MQTTPrefs legacy_mqtt_prefs{};
  940. MQTTPrefsStore::setDefaults(legacy_mqtt_prefs);
  941. MQTTPrefsStore::load(_fs, legacy_mqtt_prefs);
  942. legacy_wifi_powersave = legacy_mqtt_prefs.legacy_wifi_powersave;
  943. legacy_wifi_ssid = legacy_mqtt_prefs.legacy_wifi_ssid;
  944. legacy_wifi_pwd = legacy_mqtt_prefs.legacy_wifi_pwd;
  945. #endif
  946. network.begin(_fs, legacy_wifi_powersave, legacy_wifi_ssid, legacy_wifi_pwd);
  947. #endif
  948. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  949. board.setInhibitSleep(true);
  950. web.setCommandRunner(this);
  951. web.setNetworkStateProvider(&network);
  952. web.begin(_fs);
  953. _stats_history.begin(web.isWebStatsEnabled(), _archive);
  954. if (web.isWebStatsEnabled() && !_stats_history.isLiveOnly() && _archive != nullptr && _archive->isMounted()) {
  955. restoreArchiveNeighbours();
  956. next_archive_neighbours_flush_ms = millis() + kArchiveNeighboursFlushIntervalMs;
  957. }
  958. if (web.isWebStatsEnabled()) {
  959. recordStatsEvent(HISTORY_EVENT_BOOT);
  960. if (_archive != nullptr) {
  961. recordStatsEvent(_archive->isMounted() ? HISTORY_EVENT_ARCHIVE_MOUNTED : HISTORY_EVENT_ARCHIVE_UNAVAILABLE);
  962. }
  963. }
  964. #endif
  965. #if defined(WITH_MQTT_UPLINK) && !(defined(ESP_PLATFORM) && WITH_WEB_PANEL)
  966. board.setInhibitSleep(true);
  967. #endif
  968. #ifdef WITH_MQTT_UPLINK
  969. mqtt.setNodeNameSource(_prefs.node_name);
  970. #if defined(ESP_PLATFORM)
  971. mqtt.setNetworkStateProvider(&network);
  972. #endif
  973. mqtt.begin(_fs);
  974. #endif
  975. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  976. radio_set_tx_power(_prefs.tx_power_dbm);
  977. radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);
  978. MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s",
  979. radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled");
  980. updateAdvertTimer();
  981. updateFloodAdvertTimer();
  982. board.setAdcMultiplier(_prefs.adc_multiplier);
  983. board.setBatteryReporting(_prefs.battery_reporting_enabled);
  984. #if ENV_INCLUDE_GPS == 1
  985. applyGpsPrefs();
  986. #endif
  987. next_history_sample_ms = futureMillis(1000);
  988. }
  989. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  990. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  991. pending_freq = freq;
  992. pending_bw = bw;
  993. pending_sf = sf;
  994. pending_cr = cr;
  995. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  996. }
  997. bool MyMesh::formatFileSystem() {
  998. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  999. return InternalFS.format();
  1000. #elif defined(RP2040_PLATFORM)
  1001. return LittleFS.format();
  1002. #elif defined(ESP32)
  1003. return SPIFFS.format();
  1004. #else
  1005. #error "need to implement file system erase"
  1006. return false;
  1007. #endif
  1008. }
  1009. void MyMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
  1010. mesh::Packet *pkt = createSelfAdvert();
  1011. if (pkt) {
  1012. if (flood) {
  1013. sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1);
  1014. } else {
  1015. sendZeroHop(pkt, delay_millis);
  1016. }
  1017. } else {
  1018. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  1019. }
  1020. }
  1021. void MyMesh::updateAdvertTimer() {
  1022. if (_prefs.advert_interval > 0) { // schedule local advert timer
  1023. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  1024. } else {
  1025. next_local_advert = 0; // stop the timer
  1026. }
  1027. }
  1028. void MyMesh::updateFloodAdvertTimer() {
  1029. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  1030. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  1031. } else {
  1032. next_flood_advert = 0; // stop the timer
  1033. }
  1034. }
  1035. void MyMesh::dumpLogFile() {
  1036. #if defined(RP2040_PLATFORM)
  1037. File f = _fs->open(PACKET_LOG_FILE, "r");
  1038. #else
  1039. File f = _fs->open(PACKET_LOG_FILE);
  1040. #endif
  1041. if (f) {
  1042. while (f.available()) {
  1043. int c = f.read();
  1044. if (c < 0) break;
  1045. Serial.print((char)c);
  1046. }
  1047. f.close();
  1048. }
  1049. }
  1050. void MyMesh::setTxPower(int8_t power_dbm) {
  1051. radio_set_tx_power(power_dbm);
  1052. }
  1053. #if defined(USE_SX1262) || defined(USE_SX1268)
  1054. void MyMesh::setRxBoostedGain(bool enable) {
  1055. radio_driver.setRxBoostedGainMode(enable);
  1056. }
  1057. #endif
  1058. void MyMesh::formatNeighborsReply(char *reply) {
  1059. char *dp = reply;
  1060. #if MAX_NEIGHBOURS
  1061. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  1062. int16_t neighbours_count = 0;
  1063. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  1064. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  1065. auto neighbour = &neighbours[i];
  1066. if (neighbour->heard_timestamp > 0) {
  1067. sorted_neighbours[neighbours_count] = neighbour;
  1068. neighbours_count++;
  1069. }
  1070. }
  1071. // sort neighbours newest to oldest
  1072. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  1073. return a->heard_timestamp > b->heard_timestamp; // desc
  1074. });
  1075. for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
  1076. NeighbourInfo *neighbour = sorted_neighbours[i];
  1077. // add new line if not first item
  1078. if (i > 0) *dp++ = '\n';
  1079. char hex[10];
  1080. // get 4 bytes of neighbour id as hex
  1081. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  1082. // add next neighbour
  1083. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  1084. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  1085. while (*dp)
  1086. dp++; // find end of string
  1087. }
  1088. #endif
  1089. if (dp == reply) { // no neighbours, need empty response
  1090. strcpy(dp, "-none-");
  1091. dp += 6;
  1092. }
  1093. *dp = 0; // null terminator
  1094. }
  1095. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  1096. #if MAX_NEIGHBOURS
  1097. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  1098. NeighbourInfo *neighbour = &neighbours[i];
  1099. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  1100. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  1101. _archive_neighbours_dirty = true;
  1102. }
  1103. }
  1104. #endif
  1105. }
  1106. void MyMesh::formatStatsReply(char *reply, size_t reply_size) {
  1107. StatsFormatHelper::formatCoreStats(reply, reply_size, board, *_ms, _err_flags, _mgr);
  1108. }
  1109. void MyMesh::formatRadioStatsReply(char *reply, size_t reply_size) {
  1110. StatsFormatHelper::formatRadioStats(reply, reply_size, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
  1111. }
  1112. void MyMesh::formatPacketStatsReply(char *reply, size_t reply_size) {
  1113. StatsFormatHelper::formatPacketStats(reply, reply_size, radio_driver, getNumSentFlood(), getNumSentDirect(),
  1114. getNumRecvFlood(), getNumRecvDirect());
  1115. }
  1116. void MyMesh::formatMemoryReply(char *reply, size_t reply_size) {
  1117. StatsFormatHelper::formatMemoryStats(reply, reply_size);
  1118. }
  1119. size_t MyMesh::getNeighbourCount() const {
  1120. #if MAX_NEIGHBOURS
  1121. size_t count = 0;
  1122. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  1123. if (neighbours[i].heard_timestamp > 0) {
  1124. count++;
  1125. }
  1126. }
  1127. return count;
  1128. #else
  1129. return 0;
  1130. #endif
  1131. }
  1132. bool MyMesh::restoreArchiveNeighbours() {
  1133. #if MAX_NEIGHBOURS
  1134. if (_archive == nullptr || !_archive->isMounted()) {
  1135. return false;
  1136. }
  1137. FILESYSTEM* fs = _archive->getFS();
  1138. if (fs == nullptr || !fs->exists(kArchiveNeighboursSnapshotPath)) {
  1139. return false;
  1140. }
  1141. File file = openArchiveReadWithRecovery(_archive, kArchiveNeighboursSnapshotPath);
  1142. if (!file) {
  1143. ARCHIVE_LOG("neighbours restore open failed path=%s", kArchiveNeighboursSnapshotPath);
  1144. return false;
  1145. }
  1146. memset(neighbours, 0, sizeof(neighbours));
  1147. char line[128];
  1148. size_t line_len = 0;
  1149. size_t restored = 0;
  1150. while (file.available()) {
  1151. const int raw = file.read();
  1152. if (raw < 0) {
  1153. break;
  1154. }
  1155. const char ch = static_cast<char>(raw);
  1156. if (ch == '\r') {
  1157. continue;
  1158. }
  1159. if (ch == '\n') {
  1160. line[line_len] = 0;
  1161. if (line_len > 0 && restored < MAX_NEIGHBOURS) {
  1162. char full_hex[65];
  1163. unsigned long advert_timestamp = 0;
  1164. unsigned long heard_timestamp = 0;
  1165. int snr = 0;
  1166. memset(full_hex, 0, sizeof(full_hex));
  1167. if (sscanf(line, "%64[^,],%lu,%lu,%d", full_hex, &advert_timestamp, &heard_timestamp, &snr) == 4) {
  1168. uint8_t pub_key[PUB_KEY_SIZE];
  1169. if (mesh::Utils::fromHex(pub_key, PUB_KEY_SIZE, full_hex)) {
  1170. neighbours[restored].id = mesh::Identity(pub_key);
  1171. neighbours[restored].advert_timestamp = static_cast<uint32_t>(advert_timestamp);
  1172. neighbours[restored].heard_timestamp = static_cast<uint32_t>(heard_timestamp);
  1173. neighbours[restored].snr = static_cast<int8_t>(constrain(snr, -128, 127));
  1174. restored++;
  1175. }
  1176. }
  1177. }
  1178. line_len = 0;
  1179. continue;
  1180. }
  1181. if (line_len + 1 < sizeof(line)) {
  1182. line[line_len++] = ch;
  1183. }
  1184. }
  1185. if (line_len > 0 && restored < MAX_NEIGHBOURS) {
  1186. line[line_len] = 0;
  1187. char full_hex[65];
  1188. unsigned long advert_timestamp = 0;
  1189. unsigned long heard_timestamp = 0;
  1190. int snr = 0;
  1191. memset(full_hex, 0, sizeof(full_hex));
  1192. if (sscanf(line, "%64[^,],%lu,%lu,%d", full_hex, &advert_timestamp, &heard_timestamp, &snr) == 4) {
  1193. uint8_t pub_key[PUB_KEY_SIZE];
  1194. if (mesh::Utils::fromHex(pub_key, PUB_KEY_SIZE, full_hex)) {
  1195. neighbours[restored].id = mesh::Identity(pub_key);
  1196. neighbours[restored].advert_timestamp = static_cast<uint32_t>(advert_timestamp);
  1197. neighbours[restored].heard_timestamp = static_cast<uint32_t>(heard_timestamp);
  1198. neighbours[restored].snr = static_cast<int8_t>(constrain(snr, -128, 127));
  1199. restored++;
  1200. }
  1201. }
  1202. }
  1203. file.close();
  1204. _archive_neighbours_dirty = false;
  1205. return restored > 0;
  1206. #else
  1207. return false;
  1208. #endif
  1209. }
  1210. void MyMesh::flushArchiveNeighbours() {
  1211. #if MAX_NEIGHBOURS
  1212. if (_archive == nullptr || !_archive->isMounted()) {
  1213. return;
  1214. }
  1215. FILESYSTEM* fs = _archive->getFS();
  1216. if (fs == nullptr) {
  1217. return;
  1218. }
  1219. int16_t neighbours_count = 0;
  1220. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  1221. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  1222. if (neighbours[i].heard_timestamp > 0) {
  1223. sorted_neighbours[neighbours_count++] = &neighbours[i];
  1224. }
  1225. }
  1226. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  1227. return a->heard_timestamp > b->heard_timestamp;
  1228. });
  1229. File file = openArchiveWriteWithRecovery(_archive, kArchiveNeighboursSnapshotPath);
  1230. if (!file) {
  1231. ARCHIVE_LOG("neighbours open failed path=%s", kArchiveNeighboursSnapshotPath);
  1232. return;
  1233. }
  1234. size_t total_written = 0;
  1235. for (int i = 0; i < neighbours_count; ++i) {
  1236. char full_hex[65];
  1237. mesh::Utils::toHex(full_hex, sorted_neighbours[i]->id.pub_key, PUB_KEY_SIZE);
  1238. total_written += file.printf("%s,%lu,%lu,%d\n",
  1239. full_hex,
  1240. static_cast<unsigned long>(sorted_neighbours[i]->advert_timestamp),
  1241. static_cast<unsigned long>(sorted_neighbours[i]->heard_timestamp),
  1242. static_cast<int>(sorted_neighbours[i]->snr));
  1243. }
  1244. file.flush();
  1245. file.close();
  1246. ARCHIVE_LOG("neighbours flushed path=%s bytes=%u count=%d",
  1247. kArchiveNeighboursSnapshotPath,
  1248. static_cast<unsigned>(total_written),
  1249. static_cast<int>(neighbours_count));
  1250. _archive_neighbours_dirty = false;
  1251. #endif
  1252. }
  1253. void MyMesh::maybeFlushArchiveNeighbours(unsigned long now_ms) {
  1254. #if MAX_NEIGHBOURS
  1255. if (!_archive_neighbours_dirty || _archive == nullptr || !_archive->isMounted()) {
  1256. return;
  1257. }
  1258. if (next_archive_neighbours_flush_ms == 0 || millisHasNowPassed(next_archive_neighbours_flush_ms)) {
  1259. flushArchiveNeighbours();
  1260. next_archive_neighbours_flush_ms = now_ms + kArchiveNeighboursFlushIntervalMs;
  1261. }
  1262. #else
  1263. (void)now_ms;
  1264. #endif
  1265. }
  1266. void MyMesh::recordStatsEvent(uint8_t type, int16_t value) {
  1267. _stats_history.recordEvent(type, getRTCClock()->getCurrentTime(), static_cast<uint32_t>(uptime_millis / 1000), value);
  1268. }
  1269. void MyMesh::updateStatsHistory(unsigned long now_ms) {
  1270. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  1271. constexpr uint32_t kLowMemoryEnterBytes = 32UL * 1024UL;
  1272. constexpr uint32_t kLowMemoryClearBytes = 48UL * 1024UL;
  1273. constexpr uint32_t kLowMemoryEventCooldownSecs = 5UL * 60UL;
  1274. _stats_history.setArchive(_archive);
  1275. _stats_history.setEnabled(web.isWebStatsEnabled());
  1276. if (!_stats_history.isEnabled()) {
  1277. _stats_state.initialized = false;
  1278. _archive_neighbours_dirty = false;
  1279. return;
  1280. }
  1281. _stats_history.maybeReleaseIdleBuffers(now_ms);
  1282. const bool wifi_connected = network.isWifiConnected();
  1283. #ifdef WITH_MQTT_UPLINK
  1284. const bool mqtt_connected = mqtt.isAnyBrokerConnected();
  1285. #else
  1286. const bool mqtt_connected = false;
  1287. #endif
  1288. const bool web_panel_up = web.isPanelRunning();
  1289. const bool archive_mounted = (_archive != nullptr) && _archive->isMounted();
  1290. #if defined(ESP32)
  1291. const uint32_t free_heap = ESP.getFreeHeap();
  1292. const uint32_t max_alloc_heap = ESP.getMaxAllocHeap();
  1293. const uint32_t uptime_secs = static_cast<uint32_t>(uptime_millis / 1000);
  1294. bool low_memory = _stats_state.low_memory;
  1295. if (!_stats_state.initialized) {
  1296. low_memory = free_heap <= kLowMemoryEnterBytes;
  1297. } else if (low_memory) {
  1298. low_memory = free_heap <= kLowMemoryClearBytes;
  1299. } else {
  1300. low_memory = free_heap <= kLowMemoryEnterBytes;
  1301. }
  1302. #else
  1303. const bool low_memory = false;
  1304. #endif
  1305. if (!_stats_state.initialized) {
  1306. _stats_state.initialized = true;
  1307. _stats_state.wifi_connected = wifi_connected;
  1308. _stats_state.mqtt_connected = mqtt_connected;
  1309. _stats_state.web_panel_up = web_panel_up;
  1310. _stats_state.archive_mounted = archive_mounted;
  1311. _stats_state.low_memory = low_memory;
  1312. _stats_state.last_low_memory_event_uptime_secs = 0;
  1313. } else {
  1314. if (_stats_state.mqtt_connected != mqtt_connected) {
  1315. recordStatsEvent(mqtt_connected ? HISTORY_EVENT_MQTT_CONNECTED : HISTORY_EVENT_MQTT_DISCONNECTED);
  1316. _stats_state.mqtt_connected = mqtt_connected;
  1317. }
  1318. if (_stats_state.web_panel_up != web_panel_up) {
  1319. recordStatsEvent(web_panel_up ? HISTORY_EVENT_WEB_STARTED : HISTORY_EVENT_WEB_STOPPED);
  1320. _stats_state.web_panel_up = web_panel_up;
  1321. }
  1322. if (_stats_state.archive_mounted != archive_mounted) {
  1323. recordStatsEvent(archive_mounted ? HISTORY_EVENT_ARCHIVE_MOUNTED : HISTORY_EVENT_ARCHIVE_UNAVAILABLE);
  1324. _stats_state.archive_mounted = archive_mounted;
  1325. if (!_stats_history.isLiveOnly() && archive_mounted) {
  1326. if (getNeighbourCount() == 0) {
  1327. restoreArchiveNeighbours();
  1328. }
  1329. next_archive_neighbours_flush_ms = now_ms + kArchiveNeighboursFlushIntervalMs;
  1330. }
  1331. }
  1332. if (!_stats_history.isLiveOnly() && !_stats_state.low_memory && low_memory) {
  1333. #if defined(ESP32)
  1334. if (_stats_state.last_low_memory_event_uptime_secs == 0 ||
  1335. (uptime_secs - _stats_state.last_low_memory_event_uptime_secs) >= kLowMemoryEventCooldownSecs) {
  1336. recordStatsEvent(HISTORY_EVENT_LOW_MEMORY, static_cast<int16_t>(min<uint32_t>(free_heap / 1024, 32767)));
  1337. _stats_state.last_low_memory_event_uptime_secs = uptime_secs;
  1338. }
  1339. #endif
  1340. }
  1341. _stats_state.wifi_connected = wifi_connected;
  1342. _stats_state.low_memory = low_memory;
  1343. }
  1344. #if defined(ESP32)
  1345. const bool live_stats_headroom_low =
  1346. _stats_history.isLiveOnly() && (free_heap <= kLowMemoryClearBytes || max_alloc_heap <= (24UL * 1024UL));
  1347. #else
  1348. const bool live_stats_headroom_low = false;
  1349. #endif
  1350. if (next_history_sample_ms == 0 || millisHasNowPassed(next_history_sample_ms)) {
  1351. if (!live_stats_headroom_low) {
  1352. HistorySample sample{};
  1353. sample.epoch_secs = getRTCClock()->getCurrentTime();
  1354. sample.uptime_secs = static_cast<uint32_t>(uptime_millis / 1000);
  1355. sample.packets_sent = radio_driver.getPacketsSent();
  1356. sample.packets_recv = radio_driver.getPacketsRecv();
  1357. sample.battery_mv = board.getBattMilliVolts();
  1358. sample.queue_len = static_cast<uint16_t>(_mgr->getOutboundTotal());
  1359. sample.error_flags = _err_flags;
  1360. sample.recv_errors = static_cast<uint16_t>(min<uint32_t>(radio_driver.getPacketsRecvErrors(), 0xFFFF));
  1361. sample.neighbour_count = static_cast<uint16_t>(min<size_t>(getNeighbourCount(), 0xFFFF));
  1362. sample.direct_dups =
  1363. static_cast<uint16_t>(min<uint32_t>(((SimpleMeshTables *)getTables())->getNumDirectDups(), 0xFFFF));
  1364. sample.flood_dups =
  1365. static_cast<uint16_t>(min<uint32_t>(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF));
  1366. sample.last_rssi_x4 = static_cast<int16_t>(radio_driver.getLastRSSI() * 4.0f);
  1367. sample.last_snr_x4 = static_cast<int16_t>(radio_driver.getLastSNR() * 4.0f);
  1368. sample.noise_floor = static_cast<int16_t>(_radio->getNoiseFloor());
  1369. sample.battery_pct = static_cast<int8_t>(board.getBatteryPercent());
  1370. #if defined(ESP32)
  1371. sample.heap_free = free_heap;
  1372. sample.heap_min = ESP.getMinFreeHeap();
  1373. sample.psram_free = ESP.getFreePsram();
  1374. sample.psram_min = ESP.getMinFreePsram();
  1375. #endif
  1376. if (board.isExternalPowered()) sample.flags |= HISTORY_FLAG_EXTERNAL_POWER;
  1377. if (board.isCharging()) sample.flags |= HISTORY_FLAG_CHARGING;
  1378. if (board.isVbusPresent()) sample.flags |= HISTORY_FLAG_VBUS;
  1379. if (wifi_connected) sample.flags |= HISTORY_FLAG_WIFI_CONNECTED;
  1380. if (mqtt_connected) sample.flags |= HISTORY_FLAG_MQTT_CONNECTED;
  1381. if (web.isWebEnabled()) sample.flags |= HISTORY_FLAG_WEB_ENABLED;
  1382. if (web_panel_up) sample.flags |= HISTORY_FLAG_WEB_PANEL_UP;
  1383. if (archive_mounted) sample.flags |= HISTORY_FLAG_ARCHIVE_MOUNTED;
  1384. _stats_history.pushSample(sample);
  1385. }
  1386. next_history_sample_ms = now_ms + 60000UL;
  1387. }
  1388. _stats_history.maybeFlush(now_ms);
  1389. if (!_stats_history.isLiveOnly()) {
  1390. maybeFlushArchiveNeighbours(now_ms);
  1391. }
  1392. #else
  1393. (void)now_ms;
  1394. #endif
  1395. }
  1396. bool MyMesh::appendJsonEvents(char* reply, size_t reply_size, size_t& offset) const {
  1397. offset += snprintf(&reply[offset], reply_size - offset, "\"events\":[");
  1398. const size_t max_events = min<size_t>(_stats_history.getEventCount(), 6);
  1399. const uint32_t now_epoch_secs = getRTCClock()->getCurrentTime();
  1400. const uint32_t now_uptime_secs = static_cast<uint32_t>(uptime_millis / 1000);
  1401. for (size_t i = 0; i < max_events; ++i) {
  1402. HistoryEvent event{};
  1403. if (!_stats_history.getRecentEvent(i, event)) {
  1404. break;
  1405. }
  1406. const uint32_t age_secs = (now_epoch_secs >= event.epoch_secs && event.epoch_secs > 0)
  1407. ? (now_epoch_secs - event.epoch_secs)
  1408. : ((now_uptime_secs >= event.uptime_secs) ? (now_uptime_secs - event.uptime_secs) : event.uptime_secs);
  1409. offset += snprintf(&reply[offset], reply_size - offset,
  1410. "%s{\"t\":%lu,\"type\":\"%s\",\"value\":%d}",
  1411. i == 0 ? "" : ",",
  1412. static_cast<unsigned long>(age_secs),
  1413. StatsHistory::getEventTypeName(event.type),
  1414. static_cast<int>(event.value));
  1415. if (offset >= reply_size) {
  1416. return false;
  1417. }
  1418. }
  1419. offset += snprintf(&reply[offset], reply_size - offset, "]");
  1420. return offset < reply_size;
  1421. }
  1422. bool MyMesh::appendJsonNeighbours(char* reply, size_t reply_size, size_t& offset) const {
  1423. offset += snprintf(&reply[offset], reply_size - offset, "\"neighbors_detail\":[");
  1424. if (offset >= reply_size) {
  1425. return false;
  1426. }
  1427. #if MAX_NEIGHBOURS
  1428. constexpr size_t kMaxNeighboursJson = 10;
  1429. int16_t neighbours_count = 0;
  1430. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  1431. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  1432. auto neighbour = const_cast<NeighbourInfo*>(&neighbours[i]);
  1433. if (neighbour->heard_timestamp > 0) {
  1434. sorted_neighbours[neighbours_count++] = neighbour;
  1435. }
  1436. }
  1437. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  1438. return a->heard_timestamp > b->heard_timestamp;
  1439. });
  1440. const size_t emit_count = min<size_t>(neighbours_count, kMaxNeighboursJson);
  1441. const uint32_t now_secs = getRTCClock()->getCurrentTime();
  1442. for (size_t i = 0; i < emit_count; ++i) {
  1443. const NeighbourInfo* neighbour = sorted_neighbours[i];
  1444. char hex[7];
  1445. char full_hex[65];
  1446. mesh::Utils::toHex(hex, neighbour->id.pub_key, 3);
  1447. mesh::Utils::toHex(full_hex, neighbour->id.pub_key, PUB_KEY_SIZE);
  1448. const uint32_t heard_secs_ago = now_secs - neighbour->heard_timestamp;
  1449. const uint32_t advert_secs_ago = now_secs - neighbour->advert_timestamp;
  1450. offset += snprintf(&reply[offset], reply_size - offset,
  1451. "%s{\"id\":\"%s\",\"full_id\":\"%s\",\"heard_secs_ago\":%lu,\"advert_secs_ago\":%lu,\"snr_db\":%.2f}",
  1452. i == 0 ? "" : ",",
  1453. hex,
  1454. full_hex,
  1455. static_cast<unsigned long>(heard_secs_ago),
  1456. static_cast<unsigned long>(advert_secs_ago),
  1457. static_cast<double>(neighbour->snr) / 4.0);
  1458. if (offset >= reply_size) {
  1459. return false;
  1460. }
  1461. }
  1462. #endif
  1463. offset += snprintf(&reply[offset], reply_size - offset, "]");
  1464. return offset < reply_size;
  1465. }
  1466. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  1467. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  1468. IdentityStore store(*_fs, "");
  1469. #elif defined(ESP32)
  1470. IdentityStore store(*_fs, "/identity");
  1471. #elif defined(RP2040_PLATFORM)
  1472. IdentityStore store(*_fs, "/identity");
  1473. #else
  1474. #error "need to define saveIdentity()"
  1475. #endif
  1476. store.save("_main", new_id);
  1477. }
  1478. void MyMesh::clearStats() {
  1479. radio_driver.resetStats();
  1480. resetStats();
  1481. ((SimpleMeshTables *)getTables())->resetStats();
  1482. }
  1483. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  1484. if (region_load_active) {
  1485. if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
  1486. region_map = temp_map; // copy over the temp instance as new current map
  1487. region_load_active = false;
  1488. sprintf(reply, "OK - loaded %d regions", region_map.getCount());
  1489. } else {
  1490. char *np = command;
  1491. while (*np == ' ') np++; // skip indent
  1492. int indent = np - command;
  1493. char *ep = np;
  1494. while (RegionMap::is_name_char(*ep)) ep++;
  1495. if (*ep) { *ep++ = 0; } // set null terminator for end of name
  1496. while (*ep && *ep != 'F') ep++; // look for (optional) flags
  1497. if (indent > 0 && indent < 8 && strlen(np) > 0) {
  1498. auto parent = load_stack[indent - 1];
  1499. if (parent) {
  1500. auto old = region_map.findByName(np);
  1501. auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists)
  1502. if (nw) {
  1503. nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr
  1504. load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's
  1505. }
  1506. }
  1507. }
  1508. reply[0] = 0;
  1509. }
  1510. return;
  1511. }
  1512. while (*command == ' ') command++; // skip leading spaces
  1513. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  1514. memcpy(reply, command, 3); // reflect the prefix back
  1515. reply += 3;
  1516. command += 3;
  1517. }
  1518. // handle ACL related commands
  1519. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  1520. char* hex = &command[8];
  1521. char* sp = strchr(hex, ' '); // look for separator char
  1522. if (sp == NULL) {
  1523. strcpy(reply, "Err - bad params");
  1524. } else {
  1525. *sp++ = 0; // replace space with null terminator
  1526. uint8_t pubkey[PUB_KEY_SIZE];
  1527. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  1528. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  1529. uint8_t perms = atoi(sp);
  1530. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  1531. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  1532. strcpy(reply, "OK");
  1533. } else {
  1534. strcpy(reply, "Err - invalid params");
  1535. }
  1536. } else {
  1537. strcpy(reply, "Err - bad pubkey");
  1538. }
  1539. }
  1540. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  1541. Serial.println("ACL:");
  1542. for (int i = 0; i < acl.getNumClients(); i++) {
  1543. auto c = acl.getClientByIdx(i);
  1544. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  1545. Serial.printf("%02X ", c->permissions);
  1546. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  1547. Serial.printf("\n");
  1548. }
  1549. reply[0] = 0;
  1550. } else if (memcmp(command, "region", 6) == 0) {
  1551. reply[0] = 0;
  1552. const char* parts[4];
  1553. int n = mesh::Utils::parseTextParts(command, parts, 4, ' ');
  1554. if (n == 1) {
  1555. region_map.exportTo(reply, 160);
  1556. } else if (n >= 2 && strcmp(parts[1], "load") == 0) {
  1557. temp_map.resetFrom(region_map); // rebuild regions in a temp instance
  1558. memset(load_stack, 0, sizeof(load_stack));
  1559. load_stack[0] = &temp_map.getWildcard();
  1560. region_load_active = true;
  1561. } else if (n >= 2 && strcmp(parts[1], "save") == 0) {
  1562. _prefs.discovery_mod_timestamp = rtc_clock.getCurrentTime(); // this node is now 'modified' (for discovery info)
  1563. savePrefs();
  1564. bool success = region_map.save(_fs);
  1565. strcpy(reply, success ? "OK" : "Err - save failed");
  1566. } else if (n >= 3 && strcmp(parts[1], "allowf") == 0) {
  1567. auto region = region_map.findByNamePrefix(parts[2]);
  1568. if (region) {
  1569. region->flags &= ~REGION_DENY_FLOOD;
  1570. strcpy(reply, "OK");
  1571. } else {
  1572. strcpy(reply, "Err - unknown region");
  1573. }
  1574. } else if (n >= 3 && strcmp(parts[1], "denyf") == 0) {
  1575. auto region = region_map.findByNamePrefix(parts[2]);
  1576. if (region) {
  1577. region->flags |= REGION_DENY_FLOOD;
  1578. strcpy(reply, "OK");
  1579. } else {
  1580. strcpy(reply, "Err - unknown region");
  1581. }
  1582. } else if (n >= 3 && strcmp(parts[1], "get") == 0) {
  1583. auto region = region_map.findByNamePrefix(parts[2]);
  1584. if (region) {
  1585. auto parent = region_map.findById(region->parent);
  1586. if (parent && parent->id != 0) {
  1587. sprintf(reply, " %s (%s) %s", region->name, parent->name, (region->flags & REGION_DENY_FLOOD) ? "" : "F");
  1588. } else {
  1589. sprintf(reply, " %s %s", region->name, (region->flags & REGION_DENY_FLOOD) ? "" : "F");
  1590. }
  1591. } else {
  1592. strcpy(reply, "Err - unknown region");
  1593. }
  1594. } else if (n >= 3 && strcmp(parts[1], "home") == 0) {
  1595. auto home = region_map.findByNamePrefix(parts[2]);
  1596. if (home) {
  1597. region_map.setHomeRegion(home);
  1598. sprintf(reply, " home is now %s", home->name);
  1599. } else {
  1600. strcpy(reply, "Err - unknown region");
  1601. }
  1602. } else if (n == 2 && strcmp(parts[1], "home") == 0) {
  1603. auto home = region_map.getHomeRegion();
  1604. sprintf(reply, " home is %s", home ? home->name : "*");
  1605. } else if (n >= 3 && strcmp(parts[1], "put") == 0) {
  1606. auto parent = n >= 4 ? region_map.findByNamePrefix(parts[3]) : &region_map.getWildcard();
  1607. if (parent == NULL) {
  1608. strcpy(reply, "Err - unknown parent");
  1609. } else {
  1610. auto region = region_map.putRegion(parts[2], parent->id);
  1611. if (region == NULL) {
  1612. strcpy(reply, "Err - unable to put");
  1613. } else {
  1614. strcpy(reply, "OK");
  1615. }
  1616. }
  1617. } else if (n >= 3 && strcmp(parts[1], "remove") == 0) {
  1618. auto region = region_map.findByName(parts[2]);
  1619. if (region) {
  1620. if (region_map.removeRegion(*region)) {
  1621. strcpy(reply, "OK");
  1622. } else {
  1623. strcpy(reply, "Err - not empty");
  1624. }
  1625. } else {
  1626. strcpy(reply, "Err - not found");
  1627. }
  1628. } else if (n >= 3 && strcmp(parts[1], "list") == 0) {
  1629. uint8_t mask = 0;
  1630. bool invert = false;
  1631. if (strcmp(parts[2], "allowed") == 0) {
  1632. mask = REGION_DENY_FLOOD;
  1633. invert = false; // list regions that DON'T have DENY flag
  1634. } else if (strcmp(parts[2], "denied") == 0) {
  1635. mask = REGION_DENY_FLOOD;
  1636. invert = true; // list regions that DO have DENY flag
  1637. } else {
  1638. strcpy(reply, "Err - use 'allowed' or 'denied'");
  1639. return;
  1640. }
  1641. int len = region_map.exportNamesTo(reply, 160, mask, invert);
  1642. if (len == 0) {
  1643. strcpy(reply, "-none-");
  1644. }
  1645. } else {
  1646. strcpy(reply, "Err - ??");
  1647. }
  1648. } else if (memcmp(command, "discover.neighbors", 18) == 0) {
  1649. const char* sub = command + 18;
  1650. while (*sub == ' ') sub++;
  1651. if (*sub != 0) {
  1652. strcpy(reply, "Err - discover.neighbors has no options");
  1653. } else {
  1654. sendNodeDiscoverReq();
  1655. strcpy(reply, "OK - Discover sent");
  1656. }
  1657. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  1658. } else if (strcmp(command, "get web.status") == 0 || strcmp(command, "get web") == 0) {
  1659. web.formatWebStatusReply(reply, 160);
  1660. } else if (strcmp(command, "get web.stats.status") == 0) {
  1661. snprintf(reply, 160,
  1662. "> enabled:%s history:%s psram:%s degraded:%s mode:%s samples:%u/%u events:%u/%u archive:%s logical:%s path:%s",
  1663. web.isWebStatsEnabled() ? "on" : "off",
  1664. (_stats_history.isEnabled() && _stats_history.isRecentHistoryAvailable()) ? "active" : "inactive",
  1665. _stats_history.isPsramBacked() ? "yes" : "no",
  1666. _stats_history.isDegraded() ? "yes" : "no",
  1667. _stats_history.isLiveOnly() ? "live" : "full",
  1668. static_cast<unsigned>(_stats_history.getSampleCount()),
  1669. static_cast<unsigned>(_stats_history.getSampleCapacity()),
  1670. static_cast<unsigned>(_stats_history.getEventCount()),
  1671. static_cast<unsigned>(_stats_history.getEventCapacity()),
  1672. (_archive != nullptr && _archive->isMounted()) ? "mounted" : "unavailable",
  1673. (_archive != nullptr) ? _archive->getLogicalName() : "archive",
  1674. (_archive != nullptr) ? _archive->getLogicalStatsPath() : "archive:/stats");
  1675. #endif
  1676. #if defined(ESP_PLATFORM)
  1677. } else if (memcmp(command, "get wifi.status", 15) == 0) {
  1678. network.formatWifiStatusReply(reply, 160);
  1679. } else if (memcmp(command, "get wifi.ssid", 13) == 0) {
  1680. sprintf(reply, "> %s", network.getWifiSSID()[0] ? network.getWifiSSID() : "-");
  1681. } else if (memcmp(command, "get wifi.powersaving", 20) == 0) {
  1682. sprintf(reply, "> %s", network.getWifiPowerSave());
  1683. #endif
  1684. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  1685. } else if (memcmp(command, "set web ", 8) == 0) {
  1686. web.setWebEnabled(memcmp(&command[8], "on", 2) == 0);
  1687. strcpy(reply, "OK");
  1688. } else if (memcmp(command, "set.web ", 8) == 0) {
  1689. web.setWebEnabled(memcmp(&command[8], "on", 2) == 0);
  1690. strcpy(reply, "OK");
  1691. } else if (memcmp(command, "set web.stats ", 14) == 0 || memcmp(command, "set.web.stats ", 15) == 0) {
  1692. const char* value = (memcmp(command, "set web.stats ", 14) == 0) ? &command[14] : &command[15];
  1693. const bool enabled = memcmp(value, "on", 2) == 0;
  1694. if (web.setWebStatsEnabled(enabled)) {
  1695. _stats_history.setEnabled(enabled);
  1696. recordStatsEvent(enabled ? HISTORY_EVENT_STATS_ENABLED : HISTORY_EVENT_STATS_DISABLED);
  1697. if (enabled) {
  1698. next_history_sample_ms = millis();
  1699. } else {
  1700. _stats_state.initialized = false;
  1701. }
  1702. strcpy(reply, enabled ? "OK - web.stats on" : "OK - web.stats off");
  1703. } else {
  1704. strcpy(reply, "Err - unable to update web.stats");
  1705. }
  1706. #endif
  1707. #if defined(ESP_PLATFORM)
  1708. } else if (memcmp(command, "set wifi.ssid ", 14) == 0) {
  1709. if (network.setWifiSSID(&command[14])) {
  1710. strcpy(reply, "OK");
  1711. } else {
  1712. strcpy(reply, "Err - bad wifi.ssid");
  1713. }
  1714. } else if (memcmp(command, "set wifi.pwd ", 13) == 0) {
  1715. if (network.setWifiPassword(&command[13])) {
  1716. strcpy(reply, "OK");
  1717. } else {
  1718. strcpy(reply, "Err - bad wifi.pwd");
  1719. }
  1720. } else if (memcmp(command, "set wifi.powersaving ", 21) == 0) {
  1721. if (network.setWifiPowerSave(&command[21])) {
  1722. strcpy(reply, "OK");
  1723. } else {
  1724. strcpy(reply, "Err - use none|min|max");
  1725. }
  1726. #endif
  1727. #ifdef WITH_MQTT_UPLINK
  1728. } else if (memcmp(command, "mqtt.owner ", 11) == 0) {
  1729. if (mqtt.setOwnerPublicKey(&command[11])) {
  1730. strcpy(reply, "OK");
  1731. } else {
  1732. strcpy(reply, "Err - owner must be 64 hex chars");
  1733. }
  1734. } else if (memcmp(command, "mqtt.email ", 11) == 0) {
  1735. if (mqtt.setOwnerEmail(&command[11])) {
  1736. strcpy(reply, "OK");
  1737. } else {
  1738. strcpy(reply, "Err - bad mqtt.email");
  1739. }
  1740. } else if (strcmp(command, "send mqtt.status") == 0) {
  1741. if (mqtt.sendStatusNow()) {
  1742. strcpy(reply, "OK");
  1743. } else {
  1744. strcpy(reply, "Err - mqtt status unavailable");
  1745. }
  1746. } else if (strcmp(command, "get mqtt.statuscfg") == 0) {
  1747. sprintf(reply, "> %s", mqtt.isStatusEnabled() ? "on" : "off");
  1748. } else if (strcmp(command, "get mqtt.status") == 0) {
  1749. mqtt.formatStatusReply(reply, 160);
  1750. } else if (memcmp(command, "get mqtt.iata", 13) == 0) {
  1751. sprintf(reply, "> %s", mqtt.getIata());
  1752. } else if (memcmp(command, "get mqtt.owner", 14) == 0) {
  1753. sprintf(reply, "> %s", mqtt.getOwnerPublicKey()[0] ? mqtt.getOwnerPublicKey() : "-");
  1754. } else if (memcmp(command, "get mqtt.email", 14) == 0) {
  1755. sprintf(reply, "> %s", mqtt.getOwnerEmail()[0] ? mqtt.getOwnerEmail() : "-");
  1756. } else if (memcmp(command, "get mqtt.packets", 16) == 0) {
  1757. sprintf(reply, "> %s", mqtt.isPacketsEnabled() ? "on" : "off");
  1758. } else if (memcmp(command, "get mqtt.raw", 12) == 0) {
  1759. sprintf(reply, "> %s", mqtt.isRawEnabled() ? "on" : "off");
  1760. } else if (memcmp(command, "get mqtt.tx", 11) == 0) {
  1761. sprintf(reply, "> %s", mqtt.isTxEnabled() ? "on" : "off");
  1762. } else if (memcmp(command, "get mqtt.eastmesh-au", 20) == 0 || memcmp(command, "get mqtt.eastmesh.au", 20) == 0) {
  1763. sprintf(reply, "> %s", mqtt.isEndpointEnabled(0x01) ? "on" : "off");
  1764. } else if (memcmp(command, "get mqtt.letsmesh-eu", 21) == 0 || memcmp(command, "get mqtt.letsmesh.eu", 21) == 0) {
  1765. sprintf(reply, "> %s", mqtt.isEndpointEnabled(0x02) ? "on" : "off");
  1766. } else if (memcmp(command, "get mqtt.letsmesh-us", 21) == 0 || memcmp(command, "get mqtt.letsmesh.us", 21) == 0) {
  1767. sprintf(reply, "> %s", mqtt.isEndpointEnabled(0x04) ? "on" : "off");
  1768. } else if (memcmp(command, "set mqtt.tx ", 12) == 0) {
  1769. mqtt.setTxEnabled(memcmp(&command[12], "on", 2) == 0);
  1770. strcpy(reply, "OK");
  1771. } else if (memcmp(command, "set mqtt.iata ", 14) == 0) {
  1772. if (mqtt.setIata(&command[14])) {
  1773. strcpy(reply, "OK");
  1774. } else {
  1775. strcpy(reply, "Err - bad mqtt.iata");
  1776. }
  1777. } else if (memcmp(command, "set mqtt.owner ", 15) == 0) {
  1778. if (mqtt.setOwnerPublicKey(&command[15])) {
  1779. strcpy(reply, "OK");
  1780. } else {
  1781. strcpy(reply, "Err - owner must be 64 hex chars");
  1782. }
  1783. } else if (memcmp(command, "set mqtt.email ", 15) == 0) {
  1784. if (mqtt.setOwnerEmail(&command[15])) {
  1785. strcpy(reply, "OK");
  1786. } else {
  1787. strcpy(reply, "Err - bad mqtt.email");
  1788. }
  1789. } else if (memcmp(command, "set mqtt.packets ", 17) == 0) {
  1790. mqtt.setPacketsEnabled(memcmp(&command[17], "on", 2) == 0);
  1791. strcpy(reply, "OK");
  1792. } else if (memcmp(command, "set mqtt.raw ", 13) == 0) {
  1793. mqtt.setRawEnabled(memcmp(&command[13], "on", 2) == 0);
  1794. strcpy(reply, "OK");
  1795. } else if (memcmp(command, "set mqtt.status ", 16) == 0) {
  1796. mqtt.setStatusEnabled(memcmp(&command[16], "on", 2) == 0);
  1797. strcpy(reply, "OK");
  1798. } else if (memcmp(command, "set mqtt.eastmesh-au ", 21) == 0 || memcmp(command, "set mqtt.eastmesh.au ", 21) == 0) {
  1799. if (mqtt.setEndpointEnabled(0x01, memcmp(&command[21], "on", 2) == 0)) {
  1800. strcpy(reply, "OK");
  1801. } else {
  1802. strcpy(reply, "Err - max 2 mqtt brokers");
  1803. }
  1804. } else if (memcmp(command, "set mqtt.letsmesh-eu ", 21) == 0 || memcmp(command, "set mqtt.letsmesh.eu ", 21) == 0) {
  1805. if (mqtt.setEndpointEnabled(0x02, memcmp(&command[21], "on", 2) == 0)) {
  1806. strcpy(reply, "OK");
  1807. } else {
  1808. strcpy(reply, "Err - max 2 mqtt brokers");
  1809. }
  1810. } else if (memcmp(command, "set mqtt.letsmesh-us ", 21) == 0 || memcmp(command, "set mqtt.letsmesh.us ", 21) == 0) {
  1811. if (mqtt.setEndpointEnabled(0x04, memcmp(&command[21], "on", 2) == 0)) {
  1812. strcpy(reply, "OK");
  1813. } else {
  1814. strcpy(reply, "Err - max 2 mqtt brokers");
  1815. }
  1816. #endif
  1817. } else{
  1818. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  1819. }
  1820. }
  1821. void MyMesh::runWebCommand(const char* command, char* reply, size_t reply_size) {
  1822. if (reply_size == 0) {
  1823. return;
  1824. }
  1825. reply[0] = 0;
  1826. if (command == nullptr) {
  1827. strncpy(reply, "Err - empty command", reply_size - 1);
  1828. reply[reply_size - 1] = 0;
  1829. return;
  1830. }
  1831. auto matches_exact = [command](const char* candidate) -> bool {
  1832. return strcmp(command, candidate) == 0;
  1833. };
  1834. auto matches_prefix = [command](const char* candidate) -> bool {
  1835. size_t len = strlen(candidate);
  1836. return strncmp(command, candidate, len) == 0;
  1837. };
  1838. bool allowed =
  1839. matches_exact("clock") ||
  1840. matches_exact("get mqtt.status") ||
  1841. matches_exact("get web.status") ||
  1842. matches_exact("get web.stats.status") ||
  1843. matches_exact("get web") ||
  1844. matches_exact("advert") ||
  1845. matches_exact("reboot") ||
  1846. matches_exact("start ota") ||
  1847. matches_exact("get wifi.status") ||
  1848. matches_exact("get wifi.powersaving") ||
  1849. matches_exact("stats-core") ||
  1850. matches_exact("stats-radio") ||
  1851. matches_exact("stats-packets") ||
  1852. matches_exact("memory") ||
  1853. matches_exact("get mqtt.iata") ||
  1854. matches_exact("get mqtt.owner") ||
  1855. matches_exact("get mqtt.email") ||
  1856. matches_exact("get mqtt.packets") ||
  1857. matches_exact("get mqtt.raw") ||
  1858. matches_exact("get mqtt.statuscfg") ||
  1859. matches_exact("get mqtt.tx") ||
  1860. matches_exact("get mqtt.eastmesh-au") ||
  1861. matches_exact("get mqtt.eastmesh.au") ||
  1862. matches_exact("get mqtt.letsmesh-eu") ||
  1863. matches_exact("get mqtt.letsmesh.eu") ||
  1864. matches_exact("get mqtt.letsmesh-us") ||
  1865. matches_exact("get mqtt.letsmesh.us") ||
  1866. matches_exact("get name") ||
  1867. matches_exact("get lat") ||
  1868. matches_exact("get lon") ||
  1869. matches_exact("get radio") ||
  1870. matches_exact("get prv.key") ||
  1871. matches_exact("get role") ||
  1872. matches_exact("get public.key") ||
  1873. matches_exact("get advert.interval") ||
  1874. matches_exact("get flood.advert.interval") ||
  1875. matches_exact("get repeat") ||
  1876. matches_exact("get flood.max") ||
  1877. matches_exact("get path.hash.mode") ||
  1878. matches_exact("get owner.info") ||
  1879. matches_exact("get guest.password") ||
  1880. matches_prefix("set wifi.ssid ") ||
  1881. matches_prefix("set wifi.pwd ") ||
  1882. matches_prefix("set wifi.powersaving ") ||
  1883. matches_prefix("set mqtt.iata ") ||
  1884. matches_prefix("set mqtt.owner ") ||
  1885. matches_prefix("set mqtt.email ") ||
  1886. matches_prefix("set mqtt.packets ") ||
  1887. matches_prefix("set mqtt.raw ") ||
  1888. matches_prefix("set mqtt.status ") ||
  1889. matches_prefix("set mqtt.tx ") ||
  1890. matches_prefix("set web ") ||
  1891. matches_prefix("set.web ") ||
  1892. matches_prefix("set web.stats ") ||
  1893. matches_prefix("set.web.stats ") ||
  1894. matches_prefix("set mqtt.eastmesh-au ") ||
  1895. matches_prefix("set mqtt.eastmesh.au ") ||
  1896. matches_prefix("set mqtt.letsmesh-eu ") ||
  1897. matches_prefix("set mqtt.letsmesh.eu ") ||
  1898. matches_prefix("set mqtt.letsmesh-us ") ||
  1899. matches_prefix("set mqtt.letsmesh.us ") ||
  1900. matches_prefix("set name ") ||
  1901. matches_prefix("set lat ") ||
  1902. matches_prefix("set lon ") ||
  1903. matches_prefix("set radio ") ||
  1904. matches_prefix("password ") ||
  1905. matches_prefix("set guest.password ") ||
  1906. matches_prefix("set prv.key ") ||
  1907. matches_prefix("set advert.interval ") ||
  1908. matches_prefix("set flood.advert.interval ") ||
  1909. matches_prefix("set repeat ") ||
  1910. matches_prefix("set flood.max ") ||
  1911. matches_prefix("set path.hash.mode ") ||
  1912. matches_prefix("time ") ||
  1913. matches_prefix("time.force ") ||
  1914. matches_prefix("set owner.info ");
  1915. if (!allowed) {
  1916. strncpy(reply, "Err - command not allowlisted for web access", reply_size - 1);
  1917. reply[reply_size - 1] = 0;
  1918. return;
  1919. }
  1920. char command_buf[192];
  1921. StrHelper::strncpy(command_buf, command, sizeof(command_buf));
  1922. handleCommand(0, command_buf, reply);
  1923. reply[reply_size - 1] = 0;
  1924. }
  1925. bool MyMesh::isWebStatsEnabled() const {
  1926. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  1927. return web.isWebStatsEnabled();
  1928. #else
  1929. return false;
  1930. #endif
  1931. }
  1932. bool MyMesh::formatWebStatsSummaryJson(char* reply, size_t reply_size) {
  1933. if (reply == nullptr || reply_size == 0) {
  1934. return false;
  1935. }
  1936. reply[0] = 0;
  1937. #if !defined(ESP_PLATFORM) || !WITH_WEB_PANEL
  1938. return false;
  1939. #else
  1940. char wifi_ssid[48];
  1941. char wifi_status[20];
  1942. char wifi_state[24];
  1943. char wifi_ip[20];
  1944. char wifi_signal[16];
  1945. char wifi_powersave[12];
  1946. escapeJsonString(network.getWifiSSID()[0] ? network.getWifiSSID() : "-", wifi_ssid, sizeof(wifi_ssid));
  1947. escapeJsonString(network.getWifiPowerSave(), wifi_powersave, sizeof(wifi_powersave));
  1948. int wifi_rssi = 0;
  1949. int wifi_quality = 0;
  1950. int wifi_code = 0;
  1951. #if defined(ESP32)
  1952. if (network.getWifiSSID()[0] == 0) {
  1953. strncpy(wifi_status, "unconfigured", sizeof(wifi_status) - 1);
  1954. wifi_status[sizeof(wifi_status) - 1] = 0;
  1955. strncpy(wifi_state, "unconfigured", sizeof(wifi_state) - 1);
  1956. wifi_state[sizeof(wifi_state) - 1] = 0;
  1957. strncpy(wifi_ip, "--", sizeof(wifi_ip) - 1);
  1958. wifi_ip[sizeof(wifi_ip) - 1] = 0;
  1959. strncpy(wifi_signal, "--", sizeof(wifi_signal) - 1);
  1960. wifi_signal[sizeof(wifi_signal) - 1] = 0;
  1961. } else if (network.isWifiConnected()) {
  1962. strncpy(wifi_status, "connected", sizeof(wifi_status) - 1);
  1963. wifi_status[sizeof(wifi_status) - 1] = 0;
  1964. strncpy(wifi_state, "connected", sizeof(wifi_state) - 1);
  1965. wifi_state[sizeof(wifi_state) - 1] = 0;
  1966. String ip = WiFi.localIP().toString();
  1967. escapeJsonString(ip.c_str(), wifi_ip, sizeof(wifi_ip));
  1968. wifi_rssi = WiFi.RSSI();
  1969. wifi_code = static_cast<int>(WiFi.status());
  1970. if (wifi_rssi <= -100) {
  1971. wifi_quality = 0;
  1972. strncpy(wifi_signal, "poor", sizeof(wifi_signal) - 1);
  1973. } else if (wifi_rssi >= -50) {
  1974. wifi_quality = 100;
  1975. strncpy(wifi_signal, "excellent", sizeof(wifi_signal) - 1);
  1976. } else {
  1977. wifi_quality = 2 * (wifi_rssi + 100);
  1978. if (wifi_rssi >= -60) {
  1979. strncpy(wifi_signal, "excellent", sizeof(wifi_signal) - 1);
  1980. } else if (wifi_rssi >= -67) {
  1981. strncpy(wifi_signal, "good", sizeof(wifi_signal) - 1);
  1982. } else if (wifi_rssi >= -75) {
  1983. strncpy(wifi_signal, "fair", sizeof(wifi_signal) - 1);
  1984. } else {
  1985. strncpy(wifi_signal, "poor", sizeof(wifi_signal) - 1);
  1986. }
  1987. }
  1988. wifi_signal[sizeof(wifi_signal) - 1] = 0;
  1989. } else {
  1990. strncpy(wifi_status, "connecting", sizeof(wifi_status) - 1);
  1991. wifi_status[sizeof(wifi_status) - 1] = 0;
  1992. wifi_code = static_cast<int>(WiFi.status());
  1993. switch (WiFi.status()) {
  1994. case WL_IDLE_STATUS:
  1995. strncpy(wifi_state, "idle", sizeof(wifi_state) - 1);
  1996. break;
  1997. case WL_NO_SSID_AVAIL:
  1998. strncpy(wifi_state, "no_ssid", sizeof(wifi_state) - 1);
  1999. break;
  2000. case WL_SCAN_COMPLETED:
  2001. strncpy(wifi_state, "scan_completed", sizeof(wifi_state) - 1);
  2002. break;
  2003. case WL_CONNECT_FAILED:
  2004. strncpy(wifi_state, "connect_failed", sizeof(wifi_state) - 1);
  2005. break;
  2006. case WL_CONNECTION_LOST:
  2007. strncpy(wifi_state, "connection_lost", sizeof(wifi_state) - 1);
  2008. break;
  2009. case WL_DISCONNECTED:
  2010. strncpy(wifi_state, "disconnected", sizeof(wifi_state) - 1);
  2011. break;
  2012. default:
  2013. strncpy(wifi_state, "unknown", sizeof(wifi_state) - 1);
  2014. break;
  2015. }
  2016. wifi_state[sizeof(wifi_state) - 1] = 0;
  2017. strncpy(wifi_ip, "--", sizeof(wifi_ip) - 1);
  2018. wifi_ip[sizeof(wifi_ip) - 1] = 0;
  2019. strncpy(wifi_signal, "--", sizeof(wifi_signal) - 1);
  2020. wifi_signal[sizeof(wifi_signal) - 1] = 0;
  2021. }
  2022. #else
  2023. strncpy(wifi_status, "unsupported", sizeof(wifi_status) - 1);
  2024. wifi_status[sizeof(wifi_status) - 1] = 0;
  2025. strncpy(wifi_state, "unsupported", sizeof(wifi_state) - 1);
  2026. wifi_state[sizeof(wifi_state) - 1] = 0;
  2027. strncpy(wifi_ip, "--", sizeof(wifi_ip) - 1);
  2028. wifi_ip[sizeof(wifi_ip) - 1] = 0;
  2029. strncpy(wifi_signal, "--", sizeof(wifi_signal) - 1);
  2030. wifi_signal[sizeof(wifi_signal) - 1] = 0;
  2031. #endif
  2032. const int battery_pct = board.getBatteryPercent();
  2033. const bool archive_available = (_archive != nullptr) && _archive->isMounted();
  2034. #ifdef WITH_MQTT_UPLINK
  2035. const bool mqtt_connected = mqtt.isAnyBrokerConnected();
  2036. const char* mqtt_state = mqtt.getAggregateBrokerState();
  2037. #else
  2038. const bool mqtt_connected = false;
  2039. const char* mqtt_state = "down";
  2040. #endif
  2041. const bool web_panel_up = web.isPanelRunning();
  2042. const char* archive_name = (_archive != nullptr) ? _archive->getLogicalName() : "archive";
  2043. const char* archive_path = (_archive != nullptr) ? _archive->getLogicalStatsPath() : "archive:/stats";
  2044. const char* archive_type = (_archive != nullptr) ? _archive->getCardTypeName() : "unavailable";
  2045. _stats_history.noteAccess(millis());
  2046. size_t offset = 0;
  2047. offset += snprintf(&reply[offset], reply_size - offset,
  2048. "{\"enabled\":true,"
  2049. "\"history\":{\"active\":%s,\"psram\":%s,\"degraded\":%s,\"live_only\":%s,\"samples\":%u,\"sample_capacity\":%u,\"sample_interval_secs\":%lu,"
  2050. "\"archive_restored\":%s,\"archive_restored_samples\":%u,\"archive_summary_interval_secs\":%lu,"
  2051. "\"events\":%u,\"event_capacity\":%u},"
  2052. "\"archive\":{\"logical\":\"%s\",\"available\":%s,\"path\":\"%s\",\"type\":\"%s\","
  2053. "\"total_bytes\":%llu,\"used_bytes\":%llu},"
  2054. "\"core\":{\"battery_mv\":%u,\"battery_pct\":%d,\"uptime_secs\":%lu,\"errors\":%u,\"queue_len\":%u,"
  2055. "\"external_power\":%s,\"charging\":%s,\"vbus\":%s},"
  2056. "\"radio\":{\"noise_floor\":%d,\"last_rssi\":%.2f,\"last_snr\":%.2f,\"tx_air_secs\":%lu,\"rx_air_secs\":%lu},"
  2057. "\"packets\":{\"recv\":%u,\"sent\":%u,\"flood_tx\":%u,\"direct_tx\":%u,\"flood_rx\":%u,\"direct_rx\":%u,"
  2058. "\"recv_errors\":%u,\"direct_dups\":%u,\"flood_dups\":%u,\"neighbors\":%u},"
  2059. "\"memory\":{\"heap_free\":%u,\"heap_min\":%u,\"heap_max\":%u,\"psram_free\":%u,\"psram_min\":%u,\"psram_max\":%u},"
  2060. "\"wifi\":{\"ssid\":\"%s\",\"status\":\"%s\",\"connected\":%s,\"state\":\"%s\",\"code\":%d,\"ip\":\"%s\",\"rssi\":%d,\"quality\":%d,\"signal\":\"%s\",\"powersave\":\"%s\"},"
  2061. "\"services\":{\"mqtt_connected\":%s,\"mqtt_state\":\"%s\",\"web_enabled\":%s,\"web_panel_up\":%s,\"web_auth\":\"%s\","
  2062. "\"archive_available\":%s}",
  2063. (_stats_history.isEnabled() && _stats_history.isRecentHistoryAvailable()) ? "true" : "false",
  2064. _stats_history.isPsramBacked() ? "true" : "false",
  2065. _stats_history.isDegraded() ? "true" : "false",
  2066. _stats_history.isLiveOnly() ? "true" : "false",
  2067. static_cast<unsigned>(_stats_history.getSampleCount()),
  2068. static_cast<unsigned>(_stats_history.getSampleCapacity()),
  2069. static_cast<unsigned long>(StatsHistory::getSampleIntervalSecs()),
  2070. _stats_history.hasArchiveRestore() ? "true" : "false",
  2071. static_cast<unsigned>(_stats_history.getRestoredSampleCount()),
  2072. static_cast<unsigned long>(StatsHistory::getArchiveSummaryIntervalSecs()),
  2073. static_cast<unsigned>(_stats_history.getEventCount()),
  2074. static_cast<unsigned>(_stats_history.getEventCapacity()),
  2075. archive_name,
  2076. archive_available ? "true" : "false",
  2077. archive_path,
  2078. archive_type,
  2079. static_cast<unsigned long long>(_archive != nullptr ? _archive->getTotalBytes() : 0),
  2080. static_cast<unsigned long long>(_archive != nullptr ? _archive->getUsedBytes() : 0),
  2081. board.getBattMilliVolts(),
  2082. battery_pct,
  2083. static_cast<unsigned long>(uptime_millis / 1000),
  2084. _err_flags,
  2085. static_cast<unsigned>(_mgr->getOutboundTotal()),
  2086. board.isExternalPowered() ? "true" : "false",
  2087. board.isCharging() ? "true" : "false",
  2088. board.isVbusPresent() ? "true" : "false",
  2089. static_cast<int>(_radio->getNoiseFloor()),
  2090. radio_driver.getLastRSSI(),
  2091. radio_driver.getLastSNR(),
  2092. static_cast<unsigned long>(getTotalAirTime() / 1000),
  2093. static_cast<unsigned long>(getReceiveAirTime() / 1000),
  2094. static_cast<unsigned>(radio_driver.getPacketsRecv()),
  2095. static_cast<unsigned>(radio_driver.getPacketsSent()),
  2096. static_cast<unsigned>(getNumSentFlood()),
  2097. static_cast<unsigned>(getNumSentDirect()),
  2098. static_cast<unsigned>(getNumRecvFlood()),
  2099. static_cast<unsigned>(getNumRecvDirect()),
  2100. static_cast<unsigned>(radio_driver.getPacketsRecvErrors()),
  2101. static_cast<unsigned>(((SimpleMeshTables *)getTables())->getNumDirectDups()),
  2102. static_cast<unsigned>(((SimpleMeshTables *)getTables())->getNumFloodDups()),
  2103. static_cast<unsigned>(getNeighbourCount()),
  2104. ESP.getFreeHeap(),
  2105. ESP.getMinFreeHeap(),
  2106. ESP.getMaxAllocHeap(),
  2107. ESP.getFreePsram(),
  2108. ESP.getMinFreePsram(),
  2109. ESP.getMaxAllocPsram(),
  2110. wifi_ssid,
  2111. wifi_status,
  2112. network.isWifiConnected() ? "true" : "false",
  2113. wifi_state,
  2114. wifi_code,
  2115. wifi_ip,
  2116. wifi_rssi,
  2117. wifi_quality,
  2118. wifi_signal,
  2119. wifi_powersave,
  2120. mqtt_connected ? "true" : "false",
  2121. mqtt_state,
  2122. web.isWebEnabled() ? "true" : "false",
  2123. web_panel_up ? "true" : "false",
  2124. web.isPanelUnlocked() ? "unlocked" : "locked",
  2125. archive_available ? "true" : "false");
  2126. if (offset >= reply_size) {
  2127. return false;
  2128. }
  2129. offset += snprintf(&reply[offset], reply_size - offset, ",");
  2130. if (!appendJsonEvents(reply, reply_size, offset)) {
  2131. return false;
  2132. }
  2133. offset += snprintf(&reply[offset], reply_size - offset, ",");
  2134. if (!appendJsonNeighbours(reply, reply_size, offset)) {
  2135. return false;
  2136. }
  2137. offset += snprintf(&reply[offset], reply_size - offset, "}");
  2138. return offset < reply_size;
  2139. #endif
  2140. }
  2141. bool MyMesh::formatWebStatsSeriesJson(const char* series, char* reply, size_t reply_size) {
  2142. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  2143. if (!web.isWebStatsEnabled()) {
  2144. if (reply != nullptr && reply_size > 0) {
  2145. reply[0] = 0;
  2146. }
  2147. return false;
  2148. }
  2149. _stats_history.noteAccess(millis());
  2150. return _stats_history.buildSeriesJson(
  2151. series,
  2152. reply,
  2153. reply_size,
  2154. getRTCClock()->getCurrentTime(),
  2155. static_cast<uint32_t>(uptime_millis / 1000));
  2156. #else
  2157. (void)series;
  2158. if (reply != nullptr && reply_size > 0) {
  2159. reply[0] = 0;
  2160. }
  2161. return false;
  2162. #endif
  2163. }
  2164. void MyMesh::loop() {
  2165. #ifdef WITH_BRIDGE
  2166. bridge.loop();
  2167. #endif
  2168. const uint32_t now = millis();
  2169. uptime_millis += now - last_millis;
  2170. last_millis = now;
  2171. mesh::Mesh::loop();
  2172. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  2173. mesh::Packet *pkt = createSelfAdvert();
  2174. uint32_t delay_millis = 0;
  2175. if (pkt) sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1);
  2176. updateFloodAdvertTimer(); // schedule next flood advert
  2177. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  2178. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  2179. mesh::Packet *pkt = createSelfAdvert();
  2180. if (pkt) sendZeroHop(pkt);
  2181. updateAdvertTimer(); // schedule next local advert
  2182. }
  2183. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  2184. set_radio_at = 0; // clear timer
  2185. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  2186. MESH_DEBUG_PRINTLN("Temp radio params");
  2187. }
  2188. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  2189. revert_radio_at = 0; // clear timer
  2190. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  2191. MESH_DEBUG_PRINTLN("Radio params restored");
  2192. }
  2193. // is pending dirty contacts write needed?
  2194. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  2195. acl.save(_fs);
  2196. dirty_contacts_expiry = 0;
  2197. }
  2198. #if defined(ESP_PLATFORM)
  2199. bool network_required = false;
  2200. #if WITH_WEB_PANEL
  2201. network_required = web.isWebEnabled();
  2202. #endif
  2203. #ifdef WITH_MQTT_UPLINK
  2204. network_required = network_required || mqtt.isActive();
  2205. #endif
  2206. network.loop(network_required);
  2207. #if WITH_WEB_PANEL
  2208. web.loop();
  2209. #endif
  2210. #endif
  2211. #ifdef WITH_MQTT_UPLINK
  2212. MQTTStatusSnapshot mqtt_status{};
  2213. mqtt_status.battery_mv = static_cast<int>(board.getBattMilliVolts());
  2214. mqtt_status.uptime_secs = static_cast<uint32_t>(uptime_millis / 1000);
  2215. mqtt_status.error_flags = _err_flags;
  2216. mqtt_status.queue_len = static_cast<uint16_t>(_mgr->getOutboundTotal());
  2217. mqtt_status.noise_floor = static_cast<int>(_radio->getNoiseFloor());
  2218. mqtt_status.tx_air_secs = static_cast<uint32_t>(getTotalAirTime() / 1000);
  2219. mqtt_status.rx_air_secs = static_cast<uint32_t>(getReceiveAirTime() / 1000);
  2220. mqtt_status.recv_errors = radio_driver.getPacketsRecvErrors();
  2221. mqtt_status.radio_freq = _prefs.freq;
  2222. mqtt_status.radio_bw = _prefs.bw;
  2223. mqtt_status.radio_sf = _prefs.sf;
  2224. mqtt_status.radio_cr = _prefs.cr;
  2225. mqtt.loop(mqtt_status);
  2226. #endif
  2227. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  2228. updateStatsHistory(now);
  2229. #endif
  2230. }
  2231. // To check if there is pending work
  2232. bool MyMesh::hasPendingWork() const {
  2233. #if defined(WITH_BRIDGE)
  2234. if (bridge.isRunning()) return true; // bridge needs WiFi radio, can't sleep
  2235. #endif
  2236. #if defined(WITH_MQTT_UPLINK)
  2237. if (mqtt.isActive()) return true;
  2238. #endif
  2239. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  2240. if (web.isWebEnabled()) return true;
  2241. #endif
  2242. return _mgr->getOutboundTotal() > 0;
  2243. }