-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmaRIWebServer.cpp
More file actions
425 lines (347 loc) · 11.6 KB
/
Copy pathSmaRIWebServer.cpp
File metadata and controls
425 lines (347 loc) · 11.6 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
#include "SmaRiWebServer.h"
#include "Config.h"
SmaRiWebServer::SmaRiWebServer(uint16_t port)
: _server(port) {}
void SmaRiWebServer::registerRoutes() {
_server.on("/health", HTTP_GET, [this]() {
if (!requireAuth()) return;
_server.send(200, "text/plain", "OK");
});
_server.on("/api/status", HTTP_GET, [this]() {
if (!requireAuth()) return;
if (_statusProvider) {
const String json = _statusProvider();
_server.send(200, "application/json", json);
} else {
_server.send(503, "application/json", "{\"error\":\"status provider not set\"}");
}
});
_server.on("/api/relay", HTTP_GET, [this]() {
if (!requireAuth()) return;
if (!_relayHandler) {
_server.send(503, "application/json", "{\"error\":\"handler not set\"}");
return;
}
if (!_server.hasArg("id")) {
_server.send(400, "application/json", "{\"error\":\"missing id\"}");
return;
}
uint8_t id = _server.arg("id").toInt();
uint32_t ms = _server.hasArg("ms") ? _server.arg("ms").toInt() : 0;
String error;
bool ok = _relayHandler(id, ms, error);
if (ok) {
_server.send(200, "application/json", "{\"result\":\"ok\"}");
} else {
_server.send(409, "application/json",
"{\"error\":\"" + error + "\"}");
}
});
_server.onNotFound([this]() {
_server.send(404, "text/plain", "Not Found");
});
_server.on("/api/log", HTTP_GET, [this]() {
if (!requireAuth()) return;
if (_logProvider) {
_server.send(200, "application/json", _logProvider());
} else {
_server.send(503, "application/json", "{\"error\":\"log provider not set\"}");
}
});
_server.on("/", HTTP_GET, [this]() {
if (!requireAuth()) return;
_server.send(200, "text/html", R"HTML(
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>SmaRI</title>
<style>
:root{
--bg: #0b0f14;
--card: #0f1622;
--border: #223045;
--text: #e6edf3;
--muted: #9aa7b6;
--good: #3ddc84;
--bad: #ff5d5d;
--btn: #1f2a3a;
--btnHover: #2a3a52;
--btnActive: #334a6b;
--shadow: rgba(0,0,0,.35);
--ring: rgba(125, 211, 252, .25);
}
* { box-sizing: border-box; }
body {
margin: 0;
padding: 18px;
font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
background: radial-gradient(1200px 600px at 20% -10%, #172033 0%, transparent 60%),
radial-gradient(900px 500px at 90% 0%, #1a2a3f 0%, transparent 55%),
var(--bg);
color: var(--text);
height: 100vh;
}
.wrap { max-width: 540px; margin: 0 auto; }
.card {
background: linear-gradient(180deg, rgba(255,255,255,.02), transparent 60%), var(--card);
border: 1px solid var(--border);
border-radius: 16px;
padding: 16px;
box-shadow: 0 10px 30px var(--shadow);
}
h2 { margin: 0 0 12px 0; font-size: 20px; letter-spacing: .2px; }
.sub { color: var(--muted); font-size: 12px; margin-top: -6px; margin-bottom: 12px; }
.row {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
border-radius: 12px;
border: 1px solid rgba(255,255,255,.04);
background: rgba(255,255,255,.02);
margin: 8px 0;
}
.label { color: var(--muted); font-size: 13px; }
.value { font-weight: 650; font-size: 13px; }
.pill {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 6px 10px;
border-radius: 999px;
border: 1px solid rgba(255,255,255,.08);
background: rgba(255,255,255,.03);
}
.ok { color: var(--good); }
.bad { color: var(--bad); }
.grid {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
margin-top: 12px;
}
button {
width: 100%;
padding: 14px 14px;
font-size: 16px;
font-weight: 650;
border-radius: 14px;
border: 1px solid rgba(255,255,255,.10);
background: linear-gradient(180deg, rgba(255,255,255,.05), rgba(255,255,255,.02));
color: var(--text);
cursor: pointer;
transition: transform .06s ease, background .15s ease, border-color .15s ease;
outline: none;
}
button:hover { background: rgba(255,255,255,.06); border-color: rgba(255,255,255,.18); }
button:active { transform: translateY(1px); background: rgba(255,255,255,.08); }
button:focus { box-shadow: 0 0 0 4px var(--ring); }
button:disabled {
opacity: .45;
cursor: not-allowed;
transform: none;
}
.msg {
margin-top: 12px;
color: var(--muted);
font-size: 12px;
min-height: 18px;
}
.spinner {
display: inline-block;
width: 11px;
height: 11px;
border: 2px solid rgba(255,255,255,.25);
border-top-color: rgba(255,255,255,.85);
border-radius: 50%;
animation: spin 0.8s linear infinite;
vertical-align: middle;
}
@keyframes spin { to { transform: rotate(360deg);} }
</style>
</head>
<body>
<div class="wrap">
<div class="card">
<h2>SmaRI Control</h2>
<div class="sub">Local web panel</div>
<div class="row">
<div class="label">Wi-Fi</div>
<div id="wifi" class="value pill">—</div>
</div>
<div class="row">
<div class="label">IP</div>
<div id="ip" class="value">—</div>
</div>
<div class="row">
<div class="label">RSSI</div>
<div id="rssi" class="value">—</div>
</div>
<div class="row">
<div class="label">Relay</div>
<div id="relay" class="value pill">—</div>
</div>
<div class="grid">
<button id="btn1" onclick="triggerRelay(1)">Driveway</button>
<button id="btn2" onclick="triggerRelay(2)">Pedestrian</button>
</div>
<div class="msg" id="msg"></div>
</div>
</div>
<script>
let busy = false;
function setBusy(isBusy, remainingMs) {
busy = isBusy;
document.getElementById('btn1').disabled = busy;
document.getElementById('btn2').disabled = busy;
const relayEl = document.getElementById('relay');
if (busy) {
relayEl.innerHTML = 'BUSY <span class="spinner"></span> ' + (remainingMs || 0) + ' ms';
} else {
relayEl.textContent = 'IDLE';
}
}
function setWifiPill(state) {
const el = document.getElementById('wifi');
const s = (state || '—').toString();
el.textContent = s;
// add color hint
el.classList.remove('ok', 'bad');
if (s === 'connected') el.classList.add('ok');
if (s === 'failed') el.classList.add('bad');
}
async function refreshStatus() {
try {
const r = await fetch('/api/status', { cache: 'no-store' });
const s = await r.json();
setWifiPill(s.wifi_state);
document.getElementById('ip').textContent = s.ip || '—';
document.getElementById('rssi').textContent = (s.rssi !== undefined) ? s.rssi : '—';
setBusy(!!s.relay_busy, s.relay_remaining_ms);
document.getElementById('msg').textContent = '';
} catch (e) {
document.getElementById('msg').innerHTML = '<span class="bad">Status error</span>';
}
}
async function triggerRelay(id) {
if (busy) return;
document.getElementById('msg').innerHTML = 'Sending... <span class="spinner"></span>';
try {
const r = await fetch('/api/relay?id=' + id, { cache: 'no-store' });
const t = await r.text();
if (r.ok) {
document.getElementById('msg').innerHTML = '<span class="ok">OK</span>';
} else {
document.getElementById('msg').innerHTML = '<span class="bad">Error:</span> ' + t;
}
} catch (e) {
document.getElementById('msg').innerHTML = '<span class="bad">Request failed</span>';
}
refreshStatus();
}
refreshStatus();
setInterval(refreshStatus, 5000);
</script>
</body>
</html>
)HTML");
});
}
void SmaRiWebServer::begin() {
if (_running) return;
registerRoutes();
_server.begin();
_running = true;
}
void SmaRiWebServer::end() {
if (!_running) return;
_server.stop(); // available on ESP32 WebServer
_running = false;
}
void SmaRiWebServer::loop() {
if (!_running) return;
_server.handleClient();
}
bool SmaRiWebServer::isRunning() const {
return _running;
}
void SmaRiWebServer::setStatusProvider(std::function<String()> provider) {
_statusProvider = provider;
}
void SmaRiWebServer::setRelayCommandHandler(
std::function<bool(uint8_t, uint32_t, String&)> handler
) {
_relayHandler = handler;
}
bool SmaRiWebServer::requireAuth(bool countFailure) {
if (!WEB_AUTH_ENABLED) {
return true;
}
const unsigned long now = millis();
// If lockout is active, block the request.
// isLockoutActive() also clears the lockout automatically when expired.
if (isLockoutActive(now)) {
_server.send(403, "text/plain", "Temporarily locked");
return false;
}
// Authentication success
if (_server.authenticate(WEB_USER, WEB_PASS)) {
_authFailures = 0;
_lastAuthFailureMs = 0;
return true;
}
// Authentication failure
if (countFailure) {
registerAuthFailure(now);
// If this failed attempt triggered the lockout, return locked immediately.
if (isLockoutActive(now)) {
_server.send(403, "text/plain", "Temporarily locked");
return false;
}
}
_server.requestAuthentication();
return false;
}
void SmaRiWebServer::setLogProvider(std::function<String()> provider) {
_logProvider = provider;
}
bool SmaRiWebServer::isLockoutActive(unsigned long now) {
if (!_lockoutActive) {
return false;
}
// Rollover-safe millis() comparison.
if ((unsigned long)(now - _lockoutStartedMs) >= WEB_AUTH_LOCKOUT_MS) {
clearLockout();
return false;
}
return true;
}
void SmaRiWebServer::startLockout(unsigned long now) {
_lockoutActive = true;
_lockoutStartedMs = now;
// Important: reset failures when lockout starts.
// Otherwise the first bad request after expiry would immediately lock again.
_authFailures = 0;
_lastAuthFailureMs = 0;
}
void SmaRiWebServer::clearLockout() {
_lockoutActive = false;
_lockoutStartedMs = 0;
// Important: after lockout expiry, start clean.
_authFailures = 0;
_lastAuthFailureMs = 0;
}
void SmaRiWebServer::registerAuthFailure(unsigned long now) {
// Forget old failed attempts after the configured window.
if (_authFailures > 0 &&
(unsigned long)(now - _lastAuthFailureMs) > WEB_AUTH_FAILURE_WINDOW_MS) {
_authFailures = 0;
}
_authFailures++;
_lastAuthFailureMs = now;
if (_authFailures >= WEB_AUTH_MAX_FAILURES) {
startLockout(now);
}
}