diff --git a/examples/companion_radio/DataStore.cpp b/examples/companion_radio/DataStore.cpp index 06c56a7a444..4ce8546896a 100644 --- a/examples/companion_radio/DataStore.cpp +++ b/examples/companion_radio/DataStore.cpp @@ -555,6 +555,7 @@ bool DataStore::putBlobByKey(const uint8_t key[], int key_len, const uint8_t src bool DataStore::deleteBlobByKey(const uint8_t key[], int key_len) { return true; // this is just a stub on NRF52/STM32 platforms } +void DataStore::cleanOrphanBlobs(DataStoreHost* host) {} #else inline void makeBlobPath(const uint8_t key[], int key_len, char* path, size_t path_size) { char fname[18]; @@ -598,7 +599,41 @@ bool DataStore::deleteBlobByKey(const uint8_t key[], int key_len) { makeBlobPath(key, key_len, path, sizeof(path)); _fs->remove(path); - + return true; // return true even if file did not exist } + +void DataStore::cleanOrphanBlobs(DataStoreHost* host) { + if (_fs->exists("/bl/.cleaned")) return; + MESH_DEBUG_PRINTLN("Cleaning orphan blobs..."); + File root = openRead("/bl"); + if (root) { + for (File f = root.openNextFile(); f; f = root.openNextFile()) { + char name[24]; // copy: on ESP32, f.name() points into memory freed by f.close() + strncpy(name, f.name(), sizeof(name) - 1); + name[sizeof(name) - 1] = 0; + f.close(); + if (name[0] == '.' || strlen(name) != 16) continue; + uint8_t file_key[8]; + if (!mesh::Utils::fromHex(file_key, 8, name)) continue; + bool found = false; + ContactInfo c; + for (uint32_t i = 0; host->getContactForSave(i, c) && !found; i++) { + found = (memcmp(file_key, c.id.pub_key, 8) == 0); + } + if (!found) { + char path[24]; + sprintf(path, "/bl/%s", name); + _fs->remove(path); + } + } + root.close(); + } +#if defined(ESP32) + File m = _fs->open("/bl/.cleaned", "w", true); +#else + File m = _fs->open("/bl/.cleaned", "w"); +#endif + if (m) m.close(); +} #endif diff --git a/examples/companion_radio/DataStore.h b/examples/companion_radio/DataStore.h index e0a145caf1e..9a4beee36d4 100644 --- a/examples/companion_radio/DataStore.h +++ b/examples/companion_radio/DataStore.h @@ -43,6 +43,7 @@ class DataStore { uint8_t getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]); bool putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], uint8_t len); bool deleteBlobByKey(const uint8_t key[], int key_len); + void cleanOrphanBlobs(DataStoreHost* host); File openRead(const char* filename); File openRead(FILESYSTEM* fs, const char* filename); bool removeFile(const char* filename); diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 755c56d14c0..068532cb421 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -999,6 +999,9 @@ void MyMesh::begin() { resetContacts(); _store->loadContacts(this); bootstrapRTCfromContacts(); + + _store->cleanOrphanBlobs(this); + addChannel("Public", PUBLIC_GROUP_PSK); // pre-configure public channel _store->loadChannels(this);