MyMesh.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. #include "MyMesh.h"
  2. /* ------------------------------ Config -------------------------------- */
  3. #ifndef LORA_FREQ
  4. #define LORA_FREQ 915.0
  5. #endif
  6. #ifndef LORA_BW
  7. #define LORA_BW 250
  8. #endif
  9. #ifndef LORA_SF
  10. #define LORA_SF 10
  11. #endif
  12. #ifndef LORA_CR
  13. #define LORA_CR 5
  14. #endif
  15. #ifndef LORA_TX_POWER
  16. #define LORA_TX_POWER 20
  17. #endif
  18. #ifndef ADVERT_NAME
  19. #define ADVERT_NAME "repeater"
  20. #endif
  21. #ifndef ADVERT_LAT
  22. #define ADVERT_LAT 0.0
  23. #endif
  24. #ifndef ADVERT_LON
  25. #define ADVERT_LON 0.0
  26. #endif
  27. #ifndef ADMIN_PASSWORD
  28. #define ADMIN_PASSWORD "password"
  29. #endif
  30. #ifndef SERVER_RESPONSE_DELAY
  31. #define SERVER_RESPONSE_DELAY 300
  32. #endif
  33. #ifndef TXT_ACK_DELAY
  34. #define TXT_ACK_DELAY 200
  35. #endif
  36. #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
  37. #define REQ_TYPE_KEEP_ALIVE 0x02
  38. #define REQ_TYPE_GET_TELEMETRY_DATA 0x03
  39. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  40. #define CLI_REPLY_DELAY_MILLIS 600
  41. ClientInfo *MyMesh::putClient(const mesh::Identity &id) {
  42. uint32_t min_time = 0xFFFFFFFF;
  43. ClientInfo *oldest = &known_clients[0];
  44. for (int i = 0; i < MAX_CLIENTS; i++) {
  45. if (known_clients[i].last_activity < min_time) {
  46. oldest = &known_clients[i];
  47. min_time = oldest->last_activity;
  48. }
  49. if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
  50. }
  51. oldest->id = id;
  52. oldest->out_path_len = -1; // initially out_path is unknown
  53. oldest->last_timestamp = 0;
  54. return oldest;
  55. }
  56. void MyMesh::putNeighbour(const mesh::Identity &id, uint32_t timestamp, float snr) {
  57. #if MAX_NEIGHBOURS // check if neighbours enabled
  58. // find existing neighbour, else use least recently updated
  59. uint32_t oldest_timestamp = 0xFFFFFFFF;
  60. NeighbourInfo *neighbour = &neighbours[0];
  61. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  62. // if neighbour already known, we should update it
  63. if (id.matches(neighbours[i].id)) {
  64. neighbour = &neighbours[i];
  65. break;
  66. }
  67. // otherwise we should update the least recently updated neighbour
  68. if (neighbours[i].heard_timestamp < oldest_timestamp) {
  69. neighbour = &neighbours[i];
  70. oldest_timestamp = neighbour->heard_timestamp;
  71. }
  72. }
  73. // update neighbour info
  74. neighbour->id = id;
  75. neighbour->advert_timestamp = timestamp;
  76. neighbour->heard_timestamp = getRTCClock()->getCurrentTime();
  77. neighbour->snr = (int8_t)(snr * 4);
  78. #endif
  79. }
  80. int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload,
  81. size_t payload_len) {
  82. // uint32_t now = getRTCClock()->getCurrentTimeUnique();
  83. // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  84. memcpy(reply_data, &sender_timestamp,
  85. 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  86. switch (payload[0]) {
  87. case REQ_TYPE_GET_STATUS: { // guests can also access this now
  88. RepeaterStats stats;
  89. stats.batt_milli_volts = board.getBattMilliVolts();
  90. stats.curr_tx_queue_len = _mgr->getOutboundCount(0xFFFFFFFF);
  91. stats.noise_floor = (int16_t)_radio->getNoiseFloor();
  92. stats.last_rssi = (int16_t)radio_driver.getLastRSSI();
  93. stats.n_packets_recv = radio_driver.getPacketsRecv();
  94. stats.n_packets_sent = radio_driver.getPacketsSent();
  95. stats.total_air_time_secs = getTotalAirTime() / 1000;
  96. stats.total_up_time_secs = _ms->getMillis() / 1000;
  97. stats.n_sent_flood = getNumSentFlood();
  98. stats.n_sent_direct = getNumSentDirect();
  99. stats.n_recv_flood = getNumRecvFlood();
  100. stats.n_recv_direct = getNumRecvDirect();
  101. stats.err_events = _err_flags;
  102. stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
  103. stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
  104. stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
  105. stats.total_rx_air_time_secs = getReceiveAirTime() / 1000;
  106. memcpy(&reply_data[4], &stats, sizeof(stats));
  107. return 4 + sizeof(stats); // reply_len
  108. }
  109. case REQ_TYPE_GET_TELEMETRY_DATA: {
  110. uint8_t perm_mask = ~(payload[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions
  111. telemetry.reset();
  112. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  113. // query other sensors -- target specific
  114. sensors.querySensors((sender->is_admin ? 0xFF : 0x00) & perm_mask, telemetry);
  115. uint8_t tlen = telemetry.getSize();
  116. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  117. return 4 + tlen; // reply_len
  118. }
  119. }
  120. return 0; // unknown command
  121. }
  122. mesh::Packet *MyMesh::createSelfAdvert() {
  123. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  124. uint8_t app_data_len;
  125. {
  126. AdvertDataBuilder builder(ADV_TYPE_REPEATER, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  127. app_data_len = builder.encodeTo(app_data);
  128. }
  129. return createAdvert(self_id, app_data, app_data_len);
  130. }
  131. File MyMesh::openAppend(const char *fname) {
  132. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  133. return _fs->open(fname, FILE_O_WRITE);
  134. #elif defined(RP2040_PLATFORM)
  135. return _fs->open(fname, "a");
  136. #else
  137. return _fs->open(fname, "a", true);
  138. #endif
  139. }
  140. bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
  141. if (_prefs.disable_fwd) return false;
  142. if (packet->isRouteFlood() && packet->path_len >= _prefs.flood_max) return false;
  143. return true;
  144. }
  145. const char *MyMesh::getLogDateTime() {
  146. static char tmp[32];
  147. uint32_t now = getRTCClock()->getCurrentTime();
  148. DateTime dt = DateTime(now);
  149. sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
  150. dt.year());
  151. return tmp;
  152. }
  153. void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
  154. #if MESH_PACKET_LOGGING
  155. Serial.print(getLogDateTime());
  156. Serial.print(" RAW: ");
  157. mesh::Utils::printHex(Serial, raw, len);
  158. Serial.println();
  159. #endif
  160. }
  161. void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
  162. if (_logging) {
  163. File f = openAppend(PACKET_LOG_FILE);
  164. if (f) {
  165. f.print(getLogDateTime());
  166. f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
  167. pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
  168. (int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
  169. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  170. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  171. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  172. } else {
  173. f.printf("\n");
  174. }
  175. f.close();
  176. }
  177. }
  178. }
  179. void MyMesh::logTx(mesh::Packet *pkt, int len) {
  180. #ifdef WITH_BRIDGE
  181. bridge.onPacketTransmitted(pkt);
  182. #endif
  183. if (_logging) {
  184. File f = openAppend(PACKET_LOG_FILE);
  185. if (f) {
  186. f.print(getLogDateTime());
  187. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  188. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  189. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  190. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  191. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  192. } else {
  193. f.printf("\n");
  194. }
  195. f.close();
  196. }
  197. }
  198. }
  199. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  200. if (_logging) {
  201. File f = openAppend(PACKET_LOG_FILE);
  202. if (f) {
  203. f.print(getLogDateTime());
  204. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  205. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  206. f.close();
  207. }
  208. }
  209. }
  210. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  211. if (_prefs.rx_delay_base <= 0.0f) return 0;
  212. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  213. }
  214. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  215. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  216. return getRNG()->nextInt(0, 6) * t;
  217. }
  218. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  219. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  220. return getRNG()->nextInt(0, 6) * t;
  221. }
  222. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  223. uint8_t *data, size_t len) {
  224. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  225. // client (unknown at this stage)
  226. uint32_t timestamp;
  227. memcpy(&timestamp, data, 4);
  228. bool is_admin;
  229. data[len] = 0; // ensure null terminator
  230. if (strcmp((char *)&data[4], _prefs.password) == 0) { // check for valid password
  231. is_admin = true;
  232. } else if (strcmp((char *)&data[4], _prefs.guest_password) == 0) { // check guest password
  233. is_admin = false;
  234. } else {
  235. #if MESH_DEBUG
  236. MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]);
  237. #endif
  238. return;
  239. }
  240. auto client = putClient(sender); // add to known clients (if not already known)
  241. if (timestamp <= client->last_timestamp) {
  242. MESH_DEBUG_PRINTLN("Possible login replay attack!");
  243. return; // FATAL: client table is full -OR- replay attack
  244. }
  245. MESH_DEBUG_PRINTLN("Login success!");
  246. client->last_timestamp = timestamp;
  247. client->last_activity = getRTCClock()->getCurrentTime();
  248. client->is_admin = is_admin;
  249. memcpy(client->secret, secret, PUB_KEY_SIZE);
  250. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  251. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  252. #if 0
  253. memcpy(&reply_data[4], "OK", 2); // legacy response
  254. #else
  255. reply_data[4] = RESP_SERVER_LOGIN_OK;
  256. reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16)
  257. reply_data[6] = is_admin ? 1 : 0;
  258. reply_data[7] = 0; // FUTURE: reserved
  259. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  260. #endif
  261. if (packet->isRouteFlood()) {
  262. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  263. mesh::Packet *path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
  264. PAYLOAD_TYPE_RESPONSE, reply_data, 12);
  265. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  266. } else {
  267. mesh::Packet *reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 12);
  268. if (reply) {
  269. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  270. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  271. } else {
  272. sendFlood(reply, SERVER_RESPONSE_DELAY);
  273. }
  274. }
  275. }
  276. }
  277. }
  278. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  279. int n = 0;
  280. for (int i = 0; i < MAX_CLIENTS; i++) {
  281. if (known_clients[i].id.isHashMatch(hash)) {
  282. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  283. }
  284. }
  285. return n;
  286. }
  287. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  288. int i = matching_peer_indexes[peer_idx];
  289. if (i >= 0 && i < MAX_CLIENTS) {
  290. // lookup pre-calculated shared_secret
  291. memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
  292. } else {
  293. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  294. }
  295. }
  296. void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
  297. const uint8_t *app_data, size_t app_data_len) {
  298. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  299. // if this a zero hop advert, add it to neighbours
  300. if (packet->path_len == 0) {
  301. AdvertDataParser parser(app_data, app_data_len);
  302. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  303. putNeighbour(id, timestamp, packet->getSNR());
  304. }
  305. }
  306. }
  307. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  308. uint8_t *data, size_t len) {
  309. int i = matching_peer_indexes[sender_idx];
  310. if (i < 0 ||
  311. i >= MAX_CLIENTS) { // get from our known_clients table (sender SHOULD already be known in this context)
  312. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  313. return;
  314. }
  315. auto client = &known_clients[i];
  316. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  317. uint32_t timestamp;
  318. memcpy(&timestamp, data, 4);
  319. if (timestamp > client->last_timestamp) { // prevent replay attacks
  320. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  321. if (reply_len == 0) return; // invalid command
  322. client->last_timestamp = timestamp;
  323. client->last_activity = getRTCClock()->getCurrentTime();
  324. if (packet->isRouteFlood()) {
  325. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  326. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  327. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  328. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  329. } else {
  330. mesh::Packet *reply =
  331. createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  332. if (reply) {
  333. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  334. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  335. } else {
  336. sendFlood(reply, SERVER_RESPONSE_DELAY);
  337. }
  338. }
  339. }
  340. } else {
  341. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  342. }
  343. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->is_admin) { // a CLI command
  344. uint32_t sender_timestamp;
  345. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  346. uint flags = (data[4] >> 2); // message attempt number, and other flags
  347. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  348. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  349. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  350. bool is_retry = (sender_timestamp == client->last_timestamp);
  351. client->last_timestamp = sender_timestamp;
  352. client->last_activity = getRTCClock()->getCurrentTime();
  353. // len can be > original length, but 'text' will be padded with zeroes
  354. data[len] = 0; // need to make a C string again, with null terminator
  355. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  356. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
  357. // to sender that we got it
  358. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  359. PUB_KEY_SIZE);
  360. mesh::Packet *ack = createAck(ack_hash);
  361. if (ack) {
  362. if (client->out_path_len < 0) {
  363. sendFlood(ack, TXT_ACK_DELAY);
  364. } else {
  365. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  366. }
  367. }
  368. }
  369. uint8_t temp[166];
  370. char *command = (char *)&data[5];
  371. char *reply = (char *)&temp[5];
  372. if (is_retry) {
  373. *reply = 0;
  374. } else {
  375. handleCommand(sender_timestamp, command, reply);
  376. }
  377. int text_len = strlen(reply);
  378. if (text_len > 0) {
  379. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  380. if (timestamp == sender_timestamp) {
  381. // WORKAROUND: the two timestamps need to be different, in the CLI view
  382. timestamp++;
  383. }
  384. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  385. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  386. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  387. if (reply) {
  388. if (client->out_path_len < 0) {
  389. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  390. } else {
  391. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  392. }
  393. }
  394. }
  395. } else {
  396. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  397. }
  398. }
  399. }
  400. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  401. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  402. // TODO: prevent replay attacks
  403. int i = matching_peer_indexes[sender_idx];
  404. if (i >= 0 &&
  405. i < MAX_CLIENTS) { // get from our known_clients table (sender SHOULD already be known in this context)
  406. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  407. auto client = &known_clients[i];
  408. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  409. } else {
  410. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  411. }
  412. // NOTE: no reciprocal path send!!
  413. return false;
  414. }
  415. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  416. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  417. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  418. _cli(board, rtc, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4)
  419. #if defined(WITH_RS232_BRIDGE)
  420. , bridge(WITH_RS232_BRIDGE, _mgr, &rtc)
  421. #elif defined(WITH_ESPNOW_BRIDGE)
  422. , bridge(_mgr, &rtc)
  423. #endif
  424. {
  425. memset(known_clients, 0, sizeof(known_clients));
  426. next_local_advert = next_flood_advert = 0;
  427. set_radio_at = revert_radio_at = 0;
  428. _logging = false;
  429. #if MAX_NEIGHBOURS
  430. memset(neighbours, 0, sizeof(neighbours));
  431. #endif
  432. // defaults
  433. memset(&_prefs, 0, sizeof(_prefs));
  434. _prefs.airtime_factor = 1.0; // one half
  435. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  436. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  437. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  438. _prefs.node_lat = ADVERT_LAT;
  439. _prefs.node_lon = ADVERT_LON;
  440. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  441. _prefs.freq = LORA_FREQ;
  442. _prefs.sf = LORA_SF;
  443. _prefs.bw = LORA_BW;
  444. _prefs.cr = LORA_CR;
  445. _prefs.tx_power_dbm = LORA_TX_POWER;
  446. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  447. _prefs.flood_advert_interval = 12; // 12 hours
  448. _prefs.flood_max = 64;
  449. _prefs.interference_threshold = 0; // disabled
  450. }
  451. void MyMesh::begin(FILESYSTEM *fs) {
  452. mesh::Mesh::begin();
  453. _fs = fs;
  454. // load persisted prefs
  455. _cli.loadPrefs(_fs);
  456. #ifdef WITH_BRIDGE
  457. bridge.begin();
  458. #endif
  459. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  460. radio_set_tx_power(_prefs.tx_power_dbm);
  461. updateAdvertTimer();
  462. updateFloodAdvertTimer();
  463. }
  464. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  465. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  466. pending_freq = freq;
  467. pending_bw = bw;
  468. pending_sf = sf;
  469. pending_cr = cr;
  470. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  471. }
  472. bool MyMesh::formatFileSystem() {
  473. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  474. return InternalFS.format();
  475. #elif defined(RP2040_PLATFORM)
  476. return LittleFS.format();
  477. #elif defined(ESP32)
  478. return SPIFFS.format();
  479. #else
  480. #error "need to implement file system erase"
  481. return false;
  482. #endif
  483. }
  484. void MyMesh::sendSelfAdvertisement(int delay_millis) {
  485. mesh::Packet *pkt = createSelfAdvert();
  486. if (pkt) {
  487. sendFlood(pkt, delay_millis);
  488. } else {
  489. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  490. }
  491. }
  492. void MyMesh::updateAdvertTimer() {
  493. if (_prefs.advert_interval > 0) { // schedule local advert timer
  494. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  495. } else {
  496. next_local_advert = 0; // stop the timer
  497. }
  498. }
  499. void MyMesh::updateFloodAdvertTimer() {
  500. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  501. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  502. } else {
  503. next_flood_advert = 0; // stop the timer
  504. }
  505. }
  506. void MyMesh::dumpLogFile() {
  507. #if defined(RP2040_PLATFORM)
  508. File f = _fs->open(PACKET_LOG_FILE, "r");
  509. #else
  510. File f = _fs->open(PACKET_LOG_FILE);
  511. #endif
  512. if (f) {
  513. while (f.available()) {
  514. int c = f.read();
  515. if (c < 0) break;
  516. Serial.print((char)c);
  517. }
  518. f.close();
  519. }
  520. }
  521. void MyMesh::setTxPower(uint8_t power_dbm) {
  522. radio_set_tx_power(power_dbm);
  523. }
  524. void MyMesh::formatNeighborsReply(char *reply) {
  525. char *dp = reply;
  526. #if MAX_NEIGHBOURS
  527. for (int i = 0; i < MAX_NEIGHBOURS && dp - reply < 134; i++) {
  528. NeighbourInfo *neighbour = &neighbours[i];
  529. if (neighbour->heard_timestamp == 0) continue; // skip empty slots
  530. // add new line if not first item
  531. if (i > 0) *dp++ = '\n';
  532. char hex[10];
  533. // get 4 bytes of neighbour id as hex
  534. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  535. // add next neighbour
  536. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  537. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  538. while (*dp)
  539. dp++; // find end of string
  540. }
  541. #endif
  542. if (dp == reply) { // no neighbours, need empty response
  543. strcpy(dp, "-none-");
  544. dp += 6;
  545. }
  546. *dp = 0; // null terminator
  547. }
  548. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  549. #if MAX_NEIGHBOURS
  550. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  551. NeighbourInfo *neighbour = &neighbours[i];
  552. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  553. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  554. }
  555. }
  556. #endif
  557. }
  558. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  559. self_id = new_id;
  560. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  561. IdentityStore store(*_fs, "");
  562. #elif defined(ESP32)
  563. IdentityStore store(*_fs, "/identity");
  564. #elif defined(RP2040_PLATFORM)
  565. IdentityStore store(*_fs, "/identity");
  566. #else
  567. #error "need to define saveIdentity()"
  568. #endif
  569. store.save("_main", self_id);
  570. }
  571. void MyMesh::clearStats() {
  572. radio_driver.resetStats();
  573. resetStats();
  574. ((SimpleMeshTables *)getTables())->resetStats();
  575. }
  576. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  577. while (*command == ' ')
  578. command++; // skip leading spaces
  579. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  580. memcpy(reply, command, 3); // reflect the prefix back
  581. reply += 3;
  582. command += 3;
  583. }
  584. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  585. }
  586. void MyMesh::loop() {
  587. #ifdef WITH_BRIDGE
  588. bridge.loop();
  589. #endif
  590. mesh::Mesh::loop();
  591. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  592. mesh::Packet *pkt = createSelfAdvert();
  593. if (pkt) sendFlood(pkt);
  594. updateFloodAdvertTimer(); // schedule next flood advert
  595. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  596. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  597. mesh::Packet *pkt = createSelfAdvert();
  598. if (pkt) sendZeroHop(pkt);
  599. updateAdvertTimer(); // schedule next local advert
  600. }
  601. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  602. set_radio_at = 0; // clear timer
  603. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  604. MESH_DEBUG_PRINTLN("Temp radio params");
  605. }
  606. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  607. revert_radio_at = 0; // clear timer
  608. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  609. MESH_DEBUG_PRINTLN("Radio params restored");
  610. }
  611. }