SensorMesh.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. #include "SensorMesh.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 "sensor"
  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. #ifndef SENSOR_READ_INTERVAL_SECS
  37. #define SENSOR_READ_INTERVAL_SECS 60
  38. #endif
  39. /* ------------------------------ Code -------------------------------- */
  40. #define REQ_TYPE_GET_STATUS 0x01
  41. #define REQ_TYPE_KEEP_ALIVE 0x02
  42. #define REQ_TYPE_GET_TELEMETRY_DATA 0x03
  43. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  44. #define CLI_REPLY_DELAY_MILLIS 1000
  45. #define LAZY_CONTACTS_WRITE_DELAY 5000
  46. static File openAppend(FILESYSTEM* _fs, const char* fname) {
  47. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  48. return _fs->open(fname, FILE_O_WRITE);
  49. #elif defined(RP2040_PLATFORM)
  50. return _fs->open(fname, "a");
  51. #else
  52. return _fs->open(fname, "a", true);
  53. #endif
  54. }
  55. static File openWrite(FILESYSTEM* _fs, const char* filename) {
  56. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  57. _fs->remove(filename);
  58. return _fs->open(filename, FILE_O_WRITE);
  59. #elif defined(RP2040_PLATFORM)
  60. return _fs->open(filename, "w");
  61. #else
  62. return _fs->open(filename, "w", true);
  63. #endif
  64. }
  65. void SensorMesh::loadContacts() {
  66. num_contacts = 0;
  67. if (_fs->exists("/s_contacts")) {
  68. #if defined(RP2040_PLATFORM)
  69. File file = _fs->open("/s_contacts", "r");
  70. #else
  71. File file = _fs->open("/s_contacts");
  72. #endif
  73. if (file) {
  74. bool full = false;
  75. while (!full) {
  76. ContactInfo c;
  77. uint8_t pub_key[32];
  78. uint8_t unused;
  79. bool success = (file.read(pub_key, 32) == 32);
  80. success = success && (file.read(&c.type, 1) == 1);
  81. success = success && (file.read(&c.flags, 1) == 1);
  82. success = success && (file.read(&unused, 1) == 1);
  83. success = success && (file.read((uint8_t *)&c.out_path_len, 1) == 1);
  84. success = success && (file.read(c.out_path, 64) == 64);
  85. success = success && (file.read(c.shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE);
  86. c.last_timestamp = 0; // transient
  87. c.last_activity = 0;
  88. if (!success) break; // EOF
  89. c.id = mesh::Identity(pub_key);
  90. if (num_contacts < MAX_CONTACTS) {
  91. contacts[num_contacts++] = c;
  92. } else {
  93. full = true;
  94. }
  95. }
  96. file.close();
  97. }
  98. }
  99. }
  100. void SensorMesh::saveContacts() {
  101. File file = openWrite(_fs, "/s_contacts");
  102. if (file) {
  103. uint8_t unused = 0;
  104. for (int i = 0; i < num_contacts; i++) {
  105. auto c = &contacts[i];
  106. if (c->type == 0) continue; // don't persist guest contacts
  107. bool success = (file.write(c->id.pub_key, 32) == 32);
  108. success = success && (file.write(&c->type, 1) == 1);
  109. success = success && (file.write(&c->flags, 1) == 1);
  110. success = success && (file.write(&unused, 1) == 1);
  111. success = success && (file.write((uint8_t *)&c->out_path_len, 1) == 1);
  112. success = success && (file.write(c->out_path, 64) == 64);
  113. success = success && (file.write(c->shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE);
  114. if (!success) break; // write failed
  115. }
  116. file.close();
  117. }
  118. }
  119. int SensorMesh::handleRequest(ContactInfo& sender, uint32_t sender_timestamp, uint8_t* payload, size_t payload_len) {
  120. // uint32_t now = getRTCClock()->getCurrentTimeUnique();
  121. // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  122. memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  123. switch (payload[0]) {
  124. case REQ_TYPE_GET_TELEMETRY_DATA: {
  125. telemetry.reset();
  126. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  127. // query other sensors -- target specific
  128. sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions for admin or guest
  129. uint8_t tlen = telemetry.getSize();
  130. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  131. return 4 + tlen; // reply_len
  132. }
  133. }
  134. return 0; // unknown command
  135. }
  136. mesh::Packet* SensorMesh::createSelfAdvert() {
  137. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  138. uint8_t app_data_len;
  139. {
  140. AdvertDataBuilder builder(ADV_TYPE_SENSOR, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  141. app_data_len = builder.encodeTo(app_data);
  142. }
  143. return createAdvert(self_id, app_data, app_data_len);
  144. }
  145. ContactInfo* SensorMesh::putContact(const mesh::Identity& id) {
  146. uint32_t min_time = 0xFFFFFFFF;
  147. ContactInfo* oldest = &contacts[MAX_CONTACTS - 1];
  148. for (int i = 0; i < num_contacts; i++) {
  149. if (id.matches(contacts[i].id)) return &contacts[i]; // already known
  150. if (!contacts[i].isAdmin() && contacts[i].last_activity < min_time) {
  151. oldest = &contacts[i];
  152. min_time = oldest->last_activity;
  153. }
  154. }
  155. ContactInfo* c;
  156. if (num_contacts < MAX_CONTACTS) {
  157. c = &contacts[num_contacts++];
  158. } else {
  159. c = oldest; // evict least active contact
  160. }
  161. memset(c, 0, sizeof(*c));
  162. c->id = id;
  163. c->out_path_len = -1; // initially out_path is unknown
  164. return c;
  165. }
  166. void SensorMesh::alertIfLow(Trigger& t, float value, float threshold, const char* text) {
  167. if (value < threshold) {
  168. if (!t.triggered) {
  169. t.triggered = true;
  170. t.time = getRTCClock()->getCurrentTime();
  171. sendAlert(text);
  172. }
  173. } else {
  174. if (t.triggered) {
  175. t.triggered = false;
  176. // TODO: apply debounce logic
  177. }
  178. }
  179. }
  180. void SensorMesh::alertIfHigh(Trigger& t, float value, float threshold, const char* text) {
  181. if (value > threshold) {
  182. if (!t.triggered) {
  183. t.triggered = true;
  184. t.time = getRTCClock()->getCurrentTime();
  185. sendAlert(text);
  186. }
  187. } else {
  188. if (t.triggered) {
  189. t.triggered = false;
  190. // TODO: apply debounce logic
  191. }
  192. }
  193. }
  194. float SensorMesh::getAirtimeBudgetFactor() const {
  195. return _prefs.airtime_factor;
  196. }
  197. bool SensorMesh::allowPacketForward(const mesh::Packet* packet) {
  198. if (_prefs.disable_fwd) return false;
  199. if (packet->isRouteFlood() && packet->path_len >= _prefs.flood_max) return false;
  200. return true;
  201. }
  202. int SensorMesh::calcRxDelay(float score, uint32_t air_time) const {
  203. if (_prefs.rx_delay_base <= 0.0f) return 0;
  204. return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  205. }
  206. uint32_t SensorMesh::getRetransmitDelay(const mesh::Packet* packet) {
  207. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  208. return getRNG()->nextInt(0, 6)*t;
  209. }
  210. uint32_t SensorMesh::getDirectRetransmitDelay(const mesh::Packet* packet) {
  211. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  212. return getRNG()->nextInt(0, 6)*t;
  213. }
  214. int SensorMesh::getInterferenceThreshold() const {
  215. return _prefs.interference_threshold;
  216. }
  217. int SensorMesh::getAGCResetInterval() const {
  218. return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds
  219. }
  220. void SensorMesh::onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) {
  221. if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
  222. uint32_t timestamp;
  223. memcpy(&timestamp, data, 4);
  224. bool is_admin;
  225. data[len] = 0; // ensure null terminator
  226. if (strcmp((char *) &data[4], _prefs.password) == 0) { // check for valid password
  227. is_admin = true;
  228. } else if (strcmp((char *) &data[4], _prefs.guest_password) == 0) { // check guest password
  229. is_admin = false;
  230. } else {
  231. #if MESH_DEBUG
  232. MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]);
  233. #endif
  234. return;
  235. }
  236. auto client = putContact(sender); // add to contacts (if not already known)
  237. if (timestamp <= client->last_timestamp) {
  238. MESH_DEBUG_PRINTLN("Possible login replay attack!");
  239. return; // FATAL: client table is full -OR- replay attack
  240. }
  241. MESH_DEBUG_PRINTLN("Login success!");
  242. client->last_timestamp = timestamp;
  243. client->last_activity = getRTCClock()->getCurrentTime();
  244. client->type = is_admin ? 1 : 0;
  245. self_id.calcSharedSecret(client->shared_secret, client->id); // calc ECDH shared secret
  246. if (is_admin) {
  247. // only need to saveContacts() if this is an admin
  248. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  249. }
  250. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  251. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  252. reply_data[4] = RESP_SERVER_LOGIN_OK;
  253. reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16)
  254. reply_data[6] = client->type;
  255. reply_data[7] = 0; // FUTURE: reserved
  256. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  257. if (packet->isRouteFlood()) {
  258. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  259. mesh::Packet* path = createPathReturn(sender, client->shared_secret, packet->path, packet->path_len,
  260. PAYLOAD_TYPE_RESPONSE, reply_data, 12);
  261. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  262. } else {
  263. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->shared_secret, reply_data, 12);
  264. if (reply) {
  265. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  266. sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
  267. } else {
  268. sendFlood(reply, SERVER_RESPONSE_DELAY);
  269. }
  270. }
  271. }
  272. }
  273. }
  274. int SensorMesh::searchPeersByHash(const uint8_t* hash) {
  275. int n = 0;
  276. for (int i = 0; i < num_contacts && n < MAX_SEARCH_RESULTS; i++) {
  277. if (contacts[i].id.isHashMatch(hash)) {
  278. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  279. }
  280. }
  281. return n;
  282. }
  283. void SensorMesh::getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) {
  284. int i = matching_peer_indexes[peer_idx];
  285. if (i >= 0 && i < num_contacts) {
  286. // lookup pre-calculated shared_secret
  287. memcpy(dest_secret, contacts[i].shared_secret, PUB_KEY_SIZE);
  288. } else {
  289. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  290. }
  291. }
  292. void SensorMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) {
  293. mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
  294. #if 0
  295. // if this a zero hop advert, add it to neighbours
  296. if (packet->path_len == 0) {
  297. AdvertDataParser parser(app_data, app_data_len);
  298. if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
  299. putNeighbour(id, timestamp, packet->getSNR());
  300. }
  301. }
  302. #endif
  303. }
  304. void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) {
  305. int i = matching_peer_indexes[sender_idx];
  306. if (i < 0 || i >= num_contacts) {
  307. MESH_DEBUG_PRINTLN("onPeerDataRecv: Invalid sender idx: %d", i);
  308. return;
  309. }
  310. ContactInfo& from = contacts[i];
  311. if (type == PAYLOAD_TYPE_REQ) { // request (from a known contact)
  312. uint32_t timestamp;
  313. memcpy(&timestamp, data, 4);
  314. if (timestamp > from.last_timestamp) { // prevent replay attacks
  315. int reply_len = handleRequest(from, timestamp, &data[4], len - 4);
  316. if (reply_len == 0) return; // invalid command
  317. from.last_timestamp = timestamp;
  318. from.last_activity = getRTCClock()->getCurrentTime();
  319. if (packet->isRouteFlood()) {
  320. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  321. mesh::Packet* path = createPathReturn(from.id, secret, packet->path, packet->path_len,
  322. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  323. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  324. } else {
  325. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, from.id, secret, reply_data, reply_len);
  326. if (reply) {
  327. if (from.out_path_len >= 0) { // we have an out_path, so send DIRECT
  328. sendDirect(reply, from.out_path, from.out_path_len, SERVER_RESPONSE_DELAY);
  329. } else {
  330. sendFlood(reply, SERVER_RESPONSE_DELAY);
  331. }
  332. }
  333. }
  334. } else {
  335. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  336. }
  337. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && from.isAdmin()) { // a CLI command
  338. uint32_t sender_timestamp;
  339. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  340. uint flags = (data[4] >> 2); // message attempt number, and other flags
  341. if (!(flags == TXT_TYPE_CLI_DATA)) {
  342. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  343. } else if (sender_timestamp > from.last_timestamp) { // prevent replay attacks
  344. from.last_timestamp = sender_timestamp;
  345. from.last_activity = getRTCClock()->getCurrentTime();
  346. // len can be > original length, but 'text' will be padded with zeroes
  347. data[len] = 0; // need to make a C string again, with null terminator
  348. uint8_t temp[166];
  349. const char *command = (const char *) &data[5];
  350. char *reply = (char *) &temp[5];
  351. _cli.handleCommand(sender_timestamp, command, reply);
  352. int text_len = strlen(reply);
  353. if (text_len > 0) {
  354. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  355. if (timestamp == sender_timestamp) {
  356. // WORKAROUND: the two timestamps need to be different, in the CLI view
  357. timestamp++;
  358. }
  359. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  360. temp[4] = (TXT_TYPE_CLI_DATA << 2);
  361. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, from.id, secret, temp, 5 + text_len);
  362. if (reply) {
  363. if (from.out_path_len < 0) {
  364. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  365. } else {
  366. sendDirect(reply, from.out_path, from.out_path_len, CLI_REPLY_DELAY_MILLIS);
  367. }
  368. }
  369. }
  370. } else {
  371. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  372. }
  373. }
  374. }
  375. bool SensorMesh::onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) {
  376. int i = matching_peer_indexes[sender_idx];
  377. if (i < 0 || i >= num_contacts) {
  378. MESH_DEBUG_PRINTLN("onPeerPathRecv: Invalid sender idx: %d", i);
  379. return false;
  380. }
  381. ContactInfo& from = contacts[i];
  382. MESH_DEBUG_PRINTLN("PATH to contact, path_len=%d", (uint32_t) path_len);
  383. // NOTE: for this impl, we just replace the current 'out_path' regardless, whenever sender sends us a new out_path.
  384. // FUTURE: could store multiple out_paths per contact, and try to find which is the 'best'(?)
  385. memcpy(from.out_path, path, from.out_path_len = path_len); // store a copy of path, for sendDirect()
  386. from.last_activity = getRTCClock()->getCurrentTime();
  387. if (from.isAdmin()) {
  388. // only need to saveContacts() if this is an admin
  389. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  390. }
  391. // NOTE: no reciprocal path send!!
  392. return false;
  393. }
  394. SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  395. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  396. _cli(board, rtc, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4)
  397. {
  398. num_contacts = 0;
  399. next_local_advert = next_flood_advert = 0;
  400. dirty_contacts_expiry = 0;
  401. last_read_time = 0;
  402. // defaults
  403. memset(&_prefs, 0, sizeof(_prefs));
  404. _prefs.airtime_factor = 1.0; // one half
  405. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  406. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  407. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  408. _prefs.node_lat = ADVERT_LAT;
  409. _prefs.node_lon = ADVERT_LON;
  410. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  411. _prefs.freq = LORA_FREQ;
  412. _prefs.sf = LORA_SF;
  413. _prefs.bw = LORA_BW;
  414. _prefs.cr = LORA_CR;
  415. _prefs.tx_power_dbm = LORA_TX_POWER;
  416. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  417. _prefs.flood_advert_interval = 3; // 3 hours
  418. _prefs.disable_fwd = true;
  419. _prefs.flood_max = 64;
  420. _prefs.interference_threshold = 0; // disabled
  421. }
  422. void SensorMesh::begin(FILESYSTEM* fs) {
  423. mesh::Mesh::begin();
  424. _fs = fs;
  425. // load persisted prefs
  426. _cli.loadPrefs(_fs);
  427. loadContacts();
  428. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  429. radio_set_tx_power(_prefs.tx_power_dbm);
  430. updateAdvertTimer();
  431. updateFloodAdvertTimer();
  432. }
  433. bool SensorMesh::formatFileSystem() {
  434. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  435. return InternalFS.format();
  436. #elif defined(RP2040_PLATFORM)
  437. return LittleFS.format();
  438. #elif defined(ESP32)
  439. return SPIFFS.format();
  440. #else
  441. #error "need to implement file system erase"
  442. return false;
  443. #endif
  444. }
  445. void SensorMesh::sendSelfAdvertisement(int delay_millis) {
  446. mesh::Packet* pkt = createSelfAdvert();
  447. if (pkt) {
  448. sendFlood(pkt, delay_millis);
  449. } else {
  450. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  451. }
  452. }
  453. void SensorMesh::updateAdvertTimer() {
  454. if (_prefs.advert_interval > 0) { // schedule local advert timer
  455. next_local_advert = futureMillis( ((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  456. } else {
  457. next_local_advert = 0; // stop the timer
  458. }
  459. }
  460. void SensorMesh::updateFloodAdvertTimer() {
  461. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  462. next_flood_advert = futureMillis( ((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  463. } else {
  464. next_flood_advert = 0; // stop the timer
  465. }
  466. }
  467. void SensorMesh::setTxPower(uint8_t power_dbm) {
  468. radio_set_tx_power(power_dbm);
  469. }
  470. void SensorMesh::loop() {
  471. mesh::Mesh::loop();
  472. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  473. mesh::Packet* pkt = createSelfAdvert();
  474. if (pkt) sendFlood(pkt);
  475. updateFloodAdvertTimer(); // schedule next flood advert
  476. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  477. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  478. mesh::Packet* pkt = createSelfAdvert();
  479. if (pkt) sendZeroHop(pkt);
  480. updateAdvertTimer(); // schedule next local advert
  481. }
  482. uint32_t curr = getRTCClock()->getCurrentTime();
  483. if (curr >= last_read_time + SENSOR_READ_INTERVAL_SECS) {
  484. telemetry.reset();
  485. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  486. // query other sensors -- target specific
  487. sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions
  488. checkForAlerts();
  489. // save telemetry to time-series datastore
  490. File file = openAppend(_fs, "/s_data");
  491. if (file) {
  492. file.write((uint8_t *)&curr, 4); // start record with RTC timestamp
  493. uint8_t tlen = telemetry.getSize();
  494. file.write(&tlen, 1);
  495. file.write(telemetry.getBuffer(), tlen);
  496. uint8_t zero = 0;
  497. while (tlen < MAX_PACKET_PAYLOAD - 4) { // pad with zeroes, for fixed record length
  498. file.write(&zero, 1);
  499. tlen++;
  500. }
  501. file.close();
  502. }
  503. last_read_time = curr;
  504. }
  505. // is there are pending dirty contacts write needed?
  506. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  507. saveContacts();
  508. dirty_contacts_expiry = 0;
  509. }
  510. }