SensorMesh.cpp 32 KB

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