MyMesh.cpp 102 KB

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