-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_network.cpp
More file actions
420 lines (375 loc) · 14.7 KB
/
Copy pathapp_network.cpp
File metadata and controls
420 lines (375 loc) · 14.7 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
#include "app_network.h"
#include "NetworkSetup.h"
#include <ESPAsyncWebServer.h>
#include <LittleFS.h>
#include <ArduinoJson.h>
#include "workout_manager.h"
#include "workout_storage.h"
#include "swim_machine.h"
#include "hub75.h"
#include "otapassword.h"
/* Internal singletons */
static AsyncWebServer g_server(80);
static AsyncEventSource g_sse("/events");
namespace AppNetwork
{
static const uint32_t maxJsonSize = 1024 * 8;
static const size_t kPSKLen = 10; // PSK = first 10 chars of OTA_PASSWORD
// Check PSK from header X-PSK (case-insensitive), or query/body param "psk"
static bool check_psk(AsyncWebServerRequest* r) {
auto getHeaderCaseInsensitive = [&](const char* name) -> String {
if (r->hasHeader(name)) {
auto* h = r->getHeader(name);
if (h) return h->value();
}
// Fallback: iterate headers and compare case-insensitively
for (size_t i = 0; i < r->headers(); ++i) {
auto* h = r->getHeader(i);
if (h && h->name().equalsIgnoreCase(name)) {
return h->value();
}
}
return String();
};
String psk = getHeaderCaseInsensitive("X-PSK");
if (psk.length() == 0) {
if (r->hasParam("psk")) {
psk = r->getParam("psk")->value();
} else if (r->hasParam("psk", true)) {
psk = r->getParam("psk", true)->value();
}
}
String expected10 = String(OTA_PASSWORD).substring(0, kPSKLen);
String expectedFull = String(OTA_PASSWORD);
if (psk != expected10 && psk != expectedFull) {
r->send(401, "text/plain", "unauthorized");
return false;
}
return true;
}
// Create intermediate directories for a given absolute path (/dir/sub/file)
static bool ensure_dirs(const String& absPath) {
int lastSlash = absPath.lastIndexOf('/');
if (lastSlash <= 0) return true;
String dir = absPath.substring(0, lastSlash);
if (dir.length() == 0) return true;
String partial;
int start = 0;
while (start < (int)dir.length()) {
int idx = dir.indexOf('/', start);
String chunk = (idx < 0) ? dir.substring(start) : dir.substring(start, idx);
if (chunk.length() > 0) {
partial += "/";
partial += chunk;
LittleFS.mkdir(partial);
}
if (idx < 0) break;
start = idx + 1;
}
return true;
}
// Normalize a user-provided path into absolute path under LittleFS root
static String sanitize_path(String in) {
in.replace("\\", "/");
while (in.startsWith("/")) in = in.substring(1);
in.replace("..", "");
String out = "/" + in;
return out;
}
// helper: send JSON
static void send_json(AsyncWebServerRequest *r, const String &js)
{
r->send(200, "application/json", js);
}
// helper: require ?id=
static bool require_id(AsyncWebServerRequest *r, String &id)
{
if (!r->hasParam("id"))
{
r->send(400, "text/plain", "missing id");
return false;
}
id = r->getParam("id")->value();
return true;
}
static void serve_index(AsyncWebServerRequest *req)
{
// When only SoftAP is active (no STA/Ethernet), redirect to Wi-Fi setup page
if (ConnectionManager::softApActive())
{
req->redirect("/wifi");
return;
}
if (LittleFS.exists("/index.html"))
req->send(LittleFS, "/index.html", "text/html");
else
req->send(200, "text/plain", "Upload index.html");
}
static void addCaptivePortalRoutes()
{
// Simple portal to set WiFi credentials while in SoftAP mode
g_server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest *req)
{
String html =
"<html><body><h1>Configure WiFi</h1>"
"<form action=\"/save\" method=\"POST\">"
"SSID: <input type=\"text\" name=\"ssid\"><br>"
"Password: <input type=\"password\" name=\"password\"><br>"
"<input type=\"submit\" value=\"Save\">"
"</form>"
"<p><a href=\"/index.html\">Open main interface</a></p><p>get w</p>"
"</body></html>";
req->send(200, "text/html", html); });
g_server.on("/save", HTTP_POST, [](AsyncWebServerRequest *req)
{
if (req->hasParam("ssid", true) && req->hasParam("password", true)) {
String ssid = req->getParam("ssid", true)->value();
String password = req->getParam("password", true)->value();
NetworkSetup::setNewWifiCredentials(ssid, password);
req->send(200, "text/html",
"<html><body><h1>Saved</h1></body></html>");
//delay(1000);
//ESP.restart();
} else {
req->send(400, "text/plain", "Missing SSID or password");
} });
}
void begin()
{
// Ensure SSE handler is present
g_server.addHandler(&g_sse);
// Always provide captive portal endpoints
addCaptivePortalRoutes();
// Routes owned here (LittleFS should already be mounted by WebUI::begin before calling this)
g_server.on("/run.html", HTTP_GET, [](AsyncWebServerRequest *req)
{
if (LittleFS.exists("/run.html"))
{
req->send(LittleFS, "/run.html", "text/html");
}
else
{
req->send(404, "text/plain", "Upload run.html");
} });
g_server.on("/status.html", HTTP_GET, [](AsyncWebServerRequest *req)
{
if (LittleFS.exists("/status.html"))
{
req->send(LittleFS, "/status.html", "text/html");
}
else
{
req->send(404, "text/plain", "Upload status.html");
} });
g_server.on("/settings.html", HTTP_GET, [](AsyncWebServerRequest *req)
{
if (LittleFS.exists("/settings.html"))
{
req->send(LittleFS, "/settings.html", "text/html");
}
else
{
req->send(404, "text/plain", "Upload settings.html");
} });
// Settings API: brightness get/set
g_server.on("/api/settings", HTTP_GET, [](AsyncWebServerRequest *r)
{
StaticJsonDocument<256> d;
d["brightness"] = HUB75_getBrightnessPercent();
d["screensaver_sec"] = HUB75_getScreensaverSec();
d["panel_mode"] = HUB75_getPanelMode(); // 0 = classic, 1 = big countdown
d["dry_run"] = AppSettings_getDryRun();
d["caps"] = AppSettings_getCaps();
d["hostname"] = NetworkSetup::getHostname(); // device name: <hostname>.local
// Capability flag: this firmware stores nested "set" items
// (repeat xN). Older firmware omits it, so the web UI can hide
// the set editor instead of silently corrupting sets.
d["sets"] = true;
String out; serializeJson(d, out);
send_json(r, out); });
g_server.on("/api/settings", HTTP_POST, [](AsyncWebServerRequest *r)
{ /* response sent in body handler */ },
nullptr,
[](AsyncWebServerRequest *r, uint8_t *data, size_t len, size_t index, size_t total)
{
static uint8_t g_buffer[maxJsonSize];
if (total > maxJsonSize) { r->send(413, "text/plain", "Too large"); return; }
memcpy(&g_buffer[index], data, len);
if (index + len < total) return;
StaticJsonDocument<128> d;
DeserializationError err = deserializeJson(d, g_buffer, total);
if (err) { r->send(400, "text/plain", "Bad JSON"); return; }
// Both fields are optional; apply whichever are present.
if (d.containsKey("brightness")) {
int b = d["brightness"] | -1;
if (b < 0 || b > 100) { r->send(400, "text/plain", "brightness 0..100"); return; }
HUB75_setBrightnessPercent((uint8_t)b);
}
if (d.containsKey("screensaver_sec")) {
long s = d["screensaver_sec"] | -1;
if (s < 0 || s > 86400) { r->send(400, "text/plain", "screensaver_sec 0..86400"); return; }
HUB75_setScreensaverSec((uint16_t)s);
}
if (d.containsKey("panel_mode")) {
int pm = d["panel_mode"] | -1;
if (pm != 0 && pm != 1) { r->send(400, "text/plain", "panel_mode 0 or 1"); return; }
HUB75_setPanelMode((uint8_t)pm);
}
if (d.containsKey("caps")) {
AppSettings_setCaps(d["caps"] | true);
}
if (d.containsKey("dry_run")) {
bool dr = d["dry_run"] | false;
AppSettings_setDryRun(dr);
SwimMachine::setDryRun(dr); // take effect immediately, even mid-run
}
// Renaming schedules a restart, so handle it after reading every
// other field and set the response before the device reboots.
bool renaming = false;
if (d.containsKey("hostname")) {
String hn = String((const char*)(d["hostname"] | ""));
if (hn.length() == 0) { r->send(400, "text/plain", "hostname empty"); return; }
NetworkSetup::setHostname(hn);
renaming = true;
}
StaticJsonDocument<256> resp;
resp["brightness"] = HUB75_getBrightnessPercent();
resp["screensaver_sec"] = HUB75_getScreensaverSec();
resp["panel_mode"] = HUB75_getPanelMode();
resp["dry_run"] = AppSettings_getDryRun();
resp["caps"] = AppSettings_getCaps();
resp["hostname"] = NetworkSetup::getHostname();
resp["restarting"] = renaming; // client should reconnect at the new name
String out; serializeJson(resp, out);
send_json(r, out);
});
// Raw body upload API: POST /api/upload?path=relative/sub/file [&psk=...]
// Body is the file bytes; supports subfolders.
g_server.on("/api/upload", HTTP_POST, [](AsyncWebServerRequest *r)
{ /* response sent in body handler */ },
nullptr,
[](AsyncWebServerRequest *r, uint8_t *data, size_t len, size_t index, size_t total)
{
if (!check_psk(r)) return;
if (!r->hasParam("path")) { r->send(400, "text/plain", "missing path"); return; }
String rel = r->getParam("path")->value();
String abs = sanitize_path(rel);
if (index == 0) {
ensure_dirs(abs);
File f = LittleFS.open(abs, "w");
if (!f) { r->send(500, "text/plain", "open failed"); return; }
size_t w = f.write(data, len);
f.close();
if (w != len) { r->send(500, "text/plain", "write failed"); return; }
} else {
File f = LittleFS.open(abs, "a");
if (!f) { r->send(500, "text/plain", "append open failed"); return; }
size_t w = f.write(data, len);
f.close();
if (w != len) { r->send(500, "text/plain", "append failed"); return; }
}
if (index + len >= total) {
StaticJsonDocument<128> d;
d["path"] = rel;
d["size"] = (uint32_t)total;
String out; serializeJson(d, out);
send_json(r, out);
}
});
g_server.on("/", HTTP_GET, serve_index);
// Same page under its explicit name: links/bookmarks to "/index.html"
// (e.g. Settings > Back to Editor) would otherwise 404.
g_server.on("/index.html", HTTP_GET, serve_index);
g_server.serveStatic("/static", LittleFS, "/static/");
// API: list IDs
g_server.on("/api/workouts", HTTP_GET, [](AsyncWebServerRequest *r)
{
StaticJsonDocument<256> d;
auto arr = d.to<JsonArray>();
for (auto id : WorkoutStorage::list_ids())
arr.add(id);
String out;
serializeJson(d, out);
send_json(r, out); });
// API: get one
g_server.on("/api/workout", HTTP_GET, [](AsyncWebServerRequest *r)
{
String id;
if (!require_id(r, id))
return;
Workout w;
if (!WorkoutStorage::load(id, w))
{
r->send(404);
return;
}
send_json(r, WorkoutStorage::to_json(w)); });
// API: save one
g_server.on("/api/workout", HTTP_POST, [](AsyncWebServerRequest *r)
{ r->send(200); },
nullptr,
[](AsyncWebServerRequest *r, uint8_t *data, size_t len, size_t index, size_t total)
{
static uint8_t g_buffer[maxJsonSize]; // for reading Json objects
if (total > maxJsonSize)
{
r->send(413, "text/plain", "Too large");
return;
} // 413 Payload Too Large
memcpy(&g_buffer[index], data, len);
if (index + len < total) // more coming – return now
return;
Workout w;
if (!WorkoutStorage::from_json(g_buffer, total, w))
{
r->send(400);
return;
}
WorkoutStorage::save(w);
send_json(r, WorkoutStorage::to_json(w));
});
// API: delete one
g_server.on("/api/workout", HTTP_DELETE, [](AsyncWebServerRequest *r)
{
String id;
if (!require_id(r, id))
return;
if (!WorkoutStorage::erase(id))
{
r->send(404);
return;
}
r->send(200); });
// API: run only the specified workout
g_server.on("/api/run", HTTP_POST, [](AsyncWebServerRequest *r)
{
String id;
if (!require_id(r, id))
return;
if (!WorkoutManager::run(id))
{
r->send(404, "text/plain", "could not start workout");
return;
}
r->send(200, "text/plain", "OK"); });
// API: pause & stop
g_server.on("/api/pause", HTTP_POST, [](AsyncWebServerRequest *r)
{
WorkoutManager::pause();
r->send(200); });
g_server.on("/api/stop", HTTP_POST, [](AsyncWebServerRequest *r)
{
WorkoutManager::stop();
r->send(200); });
// Start server
g_server.begin();
}
bool connected()
{
return ConnectionManager::ethHasIp() || ConnectionManager::wifiHasIp();
}
void push_event(const char *e, const char *j)
{
g_sse.send(j, e);
}
} // namespace AppNetwork