-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebInterface.cpp
More file actions
656 lines (603 loc) · 27.3 KB
/
Copy pathWebInterface.cpp
File metadata and controls
656 lines (603 loc) · 27.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
/*
* WebInterface.cpp — async HTTP + WebSocket control surface.
* See include/net/WebInterface.hpp.
*
* Routes:
* GET / static UI from SPIFFS (index.html, app.css, app.js, logo.svg)
* GET /api/v1/status cached reactor + wifi + system status JSON
* POST /api/v1/run {action:"start"|"stop", targetC, rpm, durationMin}
* POST /api/v1/setpoint {targetC?, rpm?} (live changes)
* POST /api/v1/disc {rpm?, currentMa?, microsteps?, direction?, enabled?}
* GET /api/v1/wifi/scan cached scan results (also triggers a fresh scan)
* POST /api/v1/wifi/connect {ssid, password}
* POST /api/v1/wifi/forget
* GET /api/v1/log download the latest run's CSV (alias for the newest /runs file)
* POST /api/v1/log/interval {seconds} set the SD log row interval (1..3600)
* GET /api/v1/calibration returns cached calibration state (method, calibrated, points)
* POST /api/v1/calibration/point {referenceC}; queues capture of a calibration point (live NTC resistance)
* POST /api/v1/calibration/compute queues fit (offset/Beta/Steinhart by point count); result via GET
* POST /api/v1/calibration/reset queues revert to factory Beta
* POST /api/v1/disc/test brief disc jog to confirm the drive turns (~8 rpm, 3 s)
* POST /api/v1/sd/erase erase ALL files on the SD card, then recreate the log
* WS /ws telemetry push
*/
#include "net/WebInterface.hpp"
#include <AsyncJson.h>
#include "net/EspNowResponder.hpp"
#include <ESPAsyncWebServer.h>
#include <FS.h>
#include <SD.h>
#include <SPIFFS.h>
#include <memory>
#include <string.h>
#include "app_config.hpp"
#include "features/control/Reactor.hpp"
#include "net/WifiManager.hpp"
#include "storage/SdLogger.hpp"
#include "storage/RunFiles.hpp"
WebInterface::WebInterface(Reactor& reactor, WifiManager& wifi, SdLogger& sd,
const Config& config)
: reactor_(reactor), wifi_(wifi), sd_(sd), cfg_(config) {
mutex_ = xSemaphoreCreateMutex();
}
void WebInterface::begin() {
if (!SPIFFS.begin(true)) {
Serial.println("[WEB] SPIFFS mount failed");
} else {
Serial.printf("[WEB] SPIFFS mounted, index.html %s\n",
SPIFFS.exists("/index.html") ? "found" : "MISSING (run uploadfs)");
}
server_ = new AsyncWebServer(cfg_.port);
ws_ = new AsyncWebSocket("/ws");
registerRoutes();
server_->begin();
Serial.printf("[WEB] server up on port %u\n", cfg_.port);
}
static void sendJson(AsyncWebServerRequest* req, const String& body) {
AsyncWebServerResponse* resp = req->beginResponse(200, "application/json", body);
resp->addHeader("Access-Control-Allow-Origin", "*");
req->send(resp);
}
static void sendOk(AsyncWebServerRequest* req) { sendJson(req, "{\"ok\":true}"); }
static void sendError(AsyncWebServerRequest* req, int status, const char* code,
const char* msg) {
String body = String("{\"ok\":false,\"error\":{\"code\":\"") + code +
"\",\"message\":\"" + msg + "\"}}";
AsyncWebServerResponse* resp = req->beginResponse(status, "application/json", body);
resp->addHeader("Access-Control-Allow-Origin", "*");
req->send(resp);
}
// Stream "header line + roughly the last `rows` rows" of a run CSV as a chunked
// response. Rows are estimated at kTailRowBytes; seek that far back from the end
// and drop the (likely partial) line at the seek point. The open File lives in a
// shared_ptr captured by the chunk callback, so it closes with the response —
// including on client disconnect. Runs on the async task, same as the full-file
// req->send(SD, ...) path.
static void sendCsvTail(AsyncWebServerRequest* req, const String& path, uint32_t rows) {
static constexpr uint32_t kTailRowBytes = 96; // generous per-row estimate
struct TailCtx {
File file;
String head; // header line + '\n', replayed before the tail bytes
size_t headSent = 0;
};
auto ctx = std::make_shared<TailCtx>();
ctx->file = SD.open(path, FILE_READ);
if (!ctx->file) {
sendError(req, 404, "not_found", "no such run");
return;
}
ctx->head = ctx->file.readStringUntil('\n') + "\n";
const size_t size = ctx->file.size();
const uint64_t back = (uint64_t)rows * kTailRowBytes;
const bool truncated = back < size;
if (truncated) {
ctx->file.seek(size - (size_t)back);
ctx->file.readStringUntil('\n'); // discard the partial line at the seek point
} // else: window covers the whole file — position is already just past the header
AsyncWebServerResponse* resp = req->beginChunkedResponse(
"text/csv", [ctx](uint8_t* buf, size_t maxLen, size_t) -> size_t {
size_t n = 0;
while (n < maxLen && ctx->headSent < ctx->head.length())
buf[n++] = (uint8_t)ctx->head[ctx->headSent++];
if (n < maxLen && ctx->file)
n += ctx->file.read(buf + n, maxLen - n);
return n; // 0 = end of response
});
resp->addHeader("Access-Control-Allow-Origin", "*");
// Lets the UI distinguish "this is a window" from "this was the whole file"
// (the cached runs-list bytes are stale for the live run).
resp->addHeader("X-Tail-Truncated", truncated ? "1" : "0");
req->send(resp);
}
// Returns true (and sends 503 feature_disabled) when the feature is off; the
// caller then returns. Keeps each gated handler to a single guard line.
static bool featureGate(AsyncWebServerRequest* req, bool enabled) {
if (enabled) return false;
sendError(req, 503, "feature_disabled", "feature disabled at build time");
return true;
}
// Copy a sanitized session name into a fixed buffer (firmware is authoritative).
static void copySanitizedName(char* dst, size_t dstSize, const String& raw) {
const std::string s = RunFiles::sanitizeName(std::string(raw.c_str()), dstSize - 1);
strncpy(dst, s.c_str(), dstSize - 1);
dst[dstSize - 1] = '\0';
}
void WebInterface::registerRoutes() {
// ── WebSocket ──
ws_->onEvent([this](AsyncWebSocket*, AsyncWebSocketClient* client,
AwsEventType type, void*, uint8_t*, size_t) {
if (type == WS_EVT_CONNECT) {
xSemaphoreTake(mutex_, portMAX_DELAY);
const String snapshot = statusJson_;
xSemaphoreGive(mutex_);
client->text(snapshot);
}
});
server_->addHandler(ws_);
// ── GET status ──
server_->on("/api/v1/status", HTTP_GET, [this](AsyncWebServerRequest* req) {
xSemaphoreTake(mutex_, portMAX_DELAY);
const String body = statusJson_;
xSemaphoreGive(mutex_);
sendJson(req, body);
});
// ── GET wifi scan ──
server_->on("/api/v1/wifi/scan", HTTP_GET, [this](AsyncWebServerRequest* req) {
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.wifiScan = true;
const String body = scanJson_;
xSemaphoreGive(mutex_);
sendJson(req, body);
});
// ── POST run ──
auto* runHandler = new AsyncCallbackJsonWebHandler(
"/api/v1/run", [this](AsyncWebServerRequest* req, JsonVariant& json) {
JsonObject o = json.as<JsonObject>();
const String action = o["action"] | "";
if (action == "start") {
const float rpm = o["rpm"] | 8.0f;
const float targetC = o["targetC"] | 36.0f;
if (rpm < 0.0f || rpm > 30.0f) { // kMinRpm..kMaxRpm
sendError(req, 400, "out_of_range", "rpm must be 0..30");
return;
}
if (targetC < 0.0f || targetC > 55.0f) { // processMaxC ceiling
sendError(req, 400, "out_of_range", "targetC must be 0..55");
return;
}
const String name = o["name"] | "";
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.runStart = true;
pending_.runTargetC = targetC;
pending_.runRpm = rpm;
pending_.runDurMin = o["durationMin"] | 0;
copySanitizedName(pending_.runName, sizeof(pending_.runName), name);
xSemaphoreGive(mutex_);
sendOk(req);
} else if (action == "stop") {
const String data = o["data"] | "save";
if (data != "save" && data != "discard") {
sendError(req, 400, "invalid_request", "data must be save|discard");
return;
}
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.runStop = true;
pending_.runStopSave = (data == "save");
xSemaphoreGive(mutex_);
sendOk(req);
} else {
sendError(req, 400, "invalid_request", "action must be start|stop");
}
});
server_->addHandler(runHandler);
// ── POST setpoint (live targetC / rpm) ──
auto* setHandler = new AsyncCallbackJsonWebHandler(
"/api/v1/setpoint", [this](AsyncWebServerRequest* req, JsonVariant& json) {
JsonObject o = json.as<JsonObject>();
if (!o["targetC"].isNull()) {
const float targetC = o["targetC"].as<float>();
if (targetC < 0.0f || targetC > 55.0f) { // processMaxC ceiling
sendError(req, 400, "out_of_range", "targetC must be 0..55");
return;
}
}
xSemaphoreTake(mutex_, portMAX_DELAY);
if (!o["targetC"].isNull()) {
pending_.setTarget = true;
pending_.setTargetC = o["targetC"].as<float>();
}
if (!o["rpm"].isNull()) {
pending_.setRpm = true;
pending_.setRpmVal = o["rpm"].as<float>();
}
xSemaphoreGive(mutex_);
sendOk(req);
});
server_->addHandler(setHandler);
// ── POST disc/test (timed motor jog) ──
// Registered BEFORE /api/v1/disc: the JSON handler for "/api/v1/disc" also
// prefix-matches "/api/v1/disc/test", so the specific route must come first.
server_->on("/api/v1/disc/test", HTTP_POST, [this](AsyncWebServerRequest* req) {
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.motorTest = true;
xSemaphoreGive(mutex_);
sendOk(req);
});
// ── POST disc (drive params) ──
auto* discHandler = new AsyncCallbackJsonWebHandler(
"/api/v1/disc", [this](AsyncWebServerRequest* req, JsonVariant& json) {
JsonObject o = json.as<JsonObject>();
xSemaphoreTake(mutex_, portMAX_DELAY);
if (!o["rpm"].isNull()) { pending_.discRpm = true; pending_.discRpmVal = o["rpm"].as<float>(); }
if (!o["currentMa"].isNull()) { pending_.discCurrent = true; pending_.discCurrentMa = o["currentMa"].as<uint16_t>(); }
if (!o["microsteps"].isNull()){ pending_.discMicro = true; pending_.discMicrosteps = o["microsteps"].as<uint16_t>(); }
if (!o["direction"].isNull()) { pending_.discDir = true; pending_.discReverse = (o["direction"].as<String>() == "ccw"); }
if (!o["enabled"].isNull()) { pending_.discEnable = true; pending_.discEnableVal = o["enabled"].as<bool>(); }
xSemaphoreGive(mutex_);
sendOk(req);
});
server_->addHandler(discHandler);
// ── POST pid/autotune (start|cancel) ──
// Registered BEFORE /api/v1/pid: the plain JSON handler for "/api/v1/pid" also
// prefix-matches "/api/v1/pid/..." (no regex support), so the more specific
// route must come first or /pid would swallow /pid/autotune. First match wins.
auto* autotuneHandler = new AsyncCallbackJsonWebHandler(
"/api/v1/pid/autotune", [this](AsyncWebServerRequest* req, JsonVariant& json) {
if (featureGate(req, AppConfig::Features::kEnableAutotune)) return;
JsonObject o = json.as<JsonObject>();
const String action = o["action"] | "";
if (action != "start" && action != "cancel") {
sendError(req, 400, "invalid_request", "action must be start|cancel");
return;
}
// Idle guard: with no active run the heater loop never advances the
// tune — it would sit at 0% and time out "failed" mid-next-run.
if (action == "start" && !reactor_.running()) {
sendError(req, 409, "run_not_active", "start a run before autotune");
return;
}
xSemaphoreTake(mutex_, portMAX_DELAY);
if (action == "start") pending_.autotuneStart = true;
else pending_.autotuneCancel = true;
xSemaphoreGive(mutex_);
sendOk(req);
});
server_->addHandler(autotuneHandler);
// ── POST pid (gains + mode) ──
auto* pidHandler = new AsyncCallbackJsonWebHandler(
"/api/v1/pid", [this](AsyncWebServerRequest* req, JsonVariant& json) {
JsonObject o = json.as<JsonObject>();
xSemaphoreTake(mutex_, portMAX_DELAY);
if (!o["kp"].isNull() && !o["ki"].isNull() && !o["kd"].isNull()) {
pending_.pidGains = true;
pending_.pidKp = o["kp"].as<float>();
pending_.pidKi = o["ki"].as<float>();
pending_.pidKd = o["kd"].as<float>();
}
if (!o["mode"].isNull()) {
pending_.pidMode = true;
pending_.pidModeStr = o["mode"].as<String>();
}
xSemaphoreGive(mutex_);
sendOk(req);
});
server_->addHandler(pidHandler);
// ── GET calibration ──
server_->on("/api/v1/calibration", HTTP_GET, [this](AsyncWebServerRequest* req) {
xSemaphoreTake(mutex_, portMAX_DELAY);
const String body = calJson_;
xSemaphoreGive(mutex_);
sendJson(req, body);
});
// ── POST calibration/point ──
auto* calPointHandler = new AsyncCallbackJsonWebHandler(
"/api/v1/calibration/point", [this](AsyncWebServerRequest* req, JsonVariant& json) {
JsonObject o = json.as<JsonObject>();
if (o["referenceC"].isNull()) {
sendError(req, 400, "invalid_request", "referenceC required");
return;
}
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.calPoint = true;
pending_.calRefC = o["referenceC"].as<float>();
xSemaphoreGive(mutex_);
sendOk(req);
});
server_->addHandler(calPointHandler);
// ── POST calibration/compute ──
server_->on("/api/v1/calibration/compute", HTTP_POST, [this](AsyncWebServerRequest* req) {
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.calCompute = true;
xSemaphoreGive(mutex_);
sendOk(req);
});
// ── POST calibration/reset ──
server_->on("/api/v1/calibration/reset", HTTP_POST, [this](AsyncWebServerRequest* req) {
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.calReset = true;
xSemaphoreGive(mutex_);
sendOk(req);
});
// ── POST sd/erase ──
server_->on("/api/v1/sd/erase", HTTP_POST, [this](AsyncWebServerRequest* req) {
if (featureGate(req, AppConfig::Features::kEnableSdLogging)) return;
// Run guard: erasing mid-run would delete the LIVE run's file and leave the
// rest of the run unlogged (eraseAll discards the open run first).
if (reactor_.running()) {
sendError(req, 409, "run_active", "stop the run before erasing the card");
return;
}
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.sdErase = true;
xSemaphoreGive(mutex_);
sendOk(req);
});
// ── POST wifi connect ──
auto* wifiHandler = new AsyncCallbackJsonWebHandler(
"/api/v1/wifi/connect", [this](AsyncWebServerRequest* req, JsonVariant& json) {
JsonObject o = json.as<JsonObject>();
const String ssid = o["ssid"] | "";
if (ssid.isEmpty()) {
sendError(req, 400, "wifi_ssid_required", "ssid is required");
return;
}
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.wifiConnect = true;
pending_.wifiSsid = ssid;
pending_.wifiPass = o["password"] | "";
xSemaphoreGive(mutex_);
sendOk(req);
});
server_->addHandler(wifiHandler);
server_->on("/api/v1/wifi/forget", HTTP_POST, [this](AsyncWebServerRequest* req) {
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.wifiForget = true;
xSemaphoreGive(mutex_);
sendOk(req);
});
// ── SD log download: alias for the latest run's CSV ──
// Resolves the newest run id from the loop-built cache (NOT a live card
// enumeration) to keep this async handler off the SD bus; only the single
// file send touches the card, same as GET /runs/{id}.
server_->on("/api/v1/log", HTTP_GET, [this](AsyncWebServerRequest* req) {
if (featureGate(req, AppConfig::Features::kEnableSdLogging)) return;
if (!sd_.mounted()) {
sendError(req, 503, "no_log", "no SD card mounted");
return;
}
xSemaphoreTake(mutex_, portMAX_DELAY);
const int latest = latestRunId_;
xSemaphoreGive(mutex_);
if (latest <= 0) {
sendError(req, 503, "no_log", "no runs recorded yet");
return;
}
const String path = sd_.runCsvPath(latest);
if (!SD.exists(path)) {
sendError(req, 503, "no_log", "latest run file missing");
return;
}
req->send(SD, path, "text/csv", true);
});
// ── POST log interval (seconds between SD log rows) ──
auto* logIntervalHandler = new AsyncCallbackJsonWebHandler(
"/api/v1/log/interval", [this](AsyncWebServerRequest* req, JsonVariant& json) {
if (featureGate(req, AppConfig::Features::kEnableSdLogging)) return;
JsonObject o = json.as<JsonObject>();
if (o["seconds"].isNull()) {
sendError(req, 400, "invalid_request", "seconds required");
return;
}
const long s = o["seconds"].as<long>();
if (s < 1 || s > 3600) {
sendError(req, 400, "out_of_range", "seconds must be 1..3600");
return;
}
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.logInterval = true;
pending_.logIntervalSec = (uint32_t)s;
xSemaphoreGive(mutex_);
sendOk(req);
});
server_->addHandler(logIntervalHandler);
// ── Per-run routes ──
// IMPORTANT: register the specific /runs/<id> routes BEFORE the /runs list
// route. ESPAsyncWebServer's plain on("/api/v1/runs") also matches any URL that
// starts with "/api/v1/runs/" (built-in prefix matching), so if the list route
// came first it would swallow /api/v1/runs/<id> and return the list JSON instead
// of the CSV. First match wins, so the regex routes must be registered first.
// ── GET one run's CSV (download) ──
server_->on("^\\/api\\/v1\\/runs\\/([0-9]+)$", HTTP_GET,
[this](AsyncWebServerRequest* req) {
if (featureGate(req, AppConfig::Features::kEnableSdLogging)) return;
const int id = req->pathArg(0).toInt();
const String path = sd_.runCsvPath(id);
if (!sd_.mounted() || !SD.exists(path)) {
sendError(req, 404, "not_found", "no such run");
return;
}
// ?tail=N — header line + roughly the last N rows, so the UI can show a
// recent window without pulling a multi-day CSV off the card. Seeks back
// N * kTailRowBytes from the end and skips the first partial line.
if (req->hasParam("tail")) {
const long rows = req->getParam("tail")->value().toInt();
if (rows > 0) { sendCsvTail(req, path, (uint32_t)rows); return; }
}
req->send(SD, path, "text/csv", true);
});
// ── POST delete a run ──
server_->on("^\\/api\\/v1\\/runs\\/([0-9]+)\\/delete$", HTTP_POST,
[this](AsyncWebServerRequest* req) {
if (featureGate(req, AppConfig::Features::kEnableSdLogging)) return;
const int id = req->pathArg(0).toInt();
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.runDelete = true;
pending_.runDeleteId = id;
xSemaphoreGive(mutex_);
sendOk(req);
});
// ── GET runs list (served from the loop-built cache) ──
server_->on("/api/v1/runs", HTTP_GET, [this](AsyncWebServerRequest* req) {
if (featureGate(req, AppConfig::Features::kEnableSdLogging)) return;
xSemaphoreTake(mutex_, portMAX_DELAY);
const String body = runsJson_;
xSemaphoreGive(mutex_);
sendJson(req, body);
});
// ── POST espnow/pair (open the 60s allow-pairing window) ──
server_->on("/api/v1/espnow/pair", HTTP_POST, [this](AsyncWebServerRequest* req) {
if (featureGate(req, AppConfig::Features::kEnableEspNow)) return;
if (espnow_) espnow_->openPairWindow();
sendOk(req);
});
// ── POST espnow/forget (clear binding) ──
server_->on("/api/v1/espnow/forget", HTTP_POST, [this](AsyncWebServerRequest* req) {
if (featureGate(req, AppConfig::Features::kEnableEspNow)) return;
if (espnow_) espnow_->forget();
sendOk(req);
});
// ── POST espnow/recalibrate (ask the bound HUB to re-run its touch wizard) ──
server_->on("/api/v1/espnow/recalibrate", HTTP_POST, [this](AsyncWebServerRequest* req) {
if (featureGate(req, AppConfig::Features::kEnableEspNow)) return;
if (espnow_) espnow_->recalibrateHub();
sendOk(req);
});
// ── Static UI + SPA fallback ──
server_->serveStatic("/", SPIFFS, "/").setDefaultFile("index.html");
server_->onNotFound([](AsyncWebServerRequest* req) {
if (req->url().startsWith("/api/")) {
sendError(req, 404, "not_found", "unknown endpoint");
return;
}
if (SPIFFS.exists("/index.html")) {
req->send(SPIFFS, "/index.html", "text/html");
} else {
req->send(200, "text/html",
"<h1>Mini Reactor</h1><p>UI assets missing — run "
"<code>pio run -t uploadfs</code>.</p>");
}
});
}
void WebInterface::applyPending() {
Pending p;
xSemaphoreTake(mutex_, portMAX_DELAY);
p = pending_;
pending_ = Pending{};
xSemaphoreGive(mutex_);
// Log each triggered command to serial ([CMD]) for on-device debugging.
if (p.runStart) {
Serial.printf("[CMD] run start: target=%.1fC rpm=%.1f dur=%umin name='%s'\n",
p.runTargetC, p.runRpm, (unsigned)p.runDurMin, p.runName);
reactor_.start(p.runTargetC, p.runRpm, p.runDurMin);
if (AppConfig::Features::kEnableSdLogging && reactor_.running()) sd_.startRun(p.runName); // open the per-run file
}
if (p.runStop) {
Serial.printf("[CMD] run stop (%s)\n", p.runStopSave ? "save" : "discard");
reactor_.stop();
sd_.endRun(p.runStopSave);
}
if (p.runDelete) {
Serial.printf("[CMD] run delete id=%d\n", p.runDeleteId);
sd_.deleteRun(p.runDeleteId);
}
if (p.setTarget) { Serial.printf("[CMD] setpoint target=%.1fC\n", p.setTargetC); reactor_.setTargetC(p.setTargetC); }
if (p.setRpm) { Serial.printf("[CMD] setpoint rpm=%.1f\n", p.setRpmVal); reactor_.setRpm(p.setRpmVal); }
if (p.discRpm) { Serial.printf("[CMD] disc rpm=%.1f\n", p.discRpmVal); reactor_.setRpm(p.discRpmVal); }
if (p.discCurrent) { Serial.printf("[CMD] disc current=%umA\n", (unsigned)p.discCurrentMa); reactor_.setDiscCurrentMa(p.discCurrentMa); }
if (p.discMicro) { Serial.printf("[CMD] disc microsteps=%u\n", (unsigned)p.discMicrosteps); reactor_.setDiscMicrosteps(p.discMicrosteps); }
if (p.discDir) { Serial.printf("[CMD] disc direction=%s\n", p.discReverse ? "ccw" : "cw"); reactor_.setDiscReverse(p.discReverse); }
if (p.discEnable) { Serial.printf("[CMD] disc enable=%d\n", p.discEnableVal); reactor_.setDiscEnabled(p.discEnableVal); }
if (p.pidGains) { Serial.printf("[CMD] pid gains kp=%.4f ki=%.4f kd=%.4f\n", p.pidKp, p.pidKi, p.pidKd); reactor_.setPidGains(p.pidKp, p.pidKi, p.pidKd); }
if (p.pidMode) { Serial.printf("[CMD] pid mode=%s\n", p.pidModeStr.c_str()); reactor_.setPidMode(p.pidModeStr.c_str()); }
if (p.autotuneStart) { Serial.println("[CMD] autotune start"); reactor_.startAutotune(); }
if (p.autotuneCancel) { Serial.println("[CMD] autotune cancel"); reactor_.cancelAutotune(); }
if (p.calPoint) { Serial.printf("[CMD] calibration point ref=%.1fC\n", p.calRefC); reactor_.addCalibrationPoint(p.calRefC); }
if (p.calCompute) { Serial.println("[CMD] calibration compute"); reactor_.computeCalibration(); }
if (p.calReset) { Serial.println("[CMD] calibration reset"); reactor_.resetCalibration(); }
if (p.wifiConnect) { Serial.printf("[CMD] wifi connect ssid='%s'\n", p.wifiSsid.c_str()); wifi_.connect(p.wifiSsid, p.wifiPass); }
if (p.wifiForget) { Serial.println("[CMD] wifi forget"); wifi_.forget(); }
if (p.wifiScan) { Serial.println("[CMD] wifi scan requested"); wifi_.requestScan(); }
if (p.logInterval) { Serial.printf("[CMD] log interval=%us\n", (unsigned)p.logIntervalSec); sd_.setLogIntervalSec(p.logIntervalSec); }
if (p.sdErase) { Serial.println("[CMD] sd ERASE all files"); sd_.eraseAll(); }
if (p.motorTest) { Serial.println("[CMD] motor test jog"); reactor_.startMotorTest(); }
if (p.pauseCmd) {
if (p.pauseMode == 1) { Serial.println("[CMD] pause motor (B1)"); reactor_.setMotorPaused(true); }
else if (p.pauseMode == 2) { Serial.println("[CMD] pause all (B2)"); reactor_.setFullHold(true); }
else { Serial.println("[CMD] resume"); reactor_.setMotorPaused(false); reactor_.setFullHold(false); }
}
}
void WebInterface::cacheCalJson(const String& calJson) {
xSemaphoreTake(mutex_, portMAX_DELAY);
calJson_ = calJson;
xSemaphoreGive(mutex_);
}
void WebInterface::cacheRunsJson(const String& runsJson) {
xSemaphoreTake(mutex_, portMAX_DELAY);
runsJson_ = runsJson;
xSemaphoreGive(mutex_);
}
void WebInterface::cacheLatestRunId(int id) {
xSemaphoreTake(mutex_, portMAX_DELAY);
latestRunId_ = id;
xSemaphoreGive(mutex_);
}
void WebInterface::cmdRunStart(float targetC, float rpm, uint16_t durMin, const char* name) {
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.runStart = true;
pending_.runTargetC = targetC;
pending_.runRpm = rpm;
pending_.runDurMin = durMin;
copySanitizedName(pending_.runName, sizeof(pending_.runName), String(name ? name : ""));
xSemaphoreGive(mutex_);
}
void WebInterface::cmdRunStop(bool save) {
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.runStop = true;
pending_.runStopSave = save;
xSemaphoreGive(mutex_);
}
void WebInterface::cmdSetpoint(bool hasT, float targetC, bool hasR, float rpm) {
xSemaphoreTake(mutex_, portMAX_DELAY);
if (hasT) { pending_.setTarget = true; pending_.setTargetC = targetC; }
if (hasR) { pending_.setRpm = true; pending_.setRpmVal = rpm; }
xSemaphoreGive(mutex_);
}
void WebInterface::cmdDisc(bool hasRpm, float rpm, bool hasCur, uint16_t mA,
bool hasMicro, uint16_t micro, bool hasDir, bool reverse,
bool hasEn, bool en) {
xSemaphoreTake(mutex_, portMAX_DELAY);
if (hasRpm) { pending_.discRpm = true; pending_.discRpmVal = rpm; }
if (hasCur) { pending_.discCurrent = true; pending_.discCurrentMa = mA; }
if (hasMicro) { pending_.discMicro = true; pending_.discMicrosteps = micro; }
if (hasDir) { pending_.discDir = true; pending_.discReverse = reverse; }
if (hasEn) { pending_.discEnable = true; pending_.discEnableVal = en; }
xSemaphoreGive(mutex_);
}
void WebInterface::cmdDiscTest() {
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.motorTest = true;
xSemaphoreGive(mutex_);
}
void WebInterface::cmdPause(uint8_t mode) {
xSemaphoreTake(mutex_, portMAX_DELAY);
pending_.pauseCmd = true;
pending_.pauseMode = mode;
xSemaphoreGive(mutex_);
}
void WebInterface::update(const String& statusJson, const String& scanJson) {
xSemaphoreTake(mutex_, portMAX_DELAY);
statusJson_ = statusJson;
scanJson_ = scanJson;
xSemaphoreGive(mutex_);
applyPending();
const uint32_t now = millis();
if (ws_ && ws_->count() > 0 && now - lastPushMs_ >= cfg_.wsPushPeriodMs) {
lastPushMs_ = now;
// Broadcast ONLY when every client's TX queue has room. Pushing regardless
// piles frames a marginal link can't drain, exhausting the shared WiFi TX-
// buffer pool — which wedges BOTH the web UI and ESP-NOW (NO_MEM). Skipping a
// frame just drops one ~4Hz telemetry sample; the next carries fresh state.
if (ws_->availableForWriteAll()) ws_->textAll(statusJson);
}
if (ws_) ws_->cleanupClients();
}