SensorMesh.cpp 34 KB

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