-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_admin.py
More file actions
728 lines (624 loc) · 29.6 KB
/
Copy pathweb_admin.py
File metadata and controls
728 lines (624 loc) · 29.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
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
import network
import socket
import time
import json
import gc
from config_store import save_config
AP_SSID = "BFU_ACCESS_SETUP"
AP_PASSWORD = "12345678"
ap = network.WLAN(network.AP_IF)
sta = network.WLAN(network.STA_IF)
server = None
last_ip = ""
last_mode = "AP"
wifi_cache = []
web_message = ""
access_mode = "locked"
def set_access_mode(mode):
global access_mode
access_mode = mode
# Minimal CSS
_CSS = ("body{font-family:sans-serif;background:#111;color:#eee;margin:0;padding:10px}"
".top{display:flex;gap:6px;margin-bottom:10px}"
".top a{background:#1f1f1f;color:#eee;text-decoration:none;padding:8px 10px;border-radius:8px;font-size:13px}"
".top a.active{background:#00c853;color:#000}"
".card{background:#1f1f1f;border-radius:10px;padding:10px;margin-bottom:8px}"
"input,select,button{width:100%;padding:9px;margin:3px 0 8px;border-radius:8px;border:0;box-sizing:border-box}"
"button{background:#00c853;color:#000;font-weight:bold}"
".del{background:#ff5252}"
".small{color:#aaa;font-size:12px}"
".ok{color:#00c853;font-weight:bold}"
".bad{color:#ff5252;font-weight:bold}"
".msg{background:#263238}"
"summary{cursor:pointer}h2,h3{margin-top:0}label{color:#aaa;font-size:12px}"
".mb{display:block;background:#1f1f1f;color:#eee;text-decoration:none;padding:12px;border-radius:10px;margin-bottom:6px;font-weight:bold}"
".lk{padding:12px;border-radius:10px;margin-bottom:8px;font-weight:bold;font-size:15px}"
".lk.locked{background:#2a0a0a;color:#ff5252}"
".lk.granted{background:#0a2a0a;color:#00c853}"
".lk.denied{background:#2a0a0a;color:#ff7043}"
".ok-box{background:#0a2a0a;color:#00c853;border-radius:10px;padding:10px;margin-bottom:8px}")
def start_ap():
global last_ip, last_mode
ap.active(True)
time.sleep_ms(300)
try:
ap.config(essid=AP_SSID, password=AP_PASSWORD, channel=6, hidden=0, authmode=network.AUTH_WPA_WPA2_PSK)
except TypeError:
ap.config(essid=AP_SSID, password=AP_PASSWORD, channel=6, authmode=network.AUTH_WPA_WPA2_PSK)
time.sleep_ms(300)
print("[AP] active:", ap.active())
print("[AP] ifconfig:", ap.ifconfig())
last_ip = ap.ifconfig()[0]
print("[AP] ssid:", AP_SSID)
last_mode = "AP"
return last_ip
def stop_ap():
try:
ap.active(False)
except:
pass
def connect_sta(ssid, password, timeout_ms=12000, progress_cb=None, progress_from=28, progress_to=42):
global last_ip, last_mode
sta.active(True)
try:
sta.disconnect()
except:
pass
time.sleep_ms(500)
try:
sta.connect(ssid, password)
except OSError as e:
print("[WIFI] connect OSError:", e)
return False, ""
start = time.ticks_ms()
last_progress = -1
while time.ticks_diff(time.ticks_ms(), start) < timeout_ms:
if sta.isconnected():
if progress_cb:
progress_cb(progress_to, "WIFI", "CONNECTED")
last_ip = sta.ifconfig()[0]
last_mode = "STA"
return True, last_ip
if progress_cb:
elapsed = time.ticks_diff(time.ticks_ms(), start)
percent = progress_from + int((progress_to - progress_from) * elapsed / timeout_ms)
if percent > progress_to - 1:
percent = progress_to - 1
if percent != last_progress:
last_progress = percent
progress_cb(percent, "WIFI", "CONNECTING")
time.sleep_ms(250)
try:
sta.disconnect()
except:
pass
return False, ""
def start_network(config, progress_cb=None):
global last_ip, last_mode
if config.get("configured") and config.get("wifi_ssid"):
print("[NET] configured Wi-Fi found, trying STA")
if progress_cb:
progress_cb(26, "WIFI", "AP BACKUP")
start_ap()
ok, ip = connect_sta(
config.get("wifi_ssid"),
config.get("wifi_password"),
timeout_ms=12000,
progress_cb=progress_cb,
progress_from=28,
progress_to=42
)
if ok:
print("[NET] STA connected:", ip)
if progress_cb:
progress_cb(43, "WIFI", "READY")
time.sleep_ms(300)
stop_ap()
return "STA", ip
print("[NET] STA failed, AP stays ON")
last_mode = "AP"
last_ip = ap.ifconfig()[0]
if progress_cb:
progress_cb(43, "SETUP AP", "READY")
return "AP", last_ip
if progress_cb:
progress_cb(30, "SETUP AP", "STARTING")
ip = start_ap()
print("[NET] AP setup mode started:", ip)
if progress_cb:
progress_cb(43, "SETUP AP", "READY")
return "AP", ip
def url_decode(s):
data = bytearray()
i = 0
while i < len(s):
if s[i] == "+":
data.append(32)
i += 1
elif s[i] == "%" and i + 2 < len(s):
try:
data.append(int(s[i+1:i+3], 16))
i += 3
except:
data.append(ord(s[i]))
i += 1
else:
data.append(ord(s[i]))
i += 1
try:
return data.decode("utf-8")
except:
return ""
def html_escape(s):
if s is None:
return ""
s = str(s)
s = s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
return s
def parse_form(body):
data = {}
for part in body.split("&"):
if "=" in part:
k, v = part.split("=", 1)
data[url_decode(k)] = url_decode(v)
return data
def scan_wifi_before_ap():
global wifi_cache
print("[WIFI] startup/background scan disabled; use GET /api/scan")
return len(wifi_cache)
def send_str(client, s):
try:
data = s.encode()
view = memoryview(data)
pos = 0
while pos < len(data):
client.send(view[pos:pos+512])
pos += 512
except OSError:
print("[WEB] send error")
raise
def h200():
return "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nConnection: close\r\n\r\n"
def json_resp(data):
return "HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n" + json.dumps(data)
def redirect(loc="/"):
return "HTTP/1.1 303 See Other\r\nLocation: {}\r\nConnection: close\r\n\r\n".format(loc)
def init_server():
global server
print("[WEB] binding server on 0.0.0.0:80")
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(addr)
server.listen(3)
server.setblocking(False)
print("[WEB] server ready")
def uid_owner_index(config, uid):
if not uid:
return -1
for i, u in enumerate(config.get("users", [])):
if u.get("uid") == uid:
return i
return -1
def get_last_uid(config, current_uid):
if current_uid:
return current_uid
logs = config.get("scan_logs", [])
return logs[0].get("uid", "") if logs else ""
def page_head(client, title, active):
nav_h = "active" if active == "home" else ""
nav_s = "active" if active == "settings" else ""
send_str(client, h200())
send_str(client, '<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>')
send_str(client, html_escape(title))
send_str(client, '</title><style>')
send_str(client, _CSS)
send_str(client, '</style></head><body><h2>BFU Access</h2><div class="top">')
send_str(client, '<a class="{}" href="/">Головна</a>'.format(nav_h))
send_str(client, '<a class="{}" href="/settings">Налаштування</a>'.format(nav_s))
send_str(client, '</div>')
if web_message:
send_str(client, '<div class="card msg">{}</div>'.format(html_escape(web_message)))
def page_foot(client):
send_str(client, '</body></html>')
def _mode_cls(m):
return "granted" if m == "granted" else ("denied" if m == "denied" else "locked")
def _mode_txt(m):
return "ДОСТУП ДОЗВОЛЕНО" if m == "granted" else ("ДОСТУП ЗАБОРОНЕНО" if m == "denied" else "ДОСТУП ЗАКРИТО")
def _device_time():
try:
t = time.localtime()
return "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(t[0],t[1],t[2],t[3],t[4],t[5])
except:
return ""
def api_status(config, current_uid):
logs = config.get("scan_logs", [])
uid = current_uid or (logs[0].get("uid", "") if logs else "")
owner_idx = uid_owner_index(config, uid)
return {
"access_mode": access_mode,
"last_uid": uid,
"last_uid_assigned": owner_idx >= 0,
"last_uid_owner": config["users"][owner_idx].get("name", "") if owner_idx >= 0 else "",
"scan_logs": logs[:3]
}
def api_wifi():
return {"networks": wifi_cache}
def api_scan():
global wifi_cache
all_networks = {}
try:
sta.active(True)
time.sleep_ms(1200)
for attempt in range(3):
nets = sta.scan()
for n in nets:
try:
raw = n[0]
ssid = raw.decode("utf-8") if isinstance(raw, (bytes, bytearray)) else str(raw)
ssid = ssid.strip()
rssi = int(n[3])
ch = int(n[2])
auth = int(n[4])
except:
continue
print("[SCAN]", ssid, "RSSI", rssi, "CH", ch, "AUTH", auth)
if not ssid:
continue
prev = all_networks.get(ssid)
if prev is None or rssi > prev["rssi"]:
all_networks[ssid] = {
"ssid": ssid,
"rssi": rssi,
"ch": ch,
"auth": auth
}
time.sleep_ms(700)
except Exception as e:
print("[WIFI] scan error:", e)
result = list(all_networks.values())
result.sort(key=lambda x: x["rssi"], reverse=True)
wifi_cache = [n["ssid"] for n in result]
return {"ok": True, "networks": result}
# HOME — safe polling, 1 fetch at a time
def send_home(client, config):
gc.collect()
page_head(client, "BFU Access", "home")
send_str(client, '<div class="card"><h3>Стан системи</h3>')
send_str(client, '<span class="small">Режим: {} | IP: {} | Wi-Fi: {} | Користувачів: {}</span></div>'.format(
html_escape(last_mode), html_escape(last_ip),
html_escape(config.get("wifi_ssid", "")), len(config.get("users", []))))
cls = _mode_cls(access_mode)
txt = _mode_txt(access_mode)
send_str(client, '<div id="ak" class="lk {}"><span id="at">{}</span></div>'.format(cls, txt))
send_str(client, '<h3>Події <a href="/logs" style="font-size:12px;color:#aaa">[всі]</a></h3>')
send_str(client, '<div id="sl">')
for e in config.get("scan_logs", [])[:3]:
c = "ok" if e.get("allowed") else "bad"
send_str(client, '<div class="card"><span class="small {}">{} | UID: {} | {}</span></div>'.format(
c, html_escape(e.get("name", "")), html_escape(e.get("uid", "")), html_escape(e.get("time", ""))))
if not config.get("scan_logs"):
send_str(client, '<div class="card"><span class="small">Немає подій.</span></div>')
send_str(client, '</div>')
# Safe polling: only 1 fetch at a time, busy flag prevents overlap
send_str(client, '<script>')
send_str(client, 'function eh(t){return t?String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"):"";}')
send_str(client, 'var AM={locked:"ДОСТУП ЗАКРИТО",granted:"ДОСТУП ДОЗВОЛЕНО",denied:"ДОСТУП ЗАБОРОНЕНО"};')
send_str(client, 'var busy=false;')
send_str(client, 'function upd(){if(busy)return;busy=true;')
send_str(client, 'fetch("/api/status").then(r=>r.json()).then(d=>{')
send_str(client, 'var m=d.access_mode||"locked";')
send_str(client, 'document.getElementById("ak").className="lk "+m;')
send_str(client, 'document.getElementById("at").textContent=AM[m]||AM.locked;')
send_str(client, 'var h="",s=d.scan_logs;for(var i=0;i<s.length;i++){var e=s[i],c=e.allowed?"ok":"bad";')
send_str(client, 'h+=\'<div class="card"><span class="small \'+c+\'">\'+eh(e.name)+\' | UID: \'+eh(e.uid)+\' | \'+eh(e.time)+\'</span></div>\';}')
send_str(client, 'if(!h)h=\'<div class="card"><span class="small">Немає подій.</span></div>\';')
send_str(client, 'document.getElementById("sl").innerHTML=h;')
send_str(client, '}).catch(()=>{}).finally(()=>{busy=false;});}')
send_str(client, 'setInterval(upd,1500);upd();')
send_str(client, '</script>')
page_foot(client)
# SETTINGS
def send_settings(client, config):
gc.collect()
page_head(client, "Налаштування", "settings")
send_str(client, '<div class="card"><h3>Налаштування</h3></div>')
send_str(client, '<a class="mb" href="/wifi">Wi-Fi</a>')
send_str(client, '<a class="mb" href="/users">Користувачі</a>')
send_str(client, '<a class="mb" href="/logs">Журнал подій</a>')
send_str(client, '<div class="card"><h3>Дата та час</h3>')
send_str(client, '<p class="small">Час пристрою: {}</p>'.format(_device_time()))
send_str(client, '<form method="POST" action="/set_time">')
send_str(client, '<label>Дата</label><input name="date" type="date">')
send_str(client, '<label>Формат часу</label><select name="time_format"><option value="24">24 години</option><option value="12">12 годин (AM/PM)</option></select>')
send_str(client, '<label>Час</label><input name="time_val" type="time">')
send_str(client, '<button>Зберегти час</button></form></div>')
send_str(client, '<div class="card"><h3>Скидання</h3>')
send_str(client, '<form method="POST" action="/reset"><button class="del">Скинути Wi-Fi та журнал</button></form></div>')
page_foot(client)
# WIFI
def send_wifi(client, config):
gc.collect()
page_head(client, "Wi-Fi", "settings")
send_str(client, '<a class="mb" href="/settings">← Назад</a>')
if last_mode == "STA" and last_ip:
send_str(client, '<div class="ok-box"><b>Wi-Fi підключено</b><br><span class="small">IP: {}</span></div>'.format(html_escape(last_ip)))
send_str(client, '<div class="card"><span class="small">Режим: {} | IP: {} | Мережа: {}</span></div>'.format(
html_escape(last_mode), html_escape(last_ip), html_escape(config.get("wifi_ssid", ""))))
send_str(client, '<div class="card"><form method="POST" action="/wifi">')
if last_mode == "AP":
send_str(client, '<p class="small">Setup Mode активний. Оберіть мережу зі списку або введіть SSID вручну.</p>')
send_str(client, '<label>Мережа зі списку</label>')
send_str(client, '<select id="ss"><option value="">Сканування...</option></select>')
send_str(client, '<label>SSID (введіть вручну)</label>')
send_str(client, '<input id="sm" name="ssid" placeholder="Назва Wi-Fi">')
send_str(client, '<p class="small">Після вибору зі списку SSID автоматично копіюється в поле.</p>')
send_str(client, '<label>Пароль</label>')
send_str(client, '<input name="password" type="password" placeholder="Пароль">')
send_str(client, '<button>Підключити</button></form>')
send_str(client, '<p class="small">Новий IP зявиться на OLED.</p></div>')
send_str(client, '<script>')
send_str(client, 'function esc(s){return String(s||"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\"/g,""");}')
send_str(client, 'function scan(){fetch("/api/scan").then(r=>r.json()).then(d=>{var ss=document.getElementById("ss");if(!ss)return;ss.innerHTML="";')
send_str(client, 'if(!d.networks||!d.networks.length){ss.innerHTML=\'<option value="">Мережі не знайдено</option>\';return;}')
send_str(client, 'ss.innerHTML=\'<option value="">Оберіть мережу...</option>\';d.networks.forEach(function(n){var o=document.createElement("option");o.value=n.ssid;o.text=esc(n.ssid)+" ("+n.rssi+" dBm ch"+n.ch+")";ss.appendChild(o);});')
send_str(client, '}).catch(function(){var ss=document.getElementById("ss");if(ss){ss.innerHTML=\'<option value="">Мережі не знайдено</option>\';}});}')
send_str(client, 'var ss=document.getElementById("ss"),sm=document.getElementById("sm");if(ss&&sm){ss.addEventListener("change",function(){if(ss.value)sm.value=ss.value;});}')
send_str(client, 'scan();')
send_str(client, '</script>')
page_foot(client)
# USERS — safe polling for UID input
def send_users(client, config, current_uid):
gc.collect()
last_uid = get_last_uid(config, current_uid)
owner = uid_owner_index(config, last_uid)
page_head(client, "Користувачі", "settings")
send_str(client, '<a class="mb" href="/settings">← Назад</a>')
send_str(client, '<div class="card"><h3>Привязка ключа</h3>')
if last_uid:
if owner >= 0:
send_str(client, '<p class="small">Ключ вже привязаний: {} — {}</p>'.format(
html_escape(last_uid), html_escape(config["users"][owner].get("name", ""))))
else:
send_str(client, '<p class="small">Новий ключ: {}</p>'.format(html_escape(last_uid)))
send_str(client, '<form method="POST" action="/assign_uid"><input type="hidden" name="uid" value="{}">'.format(html_escape(last_uid)))
send_str(client, '<label>Користувач</label><select name="index">')
for i, u in enumerate(config.get("users", [])):
send_str(client, '<option value="{}">{}</option>'.format(i, html_escape(u.get("name", ""))))
send_str(client, '</select><button>Привязати</button></form>')
else:
send_str(client, '<p class="small">Проскануй NFC ключ.</p>')
send_str(client, '</div>')
send_str(client, '<div class="card"><h3>Додати користувача</h3><form method="POST" action="/add_user">')
send_str(client, '<label>Імʼя (до 5 букв)</label><input name="name" maxlength="5">')
send_str(client, '<label>PIN</label><input name="pin">')
send_str(client, '<label>NFC UID</label><input id="ui" name="uid" value="{}">'.format(html_escape(last_uid or "")))
send_str(client, '<button>Додати</button></form></div>')
send_str(client, '<h3>Список</h3>')
for i, u in enumerate(config.get("users", [])):
nm = html_escape(u.get("name", ""))
pn = html_escape(u.get("pin", ""))
ud = html_escape(u.get("uid", ""))
send_str(client, '<details class="card"><summary><b>{}</b> <span class="small">PIN:{} UID:{}</span></summary>'.format(nm, pn, ud or "немає"))
send_str(client, '<form method="POST" action="/edit_user"><input type="hidden" name="index" value="{}">'.format(i))
send_str(client, '<label>Імʼя</label><input name="name" maxlength="5" value="{}">'.format(nm))
send_str(client, '<label>PIN</label><input name="pin" value="{}">'.format(pn))
send_str(client, '<label>UID</label><input name="uid" value="{}">'.format(ud))
send_str(client, '<button>Зберегти</button></form>')
send_str(client, '<form method="POST" action="/delete_user"><input type="hidden" name="index" value="{}"><button class="del">Видалити</button></form>'.format(i))
send_str(client, '</details>')
# Safe polling: 1 fetch at a time, only update UID input
send_str(client, '<script>var busy=false;')
send_str(client, 'function upd(){if(busy)return;busy=true;')
send_str(client, 'fetch("/api/status").then(r=>r.json()).then(d=>{')
send_str(client, 'if(d.last_uid)document.getElementById("ui").value=d.last_uid;')
send_str(client, '}).catch(()=>{}).finally(()=>{busy=false;});}')
send_str(client, 'setInterval(upd,4000);upd();</script>')
page_foot(client)
# LOGS — static, no live update
def send_logs(client, config):
gc.collect()
page_head(client, "Журнал", "settings")
send_str(client, '<a class="mb" href="/settings">← Назад</a>')
send_str(client, '<h3>Журнал подій</h3>')
logs = config.get("scan_logs", [])[:10]
if not logs:
send_str(client, '<div class="card"><span class="small">Немає подій.</span></div>')
else:
for e in logs:
c = "ok" if e.get("allowed") else "bad"
send_str(client, '<div class="card"><b class="{}">{}</b><br>'.format(c, html_escape(e.get("status", ""))))
send_str(client, '<span class="small">UID: {}</span><br>'.format(html_escape(e.get("uid", ""))))
send_str(client, '<span class="small">USER: {}</span><br>'.format(html_escape(e.get("name", ""))))
send_str(client, '<span class="small">TIME: {}</span></div>'.format(html_escape(e.get("time", ""))))
page_foot(client)
def poll_web(config, current_uid_getter, oled_callback=None):
global last_ip, last_mode, web_message
if server is None:
return config
try:
client, addr = server.accept()
print("[WEB] client connected:", addr)
except:
return config
try:
client.settimeout(0.5)
request = client.recv(1024).decode()
if not request:
client.close()
return config
first_line = request.split("\r\n")[0]
parts = first_line.split(" ")
if len(parts) < 2:
client.close()
return config
method = parts[0]
path = parts[1].split("?")[0]
body = request.split("\r\n\r\n", 1)[1] if "\r\n\r\n" in request else ""
if method == "GET" and path == "/":
send_home(client, config)
elif method == "GET" and path == "/settings":
send_settings(client, config)
elif method == "GET" and path == "/wifi":
send_wifi(client, config)
elif method == "GET" and path == "/users":
send_users(client, config, current_uid_getter())
elif method == "GET" and path == "/logs":
send_logs(client, config)
elif method == "GET" and path == "/api/status":
gc.collect()
client.send(json_resp(api_status(config, current_uid_getter())).encode())
elif method == "GET" and path == "/api/wifi":
gc.collect()
client.send(json_resp(api_wifi()).encode())
elif method == "GET" and path == "/api/scan":
gc.collect()
client.send(json_resp(api_scan()).encode())
elif method == "POST" and path == "/set_time":
form = parse_form(body)
date_str = form.get("date", "")
time_str = form.get("time_val", "")
try:
import machine
pd = date_str.split("-")
pt = time_str.split(":")
hour = int(pt[0])
minute = int(pt[1]) if len(pt) > 1 else 0
rtc = machine.RTC()
rtc.datetime((int(pd[0]), int(pd[1]), int(pd[2]), 0, hour, minute, 0, 0))
web_message = "Час встановлено: {} {:02d}:{:02d}".format(date_str, hour, minute)
except Exception as e:
web_message = "Помилка часу."
print("[TIME] error:", e)
client.send(redirect("/settings").encode())
elif method == "POST" and path == "/wifi":
form = parse_form(body)
ssid = form.get("ssid", "") or form.get("sm", "") or form.get("ssid_manual", "")
password = form.get("password", "")
if not ssid:
web_message = "Введіть SSID."
client.send(redirect("/wifi").encode())
else:
send_str(client, h200())
send_str(client, '<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Підключення</title><style>')
send_str(client, _CSS)
send_str(client, '</style></head><body><h2>Підключення до Wi-Fi...</h2>')
send_str(client, '<div class="card"><p>Якщо AP зникне — відкрийте новий IP з OLED.</p></div></body></html>')
try:
client.close()
except:
pass
if oled_callback:
oled_callback("ПІДКЛЮЧЕННЯ", ssid[:16], "ЗАЧЕКАЙТЕ", "")
ok, ip = connect_sta(ssid, password)
if ok:
config["wifi_ssid"] = ssid
config["wifi_password"] = password
config["configured"] = True
save_config(config)
last_ip = ip
last_mode = "STA"
stop_ap()
web_message = "Wi-Fi OK: {}".format(ip)
if oled_callback:
oled_callback("WIFI ГОТОВО", "ВІДКРИЙ IP", ip, "")
else:
start_ap()
web_message = "Wi-Fi помилка. Перевір SSID або пароль."
if oled_callback:
oled_callback("WIFI ПОМИЛКА", "SETUP MODE", AP_SSID, ap.ifconfig()[0])
return config
elif method == "POST" and path == "/add_user":
form = parse_form(body)
name = form.get("name", "").strip()[:5]
pin = form.get("pin", "")
uid = form.get("uid", "")
if uid:
owner = uid_owner_index(config, uid)
if owner >= 0:
web_message = "UID вже привязаний: {}".format(config["users"][owner].get("name", ""))
client.send(redirect("/users").encode())
client.close()
return config
if name and (pin or uid):
config["users"].append({"name": name, "pin": pin, "uid": uid})
config["configured"] = True
save_config(config)
web_message = "Додано."
client.send(redirect("/users").encode())
elif method == "POST" and path == "/assign_uid":
form = parse_form(body)
uid = form.get("uid", "")
try:
index = int(form.get("index", "-1"))
except:
index = -1
if not uid:
web_message = "Проскануй NFC."
elif index < 0 or index >= len(config.get("users", [])):
web_message = "Користувача не знайдено."
else:
owner = uid_owner_index(config, uid)
if owner >= 0 and owner != index:
web_message = "UID вже привязаний."
else:
config["users"][index]["uid"] = uid
save_config(config)
web_message = "Привязано."
client.send(redirect("/users").encode())
elif method == "POST" and path == "/edit_user":
form = parse_form(body)
try:
index = int(form.get("index", "-1"))
if 0 <= index < len(config.get("users", [])):
uid = form.get("uid", "")
owner = uid_owner_index(config, uid)
if uid and owner >= 0 and owner != index:
web_message = "UID вже привязаний."
else:
config["users"][index]["name"] = form.get("name", "").strip()[:5]
config["users"][index]["pin"] = form.get("pin", "")
config["users"][index]["uid"] = uid
save_config(config)
web_message = "Оновлено."
except:
web_message = "Помилка."
client.send(redirect("/users").encode())
elif method == "POST" and path == "/delete_user":
form = parse_form(body)
try:
index = int(form.get("index", "-1"))
if 0 <= index < len(config.get("users", [])):
config["users"].pop(index)
save_config(config)
web_message = "Видалено."
except:
web_message = "Помилка."
client.send(redirect("/users").encode())
elif method == "POST" and path == "/reset":
config["configured"] = False
config["wifi_ssid"] = ""
config["wifi_password"] = ""
config["scan_logs"] = []
save_config(config)
ip = start_ap()
web_message = "Скинуто."
if oled_callback:
oled_callback("SETUP MODE", "ПІДКЛЮЧИСЬ", AP_SSID, ip)
client.send(redirect("/settings").encode())
else:
client.send("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n<h2>404</h2>".encode())
except OSError:
print("[WEB] client error")
except Exception as e:
print("[WEB] error:", e)
try:
client.send("HTTP/1.1 500 Error\r\nConnection: close\r\n\r\n<h2>Error</h2>".encode())
except:
pass
try:
client.close()
except:
pass
gc.collect()
return config