Repository navigation
Expand file tree
/
Copy pathcode.py
More file actions
631 lines (512 loc) · 27.3 KB
/
Copy pathcode.py
File metadata and controls
631 lines (512 loc) · 27.3 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
"""
code.py — главный файл, склейка всех модулей.
Порядок инициализации важен:
1. config.load() — конфиг и состояние
2. trigger_bus.init() — HID-клавиатура (ДО любых fire())
3. display — дисплей
4. inputs_manager — датчики (Hall, INA226, кнопка) через InputsManager
5. encoder — энкодер с callback
6. warning_screen — варнинг оверлей (низкий заряд)
7. splash_screen — HUD батареи во время скринсейвера
"""
import time
import config
import trigger_bus
import inputs_manager
from encoder import (
EncoderHandler,
EV_ROTATE_LEFT,
EV_ROTATE_RIGHT,
EV_PRESS,
EV_LONG_PRESS,
)
from display import DisplayManager
from inputs_manager import InputsManager
from splash_trigger import SplashTrigger
from splash_screen import SplashScreen
from warning_screen import WarningScreen
# ── 1. Конфигурация ────────────────────────────────────────────────────────
config.load()
# Корневое меню (неизменно на протяжении всей работы)
root_menu = config.get_config().get("active_menu", [])
menu_cursor = config.get_state().get("menu_cursor", 0)
# Текущий отображаемый список (при старте равен корневому)
current_menu_list = root_menu
# Стек для навигации назад: хранит кортежи (список_родителя, позиция_курсора)
menu_stack = []
# Encoder Control: активный item в режиме прямого управления (None = обычная навигация)
encoder_control_item = None
# Защита от выхода за пределы (если конфиг урезали после сохранения позиции)
if root_menu and menu_cursor >= len(root_menu):
menu_cursor = 0
elif not root_menu:
menu_cursor = 0
print("[main] active_menu:", len(root_menu), "items")
# ── 2. Инициализация железа ────────────────────────────────────────────────
# ОБЯЗАТЕЛЬНО до любого fire() — поднимает HID-клавиатуру
trigger_bus.init()
print("[main] Init display...")
if config.get_config().get("device", {}).get("display_enabled", True):
try:
display = DisplayManager()
display.show_boot()
display.set_render_mode(config.get_config().get("device", {}).get("display_mode", "text"))
except Exception as e:
print("[main] Display init failed:", e)
display = None
else:
print("[main] Display disabled in config")
display = None
splash_trigger = SplashTrigger()
splash_screen = SplashScreen(display._disp) if display else None
warning_screen = WarningScreen(display._disp) if display else None
print("[main] Init inputs manager (Hall sensors, INA226, button)...")
inputs = InputsManager(i2c=display.i2c if display else None)
inputs.startup_blink()
print("[main] Init encoder...")
if config.get_config().get("device", {}).get("encoder_enabled", True):
try:
encoder = EncoderHandler()
except Exception as e:
print("[main] Encoder init failed:", e)
encoder = None
else:
print("[main] Encoder disabled in config")
encoder = None
# ── 3. Вспомогательные функции ─────────────────────────────────────────────
def get_current_label():
"""Имя текущего пункта меню."""
if not current_menu_list:
return "No menu"
return current_menu_list[menu_cursor].get("label", "?")
def get_current_action():
"""Имя следующего действия в sequence (для нижней строки дисплея)."""
if not current_menu_list:
return ""
item = current_menu_list[menu_cursor]
# Encoder Control — не папка и не обычное действие, свой индикатор
if item.get("type") == "encoder_control":
return ">> Encoder"
# Папка без sequence — показываем индикатор вложенного меню
if "sequence" not in item and "pipeline" not in item:
return ">> Open"
return trigger_bus.get_next_action_name(item["id"])
def refresh_menu():
"""Перерисовать меню без анимации."""
if display and current_menu_list:
display.set_menu_items(current_menu_list)
display.set_menu_state(menu_cursor, len(current_menu_list), len(menu_stack))
display.draw_menu(get_current_label(), get_current_action())
def save_cursor():
"""Сохранить позицию курсора в state.json."""
state = config.get_state()
state["menu_cursor"] = menu_cursor
config.save_state()
# ── 4. Сон и заставка экрана ────────────────────────────────────────────────
last_interaction_time = time.monotonic()
screen_sleeping = False
screensaver_active = False
# Загрузка параметров таймаута и типа заставки
device_cfg = config.get_config().get("device", {})
screen_timeout = device_cfg.get("screen_timeout_s", 0) # 0 — отключено
screensaver_name = device_cfg.get("screensaver", "off") # "off", "tesseract", "starfield", "matrix"
next_anim_t = 0.0
def wake_up_display():
"""Пробуждение экрана из любого режима ожидания."""
global last_interaction_time, screen_sleeping, screensaver_active, encoder_control_item
last_interaction_time = time.monotonic()
if display:
# Если сплеш активен — он сам восстановит root_group, форсируем hide
if splash_screen and splash_screen.is_active:
splash_screen._hide()
if screensaver_active:
display.stop_screensaver()
screensaver_active = False
if screen_sleeping:
display.wake()
screen_sleeping = False
if encoder_control_item is not None:
_enter_encoder_control_display(encoder_control_item)
else:
refresh_menu()
print("[main] Display awake")
# ── 5. Callback энкодера ───────────────────────────────────────────────────
def _enter_encoder_control_display(item):
"""Отрисовка фонового вида режима Encoder Control."""
if display:
mode_label = item.get("label", "?")
output_mode = item.get("output_mode", "?")
mode_type = "Mouse" if output_mode == "mouse" else "Scenario"
display.show_encoder_control(mode_label, mode_type)
def _handle_encoder_control_event(event):
"""Маршрутизация событий энкодера внутри активного режима Encoder Control."""
global encoder_control_item
item = encoder_control_item
if item is None:
return
if event == EV_LONG_PRESS:
exited = item
encoder_control_item = None
if exited.get("exit_pipeline"):
if display:
display.show_executing(
exited.get("label", "?"),
trigger_bus.get_exit_action_name(exited["id"])
)
trigger_bus.fire_exit(exited["id"])
refresh_menu()
return
output_mode = item.get("output_mode")
if output_mode == "mouse":
if event == EV_ROTATE_RIGHT:
trigger_bus.execute_output("mouse", {"action": "scroll", "wheel": 3})
elif event == EV_ROTATE_LEFT:
trigger_bus.execute_output("mouse", {"action": "scroll", "wheel": -3})
elif event == EV_PRESS:
trigger_bus.execute_output("mouse", {"action": "click", "button": "right"})
elif output_mode == "scenario":
pipeline = None
if event == EV_ROTATE_RIGHT:
pipeline = item.get("on_rotate_right")
elif event == EV_ROTATE_LEFT:
pipeline = item.get("on_rotate_left")
elif event == EV_PRESS:
pipeline = item.get("on_click")
if pipeline:
if display:
event_label = {
EV_ROTATE_RIGHT: "-> Right",
EV_ROTATE_LEFT: "-> Left",
EV_PRESS: "-> Click",
}.get(event, "")
display.show_executing(item.get("label", "?"), event_label)
trigger_id = "encoder_ctrl_" + str(item.get("id", "?")) + "_" + str(event)
trigger_bus.execute_pipeline(
{"pipeline": pipeline, "loop": False},
trigger_id,
trigger_bus.PRIORITY_HIGH
)
def on_encoder_event(event):
"""
Вызывается из encoder.update() при каждом событии.
Синхронный вызов — не делать тут долгих операций.
"""
global menu_cursor, current_menu_list, last_interaction_time, screen_sleeping, screensaver_active, encoder_control_item
# ── Warning screen interception ───────────────────────────────────
if warning_screen and warning_screen.is_active:
if event == EV_PRESS:
# Центр: отменить триггер, показать CANCELED
inputs.cancel_ina_trigger()
warning_screen.show_canceled()
elif event in (EV_ROTATE_LEFT, EV_ROTATE_RIGHT):
# Скролл: dismiss warning без cooldown (snooze до восстановления батареи)
inputs.dismiss_ina_warning()
warning_screen.hide()
# EV_LONG_PRESS — пропускаем в обычную логику
if event != EV_LONG_PRESS:
return # блокируем обычную обработку
# ── конец перехвата ───────────────────────────────────────────
# Если экран погас или активна заставка — пробуждаем его первым действием (игнорируя клик/поворот)
if screen_sleeping or screensaver_active:
was_control = encoder_control_item is not None
wake_up_display()
# В Direct Control все события проходят сразу (включая выход вслепую);
# в обычном меню первое событие только будит экран.
if not was_control:
return
# Сбрасываем таймер активности
last_interaction_time = time.monotonic()
# Encoder Control: пока режим активен, события маршрутизируются
# отдельно и не попадают в обычную навигацию по меню
if encoder_control_item is not None:
_handle_encoder_control_event(event)
return
if event == EV_ROTATE_RIGHT:
if not current_menu_list:
return
# Проверка упора для геометрического корневого меню
if display and len(menu_stack) == 0 and display.is_geometric():
if menu_cursor >= len(current_menu_list) - 1:
display.bump("right")
return
old_label = get_current_label()
menu_cursor = (menu_cursor + 1) % len(current_menu_list)
new_label = get_current_label()
if display:
display.set_menu_items(current_menu_list)
display.set_menu_state(menu_cursor, len(current_menu_list), len(menu_stack))
display.animate_swipe(old_label, new_label, direction="right")
display.draw_menu(new_label, get_current_action())
elif event == EV_ROTATE_LEFT:
if not current_menu_list:
return
# Проверка упора для геометрического корневого меню
if display and len(menu_stack) == 0 and display.is_geometric():
if menu_cursor <= 0:
display.bump("left")
return
old_label = get_current_label()
menu_cursor = (menu_cursor - 1) % len(current_menu_list)
new_label = get_current_label()
if display:
display.set_menu_items(current_menu_list)
display.set_menu_state(menu_cursor, len(current_menu_list), len(menu_stack))
display.animate_swipe(old_label, new_label, direction="left")
display.draw_menu(new_label, get_current_action())
elif event == EV_PRESS:
if not current_menu_list:
return
item = current_menu_list[menu_cursor]
item_id = item["id"]
lbl = item.get("label", "?")
# 1. Если есть sequence или pipeline — выполняем команду (entry-action)
if "sequence" in item or "pipeline" in item:
action = get_current_action()
if display:
display.show_executing(lbl, action)
trigger_bus.fire_active(
item_id,
trigger_bus.PRIORITY_HIGH if item.get("type") == "encoder_control"
else trigger_bus.PRIORITY_NORMAL
)
# 2. Если есть submenu — проваливаемся внутрь
if "submenu" in item:
menu_stack.append((current_menu_list, menu_cursor))
current_menu_list = item["submenu"]
menu_cursor = 0
# 3. Encoder Control — активируем режим прямого управления
# (НЕ спуск по menu_stack, current_menu_list/menu_cursor не трогаем)
if item.get("type") == "encoder_control":
encoder_control_item = item
_enter_encoder_control_display(item)
return
# Обновляем экран
refresh_menu()
elif event == EV_LONG_PRESS:
# Возврат на уровень вверх
if menu_stack:
current_menu_list, menu_cursor = menu_stack.pop()
# После pop() current_menu_list[menu_cursor] — сама папка, из которой вышли
if current_menu_list:
exited = current_menu_list[menu_cursor]
if exited.get("exit_pipeline"):
if display:
display.show_executing(
exited.get("label", "?"),
trigger_bus.get_exit_action_name(exited["id"])
)
# Навигация не зависит от результата (busy/cooldown не мешают выйти)
trigger_bus.fire_exit(exited["id"])
refresh_menu()
else:
# Уже в корне — показываем статус
print("[main] long press — root menu")
if display:
display.show_status("Root Menu", "Cannot go back", "")
time.sleep(1.0)
refresh_menu()
# Подключаем callback — с этого момента encoder.update() будет его вызывать
if encoder:
encoder.set_callback(on_encoder_event)
# ── 6. Первый кадр ─────────────────────────────────────────────────────────
refresh_menu()
print("[main] Ready!")
# ── 7. Auto-Boot при отсутствии USB ────────────────────────────────────────
import supervisor
# ── 7. Auto-Boot Configuration ─────────────────────────────────────────────
# Ищем GPIO output с включенным auto_boot
auto_boot_enabled = False
auto_boot_next_check = time.monotonic() + 5
auto_boot_in_progress = False
auto_boot_last_attempt = 0
auto_boot_attempt_start = 0
auto_boot_output_name = None
check_interval = 15 # default, переопределяется из config
max_attempts = 2 # default, переопределяется из config
retry_cooldown_min = 5
boot_grace_end = time.monotonic() + 60
outputs_cfg = config.get_config().get("outputs", {})
for output_name, output_cfg in outputs_cfg.items():
# Ищем GPIO output с auto_boot секцией
if output_cfg.get("type") != "gpio":
continue
auto_boot_cfg = output_cfg.get("auto_boot")
if not auto_boot_cfg:
continue
if not auto_boot_cfg.get("enabled", False):
continue
# Проверка что сам output включен
if not output_cfg.get("enabled", False):
print(f"[auto_boot] WARNING: output '{output_name}' has auto_boot enabled but output itself is disabled — SKIPPED")
continue
# Нашли активный auto_boot
auto_boot_enabled = True
auto_boot_output_name = output_name
check_interval = auto_boot_cfg.get("check_interval_s", 15)
max_attempts = auto_boot_cfg.get("max_attempts", 2)
retry_cooldown_min = auto_boot_cfg.get("retry_cooldown_min", 5)
print(f"[auto_boot] Enabled: check_interval={check_interval}s, attempts={max_attempts}, retry_cooldown={retry_cooldown_min}min")
print(f"[auto_boot] Output: '{output_name}' (GPIO pin {output_cfg.get('pin')})")
print(f"[auto_boot] Will execute gpio_pulse directly on output")
print(f"[auto_boot] First check in 5 seconds...")
break # Используем только первый найденный
if not auto_boot_enabled:
print("[auto_boot] Disabled (no GPIO output with auto_boot.enabled found)")
# ── 8. Главный цикл ────────────────────────────────────────────────────────
while True:
# Inputs system: датчики, кнопка
inputs.update()
# Активная система: энкодер — события идут через on_encoder_event()
if encoder:
encoder.update()
# Trackball activity check
_act = inputs_manager.get_last_activity()
if _act > last_interaction_time:
if screen_sleeping or screensaver_active:
wake_up_display()
last_interaction_time = _act
# Таймер автовыключения / заставки экрана
now = time.monotonic()
if screen_timeout > 0 and (now - last_interaction_time) > screen_timeout:
if not screen_sleeping and not screensaver_active and not (splash_screen and splash_screen.is_active):
if screensaver_name == "off":
if display:
display.sleep()
screen_sleeping = True
print("[main] Display sleep")
else:
if display:
display.start_screensaver(screensaver_name)
screensaver_active = True
splash_trigger.reset_timer() # Сброс таймера при входе в screensaver
print("[main] Screensaver started:", screensaver_name)
# Обновление кадров заставки (~20 FPS)
ina_warning_blocking = warning_screen and warning_screen.is_active
if screensaver_active and now >= next_anim_t and not ina_warning_blocking:
if display:
display.update_screensaver()
next_anim_t = now + 0.05
# --- INA226 Warning logic ---
if warning_screen and inputs.ina_warning_active:
if not warning_screen.is_active:
pct = inputs.ina_warning_percent or 0
warning_screen.show(pct)
if warning_screen and warning_screen.is_active:
warning_screen.tick()
# --- INA226 Splash logic ---
is_idle = screensaver_active or screen_sleeping
if not ina_warning_blocking:
if splash_screen and splash_screen.is_active:
splash_screen.tick()
else:
# Check INA226 availability before triggering splash
power_monitor = inputs.get_power_monitor("ina226")
ina_available = power_monitor is not None and power_monitor.available
if splash_screen and splash_trigger.tick(is_idle, ina_available):
# Если дисплей спал — разбудить перед показом
if screen_sleeping and display:
display.wake()
screen_sleeping = False
# Get metrics from power monitor
if power_monitor:
metrics = power_monitor.get_metrics()
if metrics is not None:
splash_screen.show(metrics)
# --- Auto-Boot циклическая проверка ---
try:
if auto_boot_enabled and not auto_boot_in_progress and now >= auto_boot_next_check and not inputs.auto_boot_blocked and now <= boot_grace_end:
# Проверяем USB ДО начала цикла
usb_state = supervisor.runtime.usb_connected
# Логирование начала проверки (первый раз — очистить лог)
try:
log_mode = "w" if auto_boot_last_attempt == 0 and auto_boot_next_check <= now + 10 else "a"
with open("/auto_boot_log.txt", log_mode) as log:
if log_mode == "w":
log.write(f"=== AUTO_BOOT LOG START ({now:.1f}s) ===\n")
log.write(f"[{now:.1f}] Check: usb={usb_state}, next_check={auto_boot_next_check:.1f}\n")
except:
pass
if usb_state:
print(f"[auto_boot] USB connected — skipping cycle")
auto_boot_next_check = now + 15 # Проверять каждые 15 сек пока USB подключен
else:
# Начинаем новый цикл проверки
auto_boot_in_progress = True
auto_boot_last_attempt = 0 # Сброс счётчика
auto_boot_attempt_start = now
print(f"[auto_boot] Starting check cycle (retry_cooldown={retry_cooldown_min}min)")
# Логирование старта цикла
try:
with open("/auto_boot_log.txt", "a") as log:
log.write(f"[{now:.1f}] CYCLE START: usb={usb_state}\n")
except:
pass
if auto_boot_enabled and auto_boot_in_progress:
# Вычисляем текущую попытку по времени
elapsed = now - auto_boot_attempt_start
current_attempt = int(elapsed / check_interval) + 1
# Новая попытка: current_attempt больше чем last_attempt
if current_attempt > auto_boot_last_attempt:
auto_boot_last_attempt = current_attempt
usb_state = supervisor.runtime.usb_connected
# Логирование попытки
try:
with open("/auto_boot_log.txt", "a") as log:
log.write(f"[{now:.1f}] Attempt {current_attempt}/{max_attempts}: usb={usb_state}, elapsed={elapsed:.1f}s\n")
except:
pass
# Проверяем USB
if usb_state:
print(f"[auto_boot] USB connected — cycle canceled")
auto_boot_in_progress = False
# Следующая проверка через retry_cooldown
auto_boot_next_check = now + (retry_cooldown_min * 60)
print(f"[auto_boot] Next check in {retry_cooldown_min} minutes")
# Логирование отмены
try:
with open("/auto_boot_log.txt", "a") as log:
log.write(f"[{now:.1f}] CYCLE CANCELED: USB detected\n")
except:
pass
elif current_attempt <= max_attempts:
print(f"[auto_boot] Attempt {current_attempt}/{max_attempts}: USB not connected")
# Последняя попытка — запускаем сценарий
if current_attempt == max_attempts:
print(f"[auto_boot] Max attempts reached — triggering GPIO pulse on '{auto_boot_output_name}'")
# Логирование запуска
try:
with open("/auto_boot_log.txt", "a") as log:
log.write(f"[{now:.1f}] TRIGGERING GPIO: {auto_boot_output_name}\n")
except:
pass
if display:
display.show_status("Auto-Boot", "Starting server...", "")
time.sleep(1.5)
refresh_menu()
# Вызываем execute через публичный API
success = trigger_bus.execute_output(auto_boot_output_name, {"action": "gpio_pulse"})
if success:
print(f"[auto_boot] GPIO pulse executed successfully")
else:
print(f"[auto_boot] WARNING: GPIO pulse failed")
# Логирование завершения
try:
with open("/auto_boot_log.txt", "a") as log:
log.write(f"[{now:.1f}] GPIO PULSE {'SUCCESS' if success else 'FAILED'}\n")
except:
pass
auto_boot_in_progress = False
# Следующая проверка через retry_cooldown
auto_boot_next_check = now + (retry_cooldown_min * 60)
print(f"[auto_boot] Next check in {retry_cooldown_min} minutes")
except Exception as e:
# Критическая ошибка в auto_boot
try:
with open("/auto_boot_log.txt", "a") as log:
log.write(f"[{now:.1f}] ERROR: {e}\n")
except:
pass
print(f"[auto_boot] CRITICAL ERROR:", e)
auto_boot_in_progress = False
auto_boot_next_check = now + 60 # Повтор через минуту при ошибке
time.sleep(0.01)