10namespace fs = std::filesystem;
12static const char *
const TAG =
"preferences";
17 const char *prefdir = getenv(
"ESPHOME_PREFDIR");
18 std::string pref_path;
19 if (prefdir !=
nullptr) {
22 const char *home = getenv(
"HOME");
23 if (home ==
nullptr) {
24 ESP_LOGE(TAG,
"ESPHOME_PREFDIR and HOME environment variables not set, unable to save preferences");
27 pref_path = std::string(home) +
"/.esphome/prefs";
30 fs::create_directories(pref_path, ec);
32 ESP_LOGE(TAG,
"Failed to create preferences directory: %s (%s)", pref_path.c_str(), ec.message().c_str());
39 FILE *fp = fopen(this->
filename_.c_str(),
"rb");
44 if (fread(&key,
sizeof(key), 1, fp) != 1)
46 if (fread(&
len,
sizeof(
len), 1, fp) != 1)
49 if (fread(data,
sizeof(uint8_t),
len, fp) !=
len)
51 std::vector vec(data, data +
len);
52 this->
data_[key] = vec;
62 ESP_LOGE(TAG,
"Preferences filename not set, unable to save preferences");
65 FILE *fp = fopen(this->
filename_.c_str(),
"wb");
67 ESP_LOGE(TAG,
"Failed to open preferences file for writing: %s", this->
filename_.c_str());
71 for (
auto &it : this->
data_) {
72 fwrite(&it.first,
sizeof(
uint32_t), 1, fp);
73 uint8_t
len = it.second.size();
74 fwrite(&
len,
sizeof(
len), 1, fp);
75 fwrite(it.second.data(),
sizeof(uint8_t), it.second.size(), fp);
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
bool load(uint8_t *data, size_t len) const
bool save(const uint8_t *data, size_t len) const
bool load(uint32_t key, uint8_t *data, size_t len)
std::map< uint32_t, std::vector< uint8_t > > data_
bool save(uint32_t key, const uint8_t *data, size_t len)
ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)
HostPreferences * get_preferences()
HostPreferences * host_preferences
ESPPreferences * global_preferences
Application App
Global storage of Application pointer - only one Application can exist.