-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlumen_config_manager.cpp
More file actions
382 lines (312 loc) · 9.64 KB
/
Copy pathlumen_config_manager.cpp
File metadata and controls
382 lines (312 loc) · 9.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#include "lumen_config_manager.h"
#include <Preferences.h>
#include <esp_err.h>
#include <esp_log.h>
#include <esp_mac.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <stdio.h>
#include <string.h>
#include "lumen_system_utils.h"
#include "lumen_type_validation.h"
namespace {
static const char* TAG = "config_manager";
static const char* NVS_NAMESPACE = "lumen";
static const char* KEY_RUNTIME_CFG = "runtime_cfg";
static const char* KEY_ENERGY_WH = "energy_wh";
struct PersistedRuntimeConfig {
char device_id[DEVICE_ID_MAX_LEN];
uint8_t mode;
uint8_t reserved[3];
ThresholdConfig thresholds;
LedState led;
};
// catch struct layout changes at compile time if these fire, the blob format
// has shifted and previously persisted configs will read back as garbage
static_assert(sizeof(LedState) == 8, "LedState layout changed, NVS blob will break");
static_assert(sizeof(ThresholdConfig) == 16, "ThresholdConfig layout changed, NVS blob will break");
static_assert(
sizeof(PersistedRuntimeConfig) == 52,
"PersistedRuntimeConfig layout changed, NVS blob will break"
);
static Preferences preferences;
static RuntimeConfig runtime_config = {};
static bool is_initialized = false;
static bool has_nvs = false;
static StaticSemaphore_t config_mutex_storage;
static SemaphoreHandle_t config_mutex = nullptr;
bool ensureConfigMutex() {
if (config_mutex != nullptr) {
return true;
}
config_mutex = xSemaphoreCreateMutexStatic(&config_mutex_storage);
return config_mutex != nullptr;
}
void lockConfig() {
if (ensureConfigMutex()) {
xSemaphoreTake(config_mutex, portMAX_DELAY);
}
}
void unlockConfig() {
if (config_mutex != nullptr) {
xSemaphoreGive(config_mutex);
}
}
ThresholdConfig buildDefaultThresholds() {
ThresholdConfig thresholds = {};
thresholds.temp_min_c = 18.0f;
thresholds.temp_max_c = 28.0f;
thresholds.humidity_min_pct = 60.0f;
thresholds.humidity_max_pct = 80.0f;
return thresholds;
}
LedState buildDefaultLedState() {
LedState led = {};
led.power = true;
led.brightness_pct = 50U;
led.red_enabled = true;
led.blue_enabled = true;
led.far_red_enabled = true;
led.red_dist_pct = 40U;
led.blue_dist_pct = 35U;
led.far_red_dist_pct = 25U;
return led;
}
bool generateDeviceId(char* out_device_id, size_t out_len) {
uint8_t base_mac[6] = {};
const esp_err_t read_result = esp_read_mac(base_mac, ESP_MAC_WIFI_STA);
if (read_result != ESP_OK) {
ESP_LOGE(TAG, "mac read failed: %s", esp_err_to_name(read_result));
return false;
}
const int written = snprintf(
out_device_id,
out_len,
"lumen-%02x%02x%02x%02x%02x%02x",
base_mac[0],
base_mac[1],
base_mac[2],
base_mac[3],
base_mac[4],
base_mac[5]
);
if (written <= 0 || static_cast<size_t>(written) >= out_len) {
ESP_LOGE(TAG, "device id build failed");
return false;
}
return true;
}
void applyDefaultConfig(RuntimeConfig& config) {
memset(&config, 0, sizeof(config));
config.mode = DeviceMode::AUTONOMOUS;
config.thresholds = buildDefaultThresholds();
config.led = buildDefaultLedState();
config.energy_total_wh = 0.0f;
if (!generateDeviceId(config.device_id, sizeof(config.device_id))) {
copyText(config.device_id, sizeof(config.device_id), "lumen-unknown");
}
}
DeviceMode sanitizeMode(uint8_t raw_mode) {
if (raw_mode == static_cast<uint8_t>(DeviceMode::MANUAL)) {
return DeviceMode::MANUAL;
}
return DeviceMode::AUTONOMOUS;
}
bool hasTextInBuffer(const char* text, size_t max_len) {
return (text != nullptr) && (strnlen(text, max_len) < max_len) && (text[0] != '\0');
}
bool writeRuntimeConfigBlob(const RuntimeConfig& config) {
if (!has_nvs) {
ESP_LOGW(TAG, "nvs unavailable");
return false;
}
if (!hasTextInBuffer(config.device_id, sizeof(config.device_id))) {
ESP_LOGW(TAG, "runtime config save rejected: bad device id");
return false;
}
if (!isThresholdConfigValid(config.thresholds) || !isLedStateValid(config.led)) {
ESP_LOGW(TAG, "runtime config save rejected: invalid payload");
return false;
}
PersistedRuntimeConfig persisted = {};
copyText(persisted.device_id, sizeof(persisted.device_id), config.device_id);
persisted.mode = static_cast<uint8_t>(config.mode);
persisted.thresholds = config.thresholds;
persisted.led = config.led;
const size_t written = preferences.putBytes(KEY_RUNTIME_CFG, &persisted, sizeof(persisted));
if (written != sizeof(persisted)) {
ESP_LOGE(TAG, "runtime config blob write failed");
return false;
}
return true;
}
bool writeEnergyTotal(float total_wh) {
if (!has_nvs) {
ESP_LOGW(TAG, "nvs unavailable");
return false;
}
if (!isEnergyTotalValid(total_wh)) {
ESP_LOGW(TAG, "energy save rejected");
return false;
}
const size_t written = preferences.putFloat(KEY_ENERGY_WH, total_wh);
if (written == 0U) {
ESP_LOGE(TAG, "energy write failed");
return false;
}
return true;
}
bool loadRuntimeConfigBlob(RuntimeConfig& config) {
PersistedRuntimeConfig persisted = {};
const size_t read_len = preferences.getBytes(KEY_RUNTIME_CFG, &persisted, sizeof(persisted));
if (read_len != sizeof(persisted)) {
return false;
}
if (hasTextInBuffer(persisted.device_id, sizeof(persisted.device_id))) {
copyText(config.device_id, sizeof(config.device_id), persisted.device_id);
} else {
ESP_LOGW(TAG, "invalid device id in blob, using default");
}
config.mode = sanitizeMode(persisted.mode);
if (isThresholdConfigValid(persisted.thresholds)) {
config.thresholds = persisted.thresholds;
} else {
ESP_LOGW(TAG, "invalid thresholds in blob, using default");
}
if (isLedStateValid(persisted.led)) {
config.led = persisted.led;
} else {
ESP_LOGW(TAG, "invalid led state in blob, using default");
}
return true;
}
void loadEnergyTotal(RuntimeConfig& config) {
const float stored = preferences.getFloat(KEY_ENERGY_WH, config.energy_total_wh);
if (isEnergyTotalValid(stored)) {
config.energy_total_wh = stored;
} else {
ESP_LOGW(TAG, "invalid energy total in nvs, using default");
}
}
} // namespace
namespace ConfigManager {
bool init() {
if (!ensureConfigMutex()) {
ESP_LOGE(TAG, "config mutex create failed");
return false;
}
lockConfig();
applyDefaultConfig(runtime_config);
has_nvs = preferences.begin(NVS_NAMESPACE, false);
if (!has_nvs) {
ESP_LOGE(TAG, "nvs open failed, running with defaults");
is_initialized = true;
unlockConfig();
return false;
}
loadRuntimeConfigBlob(runtime_config);
loadEnergyTotal(runtime_config);
is_initialized = true;
ESP_LOGI(TAG, "config loaded for %s", runtime_config.device_id);
unlockConfig();
return true;
}
bool loadDefaults() {
lockConfig();
applyDefaultConfig(runtime_config);
if (!has_nvs) {
ESP_LOGW(TAG, "defaults applied in ram only");
unlockConfig();
return false;
}
bool ok = writeRuntimeConfigBlob(runtime_config);
ok &= writeEnergyTotal(runtime_config.energy_total_wh);
unlockConfig();
return ok;
}
RuntimeConfig getConfigSnapshot() {
RuntimeConfig snapshot = {};
lockConfig();
snapshot = runtime_config;
unlockConfig();
return snapshot;
}
bool saveThresholds(const ThresholdConfig& thresholds) {
if (!isThresholdConfigValid(thresholds)) {
ESP_LOGW(TAG, "threshold save rejected");
return false;
}
lockConfig();
RuntimeConfig next = runtime_config;
next.thresholds = thresholds;
if (!writeRuntimeConfigBlob(next)) {
unlockConfig();
return false;
}
runtime_config.thresholds = thresholds;
unlockConfig();
return true;
}
bool saveMode(DeviceMode mode) {
lockConfig();
RuntimeConfig next = runtime_config;
next.mode = mode;
if (!writeRuntimeConfigBlob(next)) {
unlockConfig();
return false;
}
runtime_config.mode = mode;
unlockConfig();
return true;
}
bool saveLedState(const LedState& led) {
if (!isLedStateValid(led)) {
ESP_LOGW(TAG, "led save rejected");
return false;
}
lockConfig();
RuntimeConfig next = runtime_config;
next.led = led;
if (!writeRuntimeConfigBlob(next)) {
unlockConfig();
return false;
}
runtime_config.led = led;
unlockConfig();
return true;
}
bool saveEnergyTotal(float total_wh) {
if (!isEnergyTotalValid(total_wh)) {
ESP_LOGW(TAG, "energy save rejected");
return false;
}
lockConfig();
if (!writeEnergyTotal(total_wh)) {
unlockConfig();
return false;
}
runtime_config.energy_total_wh = total_wh;
unlockConfig();
return true;
}
bool saveRuntimeConfig(const RuntimeConfig& config) {
if (!isThresholdConfigValid(config.thresholds) || !isLedStateValid(config.led)) {
ESP_LOGW(TAG, "runtime config save rejected: invalid payload");
return false;
}
lockConfig();
RuntimeConfig next = runtime_config;
next.mode = config.mode;
next.thresholds = config.thresholds;
next.led = config.led;
if (!writeRuntimeConfigBlob(next)) {
unlockConfig();
return false;
}
runtime_config.mode = next.mode;
runtime_config.thresholds = next.thresholds;
runtime_config.led = next.led;
unlockConfig();
return true;
}
} // namespace ConfigManager