-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
1280 lines (1073 loc) · 40.4 KB
/
Copy pathapp.py
File metadata and controls
1280 lines (1073 loc) · 40.4 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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# app.py
import ui_html
import time
import socket
import ujson
import network
import wifi_prov
import neopixel
from machine import Pin, I2C
from pn532 import PN532_I2C
import encrypt
# -----------------------
# SETTINGS
# -----------------------
I2C_ID = 0
I2C_SCL = 8
I2C_SDA = 9
I2C_FREQ = 20000
PN532_ADDR = 0x24
# LED on Freenove is WS2812 on GPIO48 (NOT a simple LED).
LED_PIN = 48
DEBUG_ERRORS = True
# -----------------------
# TELEGRAM (ESP32 автономно)
# -----------------------
ENV_FILE = ".env"
TG_ENABLED = bool(encrypt.get_env_value(ENV_FILE, "TG_ENABLED"))
TG_BOT_TOKEN = encrypt.get_env_value(ENV_FILE, "TG_BOT_TOKEN")
TG_ADMIN_CHAT_ID = int(encrypt.get_env_value(ENV_FILE, "TG_ADMIN_CHAT_ID"))
TG_DEVICE_NAME = encrypt.get_env_value(ENV_FILE, "TG_DEVICE_NAME")
TG_POLL_EVERY_MS = int(encrypt.get_env_value(ENV_FILE, "TG_POLL_EVERY_MS"))
TG_NOTIFY_ON_TAP = bool(encrypt.get_env_value(ENV_FILE, "TG_NOTIFY_ON_TAP"))
ADMIN_TOKEN = encrypt.get_env_value(ENV_FILE, "ADMIN_TOKEN") or ""
# UI Basic Auth
UI_AUTH_ENABLED = bool(encrypt.get_env_value(ENV_FILE, "UI_AUTH_ENABLED"))
UI_USER = encrypt.get_env_value(ENV_FILE, "UI_USER") or ""
UI_PASS = encrypt.get_env_value(ENV_FILE, "UI_PASS") or ""
# ✅ Freenove BOOT button is GPIO0
BTN_PIN = 0
BTN_ACTIVE_LOW = True
PRESS_WINDOW_MS = 30000
PRESS_TARGET = 7
DEBOUNCE_MS = 180
HOLD_CLEAR_MS = 10000
NFC_POLL_TIMEOUT_MS = 80
NFC_LOOP_SLEEP_MS = 25
LOG_BTN = True
LOG_PORTAL = True
UIDS_FILE = "uids.json"
DEFAULT_UIDS_HEX = []
ALLOWED_UIDS = set()
ALLOWED_UIDS_HEX = set()
# ✅ NEW: Names storage
UID_NAME_BY_HEX = {} # "15 D6 14 06" -> "John"
DEFAULT_CARDS = [] # optional: [{"uid":"..","name":".."}]
LAST_UID_HEX = ""
LAST_ACCESS = ""
LAST_FW = ""
LAST_NAME = ""
EVENT_ID = 0
# -----------------------
# TIME / LOG
# -----------------------
def now_ms():
return time.ticks_ms()
def ms_diff(a, b):
return time.ticks_diff(a, b)
def op_ms(t0):
return ms_diff(time.ticks_ms(), t0)
def log(*args):
try:
print(*args)
except:
pass
def op_log(name, ms, extra=""):
try:
print("[OP]", name, ms, extra)
except:
pass
# -----------------------
# WS2812 (NeoPixel) helpers
# -----------------------
def _np_off(np):
try:
if np and hasattr(np, "write"):
np[0] = (0, 0, 0)
np.write()
except:
pass
def _np_set(np, color):
try:
if np and hasattr(np, "write"):
np[0] = color
np.write()
except:
pass
def breathe(np, color=(0, 60, 0), duration_ms=500, steps=18):
if np is None or (not hasattr(np, "write")):
return
try:
half_steps = max(6, steps)
delay = max(8, duration_ms // (half_steps * 2))
r0, g0, b0 = color
for i in range(half_steps + 1):
k = i / half_steps
np[0] = (int(r0 * k), int(g0 * k), int(b0 * k))
np.write()
time.sleep_ms(delay)
for i in range(half_steps, -1, -1):
k = i / half_steps
np[0] = (int(r0 * k), int(g0 * k), int(b0 * k))
np.write()
time.sleep_ms(delay)
_np_off(np)
except:
_np_off(np)
def fast_blink(np, color=(60, 0, 0), times=4, on_ms=60, off_ms=60):
if np is None:
return
try:
for _ in range(times):
_np_set(np, color)
time.sleep_ms(on_ms)
_np_off(np)
time.sleep_ms(off_ms)
except:
_np_off(np)
def blink(led, times=1, on_ms=150, off_ms=150, color=(40, 40, 40)):
if led is None:
return
try:
if hasattr(led, "write"):
for _ in range(times):
led[0] = color
led.write()
time.sleep_ms(on_ms)
led[0] = (0, 0, 0)
led.write()
time.sleep_ms(off_ms)
else:
for _ in range(times):
led.value(1)
time.sleep_ms(on_ms)
led.value(0)
time.sleep_ms(off_ms)
except:
pass
# -----------------------
# UID utils + storage
# -----------------------
def uid_bytes_to_hex(uid_bytes: bytes):
return " ".join(["{:02X}".format(b) for b in uid_bytes])
def uid_hex_to_bytes(uid_hex: str):
try:
if not uid_hex:
return None
s = uid_hex.strip()
if not s:
return None
cleaned = []
for ch in s:
o = ord(ch)
is_hex = (48 <= o <= 57) or (65 <= o <= 70) or (97 <= o <= 102)
cleaned.append(ch if is_hex else " ")
s = "".join(cleaned)
s = " ".join(s.split())
if not s:
return None
parts = s.split(" ")
if len(parts) == 1 and len(parts[0]) > 2:
raw = parts[0]
if len(raw) % 2 != 0:
return None
parts = [raw[i:i+2] for i in range(0, len(raw), 2)]
data = bytes([int(p, 16) for p in parts if p])
return data if len(data) > 0 else None
except:
return None
def _sync_hex_set_from_bytes():
global ALLOWED_UIDS_HEX
ALLOWED_UIDS_HEX = set([uid_bytes_to_hex(u) for u in ALLOWED_UIDS])
def uids_list_cards():
_sync_hex_set_from_bytes()
out = []
for hx in sorted(list(ALLOWED_UIDS_HEX)):
out.append({"uid": hx, "name": UID_NAME_BY_HEX.get(hx, "")})
return out
def uids_list_hex():
return [c["uid"] for c in uids_list_cards()]
def _load_uids_file_or_init():
global ALLOWED_UIDS, ALLOWED_UIDS_HEX, UID_NAME_BY_HEX
UID_NAME_BY_HEX = {}
try:
with open(UIDS_FILE, "r") as f:
j = ujson.load(f)
tmp = set()
# NEW format
if "cards" in j and isinstance(j.get("cards"), list):
for item in j.get("cards", []):
hx = (item.get("uid") or "").strip()
nm = (item.get("name") or "").strip()
b = uid_hex_to_bytes(hx)
if b:
tmp.add(b)
UID_NAME_BY_HEX[uid_bytes_to_hex(b)] = nm or ""
ALLOWED_UIDS = tmp
_sync_hex_set_from_bytes()
log("UIDS", "loaded cards:", len(ALLOWED_UIDS))
return True
# OLD format compatibility: {"uids":[...]}
uids = j.get("uids", [])
for hx in uids:
b = uid_hex_to_bytes(hx)
if b:
tmp.add(b)
ALLOWED_UIDS = tmp
_sync_hex_set_from_bytes()
for hx in list(ALLOWED_UIDS_HEX):
UID_NAME_BY_HEX[hx] = ""
log("UIDS", "loaded (old format):", len(ALLOWED_UIDS))
_save_uids_file()
return True
except Exception as e:
log("UIDS", "no file -> init default:", e)
tmp = set()
for hx in DEFAULT_UIDS_HEX:
b = uid_hex_to_bytes(hx)
if b:
tmp.add(b)
UID_NAME_BY_HEX[uid_bytes_to_hex(b)] = ""
for item in DEFAULT_CARDS:
hx = (item.get("uid") or "").strip()
nm = (item.get("name") or "").strip()
b = uid_hex_to_bytes(hx)
if b:
tmp.add(b)
UID_NAME_BY_HEX[uid_bytes_to_hex(b)] = nm or ""
ALLOWED_UIDS = tmp
_sync_hex_set_from_bytes()
_save_uids_file()
log("UIDS", "initialized:", len(ALLOWED_UIDS))
return True
def _save_uids_file():
try:
_sync_hex_set_from_bytes()
cards = []
for hx in sorted(list(ALLOWED_UIDS_HEX)):
cards.append({"uid": hx, "name": UID_NAME_BY_HEX.get(hx, "")})
with open(UIDS_FILE, "w") as f:
ujson.dump({"cards": cards}, f)
return True
except Exception as e:
log("UIDS", "save error:", e)
return False
def uids_add(uid_hex: str, name: str = ""):
global ALLOWED_UIDS
b = uid_hex_to_bytes(uid_hex)
if not b:
return False, "Bad UID format"
hx = uid_bytes_to_hex(b)
if b in ALLOWED_UIDS:
if name is not None and str(name).strip() != "":
UID_NAME_BY_HEX[hx] = str(name).strip()
_save_uids_file()
return True, "Name updated: {} -> {}".format(hx, UID_NAME_BY_HEX[hx])
return True, "Already exists"
ALLOWED_UIDS.add(b)
UID_NAME_BY_HEX[hx] = (str(name).strip() if name else "")
ok = _save_uids_file()
return bool(ok), "Added: {}".format(hx)
def uids_remove(uid_hex: str):
global ALLOWED_UIDS
b = uid_hex_to_bytes(uid_hex)
if not b:
return False, "Bad UID format"
hx = uid_bytes_to_hex(b)
if b not in ALLOWED_UIDS:
return False, "Not found"
ALLOWED_UIDS.remove(b)
try:
if hx in UID_NAME_BY_HEX:
del UID_NAME_BY_HEX[hx]
except:
pass
ok = _save_uids_file()
return bool(ok), "Removed: {}".format(hx)
def uids_set_name(uid_hex: str, name: str):
b = uid_hex_to_bytes(uid_hex)
if not b:
return False, "Bad UID format"
hx = uid_bytes_to_hex(b)
if b not in ALLOWED_UIDS:
return False, "Not found"
UID_NAME_BY_HEX[hx] = (str(name).strip() if name else "")
ok = _save_uids_file()
return bool(ok), "Renamed: {} -> {}".format(hx, UID_NAME_BY_HEX[hx])
def uids_clear_all():
global ALLOWED_UIDS, UID_NAME_BY_HEX
ALLOWED_UIDS = set()
UID_NAME_BY_HEX = {}
ok = _save_uids_file()
return bool(ok)
# -----------------------
# SESSION MANAGEMENT
# -----------------------
SESSIONS = {} # {"session_id": timestamp_ms}
SESSION_TIMEOUT_MS = 3600000 # 1 hour
def _generate_session_id():
"""Generate a random session ID using MicroPython-compatible method"""
# MicroPython allows getrandbits() only up to 32 bits
try:
import urandom
r1 = urandom.getrandbits(32)
r2 = urandom.getrandbits(32)
r3 = urandom.getrandbits(32)
r4 = urandom.getrandbits(32)
# Generate 128-bit session ID (32 hex chars)
return "{:08x}{:08x}{:08x}{:08x}".format(r1, r2, r3, r4)
except:
# Fallback: use timestamp-based session ID
return "sess-{}".format(now_ms())
def _parse_cookies(headers):
"""Parse cookies from headers into a dict"""
cookie_header = headers.get("cookie", "")
cookies = {}
if cookie_header:
for part in cookie_header.split(";"):
part = part.strip()
if "=" in part:
k, v = part.split("=", 1)
cookies[k.strip()] = v.strip()
return cookies
def _check_session(headers):
"""Check if request has valid session cookie"""
if not UI_AUTH_ENABLED or not UI_USER or not UI_PASS:
return True # Auth disabled
cookies = _parse_cookies(headers)
sess_id = cookies.get("sess", "")
if not sess_id or sess_id not in SESSIONS:
return False
# Check session timeout
now = now_ms()
if ms_diff(now, SESSIONS[sess_id]) > SESSION_TIMEOUT_MS:
try:
del SESSIONS[sess_id]
except:
pass
return False
# Update session timestamp
SESSIONS[sess_id] = now
return True
def _create_session():
"""Create a new session and return session ID"""
sess_id = _generate_session_id()
SESSIONS[sess_id] = now_ms()
return sess_id
def _destroy_session(headers):
"""Destroy session from cookie"""
cookies = _parse_cookies(headers)
sess_id = cookies.get("sess", "")
if sess_id and sess_id in SESSIONS:
try:
del SESSIONS[sess_id]
except:
pass
def _redirect(cl, location):
"""Send HTTP redirect response"""
try:
hdr = (
"HTTP/1.1 302 Found\r\n"
"Location: {}\r\n"
"Content-Length: 0\r\n"
"Connection: close\r\n\r\n"
).format(location)
cl.send(hdr.encode())
except:
pass
def _set_cookie_redirect(cl, location, sess_id):
"""Send redirect with Set-Cookie header"""
try:
hdr = (
"HTTP/1.1 302 Found\r\n"
"Location: {}\r\n"
"Set-Cookie: sess={}; Path=/; HttpOnly; Max-Age=3600\r\n"
"Content-Length: 0\r\n"
"Connection: close\r\n\r\n"
).format(location, sess_id)
cl.send(hdr.encode())
except:
pass
def _clear_cookie_redirect(cl, location):
"""Send redirect with cookie deletion"""
try:
hdr = (
"HTTP/1.1 302 Found\r\n"
"Location: {}\r\n"
"Set-Cookie: sess=; Path=/; HttpOnly; Max-Age=0\r\n"
"Content-Length: 0\r\n"
"Connection: close\r\n\r\n"
).format(location)
cl.send(hdr.encode())
except:
pass
# -----------------------
# HTTP helpers
# -----------------------
def _read_http_request(cl):
try:
cl.settimeout(1.0)
data = cl.recv(2048)
if not data:
return None
t0 = time.ticks_ms()
while (b"\r\n\r\n" not in data) and (time.ticks_diff(time.ticks_ms(), t0) < 250):
try:
more = cl.recv(2048)
if not more:
break
data += more
except:
break
head, body = (data.split(b"\r\n\r\n", 1) + [b""])[:2]
lines = head.split(b"\r\n")
if not lines:
return None
req_line = lines[0].decode()
method, path, _ = req_line.split(" ", 2)
headers = {}
for ln in lines[1:]:
if b":" in ln:
k, v = ln.split(b":", 1)
headers[k.strip().lower().decode()] = v.strip().decode()
cl_len = int(headers.get("content-length", "0") or "0")
if cl_len > len(body):
need = cl_len - len(body)
while need > 0:
chunk = cl.recv(min(2048, need))
if not chunk:
break
body += chunk
need -= len(chunk)
return method, path, headers, body
except Exception as e:
if DEBUG_ERRORS and getattr(e, "errno", None) != 116:
log("HTTP", "read error:", e)
return None
def _http_send(cl, status="200 OK", ctype="text/plain; charset=utf-8", body=""):
try:
body_b = body.encode() if isinstance(body, str) else body
hdr = "HTTP/1.1 {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n".format(
status, ctype, len(body_b)
)
cl.send(hdr.encode() + body_b)
except:
pass
def _json_response(cl, obj, status="200 OK"):
_http_send(cl, status=status, ctype="application/json", body=ujson.dumps(obj))
def _sse_headers():
return (
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/event-stream\r\n"
"Cache-Control: no-cache\r\n"
"Connection: keep-alive\r\n\r\n"
)
def _sse_event(event_id, fw, uid_hex, access, uids=None, ok=None, msg=None, src=None, cards=None, name=None):
if uids is None:
uids = []
if cards is None:
cards = []
payload = {"id": event_id, "fw": fw, "uid": uid_hex, "access": access, "uids": uids, "cards": cards}
if name is not None:
payload["name"] = name
if src is not None:
payload["src"] = src
if ok is not None:
payload["ok"] = bool(ok)
if msg is not None:
payload["msg"] = msg
return "event: update\ndata: {}\n\n".format(ujson.dumps(payload))
def _check_admin_token(headers, body):
"""
Check for admin token in:
1. Authorization header: "Bearer <token>"
2. X-Admin-Token header: "<token>"
3. JSON body: {"token": "<token>"}
Returns True if valid, False otherwise.
"""
if not ADMIN_TOKEN:
return True # No token configured = no auth required
# Check Authorization header
auth = headers.get("authorization", "")
if auth.startswith("Bearer ") and auth[7:] == ADMIN_TOKEN:
return True
# Check X-Admin-Token header
if headers.get("x-admin-token", "") == ADMIN_TOKEN:
return True
# Check JSON body
try:
if body:
data = ujson.loads(body.decode() if isinstance(body, bytes) else body)
if data.get("token") == ADMIN_TOKEN:
return True
except:
pass
return False
def _check_basic_auth(headers):
"""
Check HTTP Basic Auth credentials.
Returns True if auth is disabled or credentials are valid, False otherwise.
"""
if not UI_AUTH_ENABLED or not UI_USER or not UI_PASS:
return True # Auth disabled or not configured
auth = headers.get("authorization", "")
if not auth.startswith("Basic "):
return False
try:
import ubinascii
encoded = auth[6:] # Remove "Basic " prefix
decoded = ubinascii.a2b_base64(encoded).decode()
username, password = decoded.split(":", 1)
return username == UI_USER and password == UI_PASS
except:
return False
def _unauth(cl):
"""
Send 401 Unauthorized response with WWW-Authenticate header.
"""
try:
hdr = (
"HTTP/1.1 401 Unauthorized\r\n"
"WWW-Authenticate: Basic realm=\"ESP32 NFC Panel\"\r\n"
"Content-Type: text/plain; charset=utf-8\r\n"
"Content-Length: 12\r\n"
"Connection: close\r\n\r\n"
"Unauthorized"
)
cl.send(hdr.encode())
except:
pass
# -----------------------
# WEB SERVER + PORTAL
# -----------------------
def _start_web_server():
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(2)
s.setblocking(False)
log("PORT80", "listening on :80")
return s
def _sta_mode_restore():
try:
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
except:
pass
def _enter_wifi_setup_and_return(srv, sse_client):
if LOG_PORTAL:
log("PORTAL", "enter provisioning (closing app server)")
if srv:
try:
srv.close()
except:
pass
srv = None
try:
if sse_client:
sse_client.close()
except:
pass
sse_client = None
op_t0 = time.ticks_ms()
try:
wifi_prov.provisioning_portal(loop_forever=False)
except Exception as e:
log("PORTAL", "error:", e)
op_dt = op_ms(op_t0)
op_log("PORTAL_SESSION", op_dt)
_sta_mode_restore()
if LOG_PORTAL:
log("PORTAL", "returned from portal, restarting app web server")
time.sleep_ms(200)
try:
srv = _start_web_server()
except Exception as e:
log("PORT80", "cannot start app server:", e)
srv = None
return srv, sse_client
# ---- Telegram wrapper: do not crash if tg_esp/SSL missing ----
try:
import tg_esp
except Exception as e:
tg_esp = None
TG_ENABLED = False
log("TG", "disabled (tg_esp import failed):", e)
# -----------------------
# MAIN APP LOOP
# -----------------------
def run():
global LAST_UID_HEX, LAST_ACCESS, LAST_FW, LAST_NAME, EVENT_ID
log("APP", "run() start")
_load_uids_file_or_init()
tg_ready = False
tg_online_sent = False
tg_last_try_ms = 0
if TG_ENABLED and tg_esp and TG_BOT_TOKEN and TG_BOT_TOKEN != "PUT_YOUR_NEW_TOKEN_HERE":
try:
tg_esp.configure(TG_BOT_TOKEN, TG_ADMIN_CHAT_ID, TG_POLL_EVERY_MS)
tg_ready = True
except Exception as e:
tg_ready = False
if DEBUG_ERRORS:
log("TG", "configure fail:", e)
# LED
led = None
if LED_PIN is not None:
try:
led = neopixel.NeoPixel(Pin(LED_PIN, Pin.OUT), 1)
led[0] = (0, 0, 0)
led.write()
except Exception as e:
led = None
if DEBUG_ERRORS:
log("LED", "init fail:", e)
# Button
btn = Pin(BTN_PIN, Pin.IN, Pin.PULL_UP)
press_count = 0
window_start = 0
last_irq_ms = 0
request_portal = False
portal_pending = False
tap_op_start = 0
hold_start = 0
was_down = False
def btn_is_down():
return (btn.value() == 0) if BTN_ACTIVE_LOW else (btn.value() == 1)
def _irq_handler(pin):
nonlocal press_count, window_start, last_irq_ms, request_portal, portal_pending, tap_op_start
if portal_pending:
return
t = now_ms()
if ms_diff(t, last_irq_ms) < DEBOUNCE_MS:
return
last_irq_ms = t
if press_count == 0:
window_start = t
tap_op_start = t
if LOG_BTN:
log("BTN", "window start")
if ms_diff(t, window_start) > PRESS_WINDOW_MS:
press_count = 0
window_start = t
tap_op_start = t
if LOG_BTN:
log("BTN", "window expired -> reset")
log("BTN", "window start")
press_count += 1
if LOG_BTN:
left = PRESS_WINDOW_MS - ms_diff(t, window_start)
log("BTN", "tap", press_count, "/", PRESS_TARGET, "window_left_ms=", max(0, left))
if press_count >= PRESS_TARGET:
press_count = 0
window_start = 0
request_portal = True
portal_pending = True
if LOG_BTN:
log("BTN", "7x -> REQUEST portal")
dt = ms_diff(t, tap_op_start) if tap_op_start else 0
op_log("BTN_7TAP", dt, "request portal")
tap_op_start = 0
btn.irq(trigger=Pin.IRQ_FALLING, handler=_irq_handler)
# NFC init
i2c = I2C(I2C_ID, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=I2C_FREQ)
nfc = PN532_I2C(i2c, addr=PN532_ADDR)
time.sleep(0.3)
fw = nfc.get_firmware_version()
LAST_FW = fw
log("NFC", "FW:", fw)
nfc.sam_config()
log("NFC", "SAM OK")
# Web server
srv = _start_web_server()
sse_client = None
def _tg_handle_cmd(text: str):
nonlocal sse_client
global EVENT_ID
t = (text or "").strip()
if t in ("/start", "/help"):
return "ESP32 NFC bot\n/last\n/add_last\n/help"
if t == "/last":
return "LAST UID: {}\nName: {}\nAccess: {}".format(
LAST_UID_HEX or "-", LAST_NAME or "-", LAST_ACCESS or "-"
)
if t == "/add_last":
if not LAST_UID_HEX:
return "No LAST UID (tap a card first)"
ok, msg = uids_add(LAST_UID_HEX)
if ok and led is not None:
blink(led, times=2, on_ms=90, off_ms=60, color=(60, 35, 0))
EVENT_ID += 1
if sse_client:
try:
sse_client.send(_sse_event(
EVENT_ID, LAST_FW, LAST_UID_HEX, LAST_ACCESS,
uids_list_hex(), ok=ok, msg=msg, src="tg",
cards=uids_list_cards(), name=LAST_NAME
).encode())
except:
try:
sse_client.close()
except:
pass
sse_client = None
log("SSE", "client disconnected")
return ("OK: " if ok else "ERR: ") + msg
return None
last_uid = None
last_time = 0
while True:
try:
# ---- Button hold detection ----
down = btn_is_down()
if LOG_BTN and down and not was_down:
log("BTN", "DOWN (hold start)")
hold_start = now_ms()
if down:
if hold_start and ms_diff(now_ms(), hold_start) >= HOLD_CLEAR_MS:
log("BTN", "HOLD 10s -> clear wifi.json + portal")
op_t0 = time.ticks_ms()
try:
ok = wifi_prov.clear_cfg()
except:
ok = False
op_dt = op_ms(op_t0)
log("BTN", "wifi.json cleared:", ok)
op_log("BTN_HOLD_CLEAR", op_dt, "ok={}".format(ok))
hold_start = 0
request_portal = True
portal_pending = True
else:
if LOG_BTN and (not down) and was_down:
log("BTN", "UP")
hold_start = 0
was_down = down
# ---- Portal request ----
if request_portal:
request_portal = False
btn.irq(handler=None)
srv, sse_client = _enter_wifi_setup_and_return(srv, sse_client)
time.sleep_ms(200)
portal_pending = False
btn.irq(trigger=Pin.IRQ_FALLING, handler=_irq_handler)
# ---- HTTP accept ----
if srv:
try:
cl, _ = srv.accept()
except OSError:
cl = None
if cl:
req = _read_http_request(cl)
if not req:
try:
cl.close()
except:
pass
else:
method, path, headers, body = req
# GET /login - Show login page
if method == "GET" and path == "/login":
_http_send(
cl,
status="200 OK",
ctype="text/html; charset=utf-8",
body=ui_html.build_login_html()
)
try:
cl.close()
except:
pass
# POST /login - Authenticate and create session
elif method == "POST" and path == "/login":
try:
data = ujson.loads(body.decode() if body else "{}")
username = data.get("username", "")
password = data.get("password", "")
if username == UI_USER and password == UI_PASS:
sess_id = _create_session()
_set_cookie_redirect(cl, "/", sess_id)
log("AUTH", "Login successful for user:", username)
else:
_json_response(cl, {"ok": False, "msg": "Invalid credentials"}, status="401 Unauthorized")
log("AUTH", "Login failed for user:", username)
except Exception as e:
_json_response(cl, {"ok": False, "msg": "Login error"}, status="400 Bad Request")
if DEBUG_ERRORS:
log("AUTH", "Login error:", e)
try:
cl.close()
except:
pass
# GET /logout - Destroy session and redirect to login
elif method == "GET" and path == "/logout":
_destroy_session(headers)
_clear_cookie_redirect(cl, "/login")
log("AUTH", "Logout")
try:
cl.close()
except:
pass
# GET / - Main dashboard (protected)
elif method == "GET" and (path == "/" or path.startswith("/?")):
if not _check_session(headers):
_redirect(cl, "/login")
try:
cl.close()
except:
pass
else: