-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisplay_driver.py
More file actions
1875 lines (1626 loc) · 65 KB
/
Copy pathdisplay_driver.py
File metadata and controls
1875 lines (1626 loc) · 65 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
# SPDX-FileCopyrightText: 2024 Brad Barnett
# SPDX-FileCopyrightText: 2021 Amir Gonnen (event_loop; MIT)
#
# SPDX-License-Identifier: MIT
"""
display_driver.py - LVGL displaydev/input wiring and event loop for PyDevices.
Canonical copy lives in PyDevices/lvgl-bindings (``python/display_driver.py``).
Consumer repos (lvgl-micropython, lvgl-circuitpython, lvgl-python)
vendor a synced copy; do not edit those copies directly.
Requires a valid ``board_config.py`` on the path. Importing this module creates
an LVGL-owned runtime, starts ``event_loop``, and registers display flush and
input devices. It intentionally does not depend on the optional ``eventsys``
application traffic controller.
``event_loop`` was adapted from upstream lv_utils (Amir Gonnen). Integration
changes kept intentionally small:
* Periodic tick from the local LVGL runtime instead of ``machine.Timer``.
* ``asyncio`` from ``multimer``.
* Sync path runs ``lv.task_handler()`` from the tick callback (re-entrancy
guarded); the runtime timer already delivers on the main thread.
* Async mode arms the refresh task lazily on the first timer tick so module-top
``import display_driver`` is safe before any event loop exists.
* No app-loop helper — LVGL apps call ``runtime.run_forever()``.
Interactive desktop (librt + REPL): ``task_handler`` / indev reads are paced at
``LVGL_PERIOD_MS`` (10 ms) with a wall-clock gate. Display refresh stays at
LVGL's ``LV_DEF_REFR_PERIOD`` (~33 ms). PARTIAL ``show()`` is gated to that
refresh cadence so presents do not track the faster task loop. The Runtime
timer stays at 10 ms; a host-pump subscription drains SDL/keys every tick so
the window cannot stall while LVGL is paused or slow.
"""
import gc
import sys
import board_config
display_drv = board_config.display_drv
import lvgl as lv
import events
import keys
try:
from multimer import asyncio, loop_running, ticks_add, ticks_diff, ticks_ms
except ImportError:
asyncio = None
loop_running = None
ticks_add = None
ticks_diff = None
ticks_ms = None
asyncio_available = asyncio is not None
LVGL_PERIOD_MS = 10
# Match LV_DEF_REFR_PERIOD in lv_conf.h — PARTIAL present cadence / display refresh.
LVGL_REFR_PERIOD_MS = 33
_driver_ref = None # primary DisplayDriver (compat)
_drivers = [] # all DisplayDriver instances
_host_pump_sub = None
_present_next_ok_ms = None
# Local input types. Values intentionally match LVGL's historical PyDevices
# bridge values so diagnostic code can inspect ``device.type`` without
# importing the optional eventsys package.
HOST = 0x01
POINTER = 0x02
ENCODER = 0x03
KEYPAD = 0x04
class InputDevice:
"""Small input adapter used only by the LVGL bridge."""
type = -1
responses = events.filter
def __init__(self, read=None, data=None, read2=None, data2=None):
self._read = read if read is not None else lambda: None
self._data = data
self._read2 = read2 if read2 is not None else lambda: None
self._data2 = data2
self._state = None
self._runtime = None
self._user_data = None
self._callbacks = []
@property
def runtime(self):
return self._runtime
@runtime.setter
def runtime(self, value):
self._runtime = value
@property
def user_data(self):
return self._user_data
@user_data.setter
def user_data(self, value):
self._user_data = value
def subscribe(self, callback, event_types=None):
if not callable(callback):
raise ValueError("callback is not callable")
item = (callback, event_types)
if item not in self._callbacks:
self._callbacks.append(item)
def unsubscribe(self, callback, event_types=None):
self._callbacks = [item for item in self._callbacks if item[0] is not callback]
def poll(self, *args):
raw = self._poll()
if raw is None:
return []
result = raw if isinstance(raw, list) else [raw]
result = [event for event in result if event.type in events.filter]
for event in result:
if self._runtime is not None:
self._runtime._dispatch_event(event, self)
for callback, event_types in tuple(self._callbacks):
if event_types is None or event.type in event_types:
callback(event, *args)
return result
class HostInput(InputDevice):
"""Adapt a host display's ``get_events`` callback for LVGL."""
type = HOST
def __init__(self, host_read, display=None, event_filter=None):
super().__init__(read=host_read, data=display, data2=event_filter or events.filter)
self.scale = getattr(display, "touch_scale", 1) if display is not None else 1
self._quit_chord_ok = hasattr(display, "quit_chord")
def _touch_scale_for(self, window_id):
panel = self._data
if window_id is not None and self._runtime is not None:
for candidate in self._runtime.displays:
if getattr(candidate, "_window_id", None) == window_id:
panel = candidate
break
scale = getattr(panel, "touch_scale", None) if panel is not None else None
if scale is None:
return self.scale
self.scale = scale
return scale
def _poll(self):
incoming = self._read()
if incoming is None:
return None
result = []
quit_chord = self._data.quit_chord if self._quit_chord_ok else None
chord_key = quit_chord[0] if quit_chord else None
for event in incoming:
if event.type == events.KEYDOWN and keys.chord_matches(
quit_chord, event.key, event.mod
):
event = events.Quit(events.QUIT)
elif event.type == events.KEYUP and quit_chord and event.key == chord_key:
continue
if event.type not in self._data2:
continue
if event.type in (
events.MOUSEMOTION,
events.MOUSEBUTTONDOWN,
events.MOUSEBUTTONUP,
):
scale = self._touch_scale_for(getattr(event, "window", None))
if scale and scale != 1:
pos = (int(event.pos[0] // scale), int(event.pos[1] // scale))
if event.type == events.MOUSEMOTION:
event = events.Motion(
event.type,
pos,
(event.rel[0] // scale, event.rel[1] // scale),
event.buttons,
event.touch,
event.window,
)
else:
event = events.Button(
event.type, pos, event.button, event.touch, event.window
)
result.append(event)
return result or None
_DEFAULT_TOUCH_ROTATION_TABLE = (0b000, 0b101, 0b110, 0b011)
_SWAP_XY = 0b001
_REVERSE_X = 0b010
_REVERSE_Y = 0b100
def _normalize_points(sample):
if not sample:
return ()
if isinstance(sample[0], int):
return (tuple(sample),)
return tuple(tuple(point) for point in sample)
class TouchInput(InputDevice):
"""Adapt a board touch callable to pointer events for LVGL."""
type = POINTER
responses = (events.MOUSEMOTION, events.MOUSEBUTTONDOWN, events.MOUSEBUTTONUP)
def __init__(self, read, display, rotation_table=None):
super().__init__(read=read, data=display, data2=rotation_table)
self._data2 = self._data2 or _DEFAULT_TOUCH_ROTATION_TABLE
self.rotation = display.rotation
try:
display.touch_device = self
except Exception:
pass
self.points = ()
@property
def rotation(self):
return self._rotation
@rotation.setter
def rotation(self, value):
self._rotation = value % 360
self._mask = self._data2[self._rotation // 90]
def _map_point(self, point):
x, y = int(point[0]), int(point[1])
if self._mask & _SWAP_XY:
x, y = y, x
if self._mask & _REVERSE_X:
x = self._data.width - x - 1
if self._mask & _REVERSE_Y:
y = self._data.height - y - 1
return (x, y) + tuple(point[2:]) if len(point) > 2 else (x, y)
def _poll(self):
try:
mapped = tuple(self._map_point(point) for point in _normalize_points(self._read()))
except OSError:
return None
self.points = mapped
if mapped:
x, y = int(mapped[0][0]), int(mapped[0][1])
previous = self._state
self._state = (x, y)
if previous is None:
return events.Button(events.MOUSEBUTTONDOWN, self._state, 1, False, None)
return events.Motion(
events.MOUSEMOTION,
self._state,
(x - previous[0], y - previous[1]),
(1, 0, 0),
False,
None,
)
if self._state is not None:
previous = self._state
self._state = None
return events.Button(events.MOUSEBUTTONUP, previous, 1, False, None)
return None
class KeypadInput(InputDevice):
"""Adapt a pressed-key collection to KEYDOWN/KEYUP events."""
type = KEYPAD
responses = (events.KEYDOWN, events.KEYUP)
def __init__(self, read):
super().__init__(read=read)
self._state = set()
@staticmethod
def _name(key):
name = keys.keyname(key)
if name != "Unknown":
return name
if isinstance(key, int) and 32 <= key <= 126:
return chr(key)
return "0x%x" % key if isinstance(key, int) else str(key)
def _poll(self):
current = set(self._read())
released = self._state - current
if released:
key = released.pop()
self._state.remove(key)
return events.Key(events.KEYUP, self._name(key), key, 0, 0, None)
pressed = current - self._state
if pressed:
key = pressed.pop()
self._state.add(key)
return events.Key(events.KEYDOWN, self._name(key), key, 0, 0, None)
return None
class EncoderInput(InputDevice):
"""Adapt an encoder position and optional button to LVGL events."""
type = ENCODER
responses = (events.MOUSEWHEEL, events.MOUSEBUTTONDOWN, events.MOUSEBUTTONUP)
def __init__(self, read, button_read=None, button=2):
super().__init__(read=read, read2=button_read, data=button)
self._state = (0, False)
def _poll(self):
last_pos, last_pressed = self._state
pressed = self._read2()
if pressed != last_pressed:
self._state = (last_pos, pressed)
return events.Button(
events.MOUSEBUTTONDOWN if pressed else events.MOUSEBUTTONUP,
(0, 0),
self._data,
False,
None,
)
pos = self._read()
if pos != last_pos:
steps = pos - last_pos
self._state = (pos, last_pressed)
if self._data % 2 == 0:
return events.Wheel(events.MOUSEWHEEL, False, 0, steps, 0, steps, False, None)
return events.Wheel(events.MOUSEWHEEL, False, steps, 0, steps, 0, False, None)
return None
_virtual_peers = {}
_virtual_pending = {}
class VirtualDevices:
"""Fan one host input into LVGL pointer, encoder, and keypad inputs."""
class VirtualDevice:
def __init__(self, owner, device_type):
self._owner = owner
self.type = device_type
self.user_data = None
self._fifo = []
self._callbacks = []
self._active_key_event = None
self.points = ()
self._fingers = {}
def subscribe(self, callback, event_types=None):
if callback not in self._callbacks:
self._callbacks.append(callback)
def unsubscribe(self, callback, event_types=None):
if callback in self._callbacks:
self._callbacks.remove(callback)
@property
def has_pending(self):
return bool(self._fifo)
def poll(self, *args):
self._owner.poll_host_device()
event = self._fifo.pop(0) if self._fifo else None
for callback in tuple(self._callbacks):
callback(event, *args)
def add_event(self, event):
if (
event.type == events.MOUSEMOTION
and self._fifo
and self._fifo[-1].type == events.MOUSEMOTION
):
self._fifo[-1] = event
return
if (
event.type == events.KEYDOWN
and self._fifo
and self._fifo[-1].type == events.KEYDOWN
and getattr(self._fifo[-1], "key", None) == getattr(event, "key", None)
):
self._fifo[-1] = event
return
if self.type == KEYPAD:
key = getattr(event, "key", None)
active = self._active_key_event
active_key = getattr(active, "key", None)
if event.type == events.KEYDOWN:
if active is not None and active_key != key:
self._fifo.append(
events.Key(
events.KEYUP,
active.name,
active.key,
active.mod,
active.scancode,
active.window,
)
)
self._active_key_event = event
elif event.type == events.KEYUP:
if active is not None and active_key != key:
return
self._active_key_event = None
self._fifo.append(event)
def _set_finger(self, finger_id, point):
if point is None:
self._fingers.pop(finger_id, None)
else:
self._fingers[finger_id] = point
self.points = tuple(
(pos[0], pos[1], fid) for fid, pos in self._fingers.items()
)
def __init__(self, host_device, window_id=None):
self._host_device = host_device
self._window_id = window_id
self._vd_pointer = self.VirtualDevice(self, POINTER)
self._vd_encoder = self.VirtualDevice(self, ENCODER)
self._vd_keypad = self.VirtualDevice(self, KEYPAD)
self.devices = [self._vd_pointer, self._vd_encoder, self._vd_keypad]
peers = _virtual_peers.setdefault(id(host_device), [])
peers.append(self)
self._peers = peers
def _accepts_window(self, event):
if self._window_id is None:
return True
window = getattr(event, "window", None)
return window is None or window == self._window_id
def poll_host_device(self):
if self._peers and self._peers[0] is not self:
return
pending = _virtual_pending.setdefault(id(self._host_device), [])
if not pending:
batch = self._host_device.poll()
if batch:
pending.extend(batch)
while pending:
event = pending.pop(0)
for peer in self._peers:
peer._route(event)
if event.type in (events.FINGERDOWN, events.FINGERUP, events.FINGERMOTION):
return
def _route(self, event):
if not self._accepts_window(event):
return
if event.type in (events.FINGERDOWN, events.FINGERMOTION):
pointer = self._vd_pointer
pointer._set_finger(event.finger_id, event.pos)
if pointer._fingers:
primary_id = min(pointer._fingers)
x, y = pointer._fingers[primary_id]
if event.finger_id == primary_id:
if event.type == events.FINGERDOWN:
pointer.add_event(
events.Button(
events.MOUSEBUTTONDOWN, (x, y), 1, True, event.window
)
)
else:
pointer.add_event(
events.Motion(
events.MOUSEMOTION,
(x, y),
(0, 0),
(1, 0, 0),
True,
event.window,
)
)
elif event.type == events.FINGERUP:
pointer = self._vd_pointer
was_primary = pointer._fingers and event.finger_id == min(pointer._fingers)
last = pointer._fingers.get(event.finger_id, event.pos)
pointer._set_finger(event.finger_id, None)
if was_primary:
pointer.add_event(
events.Button(events.MOUSEBUTTONUP, last, 1, True, event.window)
)
elif event.type in (events.MOUSEBUTTONDOWN, events.MOUSEBUTTONUP) or (
event.type == events.MOUSEMOTION and event.buttons[0]
):
if not (getattr(event, "touch", False) and self._vd_pointer._fingers):
self._vd_pointer.add_event(event)
elif event.type == events.MOUSEWHEEL:
self._vd_encoder.add_event(event)
elif event.type in (events.KEYDOWN, events.KEYUP):
self._vd_keypad.add_event(event)
class _TickSubscription:
def __init__(self, runtime, entry):
self._runtime = runtime
self._entry = entry
def deinit(self):
if self._entry is None:
return
try:
self._runtime._tick_callbacks.remove(self._entry)
except ValueError:
pass
self._entry = None
def _interactive_session():
main = sys.modules.get("__main__")
main_file = getattr(main, "__file__", None) if main is not None else None
if getattr(sys.implementation, "name", "") == "cpython":
return bool(getattr(getattr(sys, "flags", None), "interactive", 0)) or main_file is None
try:
with open("/proc/self/cmdline", "rb") as cmdline:
args = tuple(value for value in cmdline.read().split(b"\0") if value)
if b"-i" in args:
return True
if b"-m" in args or b"-c" in args:
return False
except Exception:
pass
return main_file is None or main_file in ("<stdin>", "<string>")
class LVGLRuntime:
"""Private traffic coordinator owned by this LVGL bridge."""
events = events
def __init__(self, config):
self._config = config
self._displays = [config.display_drv]
self.devices = []
self.host_dev = None
self.touch_dev = None
self.keypad_dev = None
self.encoder_dev = None
self._event_callbacks = {}
self._tick_callbacks = []
self._timer = None
self._timer_async = bool(
getattr(
config,
"timer_async",
getattr(config.display_drv, "requires_async_timer", False),
)
)
self._pending_timer_async = False
self._in_tick = False
self._quit_requested = False
self._exit_code = None
self._blocking = False
self._blocking_run_forever = False
self._before_quit = None
self._teardown_timer = None
self._teardown_done = False
host_read = getattr(config, "host_read", None)
if host_read is not None:
self.host_dev = self.register(HostInput(host_read, config.display_drv))
touch_read = getattr(config, "touch_read", None)
if touch_read is not None:
self.touch_dev = self.register(
TouchInput(
touch_read,
config.display_drv,
getattr(config, "touch_rotation_table", None),
)
)
keypad_read = getattr(config, "keypad_read", None)
if keypad_read is not None:
self.keypad_dev = self.register(KeypadInput(keypad_read))
encoder_read = getattr(config, "encoder_read", None)
if encoder_read is not None:
self.encoder_dev = self.register(
EncoderInput(
encoder_read,
getattr(config, "encoder_button_read", None),
)
)
@property
def timer_async(self):
return self._timer_async
@property
def displays(self):
return tuple(self._displays)
@property
def primary(self):
return self._displays[0] if self._displays else None
@property
def touch_device(self):
return self.touch_dev
@property
def quit_requested(self):
return self._quit_requested
@property
def before_quit(self):
return self._before_quit
@before_quit.setter
def before_quit(self, callback):
if callback is not None and not callable(callback):
raise ValueError("before_quit must be callable")
self._before_quit = callback
def register(self, device):
device.runtime = self
self.devices.append(device)
return device
def add_display(self, display):
if display not in self._displays:
self._displays.append(display)
return display
def add_encoder(self, read, *, button_read=None, button=2):
self.encoder_dev = self.register(EncoderInput(read, button_read, button))
return self.encoder_dev
def on(self, event_type, callback):
if isinstance(event_type, (list, tuple)):
for item in event_type:
self.on(item, callback)
return
callbacks = self._event_callbacks.setdefault(event_type, [])
if callback not in callbacks:
callbacks.append(callback)
def _dispatch_event(self, event, device):
if event.type == events.QUIT:
self.request_quit()
for callback in tuple(self._event_callbacks.get(event.type, ())):
callback(event)
def poll(self):
try:
from multimer._schedule import _run_pending
from multimer._select import _drain
_run_pending()
if _drain is not None:
_drain()
except ImportError:
pass
result = []
for device in self.devices:
result.extend(device.poll())
return result
def _ensure_ticks(self):
if ticks_ms is None:
raise RuntimeError("multimer ticks helpers are required")
def _start_timer(self, asynchronous):
if self._timer is not None:
return self._timer
from multimer import AsyncTimer, Timer
timer_type = AsyncTimer if asynchronous else Timer
timer = None
error = None
for timer_id in (-1, 0, 1, 2, 3):
try:
timer = timer_type(timer_id)
break
except ValueError as exc:
error = exc
if timer is None:
raise error
self._timer = timer
timer.init(
mode=timer_type.PERIODIC,
period=LVGL_PERIOD_MS,
callback=self._dispatch_tick,
hard=False,
)
return timer
def _dispatch_tick(self, timer):
if self._in_tick or self._quit_requested:
return
self._in_tick = True
try:
now = ticks_ms()
for entry in tuple(self._tick_callbacks):
if ticks_diff(entry[2], now) > 0:
continue
entry[2] = ticks_add(now, entry[1])
entry[0](timer)
finally:
self._in_tick = False
if self._quit_requested and not self._blocking:
self._defer_teardown()
def on_tick(self, callback, *, period, async_=False):
if not callable(callback):
raise ValueError("callback is not callable")
self._ensure_ticks()
if self._timer is None:
if async_ and not _asyncio_loop_running():
self._pending_timer_async = True
else:
self._start_timer(async_)
entry = [callback, int(period), ticks_add(ticks_ms(), int(period))]
self._tick_callbacks.append(entry)
return _TickSubscription(self, entry)
def stop_timer(self):
self._tick_callbacks = []
timer = self._timer
self._timer = None
self._pending_timer_async = False
if timer is not None:
timer.deinit()
def _arm_async(self):
inst = event_loop.current_instance()
if inst is not None:
inst.arm()
if self._pending_timer_async and self._timer is None:
self._start_timer(True)
self._pending_timer_async = False
async def run(self, tick_ms=LVGL_PERIOD_MS):
if asyncio is None:
raise RuntimeError("asyncio is not available")
self._arm_async()
self._blocking = True
self._blocking_run_forever = True # harness / eventsys duck-typing parity
try:
while not self._quit_requested:
await asyncio.sleep(tick_ms / 1000)
try:
from multimer import run_deadline_hook
run_deadline_hook()
except ImportError:
pass
finally:
self._blocking = False
self._blocking_run_forever = False
self._perform_teardown()
self._raise_exit_code()
def run_forever(self, tick_ms=LVGL_PERIOD_MS):
import multimer
if self._timer_async:
if _asyncio_loop_running():
self._arm_async()
return
if asyncio is None:
raise RuntimeError("asyncio is not available")
asyncio.run(self.run(tick_ms))
self._raise_exit_code()
return
if _interactive_session() and multimer.uses_signals():
return
self._blocking = True
self._blocking_run_forever = True # harness / eventsys duck-typing parity
try:
while not self._quit_requested:
multimer.sleep_ms(tick_ms)
finally:
self._blocking = False
self._blocking_run_forever = False
self._perform_teardown()
self._raise_exit_code()
def run_async(self, coro_or_fn):
if asyncio is None:
raise RuntimeError("asyncio is not available")
async def runner():
self._arm_async()
coro = coro_or_fn() if callable(coro_or_fn) else coro_or_fn
return await coro
if _asyncio_loop_running():
return asyncio.create_task(runner())
return asyncio.run(runner())
def request_quit(self, code=None):
self._quit_requested = True
if code is not None:
self._exit_code = int(code)
if not self._in_tick and not self._blocking:
self._perform_teardown()
def _raise_exit_code(self):
if self._exit_code is None:
return
code = self._exit_code
self._exit_code = None
raise SystemExit(code)
def _defer_teardown(self):
if self._teardown_done or self._teardown_timer is not None:
return
from multimer import Timer
helper = None
error = None
for timer_id in (-1, 0, 1, 2, 3):
try:
helper = Timer(timer_id)
break
except ValueError as exc:
error = exc
if helper is None:
raise error
self._teardown_timer = helper
def finish(_timer):
self._teardown_timer = None
self._perform_teardown()
helper.init(mode=Timer.ONE_SHOT, period=1, callback=finish, hard=False)
def _perform_teardown(self):
if self._teardown_done:
return
self._teardown_done = True
if self._before_quit is not None:
self._before_quit()
self.stop_timer()
for panel in tuple(self._displays):
close = getattr(panel, "quit", None) or getattr(panel, "deinit", None)
if callable(close):
try:
close()
except Exception:
pass
self._displays = []
runtime = LVGLRuntime(board_config)
def _asyncio_loop_running():
"""True when an asyncio loop is already running (host loop or inside a task)."""
if loop_running is None:
return False
return loop_running()
class event_loop:
"""LVGL task loop driven by ``LVGLRuntime.on_tick``.
One instance may be active at a time. Sync mode runs ``lv.task_handler``
from the shared timer; async mode signals an asyncio refresh task.
Prefer ``import display_driver`` (module ``main()``) over constructing this
by hand unless you need custom ``freq`` / ``asynchronous`` settings.
"""
_current_instance = None
def __init__(
self,
freq=None,
max_scheduled=2,
refresh_cb=None,
asynchronous=False,
exception_sink=None,
period_ms=None,
):
"""Create and register the LVGL event loop.
Args:
freq: Desired Hz when ``period_ms`` is omitted (period = ``1000 // freq``).
max_scheduled: Kept for lv_utils API parity (unused).
refresh_cb: Optional zero-arg callable after each successful
``lv.task_handler()``.
asynchronous: When True, drive LVGL via an asyncio refresh task.
exception_sink: Callable receiving exceptions from task handling;
defaults to :meth:`default_exception_sink`.
period_ms: Explicit tick period in milliseconds (overrides ``freq``).
Raises:
RuntimeError: Another loop is already running or async mode is
requested without asyncio.
"""
if self.is_running():
raise RuntimeError("Event loop is already running!")
if not lv.is_initialized():
lv.init()
event_loop._current_instance = self
if period_ms is not None:
self.delay = int(period_ms)
elif freq is not None:
self.delay = max(1, 1000 // int(freq))
else:
self.delay = LVGL_PERIOD_MS
self.refresh_cb = refresh_cb
self.exception_sink = exception_sink if exception_sink else self.default_exception_sink
# Start paused and do not arm machine.Timer until ``enable()``. On
# ESP32-P4, even a no-op timer callback interrupting SPIRAM
# ``draw_buf_create`` corrupts LVGL handlers (Illegal instruction,
# MTVAL often an ASCII fragment like ``star``).
self._pause = 1
self._in_task = False
self._next_ok_ms = None
self._last_tick_ms = None
self.asynchronous = asynchronous
self.refresh_task = None
self._timer_sub = None
self._async_armed = False
if self.asynchronous:
if not asyncio_available:
raise RuntimeError("Cannot run asynchronous event loop. asyncio is not available!")
self.refresh_event = asyncio.Event()
if _asyncio_loop_running():
self.arm()
# Sync: defer ``on_tick`` until first ``enable()`` (see ``_arm_sync_timer``).
def _arm_sync_timer(self):
"""Subscribe the sync tick once; safe to call repeatedly."""
if self.asynchronous:
return
# runtime.stop_timer() deinits the HW timer and clears callbacks but
# does not notify us — drop a stale handle so we can re-subscribe.
if self._timer_sub is not None:
if runtime._timer is not None:
return
self._timer_sub = None
self._timer_sub = runtime.on_tick(self.timer_cb, period=self.delay, async_=False)
def arm(self):
"""Create the async refresh task + shared timer once a loop is running.
No-op in sync mode or when already armed. Safe to call repeatedly.
"""
if not self.asynchronous or self._async_armed:
return
self._async_armed = True
self.refresh_task = asyncio.create_task(self.async_refresh())
self._timer_sub = runtime.on_tick(self.timer_cb, period=self.delay, async_=True)
def deinit(self):
"""Stop the tick subscription / async task and clear the singleton."""
if getattr(self, "_timer_sub", None) is not None:
self._timer_sub.deinit()
self._timer_sub = None
if self.asynchronous and self.refresh_task is not None:
self.refresh_task.cancel()
self.refresh_task = None
self._async_armed = False
event_loop._current_instance = None
def disable(self):
"""Pause LVGL task handling (re-entrant; pair with :meth:`enable`)."""
# Pause LVGL task handling (e.g. while building the UI). Re-entrant.
self._pause += 1
def enable(self):
"""Resume LVGL task handling after :meth:`disable`; arms the sync timer."""
if self._pause > 0:
self._pause -= 1
if self._pause == 0:
self._arm_sync_timer()
# Async path: arm refresh task + timer_cb if import-time construction
# could not (MicroPython lacks get_running_loop; UI builders that
# disable()/enable() around layout also land here).
if self.asynchronous and not self._async_armed and _asyncio_loop_running():
self.arm()
@staticmethod
def is_running():
"""True when an :class:`event_loop` instance is currently registered."""
return event_loop._current_instance is not None
@staticmethod
def current_instance():
"""Return the active :class:`event_loop`, or ``None``."""
return event_loop._current_instance
def task_handler(self, _=None):
"""Run ``lv.task_handler()`` once when not paused and not nested."""