MyMesh.cpp 91 KB

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