omnipython-apps 0.1.4.dev8__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 (218) hide show
  1. apps/__init__.py +5 -0
  2. apps/about/__init__.py +257 -0
  3. apps/about/app.json +1 -0
  4. apps/about/credits.py +12 -0
  5. apps/about/facts.py +398 -0
  6. apps/about/fonts/OFL.txt +93 -0
  7. apps/about/fonts/latin1_14.bin +0 -0
  8. apps/about/fonts/latin1_16.bin +0 -0
  9. apps/about/fonts/latin1_24.bin +0 -0
  10. apps/about/fonts/latin1_32.bin +0 -0
  11. apps/about/fonts/latin1_40.bin +0 -0
  12. apps/backline/__init__.py +58 -0
  13. apps/backline/app.json +1 -0
  14. apps/backline/app.py +475 -0
  15. apps/backline/art.py +717 -0
  16. apps/backline/ask.py +781 -0
  17. apps/backline/box.py +502 -0
  18. apps/backline/cast.py +137 -0
  19. apps/backline/desk/__init__.py +329 -0
  20. apps/backline/desk/editor.py +331 -0
  21. apps/backline/desk/grid.py +154 -0
  22. apps/backline/desk/look.py +169 -0
  23. apps/backline/desk/pedals.py +102 -0
  24. apps/backline/desk/perform.py +157 -0
  25. apps/backline/desk/prompt.py +210 -0
  26. apps/backline/desk/strip.py +159 -0
  27. apps/backline/desk_main.py +226 -0
  28. apps/backline/engine.py +622 -0
  29. apps/backline/floor.py +509 -0
  30. apps/backline/footswitch.py +119 -0
  31. apps/backline/glyphs.py +82 -0
  32. apps/backline/kits.py +428 -0
  33. apps/backline/midipedal.py +362 -0
  34. apps/backline/page_data.py +413 -0
  35. apps/backline/parts.py +145 -0
  36. apps/backline/pedal.py +107 -0
  37. apps/backline/remote.py +134 -0
  38. apps/backline/songs/ballad_68.json +1 -0
  39. apps/backline/songs/bossa.json +1 -0
  40. apps/backline/songs/country_train.json +1 -0
  41. apps/backline/songs/funk.json +1 -0
  42. apps/backline/songs/metal.json +1 -0
  43. apps/backline/songs/pop.json +1 -0
  44. apps/backline/songs/rock.json +1 -0
  45. apps/backline/songs/shuffle.json +1 -0
  46. apps/battery/__init__.py +101 -0
  47. apps/battery/app.json +1 -0
  48. apps/bit_world/act_deck.py +683 -0
  49. apps/bit_world/act_game.py +762 -0
  50. apps/bit_world/act_pet.py +1032 -0
  51. apps/bit_world/app.json +1 -0
  52. apps/bit_world/bit_output.py +45 -0
  53. apps/bit_world/bit_palette.py +503 -0
  54. apps/bit_world/bit_sound.py +431 -0
  55. apps/bit_world/bit_sprites.py +632 -0
  56. apps/bit_world/bit_world.py +534 -0
  57. apps/btreceiver/__init__.py +690 -0
  58. apps/btreceiver/app.json +1 -0
  59. apps/btreceiver/chime.py +155 -0
  60. apps/btreceiver/demo.py +529 -0
  61. apps/btreceiver/screen.py +633 -0
  62. apps/camera/__init__.py +316 -0
  63. apps/camera/app.json +1 -0
  64. apps/card/__init__.py +113 -0
  65. apps/card/app.json +1 -0
  66. apps/cast/__init__.py +631 -0
  67. apps/cast/app.json +1 -0
  68. apps/cast/receivers.py +193 -0
  69. apps/chess/__init__.py +18 -0
  70. apps/chess/app.json +1 -0
  71. apps/chess/app.py +922 -0
  72. apps/chess/art.py +323 -0
  73. apps/chess/ble.py +411 -0
  74. apps/chess/engine.py +925 -0
  75. apps/chess/game.py +327 -0
  76. apps/chess/net.py +261 -0
  77. apps/clock/__init__.py +38 -0
  78. apps/clock/app.json +1 -0
  79. apps/detect/__init__.py +214 -0
  80. apps/detect/app.json +1 -0
  81. apps/fmsynth/__init__.py +41 -0
  82. apps/fmsynth/algorithms.py +61 -0
  83. apps/fmsynth/app.json +1 -0
  84. apps/fmsynth/app.py +355 -0
  85. apps/fmsynth/editor.py +206 -0
  86. apps/fmsynth/engine.py +257 -0
  87. apps/fmsynth/meters.py +262 -0
  88. apps/fmsynth/midi.py +375 -0
  89. apps/fmsynth/panel_view.py +1071 -0
  90. apps/fmsynth/patches/fmsynth-01.syx +0 -0
  91. apps/fmsynth/settings.py +138 -0
  92. apps/fmsynth/voice.py +398 -0
  93. apps/gamepad/__init__.py +685 -0
  94. apps/gamepad/app.json +1 -0
  95. apps/gamepad/pad.py +94 -0
  96. apps/gamepad/watch.py +352 -0
  97. apps/hidden/__init__.py +72 -0
  98. apps/hidden/app.json +1 -0
  99. apps/home/__init__.py +483 -0
  100. apps/home/app.json +1 -0
  101. apps/home/main.py +36 -0
  102. apps/homeassistant/__init__.py +213 -0
  103. apps/homeassistant/api.py +104 -0
  104. apps/homeassistant/app.json +1 -0
  105. apps/huey/__init__.py +287 -0
  106. apps/huey/acting.py +184 -0
  107. apps/huey/actor.py +194 -0
  108. apps/huey/app.json +1 -0
  109. apps/huey/client.py +125 -0
  110. apps/huey/servers.py +121 -0
  111. apps/huey/settings.example.json +8 -0
  112. apps/huey/settings.py +97 -0
  113. apps/huey/turn.py +504 -0
  114. apps/huey/voice.py +217 -0
  115. apps/info/__init__.py +810 -0
  116. apps/info/app.json +1 -0
  117. apps/lora/__init__.py +62 -0
  118. apps/lora/app.json +1 -0
  119. apps/manifest.py +71 -0
  120. apps/medialink_baby_monitor/__init__.py +222 -0
  121. apps/medialink_baby_monitor/app.json +1 -0
  122. apps/medialink_doorbell/__init__.py +251 -0
  123. apps/medialink_doorbell/app.json +1 -0
  124. apps/medialink_hands_free/__init__.py +217 -0
  125. apps/medialink_hands_free/app.json +1 -0
  126. apps/medialink_surveillance_camera/__init__.py +258 -0
  127. apps/medialink_surveillance_camera/app.json +1 -0
  128. apps/medialink_video_doorbell/__init__.py +289 -0
  129. apps/medialink_video_doorbell/app.json +1 -0
  130. apps/medialink_videophone/__init__.py +273 -0
  131. apps/medialink_videophone/app.json +1 -0
  132. apps/medialink_walkie_talkie/__init__.py +228 -0
  133. apps/medialink_walkie_talkie/app.json +1 -0
  134. apps/midicontroller/__init__.py +774 -0
  135. apps/midicontroller/app.json +1 -0
  136. apps/midicontroller/links.py +421 -0
  137. apps/midicontroller/surface.py +343 -0
  138. apps/midiengine/__init__.py +977 -0
  139. apps/midiengine/app.json +1 -0
  140. apps/midiengine/banks.py +85 -0
  141. apps/midiengine/midiin.py +165 -0
  142. apps/midiengine/player.py +392 -0
  143. apps/midiengine/umidiparser.py +1413 -0
  144. apps/mp3/__init__.py +240 -0
  145. apps/mp3/app.json +1 -0
  146. apps/perch/__init__.py +119 -0
  147. apps/perch/app.json +1 -0
  148. apps/perch/huey.py +481 -0
  149. apps/perch/huey_props.py +386 -0
  150. apps/perch/huey_shift.py +42 -0
  151. apps/perch/huey_views.py +296 -0
  152. apps/perch/scene_bench.py +680 -0
  153. apps/perch/scene_coast.py +479 -0
  154. apps/perch/scene_desk.py +492 -0
  155. apps/perch/stage.py +1274 -0
  156. apps/perch/vec.py +366 -0
  157. apps/repl/__init__.py +325 -0
  158. apps/repl/app.json +1 -0
  159. apps/roku/__init__.py +156 -0
  160. apps/roku/app.json +1 -0
  161. apps/rokucam/__init__.py +362 -0
  162. apps/rokucam/app.json +1 -0
  163. apps/security/__init__.py +261 -0
  164. apps/security/app.json +1 -0
  165. apps/settings/__init__.py +221 -0
  166. apps/settings/app.json +1 -0
  167. apps/shell/__init__.py +33 -0
  168. apps/shell/app.json +1 -0
  169. apps/spotify/__init__.py +669 -0
  170. apps/spotify/app.json +1 -0
  171. apps/spotify/screen.py +82 -0
  172. apps/steps/__init__.py +58 -0
  173. apps/steps/app.json +1 -0
  174. apps/stompbox/__init__.py +31 -0
  175. apps/stompbox/app.json +1 -0
  176. apps/stompbox/app.py +668 -0
  177. apps/stompbox/boards.json +20 -0
  178. apps/stompbox/effects.py +241 -0
  179. apps/stompbox/engine.py +340 -0
  180. apps/stompbox/footswitch.py +331 -0
  181. apps/stompbox/inputs.py +449 -0
  182. apps/stompbox/meter.py +72 -0
  183. apps/stompbox/outputs.py +135 -0
  184. apps/stompbox/pedals.txt +45 -0
  185. apps/stompbox/presets.py +106 -0
  186. apps/stompbox/styles.py +135 -0
  187. apps/stompbox/ui.py +817 -0
  188. apps/stompbox/wavfile.py +73 -0
  189. apps/synthstation/__init__.py +20 -0
  190. apps/synthstation/app.json +1 -0
  191. apps/synthstation/audio.py +397 -0
  192. apps/synthstation/catalog.py +50 -0
  193. apps/synthstation/meters.py +136 -0
  194. apps/synthstation/midi.py +380 -0
  195. apps/synthstation/pads.py +177 -0
  196. apps/synthstation/parts.py +128 -0
  197. apps/synthstation/station.py +1069 -0
  198. apps/system/__init__.py +11 -0
  199. apps/system/app.json +1 -0
  200. apps/touchcal/__init__.py +324 -0
  201. apps/touchcal/app.json +1 -0
  202. apps/touchcal/fit.py +262 -0
  203. apps/wake/__init__.py +268 -0
  204. apps/wake/app.json +1 -0
  205. apps/wake/feed.py +155 -0
  206. apps/watch/__init__.py +355 -0
  207. apps/watch/app.json +1 -0
  208. apps/watch/faces.py +35 -0
  209. apps/watch/wheel.py +157 -0
  210. apps/weather/__init__.py +278 -0
  211. apps/weather/app.json +1 -0
  212. apps/weather/icons.py +172 -0
  213. apps/weather/sizing.py +71 -0
  214. apps/weather/zippad.py +172 -0
  215. omnipython_apps-0.1.4.dev8.dist-info/METADATA +33 -0
  216. omnipython_apps-0.1.4.dev8.dist-info/RECORD +218 -0
  217. omnipython_apps-0.1.4.dev8.dist-info/WHEEL +5 -0
  218. omnipython_apps-0.1.4.dev8.dist-info/top_level.txt +1 -0
@@ -0,0 +1,685 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Gamepad: be a USB game controller, or test one.
5
+
6
+ On a board with a USB device port (an ESP32-S2, S3 or P4), the screen is a
7
+ gamepad: a d-pad, a stick, A, B, X and Y, two shoulder buttons, Select and
8
+ Start. Plug the port into a computer or into another board's host port and
9
+ it's a game controller with sixteen buttons, a hat and four axes. The touch
10
+ panel reads one finger, so one control moves at a time.
11
+
12
+ On a board with a USB host port, it shows the gamepad plugged into it as it
13
+ changes: each button lights while it's held, the sticks and the hat move,
14
+ and every axis has a bar. Any HID gamepad or joystick works, whatever its
15
+ layout, apart from the ones that need a start-up message first (a DualShock
16
+ 4, a Switch Pro controller).
17
+
18
+ In a browser page, it shows the same for the gamepad chosen in
19
+ Connections, or the first the browser shows the page; a browser shows one
20
+ once a button is pressed on it.
21
+
22
+ A board that can do both asks which. The gamepad needs ``usb-hid`` and the
23
+ tester ``usb-host-hid``, which ``omip.install("usb-host-hid")`` puts in
24
+ ``/lib``. Both fit a screen of 480 x 320 or larger.
25
+ """
26
+
27
+ import lvgl as lv
28
+ from multimer import ticks_diff, ticks_ms
29
+ from touchkit import ui
30
+
31
+ from .pad import A, B, L, R, SELECT, START, X, Y, Pad, Sender, hat_at, stick_at
32
+ from .watch import AXIS_NAMES, BUTTON_NAMES, CENTRED, EXTRA_NAMES, EXTRA_ORDER, PRESSURE_OF, PageWatch, Watch
33
+
34
+ #: How often the screen catches up with the pad or the tester, in ms.
35
+ TICK_MS = 20
36
+ #: The face buttons: number, label, colour and place in the diamond (column, row).
37
+ FACE = (
38
+ (Y, "Y", 0xE0A030, (1, 0)),
39
+ (X, "X", 0x3A7BD5, (0, 1)),
40
+ (B, "B", 0xD9483B, (2, 1)),
41
+ (A, "A", 0x3BA55C, (1, 2)),
42
+ )
43
+ #: The hat's eight directions as the d-pad arrows they light: up, right, down, left.
44
+ LIT = ((1, 0, 0, 0), (1, 1, 0, 0), (0, 1, 0, 0), (0, 1, 1, 0), (0, 0, 1, 0), (0, 0, 1, 1), (0, 0, 0, 1), (1, 0, 0, 1))
45
+ #: What the tester says while it has no gamepad.
46
+ WAITING = "Plug a gamepad into the USB host port.\nPlugged in? Press its Home button to wake it."
47
+ COMPASS = ("N", "NE", "E", "SE", "S", "SW", "W", "NW")
48
+
49
+
50
+ #: The platforms that are a browser page.
51
+ BROWSERS = ("webassembly", "emscripten")
52
+ #: What the tester says in a browser page while it has no gamepad.
53
+ PAGE_WAITING = "Press a button on a gamepad:\nthe browser shows one to the page then."
54
+
55
+
56
+ def sides():
57
+ """What this board can be: ``"device"`` with a USB device port,
58
+ ``"host"`` with a USB host port, in that order. A browser page is
59
+ ``"page"`` alone: it tests the pads the browser shows it."""
60
+ import sys
61
+
62
+ if sys.platform in BROWSERS:
63
+ return ["page"]
64
+ out = []
65
+ try:
66
+ import machine
67
+
68
+ if hasattr(machine, "USBDevice"):
69
+ out.append("device")
70
+ except ImportError:
71
+ pass
72
+ try:
73
+ import _usbhost
74
+
75
+ if hasattr(_usbhost, "host_start"):
76
+ out.append("host")
77
+ except ImportError:
78
+ pass
79
+ return out
80
+
81
+
82
+ def _one_port():
83
+ """Whether the USB host and device share this board's one USB port, as
84
+ on the ESP32-S2 and S3."""
85
+ import sys
86
+
87
+ m = getattr(sys.implementation, "_machine", "")
88
+ return "ESP32S2" in m or "ESP32S3" in m
89
+
90
+
91
+ def _free_port():
92
+ """Stop a USB host that holds the port the gamepad needs. Returns True
93
+ if one was running."""
94
+ if not _one_port():
95
+ return False
96
+ try:
97
+ import usb.core
98
+ except ImportError:
99
+ return False
100
+ if not usb.core.running():
101
+ return False
102
+ usb.core.stop()
103
+ print("gamepad: stopped the USB host, which shares this board's USB port")
104
+ return True
105
+
106
+
107
+ def _margin(W):
108
+ return max(8, W // 60)
109
+
110
+
111
+ def _status_row(scope):
112
+ """The status line on a row of its own across the top of the app, so
113
+ nothing is drawn over it. Returns the label and the row's height."""
114
+ W = scope.size[0]
115
+ m = _margin(W)
116
+ lbl = ui.label(scope.root, "", ui.small, ui.MUTED)
117
+ lbl.set_long_mode(lv.label.LONG_MODE.DOTS) # a long one ends in dots, inside the row
118
+ lbl.set_size(W - 2 * m, ui.small.line_height)
119
+ lbl.set_pos(m, 4)
120
+ return lbl, ui.small.line_height + 8
121
+
122
+
123
+ def _missing(scope, short, text):
124
+ """What this board lacks: *short* on the status line, *text* in the
125
+ middle, and touchkit's Hide from Home button under it."""
126
+ status, row = _status_row(scope)
127
+ status.set_text(short)
128
+ W, H = scope.size
129
+ msg = ui.label(scope.root, text, ui.font, ui.WHITE)
130
+ msg.set_width(W - 48)
131
+ msg.set_style_text_align(lv.TEXT_ALIGN.CENTER, 0)
132
+ msg.align(lv.ALIGN.CENTER, 0, row // 2)
133
+ ui.hide_button(scope, short, msg)
134
+ return msg
135
+
136
+
137
+ def _zone(parent, x, y, size, color=None):
138
+ """A round, touchable area that keeps the press while the finger slides off it."""
139
+ o = ui.plain(lv.obj(parent))
140
+ o.set_pos(x, y)
141
+ o.set_size(size, size)
142
+ o.set_style_radius(lv.RADIUS_CIRCLE, 0)
143
+ o.set_style_bg_color(color or ui.PANEL, 0)
144
+ o.set_style_bg_opa(lv.OPA.COVER, 0)
145
+ o.add_flag(lv.obj.FLAG.CLICKABLE)
146
+ o.add_flag(lv.obj.FLAG.PRESS_LOCK)
147
+ o.remove_flag(lv.obj.FLAG.GESTURE_BUBBLE)
148
+ return o
149
+
150
+
151
+ def _touch_offset(obj):
152
+ """Where the finger is, from *obj*'s centre."""
153
+ p = lv.point_t()
154
+ lv.indev_active().get_point(p)
155
+ a = lv.area_t()
156
+ obj.get_coords(a)
157
+ return p.x - (a.x1 + a.x2) // 2, p.y - (a.y1 + a.y2) // 2
158
+
159
+
160
+ def _on_press(obj, cb):
161
+ """Call ``cb(True)`` while *obj* is pressed or the finger moves on it, and
162
+ ``cb(False)`` when it lets go."""
163
+
164
+ def ev(e):
165
+ code = e.get_code()
166
+ cb(code == lv.EVENT.PRESSED or code == lv.EVENT.PRESSING)
167
+
168
+ for code in (lv.EVENT.PRESSED, lv.EVENT.PRESSING, lv.EVENT.RELEASED, lv.EVENT.PRESS_LOST):
169
+ obj.add_event_cb(ev, code, None)
170
+
171
+
172
+ def _pad_button(parent, text, x, y, w, h, color, radius, number, st, font=None):
173
+ b, lbl = ui.button(parent, text, lambda: None, w=w, h=h, font=font or ui.big, color=lv.color_hex(color))
174
+ b.set_pos(x, y)
175
+ b.set_style_radius(radius, 0)
176
+ b.remove_flag(lv.obj.FLAG.GESTURE_BUBBLE)
177
+ # A ring while it's held, since the finger covers the button.
178
+ b.set_style_outline_width(4, lv.STATE.PRESSED)
179
+ b.set_style_outline_color(ui.WHITE, lv.STATE.PRESSED)
180
+ b.set_style_outline_pad(3, lv.STATE.PRESSED)
181
+
182
+ def held(down):
183
+ if down:
184
+ st["pad"].press(number)
185
+ else:
186
+ st["pad"].release(number)
187
+ st["send"]()
188
+
189
+ _on_press(b, held)
190
+ st["buttons"][number] = b
191
+ return b
192
+
193
+
194
+ def be_gamepad(scope):
195
+ """The screen as a gamepad on the board's USB device port."""
196
+ root = scope.root
197
+ W, H = scope.size
198
+ try:
199
+ import usb_hid
200
+ from usb.device.hid import HIDInterface # noqa: F401 # what usb_hid runs over
201
+ except ImportError as e:
202
+ print("gamepad:", e)
203
+ _missing(scope, "missing: usb-device-hid", 'The gamepad needs usb-device-hid:\nomip.install("usb-device-hid")')
204
+ return None
205
+ status, row = _status_row(scope)
206
+ _free_port()
207
+ usb_hid.enable((usb_hid.Device.GAMEPAD,))
208
+ scope.on_close(usb_hid.disable) # the port is the board's serial port alone again
209
+
210
+ pad = Pad()
211
+ sender = Sender(pad, usb_hid.Device.GAMEPAD)
212
+ st = {"pad": pad, "sender": sender, "shown": None, "buttons": {}}
213
+
214
+ def send():
215
+ sender.send()
216
+ show()
217
+
218
+ st["send"] = send
219
+
220
+ # Under the status row the shoulders, then the d-pad, the stick and the
221
+ # face buttons.
222
+ m = _margin(W)
223
+ top = max(44, (H - row) // 7)
224
+ s = min((W - 4 * m) // 3, H - row - top - 2 * m)
225
+ y0 = row + top + m + (H - row - top - m - s) // 2
226
+ side_w = max(80, W // 6)
227
+ _pad_button(root, "L", m, row, side_w, top, 0x2A3550, 12, L, st)
228
+ _pad_button(root, "R", W - m - side_w, row, side_w, top, 0x2A3550, 12, R, st)
229
+ mid_w = max(80, W // 8)
230
+ _pad_button(root, "Select", W // 2 - mid_w - m // 2, row, mid_w, top, 0x1A2030, top // 2, SELECT, st, ui.font)
231
+ _pad_button(root, "Start", W // 2 + m // 2, row, mid_w, top, 0x1A2030, top // 2, START, st, ui.font)
232
+
233
+ dpad = _zone(root, m, y0, s)
234
+ arrows = []
235
+ arrow_font = ui.huge if s >= 200 else ui.big # four huge arrows meet in a small d-pad
236
+ for sym, align, dx, dy in (
237
+ (lv.SYMBOL.UP, lv.ALIGN.TOP_MID, 0, s // 10),
238
+ (lv.SYMBOL.RIGHT, lv.ALIGN.RIGHT_MID, -s // 10, 0),
239
+ (lv.SYMBOL.DOWN, lv.ALIGN.BOTTOM_MID, 0, -s // 10),
240
+ (lv.SYMBOL.LEFT, lv.ALIGN.LEFT_MID, s // 10, 0),
241
+ ):
242
+ a = ui.label(dpad, sym, arrow_font, ui.MUTED)
243
+ a.align(align, dx, dy)
244
+ arrows.append(a)
245
+
246
+ def dpad_moved(down):
247
+ pad.hat = hat_at(*_touch_offset(dpad), s // 2) if down else None
248
+ lit = LIT[pad.hat] if pad.hat is not None else (0, 0, 0, 0)
249
+ for a, on in zip(arrows, lit):
250
+ a.set_style_text_color(ui.ACCENT if on else ui.MUTED, 0)
251
+ send()
252
+
253
+ _on_press(dpad, dpad_moved)
254
+ st["dpad"] = dpad
255
+
256
+ stick = _zone(root, (W - s) // 2, y0, s)
257
+ knob_d = s * 2 // 5
258
+ knob = ui.plain(lv.obj(stick))
259
+ knob.set_size(knob_d, knob_d)
260
+ knob.set_style_radius(lv.RADIUS_CIRCLE, 0)
261
+ knob.set_style_bg_color(ui.KEY, 0)
262
+ knob.set_style_bg_opa(lv.OPA.COVER, 0)
263
+ knob.remove_flag(lv.obj.FLAG.CLICKABLE)
264
+ knob.center()
265
+ reach = (s - knob_d) // 2
266
+
267
+ def stick_moved(down):
268
+ pad.x, pad.y = stick_at(*_touch_offset(stick), reach) if down else (0, 0)
269
+ knob.align(lv.ALIGN.CENTER, pad.x * reach // 127, pad.y * reach // 127)
270
+ knob.set_style_bg_color(ui.ACCENT if down else ui.KEY, 0)
271
+ send()
272
+
273
+ _on_press(stick, stick_moved)
274
+ st["stick"] = stick
275
+
276
+ fx = W - m - s
277
+ cell = s // 3
278
+ for number, text, color, (col, line) in FACE:
279
+ _pad_button(root, text, fx + col * cell + 4, y0 + line * cell + 4, cell - 8, cell - 8, color,
280
+ lv.RADIUS_CIRCLE, number, st)
281
+
282
+ def show():
283
+ if sender.error is not None:
284
+ text = "no host yet: plug the USB port into a computer"
285
+ else:
286
+ held = [str(n) for n in range(1, 17) if pad.buttons >> n - 1 & 1]
287
+ text = "buttons %s hat %s stick %d, %d %d sent" % (
288
+ " ".join(held) or "-", COMPASS[pad.hat] if pad.hat is not None else "-", pad.x, pad.y, sender.count)
289
+ if text != st["shown"]:
290
+ st["shown"] = text
291
+ status.set_text(text)
292
+
293
+ def tick(_t=None):
294
+ # A report the host didn't take goes again until it does.
295
+ send()
296
+
297
+ tick()
298
+ scope.every(250, tick)
299
+ return st
300
+
301
+
302
+ #: The height of the caption over each square.
303
+ CAPTION = ui.tiny.line_height + 2
304
+
305
+
306
+ def _caption(parent, x, y, text):
307
+ """*text* over the square at *x*, *y*: above it, where the dot never goes."""
308
+ ui.label(parent, text, ui.tiny, ui.MUTED).set_pos(x + 2, y - CAPTION)
309
+
310
+
311
+ def _square(parent, x, y, size, title):
312
+ """A stick's square, with a dot that shows where it is. Returns the dot."""
313
+ _caption(parent, x, y, title)
314
+ box = ui.box(parent, x, y, size, size)
315
+ box.set_style_pad_all(0, 0)
316
+ for w, h in ((size - 16, 1), (1, size - 16)):
317
+ line = ui.plain(lv.obj(box))
318
+ line.set_size(w, h)
319
+ line.set_style_bg_color(ui.KEY, 0)
320
+ line.set_style_bg_opa(lv.OPA.COVER, 0)
321
+ line.center()
322
+ dot = ui.plain(lv.obj(box))
323
+ dot.set_size(size // 7, size // 7)
324
+ dot.set_style_radius(lv.RADIUS_CIRCLE, 0)
325
+ dot.set_style_bg_color(ui.ACCENT, 0)
326
+ dot.set_style_bg_opa(lv.OPA.COVER, 0)
327
+ dot.center()
328
+ return dot, (size - size // 7) // 2
329
+
330
+
331
+ def _pairs(axes):
332
+ """The sticks to draw as squares: (X, Y), then (Rx, Ry) or (Z, Rz)."""
333
+ out = []
334
+ for a, b in ((0x010030, 0x010031), (0x010033, 0x010034), (0x010032, 0x010035)):
335
+ if a in axes and b in axes and len(out) < 2:
336
+ out.append((a, b))
337
+ return out
338
+
339
+
340
+ def _text_width(text):
341
+ size = lv.point_t()
342
+ lv.text_get_size(size, text, ui.tiny, 0, 0, 32767, lv.TEXT_FLAG.NONE)
343
+ return size.x
344
+
345
+
346
+ def _widths(items):
347
+ """How wide each of a strip's columns must be: its name or its biggest
348
+ value, whichever is wider, and room for the bar."""
349
+ return [max(24, _text_width(text), _text_width(str(hi))) + 6 for text, lo, hi in items]
350
+
351
+
352
+ def _strip(parent, items, x, y, width, tall, numbers, centred=()):
353
+ """Upright bars side by side from *x*, *y*: one for each (name, low, high)
354
+ in *items*, its name below and, with *numbers*, its value above, spread
355
+ over *width*. A column whose index has a (middle, span) in *centred*
356
+ fills from the middle. Returns (bar, value label or None, name label,
357
+ (middle, span) or None) for each."""
358
+ widths = _widths(items)
359
+ grow = max(0, min(54 - max(widths), (width - sum(widths)) // len(items)))
360
+ out = []
361
+ cx = x
362
+ for i, ((text, lo, hi), cw) in enumerate(zip(items, widths)):
363
+ cw += grow
364
+ middle = centred[i] if i < len(centred) else None
365
+ value = None
366
+ by = y
367
+ if numbers:
368
+ value = ui.label(parent, "", ui.tiny, ui.WHITE)
369
+ value.set_width(cw)
370
+ value.set_style_text_align(lv.TEXT_ALIGN.CENTER, 0)
371
+ value.set_pos(cx, y)
372
+ by += CAPTION
373
+ bar = lv.bar(parent)
374
+ if middle is None:
375
+ bar.set_range(lo, hi)
376
+ bar.set_value(lo, False)
377
+ else:
378
+ bar.set_mode(lv.bar.MODE.SYMMETRICAL)
379
+ bar.set_range(-middle[1], middle[1])
380
+ bar.set_value(0, False)
381
+ bar.set_pos(cx + cw // 2 - 6, by)
382
+ bar.set_size(12, tall)
383
+ name = ui.label(parent, text, ui.tiny, ui.MUTED)
384
+ name.set_width(cw)
385
+ name.set_style_text_align(lv.TEXT_ALIGN.CENTER, 0)
386
+ name.set_pos(cx, by + tall + 2)
387
+ out.append((bar, value, name, middle))
388
+ cx += cw
389
+ return out
390
+
391
+
392
+ def _strip_height(tall, numbers):
393
+ """How tall a `_strip` of bars *tall* high stands, names and all."""
394
+ return tall + (2 if numbers else 1) * CAPTION + 2
395
+
396
+
397
+ def _fit_strip(room):
398
+ """The bars' height and whether their numbers fit, in *room* pixels."""
399
+ numbers = room >= _strip_height(32, True)
400
+ return max(10, min(48, room - _strip_height(0, numbers))), numbers
401
+
402
+
403
+ def _show(column, v, held):
404
+ bar, value, name, middle = column
405
+ if middle is None:
406
+ bar.set_value(v, False)
407
+ else:
408
+ span = middle[1]
409
+ bar.set_value(max(-span, min(span, v - middle[0])), False)
410
+ if value is not None:
411
+ value.set_text(str(v))
412
+ name.set_style_text_color(ui.ACCENT if held else ui.MUTED, 0)
413
+
414
+
415
+ def test_page_gamepad(scope):
416
+ """A gamepad the browser shows the page, live: the one chosen in
417
+ Connections, or the first."""
418
+ return test_gamepad(scope, PageWatch())
419
+
420
+
421
+ def test_gamepad(scope, watch=None):
422
+ """The gamepad on the board's USB host port, live; or what *watch*
423
+ reads, read like `Watch`."""
424
+ root = scope.root
425
+ W, H = scope.size
426
+ waiting = WAITING if watch is None else PAGE_WAITING
427
+ if watch is None:
428
+ try:
429
+ import usb.core
430
+ from usb.host import hid_generic
431
+ except ImportError as e:
432
+ print("gamepad:", e)
433
+ _missing(scope, "missing: usb-host-hid", 'The tester needs usb-host-hid:\nomip.install("usb-host-hid")')
434
+ return None
435
+ status, row = _status_row(scope)
436
+ if watch is None:
437
+ # Take the host as it runs: a launcher that started it keeps its
438
+ # speed, its devices and its audio. Only a host started here is this
439
+ # tester's to stop.
440
+ if usb.core.running():
441
+ stop = None
442
+ else:
443
+ usb.core.start(classes=("hid",))
444
+ stop = usb.core.stop
445
+ watch = Watch(usb.core, hid_generic)
446
+ else:
447
+ stop = None
448
+ st = {"watch": watch, "layout": None, "view": None, "shown": None}
449
+
450
+ def close():
451
+ watch.close()
452
+ if stop is not None:
453
+ stop()
454
+
455
+ scope.on_close(close)
456
+
457
+ # Everything else goes below the status row.
458
+ H -= row
459
+ body = ui.plain(lv.obj(root))
460
+ body.set_pos(0, row)
461
+ body.set_size(W, H)
462
+ hint = ui.label(body, waiting, ui.font, ui.MUTED)
463
+ hint.center()
464
+
465
+ def build(layout):
466
+ """Widgets for this pad's buttons, sticks, hats and axes."""
467
+ body.clean()
468
+ buttons, axes, hats, extras = layout
469
+ m = _margin(W)
470
+ view = {"lamps": {}, "keys": {}, "pressure": {}, "dots": [], "bars": {}, "values": {}, "hat": None,
471
+ "extras": []}
472
+ pairs = _pairs(axes)
473
+ # Which vendor values are a button's pressure; the rest go in a strip.
474
+ pressure = {}
475
+ rest = []
476
+ for i, (usage, lo, hi) in enumerate(extras):
477
+ if PRESSURE_OF.get(usage) in buttons:
478
+ pressure[PRESSURE_OF[usage]] = i
479
+ else:
480
+ rest.append(i)
481
+ rest.sort(key=lambda i: EXTRA_ORDER.index(extras[i][0]) if extras[i][0] in EXTRA_ORDER else 99 + i)
482
+ line = ui.small.line_height + 6 # an axis's row at its thinnest
483
+ count = len(pairs) + (1 if hats else 0)
484
+ if pressure:
485
+ # A pad that says how hard its buttons are pressed: each button
486
+ # is an upright bar, 0 to 255, in its number's order. The bars
487
+ # and the strip of the other vendor values share their height.
488
+ # A pad that names its pressures is in the PS3 layout, whose
489
+ # buttons have known names; Home, too long for its column, is
490
+ # the house.
491
+ names = [BUTTON_NAMES[n - 1] if n <= len(BUTTON_NAMES) else str(n) for n in buttons]
492
+ keys = [(lv.SYMBOL.HOME if t == "Home" else t, 0, 255) for t in names]
493
+ others = [(EXTRA_NAMES.get(extras[i][0], str(i + 1)), extras[i][1], extras[i][2]) for i in rest]
494
+ # Side by side in one row where they fit, the buttons first.
495
+ key_w, other_w = sum(_widths(keys)), sum(_widths(others)) if others else 0
496
+ one_row = bool(rest) and key_w + other_w <= W - 3 * m
497
+ strips = 2 if rest and not one_row else 1
498
+ need = len(axes) * line + (2 * m + CAPTION + 48 if count else 0)
499
+ cols, rows = 1, len(axes)
500
+ room = (H - m - need) // strips - m
501
+ if room < _strip_height(16, False) and rows > 1:
502
+ cols, rows = 2, (rows + 1) // 2
503
+ room += (len(axes) - rows) * line // strips
504
+ tall, numbers = _fit_strip(room)
505
+ y = H - m - _strip_height(tall, numbers)
506
+ width = (W - 3 * m) * key_w // (key_w + other_w) if one_row else W - 2 * m
507
+ view["keys"] = dict(zip(buttons, _strip(body, keys, m, y, width, tall, numbers)))
508
+ view["pressure"] = pressure
509
+ if one_row:
510
+ view["extras"] = list(zip(rest, _strip(body, others, 2 * m + width, y, W - 3 * m - width, tall,
511
+ numbers, [CENTRED.get(extras[i][0]) for i in rest])))
512
+ rest = []
513
+ top = y - m
514
+ else:
515
+ # The buttons along the bottom as lamps, in rows of up to sixteen.
516
+ n_cols = min(16, len(buttons)) or 1
517
+ bw = min(56, (W - m) // n_cols - 6)
518
+ n_rows = (len(buttons) + n_cols - 1) // n_cols
519
+ lamps_y = H - m - n_rows * (bw + 6) + 6
520
+ lamp_font = ui.small if bw >= 32 else ui.tiny
521
+ for i, n in enumerate(buttons):
522
+ lamp = ui.box(body, m + (i % n_cols) * (bw + 6), lamps_y + (i // n_cols) * (bw + 6), bw, bw, ui.KEY)
523
+ lamp.set_style_pad_all(0, 0)
524
+ ui.label(lamp, str(n), lamp_font, ui.WHITE).center()
525
+ view["lamps"][n] = lamp
526
+ top = lamps_y - m
527
+ cols, rows = 1, len(axes)
528
+ if rest:
529
+ room = top - m - rows * line - (2 * m + CAPTION + 48 if count else 0)
530
+ if room < _strip_height(16, False) and rows > 1:
531
+ cols, rows = 2, (rows + 1) // 2
532
+ room += (len(axes) - rows) * line
533
+ tall, numbers = _fit_strip(room)
534
+ # Above them a strip of upright bars for the other vendor values:
535
+ # the d-pad's pressure and the motion sensors.
536
+ if rest:
537
+ y = top - _strip_height(tall, numbers)
538
+ items = [(EXTRA_NAMES.get(extras[i][0], str(i + 1)), extras[i][1], extras[i][2]) for i in rest]
539
+ view["extras"] = list(zip(rest, _strip(body, items, m, y, W - 2 * m, tall, numbers,
540
+ [CENTRED.get(extras[i][0]) for i in rest])))
541
+ top = y - m
542
+ # Above those the sticks and the hat as squares, then a bar for each axis.
543
+ sq = max(0, min(top - rows * line - 2 * m - CAPTION, (W - m) // count - m)) if count else 0
544
+ x = (W - count * (sq + m) + m) // 2
545
+ sy = m + CAPTION
546
+ for a, b in pairs:
547
+ dot, reach = _square(body, x, sy, sq, "%s / %s" % (AXIS_NAMES[a], AXIS_NAMES[b]))
548
+ view["dots"].append((dot, reach, a, b))
549
+ x += sq + m
550
+ if hats:
551
+ _caption(body, x, sy, "Hat")
552
+ hb = ui.box(body, x, sy, sq, sq)
553
+ hb.set_style_pad_all(0, 0)
554
+ # All eight points where they fit; in a small square, the four
555
+ # that light in pairs for a diagonal, as the d-pad's arrows do.
556
+ points = range(8) if sq >= 120 else range(0, 8, 2)
557
+ mark_font = ui.small if sq >= 150 else ui.tiny
558
+ marks = []
559
+ for i in points:
560
+ lbl = ui.label(hb, COMPASS[i], mark_font, ui.MUTED)
561
+ dx, dy = ((0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1))[i]
562
+ lbl.align(lv.ALIGN.CENTER, dx * sq * 3 // 10, dy * sq * 3 // 10)
563
+ marks.append(lbl)
564
+ view["hat"] = marks
565
+ x += sq + m
566
+ y0 = sy + sq + m if sq else m
567
+ bar_h = max(line, min(36, (top - y0) // max(1, rows)))
568
+ cw = (W - m) // cols
569
+ for i, code in enumerate(axes):
570
+ x, y = m + (i % cols) * cw, y0 + (i // cols) * bar_h
571
+ name = ui.label(body, AXIS_NAMES.get(code, "%06x" % code), ui.small, ui.MUTED)
572
+ name.set_pos(x, y + (bar_h - ui.small.line_height) // 2)
573
+ bar = lv.bar(body)
574
+ bar.set_mode(lv.bar.MODE.SYMMETRICAL)
575
+ bar.set_range(-100, 100)
576
+ bar.set_value(0, False)
577
+ bar.set_pos(x + 70, y + bar_h // 4)
578
+ bar.set_size(cw - m - 70 - 52, bar_h // 2)
579
+ value = ui.label(body, "", ui.small, ui.WHITE)
580
+ value.set_pos(x + cw - m - 46, y + (bar_h - ui.small.line_height) // 2)
581
+ view["bars"][code] = bar
582
+ view["values"][code] = value
583
+ return view
584
+
585
+ def draw():
586
+ view = st["view"]
587
+ if view is None:
588
+ return
589
+ held = watch.buttons
590
+ for n, lamp in view["lamps"].items():
591
+ lamp.set_style_bg_color(ui.ACCENT if n in held else ui.KEY, 0)
592
+ axes = watch.axes
593
+ for dot, reach, a, b in view["dots"]:
594
+ dot.align(lv.ALIGN.CENTER, int((axes.get(a) or 0) * reach), int((axes.get(b) or 0) * reach))
595
+ for code, bar in view["bars"].items():
596
+ v = axes.get(code)
597
+ bar.set_value(int((v or 0) * 100), False)
598
+ raw = watch.pad.axes.get(code) if watch.pad is not None else None
599
+ view["values"][code].set_text("" if raw is None else str(raw))
600
+ extras = watch.extras
601
+ for n, column in view["keys"].items():
602
+ i = view["pressure"].get(n)
603
+ v = extras[i] if i is not None and i < len(extras) else None
604
+ if v is None:
605
+ v = 255 if n in held else 0
606
+ _show(column, v, n in held)
607
+ for i, column in view["extras"]:
608
+ v = extras[i] if i < len(extras) else None
609
+ if v is not None:
610
+ _show(column, v, False)
611
+ if view["hat"] is not None:
612
+ d = watch.hats.get(0, -1)
613
+ marks = view["hat"]
614
+ if len(marks) == 8:
615
+ lit = [i == d for i in range(8)]
616
+ else:
617
+ lit = LIT[d] if d >= 0 else (0, 0, 0, 0)
618
+ for lbl, on in zip(marks, lit):
619
+ lbl.set_style_text_color(ui.ACCENT if on else ui.MUTED, 0)
620
+
621
+ def tick(_t=None):
622
+ changed = watch.poll(ticks_ms(), ticks_diff)
623
+ if watch.layout != st["layout"]:
624
+ st["layout"] = watch.layout
625
+ if watch.layout is None:
626
+ body.clean()
627
+ st["view"] = None
628
+ ui.label(body, waiting, ui.font, ui.MUTED).center()
629
+ else:
630
+ st["view"] = build(watch.layout)
631
+ changed = True
632
+ if changed:
633
+ draw()
634
+ text = watch.status if watch.pad is None else "%s %d events" % (watch.name, watch.events)
635
+ if text != st["shown"]:
636
+ st["shown"] = text
637
+ status.set_text(text)
638
+
639
+ tick()
640
+ scope.every(TICK_MS, tick)
641
+ return st
642
+
643
+
644
+ def main(scope):
645
+ can = sides()
646
+ if not can:
647
+ _missing(scope, "no USB port for this", "Gamepad needs a board with a USB device port (to be a gamepad) "
648
+ "or a USB host port (to test one), such as an ESP32-S3 or ESP32-P4.")
649
+ return
650
+ if can == ["page"]:
651
+ test_page_gamepad(scope)
652
+ return
653
+ if len(can) == 1:
654
+ (be_gamepad if can[0] == "device" else test_gamepad)(scope)
655
+ return
656
+ # Both: ask which, once.
657
+ root = scope.root
658
+ W, H = scope.size
659
+ status, row = _status_row(scope)
660
+ status.set_text("choose one")
661
+ bw, bh = min(340, (W - 64) // 2), min(200, H - row - 48)
662
+ title_font = ui.big if bw >= 280 else ui.font
663
+
664
+ def pick(fn):
665
+ # Not from inside the button's own click: cleaning the root deletes it.
666
+ root.add_flag(lv.obj.FLAG.HIDDEN)
667
+
668
+ def start(_t=None):
669
+ root.clean()
670
+ root.remove_flag(lv.obj.FLAG.HIDDEN)
671
+ fn(scope)
672
+
673
+ scope.after(10, start)
674
+
675
+ for i, (title, text, fn) in enumerate((
676
+ ("Be a gamepad", "for a computer or a host board on the USB device port", be_gamepad),
677
+ ("Test a gamepad", "plugged into this board's USB host port", test_gamepad),
678
+ )):
679
+ b, lbl = ui.button(root, title, lambda fn=fn: pick(fn), w=bw, h=bh, font=title_font, color=ui.PANEL)
680
+ b.align(lv.ALIGN.CENTER, (bw // 2 + 16) * (2 * i - 1), row // 2)
681
+ lbl.align(lv.ALIGN.TOP_MID, 0, 20)
682
+ sub = ui.label(b, text, ui.small, ui.MUTED)
683
+ sub.set_width(bw - 32)
684
+ sub.set_style_text_align(lv.TEXT_ALIGN.CENTER, 0)
685
+ sub.align(lv.ALIGN.BOTTOM_MID, 0, -20)
apps/gamepad/app.json ADDED
@@ -0,0 +1 @@
1
+ {"name": "gamepad", "title": "Gamepad", "category": "Games", "icon": "sports_esports", "color": "#8C5A1E"}