-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.cpp
More file actions
499 lines (421 loc) · 16.3 KB
/
Copy pathconfig.cpp
File metadata and controls
499 lines (421 loc) · 16.3 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#include "config.h"
#include <ArduinoJson.h>
#include <LittleFS.h>
#include <Preferences.h>
#include <esp_mac.h>
// NVS namespace for config backup (survives LittleFS wipes)
#define NVS_NAMESPACE "masstrap"
DeviceConfig cfg;
void setDefaults(DeviceConfig& c) {
c.configured = false;
c.version = CONFIG_VERSION;
memset(c.wifi_ssid, 0, sizeof(c.wifi_ssid));
memset(c.wifi_pass, 0, sizeof(c.wifi_pass));
strncpy(c.hostname, "masstrap", sizeof(c.hostname) - 1);
strncpy(c.network_mode, "wifi", sizeof(c.network_mode) - 1);
strncpy(c.role, "finish", sizeof(c.role) - 1);
// Derive default device ID from MAC address to avoid collisions
// when multiple devices all default to ID 1
uint8_t mac[6];
esp_efuse_mac_get_default(mac);
c.device_id = (mac[5] % 253) + 1; // 1-254 range
c.sensor_pin = 4;
c.sensor_pin_2 = 5; // Speed trap second sensor
c.led_pin = 2;
// Audio — disabled by default, I2S backend for backwards compatibility
c.audio_enabled = false;
strncpy(c.audio_backend, "i2s", sizeof(c.audio_backend) - 1);
c.i2s_bclk_pin = 15;
c.i2s_lrc_pin = 16;
c.i2s_dout_pin = 17;
c.audio_volume = 10;
c.dysv5w_tx_pin = 15; // Default UART TX to DY-SV5W RXD
c.dysv5w_busy_pin = 16; // Default BUSY (DY-SV5W I/O1, LOW = playing)
// LiDAR Sensor (TF-Luna UART) — disabled by default
c.lidar_enabled = false;
c.lidar_rx_pin = 39;
c.lidar_tx_pin = 38;
c.lidar_threshold_mm = 50;
// Speed Trap
c.sensor_spacing_m = 0.10f;
memset(c.peer_mac, 0, 6);
c.track_length_m = 2.0f;
c.scale_factor = 64;
memset(c.google_sheets_url, 0, sizeof(c.google_sheets_url));
memset(c.wled_host, 0, sizeof(c.wled_host));
c.wled_effect_idle = 0;
c.wled_effect_armed = 28;
c.wled_effect_racing = 49;
c.wled_effect_finished = 11;
// Regional / Display
strncpy(c.units, "imperial", sizeof(c.units) - 1); // Default: imperial (mph, ft) — US users
strncpy(c.timezone, "EST5EDT,M3.2.0,M11.1.0", sizeof(c.timezone) - 1); // Default: US Eastern
strncpy(c.ota_password, "admin", sizeof(c.ota_password) - 1);
// Viewer password — blank = open access (backwards compatible)
memset(c.viewer_password, 0, sizeof(c.viewer_password));
}
// Attempt to restore config from NVS backup (survives LittleFS wipes)
static bool loadConfigFromNVS() {
Preferences prefs;
if (!prefs.begin(NVS_NAMESPACE, true)) return false; // read-only
bool wasConfigured = prefs.getBool("configured", false);
String ssid = prefs.getString("wifi_ssid", "");
String pass = prefs.getString("wifi_pass", "");
String host = prefs.getString("hostname", "");
String role = prefs.getString("role", "");
prefs.end();
if (!wasConfigured || ssid.length() == 0) return false;
LOG.println("[CONFIG] Recovering from NVS backup!");
LOG.printf("[CONFIG] NVS: role=%s, ssid=%s, hostname=%s\n",
role.c_str(), ssid.c_str(), host.c_str());
// Populate cfg struct with NVS values
strncpy(cfg.wifi_ssid, ssid.c_str(), sizeof(cfg.wifi_ssid) - 1);
strncpy(cfg.wifi_pass, pass.c_str(), sizeof(cfg.wifi_pass) - 1);
strncpy(cfg.hostname, host.c_str(), sizeof(cfg.hostname) - 1);
strncpy(cfg.role, role.c_str(), sizeof(cfg.role) - 1);
cfg.configured = true;
// Persist recovered config back to LittleFS so next boot is clean
saveConfig();
LOG.println("[CONFIG] NVS recovery complete — config.json restored to LittleFS");
return true;
}
bool loadConfig() {
setDefaults(cfg);
if (!LittleFS.exists(CONFIG_FILE)) {
LOG.println("[CONFIG] No config file found on LittleFS");
// Try NVS backup before giving up
if (loadConfigFromNVS()) {
return true;
}
LOG.println("[CONFIG] No NVS backup either — genuinely unconfigured");
return false;
}
File file = LittleFS.open(CONFIG_FILE, "r");
if (!file) {
LOG.println("[CONFIG] Failed to open config file");
return false;
}
String json = file.readString();
file.close();
if (json.length() == 0) {
LOG.println("[CONFIG] Config file is empty (0 bytes)");
return false;
}
LOG.printf("[CONFIG] Read %d bytes from %s\n", json.length(), CONFIG_FILE);
// Try parsing — configFromJson populates cfg and returns cfg.configured
bool parseResult = configFromJson(json);
if (parseResult) {
// Parsed OK and configured=true — normal case
return true;
}
// configFromJson returned false. Two possible reasons:
// 1. JSON parse failed entirely (malformed file)
// 2. JSON parsed OK but "configured" flag was false/missing
//
// After uploadfs, OTA, or firmware upgrades, the config file may survive
// but lack the "configured":true flag (older firmware versions, manual
// edits, or the system.html save format changed). If we got valid
// fields out of the parse, recover automatically instead of dropping
// the user into setup mode.
//
// Recovery criteria: role is a known valid value AND wifi_ssid is non-empty.
// This is stronger than just checking hostname (which defaults to "masstrap")
// and prevents recovering a truly blank/default config.
bool hasValidRole = (strcmp(cfg.role, "start") == 0 ||
strcmp(cfg.role, "finish") == 0 ||
strcmp(cfg.role, "speedtrap") == 0);
bool hasWifiCreds = strlen(cfg.wifi_ssid) > 0;
bool hasHostname = strlen(cfg.hostname) > 0 && strcmp(cfg.hostname, "masstrap") != 0;
if (hasValidRole && (hasWifiCreds || hasHostname)) {
LOG.println("[CONFIG] Config file valid but 'configured' flag was false — auto-recovering");
LOG.printf("[CONFIG] role=%s, ssid=%s, hostname=%s\n", cfg.role, cfg.wifi_ssid, cfg.hostname);
cfg.configured = true;
saveConfig(); // Persist the fix so next boot is clean
return true;
}
LOG.println("[CONFIG] Config file parsed but insufficient data to auto-recover");
LOG.printf("[CONFIG] role='%s', ssid='%s', hostname='%s', configured=%d\n",
cfg.role, cfg.wifi_ssid, cfg.hostname, cfg.configured);
// Last resort: try NVS backup
setDefaults(cfg); // Reset to clean state before NVS attempt
if (loadConfigFromNVS()) {
return true;
}
return false;
}
bool saveConfig() {
String json = configToJson();
File file = LittleFS.open(CONFIG_FILE, "w");
if (!file) {
LOG.println("[CONFIG] Failed to open config file for writing");
return false;
}
file.print(json);
file.close();
LOG.println("[CONFIG] Config saved to LittleFS");
// Backup critical boot fields to NVS (survives LittleFS wipes from uploadfs)
Preferences prefs;
if (prefs.begin(NVS_NAMESPACE, false)) {
prefs.putString("wifi_ssid", cfg.wifi_ssid);
prefs.putString("wifi_pass", cfg.wifi_pass);
prefs.putString("hostname", cfg.hostname);
prefs.putString("role", cfg.role);
prefs.putBool("configured", cfg.configured);
prefs.end();
LOG.println("[CONFIG] NVS backup saved (wifi/role/hostname)");
}
return true;
}
bool isValidGPIO(uint8_t pin) {
if (pin > 48) return false;
for (int i = 0; i < GPIO_BLACKLIST_SIZE; i++) {
if (pin == GPIO_BLACKLIST[i]) return false;
}
return true;
}
bool validateConfig(const DeviceConfig& c) {
if (!isValidGPIO(c.sensor_pin)) {
LOG.printf("[CONFIG] Invalid sensor pin: %d\n", c.sensor_pin);
return false;
}
if (!isValidGPIO(c.led_pin)) {
LOG.printf("[CONFIG] Invalid LED pin: %d\n", c.led_pin);
return false;
}
if (c.sensor_pin == c.led_pin) {
LOG.println("[CONFIG] Sensor and LED pins cannot be the same");
return false;
}
if (c.device_id == 0) {
LOG.println("[CONFIG] Device ID must be > 0");
return false;
}
if (c.track_length_m <= 0 || c.track_length_m > 100) {
LOG.println("[CONFIG] Track length must be 0-100m");
return false;
}
if (c.scale_factor < 1 || c.scale_factor > 1000) {
LOG.println("[CONFIG] Scale factor must be 1-1000");
return false;
}
if (strlen(c.hostname) == 0) {
LOG.println("[CONFIG] Hostname cannot be empty");
return false;
}
if (strcmp(c.role, "start") != 0 && strcmp(c.role, "finish") != 0 &&
strcmp(c.role, "speedtrap") != 0 && strcmp(c.role, "display") != 0 &&
strcmp(c.role, "judge") != 0 && strcmp(c.role, "lights") != 0) {
LOG.printf("[CONFIG] Invalid role: %s\n", c.role);
return false;
}
return true;
}
String configToJson() {
StaticJsonDocument<2560> doc;
doc["configured"] = cfg.configured;
doc["version"] = cfg.version;
JsonObject network = doc.createNestedObject("network");
network["wifi_ssid"] = cfg.wifi_ssid;
network["wifi_pass"] = cfg.wifi_pass;
network["hostname"] = cfg.hostname;
network["mode"] = cfg.network_mode;
JsonObject device = doc.createNestedObject("device");
device["role"] = cfg.role;
device["id"] = cfg.device_id;
JsonObject pins = doc.createNestedObject("pins");
pins["sensor_pin"] = cfg.sensor_pin;
pins["sensor_pin_2"] = cfg.sensor_pin_2;
pins["led_pin"] = cfg.led_pin;
JsonObject audio = doc.createNestedObject("audio");
audio["enabled"] = cfg.audio_enabled;
audio["backend"] = cfg.audio_backend;
audio["bclk_pin"] = cfg.i2s_bclk_pin;
audio["lrc_pin"] = cfg.i2s_lrc_pin;
audio["dout_pin"] = cfg.i2s_dout_pin;
audio["volume"] = cfg.audio_volume;
audio["dysv5w_tx_pin"] = cfg.dysv5w_tx_pin;
audio["dysv5w_busy_pin"] = cfg.dysv5w_busy_pin;
JsonObject lidar = doc.createNestedObject("lidar");
lidar["enabled"] = cfg.lidar_enabled;
lidar["rx_pin"] = cfg.lidar_rx_pin;
lidar["tx_pin"] = cfg.lidar_tx_pin;
lidar["threshold_mm"] = cfg.lidar_threshold_mm;
JsonObject peer = doc.createNestedObject("peer");
peer["mac"] = formatMac(cfg.peer_mac);
JsonObject track = doc.createNestedObject("track");
track["length_m"] = cfg.track_length_m;
track["scale_factor"] = cfg.scale_factor;
track["sensor_spacing_m"] = cfg.sensor_spacing_m;
JsonObject integrations = doc.createNestedObject("integrations");
integrations["google_sheets_url"] = cfg.google_sheets_url;
integrations["wled_host"] = cfg.wled_host;
JsonObject wled_fx = integrations.createNestedObject("wled_effects");
wled_fx["idle"] = cfg.wled_effect_idle;
wled_fx["armed"] = cfg.wled_effect_armed;
wled_fx["racing"] = cfg.wled_effect_racing;
wled_fx["finished"] = cfg.wled_effect_finished;
JsonObject regional = doc.createNestedObject("regional");
regional["units"] = cfg.units;
regional["timezone"] = cfg.timezone;
JsonObject ota = doc.createNestedObject("ota");
ota["password"] = cfg.ota_password;
JsonObject auth = doc.createNestedObject("auth");
auth["viewer_password"] = cfg.viewer_password;
String output;
serializeJsonPretty(doc, output);
return output;
}
bool configFromJson(const String& json) {
StaticJsonDocument<2560> doc;
DeserializationError err = deserializeJson(doc, json);
if (err) {
LOG.printf("[CONFIG] JSON parse error: %s\n", err.c_str());
return false;
}
cfg.configured = doc["configured"] | false;
cfg.version = doc["version"] | CONFIG_VERSION;
JsonObject network = doc["network"];
if (network) {
strncpy(cfg.wifi_ssid, network["wifi_ssid"] | "", sizeof(cfg.wifi_ssid) - 1);
strncpy(cfg.wifi_pass, network["wifi_pass"] | "", sizeof(cfg.wifi_pass) - 1);
strncpy(cfg.hostname, network["hostname"] | "masstrap", sizeof(cfg.hostname) - 1);
strncpy(cfg.network_mode, network["mode"] | "wifi", sizeof(cfg.network_mode) - 1);
}
JsonObject device = doc["device"];
if (device) {
strncpy(cfg.role, device["role"] | "finish", sizeof(cfg.role) - 1);
cfg.device_id = device["id"] | 1;
}
JsonObject pins = doc["pins"];
if (pins) {
cfg.sensor_pin = pins["sensor_pin"] | 4;
cfg.sensor_pin_2 = pins["sensor_pin_2"] | 5;
cfg.led_pin = pins["led_pin"] | 2;
}
JsonObject audio = doc["audio"];
if (audio) {
cfg.audio_enabled = audio["enabled"] | false;
strncpy(cfg.audio_backend, audio["backend"] | "i2s", sizeof(cfg.audio_backend) - 1);
cfg.i2s_bclk_pin = audio["bclk_pin"] | 15;
cfg.i2s_lrc_pin = audio["lrc_pin"] | 16;
cfg.i2s_dout_pin = audio["dout_pin"] | 17;
cfg.audio_volume = audio["volume"] | 10;
cfg.dysv5w_tx_pin = audio["dysv5w_tx_pin"] | 15;
cfg.dysv5w_busy_pin = audio["dysv5w_busy_pin"] | 16;
}
JsonObject lidar = doc["lidar"];
if (!lidar) lidar = doc["tof"]; // Backwards-compatible with old config files
if (lidar) {
cfg.lidar_enabled = lidar["enabled"] | false;
cfg.lidar_rx_pin = lidar["rx_pin"] | lidar["sda_pin"] | 39;
cfg.lidar_tx_pin = lidar["tx_pin"] | lidar["scl_pin"] | 38;
cfg.lidar_threshold_mm = lidar["threshold_mm"] | 50;
}
JsonObject peer = doc["peer"];
if (peer) {
const char* macStr = peer["mac"] | "00:00:00:00:00:00";
parseMacString(macStr, cfg.peer_mac);
}
JsonObject track = doc["track"];
if (track) {
cfg.track_length_m = track["length_m"] | 2.0f;
cfg.scale_factor = track["scale_factor"] | 64;
cfg.sensor_spacing_m = track["sensor_spacing_m"] | 0.10f;
}
JsonObject integrations = doc["integrations"];
if (integrations) {
strncpy(cfg.google_sheets_url, integrations["google_sheets_url"] | "", sizeof(cfg.google_sheets_url) - 1);
strncpy(cfg.wled_host, integrations["wled_host"] | "", sizeof(cfg.wled_host) - 1);
JsonObject wled_fx = integrations["wled_effects"];
if (wled_fx) {
cfg.wled_effect_idle = wled_fx["idle"] | 0;
cfg.wled_effect_armed = wled_fx["armed"] | 28;
cfg.wled_effect_racing = wled_fx["racing"] | 49;
cfg.wled_effect_finished = wled_fx["finished"] | 11;
}
}
JsonObject regional = doc["regional"];
if (regional) {
strncpy(cfg.units, regional["units"] | "imperial", sizeof(cfg.units) - 1);
strncpy(cfg.timezone, regional["timezone"] | "EST5EDT,M3.2.0,M11.1.0", sizeof(cfg.timezone) - 1);
}
JsonObject ota = doc["ota"];
if (ota) {
strncpy(cfg.ota_password, ota["password"] | "admin", sizeof(cfg.ota_password) - 1);
}
JsonObject auth = doc["auth"];
if (auth) {
strncpy(cfg.viewer_password, auth["viewer_password"] | "", sizeof(cfg.viewer_password) - 1);
}
if (cfg.configured) {
LOG.printf("[CONFIG] Loaded: role=%s, hostname=%s, wifi=%s\n",
cfg.role, cfg.hostname, cfg.wifi_ssid);
}
return cfg.configured;
}
void resetConfig() {
LOG.println("[CONFIG] Factory reset - deleting config and rebooting");
LittleFS.remove(CONFIG_FILE);
LittleFS.remove("/runs.csv");
// Clear NVS backup too — full factory reset
Preferences prefs;
if (prefs.begin(NVS_NAMESPACE, false)) {
prefs.clear();
prefs.end();
LOG.println("[CONFIG] NVS backup cleared");
}
delay(1500); // Allow TCP stack to flush response before reboot
ESP.restart();
}
bool parseMacString(const char* macStr, uint8_t* macOut) {
if (!macStr || strlen(macStr) < 17) {
memset(macOut, 0, 6);
return false;
}
int values[6];
int matched = sscanf(macStr, "%x:%x:%x:%x:%x:%x",
&values[0], &values[1], &values[2],
&values[3], &values[4], &values[5]);
if (matched != 6) {
memset(macOut, 0, 6);
return false;
}
for (int i = 0; i < 6; i++) {
macOut[i] = (uint8_t)values[i];
}
return true;
}
String formatMac(const uint8_t* mac) {
char buf[18];
snprintf(buf, sizeof(buf), "%02X:%02X:%02X:%02X:%02X:%02X",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(buf);
}
void getMacSuffix(char* buf, size_t len) {
uint8_t mac[6];
esp_efuse_mac_get_default(mac);
snprintf(buf, len, "%02X%02X", mac[4], mac[5]);
}
void generateHostname(const char* role, const char* macSuffix, char* outBuf, size_t outLen) {
// Abbreviate "speedtrap" to "trap" — the speedtrap IS the trap
const char* abbrev = role;
if (strcmp(role, "speedtrap") == 0) abbrev = "trap";
// Configured devices get clean hostnames without MAC suffix:
// mass-finish, mass-start, mass-trap
// MAC suffix only used for unconfigured/unknown roles as a fallback
if (abbrev && strlen(abbrev) > 0) {
snprintf(outBuf, outLen, "%s-%s", HOSTNAME_PREFIX, abbrev);
} else {
snprintf(outBuf, outLen, "%s-%s", HOSTNAME_PREFIX, macSuffix);
}
// Force lowercase (mDNS convention)
for (size_t i = 0; i < strlen(outBuf); i++) {
outBuf[i] = tolower(outBuf[i]);
}
}
const char* getRoleEmoji(const char* role) {
if (strcmp(role, "finish") == 0) return "\xF0\x9F\x8F\x81"; // 🏁 checkered flag
if (strcmp(role, "start") == 0) return "\xF0\x9F\x9A\xA6"; // 🚦 traffic light
if (strcmp(role, "speedtrap") == 0) return "\xF0\x9F\x9A\x93"; // 🚓 police car
return "\xF0\x9F\x91\xAE"; // 👮 cop (setup/unknown)
}