SensorMesh.cpp 31 KB

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