SensorMesh.cpp 20 KB

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