DataStore.cpp 24 KB

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