DataStore.cpp 20 KB

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