Avoid repeated missing SPIFFS scans during ESP32 startup

This commit is contained in:
mikecarper committed 2026-10-05 14:12:44 -07:00
1 parent 47f10c0735
commit a0de63ab5e
16 files changed
+1158

No files matched your search

+23
View File
@@ -2,6 +2,7 @@
#include "CommonCLI.h"
#include "PrefsSaveReplyGuard.h"
#include "UsbLoggingWatchdog.h"
#include "HilStartupTrace.h"
#include <helpers/ui/DisplayPowerSettings.h>
#include "CLICommandUtils.h"
#include "GpsPowerPolicy.h"
@@ -745,15 +746,23 @@ static void formatSnrDbX4Short(char* dest, size_t dest_len, int16_t snr_x4) {
}
void CommonCLI::loadPrefs(FILESYSTEM* fs) {
mesh::hilStartupTrace("prefs_profiles_begin");
_radio_profiles.begin(fs, _callbacks->getProfileRadio(), _rtc, true);
mesh::hilStartupTrace("prefs_profiles_ready");
_prefs->primary_radio_preamble = _radio_profiles.primaryPreamble();
#if !defined(WITH_MQTT_BRIDGE) && (defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM))
mesh::hilStartupTrace("prefs_recovery_begin");
mesh::ContactFileTransaction::recover(fs, "/com_prefs");
mesh::hilStartupTrace("prefs_recovery_ready");
#endif
#if defined(ENABLE_OTA)
mesh::hilStartupTrace("prefs_ota_speed_begin");
mesh::ota::beginSpeedConfig(fs);
mesh::hilStartupTrace("prefs_ota_speed_ready");
#endif
mesh::hilStartupTrace("prefs_display_begin");
const bool display_settings_loaded = mesh::ui::loadDisplayPowerSettings(fs, false);
mesh::hilStartupTrace("prefs_display_ready");
(void)display_settings_loaded;
bool is_fresh_install = false;
bool is_upgrade = false;
@@ -777,11 +786,14 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
#ifdef WITH_MQTT_BRIDGE
bool node_prefs_needs_migration = false;
mesh::hilStartupTrace("prefs_recovery_begin");
if (!recoverCommonPrefsFiles(fs)) {
MESH_DEBUG_PRINTLN("Prefs: common preference recovery is incomplete");
}
mesh::hilStartupTrace("prefs_recovery_ready");
#endif
mesh::hilStartupTrace("prefs_common_begin");
if (fs->exists("/com_prefs")) {
loadPrefsInt(fs, "/com_prefs"); loaded = true; // new filename
} else if (fs->exists("/node_prefs")) {
@@ -835,13 +847,16 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
_prefs->powersaving_enabled = DEFAULT_POWERSAVING_ENABLED && !dual_radio_active ? 1 : 0;
_prefs->bridge_pkt_src = 1; // Default to RX (logRx) for new installs
}
mesh::hilStartupTrace("prefs_common_ready");
#ifdef WITH_MQTT_BRIDGE
// Load observer preferences (MQTT/WiFi/timezone/SNMP/alert) from /mqtt_prefs.
// Readers (MQTTBridge, AlertReporter, observer CLI) use _mqtt_prefs directly -
// these fields no longer exist in NodePrefs, so there is nothing to sync.
MQTTPrefsAtomicStore::LegacyUpgradeGate legacy_upgrade(
_com_prefs_needs_upgrade || node_prefs_needs_migration);
mesh::hilStartupTrace("prefs_mqtt_begin");
loadMQTTPrefs(fs, &legacy_upgrade);
mesh::hilStartupTrace("prefs_mqtt_ready");
if (!display_settings_loaded && _mqtt_prefs.display_timeout_secs != DISPLAY_TIMEOUT_DEFAULT_SECS)
mesh::ui::migrateLegacyDisplayTimeout(_mqtt_prefs.display_timeout_secs);
if (_mqtt_prefs_hold) legacy_upgrade.holdMqttSource();
@@ -868,6 +883,7 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
// set by setMQTTPrefsDefaults(). No explicit migration needed.
#endif
mesh::hilStartupTrace("prefs_migration_begin");
#ifdef WITH_MQTT_BRIDGE
if (node_prefs_needs_migration) {
if (legacy_upgrade.mayRewriteComPrefs()) {
@@ -905,15 +921,18 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
_com_prefs_needs_upgrade = false;
}
#endif
mesh::hilStartupTrace("prefs_migration_ready");
#if defined(ENABLE_OTA)
if (loaded) syncOtaConfigFromPrefs(); // persisted OTA policy/keys -> OtaContext (else keep safe defaults)
#endif
mesh::hilStartupTrace("prefs_apply_begin");
#if MESH_USB_LOGGING_AVAILABLE
mesh::setUsbDebugEnabled(_prefs->usb_debug_enabled != 0);
mesh::setUsbLoggingEnabled(_prefs->usb_logging_enabled != 0);
#endif
_radio_profiles.adoptPrimaryPreamble(_prefs->primary_radio_preamble);
_radio_profiles.stagePrimary(_prefs->primary_radio_preamble, false);
mesh::hilStartupTrace("prefs_apply_ready");
}
#if defined(ENABLE_OTA)
@@ -939,6 +958,7 @@ void CommonCLI::syncOtaConfigFromPrefs() {
#endif
void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
mesh::hilStartupTrace("prefs_image_open_begin");
// Older or truncated preference images must never inherit these opt-ins
// from a previous load of a newer image.
_prefs->usb_debug_enabled = 0;
@@ -950,6 +970,7 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
#else
File file = fs->open(filename);
#endif
mesh::hilStartupTrace("prefs_image_open_ready");
if (file) {
#if defined(WITH_RS232_BRIDGE) && defined(RS232_BRIDGE_MERGED) \
&& !defined(RS232_BRIDGE_DEFAULT_ON)
@@ -967,6 +988,7 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
}
uint8_t pad[8];
mesh::hilStartupTrace("prefs_image_core_begin");
file.read((uint8_t *)&_prefs->airtime_factor, sizeof(_prefs->airtime_factor)); // 0
file.read((uint8_t *)&_prefs->node_name, sizeof(_prefs->node_name)); // 4
file.read(pad, 4); // 36
@@ -1010,6 +1032,7 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
file.read((uint8_t *)&_prefs->discovery_mod_timestamp, sizeof(_prefs->discovery_mod_timestamp)); // 162
file.read((uint8_t *)&_prefs->adc_multiplier, sizeof(_prefs->adc_multiplier)); // 166
file.read((uint8_t *)_prefs->owner_info, sizeof(_prefs->owner_info)); // 170
mesh::hilStartupTrace("prefs_image_core_ready");
_prefs->node_name[sizeof(_prefs->node_name) - 1] = '\0';
_prefs->password[sizeof(_prefs->password) - 1] = '\0';
_prefs->guest_password[sizeof(_prefs->guest_password) - 1] = '\0';
+7
View File
@@ -2,6 +2,7 @@
#include "ManagementReporter.h"
#include "FileRead.h"
#include "PersistentStoreFormat.h"
#include "HilStartupTrace.h"
#include <new>
#include <stdlib.h>
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
@@ -245,17 +246,23 @@ void CommonCLI::beginManagement(mesh::Mesh& mesh, FILESYSTEM* fs) {
_management_mesh = &mesh; _management_fs = fs;
_management_last_ms = millis(); _management_uptime_ms = _management_last_ms;
if (!_data_route) {
mesh::hilStartupTrace("management_route_begin");
_data_route = new (std::nothrow) mesh::DataRouteState;
if (_data_route) {
_data_route->fs = fs; _data_route->regions = _region_map;
_data_route->healthy = mesh::dataRouteLoad(*_data_route);
}
mesh::hilStartupTrace("management_route_ready");
}
// No reporter/history allocation for the default unconfigured installation.
mesh::hilStartupTrace("management_probe_begin");
if (fs->exists("/management") || fs->exists("/management.bak")) {
mesh::hilStartupTrace("management_reporter_begin");
_management = new (std::nothrow) mesh::ManagementReporter(
mesh, *_board, *_sensors, *_acl, *_prefs, *_callbacks, *this, fs);
mesh::hilStartupTrace("management_reporter_ready");
}
mesh::hilStartupTrace("management_probe_ready");
}
void CommonCLI::loopManagement() {
+5
View File
@@ -4,6 +4,7 @@
#if defined(ESP32_PLATFORM)
#include <errno.h>
#include <sys/stat.h>
#include <helpers/esp32/BootFilePresence.h>
#endif
namespace mesh {
@@ -16,6 +17,10 @@ bool filePresence(Filesystem* fs, const char* path, bool& present) {
char absolute[128];
const int length = snprintf(absolute, sizeof(absolute), "/spiffs%s", path);
if (length < 0 || static_cast<size_t>(length) >= sizeof(absolute)) return false;
if (esp32BootFileKnownAbsent(fs, path)) {
present = false;
return true;
}
struct stat info;
const int result = ::stat(absolute, &info);
if (result != 0 && errno != ENOENT) return false;
+18
View File
@@ -0,0 +1,18 @@
#pragma once
// Optional hardware-test timestamps only. Normal firmware has no extra output
// or timing work; phases are fixed literals and never contain node data.
#if defined(MESH_HIL_STARTUP_TRACE) && MESH_HIL_STARTUP_TRACE
#include <Arduino.h>
#include <helpers/UsbLogging.h>
namespace mesh {
inline void hilStartupTrace(const char* phase) {
usbConsolePort().printf("HIL_BOOT phase=%s at=%lu\r\n", phase,
static_cast<unsigned long>(millis()));
}
}
#else
namespace mesh {
inline void hilStartupTrace(const char*) {}
}
#endif
+25
View File
@@ -0,0 +1,25 @@
#pragma once
namespace mesh {
namespace detail {
struct Esp32BootAbsenceRegistry {
const void* owner = nullptr;
const void* context = nullptr;
bool (*known_absent)(const void*, const char*) = nullptr;
};
inline Esp32BootAbsenceRegistry& esp32BootAbsenceRegistry() {
static Esp32BootAbsenceRegistry registry;
return registry;
}
} // namespace detail
// The inventory belongs to one FS view, and is only active during synchronous
// startup. Unrelated filesystems and native positive/error probes are untouched.
inline bool esp32BootFileKnownAbsent(const void* filesystem, const char* path) {
const detail::Esp32BootAbsenceRegistry& registry = detail::esp32BootAbsenceRegistry();
return filesystem != nullptr && registry.owner == filesystem
&& registry.known_absent != nullptr
&& registry.known_absent(registry.context, path);
}
} // namespace mesh
+188
View File
@@ -0,0 +1,188 @@
#if defined(ESP32_PLATFORM)
#include "BootFileSystem.h"
#include "BootFilePresence.h"
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sdkconfig.h>
namespace mesh {
namespace {
constexpr size_t InventoryCapacity = 8192;
#if defined(CONFIG_SPIFFS_OBJ_NAME_LEN)
constexpr size_t MaximumPathLength = CONFIG_SPIFFS_OBJ_NAME_LEN - 1;
#else
constexpr size_t MaximumPathLength = 0;
#endif
Esp32BootFileSystem* active_inventory = nullptr;
// SPIFFS has flat names with implicit directories. Ambiguous path spellings
// must use the backend, which owns their interpretation.
bool normalPath(const char* path) {
if (path == nullptr || path[0] != '/' || path[1] == 0) return false;
const size_t length = strnlen(path, MaximumPathLength + 1);
if (length > MaximumPathLength || path[length - 1] == '/') return false;
const char* segment = path + 1;
for (const char* cursor = segment;; ++cursor) {
if (*cursor == '/' || *cursor == 0) {
const size_t count = cursor - segment;
if (count == 0 || (count == 1 && segment[0] == '.')
|| (count == 2 && segment[0] == '.' && segment[1] == '.')) return false;
if (*cursor == 0) return true;
segment = cursor + 1;
}
}
}
} // namespace
Esp32BootFileSystem::Delegate::Delegate(Esp32BootFileSystem& owner,
fs::FSImplPtr backend)
: owner_(owner), backend_(backend) {
if (backend_) mountpoint(backend_->mountpoint());
}
Esp32BootFileSystem::Esp32BootFileSystem(fs::FS& source)
: fs::FS(source), delegate_(*this, _impl) {
// Aliasing reuses the original shared_ptr control block; constructing the
// view requires no allocation. Its delegate has static lifetime in the app.
if (_impl) _impl = fs::FSImplPtr(_impl, &delegate_);
}
bool Esp32BootFileSystem::beginInventory() {
// Never rebuild after a mutation: a returned writable handle can continue
// changing the backend after open() has returned.
if (inventory_attempted_) return false;
inventory_attempted_ = true;
if (active_inventory != nullptr || MaximumPathLength < 2
|| delegate_.mountpoint() == nullptr
|| strcmp(delegate_.mountpoint(), "/spiffs") != 0) return false;
char* names = static_cast<char*>(::malloc(InventoryCapacity));
if (names == nullptr) return false;
DIR* directory = ::opendir(delegate_.mountpoint());
if (directory == nullptr) {
::free(names);
return false;
}
size_t used = 0;
bool complete = false;
while (true) {
errno = 0;
struct dirent* entry = ::readdir(directory);
if (entry == nullptr) {
complete = errno == 0;
break;
}
const size_t raw_length = strnlen(entry->d_name, sizeof(entry->d_name));
if (raw_length == 0 || raw_length == sizeof(entry->d_name)) break;
const char* name = entry->d_name;
if (name[0] == '/') ++name;
const size_t length = raw_length - (name != entry->d_name ? 1 : 0);
if (length == 0 || length + 1 > MaximumPathLength
|| length + 2 > InventoryCapacity - used) break;
names[used] = '/';
memcpy(names + used + 1, name, length + 1);
if (!normalPath(names + used)) break;
used += length + 2;
}
if (::closedir(directory) != 0) complete = false;
if (!complete) {
::free(names);
return false;
}
// Release the enumeration scratch before allocating persisted-state owners.
// An empty inventory needs no retained storage; a small one keeps only names.
if (used == 0) {
::free(names);
names = nullptr;
} else {
char* compact = static_cast<char*>(::realloc(names, used));
if (compact == nullptr) {
::free(names);
return false;
}
names = compact;
}
names_ = names;
names_used_ = used;
inventory_active_ = true;
active_inventory = this;
detail::Esp32BootAbsenceRegistry& registry = detail::esp32BootAbsenceRegistry();
registry.owner = static_cast<fs::FS*>(this);
registry.context = this;
registry.known_absent = &Esp32BootFileSystem::queryAbsent;
return true;
}
void Esp32BootFileSystem::endInventory() {
inventory_attempted_ = true;
inventory_active_ = false;
if (active_inventory == this) {
active_inventory = nullptr;
detail::Esp32BootAbsenceRegistry& registry = detail::esp32BootAbsenceRegistry();
registry = detail::Esp32BootAbsenceRegistry();
}
::free(names_);
names_ = nullptr;
names_used_ = 0;
}
void endEsp32BootFileInventory() {
if (active_inventory != nullptr) active_inventory->endInventory();
}
bool Esp32BootFileSystem::queryAbsent(const void* context, const char* path) {
return static_cast<const Esp32BootFileSystem*>(context)->knownAbsent(path);
}
bool Esp32BootFileSystem::knownAbsent(const char* path) const {
if (!inventory_active_ || !normalPath(path)) return false;
const size_t length = strlen(path);
for (size_t offset = 0; offset < names_used_;) {
const char* name = names_ + offset;
const size_t name_length = strlen(name);
// Exact filenames are case sensitive. Native SPIFFS directory prefix
// enumeration is case insensitive, so keep its virtual directories too.
if (strcmp(name, path) == 0
|| (name_length > length && name[length] == '/'
&& strncasecmp(name, path, length) == 0)) return false;
offset += name_length + 1;
}
return true;
}
fs::FileImplPtr Esp32BootFileSystem::Delegate::open(const char* path,
const char* mode, bool create) {
const bool readonly = mode != nullptr
&& (strcmp(mode, "r") == 0 || strcmp(mode, "rb") == 0) && !create;
if (!readonly) owner_.endInventory();
else if (owner_.knownAbsent(path)) return fs::FileImplPtr();
return backend_->open(path, mode, create);
}
bool Esp32BootFileSystem::Delegate::exists(const char* path) {
return !owner_.knownAbsent(path) && backend_->exists(path);
}
bool Esp32BootFileSystem::Delegate::rename(const char* from, const char* to) {
owner_.endInventory();
return backend_->rename(from, to);
}
bool Esp32BootFileSystem::Delegate::remove(const char* path) {
owner_.endInventory();
return backend_->remove(path);
}
bool Esp32BootFileSystem::Delegate::mkdir(const char* path) {
owner_.endInventory();
return backend_->mkdir(path);
}
bool Esp32BootFileSystem::Delegate::rmdir(const char* path) {
owner_.endInventory();
return backend_->rmdir(path);
}
} // namespace mesh
#endif
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#if defined(ESP32_PLATFORM)
#include <FS.h>
#include <FSImpl.h>
namespace mesh {
// This view must outlive every user of the filesystem (use static storage).
// Only known absence is cached; files and FileImpl handles stay SDK-owned.
class Esp32BootFileSystem : public fs::FS {
public:
explicit Esp32BootFileSystem(fs::FS& source);
~Esp32BootFileSystem() { endInventory(); }
Esp32BootFileSystem(const Esp32BootFileSystem&) = delete;
Esp32BootFileSystem& operator=(const Esp32BootFileSystem&) = delete;
bool beginInventory();
void endInventory();
bool isInventoryActive() const { return inventory_active_; }
private:
class Delegate : public fs::FSImpl {
public:
Delegate(Esp32BootFileSystem& owner, fs::FSImplPtr backend);
fs::FileImplPtr open(const char* path, const char* mode, bool create) override;
bool exists(const char* path) override;
bool rename(const char* from, const char* to) override;
bool remove(const char* path) override;
bool mkdir(const char* path) override;
bool rmdir(const char* path) override;
private:
Esp32BootFileSystem& owner_;
fs::FSImplPtr backend_;
};
static bool queryAbsent(const void* context, const char* path);
bool knownAbsent(const char* path) const;
Delegate delegate_;
char* names_ = nullptr;
size_t names_used_ = 0;
bool inventory_active_ = false;
bool inventory_attempted_ = false;
};
// Stop before starting any task that can access or modify persisted state.
void endEsp32BootFileInventory();
} // namespace mesh
#endif
+5
View File
@@ -7,6 +7,7 @@
#if defined(ESP32_PLATFORM)
#include <errno.h>
#include <sys/stat.h>
#include <helpers/esp32/BootFilePresence.h>
#endif
namespace mesh { namespace ota {
@@ -36,6 +37,10 @@ bool pathPresence(const char* path, bool& present) {
char vfs_path[48];
const int length = snprintf(vfs_path, sizeof(vfs_path), "/spiffs%s", path);
if (length < 0 || static_cast<size_t>(length) >= sizeof(vfs_path)) return false;
if (esp32BootFileKnownAbsent(settings_fs, path)) {
present = false;
return true;
}
struct stat info;
const int result = ::stat(vfs_path, &info);
if (result != 0 && errno != ENOENT) return false;