MyMesh.cpp 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829
  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() && packet->getPathHashCount() >= _prefs.flood_max) return false;
  672. if (packet->isRouteFlood() && recv_pkt_region == NULL) {
  673. MESH_DEBUG_PRINTLN("allowPacketForward: unknown transport code, or wildcard not allowed for FLOOD packet");
  674. return false;
  675. }
  676. if (packet->isRouteFlood() && _prefs.loop_detect != LOOP_DETECT_OFF) {
  677. const uint8_t* maximums;
  678. if (_prefs.loop_detect == LOOP_DETECT_MINIMAL) {
  679. maximums = max_loop_minimal;
  680. } else if (_prefs.loop_detect == LOOP_DETECT_MODERATE) {
  681. maximums = max_loop_moderate;
  682. } else {
  683. maximums = max_loop_strict;
  684. }
  685. if (isLooped(packet, maximums)) {
  686. MESH_DEBUG_PRINTLN("allowPacketForward: FLOOD packet loop detected!");
  687. return false;
  688. }
  689. }
  690. return true;
  691. }
  692. const char *MyMesh::getLogDateTime() {
  693. static char tmp[32];
  694. uint32_t now = getRTCClock()->getCurrentTime();
  695. DateTime dt = DateTime(now);
  696. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
  697. dt.year());
  698. return tmp;
  699. }
  700. void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
  701. #if MESH_PACKET_LOGGING
  702. Serial.print(getLogDateTime());
  703. Serial.print(" RAW: ");
  704. mesh::Utils::printHex(Serial, raw, len);
  705. Serial.println();
  706. #endif
  707. }
  708. void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
  709. #ifdef WITH_BRIDGE
  710. if (_prefs.bridge_pkt_src == 1) {
  711. bridge.sendPacket(pkt);
  712. }
  713. #endif
  714. #ifdef WITH_MQTT_UPLINK
  715. mqtt.publishPacket(*pkt, false, (int)_radio->getLastRSSI(), _radio->getLastSNR(), (int)(score * 1000),
  716. (int)_radio->getEstAirtimeFor(len));
  717. #endif
  718. if (_logging) {
  719. File f = openAppend(PACKET_LOG_FILE);
  720. if (f) {
  721. f.print(getLogDateTime());
  722. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
  723. pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  724. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
  725. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  726. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  727. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  728. } else {
  729. f.printf("\n");
  730. }
  731. f.close();
  732. }
  733. }
  734. }
  735. void MyMesh::logTx(mesh::Packet *pkt, int len) {
  736. #ifdef WITH_BRIDGE
  737. if (_prefs.bridge_pkt_src == 0) {
  738. bridge.sendPacket(pkt);
  739. }
  740. #endif
  741. #ifdef WITH_MQTT_UPLINK
  742. mqtt.publishPacket(*pkt, true, (int)_radio->getLastRSSI(), _radio->getLastSNR());
  743. #endif
  744. if (_logging) {
  745. File f = openAppend(PACKET_LOG_FILE);
  746. if (f) {
  747. f.print(getLogDateTime());
  748. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  749. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  750. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  751. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  752. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  753. } else {
  754. f.printf("\n");
  755. }
  756. f.close();
  757. }
  758. }
  759. }
  760. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  761. if (_logging) {
  762. File f = openAppend(PACKET_LOG_FILE);
  763. if (f) {
  764. f.print(getLogDateTime());
  765. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  766. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  767. f.close();
  768. }
  769. }
  770. }
  771. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  772. if (_prefs.rx_delay_base <= 0.0f) return 0;
  773. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  774. }
  775. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  776. uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.tx_delay_factor);
  777. return getRNG()->nextInt(0, 5*t + 1);
  778. }
  779. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  780. uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  781. return getRNG()->nextInt(0, 5*t + 1);
  782. }
  783. bool MyMesh::filterRecvFloodPacket(mesh::Packet* pkt) {
  784. // just try to determine region for packet (apply later in allowPacketForward())
  785. if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
  786. recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
  787. } else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
  788. if (region_map.getWildcard().flags & REGION_DENY_FLOOD) {
  789. recv_pkt_region = NULL;
  790. } else {
  791. recv_pkt_region = &region_map.getWildcard();
  792. }
  793. } else {
  794. recv_pkt_region = NULL;
  795. }
  796. // do normal processing
  797. return false;
  798. }
  799. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  800. uint8_t *data, size_t len) {
  801. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  802. // client (unknown at this stage)
  803. uint32_t timestamp;
  804. memcpy(&timestamp, data, 4);
  805. data[len] = 0; // ensure null terminator
  806. uint8_t reply_len;
  807. reply_path_len = -1;
  808. if (data[4] == 0 || data[4] >= ' ') { // is password, ie. a login request
  809. reply_len = handleLoginReq(sender, secret, timestamp, &data[4], packet->isRouteFlood());
  810. } else if (data[4] == ANON_REQ_TYPE_REGIONS && packet->isRouteDirect()) {
  811. reply_len = handleAnonRegionsReq(sender, timestamp, &data[5]);
  812. } else if (data[4] == ANON_REQ_TYPE_OWNER && packet->isRouteDirect()) {
  813. reply_len = handleAnonOwnerReq(sender, timestamp, &data[5]);
  814. } else if (data[4] == ANON_REQ_TYPE_BASIC && packet->isRouteDirect()) {
  815. reply_len = handleAnonClockReq(sender, timestamp, &data[5]);
  816. } else {
  817. reply_len = 0; // unknown/invalid request type
  818. }
  819. if (reply_len == 0) return; // invalid request
  820. if (packet->isRouteFlood()) {
  821. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  822. mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
  823. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  824. if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  825. } else if (reply_path_len < 0) {
  826. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  827. if (reply) sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  828. } else {
  829. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  830. uint8_t path_len = ((reply_path_hash_size - 1) << 6) | (reply_path_len & 63);
  831. if (reply) sendDirect(reply, reply_path, path_len, SERVER_RESPONSE_DELAY);
  832. }
  833. }
  834. }
  835. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  836. int n = 0;
  837. for (int i = 0; i < acl.getNumClients(); i++) {
  838. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  839. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  840. }
  841. }
  842. return n;
  843. }
  844. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  845. int i = matching_peer_indexes[peer_idx];
  846. if (i >= 0 && i < acl.getNumClients()) {
  847. // lookup pre-calculated shared_secret
  848. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  849. } else {
  850. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  851. }
  852. }
  853. static bool isShare(const mesh::Packet *packet) {
  854. if (packet->hasTransportCodes()) {
  855. return packet->transport_codes[0] == 0 && packet->transport_codes[1] == 0; // codes { 0, 0 } means 'send to nowhere'
  856. }
  857. return false;
  858. }
  859. void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
  860. const uint8_t *app_data, size_t app_data_len) {
  861. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  862. // if this a zero hop advert (and not via 'Share'), add it to neighbours
  863. if (packet->path_len == 0 && !isShare(packet)) {
  864. AdvertDataParser parser(app_data, app_data_len);
  865. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  866. putNeighbour(id, timestamp, packet->getSNR());
  867. }
  868. }
  869. }
  870. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  871. uint8_t *data, size_t len) {
  872. int i = matching_peer_indexes[sender_idx];
  873. if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  874. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  875. return;
  876. }
  877. ClientInfo* client = acl.getClientByIdx(i);
  878. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  879. uint32_t timestamp;
  880. memcpy(&timestamp, data, 4);
  881. if (timestamp > client->last_timestamp) { // prevent replay attacks
  882. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  883. if (reply_len == 0) return; // invalid command
  884. client->last_timestamp = timestamp;
  885. client->last_activity = getRTCClock()->getCurrentTime();
  886. if (packet->isRouteFlood()) {
  887. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  888. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  889. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  890. if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  891. } else {
  892. mesh::Packet *reply =
  893. createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  894. if (reply) {
  895. if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
  896. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  897. } else {
  898. sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
  899. }
  900. }
  901. }
  902. } else {
  903. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  904. }
  905. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->isAdmin()) { // a CLI command
  906. uint32_t sender_timestamp;
  907. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  908. uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
  909. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  910. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  911. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  912. bool is_retry = (sender_timestamp == client->last_timestamp);
  913. client->last_timestamp = sender_timestamp;
  914. client->last_activity = getRTCClock()->getCurrentTime();
  915. // len can be > original length, but 'text' will be padded with zeroes
  916. data[len] = 0; // need to make a C string again, with null terminator
  917. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  918. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
  919. // to sender that we got it
  920. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  921. PUB_KEY_SIZE);
  922. mesh::Packet *ack = createAck(ack_hash);
  923. if (ack) {
  924. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  925. sendFloodReply(ack, TXT_ACK_DELAY, packet->getPathHashSize());
  926. } else {
  927. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  928. }
  929. }
  930. }
  931. uint8_t temp[166];
  932. char *command = (char *)&data[5];
  933. char *reply = (char *)&temp[5];
  934. if (is_retry) {
  935. *reply = 0;
  936. } else {
  937. handleCommand(sender_timestamp, command, reply);
  938. }
  939. int text_len = strlen(reply);
  940. if (text_len > 0) {
  941. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  942. if (timestamp == sender_timestamp) {
  943. // WORKAROUND: the two timestamps need to be different, in the CLI view
  944. timestamp++;
  945. }
  946. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  947. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  948. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  949. if (reply) {
  950. if (client->out_path_len == OUT_PATH_UNKNOWN) {
  951. sendFloodReply(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize());
  952. } else {
  953. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  954. }
  955. }
  956. }
  957. } else {
  958. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  959. }
  960. }
  961. }
  962. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  963. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  964. // TODO: prevent replay attacks
  965. int i = matching_peer_indexes[sender_idx];
  966. if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
  967. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  968. auto client = acl.getClientByIdx(i);
  969. // store a copy of path, for sendDirect()
  970. client->out_path_len = mesh::Packet::copyPath(client->out_path, path, path_len);
  971. client->last_activity = getRTCClock()->getCurrentTime();
  972. } else {
  973. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  974. }
  975. // NOTE: no reciprocal path send!!
  976. return false;
  977. }
  978. #define CTL_TYPE_NODE_DISCOVER_REQ 0x80
  979. #define CTL_TYPE_NODE_DISCOVER_RESP 0x90
  980. void MyMesh::onControlDataRecv(mesh::Packet* packet) {
  981. uint8_t type = packet->payload[0] & 0xF0; // just test upper 4 bits
  982. if (type == CTL_TYPE_NODE_DISCOVER_REQ && packet->payload_len >= 6
  983. && !_prefs.disable_fwd && discover_limiter.allow(rtc_clock.getCurrentTime())
  984. ) {
  985. int i = 1;
  986. uint8_t filter = packet->payload[i++];
  987. uint32_t tag;
  988. memcpy(&tag, &packet->payload[i], 4); i += 4;
  989. uint32_t since;
  990. if (packet->payload_len >= i+4) { // optional since field
  991. memcpy(&since, &packet->payload[i], 4); i += 4;
  992. } else {
  993. since = 0;
  994. }
  995. if ((filter & (1 << ADV_TYPE_REPEATER)) != 0 && _prefs.discovery_mod_timestamp >= since) {
  996. bool prefix_only = packet->payload[0] & 1;
  997. uint8_t data[6 + PUB_KEY_SIZE];
  998. data[0] = CTL_TYPE_NODE_DISCOVER_RESP | ADV_TYPE_REPEATER; // low 4-bits for node type
  999. data[1] = packet->_snr; // let sender know the inbound SNR ( x 4)
  1000. memcpy(&data[2], &tag, 4); // include tag from request, for client to match to
  1001. memcpy(&data[6], self_id.pub_key, PUB_KEY_SIZE);
  1002. auto resp = createControlData(data, prefix_only ? 6 + 8 : 6 + PUB_KEY_SIZE);
  1003. if (resp) {
  1004. sendZeroHop(resp, getRetransmitDelay(resp)*4); // apply random delay (widened x4), as multiple nodes can respond to this
  1005. }
  1006. }
  1007. } else if (type == CTL_TYPE_NODE_DISCOVER_RESP && packet->payload_len >= 6) {
  1008. uint8_t node_type = packet->payload[0] & 0x0F;
  1009. if (node_type != ADV_TYPE_REPEATER) {
  1010. return;
  1011. }
  1012. if (packet->payload_len < 6 + PUB_KEY_SIZE) {
  1013. MESH_DEBUG_PRINTLN("onControlDataRecv: DISCOVER_RESP pubkey too short: %d", (uint32_t)packet->payload_len);
  1014. return;
  1015. }
  1016. if (pending_discover_tag == 0 || millisHasNowPassed(pending_discover_until)) {
  1017. pending_discover_tag = 0;
  1018. return;
  1019. }
  1020. uint32_t tag;
  1021. memcpy(&tag, &packet->payload[2], 4);
  1022. if (tag != pending_discover_tag) {
  1023. return;
  1024. }
  1025. mesh::Identity id(&packet->payload[6]);
  1026. if (id.matches(self_id)) {
  1027. return;
  1028. }
  1029. putNeighbour(id, rtc_clock.getCurrentTime(), packet->getSNR());
  1030. }
  1031. }
  1032. void MyMesh::sendNodeDiscoverReq() {
  1033. uint8_t data[10];
  1034. data[0] = CTL_TYPE_NODE_DISCOVER_REQ; // prefix_only=0
  1035. data[1] = (1 << ADV_TYPE_REPEATER);
  1036. getRNG()->random(&data[2], 4); // tag
  1037. memcpy(&pending_discover_tag, &data[2], 4);
  1038. pending_discover_until = futureMillis(60000);
  1039. uint32_t since = 0;
  1040. memcpy(&data[6], &since, 4);
  1041. auto pkt = createControlData(data, sizeof(data));
  1042. if (pkt) {
  1043. sendZeroHop(pkt);
  1044. }
  1045. }
  1046. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  1047. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  1048. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  1049. region_map(key_store), temp_map(key_store),
  1050. _cli(board, rtc, sensors, region_map, acl, &_prefs, this),
  1051. telemetry(MAX_PACKET_PAYLOAD - 4),
  1052. discover_limiter(4, 120), // max 4 every 2 minutes
  1053. anon_limiter(4, 180) // max 4 every 3 minutes
  1054. #if defined(WITH_RS232_BRIDGE)
  1055. , bridge(&_prefs, WITH_RS232_BRIDGE, _mgr, &rtc)
  1056. #endif
  1057. #if defined(WITH_ESPNOW_BRIDGE)
  1058. , bridge(&_prefs, _mgr, &rtc)
  1059. #endif
  1060. #if defined(WITH_MQTT_UPLINK)
  1061. , mqtt(rtc, self_id)
  1062. #endif
  1063. {
  1064. last_millis = 0;
  1065. _archive = nullptr;
  1066. uptime_millis = 0;
  1067. next_archive_neighbours_flush_ms = 0;
  1068. next_battery_sample_ms = 0;
  1069. next_history_sample_ms = 0;
  1070. next_local_advert = next_flood_advert = 0;
  1071. dirty_contacts_expiry = 0;
  1072. set_radio_at = revert_radio_at = 0;
  1073. _logging = false;
  1074. _archive_neighbours_dirty = false;
  1075. _battery_sample_valid = false;
  1076. _battery_mv_cache = 0;
  1077. region_load_active = false;
  1078. memset(&_stats_state, 0, sizeof(_stats_state));
  1079. #if MAX_NEIGHBOURS
  1080. memset(neighbours, 0, sizeof(neighbours));
  1081. #endif
  1082. // defaults
  1083. memset(&_prefs, 0, sizeof(_prefs));
  1084. _prefs.airtime_factor = 1.0;
  1085. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  1086. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  1087. _prefs.direct_tx_delay_factor = 0.3f; // was 0.2
  1088. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  1089. _prefs.node_lat = ADVERT_LAT;
  1090. _prefs.node_lon = ADVERT_LON;
  1091. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  1092. _prefs.freq = LORA_FREQ;
  1093. _prefs.sf = LORA_SF;
  1094. _prefs.bw = LORA_BW;
  1095. _prefs.cr = LORA_CR;
  1096. _prefs.tx_power_dbm = LORA_TX_POWER;
  1097. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  1098. _prefs.flood_advert_interval = 12; // 12 hours
  1099. _prefs.flood_max = 64;
  1100. _prefs.interference_threshold = 0; // disabled
  1101. // bridge defaults
  1102. _prefs.bridge_enabled = 1; // enabled
  1103. _prefs.bridge_delay = 500; // milliseconds
  1104. _prefs.bridge_pkt_src = 0; // logTx
  1105. _prefs.bridge_baud = 115200; // baud rate
  1106. _prefs.bridge_channel = 1; // channel 1
  1107. StrHelper::strncpy(_prefs.bridge_secret, "LVSITANOS", sizeof(_prefs.bridge_secret));
  1108. // GPS defaults
  1109. _prefs.gps_enabled = 0;
  1110. _prefs.gps_interval = 0;
  1111. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  1112. _prefs.adc_multiplier = 0.0f; // 0.0f means use default board multiplier
  1113. _prefs.reserved_290 = 0;
  1114. _prefs.fan_mode = 0; // auto
  1115. _prefs.fan_timeout_secs = 30;
  1116. #if defined(USE_SX1262) || defined(USE_SX1268)
  1117. #ifdef SX126X_RX_BOOSTED_GAIN
  1118. _prefs.rx_boosted_gain = SX126X_RX_BOOSTED_GAIN;
  1119. #else
  1120. _prefs.rx_boosted_gain = 1; // enabled by default;
  1121. #endif
  1122. #endif
  1123. pending_discover_tag = 0;
  1124. pending_discover_until = 0;
  1125. memset(default_scope.key, 0, sizeof(default_scope.key));
  1126. }
  1127. void MyMesh::begin(FILESYSTEM *fs, ArchiveStorage* archive) {
  1128. mesh::Mesh::begin();
  1129. _fs = fs;
  1130. _archive = archive;
  1131. last_millis = millis();
  1132. // load persisted prefs
  1133. _cli.loadPrefs(_fs);
  1134. acl.load(_fs, self_id);
  1135. // TODO: key_store.begin();
  1136. region_map.load(_fs);
  1137. // establish default-scope
  1138. {
  1139. RegionEntry* r = region_map.getDefaultRegion();
  1140. if (r) {
  1141. region_map.getTransportKeysFor(*r, &default_scope, 1);
  1142. } else {
  1143. #ifdef DEFAULT_FLOOD_SCOPE_NAME
  1144. r = region_map.findByName(DEFAULT_FLOOD_SCOPE_NAME);
  1145. if (r == NULL) {
  1146. r = region_map.putRegion(DEFAULT_FLOOD_SCOPE_NAME, 0); // auto-create the default scope region
  1147. if (r) { r->flags = 0; } // Allow-flood
  1148. }
  1149. if (r) {
  1150. region_map.setDefaultRegion(r);
  1151. region_map.getTransportKeysFor(*r, &default_scope, 1);
  1152. }
  1153. #endif
  1154. }
  1155. }
  1156. #if defined(WITH_BRIDGE)
  1157. if (_prefs.bridge_enabled) {
  1158. bridge.begin();
  1159. }
  1160. #endif
  1161. #if defined(ESP_PLATFORM)
  1162. uint8_t legacy_wifi_powersave = 0;
  1163. const char* legacy_wifi_ssid = nullptr;
  1164. const char* legacy_wifi_pwd = nullptr;
  1165. #ifdef WITH_MQTT_UPLINK
  1166. MQTTPrefs legacy_mqtt_prefs{};
  1167. MQTTPrefsStore::setDefaults(legacy_mqtt_prefs);
  1168. MQTTPrefsStore::load(_fs, legacy_mqtt_prefs);
  1169. legacy_wifi_powersave = legacy_mqtt_prefs.legacy_wifi_powersave;
  1170. legacy_wifi_ssid = legacy_mqtt_prefs.legacy_wifi_ssid;
  1171. legacy_wifi_pwd = legacy_mqtt_prefs.legacy_wifi_pwd;
  1172. #endif
  1173. network.begin(_fs, legacy_wifi_powersave, legacy_wifi_ssid, legacy_wifi_pwd);
  1174. #endif
  1175. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  1176. board.setInhibitSleep(true);
  1177. web.setCommandRunner(this);
  1178. web.setNetworkStateProvider(&network);
  1179. web.begin(_fs);
  1180. _stats_history.begin(web.isWebStatsEnabled(), _archive);
  1181. if (web.isWebStatsEnabled() && !_stats_history.isLiveOnly() && _archive != nullptr && _archive->isMounted()) {
  1182. restoreArchiveNeighbours();
  1183. next_archive_neighbours_flush_ms = millis() + kArchiveNeighboursFlushIntervalMs;
  1184. }
  1185. if (web.isWebStatsEnabled()) {
  1186. recordStatsEvent(HISTORY_EVENT_BOOT);
  1187. if (_archive != nullptr) {
  1188. recordStatsEvent(_archive->isMounted() ? HISTORY_EVENT_ARCHIVE_MOUNTED : HISTORY_EVENT_ARCHIVE_UNAVAILABLE);
  1189. }
  1190. }
  1191. #endif
  1192. #if defined(WITH_MQTT_UPLINK) && !(defined(ESP_PLATFORM) && WITH_WEB_PANEL)
  1193. board.setInhibitSleep(true);
  1194. #endif
  1195. #ifdef WITH_MQTT_UPLINK
  1196. mqtt.setNodeNameSource(_prefs.node_name);
  1197. #if defined(ESP_PLATFORM)
  1198. mqtt.setNetworkStateProvider(&network);
  1199. #endif
  1200. mqtt.begin(_fs);
  1201. #endif
  1202. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  1203. radio_set_tx_power(_prefs.tx_power_dbm);
  1204. radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);
  1205. MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s",
  1206. radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled");
  1207. updateAdvertTimer();
  1208. updateFloodAdvertTimer();
  1209. board.setAdcMultiplier(_prefs.adc_multiplier);
  1210. #if defined(TBEAM_1W)
  1211. auto& tbeam1w_board = static_cast<TBeam1WBoard&>(board);
  1212. tbeam1w_board.setFanPostTxHoldMs(static_cast<uint32_t>(_prefs.fan_timeout_secs) * 1000UL);
  1213. tbeam1w_board.setFanMode(static_cast<TBeam1WBoard::FanMode>(_prefs.fan_mode));
  1214. #endif
  1215. #if ENV_INCLUDE_GPS == 1
  1216. applyGpsPrefs();
  1217. #endif
  1218. next_history_sample_ms = futureMillis(1000);
  1219. }
  1220. void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size) {
  1221. if (scope.isNull()) {
  1222. sendFlood(pkt, delay_millis, path_hash_size);
  1223. } else {
  1224. uint16_t codes[2];
  1225. codes[0] = scope.calcTransportCode(pkt);
  1226. codes[1] = 0; // REVISIT: set to 'home' Region, for sender/return region?
  1227. sendFlood(pkt, codes, delay_millis, path_hash_size);
  1228. }
  1229. }
  1230. uint16_t MyMesh::getBatteryMilliVolts(bool force_refresh) {
  1231. constexpr unsigned long kBatterySampleIntervalMs = 60000UL;
  1232. if (force_refresh || !_battery_sample_valid || next_battery_sample_ms == 0 || millisHasNowPassed(next_battery_sample_ms)) {
  1233. _battery_mv_cache = board.getBattMilliVolts();
  1234. _battery_sample_valid = true;
  1235. next_battery_sample_ms = millis() + kBatterySampleIntervalMs;
  1236. }
  1237. return _battery_mv_cache;
  1238. }
  1239. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  1240. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  1241. pending_freq = freq;
  1242. pending_bw = bw;
  1243. pending_sf = sf;
  1244. pending_cr = cr;
  1245. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  1246. }
  1247. bool MyMesh::formatFileSystem() {
  1248. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  1249. return InternalFS.format();
  1250. #elif defined(RP2040_PLATFORM)
  1251. return LittleFS.format();
  1252. #elif defined(ESP32)
  1253. return SPIFFS.format();
  1254. #else
  1255. #error "need to implement file system erase"
  1256. return false;
  1257. #endif
  1258. }
  1259. void MyMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
  1260. mesh::Packet *pkt = createSelfAdvert();
  1261. if (pkt) {
  1262. if (flood) {
  1263. sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
  1264. } else {
  1265. sendZeroHop(pkt, delay_millis);
  1266. }
  1267. } else {
  1268. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  1269. }
  1270. }
  1271. void MyMesh::updateAdvertTimer() {
  1272. if (_prefs.advert_interval > 0) { // schedule local advert timer
  1273. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  1274. } else {
  1275. next_local_advert = 0; // stop the timer
  1276. }
  1277. }
  1278. void MyMesh::updateFloodAdvertTimer() {
  1279. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  1280. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  1281. } else {
  1282. next_flood_advert = 0; // stop the timer
  1283. }
  1284. }
  1285. void MyMesh::dumpLogFile() {
  1286. #if defined(RP2040_PLATFORM)
  1287. File f = _fs->open(PACKET_LOG_FILE, "r");
  1288. #else
  1289. File f = _fs->open(PACKET_LOG_FILE);
  1290. #endif
  1291. if (f) {
  1292. while (f.available()) {
  1293. int c = f.read();
  1294. if (c < 0) break;
  1295. Serial.print((char)c);
  1296. }
  1297. f.close();
  1298. }
  1299. }
  1300. void MyMesh::setTxPower(int8_t power_dbm) {
  1301. radio_set_tx_power(power_dbm);
  1302. }
  1303. #if defined(USE_SX1262) || defined(USE_SX1268)
  1304. void MyMesh::setRxBoostedGain(bool enable) {
  1305. radio_driver.setRxBoostedGainMode(enable);
  1306. }
  1307. #endif
  1308. void MyMesh::formatNeighborsReply(char *reply) {
  1309. char *dp = reply;
  1310. #if MAX_NEIGHBOURS
  1311. // create copy of neighbours list, skipping empty entries so we can sort it separately from main list
  1312. int16_t neighbours_count = 0;
  1313. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  1314. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  1315. auto neighbour = &neighbours[i];
  1316. if (neighbour->heard_timestamp > 0) {
  1317. sorted_neighbours[neighbours_count] = neighbour;
  1318. neighbours_count++;
  1319. }
  1320. }
  1321. // sort neighbours newest to oldest
  1322. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  1323. return a->heard_timestamp > b->heard_timestamp; // desc
  1324. });
  1325. for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
  1326. NeighbourInfo *neighbour = sorted_neighbours[i];
  1327. // add new line if not first item
  1328. if (i > 0) *dp++ = '\n';
  1329. char hex[10];
  1330. // get 4 bytes of neighbour id as hex
  1331. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  1332. // add next neighbour
  1333. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  1334. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  1335. while (*dp)
  1336. dp++; // find end of string
  1337. }
  1338. #endif
  1339. if (dp == reply) { // no neighbours, need empty response
  1340. strcpy(dp, "-none-");
  1341. dp += 6;
  1342. }
  1343. *dp = 0; // null terminator
  1344. }
  1345. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  1346. #if MAX_NEIGHBOURS
  1347. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  1348. NeighbourInfo *neighbour = &neighbours[i];
  1349. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  1350. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  1351. _archive_neighbours_dirty = true;
  1352. }
  1353. }
  1354. #endif
  1355. }
  1356. void MyMesh::formatStatsReply(char *reply, size_t reply_size) {
  1357. snprintf(reply,
  1358. reply_size,
  1359. "{\"battery_mv\":%u,\"uptime_secs\":%u,\"errors\":%u,\"queue_len\":%u}",
  1360. getBatteryMilliVolts(true),
  1361. _ms->getMillis() / 1000,
  1362. _err_flags,
  1363. _mgr->getOutboundTotal());
  1364. }
  1365. void MyMesh::startRegionsLoad() {
  1366. temp_map.resetFrom(region_map); // rebuild regions in a temp instance
  1367. memset(load_stack, 0, sizeof(load_stack));
  1368. load_stack[0] = &temp_map.getWildcard();
  1369. region_load_active = true;
  1370. }
  1371. bool MyMesh::saveRegions() {
  1372. return region_map.save(_fs);
  1373. }
  1374. void MyMesh::onDefaultRegionChanged(const RegionEntry* r) {
  1375. if (r) {
  1376. region_map.getTransportKeysFor(*r, &default_scope, 1);
  1377. } else {
  1378. memset(default_scope.key, 0, sizeof(default_scope.key));
  1379. }
  1380. }
  1381. void MyMesh::formatRadioStatsReply(char *reply, size_t reply_size) {
  1382. StatsFormatHelper::formatRadioStats(reply, reply_size, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
  1383. }
  1384. void MyMesh::formatPacketStatsReply(char *reply, size_t reply_size) {
  1385. StatsFormatHelper::formatPacketStats(reply, reply_size, radio_driver, getNumSentFlood(), getNumSentDirect(),
  1386. getNumRecvFlood(), getNumRecvDirect());
  1387. }
  1388. void MyMesh::formatMemoryReply(char *reply, size_t reply_size) {
  1389. StatsFormatHelper::formatMemoryStats(reply, reply_size);
  1390. }
  1391. size_t MyMesh::getNeighbourCount() const {
  1392. #if MAX_NEIGHBOURS
  1393. size_t count = 0;
  1394. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  1395. if (neighbours[i].heard_timestamp > 0) {
  1396. count++;
  1397. }
  1398. }
  1399. return count;
  1400. #else
  1401. return 0;
  1402. #endif
  1403. }
  1404. bool MyMesh::restoreArchiveNeighbours() {
  1405. #if MAX_NEIGHBOURS
  1406. if (_archive == nullptr || !_archive->isMounted()) {
  1407. return false;
  1408. }
  1409. FILESYSTEM* fs = _archive->getFS();
  1410. if (fs == nullptr) {
  1411. return false;
  1412. }
  1413. const char* restore_path = nullptr;
  1414. if (fs->exists(kArchiveNeighboursLatestPath)) {
  1415. restore_path = kArchiveNeighboursLatestPath;
  1416. } else if (fs->exists(kArchiveNeighboursSnapshotPath)) {
  1417. restore_path = kArchiveNeighboursSnapshotPath;
  1418. } else {
  1419. return false;
  1420. }
  1421. File file = openArchiveReadWithRecovery(_archive, restore_path);
  1422. if (!file) {
  1423. ARCHIVE_LOG("neighbours restore open failed path=%s", restore_path);
  1424. return false;
  1425. }
  1426. memset(neighbours, 0, sizeof(neighbours));
  1427. char line[128];
  1428. size_t line_len = 0;
  1429. size_t restored = 0;
  1430. while (file.available()) {
  1431. const int raw = file.read();
  1432. if (raw < 0) {
  1433. break;
  1434. }
  1435. const char ch = static_cast<char>(raw);
  1436. if (ch == '\r') {
  1437. continue;
  1438. }
  1439. if (ch == '\n') {
  1440. line[line_len] = 0;
  1441. if (line_len > 0 && restored < MAX_NEIGHBOURS) {
  1442. char full_hex[65];
  1443. unsigned long advert_timestamp = 0;
  1444. unsigned long heard_timestamp = 0;
  1445. int snr = 0;
  1446. memset(full_hex, 0, sizeof(full_hex));
  1447. if (sscanf(line, "%64[^,],%lu,%lu,%d", full_hex, &advert_timestamp, &heard_timestamp, &snr) == 4) {
  1448. uint8_t pub_key[PUB_KEY_SIZE];
  1449. if (mesh::Utils::fromHex(pub_key, PUB_KEY_SIZE, full_hex)) {
  1450. neighbours[restored].id = mesh::Identity(pub_key);
  1451. neighbours[restored].advert_timestamp = static_cast<uint32_t>(advert_timestamp);
  1452. neighbours[restored].heard_timestamp = static_cast<uint32_t>(heard_timestamp);
  1453. neighbours[restored].snr = static_cast<int8_t>(constrain(snr, -128, 127));
  1454. restored++;
  1455. }
  1456. }
  1457. }
  1458. line_len = 0;
  1459. continue;
  1460. }
  1461. if (line_len + 1 < sizeof(line)) {
  1462. line[line_len++] = ch;
  1463. }
  1464. }
  1465. if (line_len > 0 && restored < MAX_NEIGHBOURS) {
  1466. line[line_len] = 0;
  1467. char full_hex[65];
  1468. unsigned long advert_timestamp = 0;
  1469. unsigned long heard_timestamp = 0;
  1470. int snr = 0;
  1471. memset(full_hex, 0, sizeof(full_hex));
  1472. if (sscanf(line, "%64[^,],%lu,%lu,%d", full_hex, &advert_timestamp, &heard_timestamp, &snr) == 4) {
  1473. uint8_t pub_key[PUB_KEY_SIZE];
  1474. if (mesh::Utils::fromHex(pub_key, PUB_KEY_SIZE, full_hex)) {
  1475. neighbours[restored].id = mesh::Identity(pub_key);
  1476. neighbours[restored].advert_timestamp = static_cast<uint32_t>(advert_timestamp);
  1477. neighbours[restored].heard_timestamp = static_cast<uint32_t>(heard_timestamp);
  1478. neighbours[restored].snr = static_cast<int8_t>(constrain(snr, -128, 127));
  1479. restored++;
  1480. }
  1481. }
  1482. }
  1483. file.close();
  1484. _archive_neighbours_dirty = false;
  1485. return restored > 0;
  1486. #else
  1487. return false;
  1488. #endif
  1489. }
  1490. void MyMesh::flushArchiveNeighbours() {
  1491. #if MAX_NEIGHBOURS
  1492. if (_archive == nullptr || !_archive->isMounted()) {
  1493. return;
  1494. }
  1495. FILESYSTEM* fs = _archive->getFS();
  1496. if (fs == nullptr) {
  1497. return;
  1498. }
  1499. int16_t neighbours_count = 0;
  1500. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  1501. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  1502. if (neighbours[i].heard_timestamp > 0) {
  1503. sorted_neighbours[neighbours_count++] = &neighbours[i];
  1504. }
  1505. }
  1506. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  1507. return a->heard_timestamp > b->heard_timestamp;
  1508. });
  1509. char latest_block[1536];
  1510. size_t latest_len = 0;
  1511. uint32_t latest_epoch_secs = 0;
  1512. for (int i = 0; i < neighbours_count; ++i) {
  1513. char full_hex[65];
  1514. mesh::Utils::toHex(full_hex, sorted_neighbours[i]->id.pub_key, PUB_KEY_SIZE);
  1515. latest_len += snprintf(&latest_block[latest_len], sizeof(latest_block) - latest_len,
  1516. "%s,%lu,%lu,%d\n",
  1517. full_hex,
  1518. static_cast<unsigned long>(sorted_neighbours[i]->advert_timestamp),
  1519. static_cast<unsigned long>(sorted_neighbours[i]->heard_timestamp),
  1520. static_cast<int>(sorted_neighbours[i]->snr));
  1521. latest_epoch_secs = max<uint32_t>(latest_epoch_secs, sorted_neighbours[i]->heard_timestamp);
  1522. if (latest_len >= sizeof(latest_block)) {
  1523. latest_len = sizeof(latest_block) - 1;
  1524. break;
  1525. }
  1526. }
  1527. File latest_file = openArchiveWriteWithRecovery(_archive, kArchiveNeighboursLatestPath);
  1528. if (!latest_file) {
  1529. ARCHIVE_LOG("neighbours open failed path=%s", kArchiveNeighboursLatestPath);
  1530. return;
  1531. }
  1532. const size_t latest_written = latest_file.print(latest_block);
  1533. latest_file.flush();
  1534. latest_file.close();
  1535. char daily_path[52];
  1536. buildUtcDailyArchivePath("neighbours", latest_epoch_secs, daily_path, sizeof(daily_path));
  1537. File file = openArchiveAppendWithRecovery(_archive, daily_path);
  1538. if (!file) {
  1539. ARCHIVE_LOG("neighbours open failed path=%s", daily_path);
  1540. return;
  1541. }
  1542. size_t total_written = 0;
  1543. for (int i = 0; i < neighbours_count; ++i) {
  1544. char full_hex[65];
  1545. mesh::Utils::toHex(full_hex, sorted_neighbours[i]->id.pub_key, PUB_KEY_SIZE);
  1546. total_written += file.printf("%s,%lu,%lu,%d\n",
  1547. full_hex,
  1548. static_cast<unsigned long>(sorted_neighbours[i]->advert_timestamp),
  1549. static_cast<unsigned long>(sorted_neighbours[i]->heard_timestamp),
  1550. static_cast<int>(sorted_neighbours[i]->snr));
  1551. }
  1552. file.flush();
  1553. file.close();
  1554. ARCHIVE_LOG("neighbours flushed latest=%s bytes=%u log=%s log_bytes=%u count=%d",
  1555. kArchiveNeighboursLatestPath,
  1556. static_cast<unsigned>(latest_written),
  1557. daily_path,
  1558. static_cast<unsigned>(total_written),
  1559. static_cast<int>(neighbours_count));
  1560. _archive_neighbours_dirty = false;
  1561. #endif
  1562. }
  1563. void MyMesh::maybeFlushArchiveNeighbours(unsigned long now_ms) {
  1564. #if MAX_NEIGHBOURS
  1565. if (!_archive_neighbours_dirty || _archive == nullptr || !_archive->isMounted()) {
  1566. return;
  1567. }
  1568. if (next_archive_neighbours_flush_ms == 0 || millisHasNowPassed(next_archive_neighbours_flush_ms)) {
  1569. flushArchiveNeighbours();
  1570. next_archive_neighbours_flush_ms = now_ms + kArchiveNeighboursFlushIntervalMs;
  1571. }
  1572. #else
  1573. (void)now_ms;
  1574. #endif
  1575. }
  1576. void MyMesh::recordStatsEvent(uint8_t type, int16_t value) {
  1577. _stats_history.recordEvent(type, getRTCClock()->getCurrentTime(), static_cast<uint32_t>(uptime_millis / 1000), value);
  1578. }
  1579. void MyMesh::updateStatsHistory(unsigned long now_ms) {
  1580. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  1581. constexpr uint32_t kLowMemoryEnterBytes = 32UL * 1024UL;
  1582. constexpr uint32_t kLowMemoryClearBytes = 48UL * 1024UL;
  1583. constexpr uint32_t kLowMemoryEventCooldownSecs = 5UL * 60UL;
  1584. _stats_history.setArchive(_archive);
  1585. _stats_history.setEnabled(web.isWebStatsEnabled());
  1586. if (!_stats_history.isEnabled()) {
  1587. _stats_state.initialized = false;
  1588. _archive_neighbours_dirty = false;
  1589. return;
  1590. }
  1591. _stats_history.maybeReleaseIdleBuffers(now_ms);
  1592. const bool wifi_connected = network.isWifiConnected();
  1593. #ifdef WITH_MQTT_UPLINK
  1594. const bool mqtt_connected = mqtt.isAnyBrokerConnected();
  1595. #else
  1596. const bool mqtt_connected = false;
  1597. #endif
  1598. const bool web_panel_up = web.isPanelRunning();
  1599. const bool archive_mounted = (_archive != nullptr) && _archive->isMounted();
  1600. #if defined(ESP32)
  1601. const uint32_t free_heap = ESP.getFreeHeap();
  1602. const uint32_t max_alloc_heap = ESP.getMaxAllocHeap();
  1603. const uint32_t uptime_secs = static_cast<uint32_t>(uptime_millis / 1000);
  1604. bool low_memory = _stats_state.low_memory;
  1605. if (!_stats_state.initialized) {
  1606. low_memory = free_heap <= kLowMemoryEnterBytes;
  1607. } else if (low_memory) {
  1608. low_memory = free_heap <= kLowMemoryClearBytes;
  1609. } else {
  1610. low_memory = free_heap <= kLowMemoryEnterBytes;
  1611. }
  1612. #else
  1613. const bool low_memory = false;
  1614. #endif
  1615. if (!_stats_state.initialized) {
  1616. _stats_state.initialized = true;
  1617. _stats_state.wifi_connected = wifi_connected;
  1618. _stats_state.mqtt_connected = mqtt_connected;
  1619. _stats_state.web_panel_up = web_panel_up;
  1620. _stats_state.archive_mounted = archive_mounted;
  1621. _stats_state.low_memory = low_memory;
  1622. _stats_state.last_low_memory_event_uptime_secs = 0;
  1623. } else {
  1624. if (_stats_state.mqtt_connected != mqtt_connected) {
  1625. recordStatsEvent(mqtt_connected ? HISTORY_EVENT_MQTT_CONNECTED : HISTORY_EVENT_MQTT_DISCONNECTED);
  1626. _stats_state.mqtt_connected = mqtt_connected;
  1627. }
  1628. if (_stats_state.web_panel_up != web_panel_up) {
  1629. recordStatsEvent(web_panel_up ? HISTORY_EVENT_WEB_STARTED : HISTORY_EVENT_WEB_STOPPED);
  1630. _stats_state.web_panel_up = web_panel_up;
  1631. }
  1632. if (_stats_state.archive_mounted != archive_mounted) {
  1633. recordStatsEvent(archive_mounted ? HISTORY_EVENT_ARCHIVE_MOUNTED : HISTORY_EVENT_ARCHIVE_UNAVAILABLE);
  1634. _stats_state.archive_mounted = archive_mounted;
  1635. if (!_stats_history.isLiveOnly() && archive_mounted) {
  1636. if (getNeighbourCount() == 0) {
  1637. restoreArchiveNeighbours();
  1638. }
  1639. next_archive_neighbours_flush_ms = now_ms + kArchiveNeighboursFlushIntervalMs;
  1640. }
  1641. }
  1642. if (!_stats_history.isLiveOnly() && !_stats_state.low_memory && low_memory) {
  1643. #if defined(ESP32)
  1644. if (_stats_state.last_low_memory_event_uptime_secs == 0 ||
  1645. (uptime_secs - _stats_state.last_low_memory_event_uptime_secs) >= kLowMemoryEventCooldownSecs) {
  1646. recordStatsEvent(HISTORY_EVENT_LOW_MEMORY, static_cast<int16_t>(min<uint32_t>(free_heap / 1024, 32767)));
  1647. _stats_state.last_low_memory_event_uptime_secs = uptime_secs;
  1648. }
  1649. #endif
  1650. }
  1651. _stats_state.wifi_connected = wifi_connected;
  1652. _stats_state.low_memory = low_memory;
  1653. }
  1654. #if defined(ESP32)
  1655. const bool live_stats_headroom_low =
  1656. _stats_history.isLiveOnly() && (free_heap <= kLowMemoryClearBytes || max_alloc_heap <= (24UL * 1024UL));
  1657. #else
  1658. const bool live_stats_headroom_low = false;
  1659. #endif
  1660. if (next_history_sample_ms == 0 || millisHasNowPassed(next_history_sample_ms)) {
  1661. if (!live_stats_headroom_low) {
  1662. const uint16_t battery_mv = getBatteryMilliVolts();
  1663. WebSensorSnapshot sensor_snapshot = collectWebSensorSnapshot(board, sensors, battery_mv);
  1664. HistorySample sample{};
  1665. sample.epoch_secs = getRTCClock()->getCurrentTime();
  1666. sample.uptime_secs = static_cast<uint32_t>(uptime_millis / 1000);
  1667. sample.packets_sent = radio_driver.getPacketsSent();
  1668. sample.packets_recv = radio_driver.getPacketsRecv();
  1669. sample.battery_mv = battery_mv;
  1670. sample.queue_len = static_cast<uint16_t>(_mgr->getOutboundTotal());
  1671. sample.error_flags = _err_flags;
  1672. sample.recv_errors = static_cast<uint16_t>(min<uint32_t>(radio_driver.getPacketsRecvErrors(), 0xFFFF));
  1673. sample.neighbour_count = static_cast<uint16_t>(min<size_t>(getNeighbourCount(), 0xFFFF));
  1674. sample.direct_dups =
  1675. static_cast<uint16_t>(min<uint32_t>(((SimpleMeshTables *)getTables())->getNumDirectDups(), 0xFFFF));
  1676. sample.flood_dups =
  1677. static_cast<uint16_t>(min<uint32_t>(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF));
  1678. sample.last_rssi_x4 = static_cast<int16_t>(radio_driver.getLastRSSI() * 4.0f);
  1679. sample.last_snr_x4 = static_cast<int16_t>(radio_driver.getLastSNR() * 4.0f);
  1680. sample.noise_floor = static_cast<int16_t>(_radio->getNoiseFloor());
  1681. sample.battery_pct = static_cast<int8_t>(board.getBatteryPercent());
  1682. if (sensor_snapshot.has_supply_voltage && std::isfinite(sensor_snapshot.supply_voltage_v)) {
  1683. sample.sensor_flags |= HISTORY_SENSOR_SUPPLY_VOLTAGE;
  1684. sample.supply_voltage_centi_v =
  1685. static_cast<uint16_t>(min<int>(lroundf(sensor_snapshot.supply_voltage_v * 100.0f), 0xFFFF));
  1686. }
  1687. if (sensor_snapshot.has_sensor_temp && std::isfinite(sensor_snapshot.sensor_temp_c)) {
  1688. sample.sensor_flags |= HISTORY_SENSOR_TEMP;
  1689. sample.sensor_temp_deci_c =
  1690. static_cast<int16_t>(max<long>(-32768L, min<long>(32767L, lroundf(sensor_snapshot.sensor_temp_c * 10.0f))));
  1691. }
  1692. if (sensor_snapshot.has_mcu_temp && std::isfinite(sensor_snapshot.mcu_temp_c)) {
  1693. sample.sensor_flags |= HISTORY_SENSOR_MCU_TEMP;
  1694. sample.mcu_temp_deci_c =
  1695. static_cast<int16_t>(max<long>(-32768L, min<long>(32767L, lroundf(sensor_snapshot.mcu_temp_c * 10.0f))));
  1696. }
  1697. if (sensor_snapshot.has_humidity && std::isfinite(sensor_snapshot.humidity_pct)) {
  1698. sample.sensor_flags |= HISTORY_SENSOR_HUMIDITY;
  1699. sample.humidity_deci_pct =
  1700. static_cast<uint16_t>(min<int>(lroundf(sensor_snapshot.humidity_pct * 10.0f), 0xFFFF));
  1701. }
  1702. if (sensor_snapshot.has_pressure && std::isfinite(sensor_snapshot.pressure_hpa)) {
  1703. sample.sensor_flags |= HISTORY_SENSOR_PRESSURE;
  1704. sample.pressure_deci_hpa =
  1705. static_cast<uint16_t>(min<int>(lroundf(sensor_snapshot.pressure_hpa * 10.0f), 0xFFFF));
  1706. }
  1707. if (sensor_snapshot.has_pressure_altitude && std::isfinite(sensor_snapshot.pressure_altitude_m)) {
  1708. sample.sensor_flags |= HISTORY_SENSOR_PRESSURE_ALTITUDE;
  1709. sample.pressure_altitude_m =
  1710. static_cast<int16_t>(max<long>(-32768L, min<long>(32767L, lroundf(sensor_snapshot.pressure_altitude_m))));
  1711. }
  1712. if (sensor_snapshot.has_gps) sample.sensor_flags |= HISTORY_SENSOR_GPS_PRESENT;
  1713. if (sensor_snapshot.gps_enabled) sample.sensor_flags |= HISTORY_SENSOR_GPS_ENABLED;
  1714. if (sensor_snapshot.gps_fix) sample.sensor_flags |= HISTORY_SENSOR_GPS_FIX;
  1715. if (sensor_snapshot.has_gps_lat && std::isfinite(sensor_snapshot.gps_lat)) {
  1716. sample.sensor_flags |= HISTORY_SENSOR_GPS_LAT;
  1717. sample.gps_lat_e6 = static_cast<int32_t>(lroundf(sensor_snapshot.gps_lat * 1000000.0f));
  1718. }
  1719. if (sensor_snapshot.has_gps_lon && std::isfinite(sensor_snapshot.gps_lon)) {
  1720. sample.sensor_flags |= HISTORY_SENSOR_GPS_LON;
  1721. sample.gps_lon_e6 = static_cast<int32_t>(lroundf(sensor_snapshot.gps_lon * 1000000.0f));
  1722. }
  1723. if (sensor_snapshot.has_gps_altitude && std::isfinite(sensor_snapshot.gps_altitude_m)) {
  1724. sample.sensor_flags |= HISTORY_SENSOR_GPS_ALTITUDE;
  1725. sample.gps_altitude_m =
  1726. static_cast<int16_t>(max<long>(-32768L, min<long>(32767L, lroundf(sensor_snapshot.gps_altitude_m))));
  1727. }
  1728. if (sensor_snapshot.has_satellites) {
  1729. sample.sensor_flags |= HISTORY_SENSOR_GPS_SATELLITES;
  1730. sample.gps_satellites = static_cast<uint8_t>(min<long>(sensor_snapshot.satellites, 255));
  1731. }
  1732. #if defined(ESP32)
  1733. sample.heap_free = free_heap;
  1734. sample.heap_min = ESP.getMinFreeHeap();
  1735. sample.psram_free = ESP.getFreePsram();
  1736. sample.psram_min = ESP.getMinFreePsram();
  1737. #endif
  1738. if (board.isExternalPowered()) sample.flags |= HISTORY_FLAG_EXTERNAL_POWER;
  1739. if (board.isCharging()) sample.flags |= HISTORY_FLAG_CHARGING;
  1740. if (board.isVbusPresent()) sample.flags |= HISTORY_FLAG_VBUS;
  1741. if (wifi_connected) sample.flags |= HISTORY_FLAG_WIFI_CONNECTED;
  1742. if (mqtt_connected) sample.flags |= HISTORY_FLAG_MQTT_CONNECTED;
  1743. if (web.isWebEnabled()) sample.flags |= HISTORY_FLAG_WEB_ENABLED;
  1744. if (web_panel_up) sample.flags |= HISTORY_FLAG_WEB_PANEL_UP;
  1745. if (archive_mounted) sample.flags |= HISTORY_FLAG_ARCHIVE_MOUNTED;
  1746. _stats_history.pushSample(sample);
  1747. }
  1748. next_history_sample_ms = now_ms + 60000UL;
  1749. }
  1750. _stats_history.maybeFlush(now_ms);
  1751. if (!_stats_history.isLiveOnly()) {
  1752. maybeFlushArchiveNeighbours(now_ms);
  1753. }
  1754. #else
  1755. (void)now_ms;
  1756. #endif
  1757. }
  1758. bool MyMesh::appendJsonEvents(char* reply, size_t reply_size, size_t& offset) const {
  1759. offset += snprintf(&reply[offset], reply_size - offset, "\"events\":[");
  1760. const size_t max_events = min<size_t>(_stats_history.getEventCount(), 6);
  1761. const uint32_t now_epoch_secs = getRTCClock()->getCurrentTime();
  1762. const uint32_t now_uptime_secs = static_cast<uint32_t>(uptime_millis / 1000);
  1763. for (size_t i = 0; i < max_events; ++i) {
  1764. HistoryEvent event{};
  1765. if (!_stats_history.getRecentEvent(i, event)) {
  1766. break;
  1767. }
  1768. const uint32_t age_secs = (now_epoch_secs >= event.epoch_secs && event.epoch_secs > 0)
  1769. ? (now_epoch_secs - event.epoch_secs)
  1770. : ((now_uptime_secs >= event.uptime_secs) ? (now_uptime_secs - event.uptime_secs) : event.uptime_secs);
  1771. offset += snprintf(&reply[offset], reply_size - offset,
  1772. "%s{\"t\":%lu,\"type\":\"%s\",\"value\":%d}",
  1773. i == 0 ? "" : ",",
  1774. static_cast<unsigned long>(age_secs),
  1775. StatsHistory::getEventTypeName(event.type),
  1776. static_cast<int>(event.value));
  1777. if (offset >= reply_size) {
  1778. return false;
  1779. }
  1780. }
  1781. offset += snprintf(&reply[offset], reply_size - offset, "]");
  1782. return offset < reply_size;
  1783. }
  1784. bool MyMesh::appendJsonNeighbours(char* reply, size_t reply_size, size_t& offset) const {
  1785. offset += snprintf(&reply[offset], reply_size - offset, "\"neighbors_detail\":[");
  1786. if (offset >= reply_size) {
  1787. return false;
  1788. }
  1789. #if MAX_NEIGHBOURS
  1790. constexpr size_t kMaxNeighboursJson = 10;
  1791. int16_t neighbours_count = 0;
  1792. NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
  1793. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  1794. auto neighbour = const_cast<NeighbourInfo*>(&neighbours[i]);
  1795. if (neighbour->heard_timestamp > 0) {
  1796. sorted_neighbours[neighbours_count++] = neighbour;
  1797. }
  1798. }
  1799. std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
  1800. return a->heard_timestamp > b->heard_timestamp;
  1801. });
  1802. const size_t emit_count = min<size_t>(neighbours_count, kMaxNeighboursJson);
  1803. const uint32_t now_secs = getRTCClock()->getCurrentTime();
  1804. for (size_t i = 0; i < emit_count; ++i) {
  1805. const NeighbourInfo* neighbour = sorted_neighbours[i];
  1806. char hex[7];
  1807. char full_hex[65];
  1808. mesh::Utils::toHex(hex, neighbour->id.pub_key, 3);
  1809. mesh::Utils::toHex(full_hex, neighbour->id.pub_key, PUB_KEY_SIZE);
  1810. const uint32_t heard_secs_ago = now_secs - neighbour->heard_timestamp;
  1811. const uint32_t advert_secs_ago = now_secs - neighbour->advert_timestamp;
  1812. offset += snprintf(&reply[offset], reply_size - offset,
  1813. "%s{\"id\":\"%s\",\"full_id\":\"%s\",\"heard_secs_ago\":%lu,\"advert_secs_ago\":%lu,\"snr_db\":%.2f}",
  1814. i == 0 ? "" : ",",
  1815. hex,
  1816. full_hex,
  1817. static_cast<unsigned long>(heard_secs_ago),
  1818. static_cast<unsigned long>(advert_secs_ago),
  1819. static_cast<double>(neighbour->snr) / 4.0);
  1820. if (offset >= reply_size) {
  1821. return false;
  1822. }
  1823. }
  1824. #endif
  1825. offset += snprintf(&reply[offset], reply_size - offset, "]");
  1826. return offset < reply_size;
  1827. }
  1828. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  1829. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  1830. IdentityStore store(*_fs, "");
  1831. #elif defined(ESP32)
  1832. IdentityStore store(*_fs, "/identity");
  1833. #elif defined(RP2040_PLATFORM)
  1834. IdentityStore store(*_fs, "/identity");
  1835. #else
  1836. #error "need to define saveIdentity()"
  1837. #endif
  1838. store.save("_main", new_id);
  1839. }
  1840. void MyMesh::clearStats() {
  1841. radio_driver.resetStats();
  1842. resetStats();
  1843. ((SimpleMeshTables *)getTables())->resetStats();
  1844. }
  1845. void MyMesh::prepareForOTAStart() {
  1846. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  1847. web.prepareForOTAStart();
  1848. #endif
  1849. }
  1850. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  1851. if (region_load_active) {
  1852. if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
  1853. region_map = temp_map; // copy over the temp instance as new current map
  1854. region_load_active = false;
  1855. sprintf(reply, "OK - loaded %d regions", region_map.getCount());
  1856. } else {
  1857. char *np = command;
  1858. while (*np == ' ') np++; // skip indent
  1859. int indent = np - command;
  1860. char *ep = np;
  1861. while (RegionMap::is_name_char(*ep)) ep++;
  1862. if (*ep) { *ep++ = 0; } // set null terminator for end of name
  1863. while (*ep && *ep != 'F') ep++; // look for (optional) flags
  1864. if (indent > 0 && indent < 8 && strlen(np) > 0) {
  1865. auto parent = load_stack[indent - 1];
  1866. if (parent) {
  1867. auto old = region_map.findByName(np);
  1868. auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists)
  1869. if (nw) {
  1870. nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr
  1871. load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's
  1872. }
  1873. }
  1874. }
  1875. reply[0] = 0;
  1876. }
  1877. return;
  1878. }
  1879. while (*command == ' ') command++; // skip leading spaces
  1880. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  1881. memcpy(reply, command, 3); // reflect the prefix back
  1882. reply += 3;
  1883. command += 3;
  1884. }
  1885. // handle ACL related commands
  1886. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  1887. char* hex = &command[8];
  1888. char* sp = strchr(hex, ' '); // look for separator char
  1889. if (sp == NULL) {
  1890. strcpy(reply, "Err - bad params");
  1891. } else {
  1892. *sp++ = 0; // replace space with null terminator
  1893. uint8_t pubkey[PUB_KEY_SIZE];
  1894. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  1895. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  1896. uint8_t perms = atoi(sp);
  1897. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  1898. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  1899. strcpy(reply, "OK");
  1900. } else {
  1901. strcpy(reply, "Err - invalid params");
  1902. }
  1903. } else {
  1904. strcpy(reply, "Err - bad pubkey");
  1905. }
  1906. }
  1907. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  1908. Serial.println("ACL:");
  1909. for (int i = 0; i < acl.getNumClients(); i++) {
  1910. auto c = acl.getClientByIdx(i);
  1911. if (c->permissions == 0) continue; // skip deleted (or guest) entries
  1912. Serial.printf("%02X ", c->permissions);
  1913. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  1914. Serial.printf("\n");
  1915. }
  1916. reply[0] = 0;
  1917. } else if (memcmp(command, "discover.neighbors", 18) == 0) {
  1918. const char* sub = command + 18;
  1919. while (*sub == ' ') sub++;
  1920. if (*sub != 0) {
  1921. strcpy(reply, "Err - discover.neighbors has no options");
  1922. } else {
  1923. sendNodeDiscoverReq();
  1924. strcpy(reply, "OK - Discover sent");
  1925. }
  1926. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  1927. } else if (strcmp(command, "get web.status") == 0 || strcmp(command, "get web") == 0) {
  1928. web.formatWebStatusReply(reply, 160);
  1929. } else if (strcmp(command, "get web.stats.status") == 0) {
  1930. snprintf(reply, 160,
  1931. "> enabled:%s history:%s mode:%s psram:%s psram_bytes:%lu boot_auto:%s samples:%u/%u events:%u/%u archive:%s",
  1932. web.isWebStatsEnabled() ? "on" : "off",
  1933. (_stats_history.isEnabled() && _stats_history.isRecentHistoryAvailable()) ? "active" : "inactive",
  1934. _stats_history.isLiveOnly() ? "live" : "full",
  1935. _stats_history.isPsramBacked() ? "yes" : "no",
  1936. static_cast<unsigned long>(_stats_history.getDetectedPsramSizeBytes()),
  1937. _stats_history.isBootAutoCaptureExpected() ? "yes" : "no",
  1938. static_cast<unsigned>(_stats_history.getSampleCount()),
  1939. static_cast<unsigned>(_stats_history.getSampleCapacity()),
  1940. static_cast<unsigned>(_stats_history.getEventCount()),
  1941. static_cast<unsigned>(_stats_history.getEventCapacity()),
  1942. (_archive != nullptr && _archive->isMounted()) ? "mounted" : "unavailable");
  1943. #endif
  1944. #if defined(TBEAM_1W)
  1945. } else if (strcmp(command, "get fan") == 0) {
  1946. auto& tbeam1w_board = static_cast<TBeam1WBoard&>(board);
  1947. const float temp_c = tbeam1w_board.getLastBoardTemperatureC();
  1948. if (isnan(temp_c)) {
  1949. snprintf(reply, 160, "> mode:%s state:%s timeout:%lus temp:unavailable",
  1950. tbeam1w_board.getFanModeName(),
  1951. tbeam1w_board.isFanEnabled() ? "on" : "off",
  1952. static_cast<unsigned long>(tbeam1w_board.getFanPostTxHoldMs() / 1000UL));
  1953. } else {
  1954. snprintf(reply, 160, "> mode:%s state:%s timeout:%lus temp:%.2fC",
  1955. tbeam1w_board.getFanModeName(),
  1956. tbeam1w_board.isFanEnabled() ? "on" : "off",
  1957. static_cast<unsigned long>(tbeam1w_board.getFanPostTxHoldMs() / 1000UL),
  1958. temp_c);
  1959. }
  1960. } else if (memcmp(command, "set fan ", 8) == 0) {
  1961. auto& tbeam1w_board = static_cast<TBeam1WBoard&>(board);
  1962. const char* mode = &command[8];
  1963. if (memcmp(mode, "auto", 4) == 0) {
  1964. _prefs.fan_mode = static_cast<uint8_t>(TBeam1WBoard::FanMode::Auto);
  1965. tbeam1w_board.setFanMode(TBeam1WBoard::FanMode::Auto);
  1966. savePrefs();
  1967. strcpy(reply, "OK - fan auto");
  1968. } else if (memcmp(mode, "on", 2) == 0) {
  1969. _prefs.fan_mode = static_cast<uint8_t>(TBeam1WBoard::FanMode::On);
  1970. tbeam1w_board.setFanMode(TBeam1WBoard::FanMode::On);
  1971. savePrefs();
  1972. strcpy(reply, "OK - fan on");
  1973. } else if (memcmp(mode, "off", 3) == 0) {
  1974. _prefs.fan_mode = static_cast<uint8_t>(TBeam1WBoard::FanMode::Off);
  1975. tbeam1w_board.setFanMode(TBeam1WBoard::FanMode::Off);
  1976. savePrefs();
  1977. strcpy(reply, "OK - fan off");
  1978. } else if (memcmp(mode, "timeout ", 8) == 0) {
  1979. char* end = nullptr;
  1980. const unsigned long timeout_s = strtoul(&mode[8], &end, 10);
  1981. while (end != nullptr && *end == ' ') end++;
  1982. if (end != nullptr && *end == 's' && *(end + 1) == 0 && tbeam1w_board.setFanPostTxHoldMs(static_cast<uint32_t>(timeout_s * 1000UL))) {
  1983. _prefs.fan_timeout_secs = static_cast<uint16_t>(timeout_s);
  1984. savePrefs();
  1985. snprintf(reply, 160, "OK - fan timeout %lus", timeout_s);
  1986. } else {
  1987. strcpy(reply, "Err - use 0s..600s");
  1988. }
  1989. } else {
  1990. strcpy(reply, "Err - use auto|on|off|timeout <Ns>");
  1991. }
  1992. #endif
  1993. #if defined(ESP_PLATFORM)
  1994. } else if (memcmp(command, "get wifi.status", 15) == 0) {
  1995. network.formatWifiStatusReply(reply, 160);
  1996. } else if (memcmp(command, "get wifi.ssid", 13) == 0) {
  1997. sprintf(reply, "> %s", network.getWifiSSID()[0] ? network.getWifiSSID() : "-");
  1998. } else if (memcmp(command, "get wifi.powersaving", 20) == 0) {
  1999. sprintf(reply, "> %s", network.getWifiPowerSave());
  2000. #endif
  2001. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  2002. } else if (memcmp(command, "set web ", 8) == 0) {
  2003. web.setWebEnabled(memcmp(&command[8], "on", 2) == 0);
  2004. strcpy(reply, "OK");
  2005. } else if (memcmp(command, "set.web ", 8) == 0) {
  2006. web.setWebEnabled(memcmp(&command[8], "on", 2) == 0);
  2007. strcpy(reply, "OK");
  2008. } else if (memcmp(command, "set web.stats ", 14) == 0 || memcmp(command, "set.web.stats ", 15) == 0) {
  2009. const char* value = (memcmp(command, "set web.stats ", 14) == 0) ? &command[14] : &command[15];
  2010. const bool enabled = memcmp(value, "on", 2) == 0;
  2011. if (web.setWebStatsEnabled(enabled)) {
  2012. _stats_history.setEnabled(enabled);
  2013. recordStatsEvent(enabled ? HISTORY_EVENT_STATS_ENABLED : HISTORY_EVENT_STATS_DISABLED);
  2014. if (enabled) {
  2015. next_history_sample_ms = millis();
  2016. } else {
  2017. _stats_state.initialized = false;
  2018. }
  2019. strcpy(reply, enabled ? "OK - web.stats on" : "OK - web.stats off");
  2020. } else {
  2021. strcpy(reply, "Err - unable to update web.stats");
  2022. }
  2023. #endif
  2024. #if defined(ESP_PLATFORM)
  2025. } else if (memcmp(command, "set wifi.ssid ", 14) == 0) {
  2026. if (network.setWifiSSID(&command[14])) {
  2027. strcpy(reply, "OK");
  2028. } else {
  2029. strcpy(reply, "Err - bad wifi.ssid");
  2030. }
  2031. } else if (memcmp(command, "set wifi.pwd ", 13) == 0) {
  2032. if (network.setWifiPassword(&command[13])) {
  2033. strcpy(reply, "OK");
  2034. } else {
  2035. strcpy(reply, "Err - bad wifi.pwd");
  2036. }
  2037. } else if (memcmp(command, "set wifi.powersaving ", 21) == 0) {
  2038. if (network.setWifiPowerSave(&command[21])) {
  2039. strcpy(reply, "OK");
  2040. } else {
  2041. strcpy(reply, "Err - use none|min|max");
  2042. }
  2043. #endif
  2044. #ifdef WITH_MQTT_UPLINK
  2045. } else if (memcmp(command, "mqtt.owner ", 11) == 0) {
  2046. if (mqtt.setOwnerPublicKey(&command[11])) {
  2047. strcpy(reply, "OK");
  2048. } else {
  2049. strcpy(reply, "Err - owner must be 64 hex chars");
  2050. }
  2051. } else if (memcmp(command, "mqtt.email ", 11) == 0) {
  2052. if (mqtt.setOwnerEmail(&command[11])) {
  2053. strcpy(reply, "OK");
  2054. } else {
  2055. strcpy(reply, "Err - bad mqtt.email");
  2056. }
  2057. } else if (strcmp(command, "send mqtt.status") == 0) {
  2058. if (mqtt.sendStatusNow()) {
  2059. strcpy(reply, "OK");
  2060. } else {
  2061. strcpy(reply, "Err - mqtt status unavailable");
  2062. }
  2063. } else if (strcmp(command, "get mqtt.statuscfg") == 0) {
  2064. sprintf(reply, "> %s", mqtt.isStatusEnabled() ? "on" : "off");
  2065. } else if (strcmp(command, "get mqtt.status") == 0) {
  2066. mqtt.formatStatusReply(reply, 160);
  2067. } else if (strcmp(command, "get mqtt.client_version") == 0) {
  2068. sprintf(reply, "> %s", mqtt.getClientVersion());
  2069. } else if (memcmp(command, "get mqtt.iata", 13) == 0) {
  2070. sprintf(reply, "> %s", mqtt.getIata());
  2071. } else if (memcmp(command, "get mqtt.owner", 14) == 0) {
  2072. sprintf(reply, "> %s", mqtt.getOwnerPublicKey()[0] ? mqtt.getOwnerPublicKey() : "-");
  2073. } else if (memcmp(command, "get mqtt.email", 14) == 0) {
  2074. sprintf(reply, "> %s", mqtt.getOwnerEmail()[0] ? mqtt.getOwnerEmail() : "-");
  2075. } else if (memcmp(command, "get mqtt.packets", 16) == 0) {
  2076. sprintf(reply, "> %s", mqtt.isPacketsEnabled() ? "on" : "off");
  2077. } else if (memcmp(command, "get mqtt.raw", 12) == 0) {
  2078. sprintf(reply, "> %s", mqtt.isRawEnabled() ? "on" : "off");
  2079. } else if (memcmp(command, "get mqtt.tx", 11) == 0) {
  2080. sprintf(reply, "> %s", mqtt.isTxEnabled() ? "on" : "off");
  2081. } else if (memcmp(command, "get mqtt.eastmesh-au", 20) == 0 || memcmp(command, "get mqtt.eastmesh.au", 20) == 0) {
  2082. sprintf(reply, "> %s", mqtt.isEndpointEnabled(0x01) ? "on" : "off");
  2083. } else if (memcmp(command, "get mqtt.letsmesh-eu", 21) == 0 || memcmp(command, "get mqtt.letsmesh.eu", 21) == 0) {
  2084. sprintf(reply, "> %s", mqtt.isEndpointEnabled(0x02) ? "on" : "off");
  2085. } else if (memcmp(command, "get mqtt.letsmesh-us", 21) == 0 || memcmp(command, "get mqtt.letsmesh.us", 21) == 0) {
  2086. sprintf(reply, "> %s", mqtt.isEndpointEnabled(0x04) ? "on" : "off");
  2087. } else if (memcmp(command, "get mqtt.meshcoretel", 20) == 0) {
  2088. sprintf(reply, "> %s", mqtt.isEndpointEnabled(0x08) ? "on" : "off");
  2089. } else if (memcmp(command, "set mqtt.tx ", 12) == 0) {
  2090. mqtt.setTxEnabled(memcmp(&command[12], "on", 2) == 0);
  2091. strcpy(reply, "OK");
  2092. } else if (memcmp(command, "set mqtt.iata ", 14) == 0) {
  2093. if (mqtt.setIata(&command[14])) {
  2094. strcpy(reply, "OK");
  2095. } else {
  2096. strcpy(reply, "Err - bad mqtt.iata");
  2097. }
  2098. } else if (memcmp(command, "set mqtt.owner ", 15) == 0) {
  2099. if (mqtt.setOwnerPublicKey(&command[15])) {
  2100. strcpy(reply, "OK");
  2101. } else {
  2102. strcpy(reply, "Err - owner must be 64 hex chars");
  2103. }
  2104. } else if (memcmp(command, "set mqtt.email ", 15) == 0) {
  2105. if (mqtt.setOwnerEmail(&command[15])) {
  2106. strcpy(reply, "OK");
  2107. } else {
  2108. strcpy(reply, "Err - bad mqtt.email");
  2109. }
  2110. } else if (memcmp(command, "set mqtt.packets ", 17) == 0) {
  2111. mqtt.setPacketsEnabled(memcmp(&command[17], "on", 2) == 0);
  2112. strcpy(reply, "OK");
  2113. } else if (memcmp(command, "set mqtt.raw ", 13) == 0) {
  2114. mqtt.setRawEnabled(memcmp(&command[13], "on", 2) == 0);
  2115. strcpy(reply, "OK");
  2116. } else if (memcmp(command, "set mqtt.status ", 16) == 0) {
  2117. mqtt.setStatusEnabled(memcmp(&command[16], "on", 2) == 0);
  2118. strcpy(reply, "OK");
  2119. } else if (memcmp(command, "set mqtt.eastmesh-au ", 21) == 0 || memcmp(command, "set mqtt.eastmesh.au ", 21) == 0) {
  2120. if (mqtt.setEndpointEnabled(0x01, memcmp(&command[21], "on", 2) == 0)) {
  2121. strcpy(reply, "OK");
  2122. } else {
  2123. strcpy(reply, "Err - max 2 mqtt brokers");
  2124. }
  2125. } else if (memcmp(command, "set mqtt.letsmesh-eu ", 21) == 0 || memcmp(command, "set mqtt.letsmesh.eu ", 21) == 0) {
  2126. if (mqtt.setEndpointEnabled(0x02, memcmp(&command[21], "on", 2) == 0)) {
  2127. strcpy(reply, "OK");
  2128. } else {
  2129. strcpy(reply, "Err - max 2 mqtt brokers");
  2130. }
  2131. } else if (memcmp(command, "set mqtt.letsmesh-us ", 21) == 0 || memcmp(command, "set mqtt.letsmesh.us ", 21) == 0) {
  2132. if (mqtt.setEndpointEnabled(0x04, memcmp(&command[21], "on", 2) == 0)) {
  2133. strcpy(reply, "OK");
  2134. } else {
  2135. strcpy(reply, "Err - max 2 mqtt brokers");
  2136. }
  2137. } else if (memcmp(command, "set mqtt.meshcoretel ", 21) == 0) {
  2138. if (mqtt.setEndpointEnabled(0x08, memcmp(&command[21], "on", 2) == 0)) {
  2139. strcpy(reply, "OK");
  2140. } else {
  2141. strcpy(reply, "Err - max 2 mqtt brokers");
  2142. }
  2143. #endif
  2144. } else{
  2145. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  2146. }
  2147. }
  2148. void MyMesh::runWebCommand(const char* command, char* reply, size_t reply_size) {
  2149. if (reply_size == 0) {
  2150. return;
  2151. }
  2152. reply[0] = 0;
  2153. if (command == nullptr) {
  2154. strncpy(reply, "Err - empty command", reply_size - 1);
  2155. reply[reply_size - 1] = 0;
  2156. return;
  2157. }
  2158. char command_buf[192];
  2159. StrHelper::strncpy(command_buf, command, sizeof(command_buf));
  2160. handleCommand(0, command_buf, reply);
  2161. reply[reply_size - 1] = 0;
  2162. }
  2163. bool MyMesh::isWebStatsEnabled() const {
  2164. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  2165. return web.isWebStatsEnabled();
  2166. #else
  2167. return false;
  2168. #endif
  2169. }
  2170. bool MyMesh::formatWebStatsSummaryJson(char* reply, size_t reply_size) {
  2171. if (reply == nullptr || reply_size == 0) {
  2172. return false;
  2173. }
  2174. reply[0] = 0;
  2175. #if !defined(ESP_PLATFORM) || !WITH_WEB_PANEL
  2176. return false;
  2177. #else
  2178. char wifi_ssid[48];
  2179. char wifi_status[20];
  2180. char wifi_state[24];
  2181. char wifi_ip[20];
  2182. char wifi_signal[16];
  2183. char wifi_powersave[12];
  2184. escapeJsonString(network.getWifiSSID()[0] ? network.getWifiSSID() : "-", wifi_ssid, sizeof(wifi_ssid));
  2185. escapeJsonString(network.getWifiPowerSave(), wifi_powersave, sizeof(wifi_powersave));
  2186. int wifi_rssi = 0;
  2187. int wifi_quality = 0;
  2188. int wifi_code = 0;
  2189. #if defined(ESP32)
  2190. if (network.getWifiSSID()[0] == 0) {
  2191. strncpy(wifi_status, "unconfigured", sizeof(wifi_status) - 1);
  2192. wifi_status[sizeof(wifi_status) - 1] = 0;
  2193. strncpy(wifi_state, "unconfigured", sizeof(wifi_state) - 1);
  2194. wifi_state[sizeof(wifi_state) - 1] = 0;
  2195. strncpy(wifi_ip, "--", sizeof(wifi_ip) - 1);
  2196. wifi_ip[sizeof(wifi_ip) - 1] = 0;
  2197. strncpy(wifi_signal, "--", sizeof(wifi_signal) - 1);
  2198. wifi_signal[sizeof(wifi_signal) - 1] = 0;
  2199. } else if (network.isWifiConnected()) {
  2200. strncpy(wifi_status, "connected", sizeof(wifi_status) - 1);
  2201. wifi_status[sizeof(wifi_status) - 1] = 0;
  2202. strncpy(wifi_state, "connected", sizeof(wifi_state) - 1);
  2203. wifi_state[sizeof(wifi_state) - 1] = 0;
  2204. String ip = WiFi.localIP().toString();
  2205. escapeJsonString(ip.c_str(), wifi_ip, sizeof(wifi_ip));
  2206. wifi_rssi = WiFi.RSSI();
  2207. wifi_code = static_cast<int>(WiFi.status());
  2208. if (wifi_rssi <= -100) {
  2209. wifi_quality = 0;
  2210. strncpy(wifi_signal, "poor", sizeof(wifi_signal) - 1);
  2211. } else if (wifi_rssi >= -50) {
  2212. wifi_quality = 100;
  2213. strncpy(wifi_signal, "excellent", sizeof(wifi_signal) - 1);
  2214. } else {
  2215. wifi_quality = 2 * (wifi_rssi + 100);
  2216. if (wifi_rssi >= -60) {
  2217. strncpy(wifi_signal, "excellent", sizeof(wifi_signal) - 1);
  2218. } else if (wifi_rssi >= -67) {
  2219. strncpy(wifi_signal, "good", sizeof(wifi_signal) - 1);
  2220. } else if (wifi_rssi >= -75) {
  2221. strncpy(wifi_signal, "fair", sizeof(wifi_signal) - 1);
  2222. } else {
  2223. strncpy(wifi_signal, "poor", sizeof(wifi_signal) - 1);
  2224. }
  2225. }
  2226. wifi_signal[sizeof(wifi_signal) - 1] = 0;
  2227. } else {
  2228. strncpy(wifi_status, "connecting", sizeof(wifi_status) - 1);
  2229. wifi_status[sizeof(wifi_status) - 1] = 0;
  2230. wifi_code = static_cast<int>(WiFi.status());
  2231. switch (WiFi.status()) {
  2232. case WL_IDLE_STATUS:
  2233. strncpy(wifi_state, "idle", sizeof(wifi_state) - 1);
  2234. break;
  2235. case WL_NO_SSID_AVAIL:
  2236. strncpy(wifi_state, "no_ssid", sizeof(wifi_state) - 1);
  2237. break;
  2238. case WL_SCAN_COMPLETED:
  2239. strncpy(wifi_state, "scan_completed", sizeof(wifi_state) - 1);
  2240. break;
  2241. case WL_CONNECT_FAILED:
  2242. strncpy(wifi_state, "connect_failed", sizeof(wifi_state) - 1);
  2243. break;
  2244. case WL_CONNECTION_LOST:
  2245. strncpy(wifi_state, "connection_lost", sizeof(wifi_state) - 1);
  2246. break;
  2247. case WL_DISCONNECTED:
  2248. strncpy(wifi_state, "disconnected", sizeof(wifi_state) - 1);
  2249. break;
  2250. default:
  2251. strncpy(wifi_state, "unknown", sizeof(wifi_state) - 1);
  2252. break;
  2253. }
  2254. wifi_state[sizeof(wifi_state) - 1] = 0;
  2255. strncpy(wifi_ip, "--", sizeof(wifi_ip) - 1);
  2256. wifi_ip[sizeof(wifi_ip) - 1] = 0;
  2257. strncpy(wifi_signal, "--", sizeof(wifi_signal) - 1);
  2258. wifi_signal[sizeof(wifi_signal) - 1] = 0;
  2259. }
  2260. #else
  2261. strncpy(wifi_status, "unsupported", sizeof(wifi_status) - 1);
  2262. wifi_status[sizeof(wifi_status) - 1] = 0;
  2263. strncpy(wifi_state, "unsupported", sizeof(wifi_state) - 1);
  2264. wifi_state[sizeof(wifi_state) - 1] = 0;
  2265. strncpy(wifi_ip, "--", sizeof(wifi_ip) - 1);
  2266. wifi_ip[sizeof(wifi_ip) - 1] = 0;
  2267. strncpy(wifi_signal, "--", sizeof(wifi_signal) - 1);
  2268. wifi_signal[sizeof(wifi_signal) - 1] = 0;
  2269. #endif
  2270. const uint16_t battery_mv = getBatteryMilliVolts(true);
  2271. const int battery_pct = board.getBatteryPercent();
  2272. const uint16_t battery_min_mv = board.getBatteryMinMilliVolts();
  2273. const uint16_t battery_max_mv = board.getBatteryMaxMilliVolts();
  2274. const int battery_display_pct =
  2275. (battery_pct >= 0) ? std::max(0, std::min(100, battery_pct))
  2276. : clampBatteryPercentFromRange(battery_mv, battery_min_mv, battery_max_mv);
  2277. const WebSensorSnapshot sensor_snapshot = collectWebSensorSnapshot(board, sensors, battery_mv);
  2278. const bool archive_available = (_archive != nullptr) && _archive->isMounted();
  2279. #ifdef WITH_MQTT_UPLINK
  2280. const bool mqtt_connected = mqtt.isAnyBrokerConnected();
  2281. const char* mqtt_state = mqtt.getAggregateBrokerState();
  2282. #else
  2283. const bool mqtt_connected = false;
  2284. const char* mqtt_state = "down";
  2285. #endif
  2286. const bool web_panel_up = web.isPanelRunning();
  2287. const char* archive_name = (_archive != nullptr) ? _archive->getLogicalName() : "archive";
  2288. const char* archive_path = (_archive != nullptr) ? _archive->getLogicalStatsPath() : "archive:/stats";
  2289. const char* archive_type = (_archive != nullptr) ? _archive->getCardTypeName() : "unavailable";
  2290. _stats_history.noteAccess(millis());
  2291. const uint32_t heap_free = ESP.getFreeHeap();
  2292. const uint32_t heap_min = ESP.getMinFreeHeap();
  2293. const uint32_t heap_max = ESP.getMaxAllocHeap();
  2294. const uint32_t psram_free = ESP.getFreePsram();
  2295. const uint32_t psram_min = ESP.getMinFreePsram();
  2296. const uint32_t psram_max = ESP.getMaxAllocPsram();
  2297. size_t offset = 0;
  2298. offset += snprintf(&reply[offset], reply_size - offset,
  2299. "{\"enabled\":true,"
  2300. "\"history\":{\"active\":%s,\"psram\":%s,\"degraded\":%s,\"live_only\":%s,\"samples\":%u,\"sample_capacity\":%u,\"sample_interval_secs\":%lu,"
  2301. "\"archive_restored\":%s,\"archive_restored_samples\":%u,\"archive_summary_interval_secs\":%lu,"
  2302. "\"events\":%u,\"event_capacity\":%u},"
  2303. "\"archive\":{\"logical\":\"%s\",\"available\":%s,\"path\":\"%s\",\"type\":\"%s\","
  2304. "\"total_bytes\":%llu,\"used_bytes\":%llu},"
  2305. "\"core\":{\"battery_mv\":%u,\"battery_pct\":%d,\"battery_display_pct\":%d,\"battery_min_mv\":%u,\"battery_max_mv\":%u,"
  2306. "\"uptime_secs\":%lu,\"errors\":%u,\"queue_len\":%u,"
  2307. "\"external_power\":%s,\"charging\":%s,\"vbus\":%s},"
  2308. "\"radio\":{\"noise_floor\":%d,\"last_rssi\":%.2f,\"last_snr\":%.2f,\"tx_air_secs\":%lu,\"rx_air_secs\":%lu},"
  2309. "\"packets\":{\"recv\":%u,\"sent\":%u,\"flood_tx\":%u,\"direct_tx\":%u,\"flood_rx\":%u,\"direct_rx\":%u,"
  2310. "\"recv_errors\":%u,\"direct_dups\":%u,\"flood_dups\":%u,\"neighbors\":%u},"
  2311. "\"memory\":{\"heap_free\":%u,\"heap_min\":%u,\"heap_max\":%u,\"psram_free\":%u,\"psram_min\":%u,\"psram_max\":%u},"
  2312. "\"wifi\":{\"ssid\":\"%s\",\"status\":\"%s\",\"connected\":%s,\"state\":\"%s\",\"code\":%d,\"ip\":\"%s\",\"rssi\":%d,\"quality\":%d,\"signal\":\"%s\",\"powersave\":\"%s\"},"
  2313. "\"services\":{\"mqtt_connected\":%s,\"mqtt_state\":\"%s\",\"web_enabled\":%s,\"web_panel_up\":%s,\"web_auth\":\"%s\","
  2314. "\"archive_available\":%s}",
  2315. (_stats_history.isEnabled() && _stats_history.isRecentHistoryAvailable()) ? "true" : "false",
  2316. _stats_history.isPsramBacked() ? "true" : "false",
  2317. _stats_history.isDegraded() ? "true" : "false",
  2318. _stats_history.isLiveOnly() ? "true" : "false",
  2319. static_cast<unsigned>(_stats_history.getSampleCount()),
  2320. static_cast<unsigned>(_stats_history.getSampleCapacity()),
  2321. static_cast<unsigned long>(StatsHistory::getSampleIntervalSecs()),
  2322. _stats_history.hasArchiveRestore() ? "true" : "false",
  2323. static_cast<unsigned>(_stats_history.getRestoredSampleCount()),
  2324. static_cast<unsigned long>(StatsHistory::getArchiveSummaryIntervalSecs()),
  2325. static_cast<unsigned>(_stats_history.getEventCount()),
  2326. static_cast<unsigned>(_stats_history.getEventCapacity()),
  2327. archive_name,
  2328. archive_available ? "true" : "false",
  2329. archive_path,
  2330. archive_type,
  2331. static_cast<unsigned long long>(_archive != nullptr ? _archive->getTotalBytes() : 0),
  2332. static_cast<unsigned long long>(_archive != nullptr ? _archive->getUsedBytes() : 0),
  2333. battery_mv,
  2334. battery_pct,
  2335. battery_display_pct,
  2336. battery_min_mv,
  2337. battery_max_mv,
  2338. static_cast<unsigned long>(uptime_millis / 1000),
  2339. _err_flags,
  2340. static_cast<unsigned>(_mgr->getOutboundTotal()),
  2341. board.isExternalPowered() ? "true" : "false",
  2342. board.isCharging() ? "true" : "false",
  2343. board.isVbusPresent() ? "true" : "false",
  2344. static_cast<int>(_radio->getNoiseFloor()),
  2345. radio_driver.getLastRSSI(),
  2346. radio_driver.getLastSNR(),
  2347. static_cast<unsigned long>(getTotalAirTime() / 1000),
  2348. static_cast<unsigned long>(getReceiveAirTime() / 1000),
  2349. static_cast<unsigned>(radio_driver.getPacketsRecv()),
  2350. static_cast<unsigned>(radio_driver.getPacketsSent()),
  2351. static_cast<unsigned>(getNumSentFlood()),
  2352. static_cast<unsigned>(getNumSentDirect()),
  2353. static_cast<unsigned>(getNumRecvFlood()),
  2354. static_cast<unsigned>(getNumRecvDirect()),
  2355. static_cast<unsigned>(radio_driver.getPacketsRecvErrors()),
  2356. static_cast<unsigned>(((SimpleMeshTables *)getTables())->getNumDirectDups()),
  2357. static_cast<unsigned>(((SimpleMeshTables *)getTables())->getNumFloodDups()),
  2358. static_cast<unsigned>(getNeighbourCount()),
  2359. heap_free,
  2360. heap_min,
  2361. heap_max,
  2362. psram_free,
  2363. psram_min,
  2364. psram_max,
  2365. wifi_ssid,
  2366. wifi_status,
  2367. network.isWifiConnected() ? "true" : "false",
  2368. wifi_state,
  2369. wifi_code,
  2370. wifi_ip,
  2371. wifi_rssi,
  2372. wifi_quality,
  2373. wifi_signal,
  2374. wifi_powersave,
  2375. mqtt_connected ? "true" : "false",
  2376. mqtt_state,
  2377. web.isWebEnabled() ? "true" : "false",
  2378. web_panel_up ? "true" : "false",
  2379. web.isPanelUnlocked() ? "unlocked" : "locked",
  2380. archive_available ? "true" : "false");
  2381. if (offset >= reply_size) {
  2382. return false;
  2383. }
  2384. offset += snprintf(&reply[offset], reply_size - offset, ",");
  2385. if (!appendJsonSensors(reply, reply_size, offset, sensor_snapshot)) {
  2386. return false;
  2387. }
  2388. offset += snprintf(&reply[offset], reply_size - offset, ",");
  2389. if (!appendJsonEvents(reply, reply_size, offset)) {
  2390. return false;
  2391. }
  2392. offset += snprintf(&reply[offset], reply_size - offset, ",");
  2393. if (!appendJsonNeighbours(reply, reply_size, offset)) {
  2394. return false;
  2395. }
  2396. offset += snprintf(&reply[offset], reply_size - offset, "}");
  2397. return offset < reply_size;
  2398. #endif
  2399. }
  2400. bool MyMesh::formatWebStatsSeriesJson(const char* series, char* reply, size_t reply_size) {
  2401. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  2402. if (!web.isWebStatsEnabled()) {
  2403. if (reply != nullptr && reply_size > 0) {
  2404. reply[0] = 0;
  2405. }
  2406. return false;
  2407. }
  2408. _stats_history.noteAccess(millis());
  2409. return _stats_history.buildSeriesJson(
  2410. series,
  2411. reply,
  2412. reply_size,
  2413. getRTCClock()->getCurrentTime(),
  2414. static_cast<uint32_t>(uptime_millis / 1000));
  2415. #else
  2416. (void)series;
  2417. if (reply != nullptr && reply_size > 0) {
  2418. reply[0] = 0;
  2419. }
  2420. return false;
  2421. #endif
  2422. }
  2423. bool MyMesh::appendJsonSensors(char* reply, size_t reply_size, size_t& offset, const WebSensorSnapshot& snapshot) const {
  2424. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  2425. bool needs_comma = false;
  2426. const int open_written = snprintf(&reply[offset], reply_size - offset, "\"sensors\":{");
  2427. if (open_written < 0 || static_cast<size_t>(open_written) >= (reply_size - offset)) {
  2428. return false;
  2429. }
  2430. offset += static_cast<size_t>(open_written);
  2431. if (snapshot.has_gps) {
  2432. if (!appendJsonBoolField(reply, reply_size, offset, needs_comma, "gps_enabled", snapshot.gps_enabled)) {
  2433. return false;
  2434. }
  2435. if (!appendJsonBoolField(reply, reply_size, offset, needs_comma, "gps_fix", snapshot.gps_fix)) {
  2436. return false;
  2437. }
  2438. }
  2439. if (snapshot.has_satellites) {
  2440. if (!appendJsonLongField(reply, reply_size, offset, needs_comma, "satellites", snapshot.satellites)) {
  2441. return false;
  2442. }
  2443. }
  2444. if (snapshot.has_gps_lat) {
  2445. if (!appendJsonFloatField(reply, reply_size, offset, needs_comma, "gps_lat", snapshot.gps_lat, 6)) {
  2446. return false;
  2447. }
  2448. }
  2449. if (snapshot.has_gps_lon) {
  2450. if (!appendJsonFloatField(reply, reply_size, offset, needs_comma, "gps_lon", snapshot.gps_lon, 6)) {
  2451. return false;
  2452. }
  2453. }
  2454. if (snapshot.has_gps_altitude) {
  2455. if (!appendJsonFloatField(reply, reply_size, offset, needs_comma, "gps_altitude_m", snapshot.gps_altitude_m, 0)) {
  2456. return false;
  2457. }
  2458. }
  2459. if (snapshot.has_supply_voltage) {
  2460. if (!appendJsonFloatField(reply, reply_size, offset, needs_comma, "supply_voltage_v", snapshot.supply_voltage_v, 2)) {
  2461. return false;
  2462. }
  2463. }
  2464. if (snapshot.has_sensor_temp) {
  2465. if (!appendJsonFloatField(reply, reply_size, offset, needs_comma, "sensor_temp_c", snapshot.sensor_temp_c, 1)) {
  2466. return false;
  2467. }
  2468. }
  2469. if (snapshot.has_humidity) {
  2470. if (!appendJsonFloatField(reply, reply_size, offset, needs_comma, "humidity_pct", snapshot.humidity_pct, 0)) {
  2471. return false;
  2472. }
  2473. }
  2474. if (snapshot.has_pressure) {
  2475. if (!appendJsonFloatField(reply, reply_size, offset, needs_comma, "pressure_hpa", snapshot.pressure_hpa, 1)) {
  2476. return false;
  2477. }
  2478. }
  2479. if (snapshot.has_pressure_altitude) {
  2480. if (!appendJsonFloatField(reply, reply_size, offset, needs_comma, "pressure_altitude_m", snapshot.pressure_altitude_m, 0)) {
  2481. return false;
  2482. }
  2483. }
  2484. if (snapshot.has_mcu_temp) {
  2485. if (!appendJsonFloatField(reply, reply_size, offset, needs_comma, "mcu_temp_c", snapshot.mcu_temp_c, 1)) {
  2486. return false;
  2487. }
  2488. }
  2489. const int close_written = snprintf(&reply[offset], reply_size - offset, "}");
  2490. if (close_written < 0 || static_cast<size_t>(close_written) >= (reply_size - offset)) {
  2491. return false;
  2492. }
  2493. offset += static_cast<size_t>(close_written);
  2494. return true;
  2495. #else
  2496. (void)reply;
  2497. (void)reply_size;
  2498. (void)offset;
  2499. return false;
  2500. #endif
  2501. }
  2502. void MyMesh::loop() {
  2503. #ifdef WITH_BRIDGE
  2504. bridge.loop();
  2505. #endif
  2506. const uint32_t now = millis();
  2507. uptime_millis += now - last_millis;
  2508. last_millis = now;
  2509. mesh::Mesh::loop();
  2510. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  2511. mesh::Packet *pkt = createSelfAdvert();
  2512. uint32_t delay_millis = 0;
  2513. if (pkt) sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
  2514. updateFloodAdvertTimer(); // schedule next flood advert
  2515. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  2516. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  2517. mesh::Packet *pkt = createSelfAdvert();
  2518. if (pkt) sendZeroHop(pkt);
  2519. updateAdvertTimer(); // schedule next local advert
  2520. }
  2521. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  2522. set_radio_at = 0; // clear timer
  2523. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  2524. MESH_DEBUG_PRINTLN("Temp radio params");
  2525. }
  2526. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  2527. revert_radio_at = 0; // clear timer
  2528. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  2529. MESH_DEBUG_PRINTLN("Radio params restored");
  2530. }
  2531. // is pending dirty contacts write needed?
  2532. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  2533. acl.save(_fs);
  2534. dirty_contacts_expiry = 0;
  2535. }
  2536. #if defined(ESP_PLATFORM)
  2537. bool network_required = false;
  2538. #if WITH_WEB_PANEL
  2539. network_required = web.isWebEnabled();
  2540. #endif
  2541. #ifdef WITH_MQTT_UPLINK
  2542. network_required = network_required || mqtt.isActive();
  2543. #endif
  2544. network.loop(network_required);
  2545. #if WITH_WEB_PANEL
  2546. web.loop();
  2547. #endif
  2548. #endif
  2549. #ifdef WITH_MQTT_UPLINK
  2550. MQTTStatusSnapshot mqtt_status{};
  2551. mqtt_status.battery_mv = static_cast<int>(getBatteryMilliVolts());
  2552. mqtt_status.uptime_secs = static_cast<uint32_t>(uptime_millis / 1000);
  2553. mqtt_status.error_flags = _err_flags;
  2554. mqtt_status.queue_len = static_cast<uint16_t>(_mgr->getOutboundTotal());
  2555. mqtt_status.noise_floor = static_cast<int>(_radio->getNoiseFloor());
  2556. mqtt_status.tx_air_secs = static_cast<uint32_t>(getTotalAirTime() / 1000);
  2557. mqtt_status.rx_air_secs = static_cast<uint32_t>(getReceiveAirTime() / 1000);
  2558. mqtt_status.recv_errors = radio_driver.getPacketsRecvErrors();
  2559. mqtt_status.radio_freq = _prefs.freq;
  2560. mqtt_status.radio_bw = _prefs.bw;
  2561. mqtt_status.radio_sf = _prefs.sf;
  2562. mqtt_status.radio_cr = _prefs.cr;
  2563. mqtt.loop(mqtt_status);
  2564. #endif
  2565. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  2566. updateStatsHistory(now);
  2567. #endif
  2568. }
  2569. // To check if there is pending work
  2570. bool MyMesh::hasPendingWork() const {
  2571. #if defined(WITH_BRIDGE)
  2572. if (bridge.isRunning()) return true; // bridge needs WiFi radio, can't sleep
  2573. #endif
  2574. #if defined(WITH_MQTT_UPLINK)
  2575. if (mqtt.isActive()) return true;
  2576. #endif
  2577. #if defined(ESP_PLATFORM) && WITH_WEB_PANEL
  2578. if (web.isWebEnabled()) return true;
  2579. #endif
  2580. return _mgr->getOutboundTotal() > 0;
  2581. }