DataStore.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #include <Arduino.h>
  2. #include "DataStore.h"
  3. DataStore::DataStore(FILESYSTEM& fs, mesh::RTCClock& clock) : _fs(&fs), _clock(&clock),
  4. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  5. identity_store(fs, "")
  6. #elif defined(RP2040_PLATFORM)
  7. identity_store(fs, "/identity")
  8. #else
  9. identity_store(fs, "/identity")
  10. #endif
  11. {
  12. }
  13. static File openWrite(FILESYSTEM* _fs, const char* filename) {
  14. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  15. _fs->remove(filename);
  16. return _fs->open(filename, FILE_O_WRITE);
  17. #elif defined(RP2040_PLATFORM)
  18. return _fs->open(filename, "w");
  19. #else
  20. return _fs->open(filename, "w", true);
  21. #endif
  22. }
  23. void DataStore::begin() {
  24. #if defined(RP2040_PLATFORM)
  25. identity_store.begin();
  26. #endif
  27. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  28. checkAdvBlobFile();
  29. #else
  30. // init 'blob store' support
  31. _fs->mkdir("/bl");
  32. #endif
  33. }
  34. #if defined(ESP32)
  35. #include <SPIFFS.h>
  36. #elif defined(RP2040_PLATFORM)
  37. #include <LittleFS.h>
  38. #elif defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  39. #include <InternalFileSystem.h>
  40. #endif
  41. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  42. int _countLfsBlock(void *p, lfs_block_t block){
  43. lfs_size_t *size = (lfs_size_t*) p;
  44. *size += 1;
  45. return 0;
  46. }
  47. lfs_ssize_t _getLfsUsedBlockCount() {
  48. lfs_size_t size = 0;
  49. lfs_traverse(InternalFS._getFS(), _countLfsBlock, &size);
  50. return size;
  51. }
  52. #endif
  53. uint32_t DataStore::getStorageUsedKb() const {
  54. #if defined(ESP32)
  55. return SPIFFS.usedBytes() / 1024;
  56. #elif defined(RP2040_PLATFORM)
  57. FSInfo info;
  58. info.usedBytes = 0;
  59. _fs->info(info);
  60. return info.usedBytes / 1024;
  61. #elif defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  62. const lfs_config* config = InternalFS._getFS()->cfg;
  63. int usedBlockCount = _getLfsUsedBlockCount();
  64. int usedBytes = config->block_size * usedBlockCount;
  65. return usedBytes / 1024;
  66. #else
  67. return 0;
  68. #endif
  69. }
  70. uint32_t DataStore::getStorageTotalKb() const {
  71. #if defined(ESP32)
  72. return SPIFFS.totalBytes() / 1024;
  73. #elif defined(RP2040_PLATFORM)
  74. FSInfo info;
  75. info.totalBytes = 0;
  76. _fs->info(info);
  77. return info.totalBytes / 1024;
  78. #elif defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  79. const lfs_config* config = InternalFS._getFS()->cfg;
  80. int totalBytes = config->block_size * config->block_count;
  81. return totalBytes / 1024;
  82. #else
  83. return 0;
  84. #endif
  85. }
  86. File DataStore::openRead(const char* filename) {
  87. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  88. return _fs->open(filename, FILE_O_READ);
  89. #elif defined(RP2040_PLATFORM)
  90. return _fs->open(filename, "r");
  91. #else
  92. return _fs->open(filename, "r", false);
  93. #endif
  94. }
  95. bool DataStore::removeFile(const char* filename) {
  96. return _fs->remove(filename);
  97. }
  98. bool DataStore::formatFileSystem() {
  99. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  100. return _fs->format();
  101. #elif defined(RP2040_PLATFORM)
  102. return LittleFS.format();
  103. #elif defined(ESP32)
  104. return ((fs::SPIFFSFS *)_fs)->format();
  105. #else
  106. #error "need to implement format()"
  107. #endif
  108. }
  109. bool DataStore::loadMainIdentity(mesh::LocalIdentity &identity) {
  110. return identity_store.load("_main", identity);
  111. }
  112. bool DataStore::saveMainIdentity(const mesh::LocalIdentity &identity) {
  113. return identity_store.save("_main", identity);
  114. }
  115. void DataStore::loadPrefs(NodePrefs& prefs, double& node_lat, double& node_lon) {
  116. if (_fs->exists("/new_prefs")) {
  117. loadPrefsInt("/new_prefs", prefs, node_lat, node_lon); // new filename
  118. } else if (_fs->exists("/node_prefs")) {
  119. loadPrefsInt("/node_prefs", prefs, node_lat, node_lon);
  120. savePrefs(prefs, node_lat, node_lon); // save to new filename
  121. _fs->remove("/node_prefs"); // remove old
  122. }
  123. }
  124. void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& node_lat, double& node_lon) {
  125. #if defined(RP2040_PLATFORM)
  126. File file = _fs->open(filename, "r");
  127. #else
  128. File file = _fs->open(filename);
  129. #endif
  130. if (file) {
  131. uint8_t pad[8];
  132. file.read((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0
  133. file.read((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4
  134. file.read(pad, 4); // 36
  135. file.read((uint8_t *)&node_lat, sizeof(node_lat)); // 40
  136. file.read((uint8_t *)&node_lon, sizeof(node_lon)); // 48
  137. file.read((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56
  138. file.read((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60
  139. file.read((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61
  140. file.read(pad, 1); // 62
  141. file.read((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63
  142. file.read((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64
  143. file.read((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
  144. file.read((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69
  145. file.read((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70
  146. file.read((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env)); // 71
  147. file.read((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
  148. file.read((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy)); // 76
  149. file.read((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks)); // 77
  150. file.read(pad, 2); // 78
  151. file.read((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
  152. file.close();
  153. }
  154. }
  155. void DataStore::savePrefs(const NodePrefs& _prefs, double node_lat, double node_lon) {
  156. File file = openWrite(_fs, "/new_prefs");
  157. if (file) {
  158. uint8_t pad[8];
  159. memset(pad, 0, sizeof(pad));
  160. file.write((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0
  161. file.write((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4
  162. file.write(pad, 4); // 36
  163. file.write((uint8_t *)&node_lat, sizeof(node_lat)); // 40
  164. file.write((uint8_t *)&node_lon, sizeof(node_lon)); // 48
  165. file.write((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56
  166. file.write((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60
  167. file.write((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61
  168. file.write(pad, 1); // 62
  169. file.write((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63
  170. file.write((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64
  171. file.write((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
  172. file.write((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69
  173. file.write((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70
  174. file.write((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env)); // 71
  175. file.write((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
  176. file.write((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy)); // 76
  177. file.write((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks)); // 77
  178. file.write(pad, 2); // 78
  179. file.write((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
  180. file.close();
  181. }
  182. }
  183. void DataStore::loadContacts(DataStoreHost* host) {
  184. if (_fs->exists("/contacts3")) {
  185. #if defined(RP2040_PLATFORM)
  186. File file = _fs->open("/contacts3", "r");
  187. #else
  188. File file = _fs->open("/contacts3");
  189. #endif
  190. if (file) {
  191. bool full = false;
  192. while (!full) {
  193. ContactInfo c;
  194. uint8_t pub_key[32];
  195. uint8_t unused;
  196. bool success = (file.read(pub_key, 32) == 32);
  197. success = success && (file.read((uint8_t *)&c.name, 32) == 32);
  198. success = success && (file.read(&c.type, 1) == 1);
  199. success = success && (file.read(&c.flags, 1) == 1);
  200. success = success && (file.read(&unused, 1) == 1);
  201. success = success && (file.read((uint8_t *)&c.sync_since, 4) == 4); // was 'reserved'
  202. success = success && (file.read((uint8_t *)&c.out_path_len, 1) == 1);
  203. success = success && (file.read((uint8_t *)&c.last_advert_timestamp, 4) == 4);
  204. success = success && (file.read(c.out_path, 64) == 64);
  205. success = success && (file.read((uint8_t *)&c.lastmod, 4) == 4);
  206. success = success && (file.read((uint8_t *)&c.gps_lat, 4) == 4);
  207. success = success && (file.read((uint8_t *)&c.gps_lon, 4) == 4);
  208. if (!success) break; // EOF
  209. c.id = mesh::Identity(pub_key);
  210. if (!host->onContactLoaded(c)) full = true;
  211. }
  212. file.close();
  213. }
  214. }
  215. }
  216. void DataStore::saveContacts(DataStoreHost* host) {
  217. File file = openWrite(_fs, "/contacts3");
  218. if (file) {
  219. uint32_t idx = 0;
  220. ContactInfo c;
  221. uint8_t unused = 0;
  222. while (host->getContactForSave(idx, c)) {
  223. bool success = (file.write(c.id.pub_key, 32) == 32);
  224. success = success && (file.write((uint8_t *)&c.name, 32) == 32);
  225. success = success && (file.write(&c.type, 1) == 1);
  226. success = success && (file.write(&c.flags, 1) == 1);
  227. success = success && (file.write(&unused, 1) == 1);
  228. success = success && (file.write((uint8_t *)&c.sync_since, 4) == 4);
  229. success = success && (file.write((uint8_t *)&c.out_path_len, 1) == 1);
  230. success = success && (file.write((uint8_t *)&c.last_advert_timestamp, 4) == 4);
  231. success = success && (file.write(c.out_path, 64) == 64);
  232. success = success && (file.write((uint8_t *)&c.lastmod, 4) == 4);
  233. success = success && (file.write((uint8_t *)&c.gps_lat, 4) == 4);
  234. success = success && (file.write((uint8_t *)&c.gps_lon, 4) == 4);
  235. if (!success) break; // write failed
  236. idx++; // advance to next contact
  237. }
  238. file.close();
  239. }
  240. }
  241. void DataStore::loadChannels(DataStoreHost* host) {
  242. if (_fs->exists("/channels2")) {
  243. #if defined(RP2040_PLATFORM)
  244. File file = _fs->open("/channels2", "r");
  245. #else
  246. File file = _fs->open("/channels2");
  247. #endif
  248. if (file) {
  249. bool full = false;
  250. uint8_t channel_idx = 0;
  251. while (!full) {
  252. ChannelDetails ch;
  253. uint8_t unused[4];
  254. bool success = (file.read(unused, 4) == 4);
  255. success = success && (file.read((uint8_t *)ch.name, 32) == 32);
  256. success = success && (file.read((uint8_t *)ch.channel.secret, 32) == 32);
  257. if (!success) break; // EOF
  258. if (host->onChannelLoaded(channel_idx, ch)) {
  259. channel_idx++;
  260. } else {
  261. full = true;
  262. }
  263. }
  264. file.close();
  265. }
  266. }
  267. }
  268. void DataStore::saveChannels(DataStoreHost* host) {
  269. File file = openWrite(_fs, "/channels2");
  270. if (file) {
  271. uint8_t channel_idx = 0;
  272. ChannelDetails ch;
  273. uint8_t unused[4];
  274. memset(unused, 0, 4);
  275. while (host->getChannelForSave(channel_idx, ch)) {
  276. bool success = (file.write(unused, 4) == 4);
  277. success = success && (file.write((uint8_t *)ch.name, 32) == 32);
  278. success = success && (file.write((uint8_t *)ch.channel.secret, 32) == 32);
  279. if (!success) break; // write failed
  280. channel_idx++;
  281. }
  282. file.close();
  283. }
  284. }
  285. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  286. #define MAX_ADVERT_PKT_LEN (2 + 32 + PUB_KEY_SIZE + 4 + SIGNATURE_SIZE + MAX_ADVERT_DATA_SIZE)
  287. struct BlobRec {
  288. uint32_t timestamp;
  289. uint8_t key[7];
  290. uint8_t len;
  291. uint8_t data[MAX_ADVERT_PKT_LEN];
  292. };
  293. void DataStore::checkAdvBlobFile() {
  294. if (!_fs->exists("/adv_blobs")) {
  295. File file = openWrite(_fs, "/adv_blobs");
  296. if (file) {
  297. BlobRec zeroes;
  298. memset(&zeroes, 0, sizeof(zeroes));
  299. for (int i = 0; i < 20; i++) { // pre-allocate to fixed size
  300. file.write((uint8_t *) &zeroes, sizeof(zeroes));
  301. }
  302. file.close();
  303. }
  304. }
  305. }
  306. uint8_t DataStore::getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) {
  307. File file = _fs->open("/adv_blobs");
  308. uint8_t len = 0; // 0 = not found
  309. if (file) {
  310. BlobRec tmp;
  311. while (file.read((uint8_t *) &tmp, sizeof(tmp)) == sizeof(tmp)) {
  312. if (memcmp(key, tmp.key, sizeof(tmp.key)) == 0) { // only match by 7 byte prefix
  313. len = tmp.len;
  314. memcpy(dest_buf, tmp.data, len);
  315. break;
  316. }
  317. }
  318. file.close();
  319. }
  320. return len;
  321. }
  322. bool DataStore::putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], uint8_t len) {
  323. if (len < PUB_KEY_SIZE+4+SIGNATURE_SIZE || len > MAX_ADVERT_PKT_LEN) return false;
  324. checkAdvBlobFile();
  325. File file = _fs->open("/adv_blobs", FILE_O_WRITE);
  326. if (file) {
  327. uint32_t pos = 0, found_pos = 0;
  328. uint32_t min_timestamp = 0xFFFFFFFF;
  329. // search for matching key OR evict by oldest timestmap
  330. BlobRec tmp;
  331. file.seek(0);
  332. while (file.read((uint8_t *) &tmp, sizeof(tmp)) == sizeof(tmp)) {
  333. if (memcmp(key, tmp.key, sizeof(tmp.key)) == 0) { // only match by 7 byte prefix
  334. found_pos = pos;
  335. break;
  336. }
  337. if (tmp.timestamp < min_timestamp) {
  338. min_timestamp = tmp.timestamp;
  339. found_pos = pos;
  340. }
  341. pos += sizeof(tmp);
  342. }
  343. memcpy(tmp.key, key, sizeof(tmp.key)); // just record 7 byte prefix of key
  344. memcpy(tmp.data, src_buf, len);
  345. tmp.len = len;
  346. tmp.timestamp = _clock->getCurrentTime();
  347. file.seek(found_pos);
  348. file.write((uint8_t *) &tmp, sizeof(tmp));
  349. file.close();
  350. return true;
  351. }
  352. return false; // error
  353. }
  354. #else
  355. uint8_t DataStore::getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) {
  356. char path[64];
  357. char fname[18];
  358. if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
  359. mesh::Utils::toHex(fname, key, key_len);
  360. sprintf(path, "/bl/%s", fname);
  361. if (_fs->exists(path)) {
  362. #if defined(RP2040_PLATFORM)
  363. File f = _fs->open(path, "r");
  364. #else
  365. File f = _fs->open(path);
  366. #endif
  367. if (f) {
  368. int len = f.read(dest_buf, 255); // currently MAX 255 byte blob len supported!!
  369. f.close();
  370. return len;
  371. }
  372. }
  373. return 0; // not found
  374. }
  375. bool DataStore::putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], uint8_t len) {
  376. char path[64];
  377. char fname[18];
  378. if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
  379. mesh::Utils::toHex(fname, key, key_len);
  380. sprintf(path, "/bl/%s", fname);
  381. File f = openWrite(_fs, path);
  382. if (f) {
  383. int n = f.write(src_buf, len);
  384. f.close();
  385. if (n == len) return true; // success!
  386. _fs->remove(path); // blob was only partially written!
  387. }
  388. return false; // error
  389. }
  390. #endif