SensorMesh.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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 REQ_TYPE_GET_AVG_MIN_MAX 0x04
  45. #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
  46. #define CLI_REPLY_DELAY_MILLIS 1000
  47. #define LAZY_CONTACTS_WRITE_DELAY 5000
  48. #define ALERT_ACK_EXPIRY_MILLIS 6000 // wait 6 secs for ACKs to alert messages
  49. static File openAppend(FILESYSTEM* _fs, const char* fname) {
  50. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  51. return _fs->open(fname, FILE_O_WRITE);
  52. #elif defined(RP2040_PLATFORM)
  53. return _fs->open(fname, "a");
  54. #else
  55. return _fs->open(fname, "a", true);
  56. #endif
  57. }
  58. static File openWrite(FILESYSTEM* _fs, const char* filename) {
  59. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  60. _fs->remove(filename);
  61. return _fs->open(filename, FILE_O_WRITE);
  62. #elif defined(RP2040_PLATFORM)
  63. return _fs->open(filename, "w");
  64. #else
  65. return _fs->open(filename, "w", true);
  66. #endif
  67. }
  68. void SensorMesh::loadContacts() {
  69. num_contacts = 0;
  70. if (_fs->exists("/s_contacts")) {
  71. #if defined(RP2040_PLATFORM)
  72. File file = _fs->open("/s_contacts", "r");
  73. #else
  74. File file = _fs->open("/s_contacts");
  75. #endif
  76. if (file) {
  77. bool full = false;
  78. while (!full) {
  79. ContactInfo c;
  80. uint8_t pub_key[32];
  81. uint8_t unused[5];
  82. bool success = (file.read(pub_key, 32) == 32);
  83. success = success && (file.read((uint8_t *) &c.permissions, 2) == 2);
  84. success = success && (file.read(unused, 5) == 5);
  85. success = success && (file.read((uint8_t *)&c.out_path_len, 1) == 1);
  86. success = success && (file.read(c.out_path, 64) == 64);
  87. success = success && (file.read(c.shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE);
  88. c.last_timestamp = 0; // transient
  89. c.last_activity = 0;
  90. if (!success) break; // EOF
  91. c.id = mesh::Identity(pub_key);
  92. if (num_contacts < MAX_CONTACTS) {
  93. contacts[num_contacts++] = c;
  94. } else {
  95. full = true;
  96. }
  97. }
  98. file.close();
  99. }
  100. }
  101. }
  102. void SensorMesh::saveContacts() {
  103. File file = openWrite(_fs, "/s_contacts");
  104. if (file) {
  105. uint8_t unused[5];
  106. memset(unused, 0, sizeof(unused));
  107. for (int i = 0; i < num_contacts; i++) {
  108. auto c = &contacts[i];
  109. if (c->permissions == 0) continue; // skip deleted entries
  110. bool success = (file.write(c->id.pub_key, 32) == 32);
  111. success = success && (file.write((uint8_t *) &c->permissions, 2) == 2);
  112. success = success && (file.write(unused, 5) == 5);
  113. success = success && (file.write((uint8_t *)&c->out_path_len, 1) == 1);
  114. success = success && (file.write(c->out_path, 64) == 64);
  115. success = success && (file.write(c->shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE);
  116. if (!success) break; // write failed
  117. }
  118. file.close();
  119. }
  120. }
  121. static uint8_t getDataSize(uint8_t type) {
  122. switch (type) {
  123. case LPP_GPS:
  124. return 9;
  125. case LPP_POLYLINE:
  126. return 8; // TODO: this is MINIMIUM
  127. case LPP_GYROMETER:
  128. case LPP_ACCELEROMETER:
  129. return 6;
  130. case LPP_GENERIC_SENSOR:
  131. case LPP_FREQUENCY:
  132. case LPP_DISTANCE:
  133. case LPP_ENERGY:
  134. case LPP_UNIXTIME:
  135. return 4;
  136. case LPP_COLOUR:
  137. return 3;
  138. case LPP_ANALOG_INPUT:
  139. case LPP_ANALOG_OUTPUT:
  140. case LPP_LUMINOSITY:
  141. case LPP_TEMPERATURE:
  142. case LPP_CONCENTRATION:
  143. case LPP_BAROMETRIC_PRESSURE:
  144. case LPP_RELATIVE_HUMIDITY:
  145. case LPP_ALTITUDE:
  146. case LPP_VOLTAGE:
  147. case LPP_CURRENT:
  148. case LPP_DIRECTION:
  149. case LPP_POWER:
  150. return 2;
  151. }
  152. return 1;
  153. }
  154. static uint32_t getMultiplier(uint8_t type) {
  155. switch (type) {
  156. case LPP_CURRENT:
  157. case LPP_DISTANCE:
  158. case LPP_ENERGY:
  159. return 1000;
  160. case LPP_VOLTAGE:
  161. case LPP_ANALOG_INPUT:
  162. case LPP_ANALOG_OUTPUT:
  163. return 100;
  164. case LPP_TEMPERATURE:
  165. case LPP_BAROMETRIC_PRESSURE:
  166. case LPP_RELATIVE_HUMIDITY:
  167. return 10;
  168. }
  169. return 1;
  170. }
  171. static bool isSigned(uint8_t type) {
  172. return type == LPP_ALTITUDE || type == LPP_TEMPERATURE || type == LPP_GYROMETER ||
  173. type == LPP_ANALOG_INPUT || type == LPP_ANALOG_OUTPUT || type == LPP_GPS || type == LPP_ACCELEROMETER;
  174. }
  175. static float getFloat(const uint8_t * buffer, uint8_t size, uint32_t multiplier, bool is_signed) {
  176. uint32_t value = 0;
  177. for (uint8_t i = 0; i < size; i++) {
  178. value = (value << 8) + buffer[i];
  179. }
  180. int sign = 1;
  181. if (is_signed) {
  182. uint32_t bit = 1ul << ((size * 8) - 1);
  183. if ((value & bit) == bit) {
  184. value = (bit << 1) - value;
  185. sign = -1;
  186. }
  187. }
  188. return sign * ((float) value / multiplier);
  189. }
  190. static uint8_t putFloat(uint8_t * dest, float value, uint8_t size, uint32_t multiplier, bool is_signed) {
  191. // check sign
  192. bool sign = value < 0;
  193. if (sign) value = -value;
  194. // get value to store
  195. uint32_t v = value * multiplier;
  196. // format an uint32_t as if it was an int32_t
  197. if (is_signed & sign) {
  198. uint32_t mask = (1 << (size * 8)) - 1;
  199. v = v & mask;
  200. if (sign) v = mask - v + 1;
  201. }
  202. // add bytes (MSB first)
  203. for (uint8_t i=1; i<=size; i++) {
  204. dest[size - i] = (v & 0xFF);
  205. v >>= 8;
  206. }
  207. return size;
  208. }
  209. uint8_t SensorMesh::handleRequest(uint16_t perms, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) {
  210. memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
  211. if (req_type == REQ_TYPE_GET_TELEMETRY_DATA && (perms & PERM_GET_TELEMETRY) != 0) {
  212. telemetry.reset();
  213. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  214. // query other sensors -- target specific
  215. sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions for admin or guest
  216. uint8_t tlen = telemetry.getSize();
  217. memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
  218. return 4 + tlen; // reply_len
  219. }
  220. if (req_type == REQ_TYPE_GET_AVG_MIN_MAX && (perms & PERM_GET_MIN_MAX_AVG) != 0) {
  221. uint32_t start_secs_ago, end_secs_ago;
  222. memcpy(&start_secs_ago, &payload[0], 4);
  223. memcpy(&end_secs_ago, &payload[4], 4);
  224. uint8_t res1 = payload[8]; // reserved for future (extra query params)
  225. uint8_t res2 = payload[8];
  226. MinMaxAvg data[8];
  227. int n;
  228. if (res1 == 0 && res2 == 0) {
  229. n = querySeriesData(start_secs_ago, end_secs_ago, data, 8);
  230. } else {
  231. n = 0;
  232. }
  233. uint8_t ofs = 4;
  234. {
  235. uint32_t now = getRTCClock()->getCurrentTime();
  236. memcpy(&reply_data[ofs], &now, 4); ofs += 4;
  237. }
  238. for (int i = 0; i < n; i++) {
  239. auto d = &data[i];
  240. reply_data[ofs++] = d->_channel;
  241. reply_data[ofs++] = d->_lpp_type;
  242. uint8_t sz = getDataSize(d->_lpp_type);
  243. uint32_t mult = getMultiplier(d->_lpp_type);
  244. bool is_signed = isSigned(d->_lpp_type);
  245. ofs += putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed);
  246. ofs += putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed);
  247. ofs += putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed);
  248. }
  249. return ofs;
  250. }
  251. return 0; // unknown command
  252. }
  253. mesh::Packet* SensorMesh::createSelfAdvert() {
  254. uint8_t app_data[MAX_ADVERT_DATA_SIZE];
  255. uint8_t app_data_len;
  256. {
  257. AdvertDataBuilder builder(ADV_TYPE_SENSOR, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  258. app_data_len = builder.encodeTo(app_data);
  259. }
  260. return createAdvert(self_id, app_data, app_data_len);
  261. }
  262. ContactInfo* SensorMesh::putContact(const mesh::Identity& id) {
  263. uint32_t min_time = 0xFFFFFFFF;
  264. ContactInfo* oldest = &contacts[MAX_CONTACTS - 1];
  265. for (int i = 0; i < num_contacts; i++) {
  266. if (id.matches(contacts[i].id)) return &contacts[i]; // already known
  267. if (!contacts[i].isAdmin() && contacts[i].last_activity < min_time) {
  268. oldest = &contacts[i];
  269. min_time = oldest->last_activity;
  270. }
  271. }
  272. ContactInfo* c;
  273. if (num_contacts < MAX_CONTACTS) {
  274. c = &contacts[num_contacts++];
  275. } else {
  276. c = oldest; // evict least active contact
  277. }
  278. memset(c, 0, sizeof(*c));
  279. c->id = id;
  280. c->out_path_len = -1; // initially out_path is unknown
  281. return c;
  282. }
  283. void SensorMesh::applyContactPermissions(const uint8_t* pubkey, uint16_t perms) {
  284. mesh::Identity id(pubkey);
  285. auto c = putContact(id);
  286. if (perms == 0) { // no permissions, remove from contacts
  287. memset(c, 0, sizeof(*c));
  288. } else {
  289. c->permissions = perms; // update their permissions
  290. self_id.calcSharedSecret(c->shared_secret, pubkey);
  291. }
  292. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger saveContacts()
  293. }
  294. void SensorMesh::sendAlert(ContactInfo* c, Trigger* t) {
  295. int text_len = strlen(t->text);
  296. uint8_t data[MAX_PACKET_PAYLOAD];
  297. memcpy(data, &t->timestamp, 4);
  298. data[4] = (TXT_TYPE_PLAIN << 2) | t->attempt; // attempt and flags
  299. memcpy(&data[5], t->text, text_len);
  300. // calc expected ACK reply
  301. mesh::Utils::sha256((uint8_t *)&t->expected_acks[t->attempt], 4, data, 5 + text_len, self_id.pub_key, PUB_KEY_SIZE);
  302. t->attempt++;
  303. auto pkt = createDatagram(PAYLOAD_TYPE_TXT_MSG, c->id, c->shared_secret, data, 5 + text_len);
  304. if (pkt) {
  305. if (c->out_path_len >= 0) { // we have an out_path, so send DIRECT
  306. sendDirect(pkt, c->out_path, c->out_path_len);
  307. } else {
  308. sendFlood(pkt);
  309. }
  310. }
  311. t->send_expiry = futureMillis(ALERT_ACK_EXPIRY_MILLIS);
  312. }
  313. void SensorMesh::alertIf(bool condition, Trigger& t, AlertPriority pri, const char* text) {
  314. if (condition) {
  315. if (!t.isTriggered() && num_alert_tasks < MAX_CONCURRENT_ALERTS) {
  316. StrHelper::strncpy(t.text, text, sizeof(t.text));
  317. t.pri = pri;
  318. t.send_expiry = 0; // signal that initial send is needed
  319. t.attempt = 4;
  320. t.curr_contact_idx = -1; // start iterating thru contacts[]
  321. alert_tasks[num_alert_tasks++] = &t; // add to queue
  322. }
  323. } else {
  324. if (t.isTriggered()) {
  325. t.text[0] = 0;
  326. // remove 't' from alert queue
  327. int i = 0;
  328. while (i < num_alert_tasks && alert_tasks[i] != &t) i++;
  329. if (i < num_alert_tasks) { // found, now delete from array
  330. num_alert_tasks--;
  331. while (i < num_alert_tasks) {
  332. alert_tasks[i] = alert_tasks[i + 1];
  333. i++;
  334. }
  335. }
  336. }
  337. }
  338. }
  339. float SensorMesh::getAirtimeBudgetFactor() const {
  340. return _prefs.airtime_factor;
  341. }
  342. bool SensorMesh::allowPacketForward(const mesh::Packet* packet) {
  343. if (_prefs.disable_fwd) return false;
  344. if (packet->isRouteFlood() && packet->path_len >= _prefs.flood_max) return false;
  345. return true;
  346. }
  347. int SensorMesh::calcRxDelay(float score, uint32_t air_time) const {
  348. if (_prefs.rx_delay_base <= 0.0f) return 0;
  349. return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  350. }
  351. uint32_t SensorMesh::getRetransmitDelay(const mesh::Packet* packet) {
  352. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
  353. return getRNG()->nextInt(0, 6)*t;
  354. }
  355. uint32_t SensorMesh::getDirectRetransmitDelay(const mesh::Packet* packet) {
  356. uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
  357. return getRNG()->nextInt(0, 6)*t;
  358. }
  359. int SensorMesh::getInterferenceThreshold() const {
  360. return _prefs.interference_threshold;
  361. }
  362. int SensorMesh::getAGCResetInterval() const {
  363. return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds
  364. }
  365. uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data) {
  366. if (strcmp((char *) data, _prefs.password) != 0) { // check for valid password
  367. #if MESH_DEBUG
  368. MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]);
  369. #endif
  370. return 0;
  371. }
  372. auto client = putContact(sender); // add to contacts (if not already known)
  373. if (sender_timestamp <= client->last_timestamp) {
  374. MESH_DEBUG_PRINTLN("Possible login replay attack!");
  375. return 0; // FATAL: client table is full -OR- replay attack
  376. }
  377. MESH_DEBUG_PRINTLN("Login success!");
  378. client->last_timestamp = sender_timestamp;
  379. client->last_activity = getRTCClock()->getCurrentTime();
  380. client->permissions = PERM_IS_ADMIN | PERM_RECV_ALERTS_HI | PERM_RECV_ALERTS_LO; // initially opt-in to receive alerts (can opt out)
  381. memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
  382. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  383. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  384. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  385. reply_data[4] = RESP_SERVER_LOGIN_OK;
  386. reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16)
  387. reply_data[6] = 1; // 1 = is admin
  388. reply_data[7] = 0; // FUTURE: reserved
  389. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  390. return 12; // reply length
  391. }
  392. void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
  393. while (*command == ' ') command++; // skip leading spaces
  394. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  395. memcpy(reply, command, 3); // reflect the prefix back
  396. reply += 3;
  397. command += 3;
  398. }
  399. // handle sensor-specific CLI commands
  400. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int16}
  401. char* hex = &command[8];
  402. char* sp = strchr(hex, ' '); // look for separator char
  403. if (sp == NULL || sp - hex != PUB_KEY_SIZE*2) {
  404. strcpy(reply, "Err - bad pubkey len");
  405. } else {
  406. *sp++ = 0; // replace space with null terminator
  407. uint8_t pubkey[PUB_KEY_SIZE];
  408. if (mesh::Utils::fromHex(pubkey, PUB_KEY_SIZE, hex)) {
  409. uint16_t perms = atoi(sp);
  410. applyContactPermissions(pubkey, perms);
  411. strcpy(reply, "OK");
  412. } else {
  413. strcpy(reply, "Err - bad pubkey");
  414. }
  415. }
  416. } else if (sender_timestamp == 0 && strcmp(command, "getperm") == 0) {
  417. Serial.println("Permissions:");
  418. for (int i = 0; i < num_contacts; i++) {
  419. auto c = &contacts[i];
  420. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  421. Serial.printf(" %04X\n", c->permissions);
  422. }
  423. reply[0] = 0;
  424. } else {
  425. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  426. }
  427. }
  428. void SensorMesh::onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) {
  429. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
  430. uint32_t timestamp;
  431. memcpy(&timestamp, data, 4);
  432. data[len] = 0; // ensure null terminator
  433. uint8_t reply_len = handleLoginReq(sender, secret, timestamp, &data[4]);
  434. if (reply_len == 0) return; // invalid request
  435. if (packet->isRouteFlood()) {
  436. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  437. mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
  438. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  439. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  440. } else {
  441. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  442. if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY);
  443. }
  444. }
  445. }
  446. int SensorMesh::searchPeersByHash(const uint8_t* hash) {
  447. int n = 0;
  448. for (int i = 0; i < num_contacts && n < MAX_SEARCH_RESULTS; i++) {
  449. if (contacts[i].id.isHashMatch(hash)) {
  450. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  451. }
  452. }
  453. return n;
  454. }
  455. void SensorMesh::getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) {
  456. int i = matching_peer_indexes[peer_idx];
  457. if (i >= 0 && i < num_contacts) {
  458. // lookup pre-calculated shared_secret
  459. memcpy(dest_secret, contacts[i].shared_secret, PUB_KEY_SIZE);
  460. } else {
  461. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  462. }
  463. }
  464. void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) {
  465. int i = matching_peer_indexes[sender_idx];
  466. if (i < 0 || i >= num_contacts) {
  467. MESH_DEBUG_PRINTLN("onPeerDataRecv: Invalid sender idx: %d", i);
  468. return;
  469. }
  470. ContactInfo& from = contacts[i];
  471. if (type == PAYLOAD_TYPE_REQ) { // request (from a known contact)
  472. uint32_t timestamp;
  473. memcpy(&timestamp, data, 4);
  474. if (timestamp > from.last_timestamp) { // prevent replay attacks
  475. uint8_t reply_len = handleRequest(from.isAdmin() ? 0xFFFF : from.permissions, timestamp, data[4], &data[5], len - 5);
  476. if (reply_len == 0) return; // invalid command
  477. from.last_timestamp = timestamp;
  478. from.last_activity = getRTCClock()->getCurrentTime();
  479. if (packet->isRouteFlood()) {
  480. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  481. mesh::Packet* path = createPathReturn(from.id, secret, packet->path, packet->path_len,
  482. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  483. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  484. } else {
  485. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, from.id, secret, reply_data, reply_len);
  486. if (reply) {
  487. if (from.out_path_len >= 0) { // we have an out_path, so send DIRECT
  488. sendDirect(reply, from.out_path, from.out_path_len, SERVER_RESPONSE_DELAY);
  489. } else {
  490. sendFlood(reply, SERVER_RESPONSE_DELAY);
  491. }
  492. }
  493. }
  494. } else {
  495. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  496. }
  497. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && from.isAdmin()) { // a CLI command
  498. uint32_t sender_timestamp;
  499. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  500. uint flags = (data[4] >> 2); // message attempt number, and other flags
  501. if (!(flags == TXT_TYPE_CLI_DATA)) {
  502. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  503. } else if (sender_timestamp > from.last_timestamp) { // prevent replay attacks
  504. from.last_timestamp = sender_timestamp;
  505. from.last_activity = getRTCClock()->getCurrentTime();
  506. // len can be > original length, but 'text' will be padded with zeroes
  507. data[len] = 0; // need to make a C string again, with null terminator
  508. uint8_t temp[166];
  509. char *command = (char *) &data[5];
  510. char *reply = (char *) &temp[5];
  511. handleCommand(sender_timestamp, command, reply);
  512. int text_len = strlen(reply);
  513. if (text_len > 0) {
  514. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  515. if (timestamp == sender_timestamp) {
  516. // WORKAROUND: the two timestamps need to be different, in the CLI view
  517. timestamp++;
  518. }
  519. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  520. temp[4] = (TXT_TYPE_CLI_DATA << 2);
  521. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, from.id, secret, temp, 5 + text_len);
  522. if (reply) {
  523. if (from.out_path_len < 0) {
  524. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  525. } else {
  526. sendDirect(reply, from.out_path, from.out_path_len, CLI_REPLY_DELAY_MILLIS);
  527. }
  528. }
  529. }
  530. } else {
  531. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  532. }
  533. }
  534. }
  535. 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) {
  536. int i = matching_peer_indexes[sender_idx];
  537. if (i < 0 || i >= num_contacts) {
  538. MESH_DEBUG_PRINTLN("onPeerPathRecv: Invalid sender idx: %d", i);
  539. return false;
  540. }
  541. ContactInfo& from = contacts[i];
  542. MESH_DEBUG_PRINTLN("PATH to contact, path_len=%d", (uint32_t) path_len);
  543. // NOTE: for this impl, we just replace the current 'out_path' regardless, whenever sender sends us a new out_path.
  544. // FUTURE: could store multiple out_paths per contact, and try to find which is the 'best'(?)
  545. memcpy(from.out_path, path, from.out_path_len = path_len); // store a copy of path, for sendDirect()
  546. from.last_activity = getRTCClock()->getCurrentTime();
  547. // REVISIT: maybe make ALL out_paths non-persisted to minimise flash writes??
  548. if (from.isAdmin()) {
  549. // only do saveContacts() (of this out_path change) if this is an admin
  550. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  551. }
  552. // NOTE: no reciprocal path send!!
  553. return false;
  554. }
  555. void SensorMesh::onAckRecv(mesh::Packet* packet, uint32_t ack_crc) {
  556. if (num_alert_tasks > 0) {
  557. auto t = alert_tasks[0]; // check current alert task
  558. for (int i = 0; i < t->attempt; i++) {
  559. if (ack_crc == t->expected_acks[i]) { // matching ACK!
  560. t->attempt = 4; // signal to move to next contact
  561. t->send_expiry = 0;
  562. packet->markDoNotRetransmit(); // ACK was for this node, so don't retransmit
  563. return;
  564. }
  565. }
  566. }
  567. }
  568. SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  569. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  570. _cli(board, rtc, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4)
  571. {
  572. num_contacts = 0;
  573. next_local_advert = next_flood_advert = 0;
  574. dirty_contacts_expiry = 0;
  575. last_read_time = 0;
  576. num_alert_tasks = 0;
  577. // defaults
  578. memset(&_prefs, 0, sizeof(_prefs));
  579. _prefs.airtime_factor = 1.0; // one half
  580. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  581. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  582. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  583. _prefs.node_lat = ADVERT_LAT;
  584. _prefs.node_lon = ADVERT_LON;
  585. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  586. _prefs.freq = LORA_FREQ;
  587. _prefs.sf = LORA_SF;
  588. _prefs.bw = LORA_BW;
  589. _prefs.cr = LORA_CR;
  590. _prefs.tx_power_dbm = LORA_TX_POWER;
  591. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  592. _prefs.flood_advert_interval = 0; // disabled
  593. _prefs.disable_fwd = true;
  594. _prefs.flood_max = 64;
  595. _prefs.interference_threshold = 0; // disabled
  596. }
  597. void SensorMesh::begin(FILESYSTEM* fs) {
  598. mesh::Mesh::begin();
  599. _fs = fs;
  600. // load persisted prefs
  601. _cli.loadPrefs(_fs);
  602. loadContacts();
  603. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  604. radio_set_tx_power(_prefs.tx_power_dbm);
  605. updateAdvertTimer();
  606. updateFloodAdvertTimer();
  607. }
  608. bool SensorMesh::formatFileSystem() {
  609. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  610. return InternalFS.format();
  611. #elif defined(RP2040_PLATFORM)
  612. return LittleFS.format();
  613. #elif defined(ESP32)
  614. return SPIFFS.format();
  615. #else
  616. #error "need to implement file system erase"
  617. return false;
  618. #endif
  619. }
  620. void SensorMesh::sendSelfAdvertisement(int delay_millis) {
  621. mesh::Packet* pkt = createSelfAdvert();
  622. if (pkt) {
  623. sendFlood(pkt, delay_millis);
  624. } else {
  625. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  626. }
  627. }
  628. void SensorMesh::updateAdvertTimer() {
  629. if (_prefs.advert_interval > 0) { // schedule local advert timer
  630. next_local_advert = futureMillis( ((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  631. } else {
  632. next_local_advert = 0; // stop the timer
  633. }
  634. }
  635. void SensorMesh::updateFloodAdvertTimer() {
  636. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  637. next_flood_advert = futureMillis( ((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  638. } else {
  639. next_flood_advert = 0; // stop the timer
  640. }
  641. }
  642. void SensorMesh::setTxPower(uint8_t power_dbm) {
  643. radio_set_tx_power(power_dbm);
  644. }
  645. float SensorMesh::getTelemValue(uint8_t channel, uint8_t type) {
  646. auto buf = telemetry.getBuffer();
  647. uint8_t size = telemetry.getSize();
  648. uint8_t i = 0;
  649. while (i + 2 < size) {
  650. // Get channel #
  651. uint8_t ch = buf[i++];
  652. // Get data type
  653. uint8_t t = buf[i++];
  654. uint8_t sz = getDataSize(t);
  655. if (ch == channel && t == type) {
  656. return getFloat(&buf[i], sz, getMultiplier(t), isSigned(t));
  657. }
  658. i += sz; // skip
  659. }
  660. return 0.0f; // not found
  661. }
  662. bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) {
  663. if (channel == TELEM_CHANNEL_SELF) {
  664. lat = sensors.node_lat;
  665. lon = sensors.node_lon;
  666. alt = sensors.node_altitude;
  667. return true;
  668. }
  669. // REVISIT: custom GPS channels??
  670. return false;
  671. }
  672. void SensorMesh::loop() {
  673. mesh::Mesh::loop();
  674. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  675. mesh::Packet* pkt = createSelfAdvert();
  676. if (pkt) sendFlood(pkt);
  677. updateFloodAdvertTimer(); // schedule next flood advert
  678. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  679. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  680. mesh::Packet* pkt = createSelfAdvert();
  681. if (pkt) sendZeroHop(pkt);
  682. updateAdvertTimer(); // schedule next local advert
  683. }
  684. uint32_t curr = getRTCClock()->getCurrentTime();
  685. if (curr >= last_read_time + SENSOR_READ_INTERVAL_SECS) {
  686. telemetry.reset();
  687. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  688. // query other sensors -- target specific
  689. sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions
  690. onSensorDataRead();
  691. last_read_time = curr;
  692. }
  693. // check the alert send queue
  694. if (num_alert_tasks > 0) {
  695. auto t = alert_tasks[0]; // process head of queue
  696. if (millisHasNowPassed(t->send_expiry)) { // next send needed?
  697. if (t->attempt >= 4) { // max attempts reached, try next contact
  698. t->curr_contact_idx++;
  699. if (t->curr_contact_idx >= num_contacts) { // no more contacts to try?
  700. num_alert_tasks--; // remove t from queue
  701. for (int i = 0; i < num_alert_tasks; i++) {
  702. alert_tasks[i] = alert_tasks[i + 1];
  703. }
  704. } else {
  705. auto c = &contacts[t->curr_contact_idx];
  706. uint16_t pri_mask = (t->pri == HIGH_PRI_ALERT) ? PERM_RECV_ALERTS_HI : PERM_RECV_ALERTS_LO;
  707. if (c->permissions & pri_mask) { // contact wants alert
  708. // reset attempts
  709. t->attempt = (t->pri == LOW_PRI_ALERT) ? 3 : 0; // Low pri alerts, start at attempt #3 (ie. only make ONE attempt)
  710. t->timestamp = getRTCClock()->getCurrentTimeUnique(); // need unique timestamp per contact
  711. sendAlert(c, t); // NOTE: modifies attempt, expected_acks[] and send_expiry
  712. } else {
  713. // next contact tested in next ::loop()
  714. }
  715. }
  716. } else if (t->curr_contact_idx < num_contacts) {
  717. auto c = &contacts[t->curr_contact_idx]; // send next attempt
  718. sendAlert(c, t); // NOTE: modifies attempt, expected_acks[] and send_expiry
  719. } else {
  720. // contact list has likely been modified while waiting for alert ACK, cancel this task
  721. t->attempt = 4; // next ::loop() will remove t from queue
  722. }
  723. }
  724. }
  725. // is there are pending dirty contacts write needed?
  726. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  727. saveContacts();
  728. dirty_contacts_expiry = 0;
  729. }
  730. }