DataStore.cpp 15 KB

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