MyMesh.cpp 105 KB

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