MyMesh.cpp 107 KB

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