omnipython 0.0.1__py3-none-any.whl → 0.8.0.dev25__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. appdev/__init__.py +64 -0
  2. appdev/__init__.pyi +11 -0
  3. appdev/app.py +607 -0
  4. appdev/app.pyi +143 -0
  5. appdev/devices.py +549 -0
  6. appdev/devices.pyi +178 -0
  7. appdev/py.typed +0 -0
  8. audiodev/__init__.py +1566 -0
  9. audiodev/__init__.pyi +384 -0
  10. audiodev/accel.py +73 -0
  11. audiodev/accel.pyi +14 -0
  12. audiodev/alsa_audio.py +510 -0
  13. audiodev/alsa_audio.pyi +85 -0
  14. audiodev/android_audio.py +140 -0
  15. audiodev/android_audio.pyi +21 -0
  16. audiodev/auto.py +166 -0
  17. audiodev/auto.pyi +22 -0
  18. audiodev/bytequeue.py +181 -0
  19. audiodev/bytequeue.pyi +39 -0
  20. audiodev/emulated_audio.py +384 -0
  21. audiodev/emulated_audio.pyi +104 -0
  22. audiodev/i2s_audio.py +249 -0
  23. audiodev/i2s_audio.pyi +41 -0
  24. audiodev/pump.py +2210 -0
  25. audiodev/pump.pyi +314 -0
  26. audiodev/pwm_tone.py +65 -0
  27. audiodev/pwm_tone.pyi +30 -0
  28. audiodev/py.typed +0 -0
  29. audiodev/pygame_audio.py +908 -0
  30. audiodev/pygame_audio.pyi +86 -0
  31. audiodev/sample_out.py +1110 -0
  32. audiodev/sample_out.pyi +98 -0
  33. audiodev/sdl2_audio.py +903 -0
  34. audiodev/sdl2_audio.pyi +102 -0
  35. audiodev/wasm_audio.py +80 -0
  36. audiodev/wasm_audio.pyi +39 -0
  37. audiodev/web_audio.py +517 -0
  38. audiodev/web_audio.pyi +45 -0
  39. audiodev/win_audio.py +630 -0
  40. audiodev/win_audio.pyi +103 -0
  41. audiodev/worklet_audio.py +381 -0
  42. audiodev/worklet_audio.pyi +90 -0
  43. backends-stubs/__init__.pyi +30 -0
  44. backends.py +184 -0
  45. bledev/__init__.py +1120 -0
  46. bledev/__init__.pyi +308 -0
  47. bledev/_sig.py +77 -0
  48. bledev/auto.py +88 -0
  49. bledev/auto.pyi +13 -0
  50. bledev/battery.py +63 -0
  51. bledev/battery.pyi +20 -0
  52. bledev/bleak.py +728 -0
  53. bledev/bleak.pyi +37 -0
  54. bledev/cpble.py +1120 -0
  55. bledev/cpble.pyi +45 -0
  56. bledev/cyclingpower.py +211 -0
  57. bledev/cyclingpower.pyi +61 -0
  58. bledev/cyclingspeed.py +155 -0
  59. bledev/cyclingspeed.pyi +47 -0
  60. bledev/deviceinfo.py +85 -0
  61. bledev/deviceinfo.pyi +37 -0
  62. bledev/environmental.py +118 -0
  63. bledev/environmental.pyi +30 -0
  64. bledev/fake.py +735 -0
  65. bledev/fake.pyi +65 -0
  66. bledev/filetransfer.py +895 -0
  67. bledev/filetransfer.pyi +111 -0
  68. bledev/heartrate.py +148 -0
  69. bledev/heartrate.pyi +33 -0
  70. bledev/hid.py +574 -0
  71. bledev/hid.pyi +152 -0
  72. bledev/hid_gamepad.py +125 -0
  73. bledev/hid_gamepad.pyi +24 -0
  74. bledev/hidreport.py +704 -0
  75. bledev/hidreport.pyi +147 -0
  76. bledev/improv.py +636 -0
  77. bledev/improv.pyi +131 -0
  78. bledev/midi.py +534 -0
  79. bledev/midi.pyi +88 -0
  80. bledev/midi_codec.py +423 -0
  81. bledev/midi_codec.pyi +41 -0
  82. bledev/mpble.py +949 -0
  83. bledev/mpble.pyi +41 -0
  84. bledev/nus.py +386 -0
  85. bledev/nus.pyi +41 -0
  86. bledev/py.typed +0 -0
  87. bledev/repl.py +1032 -0
  88. bledev/repl.pyi +81 -0
  89. bledev/runningspeed.py +165 -0
  90. bledev/runningspeed.pyi +50 -0
  91. bledev/security.py +630 -0
  92. bledev/security.pyi +89 -0
  93. bledev/webble.py +639 -0
  94. bledev/webble.pyi +33 -0
  95. boarddev-stubs/__init__.pyi +76 -0
  96. boarddev.py +561 -0
  97. display_driver-stubs/__init__.pyi +131 -0
  98. display_driver.py +1916 -0
  99. displaydev/__init__.py +1288 -0
  100. displaydev/__init__.pyi +118 -0
  101. displaydev/_desktop.py +268 -0
  102. displaydev/_domkeys.py +185 -0
  103. displaydev/_webcanvas.py +184 -0
  104. displaydev/_webinput.py +290 -0
  105. displaydev/androidsdl.py +384 -0
  106. displaydev/androidsdl.pyi +15 -0
  107. displaydev/auto.py +282 -0
  108. displaydev/auto.pyi +13 -0
  109. displaydev/busdisplay.py +706 -0
  110. displaydev/busdisplay.pyi +43 -0
  111. displaydev/fbdisplay.py +442 -0
  112. displaydev/fbdisplay.pyi +25 -0
  113. displaydev/jndisplay.py +525 -0
  114. displaydev/jndisplay.pyi +31 -0
  115. displaydev/pgdisplay.py +527 -0
  116. displaydev/pgdisplay.pyi +47 -0
  117. displaydev/pixeldisplay.py +312 -0
  118. displaydev/pixeldisplay.pyi +48 -0
  119. displaydev/psdisplay.py +185 -0
  120. displaydev/psdisplay.pyi +48 -0
  121. displaydev/py.typed +0 -0
  122. displaydev/sdldisplay.py +866 -0
  123. displaydev/sdldisplay.pyi +47 -0
  124. displaydev/wasmdisplay.py +381 -0
  125. displaydev/wasmdisplay.pyi +29 -0
  126. displaydev/windisplay.py +788 -0
  127. displaydev/windisplay.pyi +35 -0
  128. displaydev/workerdisplay.py +161 -0
  129. displaydev/workerdisplay.pyi +51 -0
  130. events-stubs/__init__.pyi +109 -0
  131. events.py +122 -0
  132. keys-stubs/__init__.pyi +277 -0
  133. keys.py +680 -0
  134. medialink/__init__.py +75 -0
  135. medialink/__init__.pyi +52 -0
  136. medialink/_compat.py +97 -0
  137. medialink/codec.py +172 -0
  138. medialink/codec.pyi +47 -0
  139. medialink/discovery.py +408 -0
  140. medialink/discovery.pyi +60 -0
  141. medialink/intercom.py +407 -0
  142. medialink/intercom.pyi +52 -0
  143. medialink/link.py +486 -0
  144. medialink/link.pyi +100 -0
  145. medialink/packet.py +78 -0
  146. medialink/packet.pyi +33 -0
  147. medialink/py.typed +0 -0
  148. medialink/transport.py +179 -0
  149. medialink/transport.pyi +35 -0
  150. medialink/video.py +240 -0
  151. medialink/video.pyi +61 -0
  152. medialink/voice.py +169 -0
  153. medialink/voice.pyi +40 -0
  154. medialink/wakeword.py +167 -0
  155. medialink/wakeword.pyi +65 -0
  156. multimer/__init__.py +170 -0
  157. multimer/__init__.pyi +157 -0
  158. multimer/_asyncio_loader.py +77 -0
  159. multimer/_dispatch.py +990 -0
  160. multimer/_hostloop.py +458 -0
  161. multimer/_inputhook.py +102 -0
  162. multimer/_mpasyncio.py +347 -0
  163. multimer/_repl.py +153 -0
  164. multimer/_src_asyncio.py +75 -0
  165. multimer/_src_machine.py +463 -0
  166. multimer/_src_native.py +56 -0
  167. multimer/_src_none.py +29 -0
  168. multimer/_src_pending.py +142 -0
  169. multimer/_src_signal.py +270 -0
  170. multimer/_src_wasm.py +82 -0
  171. multimer/_ticks.py +243 -0
  172. multimer/py.typed +0 -0
  173. omip-stubs/__init__.pyi +27 -0
  174. omip.py +876 -0
  175. omnipython-0.8.0.dev25.dist-info/METADATA +16 -0
  176. omnipython-0.8.0.dev25.dist-info/RECORD +184 -0
  177. omnipython-0.8.0.dev25.dist-info/top_level.txt +24 -0
  178. orientation-stubs/__init__.pyi +18 -0
  179. orientation.py +98 -0
  180. wifi-stubs/__init__.pyi +91 -0
  181. wifi.py +449 -0
  182. wifi_manager-stubs/__init__.pyi +58 -0
  183. wifi_manager.py +1441 -0
  184. omnipython-0.0.1.dist-info/METADATA +0 -19
  185. omnipython-0.0.1.dist-info/RECORD +0 -4
  186. omnipython-0.0.1.dist-info/top_level.txt +0 -1
  187. {omnipython-0.0.1.dist-info → omnipython-0.8.0.dev25.dist-info}/WHEEL +0 -0
appdev/__init__.py ADDED
@@ -0,0 +1,64 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """appdev — application coordinator and event loop for every Python.
5
+
6
+ Quick start::
7
+
8
+ import board_config
9
+ import appdev
10
+ import events
11
+
12
+ app = appdev.App(board_config)
13
+
14
+ @app.on(events.KEYDOWN)
15
+ def on_key(e):
16
+ print("Key pressed:", e.key)
17
+
18
+ @app.every(1000)
19
+ def heartbeat(timer=None):
20
+ print("Heartbeat")
21
+
22
+ app.run()
23
+ """
24
+
25
+ from .app import (
26
+ DEFAULT_REFRESH_MS,
27
+ App,
28
+ )
29
+ from .devices import (
30
+ ENCODER,
31
+ HOST,
32
+ JOYSTICK,
33
+ KEYPAD,
34
+ POINTER,
35
+ Device,
36
+ Encoder,
37
+ HostEvents,
38
+ Joystick,
39
+ JoyMap,
40
+ Keypad,
41
+ Touch,
42
+ TouchGrid,
43
+ )
44
+
45
+ __version__ = "0.1.3"
46
+
47
+ __all__ = [
48
+ "DEFAULT_REFRESH_MS",
49
+ "ENCODER",
50
+ "HOST",
51
+ "JOYSTICK",
52
+ "KEYPAD",
53
+ "POINTER",
54
+ "App",
55
+ "Device",
56
+ "Encoder",
57
+ "HostEvents",
58
+ "JoyMap",
59
+ "Joystick",
60
+ "Keypad",
61
+ "Touch",
62
+ "TouchGrid",
63
+ "__version__",
64
+ ]
appdev/__init__.pyi ADDED
@@ -0,0 +1,11 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """appdev: application coordinator and event loop for every Python."""
5
+
6
+ from .app import App as App, DEFAULT_REFRESH_MS as DEFAULT_REFRESH_MS
7
+ from .devices import Device as Device, ENCODER as ENCODER, Encoder as Encoder, HOST as HOST, HostEvents as HostEvents, JOYSTICK as JOYSTICK, JoyMap as JoyMap, Joystick as Joystick, KEYPAD as KEYPAD, Keypad as Keypad, POINTER as POINTER, Touch as Touch, TouchGrid as TouchGrid
8
+
9
+ __all__ = ['DEFAULT_REFRESH_MS', 'App', 'ENCODER', 'HOST', 'JOYSTICK', 'KEYPAD', 'POINTER', 'Device', 'Encoder', 'HostEvents', 'Joystick', 'JoyMap', 'Keypad', 'Touch', 'TouchGrid', '__version__']
10
+
11
+ __version__: str
appdev/app.py ADDED
@@ -0,0 +1,607 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """App: devices, events, display refresh and lifecycle, on multimer's timers.
5
+
6
+ An ``App`` owns no timer machinery of its own. ``app.every(ms, fn)`` is
7
+ ``multimer.every``; the device service tick and each display's refresh are
8
+ ordinary timers you can see in ``multimer.report()``; and staying alive past
9
+ the end of the script body is ``multimer.keepalive``, which the App sets
10
+ when it has a display or a subscription. So a script that builds its UI and
11
+ ends keeps running, at the prompt under ``-i`` and in the exit hook
12
+ otherwise, with or without LVGL, and ``app.run()`` is only for a program
13
+ that wants to block.
14
+ """
15
+
16
+ import sys
17
+
18
+ import events
19
+ import keys
20
+ import multimer
21
+ from multimer import _hostloop
22
+
23
+ from .devices import (
24
+ ENCODER,
25
+ HOST,
26
+ JOYSTICK,
27
+ KEYPAD,
28
+ POINTER,
29
+ Encoder,
30
+ HostEvents,
31
+ Joystick,
32
+ Keypad,
33
+ Touch,
34
+ )
35
+
36
+ DEFAULT_REFRESH_MS = 33
37
+ SERVICE_TICK_MS = 10
38
+
39
+
40
+ class _RefreshClaim:
41
+ def __init__(self, app):
42
+ self._app = app
43
+
44
+ def release(self):
45
+ self._app.resume_refresh()
46
+
47
+
48
+ class _PollingClaim:
49
+ def __init__(self, app):
50
+ self._app = app
51
+
52
+ def release(self):
53
+ self._app.resume_polling()
54
+
55
+
56
+ class _RefreshPaused:
57
+ def __init__(self, app):
58
+ self._app = app
59
+ self._claim = None
60
+
61
+ def __enter__(self):
62
+ self._claim = self._app.pause_refresh()
63
+ return self._claim
64
+
65
+ def __exit__(self, exc_type, exc_val, exc_tb):
66
+ if self._claim is not None:
67
+ self._claim.release()
68
+ return False
69
+
70
+
71
+ class App:
72
+ """Application coordinator: devices, event dispatch, display refresh, lifecycle."""
73
+
74
+ _current = None
75
+ events = events
76
+ keys = keys
77
+ HOST = HOST
78
+ POINTER = POINTER
79
+ ENCODER = ENCODER
80
+ KEYPAD = KEYPAD
81
+ JOYSTICK = JOYSTICK
82
+
83
+ @classmethod
84
+ def current(cls):
85
+ """Return the currently active App instance, or None."""
86
+ return cls._current
87
+
88
+ def __init__(
89
+ self,
90
+ board_config=None,
91
+ *,
92
+ displays=None,
93
+ host_read=None,
94
+ touch_read=None,
95
+ touch_rotation_table=None,
96
+ refresh_period=None,
97
+ ):
98
+ prev = App._current
99
+ if prev is not None and prev is not self:
100
+ # A second App in one process (sequential apps, a test suite):
101
+ # the first one's timers must not keep dispatching into it.
102
+ try:
103
+ prev.stop_timers()
104
+ except Exception:
105
+ pass
106
+ App._current = self
107
+ self.devices = []
108
+ self._event_callbacks = {}
109
+ self._subscriptions = []
110
+ self._before_quit = None
111
+ self._on_quit = []
112
+ self._quit_requested = False
113
+ self._exit_code = None
114
+ self._refresh_timers = []
115
+ self._refresh_period = refresh_period
116
+ self._refresh_paused = False
117
+ self._refresh_claim = None
118
+ self._service_timer = None
119
+ self._polling_claim = None
120
+ self._app_drives_poll = False
121
+ self._in_service_poll = False
122
+ self._teardown_done = False
123
+
124
+ if displays is not None:
125
+ self._displays = list(displays)
126
+ elif board_config is not None and getattr(board_config, "display_drv", None) is not None:
127
+ self._displays = [board_config.display_drv]
128
+ elif board_config is not None and hasattr(board_config, "width") and hasattr(board_config, "height"):
129
+ self._displays = [board_config]
130
+ else:
131
+ self._displays = []
132
+
133
+ for drv in self._displays:
134
+ try:
135
+ drv.app = self
136
+ except Exception:
137
+ pass
138
+
139
+ primary = self.primary
140
+
141
+ effective_host_read = (
142
+ host_read
143
+ if host_read is not None
144
+ else getattr(board_config, "host_read", None) or getattr(board_config, "get_events", None)
145
+ )
146
+ if effective_host_read is not None:
147
+ self.host_dev = HostEvents(host_read=effective_host_read, display=primary)
148
+ self.register(self.host_dev)
149
+ else:
150
+ self.host_dev = None
151
+
152
+ effective_touch_read = touch_read if touch_read is not None else getattr(board_config, "touch_read", None)
153
+ effective_touch_table = (
154
+ touch_rotation_table
155
+ if touch_rotation_table is not None
156
+ else getattr(board_config, "touch_rotation_table", None)
157
+ )
158
+ if effective_touch_read is not None:
159
+ self.touch_dev = self.add_touch(
160
+ effective_touch_read, display=primary, rotation_table=effective_touch_table
161
+ )
162
+ else:
163
+ self.touch_dev = None
164
+
165
+ keypad_read = getattr(board_config, "keypad_read", None)
166
+ if keypad_read is not None:
167
+ self.add_keypad(keypad_read)
168
+ else:
169
+ self.keypad_dev = None
170
+
171
+ encoder_read = getattr(board_config, "encoder_read", None)
172
+ if encoder_read is not None:
173
+ self.add_encoder(encoder_read, button_read=getattr(board_config, "encoder_button_read", None))
174
+ else:
175
+ self.encoder_dev = None
176
+
177
+ joystick_driver = getattr(board_config, "joystick_driver", None)
178
+ if joystick_driver is not None:
179
+ emulate_digital = getattr(board_config, "joystick_emulate_digital", None)
180
+ self.add_joystick(joystick_driver=joystick_driver, emulate_digital=emulate_digital)
181
+ else:
182
+ self.joystick_dev = None
183
+
184
+ _hostloop.on_stop(self._teardown_from_loop)
185
+ if self._displays:
186
+ self._wire_display_refresh(self._refresh_period)
187
+ self._keep_alive()
188
+
189
+ # -- properties --------------------------------------------------------
190
+
191
+ @property
192
+ def strategy(self):
193
+ """How the program stays alive past the script body (see ``multimer.strategy``)."""
194
+ return multimer.strategy()
195
+
196
+ @property
197
+ def displays(self):
198
+ return tuple(self._displays)
199
+
200
+ @property
201
+ def primary(self):
202
+ return self._displays[0] if self._displays else None
203
+
204
+ @property
205
+ def quit_requested(self):
206
+ return self._quit_requested
207
+
208
+ @property
209
+ def before_quit(self):
210
+ return self._before_quit
211
+
212
+ @before_quit.setter
213
+ def before_quit(self, value):
214
+ if value is not None and not callable(value):
215
+ raise ValueError("before_quit must be callable")
216
+ self._before_quit = value
217
+
218
+ def on_quit(self, callback):
219
+ """Call *callback()* at quit, after ``before_quit``, in the order added.
220
+
221
+ Unlike ``before_quit``, any number of callbacks can be added, and
222
+ adding one never replaces another. Returns *callback*, so it works
223
+ as a decorator. An exception in one is printed and the rest still run.
224
+ """
225
+ if not callable(callback):
226
+ raise ValueError("on_quit needs a callable")
227
+ self._on_quit.append(callback)
228
+ return callback
229
+
230
+ @property
231
+ def timers(self):
232
+ """The App's own timers: service, refresh and every() subscriptions."""
233
+ out = []
234
+ if self._service_timer is not None:
235
+ out.append(self._service_timer)
236
+ out.extend(self._refresh_timers)
237
+ out.extend(t for t in self._subscriptions if t.running)
238
+ return tuple(out)
239
+
240
+ # -- displays and devices ---------------------------------------------
241
+
242
+ def add_display(self, drv):
243
+ if drv is None:
244
+ raise ValueError("drv is required")
245
+ if drv in self._displays:
246
+ return drv
247
+ first = not self._displays
248
+ self._displays.append(drv)
249
+ try:
250
+ drv.app = self
251
+ except Exception:
252
+ pass
253
+ if first:
254
+ self._wire_display_refresh(self._refresh_period)
255
+ self._keep_alive()
256
+ elif getattr(drv, "needs_refresh", False):
257
+ self._wire_one_refresh(drv, self._refresh_period)
258
+ return drv
259
+
260
+ def remove_display(self, drv):
261
+ if drv not in self._displays:
262
+ return
263
+ was_primary = drv is self.primary
264
+ self._displays.remove(drv)
265
+ for t in tuple(self._refresh_timers):
266
+ if getattr(t, "_display", None) is drv:
267
+ t.deinit()
268
+ self._refresh_timers.remove(t)
269
+ try:
270
+ drv.app = None
271
+ except Exception:
272
+ pass
273
+ if callable(getattr(drv, "quit", None)):
274
+ try:
275
+ drv.quit()
276
+ except Exception:
277
+ pass
278
+ elif callable(getattr(drv, "deinit", None)):
279
+ try:
280
+ drv.deinit()
281
+ except Exception:
282
+ pass
283
+ if was_primary or not self._displays:
284
+ self.request_quit()
285
+
286
+ def add_touch(self, read, *, display=None, rotation_table=None):
287
+ if display is None:
288
+ display = self.primary
289
+ if display is None:
290
+ raise ValueError("Touch requires a display")
291
+ touch = Touch(read=read, display=display, rotation_table=rotation_table)
292
+ self.register(touch)
293
+ if display is self.primary:
294
+ self.touch_dev = touch
295
+ return touch
296
+
297
+ def add_keypad(self, read):
298
+ keypad = Keypad(read=read)
299
+ self.register(keypad)
300
+ self.keypad_dev = keypad
301
+ return keypad
302
+
303
+ def add_encoder(self, read, *, button_read=None, button=2):
304
+ encoder = Encoder(read=read, button_read=button_read, button=button)
305
+ self.register(encoder)
306
+ self.encoder_dev = encoder
307
+ return encoder
308
+
309
+ def add_joystick(self, joystick_driver, *, emulate_digital=None, digital_threshold=0.5):
310
+ joystick = Joystick(
311
+ joystick_driver=joystick_driver,
312
+ emulate_digital=emulate_digital,
313
+ digital_threshold=digital_threshold,
314
+ )
315
+ self.register(joystick)
316
+ self.joystick_dev = joystick
317
+ return joystick
318
+
319
+ def register(self, dev):
320
+ dev.app = self
321
+ if dev not in self.devices:
322
+ self.devices.append(dev)
323
+ self._arm_service()
324
+
325
+ def unregister(self, dev):
326
+ if dev in self.devices:
327
+ self.devices.remove(dev)
328
+ dev.app = None
329
+
330
+ # -- events ---------------------------------------------------------------
331
+
332
+ def on(self, event_type_or_list, callback=None):
333
+ """Subscribe callback to one or more event types, or use as a decorator."""
334
+ if callback is None:
335
+ return lambda fn: self.on(event_type_or_list, fn)
336
+ if not callable(callback):
337
+ raise ValueError("callback must be callable")
338
+ if isinstance(event_type_or_list, (list, tuple, set)):
339
+ for et in event_type_or_list:
340
+ self.on(et, callback)
341
+ return callback
342
+ callback_set = self._event_callbacks.get(event_type_or_list)
343
+ if callback_set is None:
344
+ callback_set = set()
345
+ self._event_callbacks[event_type_or_list] = callback_set
346
+ callback_set.add(callback)
347
+ return callback
348
+
349
+ def off(self, event_type_or_list, callback):
350
+ """Unsubscribe callback from one or more event types."""
351
+ if isinstance(event_type_or_list, (list, tuple, set)):
352
+ for et in event_type_or_list:
353
+ self.off(et, callback)
354
+ return
355
+ callback_set = self._event_callbacks.get(event_type_or_list)
356
+ if callback_set:
357
+ callback_set.discard(callback)
358
+
359
+ # -- timers -----------------------------------------------------------
360
+
361
+ def every(self, ms=None, callback=None, *, period=None, name=None):
362
+ """A periodic ``multimer.Timer`` calling ``callback(timer)`` every *ms*.
363
+
364
+ The callback receives the timer, so a method needs the signature
365
+ ``def step(self, timer=None)``. Usable as a decorator
366
+ (``@app.every(1000)``). The App keeps the
367
+ process alive while any subscription runs; ``timer.deinit()`` (or
368
+ ``cancel()``) ends one.
369
+ """
370
+ if period is not None:
371
+ if callable(ms) and callback is None:
372
+ callback = ms
373
+ ms = period
374
+ if ms is None and period is None:
375
+ ms = SERVICE_TICK_MS
376
+ if callback is None:
377
+ if callable(ms):
378
+ callback = ms
379
+ ms = SERVICE_TICK_MS
380
+ else:
381
+ return lambda fn: self.every(ms, fn, name=name)
382
+ if not callable(callback):
383
+ raise ValueError("callback must be callable")
384
+ tim = multimer.every(int(ms), callback, name=name)
385
+ self._subscriptions.append(tim)
386
+ self._keep_alive()
387
+ return tim
388
+
389
+ def on_tick(self, callback, period=SERVICE_TICK_MS, **_ignored):
390
+ """Schedule a periodic callback (alias of `every`)."""
391
+ return self.every(period, callback)
392
+
393
+ def stop_timers(self):
394
+ """Stop the service tick, every refresh and every subscription."""
395
+ st = self._service_timer
396
+ self._service_timer = None
397
+ if st is not None:
398
+ st.deinit()
399
+ for t in self._refresh_timers:
400
+ t.deinit()
401
+ self._refresh_timers = []
402
+ for t in self._subscriptions:
403
+ t.deinit()
404
+ self._subscriptions = []
405
+ self._refresh_paused = False
406
+ self._refresh_claim = None
407
+
408
+ stop_timer = stop_timers
409
+
410
+ def _keep_alive(self):
411
+ multimer.keepalive(True)
412
+
413
+ # -- refresh ----------------------------------------------------------
414
+
415
+ def pause_refresh(self):
416
+ """Pause display refresh while a GUI renders frames."""
417
+ if self._refresh_claim is not None:
418
+ raise RuntimeError("display refresh already claimed/paused")
419
+ self._refresh_paused = True
420
+ self._refresh_claim = _RefreshClaim(self)
421
+ return self._refresh_claim
422
+
423
+ def resume_refresh(self):
424
+ """Resume display refresh after pausing."""
425
+ if self._refresh_claim is None:
426
+ return
427
+ self._refresh_paused = False
428
+ self._refresh_claim = None
429
+
430
+ def refresh_paused(self):
431
+ """Context manager to pause display refresh within a block."""
432
+ return _RefreshPaused(self)
433
+
434
+ def pause_polling(self):
435
+ """Stop the service tick reading the devices: the caller reads them.
436
+
437
+ A GUI that polls the input devices itself (LVGL reads its indevs
438
+ from its own timers) claims the devices with this, or the service
439
+ tick consumes the events first. ``release()`` the claim to resume.
440
+ """
441
+ if self._polling_claim is not None:
442
+ raise RuntimeError("device polling already claimed")
443
+ self._polling_claim = _PollingClaim(self)
444
+ return self._polling_claim
445
+
446
+ def resume_polling(self):
447
+ self._polling_claim = None
448
+
449
+ def _wire_display_refresh(self, refresh_period):
450
+ self._arm_service()
451
+ for display in self._displays:
452
+ self._wire_one_refresh(display, refresh_period)
453
+
454
+ def _wire_one_refresh(self, display, refresh_period):
455
+ if refresh_period is None:
456
+ if not getattr(display, "needs_refresh", False):
457
+ return
458
+ period = int(getattr(display, "refresh_period_ms", 0) or DEFAULT_REFRESH_MS)
459
+ else:
460
+ period = int(refresh_period)
461
+ if period <= 0:
462
+ return
463
+ if not callable(getattr(display, "show", None)):
464
+ return
465
+
466
+ # Look show up on every tick: a wrapper installed after the App started
467
+ # (displaydev's measure_fps) must be the one that is called.
468
+ def _show(timer_obj, _display=display):
469
+ if self._refresh_paused:
470
+ return
471
+ _display.show(timer_obj)
472
+
473
+ name = "refresh:%s" % (getattr(display, "__class__", type(display)).__name__,)
474
+ tim = multimer.every(period, _show, name=name)
475
+ tim._display = display
476
+ self._refresh_timers.append(tim)
477
+
478
+ # -- service ----------------------------------------------------------
479
+
480
+ def _arm_service(self):
481
+ if self._service_timer is not None or not self.devices and not self._displays:
482
+ return
483
+ self._service_timer = multimer.every(SERVICE_TICK_MS, self._service_tick, name="app.service")
484
+
485
+ def _service_tick(self, timer_obj):
486
+ if self._quit_requested or self._app_drives_poll or self._polling_claim is not None:
487
+ return
488
+ self._in_service_poll = True
489
+ try:
490
+ self.poll()
491
+ finally:
492
+ self._in_service_poll = False
493
+
494
+ def poll(self):
495
+ """Poll registered devices and dispatch any pending events.
496
+
497
+ A program that calls this from its own loop takes over from the
498
+ service timer; delivery of every other timer happens here too.
499
+ """
500
+ if not self._in_service_poll:
501
+ self._app_drives_poll = True
502
+ multimer.pump()
503
+ multimer.run_deadline_hook()
504
+ eventlist = []
505
+ for device in tuple(self.devices):
506
+ dev_events = device.poll()
507
+ if dev_events:
508
+ eventlist.extend(dev_events)
509
+ for event in dev_events:
510
+ if event.type == events.QUIT:
511
+ self._handle_quit()
512
+ callbacks = self._event_callbacks.get(event.type)
513
+ if callbacks:
514
+ for cb in tuple(callbacks):
515
+ cb(event)
516
+ return eventlist
517
+
518
+ # -- lifecycle --------------------------------------------------------
519
+
520
+ def run(self, tick_ms=SERVICE_TICK_MS):
521
+ """Block until quit, delivering timers and events. Optional.
522
+
523
+ Returns at once where the host already owns a loop that keeps the
524
+ program running (a REPL under ``-i``, a browser page, a notebook).
525
+ """
526
+ if multimer.strategy() == _hostloop.AMBIENT:
527
+ return
528
+ _hostloop.claim()
529
+ try:
530
+ multimer.run_until(lambda: self._teardown_done, tick_ms)
531
+ finally:
532
+ _hostloop.release()
533
+ self._raise_exit_code()
534
+
535
+ def run_async(self, coro_or_fn):
536
+ """Run a coroutine (or a factory of one) under the host's asyncio loop.
537
+
538
+ Schedules it as a task where a loop is already running (Jupyter,
539
+ PyScript) and returns the task; otherwise ``asyncio.run`` blocks.
540
+ """
541
+ aio = multimer.asyncio
542
+ if aio is None:
543
+ raise RuntimeError("asyncio is not available")
544
+
545
+ async def runner():
546
+ coro = coro_or_fn() if callable(coro_or_fn) else coro_or_fn
547
+ return await coro
548
+
549
+ if multimer.loop_running():
550
+ return aio.create_task(runner())
551
+ return aio.run(runner())
552
+
553
+ def request_quit(self, code=None):
554
+ """Request a clean application shutdown."""
555
+ if code is not None:
556
+ self._exit_code = int(code)
557
+ self._handle_quit()
558
+
559
+ def _handle_quit(self):
560
+ if self._quit_requested:
561
+ return
562
+ self._quit_requested = True
563
+ self._refresh_paused = True
564
+ self._perform_teardown()
565
+
566
+ def _teardown_from_loop(self):
567
+ self._perform_teardown()
568
+
569
+ def _perform_teardown(self):
570
+ if self._teardown_done:
571
+ return
572
+ self._teardown_done = True
573
+ self._quit_requested = True
574
+ if App._current is self:
575
+ App._current = None
576
+ if self._before_quit is not None:
577
+ try:
578
+ self._before_quit()
579
+ except Exception:
580
+ pass
581
+ for callback in tuple(self._on_quit):
582
+ try:
583
+ callback()
584
+ except Exception as exc:
585
+ pe = getattr(sys, "print_exception", None)
586
+ if pe is not None:
587
+ pe(exc)
588
+ else:
589
+ import traceback
590
+
591
+ traceback.print_exception(type(exc), exc, exc.__traceback__)
592
+ self.stop_timers()
593
+ for display in tuple(self._displays):
594
+ if callable(getattr(display, "quit", None)):
595
+ try:
596
+ display.quit()
597
+ except Exception:
598
+ pass
599
+ self._displays.clear()
600
+ # Nothing of ours is left to keep the process alive.
601
+ multimer.keepalive(False)
602
+
603
+ def _raise_exit_code(self):
604
+ code = self._exit_code
605
+ if code is not None:
606
+ self._exit_code = None
607
+ raise SystemExit(code)