MyMesh.cpp 105 KB

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