SensorMesh.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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::sendAckTo(const ContactInfo& dest, uint32_t ack_hash) {
  539. if (dest.out_path_len < 0) {
  540. mesh::Packet* ack = createAck(ack_hash);
  541. if (ack) sendFlood(ack, TXT_ACK_DELAY);
  542. } else {
  543. uint32_t d = TXT_ACK_DELAY;
  544. if (getExtraAckTransmitCount() > 0) {
  545. mesh::Packet* a1 = createMultiAck(ack_hash, 1);
  546. if (a1) sendDirect(a1, dest.out_path, dest.out_path_len, d);
  547. d += 300;
  548. }
  549. mesh::Packet* a2 = createAck(ack_hash);
  550. if (a2) sendDirect(a2, dest.out_path, dest.out_path_len, d);
  551. }
  552. }
  553. void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) {
  554. int i = matching_peer_indexes[sender_idx];
  555. if (i < 0 || i >= num_contacts) {
  556. MESH_DEBUG_PRINTLN("onPeerDataRecv: Invalid sender idx: %d", i);
  557. return;
  558. }
  559. ContactInfo& from = contacts[i];
  560. if (type == PAYLOAD_TYPE_REQ) { // request (from a known contact)
  561. uint32_t timestamp;
  562. memcpy(&timestamp, data, 4);
  563. if (timestamp > from.last_timestamp) { // prevent replay attacks
  564. uint8_t reply_len = handleRequest(from.isAdmin() ? 0xFF : from.permissions, timestamp, data[4], &data[5], len - 5);
  565. if (reply_len == 0) return; // invalid command
  566. from.last_timestamp = timestamp;
  567. from.last_activity = getRTCClock()->getCurrentTime();
  568. if (packet->isRouteFlood()) {
  569. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  570. mesh::Packet* path = createPathReturn(from.id, secret, packet->path, packet->path_len,
  571. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  572. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  573. } else {
  574. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, from.id, secret, reply_data, reply_len);
  575. if (reply) {
  576. if (from.out_path_len >= 0) { // we have an out_path, so send DIRECT
  577. sendDirect(reply, from.out_path, from.out_path_len, SERVER_RESPONSE_DELAY);
  578. } else {
  579. sendFlood(reply, SERVER_RESPONSE_DELAY);
  580. }
  581. }
  582. }
  583. } else {
  584. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  585. }
  586. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && from.isAdmin()) { // a CLI command
  587. uint32_t sender_timestamp;
  588. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  589. uint flags = (data[4] >> 2); // message attempt number, and other flags
  590. if (sender_timestamp > from.last_timestamp) { // prevent replay attacks
  591. if (flags == TXT_TYPE_PLAIN) {
  592. bool handled = handleIncomingMsg(from, sender_timestamp, &data[5], flags, len - 5);
  593. if (handled) { // if msg was handled then send an ack
  594. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
  595. mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 5 + strlen((char *)&data[5]), from.id.pub_key, PUB_KEY_SIZE);
  596. if (packet->isRouteFlood()) {
  597. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the ACK
  598. mesh::Packet* path = createPathReturn(from.id, secret, packet->path, packet->path_len,
  599. PAYLOAD_TYPE_ACK, (uint8_t *) &ack_hash, 4);
  600. if (path) sendFlood(path, TXT_ACK_DELAY);
  601. } else {
  602. sendAckTo(from, ack_hash);
  603. }
  604. }
  605. } else if (flags == TXT_TYPE_CLI_DATA) {
  606. from.last_timestamp = sender_timestamp;
  607. from.last_activity = getRTCClock()->getCurrentTime();
  608. // len can be > original length, but 'text' will be padded with zeroes
  609. data[len] = 0; // need to make a C string again, with null terminator
  610. uint8_t temp[166];
  611. char *command = (char *) &data[5];
  612. char *reply = (char *) &temp[5];
  613. handleCommand(sender_timestamp, command, reply);
  614. int text_len = strlen(reply);
  615. if (text_len > 0) {
  616. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  617. if (timestamp == sender_timestamp) {
  618. // WORKAROUND: the two timestamps need to be different, in the CLI view
  619. timestamp++;
  620. }
  621. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  622. temp[4] = (TXT_TYPE_CLI_DATA << 2);
  623. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, from.id, secret, temp, 5 + text_len);
  624. if (reply) {
  625. if (from.out_path_len < 0) {
  626. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  627. } else {
  628. sendDirect(reply, from.out_path, from.out_path_len, CLI_REPLY_DELAY_MILLIS);
  629. }
  630. }
  631. }
  632. } else {
  633. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  634. }
  635. } else {
  636. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  637. }
  638. }
  639. }
  640. bool SensorMesh::handleIncomingMsg(ContactInfo& from, uint32_t timestamp, uint8_t* data, uint flags, size_t len) {
  641. MESH_DEBUG_PRINT("handleIncomingMsg: unhandled msg from ");
  642. #ifdef MESH_DEBUG
  643. mesh::Utils::printHex(Serial, from.id.pub_key, PUB_KEY_SIZE);
  644. Serial.printf(": %s\n", data);
  645. #endif
  646. return false;
  647. }
  648. 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) {
  649. int i = matching_peer_indexes[sender_idx];
  650. if (i < 0 || i >= num_contacts) {
  651. MESH_DEBUG_PRINTLN("onPeerPathRecv: Invalid sender idx: %d", i);
  652. return false;
  653. }
  654. ContactInfo& from = contacts[i];
  655. MESH_DEBUG_PRINTLN("PATH to contact, path_len=%d", (uint32_t) path_len);
  656. // NOTE: for this impl, we just replace the current 'out_path' regardless, whenever sender sends us a new out_path.
  657. // FUTURE: could store multiple out_paths per contact, and try to find which is the 'best'(?)
  658. memcpy(from.out_path, path, from.out_path_len = path_len); // store a copy of path, for sendDirect()
  659. from.last_activity = getRTCClock()->getCurrentTime();
  660. // REVISIT: maybe make ALL out_paths non-persisted to minimise flash writes??
  661. if (from.isAdmin()) {
  662. // only do saveContacts() (of this out_path change) if this is an admin
  663. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  664. }
  665. // NOTE: no reciprocal path send!!
  666. return false;
  667. }
  668. void SensorMesh::onAckRecv(mesh::Packet* packet, uint32_t ack_crc) {
  669. if (num_alert_tasks > 0) {
  670. auto t = alert_tasks[0]; // check current alert task
  671. for (int i = 0; i < t->attempt; i++) {
  672. if (ack_crc == t->expected_acks[i]) { // matching ACK!
  673. t->attempt = 4; // signal to move to next contact
  674. t->send_expiry = 0;
  675. packet->markDoNotRetransmit(); // ACK was for this node, so don't retransmit
  676. return;
  677. }
  678. }
  679. }
  680. }
  681. SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  682. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  683. _cli(board, rtc, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4)
  684. {
  685. num_contacts = 0;
  686. next_local_advert = next_flood_advert = 0;
  687. dirty_contacts_expiry = 0;
  688. last_read_time = 0;
  689. num_alert_tasks = 0;
  690. set_radio_at = revert_radio_at = 0;
  691. // defaults
  692. memset(&_prefs, 0, sizeof(_prefs));
  693. _prefs.airtime_factor = 1.0; // one half
  694. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  695. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  696. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  697. _prefs.node_lat = ADVERT_LAT;
  698. _prefs.node_lon = ADVERT_LON;
  699. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  700. _prefs.freq = LORA_FREQ;
  701. _prefs.sf = LORA_SF;
  702. _prefs.bw = LORA_BW;
  703. _prefs.cr = LORA_CR;
  704. _prefs.tx_power_dbm = LORA_TX_POWER;
  705. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  706. _prefs.flood_advert_interval = 0; // disabled
  707. _prefs.disable_fwd = true;
  708. _prefs.flood_max = 64;
  709. _prefs.interference_threshold = 0; // disabled
  710. }
  711. void SensorMesh::begin(FILESYSTEM* fs) {
  712. mesh::Mesh::begin();
  713. _fs = fs;
  714. // load persisted prefs
  715. _cli.loadPrefs(_fs);
  716. loadContacts();
  717. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  718. radio_set_tx_power(_prefs.tx_power_dbm);
  719. updateAdvertTimer();
  720. updateFloodAdvertTimer();
  721. }
  722. bool SensorMesh::formatFileSystem() {
  723. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  724. return InternalFS.format();
  725. #elif defined(RP2040_PLATFORM)
  726. return LittleFS.format();
  727. #elif defined(ESP32)
  728. return SPIFFS.format();
  729. #else
  730. #error "need to implement file system erase"
  731. return false;
  732. #endif
  733. }
  734. void SensorMesh::saveIdentity(const mesh::LocalIdentity& new_id) {
  735. self_id = new_id;
  736. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  737. IdentityStore store(*_fs, "");
  738. #elif defined(ESP32)
  739. IdentityStore store(*_fs, "/identity");
  740. #elif defined(RP2040_PLATFORM)
  741. IdentityStore store(*_fs, "/identity");
  742. #else
  743. #error "need to define saveIdentity()"
  744. #endif
  745. store.save("_main", self_id);
  746. }
  747. void SensorMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  748. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  749. pending_freq = freq;
  750. pending_bw = bw;
  751. pending_sf = sf;
  752. pending_cr = cr;
  753. revert_radio_at = futureMillis(2000 + timeout_mins*60*1000); // schedule when to revert radio params
  754. }
  755. void SensorMesh::sendSelfAdvertisement(int delay_millis) {
  756. mesh::Packet* pkt = createSelfAdvert();
  757. if (pkt) {
  758. sendFlood(pkt, delay_millis);
  759. } else {
  760. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  761. }
  762. }
  763. void SensorMesh::updateAdvertTimer() {
  764. if (_prefs.advert_interval > 0) { // schedule local advert timer
  765. next_local_advert = futureMillis( ((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  766. } else {
  767. next_local_advert = 0; // stop the timer
  768. }
  769. }
  770. void SensorMesh::updateFloodAdvertTimer() {
  771. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  772. next_flood_advert = futureMillis( ((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  773. } else {
  774. next_flood_advert = 0; // stop the timer
  775. }
  776. }
  777. void SensorMesh::setTxPower(uint8_t power_dbm) {
  778. radio_set_tx_power(power_dbm);
  779. }
  780. float SensorMesh::getTelemValue(uint8_t channel, uint8_t type) {
  781. auto buf = telemetry.getBuffer();
  782. uint8_t size = telemetry.getSize();
  783. uint8_t i = 0;
  784. while (i + 2 < size) {
  785. // Get channel #
  786. uint8_t ch = buf[i++];
  787. // Get data type
  788. uint8_t t = buf[i++];
  789. uint8_t sz = getDataSize(t);
  790. if (ch == channel && t == type) {
  791. return getFloat(&buf[i], sz, getMultiplier(t), isSigned(t));
  792. }
  793. i += sz; // skip
  794. }
  795. return 0.0f; // not found
  796. }
  797. bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) {
  798. if (channel == TELEM_CHANNEL_SELF) {
  799. lat = sensors.node_lat;
  800. lon = sensors.node_lon;
  801. alt = sensors.node_altitude;
  802. return true;
  803. }
  804. // REVISIT: custom GPS channels??
  805. return false;
  806. }
  807. void SensorMesh::loop() {
  808. mesh::Mesh::loop();
  809. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  810. mesh::Packet* pkt = createSelfAdvert();
  811. if (pkt) sendFlood(pkt);
  812. updateFloodAdvertTimer(); // schedule next flood advert
  813. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  814. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  815. mesh::Packet* pkt = createSelfAdvert();
  816. if (pkt) sendZeroHop(pkt);
  817. updateAdvertTimer(); // schedule next local advert
  818. }
  819. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  820. set_radio_at = 0; // clear timer
  821. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  822. MESH_DEBUG_PRINTLN("Temp radio params");
  823. }
  824. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  825. revert_radio_at = 0; // clear timer
  826. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  827. MESH_DEBUG_PRINTLN("Radio params restored");
  828. }
  829. uint32_t curr = getRTCClock()->getCurrentTime();
  830. if (curr >= last_read_time + SENSOR_READ_INTERVAL_SECS) {
  831. telemetry.reset();
  832. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  833. // query other sensors -- target specific
  834. sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions
  835. onSensorDataRead();
  836. last_read_time = curr;
  837. }
  838. // check the alert send queue
  839. if (num_alert_tasks > 0) {
  840. auto t = alert_tasks[0]; // process head of queue
  841. if (millisHasNowPassed(t->send_expiry)) { // next send needed?
  842. if (t->attempt >= 4) { // max attempts reached, try next contact
  843. t->curr_contact_idx++;
  844. if (t->curr_contact_idx >= num_contacts) { // no more contacts to try?
  845. num_alert_tasks--; // remove t from queue
  846. for (int i = 0; i < num_alert_tasks; i++) {
  847. alert_tasks[i] = alert_tasks[i + 1];
  848. }
  849. } else {
  850. auto c = &contacts[t->curr_contact_idx];
  851. uint16_t pri_mask = (t->pri == HIGH_PRI_ALERT) ? PERM_RECV_ALERTS_HI : PERM_RECV_ALERTS_LO;
  852. if (c->permissions & pri_mask) { // contact wants alert
  853. // reset attempts
  854. t->attempt = (t->pri == LOW_PRI_ALERT) ? 3 : 0; // Low pri alerts, start at attempt #3 (ie. only make ONE attempt)
  855. t->timestamp = getRTCClock()->getCurrentTimeUnique(); // need unique timestamp per contact
  856. sendAlert(c, t); // NOTE: modifies attempt, expected_acks[] and send_expiry
  857. } else {
  858. // next contact tested in next ::loop()
  859. }
  860. }
  861. } else if (t->curr_contact_idx < num_contacts) {
  862. auto c = &contacts[t->curr_contact_idx]; // send next attempt
  863. sendAlert(c, t); // NOTE: modifies attempt, expected_acks[] and send_expiry
  864. } else {
  865. // contact list has likely been modified while waiting for alert ACK, cancel this task
  866. t->attempt = 4; // next ::loop() will remove t from queue
  867. }
  868. }
  869. }
  870. // is there are pending dirty contacts write needed?
  871. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  872. saveContacts();
  873. dirty_contacts_expiry = 0;
  874. }
  875. }