DataStore.cpp 15 KB

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