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