MyMesh.cpp 107 KB

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