-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1014 lines (778 loc) · 24.7 KB
/
Copy pathmain.py
File metadata and controls
1014 lines (778 loc) · 24.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
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
from machine import Pin, I2C, PWM
from ssd1306 import SSD1306_I2C
import time
import gc
from config_store import load_config, save_config, save_scan_logs
import font_ua
from font_ua import screen, big_screen, ua_text_center
from web_admin import start_network, init_server, poll_web, AP_SSID, set_access_mode
# =========================
# I2C: OLED + PN532
# =========================
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=100000)
PN532_ADDR = 0x24
oled = SSD1306_I2C(128, 64, i2c)
# =========================
# LED
# =========================
led_red = Pin(5, Pin.OUT)
led_blue = Pin(18, Pin.OUT)
led_green = Pin(19, Pin.OUT)
# =========================
# BUZZER PWM
# =========================
buzzer = PWM(Pin(23))
buzzer.freq(2500)
buzzer.duty(0)
# =========================
# KEYPAD
# =========================
row_pins = [32, 33, 25, 26]
col_pins = [27, 14, 13, 4]
keys = [
["1", "2", "3", "A"],
["4", "5", "6", "B"],
["7", "8", "9", "C"],
["*", "0", "#", "D"]
]
rows = [Pin(pin, Pin.OUT) for pin in row_pins]
cols = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in col_pins]
# =========================
# CONFIG
# =========================
config = load_config()
MAX_PIN_LENGTH = 12
entered_pin = ""
last_card_uid = ""
MODE_LOCKED = "locked"
MODE_GRANTED = "granted"
MODE_DENIED = "denied"
mode = MODE_LOCKED
granted_until = 0
current_user_name = ""
# =========================
# CLEAN LOGS
# =========================
DEBUG = True
def log(level, message):
if DEBUG:
print("[{}] {}".format(level, message))
def mask_pin(pin):
if not pin:
return ""
return "*" * len(pin)
# =========================
# I2C DEVICE DETECTION
# =========================
def identify_i2c_device(addr):
known_devices = {
0x24: "PN532 NFC/RFID reader",
0x3C: "SSD1306 OLED display 128x64",
0x3D: "SSD1306 OLED display alternative address",
}
return known_devices.get(addr, "Невідомий I2C пристрій")
def scan_i2c_devices():
devices = i2c.scan()
if not devices:
log("WARN", "I2C пристрої не знайдено")
return
log("INFO", "Знайдено I2C пристрої:")
for addr in devices:
log("I2C", "Адреса {} | {}".format(hex(addr), identify_i2c_device(addr)))
# =========================
# OLED UI
# =========================
last_oled_second = -1
last_dog_anim_time = 0
dog_x = 72
dog_dir = 1
DOG_MIN_X = 72
DOG_MAX_X = 112
DOG_ANIM_MS = 250
def get_time_text():
try:
t = time.localtime()
return "{:02d}:{:02d}:{:02d}".format(t[3], t[4], t[5])
except:
return "--:--:--"
def draw_ua(text, x, y, scale=1):
if hasattr(font_ua, "ua_text"):
font_ua.ua_text(oled, text, x, y, scale)
else:
ua_text_center(oled, text, y, scale)
def draw_time_bar():
ua_text_center(oled, get_time_text(), 0, 1)
def draw_circle(cx, cy, r, opened=False, gap_size=0):
x = r
y = 0
err = 0
while x >= y:
points = [
(cx + x, cy + y), (cx + y, cy + x),
(cx - y, cy + x), (cx - x, cy + y),
(cx - x, cy - y), (cx - y, cy - x),
(cx + y, cy - x), (cx + x, cy - y)
]
for px, py in points:
draw_pixel = True
if opened:
if gap_size == 1:
if px > cx + 19 and py < cy + 7:
draw_pixel = False
elif gap_size == 2:
if px > cx + 16 and py < cy + 11:
draw_pixel = False
elif gap_size >= 3:
if px > cx + 12 and py < cy + 15:
draw_pixel = False
if draw_pixel and 0 <= px < 128 and 0 <= py < 64:
oled.pixel(px, py, 1)
y += 1
if err <= 0:
err += 2 * y + 1
if err > 0:
x -= 1
err -= 2 * x + 1
def draw_closed_lock(x, y):
# Slightly bigger centered body
oled.fill_rect(x + 15, y + 26, 28, 21, 1)
oled.fill_rect(x + 18, y + 29, 22, 15, 0)
# Closed shackle
oled.line(x + 21, y + 26, x + 21, y + 16, 1)
oled.line(x + 22, y + 16, x + 25, y + 12, 1)
oled.line(x + 25, y + 12, x + 34, y + 12, 1)
oled.line(x + 34, y + 12, x + 38, y + 16, 1)
oled.line(x + 38, y + 16, x + 38, y + 26, 1)
oled.line(x + 24, y + 26, x + 24, y + 18, 1)
oled.line(x + 25, y + 18, x + 28, y + 15, 1)
oled.line(x + 28, y + 15, x + 32, y + 15, 1)
oled.line(x + 32, y + 15, x + 35, y + 18, 1)
oled.line(x + 35, y + 18, x + 35, y + 26, 1)
# Keyhole
oled.fill_rect(x + 27, y + 34, 5, 8, 1)
oled.fill_rect(x + 25, y + 31, 9, 6, 1)
oled.fill_rect(x + 27, y + 33, 5, 4, 0)
oled.fill_rect(x + 29, y + 37, 2, 5, 0)
def draw_open_lock(x, y):
# Body
oled.fill_rect(x + 15, y + 26, 28, 21, 1)
oled.fill_rect(x + 18, y + 29, 22, 15, 0)
# Left side of shackle stays connected to body
oled.line(x + 21, y + 26, x + 21, y + 16, 1)
oled.line(x + 22, y + 16, x + 25, y + 12, 1)
oled.line(x + 25, y + 12, x + 34, y + 12, 1)
oled.line(x + 34, y + 12, x + 38, y + 16, 1)
# Right side of shackle stops above the body
# This creates the realistic gap on the right side
oled.line(x + 38, y + 16, x + 38, y + 21, 1)
# Inner shackle line
oled.line(x + 24, y + 26, x + 24, y + 18, 1)
oled.line(x + 25, y + 18, x + 28, y + 15, 1)
oled.line(x + 28, y + 15, x + 32, y + 15, 1)
oled.line(x + 32, y + 15, x + 35, y + 18, 1)
# Inner right side also stops before body to show opening
oled.line(x + 35, y + 18, x + 35, y + 22, 1)
# Small visual gap markers / unlock rays
oled.line(x + 43, y + 22, x + 48, y + 19, 1)
oled.line(x + 44, y + 28, x + 50, y + 28, 1)
oled.line(x + 42, y + 34, x + 47, y + 37, 1)
# Keyhole
oled.fill_rect(x + 27, y + 34, 5, 8, 1)
oled.fill_rect(x + 25, y + 31, 9, 6, 1)
oled.fill_rect(x + 27, y + 33, 5, 4, 0)
oled.fill_rect(x + 29, y + 37, 2, 5, 0)
def draw_vertical_separator():
oled.vline(61, 17, 38, 1)
oled.fill_rect(58, 34, 7, 7, 1)
def draw_small_dog(x, y, flip=False):
if not flip:
oled.fill_rect(x + 2, y + 2, 7, 3, 1)
oled.fill_rect(x + 8, y + 1, 3, 3, 1)
oled.pixel(x + 9, y, 1)
oled.pixel(x + 1, y + 1, 1)
oled.pixel(x, y, 1)
oled.pixel(x + 3, y + 5, 1)
oled.pixel(x + 7, y + 5, 1)
oled.pixel(x + 11, y + 2, 1)
else:
oled.fill_rect(x + 3, y + 2, 7, 3, 1)
oled.fill_rect(x, y + 1, 3, 3, 1)
oled.pixel(x + 1, y, 1)
oled.pixel(x + 10, y + 1, 1)
oled.pixel(x + 11, y, 1)
oled.pixel(x + 4, y + 5, 1)
oled.pixel(x + 8, y + 5, 1)
oled.pixel(x, y + 2, 1)
def draw_bottom_line(dog=False, center_dog=False):
y = 55
oled.hline(70, y, 55, 1)
if dog:
draw_small_dog(dog_x, 57, flip=(dog_dir < 0))
if center_dog:
draw_small_dog(94, 57, flip=False)
def draw_base_access_ui(opened=False, dog=False, center_dog=False, gap_size=0):
oled.fill(0)
draw_time_bar()
draw_circle(29, 37, 27, opened=opened, gap_size=gap_size)
if opened:
draw_open_lock(1, 5)
else:
draw_closed_lock(1, 5)
draw_vertical_separator()
draw_bottom_line(dog=dog, center_dog=center_dog)
def update_dog_animation():
global dog_x
global dog_dir
global last_dog_anim_time
now = time.ticks_ms()
if time.ticks_diff(now, last_dog_anim_time) < DOG_ANIM_MS:
return False
last_dog_anim_time = now
dog_x += dog_dir * 3
if dog_x >= DOG_MAX_X:
dog_x = DOG_MAX_X
dog_dir = -1
if dog_x <= DOG_MIN_X:
dog_x = DOG_MIN_X
dog_dir = 1
return True
def draw_locked_ui(force=False):
global last_oled_second
t = time.localtime()
sec = t[5]
dog_changed = update_dog_animation()
if sec == last_oled_second and not force and not dog_changed:
return
last_oled_second = sec
draw_base_access_ui(opened=False, dog=True)
draw_ua("ВВЕДИ КОД", 73, 23, 1)
draw_ua("АБО СКАНУЙ", 73, 34, 1)
draw_ua("КЛЮЧ", 73, 45, 1)
oled.show()
def _safe_name(name):
"""Normalize name for OLED: str, strip, upper, max 5 chars."""
if not name:
return "USER"
n = str(name).strip().upper()
if not n:
return "USER"
return n[:5]
def draw_granted_ui(name):
display_name = _safe_name(name)
log("OLED", "Display name: {}".format(display_name))
draw_base_access_ui(opened=True, center_dog=True, gap_size=3)
draw_ua("ВІТАННЯ", 73, 24, 1)
font_ua.ua_text(oled, display_name, 73, 39, 1)
oled.show()
def draw_open_animation(name):
display_name = _safe_name(name)
log("OLED", "Display name: {}".format(display_name))
for gap in range(0, 4):
draw_base_access_ui(opened=True, center_dog=True, gap_size=gap)
draw_ua("ВІТАННЯ", 73, 24, 1)
font_ua.ua_text(oled, display_name, 73, 39, 1)
oled.show()
time.sleep_ms(120)
def draw_denied_ui():
draw_base_access_ui(opened=False, dog=False)
draw_ua("ДОСТУП", 77, 24, 1)
draw_ua("ЗАБОРОНЕНО", 73, 39, 1)
oled.show()
def show_pin_screen():
stars = "*" * len(entered_pin)
draw_base_access_ui(opened=False, dog=False)
draw_ua("ВВЕДИ КОД", 73, 24, 1)
if stars:
draw_ua(stars[:10], 73, 39, 1)
else:
draw_ua("********", 73, 39, 1)
oled.show()
# =========================
# BUZZER
# =========================
def tone(freq=2500, ms=80, duty=650):
buzzer.freq(freq)
buzzer.duty(duty)
time.sleep_ms(ms)
buzzer.duty(0)
def key_beep():
tone(3200, 55, 750)
def success_beep():
tone(2200, 90, 700)
time.sleep_ms(70)
tone(3000, 90, 700)
time.sleep_ms(70)
tone(3800, 130, 700)
def error_beep():
tone(700, 180, 750)
time.sleep_ms(80)
tone(700, 180, 750)
def arm_beep():
tone(2600, 70, 700)
time.sleep_ms(40)
tone(2100, 90, 700)
time.sleep_ms(40)
tone(1600, 140, 700)
def boot_start_beep():
tone(1800, 45, 550)
def boot_ready_beep():
tone(2200, 60, 600)
time.sleep_ms(45)
tone(3000, 75, 600)
# =========================
# LED
# =========================
def all_led_off():
led_red.off()
led_blue.off()
led_green.off()
def set_led(name):
led_red.off()
led_blue.off()
led_green.off()
if name == "red":
led_red.on()
elif name == "blue":
led_blue.on()
elif name == "green":
led_green.on()
locked_pattern = [
("red", 80),
("off", 70),
("red", 80),
("off", 180),
("blue", 80),
("off", 70),
("blue", 80),
("off", 380),
]
locked_pattern_index = 0
locked_pattern_last_time = 0
def reset_locked_pattern():
global locked_pattern_index
global locked_pattern_last_time
locked_pattern_index = 0
locked_pattern_last_time = time.ticks_ms()
set_led(locked_pattern[0][0])
def update_locked_led_pattern():
global locked_pattern_index
global locked_pattern_last_time
if mode != MODE_LOCKED:
return
now = time.ticks_ms()
current_duration = locked_pattern[locked_pattern_index][1]
if time.ticks_diff(now, locked_pattern_last_time) >= current_duration:
locked_pattern_index = (locked_pattern_index + 1) % len(locked_pattern)
locked_pattern_last_time = now
set_led(locked_pattern[locked_pattern_index][0])
# =========================
# ACCESS USERS
# =========================
def find_user_by_pin(pin):
for user in config.get("users", []):
if user.get("pin") == pin:
return user
return None
def find_user_by_uid(uid):
for user in config.get("users", []):
if user.get("uid") == uid:
return user
return None
# =========================
# NFC DEDUPLICATION
# =========================
_last_logged_uid = ""
_last_logged_time = 0
NFC_DEDUP_MS = 5000 # не логувати ту саму карту частіше ніж раз на 5 сек
def add_scan_log(uid):
global config, _last_logged_uid, _last_logged_time
now = time.ticks_ms()
# Дедуплікація: якщо та сама карта вже була зчитана менш ніж 5 сек тому — не писати flash
if uid == _last_logged_uid and time.ticks_diff(now, _last_logged_time) < NFC_DEDUP_MS:
return find_user_by_uid(uid)
_last_logged_uid = uid
_last_logged_time = now
user = find_user_by_uid(uid)
if user:
name = user.get("name", "Unknown")
status = "Присвоєний"
allowed = True
else:
name = "Невідомий ключ"
status = "Не присвоєний"
allowed = False
try:
t = time.localtime()
scanned_at = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
t[0], t[1], t[2], t[3], t[4], t[5]
)
except:
scanned_at = "Немає часу"
log_item = {
"uid": uid,
"name": name,
"status": status,
"allowed": allowed,
"time": scanned_at
}
logs = config.get("scan_logs", [])
logs.insert(0, log_item)
config["scan_logs"] = logs[:30]
save_scan_logs(config)
return user
# =========================
# ACCESS STATES
# =========================
denied_blink_count = 0
denied_next_time = 0
denied_led_state = False
def enter_locked_screen():
reset_locked_pattern()
draw_locked_ui(True)
def access_granted(name="КОРИСТУВАЧ"):
global mode
global entered_pin
global granted_until
global current_user_name
entered_pin = ""
current_user_name = name
mode = MODE_GRANTED
set_access_mode("granted")
granted_until = time.ticks_add(time.ticks_ms(), 10000)
all_led_off()
led_green.on()
draw_open_animation(current_user_name)
log("OK", "Доступ дозволено: {}".format(current_user_name))
success_beep()
def access_denied():
global mode
global entered_pin
global denied_blink_count
global denied_next_time
global denied_led_state
entered_pin = ""
mode = MODE_DENIED
set_access_mode("denied")
denied_blink_count = 0
denied_next_time = time.ticks_ms()
denied_led_state = False
all_led_off()
draw_denied_ui()
log("WARN", "Доступ заборонено")
error_beep()
def update_access_state():
global mode
global denied_blink_count
global denied_next_time
global denied_led_state
now = time.ticks_ms()
if mode == MODE_GRANTED:
led_red.off()
led_blue.off()
led_green.on()
if time.ticks_diff(now, granted_until) >= 0:
led_green.off()
arm_beep()
mode = MODE_LOCKED
set_access_mode("locked")
log("INFO", "Система знову стала на охорону")
enter_locked_screen()
return
if mode == MODE_DENIED:
if denied_blink_count < 6 and time.ticks_diff(now, denied_next_time) >= 0:
denied_led_state = not denied_led_state
if denied_led_state:
led_red.on()
else:
led_red.off()
denied_blink_count += 1
denied_next_time = time.ticks_add(now, 120)
if denied_blink_count >= 6:
led_red.off()
mode = MODE_LOCKED
set_access_mode("locked")
enter_locked_screen()
# =========================
# PIN LOGIC
# =========================
def handle_key(key):
global entered_pin
global config
if mode != MODE_LOCKED:
return
if key in ["0","1","2","3","4","5","6","7","8","9"]:
if len(entered_pin) < MAX_PIN_LENGTH:
entered_pin += key
log("KEYPAD", "PIN введено: {}".format(mask_pin(entered_pin)))
show_pin_screen()
return
if key == "#":
entered_pin = ""
log("KEYPAD", "PIN очищено")
draw_locked_ui(True)
return
if key == "*":
log("ACCESS", "Перевірка PIN: {}".format(mask_pin(entered_pin)))
user = find_user_by_pin(entered_pin)
if user:
access_granted(user.get("name", "КОРИСТУВАЧ"))
else:
access_denied()
return
# =========================
# KEYPAD FAST SCAN
# =========================
current_pressed = None
first_key_ready = False
def scan_keypad():
global current_pressed
global first_key_ready
detected_key = None
for r in range(4):
for row in rows:
row.on()
rows[r].off()
time.sleep_us(150)
for c in range(4):
if cols[c].value() == 0:
detected_key = keys[r][c]
break
if detected_key:
break
if detected_key is None:
current_pressed = None
first_key_ready = True
return None
if not first_key_ready:
current_pressed = detected_key
first_key_ready = True
log("KEYPAD", "Натиснута кнопка: {}".format(detected_key))
key_beep()
return detected_key
if detected_key != current_pressed:
current_pressed = detected_key
log("KEYPAD", "Натиснута кнопка: {}".format(detected_key))
key_beep()
return detected_key
return None
# =========================
# PN532
# =========================
def pn532_write_frame(data):
length = len(data)
lcs = (~length + 1) & 0xFF
dcs = (~sum(data) + 1) & 0xFF
frame = bytearray([0x00, 0x00, 0xFF, length, lcs])
frame += bytearray(data)
frame += bytearray([dcs, 0x00])
i2c.writeto(PN532_ADDR, frame)
def pn532_wait_ready(timeout=120):
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < timeout:
try:
status = i2c.readfrom(PN532_ADDR, 1)
if status[0] == 0x01:
return True
except:
pass
time.sleep_ms(3)
return False
def pn532_read_response(length=64, timeout=120):
if not pn532_wait_ready(timeout):
return None
return i2c.readfrom(PN532_ADDR, length)
def pn532_command(cmd, timeout=120):
pn532_write_frame([0xD4] + cmd)
time.sleep_ms(8)
pn532_read_response(8, timeout=60)
time.sleep_ms(8)
return pn532_read_response(64, timeout=timeout)
def wakeup():
try:
i2c.writeto(PN532_ADDR, b'\x55\x55\x00\x00\x00')
except:
pass
time.sleep_ms(80)
def nfc_init():
log("NFC", "Ініціалізація PN532")
for attempt in range(3):
resp = pn532_command([0x14, 0x01, 0x14, 0x01], timeout=300)
if resp:
log("NFC", "PN532 готовий")
return True
log("WARN", "PN532 не відповів, спроба {}".format(attempt + 1))
time.sleep_ms(100)
log("ERROR", "PN532 не вдалося ініціалізувати")
return False
def find_sequence(data, seq):
if not data:
return -1
for i in range(len(data) - len(seq) + 1):
found = True
for j in range(len(seq)):
if data[i + j] != seq[j]:
found = False
break
if found:
return i
return -1
def read_nfc_card():
resp = pn532_command([0x4A, 0x01, 0x00], timeout=80)
if not resp:
return None
idx = find_sequence(resp, [0xD5, 0x4B])
if idx == -1:
return None
try:
targets = resp[idx + 2]
if targets < 1:
return None
uid_len = resp[idx + 7]
uid_start = idx + 8
uid_end = uid_start + uid_len
uid = resp[uid_start:uid_end]
if uid_len <= 0 or uid_len > 10:
return None
uid_hex = " ".join("{:02X}".format(x) for x in uid)
return uid_hex
except Exception as e:
log("ERROR", "Помилка NFC: {}".format(e))
return None
def get_last_uid():
return last_card_uid
def oled_network_message(a, b, c, d):
screen(oled, a, b, c, d)
def show_ip_ack_screen(network_mode, ip):
if network_mode == "AP":
screen(oled, "SETUP MODE", "IP", ip, "НАТИСНИ A")
else:
screen(oled, "WIFI ГОТОВО", "IP", ip, "НАТИСНИ A")
def wait_for_ip_ack(network_mode, ip):
global config
show_ip_ack_screen(network_mode, ip)
log("INFO", "IP показано на OLED. Натисни A для переходу в робочий режим")
last_refresh = time.ticks_ms()
while True:
config = poll_web(config, get_last_uid, oled_network_message)
key = scan_keypad()
if key == "A":
log("INFO", "IP підтверджено кнопкою A")
tone(2600, 70, 650)
break
# Періодично повертаємо IP на екран, якщо web-сторінка тимчасово змінила OLED.
now = time.ticks_ms()
if time.ticks_diff(now, last_refresh) >= 3000:
show_ip_ack_screen(network_mode, ip)
last_refresh = now
time.sleep_ms(80)
_last_boot_percent = -1
def boot_progress(percent, line1="BFU ACCESS", line2="STARTING"):
global _last_boot_percent
if percent < 0:
percent = 0
if percent > 100:
percent = 100
percent = int(percent)
# Progress must be monotonic: no jumps back and no repeated redraws.
if percent < _last_boot_percent:
percent = _last_boot_percent
if percent == _last_boot_percent:
return
_last_boot_percent = percent
oled.fill(0)
ua_text_center(oled, line1, 6, 1)
ua_text_center(oled, line2, 20, 1)
x = 12
y = 42
w = 104
h = 10
# frame (hline/vline fallback-safe)
oled.hline(x, y, w, 1)
oled.hline(x, y + h, w, 1)
oled.vline(x, y, h, 1)
oled.vline(x + w, y, h + 1, 1)
fill_w = int((w - 4) * percent / 100)
if fill_w > 0:
oled.fill_rect(x + 2, y + 2, fill_w, h - 3, 1)
txt = "{}%".format(percent)
ua_text_center(oled, txt, 56, 1)
oled.show()
# =========================
# START
# =========================
log("INFO", "BFU Electronics Access System стартує")
boot_progress(5, "BFU ACCESS", "BOOT")
boot_start_beep()
gc.collect()
boot_progress(15, "MEMORY", "CHECK")
log("RAM", "after imports: {}".format(gc.mem_free()))
boot_progress(25, "WIFI", "STARTING")
gc.collect()
log("RAM", "before start_network: {}".format(gc.mem_free()))
network_mode, ip = start_network(config, boot_progress)
gc.collect()
log("RAM", "after start_network: {}".format(gc.mem_free()))
boot_progress(45, "WEB SERVER", "STARTING")
init_server()
log("INFO", "Web server запущено")
gc.collect()
log("RAM", "after init_server: {}".format(gc.mem_free()))
boot_progress(60, "I2C", "CHECK")
scan_i2c_devices()
boot_progress(70, "OLED", "READY")
screen(oled, "BFU", "ELECTRONICS", "ACCESS", "SYSTEM")
boot_progress(80, "NFC", "STARTING")
wakeup()
nfc_init()
boot_progress(90, "SYSTEM", "FINALIZE")
gc.collect()
log("RAM", "after nfc_init: {}".format(gc.mem_free()))
boot_progress(100, "SYSTEM", "READY")
all_led_off()
boot_ready_beep()
time.sleep_ms(200)
if network_mode == "AP":
log("INFO", "Режим налаштування Wi-Fi: SSID={}, IP={}".format(AP_SSID, ip))
screen(oled, "SETUP MODE", "ПІДКЛЮЧИСЬ", AP_SSID, ip)
else:
log("INFO", "Wi-Fi підключено, IP={}".format(ip))
screen(oled, "WIFI ГОТОВО", "ВІДКРИЙ IP", ip, "")
wait_for_ip_ack(network_mode, ip)
enter_locked_screen()
last_nfc_check = time.ticks_ms()
_loop_counter = 0
# =========================
# MAIN LOOP
# =========================
while True:
config = poll_web(config, get_last_uid, oled_network_message)
update_access_state()
update_locked_led_pattern()
if mode == MODE_LOCKED and entered_pin == "":
draw_locked_ui()
key = scan_keypad()
if key:
handle_key(key)
now = time.ticks_ms()
if mode == MODE_LOCKED and entered_pin == "":
if time.ticks_diff(now, last_nfc_check) > 1500:
uid = read_nfc_card()
if uid:
last_card_uid = uid
log("NFC", "Зчитано карту UID: {}".format(uid))
user = add_scan_log(uid)
if user:
log("ACCESS", "Ключ належить користувачу: {}".format(user.get("name", "")))
access_granted(user.get("name", "КОРИСТУВАЧ"))
else:
log("ACCESS", "Невідомий NFC ключ")