DataStore.cpp 15 KB

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