MyMesh.cpp 106 KB

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