MyMesh.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. if (_logging) {
  181. File f = openAppend(PACKET_LOG_FILE);
  182. if (f) {
  183. f.print(getLogDateTime());
  184. f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
  185. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  186. if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
  187. pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
  188. f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
  189. } else {
  190. f.printf("\n");
  191. }
  192. f.close();
  193. }
  194. }
  195. }
  196. void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
  197. if (_logging) {
  198. File f = openAppend(PACKET_LOG_FILE);
  199. if (f) {
  200. f.print(getLogDateTime());
  201. f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
  202. pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
  203. f.close();
  204. }
  205. }
  206. }
  207. int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
  208. if (_prefs.rx_delay_base <= 0.0f) return 0;
  209. return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  210. }
  211. uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
  212. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  213. return getRNG()->nextInt(0, 6) * t;
  214. }
  215. uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
  216. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  217. return getRNG()->nextInt(0, 6) * t;
  218. }
  219. void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
  220. uint8_t *data, size_t len) {
  221. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
  222. // client (unknown at this stage)
  223. uint32_t timestamp;
  224. memcpy(&timestamp, data, 4);
  225. bool is_admin;
  226. data[len] = 0; // ensure null terminator
  227. if (strcmp((char *)&data[4], _prefs.password) == 0) { // check for valid password
  228. is_admin = true;
  229. } else if (strcmp((char *)&data[4], _prefs.guest_password) == 0) { // check guest password
  230. is_admin = false;
  231. } else {
  232. #if MESH_DEBUG
  233. MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]);
  234. #endif
  235. return;
  236. }
  237. auto client = putClient(sender); // add to known clients (if not already known)
  238. if (timestamp <= client->last_timestamp) {
  239. MESH_DEBUG_PRINTLN("Possible login replay attack!");
  240. return; // FATAL: client table is full -OR- replay attack
  241. }
  242. MESH_DEBUG_PRINTLN("Login success!");
  243. client->last_timestamp = timestamp;
  244. client->last_activity = getRTCClock()->getCurrentTime();
  245. client->is_admin = is_admin;
  246. memcpy(client->secret, secret, PUB_KEY_SIZE);
  247. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  248. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  249. #if 0
  250. memcpy(&reply_data[4], "OK", 2); // legacy response
  251. #else
  252. reply_data[4] = RESP_SERVER_LOGIN_OK;
  253. reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16)
  254. reply_data[6] = is_admin ? 1 : 0;
  255. reply_data[7] = 0; // FUTURE: reserved
  256. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  257. #endif
  258. if (packet->isRouteFlood()) {
  259. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  260. mesh::Packet *path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
  261. PAYLOAD_TYPE_RESPONSE, reply_data, 12);
  262. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  263. } else {
  264. mesh::Packet *reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 12);
  265. if (reply) {
  266. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  267. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  268. } else {
  269. sendFlood(reply, SERVER_RESPONSE_DELAY);
  270. }
  271. }
  272. }
  273. }
  274. }
  275. int MyMesh::searchPeersByHash(const uint8_t *hash) {
  276. int n = 0;
  277. for (int i = 0; i < MAX_CLIENTS; i++) {
  278. if (known_clients[i].id.isHashMatch(hash)) {
  279. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  280. }
  281. }
  282. return n;
  283. }
  284. void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
  285. int i = matching_peer_indexes[peer_idx];
  286. if (i >= 0 && i < MAX_CLIENTS) {
  287. // lookup pre-calculated shared_secret
  288. memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
  289. } else {
  290. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  291. }
  292. }
  293. void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
  294. const uint8_t *app_data, size_t app_data_len) {
  295. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  296. // if this a zero hop advert, add it to neighbours
  297. if (packet->path_len == 0) {
  298. AdvertDataParser parser(app_data, app_data_len);
  299. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  300. putNeighbour(id, timestamp, packet->getSNR());
  301. }
  302. }
  303. }
  304. void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
  305. uint8_t *data, size_t len) {
  306. int i = matching_peer_indexes[sender_idx];
  307. if (i < 0 ||
  308. i >= MAX_CLIENTS) { // get from our known_clients table (sender SHOULD already be known in this context)
  309. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  310. return;
  311. }
  312. auto client = &known_clients[i];
  313. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  314. uint32_t timestamp;
  315. memcpy(&timestamp, data, 4);
  316. if (timestamp > client->last_timestamp) { // prevent replay attacks
  317. int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
  318. if (reply_len == 0) return; // invalid command
  319. client->last_timestamp = timestamp;
  320. client->last_activity = getRTCClock()->getCurrentTime();
  321. if (packet->isRouteFlood()) {
  322. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  323. mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  324. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  325. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  326. } else {
  327. mesh::Packet *reply =
  328. createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  329. if (reply) {
  330. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  331. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  332. } else {
  333. sendFlood(reply, SERVER_RESPONSE_DELAY);
  334. }
  335. }
  336. }
  337. } else {
  338. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  339. }
  340. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->is_admin) { // a CLI command
  341. uint32_t sender_timestamp;
  342. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  343. uint flags = (data[4] >> 2); // message attempt number, and other flags
  344. if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
  345. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  346. } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
  347. bool is_retry = (sender_timestamp == client->last_timestamp);
  348. client->last_timestamp = sender_timestamp;
  349. client->last_activity = getRTCClock()->getCurrentTime();
  350. // len can be > original length, but 'text' will be padded with zeroes
  351. data[len] = 0; // need to make a C string again, with null terminator
  352. if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
  353. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
  354. // to sender that we got it
  355. mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
  356. PUB_KEY_SIZE);
  357. mesh::Packet *ack = createAck(ack_hash);
  358. if (ack) {
  359. if (client->out_path_len < 0) {
  360. sendFlood(ack, TXT_ACK_DELAY);
  361. } else {
  362. sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
  363. }
  364. }
  365. }
  366. uint8_t temp[166];
  367. char *command = (char *)&data[5];
  368. char *reply = (char *)&temp[5];
  369. if (is_retry) {
  370. *reply = 0;
  371. } else {
  372. handleCommand(sender_timestamp, command, reply);
  373. }
  374. int text_len = strlen(reply);
  375. if (text_len > 0) {
  376. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  377. if (timestamp == sender_timestamp) {
  378. // WORKAROUND: the two timestamps need to be different, in the CLI view
  379. timestamp++;
  380. }
  381. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  382. temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
  383. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
  384. if (reply) {
  385. if (client->out_path_len < 0) {
  386. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  387. } else {
  388. sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
  389. }
  390. }
  391. }
  392. } else {
  393. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  394. }
  395. }
  396. }
  397. bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
  398. uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
  399. // TODO: prevent replay attacks
  400. int i = matching_peer_indexes[sender_idx];
  401. if (i >= 0 &&
  402. i < MAX_CLIENTS) { // get from our known_clients table (sender SHOULD already be known in this context)
  403. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
  404. auto client = &known_clients[i];
  405. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  406. } else {
  407. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  408. }
  409. // NOTE: no reciprocal path send!!
  410. return false;
  411. }
  412. MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
  413. mesh::RTCClock &rtc, mesh::MeshTables &tables)
  414. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  415. _cli(board, rtc, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4) {
  416. memset(known_clients, 0, sizeof(known_clients));
  417. next_local_advert = next_flood_advert = 0;
  418. set_radio_at = revert_radio_at = 0;
  419. _logging = false;
  420. #if MAX_NEIGHBOURS
  421. memset(neighbours, 0, sizeof(neighbours));
  422. #endif
  423. // defaults
  424. memset(&_prefs, 0, sizeof(_prefs));
  425. _prefs.airtime_factor = 1.0; // one half
  426. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  427. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  428. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  429. _prefs.node_lat = ADVERT_LAT;
  430. _prefs.node_lon = ADVERT_LON;
  431. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  432. _prefs.freq = LORA_FREQ;
  433. _prefs.sf = LORA_SF;
  434. _prefs.bw = LORA_BW;
  435. _prefs.cr = LORA_CR;
  436. _prefs.tx_power_dbm = LORA_TX_POWER;
  437. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  438. _prefs.flood_advert_interval = 12; // 12 hours
  439. _prefs.flood_max = 64;
  440. _prefs.interference_threshold = 0; // disabled
  441. }
  442. void MyMesh::begin(FILESYSTEM *fs) {
  443. mesh::Mesh::begin();
  444. _fs = fs;
  445. // load persisted prefs
  446. _cli.loadPrefs(_fs);
  447. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  448. radio_set_tx_power(_prefs.tx_power_dbm);
  449. updateAdvertTimer();
  450. updateFloodAdvertTimer();
  451. }
  452. void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  453. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  454. pending_freq = freq;
  455. pending_bw = bw;
  456. pending_sf = sf;
  457. pending_cr = cr;
  458. revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
  459. }
  460. bool MyMesh::formatFileSystem() {
  461. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  462. return InternalFS.format();
  463. #elif defined(RP2040_PLATFORM)
  464. return LittleFS.format();
  465. #elif defined(ESP32)
  466. return SPIFFS.format();
  467. #else
  468. #error "need to implement file system erase"
  469. return false;
  470. #endif
  471. }
  472. void MyMesh::sendSelfAdvertisement(int delay_millis) {
  473. mesh::Packet *pkt = createSelfAdvert();
  474. if (pkt) {
  475. sendFlood(pkt, delay_millis);
  476. } else {
  477. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  478. }
  479. }
  480. void MyMesh::updateAdvertTimer() {
  481. if (_prefs.advert_interval > 0) { // schedule local advert timer
  482. next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  483. } else {
  484. next_local_advert = 0; // stop the timer
  485. }
  486. }
  487. void MyMesh::updateFloodAdvertTimer() {
  488. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  489. next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  490. } else {
  491. next_flood_advert = 0; // stop the timer
  492. }
  493. }
  494. void MyMesh::dumpLogFile() {
  495. #if defined(RP2040_PLATFORM)
  496. File f = _fs->open(PACKET_LOG_FILE, "r");
  497. #else
  498. File f = _fs->open(PACKET_LOG_FILE);
  499. #endif
  500. if (f) {
  501. while (f.available()) {
  502. int c = f.read();
  503. if (c < 0) break;
  504. Serial.print((char)c);
  505. }
  506. f.close();
  507. }
  508. }
  509. void MyMesh::setTxPower(uint8_t power_dbm) {
  510. radio_set_tx_power(power_dbm);
  511. }
  512. void MyMesh::formatNeighborsReply(char *reply) {
  513. char *dp = reply;
  514. #if MAX_NEIGHBOURS
  515. for (int i = 0; i < MAX_NEIGHBOURS && dp - reply < 134; i++) {
  516. NeighbourInfo *neighbour = &neighbours[i];
  517. if (neighbour->heard_timestamp == 0) continue; // skip empty slots
  518. // add new line if not first item
  519. if (i > 0) *dp++ = '\n';
  520. char hex[10];
  521. // get 4 bytes of neighbour id as hex
  522. mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
  523. // add next neighbour
  524. uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
  525. sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
  526. while (*dp)
  527. dp++; // find end of string
  528. }
  529. #endif
  530. if (dp == reply) { // no neighbours, need empty response
  531. strcpy(dp, "-none-");
  532. dp += 6;
  533. }
  534. *dp = 0; // null terminator
  535. }
  536. void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
  537. #if MAX_NEIGHBOURS
  538. for (int i = 0; i < MAX_NEIGHBOURS; i++) {
  539. NeighbourInfo *neighbour = &neighbours[i];
  540. if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
  541. neighbours[i] = NeighbourInfo(); // clear neighbour entry
  542. }
  543. }
  544. #endif
  545. }
  546. void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
  547. self_id = new_id;
  548. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  549. IdentityStore store(*_fs, "");
  550. #elif defined(ESP32)
  551. IdentityStore store(*_fs, "/identity");
  552. #elif defined(RP2040_PLATFORM)
  553. IdentityStore store(*_fs, "/identity");
  554. #else
  555. #error "need to define saveIdentity()"
  556. #endif
  557. store.save("_main", self_id);
  558. }
  559. void MyMesh::clearStats() {
  560. radio_driver.resetStats();
  561. resetStats();
  562. ((SimpleMeshTables *)getTables())->resetStats();
  563. }
  564. void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
  565. while (*command == ' ')
  566. command++; // skip leading spaces
  567. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  568. memcpy(reply, command, 3); // reflect the prefix back
  569. reply += 3;
  570. command += 3;
  571. }
  572. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  573. }
  574. void MyMesh::loop() {
  575. mesh::Mesh::loop();
  576. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  577. mesh::Packet *pkt = createSelfAdvert();
  578. if (pkt) sendFlood(pkt);
  579. updateFloodAdvertTimer(); // schedule next flood advert
  580. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  581. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  582. mesh::Packet *pkt = createSelfAdvert();
  583. if (pkt) sendZeroHop(pkt);
  584. updateAdvertTimer(); // schedule next local advert
  585. }
  586. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  587. set_radio_at = 0; // clear timer
  588. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  589. MESH_DEBUG_PRINTLN("Temp radio params");
  590. }
  591. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  592. revert_radio_at = 0; // clear timer
  593. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  594. MESH_DEBUG_PRINTLN("Radio params restored");
  595. }
  596. }