SensorMesh.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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) {
  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. uint32_t now = getRTCClock()->getCurrentTimeUnique();
  314. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  315. reply_data[4] = RESP_SERVER_LOGIN_OK;
  316. reply_data[5] = 0;
  317. reply_data[6] = client->isAdmin() ? 1 : 0;
  318. reply_data[7] = client->permissions;
  319. getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
  320. reply_data[12] = FIRMWARE_VER_LEVEL;
  321. return 13; // reply length
  322. }
  323. void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
  324. while (*command == ' ') command++; // skip leading spaces
  325. if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
  326. memcpy(reply, command, 3); // reflect the prefix back
  327. reply += 3;
  328. command += 3;
  329. }
  330. // first, see if this is a custom-handled CLI command (ie. in main.cpp)
  331. if (handleCustomCommand(sender_timestamp, command, reply)) {
  332. return; // command has been handled
  333. }
  334. // handle sensor-specific CLI commands
  335. if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
  336. char* hex = &command[8];
  337. char* sp = strchr(hex, ' '); // look for separator char
  338. if (sp == NULL) {
  339. strcpy(reply, "Err - bad params");
  340. } else {
  341. *sp++ = 0; // replace space with null terminator
  342. uint8_t pubkey[PUB_KEY_SIZE];
  343. int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
  344. if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
  345. uint8_t perms = atoi(sp);
  346. if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
  347. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
  348. strcpy(reply, "OK");
  349. } else {
  350. strcpy(reply, "Err - invalid params");
  351. }
  352. } else {
  353. strcpy(reply, "Err - bad pubkey");
  354. }
  355. }
  356. } else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
  357. Serial.println("ACL:");
  358. for (int i = 0; i < acl.getNumClients(); i++) {
  359. auto c = acl.getClientByIdx(i);
  360. if (c->permissions == 0) continue; // skip deleted entries
  361. Serial.printf("%02X ", c->permissions);
  362. mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
  363. Serial.printf("\n");
  364. }
  365. reply[0] = 0;
  366. } else if (memcmp(command, "io ", 2) == 0) { // io {value}: write, io: read
  367. if (command[2] == ' ') { // it's a write
  368. uint32_t val;
  369. uint32_t g = board.getGpio();
  370. if (command[3] == 'r') { // reset bits
  371. sscanf(&command[4], "%x", &val);
  372. val = g & ~val;
  373. } else if (command[3] == 's') { // set bits
  374. sscanf(&command[4], "%x", &val);
  375. val |= g;
  376. } else if (command[3] == 't') { // toggle bits
  377. sscanf(&command[4], "%x", &val);
  378. val ^= g;
  379. } else { // set value
  380. sscanf(&command[3], "%x", &val);
  381. }
  382. board.setGpio(val);
  383. }
  384. sprintf(reply, "%x", board.getGpio());
  385. } else{
  386. _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
  387. }
  388. }
  389. void SensorMesh::onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) {
  390. if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
  391. uint32_t timestamp;
  392. memcpy(&timestamp, data, 4);
  393. data[len] = 0; // ensure null terminator
  394. uint8_t reply_len = handleLoginReq(sender, secret, timestamp, &data[4]);
  395. if (reply_len == 0) return; // invalid request
  396. if (packet->isRouteFlood()) {
  397. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  398. mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
  399. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  400. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  401. } else {
  402. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
  403. if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY);
  404. }
  405. }
  406. }
  407. int SensorMesh::searchPeersByHash(const uint8_t* hash) {
  408. int n = 0;
  409. for (int i = 0; i < acl.getNumClients() && n < MAX_SEARCH_RESULTS; i++) {
  410. if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
  411. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  412. }
  413. }
  414. return n;
  415. }
  416. void SensorMesh::getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) {
  417. int i = matching_peer_indexes[peer_idx];
  418. if (i >= 0 && i < acl.getNumClients()) {
  419. // lookup pre-calculated shared_secret
  420. memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
  421. } else {
  422. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  423. }
  424. }
  425. void SensorMesh::sendAckTo(const ClientInfo& dest, uint32_t ack_hash) {
  426. if (dest.out_path_len < 0) {
  427. mesh::Packet* ack = createAck(ack_hash);
  428. if (ack) sendFlood(ack, TXT_ACK_DELAY);
  429. } else {
  430. uint32_t d = TXT_ACK_DELAY;
  431. if (getExtraAckTransmitCount() > 0) {
  432. mesh::Packet* a1 = createMultiAck(ack_hash, 1);
  433. if (a1) sendDirect(a1, dest.out_path, dest.out_path_len, d);
  434. d += 300;
  435. }
  436. mesh::Packet* a2 = createAck(ack_hash);
  437. if (a2) sendDirect(a2, dest.out_path, dest.out_path_len, d);
  438. }
  439. }
  440. void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) {
  441. int i = matching_peer_indexes[sender_idx];
  442. if (i < 0 || i >= acl.getNumClients()) {
  443. MESH_DEBUG_PRINTLN("onPeerDataRecv: Invalid sender idx: %d", i);
  444. return;
  445. }
  446. ClientInfo* from = acl.getClientByIdx(i);
  447. if (type == PAYLOAD_TYPE_REQ) { // request (from a known contact)
  448. uint32_t timestamp;
  449. memcpy(&timestamp, data, 4);
  450. if (timestamp > from->last_timestamp) { // prevent replay attacks
  451. uint8_t reply_len = handleRequest(from->isAdmin() ? 0xFF : from->permissions, timestamp, data[4], &data[5], len - 5);
  452. if (reply_len == 0) return; // invalid command
  453. from->last_timestamp = timestamp;
  454. from->last_activity = getRTCClock()->getCurrentTime();
  455. if (packet->isRouteFlood()) {
  456. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  457. mesh::Packet* path = createPathReturn(from->id, secret, packet->path, packet->path_len,
  458. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  459. if (path) sendFlood(path, SERVER_RESPONSE_DELAY);
  460. } else {
  461. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, from->id, secret, reply_data, reply_len);
  462. if (reply) {
  463. if (from->out_path_len >= 0) { // we have an out_path, so send DIRECT
  464. sendDirect(reply, from->out_path, from->out_path_len, SERVER_RESPONSE_DELAY);
  465. } else {
  466. sendFlood(reply, SERVER_RESPONSE_DELAY);
  467. }
  468. }
  469. }
  470. } else {
  471. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  472. }
  473. } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && from->isAdmin()) { // a CLI command
  474. uint32_t sender_timestamp;
  475. memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  476. uint flags = (data[4] >> 2); // message attempt number, and other flags
  477. if (sender_timestamp > from->last_timestamp) { // prevent replay attacks
  478. if (flags == TXT_TYPE_PLAIN) {
  479. bool handled = handleIncomingMsg(*from, sender_timestamp, &data[5], flags, len - 5);
  480. if (handled) { // if msg was handled then send an ack
  481. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
  482. mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 5 + strlen((char *)&data[5]), from->id.pub_key, PUB_KEY_SIZE);
  483. if (packet->isRouteFlood()) {
  484. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the ACK
  485. mesh::Packet* path = createPathReturn(from->id, secret, packet->path, packet->path_len,
  486. PAYLOAD_TYPE_ACK, (uint8_t *) &ack_hash, 4);
  487. if (path) sendFlood(path, TXT_ACK_DELAY);
  488. } else {
  489. sendAckTo(*from, ack_hash);
  490. }
  491. }
  492. } else if (flags == TXT_TYPE_CLI_DATA) {
  493. from->last_timestamp = sender_timestamp;
  494. from->last_activity = getRTCClock()->getCurrentTime();
  495. // len can be > original length, but 'text' will be padded with zeroes
  496. data[len] = 0; // need to make a C string again, with null terminator
  497. uint8_t temp[166];
  498. char *command = (char *) &data[5];
  499. char *reply = (char *) &temp[5];
  500. handleCommand(sender_timestamp, command, reply);
  501. int text_len = strlen(reply);
  502. if (text_len > 0) {
  503. uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
  504. if (timestamp == sender_timestamp) {
  505. // WORKAROUND: the two timestamps need to be different, in the CLI view
  506. timestamp++;
  507. }
  508. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  509. temp[4] = (TXT_TYPE_CLI_DATA << 2);
  510. auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, from->id, secret, temp, 5 + text_len);
  511. if (reply) {
  512. if (from->out_path_len < 0) {
  513. sendFlood(reply, CLI_REPLY_DELAY_MILLIS);
  514. } else {
  515. sendDirect(reply, from->out_path, from->out_path_len, CLI_REPLY_DELAY_MILLIS);
  516. }
  517. }
  518. }
  519. } else {
  520. MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
  521. }
  522. } else {
  523. MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
  524. }
  525. }
  526. }
  527. bool SensorMesh::handleIncomingMsg(ClientInfo& from, uint32_t timestamp, uint8_t* data, uint flags, size_t len) {
  528. MESH_DEBUG_PRINT("handleIncomingMsg: unhandled msg from ");
  529. #ifdef MESH_DEBUG
  530. mesh::Utils::printHex(Serial, from.id.pub_key, PUB_KEY_SIZE);
  531. Serial.printf(": %s\n", data);
  532. #endif
  533. return false;
  534. }
  535. 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) {
  536. int i = matching_peer_indexes[sender_idx];
  537. if (i < 0 || i >= acl.getNumClients()) {
  538. MESH_DEBUG_PRINTLN("onPeerPathRecv: Invalid sender idx: %d", i);
  539. return false;
  540. }
  541. ClientInfo* from = acl.getClientByIdx(i);
  542. MESH_DEBUG_PRINTLN("PATH to contact, path_len=%d", (uint32_t) path_len);
  543. // NOTE: for this impl, we just replace the current 'out_path' regardless, whenever sender sends us a new out_path.
  544. // FUTURE: could store multiple out_paths per contact, and try to find which is the 'best'(?)
  545. memcpy(from->out_path, path, from->out_path_len = path_len); // store a copy of path, for sendDirect()
  546. from->last_activity = getRTCClock()->getCurrentTime();
  547. // REVISIT: maybe make ALL out_paths non-persisted to minimise flash writes??
  548. if (from->isAdmin()) {
  549. // only do saveContacts() (of this out_path change) if this is an admin
  550. dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
  551. }
  552. // NOTE: no reciprocal path send!!
  553. return false;
  554. }
  555. void SensorMesh::onAckRecv(mesh::Packet* packet, uint32_t ack_crc) {
  556. if (num_alert_tasks > 0) {
  557. auto t = alert_tasks[0]; // check current alert task
  558. for (int i = 0; i < t->attempt; i++) {
  559. if (ack_crc == t->expected_acks[i]) { // matching ACK!
  560. t->attempt = 4; // signal to move to next contact
  561. t->send_expiry = 0;
  562. packet->markDoNotRetransmit(); // ACK was for this node, so don't retransmit
  563. return;
  564. }
  565. }
  566. }
  567. }
  568. SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  569. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
  570. _cli(board, rtc, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4)
  571. {
  572. next_local_advert = next_flood_advert = 0;
  573. dirty_contacts_expiry = 0;
  574. last_read_time = 0;
  575. num_alert_tasks = 0;
  576. set_radio_at = revert_radio_at = 0;
  577. // defaults
  578. memset(&_prefs, 0, sizeof(_prefs));
  579. _prefs.airtime_factor = 1.0; // one half
  580. _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
  581. _prefs.tx_delay_factor = 0.5f; // was 0.25f
  582. StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
  583. _prefs.node_lat = ADVERT_LAT;
  584. _prefs.node_lon = ADVERT_LON;
  585. StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
  586. _prefs.freq = LORA_FREQ;
  587. _prefs.sf = LORA_SF;
  588. _prefs.bw = LORA_BW;
  589. _prefs.cr = LORA_CR;
  590. _prefs.tx_power_dbm = LORA_TX_POWER;
  591. _prefs.advert_interval = 1; // default to 2 minutes for NEW installs
  592. _prefs.flood_advert_interval = 0; // disabled
  593. _prefs.disable_fwd = true;
  594. _prefs.flood_max = 64;
  595. _prefs.interference_threshold = 0; // disabled
  596. // GPS defaults
  597. _prefs.gps_enabled = 0;
  598. _prefs.gps_interval = 0;
  599. _prefs.advert_loc_policy = ADVERT_LOC_PREFS;
  600. }
  601. void SensorMesh::begin(FILESYSTEM* fs) {
  602. mesh::Mesh::begin();
  603. _fs = fs;
  604. // load persisted prefs
  605. _cli.loadPrefs(_fs);
  606. acl.load(_fs);
  607. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  608. radio_set_tx_power(_prefs.tx_power_dbm);
  609. updateAdvertTimer();
  610. updateFloodAdvertTimer();
  611. #if ENV_INCLUDE_GPS == 1
  612. applyGpsPrefs();
  613. #endif
  614. }
  615. bool SensorMesh::formatFileSystem() {
  616. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  617. return InternalFS.format();
  618. #elif defined(RP2040_PLATFORM)
  619. return LittleFS.format();
  620. #elif defined(ESP32)
  621. return SPIFFS.format();
  622. #else
  623. #error "need to implement file system erase"
  624. return false;
  625. #endif
  626. }
  627. void SensorMesh::saveIdentity(const mesh::LocalIdentity& new_id) {
  628. self_id = new_id;
  629. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  630. IdentityStore store(*_fs, "");
  631. #elif defined(ESP32)
  632. IdentityStore store(*_fs, "/identity");
  633. #elif defined(RP2040_PLATFORM)
  634. IdentityStore store(*_fs, "/identity");
  635. #else
  636. #error "need to define saveIdentity()"
  637. #endif
  638. store.save("_main", self_id);
  639. }
  640. void SensorMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
  641. set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
  642. pending_freq = freq;
  643. pending_bw = bw;
  644. pending_sf = sf;
  645. pending_cr = cr;
  646. revert_radio_at = futureMillis(2000 + timeout_mins*60*1000); // schedule when to revert radio params
  647. }
  648. void SensorMesh::sendSelfAdvertisement(int delay_millis) {
  649. mesh::Packet* pkt = createSelfAdvert();
  650. if (pkt) {
  651. sendFlood(pkt, delay_millis);
  652. } else {
  653. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  654. }
  655. }
  656. void SensorMesh::updateAdvertTimer() {
  657. if (_prefs.advert_interval > 0) { // schedule local advert timer
  658. next_local_advert = futureMillis( ((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
  659. } else {
  660. next_local_advert = 0; // stop the timer
  661. }
  662. }
  663. void SensorMesh::updateFloodAdvertTimer() {
  664. if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
  665. next_flood_advert = futureMillis( ((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
  666. } else {
  667. next_flood_advert = 0; // stop the timer
  668. }
  669. }
  670. void SensorMesh::setTxPower(uint8_t power_dbm) {
  671. radio_set_tx_power(power_dbm);
  672. }
  673. float SensorMesh::getTelemValue(uint8_t channel, uint8_t type) {
  674. auto buf = telemetry.getBuffer();
  675. uint8_t size = telemetry.getSize();
  676. uint8_t i = 0;
  677. while (i + 2 < size) {
  678. // Get channel #
  679. uint8_t ch = buf[i++];
  680. // Get data type
  681. uint8_t t = buf[i++];
  682. uint8_t sz = getDataSize(t);
  683. if (ch == channel && t == type) {
  684. return getFloat(&buf[i], sz, getMultiplier(t), isSigned(t));
  685. }
  686. i += sz; // skip
  687. }
  688. return 0.0f; // not found
  689. }
  690. bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) {
  691. if (channel == TELEM_CHANNEL_SELF) {
  692. lat = sensors.node_lat;
  693. lon = sensors.node_lon;
  694. alt = sensors.node_altitude;
  695. return true;
  696. }
  697. // REVISIT: custom GPS channels??
  698. return false;
  699. }
  700. void SensorMesh::loop() {
  701. mesh::Mesh::loop();
  702. if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
  703. mesh::Packet* pkt = createSelfAdvert();
  704. if (pkt) sendFlood(pkt);
  705. updateFloodAdvertTimer(); // schedule next flood advert
  706. updateAdvertTimer(); // also schedule local advert (so they don't overlap)
  707. } else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
  708. mesh::Packet* pkt = createSelfAdvert();
  709. if (pkt) sendZeroHop(pkt);
  710. updateAdvertTimer(); // schedule next local advert
  711. }
  712. if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
  713. set_radio_at = 0; // clear timer
  714. radio_set_params(pending_freq, pending_bw, pending_sf, pending_cr);
  715. MESH_DEBUG_PRINTLN("Temp radio params");
  716. }
  717. if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
  718. revert_radio_at = 0; // clear timer
  719. radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
  720. MESH_DEBUG_PRINTLN("Radio params restored");
  721. }
  722. uint32_t curr = getRTCClock()->getCurrentTime();
  723. if (curr >= last_read_time + SENSOR_READ_INTERVAL_SECS) {
  724. telemetry.reset();
  725. telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
  726. // query other sensors -- target specific
  727. sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions
  728. onSensorDataRead();
  729. last_read_time = curr;
  730. }
  731. // check the alert send queue
  732. if (num_alert_tasks > 0) {
  733. auto t = alert_tasks[0]; // process head of queue
  734. if (millisHasNowPassed(t->send_expiry)) { // next send needed?
  735. if (t->attempt >= 4) { // max attempts reached, try next contact
  736. t->curr_contact_idx++;
  737. if (t->curr_contact_idx >= acl.getNumClients()) { // no more contacts to try?
  738. num_alert_tasks--; // remove t from queue
  739. for (int i = 0; i < num_alert_tasks; i++) {
  740. alert_tasks[i] = alert_tasks[i + 1];
  741. }
  742. } else {
  743. auto c = acl.getClientByIdx(t->curr_contact_idx);
  744. uint16_t pri_mask = (t->pri == HIGH_PRI_ALERT) ? PERM_RECV_ALERTS_HI : PERM_RECV_ALERTS_LO;
  745. if (c->permissions & pri_mask) { // contact wants alert
  746. // reset attempts
  747. t->attempt = (t->pri == LOW_PRI_ALERT) ? 3 : 0; // Low pri alerts, start at attempt #3 (ie. only make ONE attempt)
  748. t->timestamp = getRTCClock()->getCurrentTimeUnique(); // need unique timestamp per contact
  749. sendAlert(c, t); // NOTE: modifies attempt, expected_acks[] and send_expiry
  750. } else {
  751. // next contact tested in next ::loop()
  752. }
  753. }
  754. } else if (t->curr_contact_idx < acl.getNumClients()) {
  755. auto c = acl.getClientByIdx(t->curr_contact_idx); // send next attempt
  756. sendAlert(c, t); // NOTE: modifies attempt, expected_acks[] and send_expiry
  757. } else {
  758. // contact list has likely been modified while waiting for alert ACK, cancel this task
  759. t->attempt = 4; // next ::loop() will remove t from queue
  760. }
  761. }
  762. }
  763. // is there are pending dirty contacts write needed?
  764. if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
  765. acl.save(_fs);
  766. dirty_contacts_expiry = 0;
  767. }
  768. }