DataStore.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. #include <Arduino.h>
  2. #include "DataStore.h"
  3. #if defined(EXTRAFS) || defined(QSPIFLASH)
  4. #define MAX_BLOBRECS 100
  5. #else
  6. #define MAX_BLOBRECS 20
  7. #endif
  8. DataStore::DataStore(FILESYSTEM& fs, mesh::RTCClock& clock) : _fs(&fs), _fsExtra(nullptr), _clock(&clock),
  9. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  10. identity_store(fs, "")
  11. #elif defined(RP2040_PLATFORM)
  12. identity_store(fs, "/identity")
  13. #else
  14. identity_store(fs, "/identity")
  15. #endif
  16. , regions(keystore)
  17. {
  18. }
  19. #if defined(EXTRAFS) || defined(QSPIFLASH)
  20. DataStore::DataStore(FILESYSTEM& fs, FILESYSTEM& fsExtra, mesh::RTCClock& clock) : _fs(&fs), _fsExtra(&fsExtra), _clock(&clock),
  21. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  22. identity_store(fs, "")
  23. #elif defined(RP2040_PLATFORM)
  24. identity_store(fs, "/identity")
  25. #else
  26. identity_store(fs, "/identity")
  27. #endif
  28. , regions(keystore)
  29. {
  30. }
  31. #endif
  32. static File openWrite(FILESYSTEM* fs, const char* filename) {
  33. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  34. fs->remove(filename);
  35. return fs->open(filename, FILE_O_WRITE);
  36. #elif defined(RP2040_PLATFORM)
  37. return fs->open(filename, "w");
  38. #else
  39. return fs->open(filename, "w", true);
  40. #endif
  41. }
  42. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  43. static uint32_t _ContactsChannelsTotalBlocks = 0;
  44. #endif
  45. void DataStore::begin() {
  46. #if defined(RP2040_PLATFORM)
  47. identity_store.begin();
  48. #endif
  49. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  50. _ContactsChannelsTotalBlocks = _getContactsChannelsFS()->_getFS()->cfg->block_count;
  51. checkAdvBlobFile();
  52. #if defined(EXTRAFS) || defined(QSPIFLASH)
  53. migrateToSecondaryFS();
  54. #endif
  55. #else
  56. // init 'blob store' support
  57. _fs->mkdir("/bl");
  58. #endif
  59. regions.load(_fs);
  60. }
  61. #if defined(ESP32)
  62. #include <SPIFFS.h>
  63. #include <nvs_flash.h>
  64. #elif defined(RP2040_PLATFORM)
  65. #include <LittleFS.h>
  66. #elif defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  67. #if defined(QSPIFLASH)
  68. #include <CustomLFS_QSPIFlash.h>
  69. #elif defined(EXTRAFS)
  70. #include <CustomLFS.h>
  71. #else
  72. #include <InternalFileSystem.h>
  73. #endif
  74. #endif
  75. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  76. int _countLfsBlock(void *p, lfs_block_t block){
  77. if (block > _ContactsChannelsTotalBlocks) {
  78. MESH_DEBUG_PRINTLN("ERROR: Block %d exceeds filesystem bounds - CORRUPTION DETECTED!", block);
  79. return LFS_ERR_CORRUPT; // return error to abort lfs_traverse() gracefully
  80. }
  81. lfs_size_t *size = (lfs_size_t*) p;
  82. *size += 1;
  83. return 0;
  84. }
  85. lfs_ssize_t _getLfsUsedBlockCount(FILESYSTEM* fs) {
  86. lfs_size_t size = 0;
  87. int err = lfs_traverse(fs->_getFS(), _countLfsBlock, &size);
  88. if (err) {
  89. MESH_DEBUG_PRINTLN("ERROR: lfs_traverse() error: %d", err);
  90. return 0;
  91. }
  92. return size;
  93. }
  94. #endif
  95. uint32_t DataStore::getStorageUsedKb() const {
  96. #if defined(ESP32)
  97. return SPIFFS.usedBytes() / 1024;
  98. #elif defined(RP2040_PLATFORM)
  99. FSInfo info;
  100. info.usedBytes = 0;
  101. _fs->info(info);
  102. return info.usedBytes / 1024;
  103. #elif defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  104. const lfs_config* config = _getContactsChannelsFS()->_getFS()->cfg;
  105. int usedBlockCount = _getLfsUsedBlockCount(_getContactsChannelsFS());
  106. int usedBytes = config->block_size * usedBlockCount;
  107. return usedBytes / 1024;
  108. #else
  109. return 0;
  110. #endif
  111. }
  112. uint32_t DataStore::getStorageTotalKb() const {
  113. #if defined(ESP32)
  114. return SPIFFS.totalBytes() / 1024;
  115. #elif defined(RP2040_PLATFORM)
  116. FSInfo info;
  117. info.totalBytes = 0;
  118. _fs->info(info);
  119. return info.totalBytes / 1024;
  120. #elif defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  121. const lfs_config* config = _getContactsChannelsFS()->_getFS()->cfg;
  122. int totalBytes = config->block_size * config->block_count;
  123. return totalBytes / 1024;
  124. #else
  125. return 0;
  126. #endif
  127. }
  128. File DataStore::openRead(const char* filename) {
  129. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  130. return _fs->open(filename, FILE_O_READ);
  131. #elif defined(RP2040_PLATFORM)
  132. return _fs->open(filename, "r");
  133. #else
  134. return _fs->open(filename, "r", false);
  135. #endif
  136. }
  137. File DataStore::openRead(FILESYSTEM* fs, const char* filename) {
  138. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  139. return fs->open(filename, FILE_O_READ);
  140. #elif defined(RP2040_PLATFORM)
  141. return fs->open(filename, "r");
  142. #else
  143. return fs->open(filename, "r", false);
  144. #endif
  145. }
  146. bool DataStore::removeFile(const char* filename) {
  147. return _fs->remove(filename);
  148. }
  149. bool DataStore::removeFile(FILESYSTEM* fs, const char* filename) {
  150. return fs->remove(filename);
  151. }
  152. bool DataStore::formatFileSystem() {
  153. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  154. if (_fsExtra == nullptr) {
  155. return _fs->format();
  156. } else {
  157. return _fs->format() && _fsExtra->format();
  158. }
  159. #elif defined(RP2040_PLATFORM)
  160. return LittleFS.format();
  161. #elif defined(ESP32)
  162. bool fs_success = ((fs::SPIFFSFS *)_fs)->format();
  163. esp_err_t nvs_err = nvs_flash_erase(); // no need to reinit, will be done by reboot
  164. return fs_success && (nvs_err == ESP_OK);
  165. #else
  166. #error "need to implement format()"
  167. #endif
  168. }
  169. bool DataStore::loadMainIdentity(mesh::LocalIdentity &identity) {
  170. return identity_store.load("_main", identity);
  171. }
  172. bool DataStore::saveMainIdentity(const mesh::LocalIdentity &identity) {
  173. return identity_store.save("_main", identity);
  174. }
  175. void DataStore::loadPrefs(NodePrefs& prefs, double& node_lat, double& node_lon) {
  176. if (_fs->exists("/new_prefs")) {
  177. loadPrefsInt("/new_prefs", prefs, node_lat, node_lon); // new filename
  178. } else if (_fs->exists("/node_prefs")) {
  179. loadPrefsInt("/node_prefs", prefs, node_lat, node_lon);
  180. savePrefs(prefs, node_lat, node_lon); // save to new filename
  181. _fs->remove("/node_prefs"); // remove old
  182. }
  183. }
  184. void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& node_lat, double& node_lon) {
  185. File file = openRead(_fs, filename);
  186. if (file) {
  187. uint8_t pad[8];
  188. file.read((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0
  189. file.read((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4
  190. file.read(pad, 4); // 36
  191. file.read((uint8_t *)&node_lat, sizeof(node_lat)); // 40
  192. file.read((uint8_t *)&node_lon, sizeof(node_lon)); // 48
  193. file.read((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56
  194. file.read((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60
  195. file.read((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61
  196. file.read((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat)); // 62
  197. file.read((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63
  198. file.read((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64
  199. file.read((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
  200. file.read((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69
  201. file.read((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70
  202. file.read((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env)); // 71
  203. file.read((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
  204. file.read((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy)); // 76
  205. file.read((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks)); // 77
  206. file.read((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode)); // 78
  207. file.read(pad, 1); // 79
  208. file.read((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
  209. file.read((uint8_t *)&_prefs.buzzer_quiet, sizeof(_prefs.buzzer_quiet)); // 84
  210. file.read((uint8_t *)&_prefs.gps_enabled, sizeof(_prefs.gps_enabled)); // 85
  211. file.read((uint8_t *)&_prefs.gps_interval, sizeof(_prefs.gps_interval)); // 86
  212. file.read((uint8_t *)&_prefs.autoadd_config, sizeof(_prefs.autoadd_config)); // 87
  213. file.read((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops)); // 88
  214. file.read((uint8_t *)&_prefs.rx_boosted_gain, sizeof(_prefs.rx_boosted_gain)); // 89
  215. file.close();
  216. }
  217. }
  218. void DataStore::savePrefs(const NodePrefs& _prefs, double node_lat, double node_lon) {
  219. File file = openWrite(_fs, "/new_prefs");
  220. if (file) {
  221. uint8_t pad[8];
  222. memset(pad, 0, sizeof(pad));
  223. file.write((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0
  224. file.write((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4
  225. file.write(pad, 4); // 36
  226. file.write((uint8_t *)&node_lat, sizeof(node_lat)); // 40
  227. file.write((uint8_t *)&node_lon, sizeof(node_lon)); // 48
  228. file.write((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56
  229. file.write((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60
  230. file.write((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61
  231. file.write((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat)); // 62
  232. file.write((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63
  233. file.write((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64
  234. file.write((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
  235. file.write((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69
  236. file.write((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70
  237. file.write((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env)); // 71
  238. file.write((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
  239. file.write((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy)); // 76
  240. file.write((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks)); // 77
  241. file.write((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode)); // 78
  242. file.write(pad, 1); // 79
  243. file.write((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
  244. file.write((uint8_t *)&_prefs.buzzer_quiet, sizeof(_prefs.buzzer_quiet)); // 84
  245. file.write((uint8_t *)&_prefs.gps_enabled, sizeof(_prefs.gps_enabled)); // 85
  246. file.write((uint8_t *)&_prefs.gps_interval, sizeof(_prefs.gps_interval)); // 86
  247. file.write((uint8_t *)&_prefs.autoadd_config, sizeof(_prefs.autoadd_config)); // 87
  248. file.write((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops)); // 88
  249. file.write((uint8_t *)&_prefs.rx_boosted_gain, sizeof(_prefs.rx_boosted_gain)); // 89
  250. file.close();
  251. }
  252. }
  253. void DataStore::loadContacts(DataStoreHost* host) {
  254. File file = openRead(_getContactsChannelsFS(), "/contacts3");
  255. if (file) {
  256. bool full = false;
  257. while (!full) {
  258. ContactInfo c;
  259. uint8_t pub_key[32];
  260. uint8_t unused;
  261. bool success = (file.read(pub_key, 32) == 32);
  262. success = success && (file.read((uint8_t *)&c.name, 32) == 32);
  263. success = success && (file.read(&c.type, 1) == 1);
  264. success = success && (file.read(&c.flags, 1) == 1);
  265. success = success && (file.read(&unused, 1) == 1);
  266. success = success && (file.read((uint8_t *)&c.sync_since, 4) == 4); // was 'reserved'
  267. success = success && (file.read((uint8_t *)&c.out_path_len, 1) == 1);
  268. success = success && (file.read((uint8_t *)&c.last_advert_timestamp, 4) == 4);
  269. success = success && (file.read(c.out_path, 64) == 64);
  270. success = success && (file.read((uint8_t *)&c.lastmod, 4) == 4);
  271. success = success && (file.read((uint8_t *)&c.gps_lat, 4) == 4);
  272. success = success && (file.read((uint8_t *)&c.gps_lon, 4) == 4);
  273. if (!success) break; // EOF
  274. c.id = mesh::Identity(pub_key);
  275. if (!host->onContactLoaded(c)) full = true;
  276. }
  277. file.close();
  278. }
  279. }
  280. void DataStore::saveContacts(DataStoreHost* host) {
  281. File file = openWrite(_getContactsChannelsFS(), "/contacts3");
  282. if (file) {
  283. uint32_t idx = 0;
  284. ContactInfo c;
  285. uint8_t unused = 0;
  286. while (host->getContactForSave(idx, c)) {
  287. bool success = (file.write(c.id.pub_key, 32) == 32);
  288. success = success && (file.write((uint8_t *)&c.name, 32) == 32);
  289. success = success && (file.write(&c.type, 1) == 1);
  290. success = success && (file.write(&c.flags, 1) == 1);
  291. success = success && (file.write(&unused, 1) == 1);
  292. success = success && (file.write((uint8_t *)&c.sync_since, 4) == 4);
  293. success = success && (file.write((uint8_t *)&c.out_path_len, 1) == 1);
  294. success = success && (file.write((uint8_t *)&c.last_advert_timestamp, 4) == 4);
  295. success = success && (file.write(c.out_path, 64) == 64);
  296. success = success && (file.write((uint8_t *)&c.lastmod, 4) == 4);
  297. success = success && (file.write((uint8_t *)&c.gps_lat, 4) == 4);
  298. success = success && (file.write((uint8_t *)&c.gps_lon, 4) == 4);
  299. if (!success) break; // write failed
  300. idx++; // advance to next contact
  301. }
  302. file.close();
  303. }
  304. }
  305. void DataStore::loadChannels(DataStoreHost* host) {
  306. File file = openRead(_getContactsChannelsFS(), "/channels2");
  307. if (file) {
  308. bool full = false;
  309. uint8_t channel_idx = 0;
  310. while (!full) {
  311. ChannelDetails ch;
  312. uint8_t unused[4];
  313. bool success = (file.read(unused, 4) == 4);
  314. success = success && (file.read((uint8_t *)ch.name, 32) == 32);
  315. success = success && (file.read((uint8_t *)ch.channel.secret, 32) == 32);
  316. if (!success) break; // EOF
  317. if (host->onChannelLoaded(channel_idx, ch)) {
  318. channel_idx++;
  319. } else {
  320. full = true;
  321. }
  322. }
  323. file.close();
  324. }
  325. }
  326. void DataStore::saveChannels(DataStoreHost* host) {
  327. File file = openWrite(_getContactsChannelsFS(), "/channels2");
  328. if (file) {
  329. uint8_t channel_idx = 0;
  330. ChannelDetails ch;
  331. uint8_t unused[4];
  332. memset(unused, 0, 4);
  333. while (host->getChannelForSave(channel_idx, ch)) {
  334. bool success = (file.write(unused, 4) == 4);
  335. success = success && (file.write((uint8_t *)ch.name, 32) == 32);
  336. success = success && (file.write((uint8_t *)ch.channel.secret, 32) == 32);
  337. if (!success) break; // write failed
  338. channel_idx++;
  339. }
  340. file.close();
  341. }
  342. }
  343. #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
  344. #define MAX_ADVERT_PKT_LEN (2 + 32 + PUB_KEY_SIZE + 4 + SIGNATURE_SIZE + MAX_ADVERT_DATA_SIZE)
  345. struct BlobRec {
  346. uint32_t timestamp;
  347. uint8_t key[7];
  348. uint8_t len;
  349. uint8_t data[MAX_ADVERT_PKT_LEN];
  350. };
  351. void DataStore::checkAdvBlobFile() {
  352. if (!_getContactsChannelsFS()->exists("/adv_blobs")) {
  353. File file = openWrite(_getContactsChannelsFS(), "/adv_blobs");
  354. if (file) {
  355. BlobRec zeroes;
  356. memset(&zeroes, 0, sizeof(zeroes));
  357. for (int i = 0; i < MAX_BLOBRECS; i++) { // pre-allocate to fixed size
  358. file.write((uint8_t *) &zeroes, sizeof(zeroes));
  359. }
  360. file.close();
  361. }
  362. }
  363. }
  364. void DataStore::migrateToSecondaryFS() {
  365. // migrate old adv_blobs, contacts3 and channels2 files to secondary FS if they don't already exist
  366. if (!_fsExtra->exists("/adv_blobs")) {
  367. if (_fs->exists("/adv_blobs")) {
  368. File oldAdvBlobs = openRead(_fs, "/adv_blobs");
  369. File newAdvBlobs = openWrite(_fsExtra, "/adv_blobs");
  370. if (oldAdvBlobs && newAdvBlobs) {
  371. BlobRec rec;
  372. size_t count = 0;
  373. // Copy 20 BlobRecs from old to new
  374. while (count < 20 && oldAdvBlobs.read((uint8_t *)&rec, sizeof(rec)) == sizeof(rec)) {
  375. newAdvBlobs.seek(count * sizeof(BlobRec));
  376. newAdvBlobs.write((uint8_t *)&rec, sizeof(rec));
  377. count++;
  378. }
  379. }
  380. if (oldAdvBlobs) oldAdvBlobs.close();
  381. if (newAdvBlobs) newAdvBlobs.close();
  382. _fs->remove("/adv_blobs");
  383. }
  384. }
  385. if (!_fsExtra->exists("/contacts3")) {
  386. if (_fs->exists("/contacts3")) {
  387. File oldFile = openRead(_fs, "/contacts3");
  388. File newFile = openWrite(_fsExtra, "/contacts3");
  389. if (oldFile && newFile) {
  390. uint8_t buf[64];
  391. int n;
  392. while ((n = oldFile.read(buf, sizeof(buf))) > 0) {
  393. newFile.write(buf, n);
  394. }
  395. }
  396. if (oldFile) oldFile.close();
  397. if (newFile) newFile.close();
  398. _fs->remove("/contacts3");
  399. }
  400. }
  401. if (!_fsExtra->exists("/channels2")) {
  402. if (_fs->exists("/channels2")) {
  403. File oldFile = openRead(_fs, "/channels2");
  404. File newFile = openWrite(_fsExtra, "/channels2");
  405. if (oldFile && newFile) {
  406. uint8_t buf[64];
  407. int n;
  408. while ((n = oldFile.read(buf, sizeof(buf))) > 0) {
  409. newFile.write(buf, n);
  410. }
  411. }
  412. if (oldFile) oldFile.close();
  413. if (newFile) newFile.close();
  414. _fs->remove("/channels2");
  415. }
  416. }
  417. // cleanup nodes which have been testing the extra fs, copy _main.id and new_prefs back to primary
  418. if (_fsExtra->exists("/_main.id")) {
  419. if (_fs->exists("/_main.id")) {_fs->remove("/_main.id");}
  420. File oldFile = openRead(_fsExtra, "/_main.id");
  421. File newFile = openWrite(_fs, "/_main.id");
  422. if (oldFile && newFile) {
  423. uint8_t buf[64];
  424. int n;
  425. while ((n = oldFile.read(buf, sizeof(buf))) > 0) {
  426. newFile.write(buf, n);
  427. }
  428. }
  429. if (oldFile) oldFile.close();
  430. if (newFile) newFile.close();
  431. _fsExtra->remove("/_main.id");
  432. }
  433. if (_fsExtra->exists("/new_prefs")) {
  434. if (_fs->exists("/new_prefs")) {_fs->remove("/new_prefs");}
  435. File oldFile = openRead(_fsExtra, "/new_prefs");
  436. File newFile = openWrite(_fs, "/new_prefs");
  437. if (oldFile && newFile) {
  438. uint8_t buf[64];
  439. int n;
  440. while ((n = oldFile.read(buf, sizeof(buf))) > 0) {
  441. newFile.write(buf, n);
  442. }
  443. }
  444. if (oldFile) oldFile.close();
  445. if (newFile) newFile.close();
  446. _fsExtra->remove("/new_prefs");
  447. }
  448. // remove files from where they should not be anymore
  449. if (_fs->exists("/adv_blobs")) {
  450. _fs->remove("/adv_blobs");
  451. }
  452. if (_fs->exists("/contacts3")) {
  453. _fs->remove("/contacts3");
  454. }
  455. if (_fs->exists("/channels2")) {
  456. _fs->remove("/channels2");
  457. }
  458. if (_fsExtra->exists("/_main.id")) {
  459. _fsExtra->remove("/_main.id");
  460. }
  461. if (_fsExtra->exists("/new_prefs")) {
  462. _fsExtra->remove("/new_prefs");
  463. }
  464. }
  465. uint8_t DataStore::getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) {
  466. File file = openRead(_getContactsChannelsFS(), "/adv_blobs");
  467. uint8_t len = 0; // 0 = not found
  468. if (file) {
  469. BlobRec tmp;
  470. while (file.read((uint8_t *) &tmp, sizeof(tmp)) == sizeof(tmp)) {
  471. if (memcmp(key, tmp.key, sizeof(tmp.key)) == 0) { // only match by 7 byte prefix
  472. len = tmp.len;
  473. memcpy(dest_buf, tmp.data, len);
  474. break;
  475. }
  476. }
  477. file.close();
  478. }
  479. return len;
  480. }
  481. bool DataStore::putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], uint8_t len) {
  482. if (len < PUB_KEY_SIZE+4+SIGNATURE_SIZE || len > MAX_ADVERT_PKT_LEN) return false;
  483. checkAdvBlobFile();
  484. File file = _getContactsChannelsFS()->open("/adv_blobs", FILE_O_WRITE);
  485. if (file) {
  486. uint32_t pos = 0, found_pos = 0;
  487. uint32_t min_timestamp = 0xFFFFFFFF;
  488. // search for matching key OR evict by oldest timestmap
  489. BlobRec tmp;
  490. file.seek(0);
  491. while (file.read((uint8_t *) &tmp, sizeof(tmp)) == sizeof(tmp)) {
  492. if (memcmp(key, tmp.key, sizeof(tmp.key)) == 0) { // only match by 7 byte prefix
  493. found_pos = pos;
  494. break;
  495. }
  496. if (tmp.timestamp < min_timestamp) {
  497. min_timestamp = tmp.timestamp;
  498. found_pos = pos;
  499. }
  500. pos += sizeof(tmp);
  501. }
  502. memcpy(tmp.key, key, sizeof(tmp.key)); // just record 7 byte prefix of key
  503. memcpy(tmp.data, src_buf, len);
  504. tmp.len = len;
  505. tmp.timestamp = _clock->getCurrentTime();
  506. file.seek(found_pos);
  507. file.write((uint8_t *) &tmp, sizeof(tmp));
  508. file.close();
  509. return true;
  510. }
  511. return false; // error
  512. }
  513. bool DataStore::deleteBlobByKey(const uint8_t key[], int key_len) {
  514. return true; // this is just a stub on NRF52/STM32 platforms
  515. }
  516. #else
  517. inline void makeBlobPath(const uint8_t key[], int key_len, char* path, size_t path_size) {
  518. char fname[18];
  519. if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
  520. mesh::Utils::toHex(fname, key, key_len);
  521. sprintf(path, "/bl/%s", fname);
  522. }
  523. uint8_t DataStore::getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) {
  524. char path[64];
  525. makeBlobPath(key, key_len, path, sizeof(path));
  526. if (_fs->exists(path)) {
  527. File f = openRead(_fs, path);
  528. if (f) {
  529. int len = f.read(dest_buf, 255); // currently MAX 255 byte blob len supported!!
  530. f.close();
  531. return len;
  532. }
  533. }
  534. return 0; // not found
  535. }
  536. bool DataStore::putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], uint8_t len) {
  537. char path[64];
  538. makeBlobPath(key, key_len, path, sizeof(path));
  539. File f = openWrite(_fs, path);
  540. if (f) {
  541. int n = f.write(src_buf, len);
  542. f.close();
  543. if (n == len) return true; // success!
  544. _fs->remove(path); // blob was only partially written!
  545. }
  546. return false; // error
  547. }
  548. bool DataStore::deleteBlobByKey(const uint8_t key[], int key_len) {
  549. char path[64];
  550. makeBlobPath(key, key_len, path, sizeof(path));
  551. _fs->remove(path);
  552. return true; // return true even if file did not exist
  553. }
  554. #endif