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
apps/backline/box.py ADDED
@@ -0,0 +1,502 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Backline's box: the song, the engine, the kit, and the hmilink device
5
+ every view draws from.
6
+
7
+ `BacklineModel` is songmodel's `SongModel` with Backline's facts added to
8
+ what it describes (the song's parts, the songs and kits there are). `Box`
9
+ is its host: it answers the commands any panel sends and the telemetry
10
+ every panel reads.
11
+
12
+ Commands, from any panel:
13
+
14
+ - ``pedal {"pedal": 0 or 1, "down": true or false}``: a footswitch moved.
15
+ - ``gesture {"pedal": 0 or 1, "gesture": "tap", "hold" or "double"}``: a
16
+ gesture made elsewhere, as a panel with its own timing would send it.
17
+ - ``song {"index": n}`` or ``song {"step": 1 or -1}``: another starter song,
18
+ while stopped.
19
+ - ``kit {"spec": "rhythm909"}`` or ``kit {"step": 1 or -1}``: another kit,
20
+ at once, even while playing. Every panel hears ``kit`` back, with the
21
+ notes the new kit plays (``voices``).
22
+ - ``stop {}``: stop now.
23
+ - ``action {"name": "fill"}``: one of the actions a MIDI switch can be
24
+ bound to (`midipedal.BINDINGS`): start, fill, next, outro, stop or
25
+ tap_tempo.
26
+ - ``pedals {"learn": n}`` (-1 stops), ``pedals {"slot": n, "bind": "fill"}``
27
+ or ``pedals {"slot": n, "clear": true}``: the MIDI switches' map. Every
28
+ panel hears ``pedals`` back with the whole map, and again when a slot
29
+ learns its switch.
30
+ - ``ask {"text": "a slow 12-bar blues at 72"}``: ask the chat server for a
31
+ song (`ask`). Telemetry's ``ask`` says ``"asking"``, then ``"ready"`` or
32
+ ``"failed"`` (with ``ask_error``), and every panel hears ``proposal``
33
+ with the song's `ask.preview`, also in the description for a panel that
34
+ joins later.
35
+ - ``proposal {"do": "play"}``, ``{"do": "keep"}`` or ``{"do": "discard"}``:
36
+ play the song that came back (the song playing stops first), keep it
37
+ among the songs (saved in the box's own songs folder), or let it go and
38
+ have back the song from before.
39
+
40
+ Edits are songmodel ops on the document, and they reach the sound while it
41
+ plays: a step added or removed plays from its next pass, a new tempo keeps
42
+ the playhead where it is, ``/tracks/0/volume`` is the kit's level and
43
+ ``/tracks/0/mix/<group>`` (0 to 100) turns one group of drums up or down
44
+ (`engine.GROUPS`).
45
+
46
+ Telemetry is `engine.Engine.telemetry`: bar, beat, part, next part,
47
+ pedals, tempo and kit.
48
+
49
+ No LVGL and no audio output here: the app gives the box its clock and plays
50
+ the box's ``bus``, so a check can run a box and pull the sound itself.
51
+ """
52
+
53
+ import gc
54
+ import json
55
+ import os
56
+
57
+ import hmilink
58
+ from appkit import assets
59
+ from hmilink import local
60
+ from songmodel.link import SongModel
61
+
62
+ from . import ask as askmod
63
+ from . import engine as eng
64
+ from . import kits
65
+ from . import midipedal
66
+
67
+ LEVEL = 0.9 # the kit's level at track volume 100
68
+ _NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789"
69
+ here = __file__.replace("\\", "/")
70
+ SONGS = here[: here.rfind("/")] + "/songs"
71
+
72
+
73
+ def song_files(folder=SONGS):
74
+ """The starter songs, ``[(name, path)]``, in name order."""
75
+ try:
76
+ names = [n for n in assets.listdir(folder) if n.endswith(".json")]
77
+ except OSError:
78
+ return []
79
+ return [(n[:-5], folder + "/" + n) for n in names]
80
+
81
+
82
+ def load_song(path):
83
+ return json.loads(assets.read(path))
84
+
85
+
86
+ class BacklineModel(SongModel):
87
+ """The song a Backline box holds, as an hmilink model."""
88
+
89
+ def describe(self):
90
+ out = SongModel.describe(self)
91
+ out["kind"] = "backline"
92
+ out["parts"] = self.doc.get("parts")
93
+ box = self.host
94
+ if box is not None:
95
+ out["proposal"] = box.proposal_preview
96
+ out["can_ask"] = box.ask_settings is not None
97
+ out["songs"] = [n for n, _p in box.songs]
98
+ out["titles"] = box.titles()
99
+ out["kits"] = list(box.kits)
100
+ out["kit_list"] = kits.describe(box.kits)
101
+ out["kit"] = box.kit_spec()
102
+ out["voices"] = box.voices()
103
+ out["groups"] = [[n, list(p)] for n, p in eng.GROUPS] + [[eng.OTHER, []]]
104
+ out["pedals"] = box.midi.describe()
105
+ return out
106
+
107
+
108
+ class Box:
109
+ """The engine, its kit and the device. ``clock()`` is the output's frame."""
110
+
111
+ def __init__(self, clock, song=None, kit=None, rate=kits.RATE, songs=None, now_ms=None, pedal_map=None,
112
+ worker=None, ask_settings=None, user_songs=None, post=None):
113
+ self.rate = rate
114
+ self.songs = song_files() if songs is None else songs
115
+ #: Where kept songs are saved, and listed after the starters.
116
+ self.user_songs = user_songs
117
+ if user_songs:
118
+ self.songs = self.songs + song_files(user_songs)
119
+ self.kits = kits.available()
120
+ #: What runs a blocking call off the main thread (``scope.worker``); None runs it here.
121
+ self.worker = worker
122
+ self.ask_settings = ask_settings
123
+ self._post = post
124
+ self.asker = None
125
+ self.ask_state = ""
126
+ self.ask_error = ""
127
+ self.proposal = None # the song that came back, not yet kept or let go
128
+ self.proposal_preview = None
129
+ self._before = None # (song index, the song) the proposal took the place of
130
+ self.song_index = 0
131
+ self._titles = None
132
+ if isinstance(song, str):
133
+ for i, (n, _p) in enumerate(self.songs):
134
+ if n == song:
135
+ self.song_index = i
136
+ project = load_song(self.songs[self.song_index][1]) if song is None or isinstance(song, str) else song
137
+ self.bus = kits.Bus(rate)
138
+ kw = {} if now_ms is None else {"now_ms": now_ms}
139
+ self.engine = eng.Engine(project, None, clock, rate, **kw)
140
+ self.error = None
141
+ self.cast = "" # where the desk view is cast, while it is
142
+ #: The MIDI switches' map, and the input it reads (`midipedal.open_input`).
143
+ self.midi = midipedal.MidiPedal(pedal_map, on_pedal=self.pedal, on_action=self.action,
144
+ on_change=self._pedals_changed)
145
+ self.midi_in = None
146
+ self.taps = midipedal.TapTempo()
147
+ #: Switches on pins (`footswitch.Footswitch`), read each `service` pass.
148
+ self.switches = []
149
+ self.model = BacklineModel(project, forward=self.forward, host=self)
150
+ self.device = hmilink.Device(self.model, telemetry_hz=30)
151
+ # A kit kept from before that this box no longer has (a card taken
152
+ # out) gives way to the song's.
153
+ spec = (kit if kit in self.kits else None) or project["tracks"][0].get("instrument") or kits.DEFAULT
154
+ self.fetching = False
155
+ if not self.use_kit(spec) and spec == kits.SOUNDFONT and kits.find_bank() is None:
156
+ self._fetch_default()
157
+ self._level()
158
+
159
+ # -- the sound --------------------------------------------------------------
160
+
161
+ def use_kit(self, spec):
162
+ """Play kit ``spec`` from now on. A kit that won't open leaves the one
163
+ before playing and says why in ``error``. The kit playing already
164
+ isn't built again.
165
+
166
+ While the song is stopped, the kit before goes first and the heap is
167
+ collected, so the new one is built in the room it left: on a heap in
168
+ pieces, a kit built beside the old one took nearly twice as long."""
169
+ if spec == self.kit_spec():
170
+ self.error = None
171
+ return True
172
+ before = None
173
+ if not self.engine.transport["playing"] and self.bus.kit is not None:
174
+ before = self.bus.kit.spec
175
+ self.engine.set_kit(None)
176
+ self.bus.detach()
177
+ gc.collect()
178
+ try:
179
+ kit = kits.open_kit(spec, self.rate)
180
+ except Exception as e: # noqa: BLE001 - said on the screen, the old kit plays on
181
+ if before is not None:
182
+ self.use_kit(before)
183
+ self.error = "kit %s: %s" % (spec, e)
184
+ return False
185
+ self.bus.attach(kit)
186
+ self.engine.set_kit(kit)
187
+ # A kit that can hold a note back gets it early, and plays it on its frame.
188
+ self.engine.lookahead = 2 * kits.BLOCK if kit.timed else 0
189
+ self.error = None
190
+ return True
191
+
192
+ def _fetch_default(self):
193
+ """Fetch Backline's own bank on the worker, the first time it's wanted
194
+ and isn't here; the ``soundfont`` kit opens when it lands. Without a
195
+ worker the error stays, saying where the bank goes."""
196
+ if self.worker is None:
197
+ return
198
+ self.fetching = True
199
+ self.error = "fetching Backline's drums, once (%d KB)" % (kits.DEFAULT_BYTES // 1024)
200
+ self.worker.submit(kits.fetch_default, self._fetched, key="backline-drums")
201
+
202
+ def _fetched(self, path, error):
203
+ """The bank landed, or didn't: on the main thread."""
204
+ self.fetching = False
205
+ if error is not None:
206
+ self.error = "no drums: %s. Pick a drum machine, or put %s in %s" % (
207
+ error, kits.DEFAULT_BANK, kits.where())
208
+ elif self.kit_spec() is None:
209
+ self.use_kit(kits.DEFAULT)
210
+ self.device.event("kit", spec=self.kit_spec(), error=self.error, voices=self.voices())
211
+
212
+ def titles(self):
213
+ """Each starter song's own name, read once."""
214
+ if self._titles is None:
215
+ found = []
216
+ for name, path in self.songs:
217
+ try:
218
+ found.append(load_song(path).get("name") or name)
219
+ except (OSError, ValueError):
220
+ found.append(name)
221
+ self._titles = found
222
+ return self._titles
223
+
224
+ def kit_spec(self):
225
+ kit = self.engine.kit
226
+ return kit.spec if kit is not None else None
227
+
228
+ def voices(self):
229
+ """``[[pitch, name]]``: the drums the kit playing now has, by General
230
+ MIDI's short names where it has one, so a row reads the same on every kit."""
231
+ kit = self.engine.kit
232
+ if kit is None or not hasattr(kit, "voices"):
233
+ return []
234
+ short = dict(kits.GM_DRUMS)
235
+ return [[int(p), short.get(int(p), n)] for p, n in kit.voices()]
236
+
237
+ def _level(self):
238
+ vol = self.engine.track.get("volume", 100)
239
+ self.bus.level(LEVEL * vol / 100.0)
240
+
241
+ def forward(self, op):
242
+ """An op the song took from a panel: the engine follows it.
243
+
244
+ A step's notes are read as they play, so a note edit needs nothing
245
+ here. A pattern's length or the song's parts make a new plan that
246
+ keeps what plays now and what is queued."""
247
+ if op.get("op") == "replace":
248
+ self.engine.load(self.model.doc)
249
+ self._level()
250
+ return
251
+ path = op.get("path", ())
252
+ if path == ["tempo"]:
253
+ self.engine.retempo()
254
+ elif path[:1] == ["parts"] or (len(path) >= 3 and path[2] == "patterns" and "notes" not in path):
255
+ self.engine.reform()
256
+ elif path == ["tracks", 0, "volume"]:
257
+ self._level()
258
+
259
+ def service(self):
260
+ """One pass: the pedals' timing, the notes due, the kit's fill, the panels."""
261
+ e = self.engine
262
+ if self.switches:
263
+ now = e.now_ms()
264
+ for sw in self.switches:
265
+ sw.poll(now)
266
+ if self.midi_in is not None:
267
+ try:
268
+ self.midi.read_port(self.midi_in)
269
+ except Exception as err: # noqa: BLE001 - said on the screen, the song plays on
270
+ self.error = "MIDI in stopped: %s" % (err,)
271
+ self.midi_in = None
272
+ e.poll()
273
+ e.sequence()
274
+ self.bus.fill()
275
+
276
+ def poll(self):
277
+ self.device.poll()
278
+
279
+ # -- what panels ask --------------------------------------------------------
280
+
281
+ def telemetry(self):
282
+ t = self.engine.telemetry()
283
+ t["error"] = self.error or ""
284
+ # -1 while a song that came back from `ask` plays: it isn't one of the songs yet
285
+ t["song_index"] = -1 if self._before is not None else self.song_index
286
+ t["songs"] = len(self.songs)
287
+ t["cast"] = self.cast
288
+ t["ask"] = self.ask_state
289
+ t["ask_error"] = self.ask_error
290
+ # Panels on another screen: a browser, another computer or board.
291
+ t["desks"] = sum(1 for link in self.device.links if not isinstance(link, local.Link))
292
+ return t
293
+
294
+ def pedal(self, which, down):
295
+ """Footswitch ``which`` (0 or 1) went down or up. Every source of a
296
+ pedal comes in here: a panel's lamp or key, and a switch on a pin or
297
+ a MIDI note or controller on a box that has one."""
298
+ if down:
299
+ self.engine.press(which)
300
+ else:
301
+ self.engine.release(which)
302
+
303
+ def action(self, name, now=None):
304
+ """Do one of a MIDI switch's actions (`midipedal.BINDINGS`); returns
305
+ what the song did, as `engine.Engine.gesture` says it, or the new tempo.
306
+
307
+ Each is a gesture of pedal A where the song is: start only starts a
308
+ stopped song, and fill, next and outro only change one that plays."""
309
+ e = self.engine
310
+ playing = e.transport["playing"]
311
+ if name == "start":
312
+ return e.gesture(0, "tap") if not playing else None
313
+ if name in ("fill", "next", "outro"):
314
+ return e.gesture(0, {"fill": "tap", "next": "hold", "outro": "double"}[name]) if playing else None
315
+ if name == "stop":
316
+ e.stop()
317
+ e.last = "stop"
318
+ return "stop"
319
+ if name == "tap_tempo":
320
+ bpm = self.taps.tap(e.now_ms() if now is None else now)
321
+ if bpm is not None:
322
+ self.set("/tempo", bpm)
323
+ return bpm
324
+ if name == "none":
325
+ return None
326
+ raise ValueError("no action %r" % (name,))
327
+
328
+ def set(self, path, value):
329
+ """Change the song from the box itself, as a panel's op would, and
330
+ tell every panel."""
331
+ dev = self.device
332
+ op = self.model.apply({"op": "replace", "path": path, "value": value})
333
+ dev.seq += 1
334
+ msg = {"t": "op", "seq": dev.seq, "op": op["op"], "path": op["path"], "value": op.get("value")}
335
+ dev.broadcast(msg)
336
+
337
+ def _pedals_changed(self):
338
+ self.device.event("pedals", **self.midi.describe())
339
+
340
+ def command(self, name, args):
341
+ e = self.engine
342
+ if name == "pedal":
343
+ self.pedal(int(args.get("pedal", 0)), bool(args.get("down")))
344
+ return None
345
+ if name == "gesture":
346
+ did = e.gesture(int(args.get("pedal", 0)), args["gesture"])
347
+ return {"name": "gesture", "did": did}
348
+ if name == "stop":
349
+ e.stop()
350
+ return None
351
+ if name == "action":
352
+ did = self.action(args["name"])
353
+ return {"name": "action", "action": args["name"], "did": did}
354
+ if name == "pedals":
355
+ m = self.midi
356
+ if "learn" in args:
357
+ m.learn(int(args["learn"]))
358
+ elif args.get("clear"):
359
+ m.clear(int(args["slot"]))
360
+ elif "bind" in args:
361
+ m.bind(int(args["slot"]), args["bind"])
362
+ return None # the map changed: `_pedals_changed` told every panel
363
+ if name == "song":
364
+ if e.transport["playing"]:
365
+ raise ValueError("stop the song first")
366
+ n = len(self.songs)
367
+ i = args["index"] if "index" in args else self.song_index + int(args.get("step", 1))
368
+ self.song_index = i % n
369
+ project = load_song(self.songs[self.song_index][1])
370
+ # The kit first, so the document every panel gets says the kit it plays.
371
+ self.use_kit(project["tracks"][0].get("instrument") or kits.DEFAULT)
372
+ self.model.load(project)
373
+ return {"name": "song", "index": self.song_index, "kit": self.kit_spec(), "voices": self.voices()}
374
+ if name == "ask":
375
+ return self.ask(args.get("text", ""))
376
+ if name == "proposal":
377
+ return self.proposal_do(args.get("do"))
378
+ if name == "kit":
379
+ spec = args.get("spec")
380
+ if spec is None:
381
+ cur = e.kit.spec if e.kit is not None else None
382
+ i = self.kits.index(cur) if cur in self.kits else -1
383
+ spec = self.kits[(i + int(args.get("step", 1))) % len(self.kits)]
384
+ self.use_kit(spec)
385
+ return {"name": "kit", "spec": self.kit_spec(), "error": self.error, "voices": self.voices()}
386
+ raise ValueError("unknown command %r" % name)
387
+
388
+ # -- a song asked for in words ------------------------------------------------
389
+
390
+ def ask(self, text):
391
+ """Ask the chat server for a song for ``text``, from the worker."""
392
+ text = " ".join(str(text).split())
393
+ if not text:
394
+ raise ValueError("say what to play")
395
+ if self.ask_settings is None:
396
+ raise ValueError("this box has no chat server set up")
397
+ if self.ask_state == "asking":
398
+ raise ValueError("still asking for the last one")
399
+ if self.asker is None:
400
+ starters = []
401
+ for name, path in song_files():
402
+ try:
403
+ starters.append((name, load_song(path)))
404
+ except (OSError, ValueError):
405
+ pass
406
+ choices = [k for k in self.kits if k in kits.MACHINES or k == kits.SOUNDFONT]
407
+ self.asker = askmod.Asker(self.ask_settings, choices, starters, self._post)
408
+ self.ask_state = "asking"
409
+ self.ask_error = ""
410
+ asker = self.asker
411
+ if self.worker is None:
412
+ try:
413
+ found = asker.ask(text)
414
+ except Exception as e: # noqa: BLE001 - said on every panel
415
+ self._asked(None, e)
416
+ else:
417
+ self._asked(found, None)
418
+ else:
419
+ self.worker.submit(lambda: asker.ask(text), self._asked, key="backline-ask")
420
+ return {"name": "asking", "text": text}
421
+
422
+ def _asked(self, found, error):
423
+ """The worker's answer, on the main thread."""
424
+ if error is not None:
425
+ self.ask_state = "failed"
426
+ self.ask_error = str(error) or error.__class__.__name__
427
+ self.device.event("proposal", preview=None, error=self.ask_error)
428
+ return
429
+ project, preview = found
430
+ preview["kit_name"] = kits.title(preview["kit"]) if preview["kit"] in self.kits else preview["kit"]
431
+ self.proposal = project
432
+ self.proposal_preview = preview
433
+ self.ask_state = "ready"
434
+ self.device.event("proposal", preview=preview, error="")
435
+
436
+ def proposal_do(self, what):
437
+ """``"play"``, ``"keep"`` or ``"discard"`` the song that came back."""
438
+ if self.proposal is None:
439
+ raise ValueError("no song to %s: ask for one first" % what)
440
+ e = self.engine
441
+ if what == "play":
442
+ if self._before is None:
443
+ self._before = (self.song_index, json.loads(json.dumps(self.model.doc)))
444
+ e.stop()
445
+ self.model.load(json.loads(json.dumps(self.proposal)))
446
+ self.use_kit(self.proposal["tracks"][0]["instrument"])
447
+ e.gesture(0, "tap")
448
+ return {"name": "proposal", "did": "play", "kit": self.kit_spec(), "voices": self.voices()}
449
+ if what == "keep":
450
+ if not self.user_songs:
451
+ raise ValueError("this box has nowhere to keep songs")
452
+ path = self._save(self.proposal)
453
+ self.songs = self.songs + [(path[path.rfind("/") + 1:-5], path)]
454
+ self._titles = None
455
+ if self._before is not None: # it is the song loaded now
456
+ self.song_index = len(self.songs) - 1
457
+ self._before = None
458
+ self._clear()
459
+ self.device.reset_doc()
460
+ return {"name": "proposal", "did": "keep", "index": len(self.songs) - 1}
461
+ if what == "discard":
462
+ self._clear()
463
+ if self._before is not None:
464
+ index, project = self._before
465
+ e.stop()
466
+ self.song_index = index
467
+ self.model.load(project)
468
+ self.use_kit(project["tracks"][0].get("instrument") or kits.DEFAULT)
469
+ self._before = None
470
+ return {"name": "proposal", "did": "discard", "kit": self.kit_spec(), "voices": self.voices()}
471
+ raise ValueError("play, keep or discard, not %r" % (what,))
472
+
473
+ def _clear(self):
474
+ self.proposal = None
475
+ self.proposal_preview = None
476
+ self.ask_state = ""
477
+ self.ask_error = ""
478
+
479
+ def _save(self, project):
480
+ """Write ``project`` into the box's songs folder, under a name of its own."""
481
+ folder = self.user_songs
482
+ try:
483
+ os.mkdir(folder)
484
+ except OSError:
485
+ pass # there already
486
+ stem = "".join(c if c in _NAME_CHARS else "_" for c in project.get("name", "song").lower()).strip("_") or "song"
487
+ taken = set(n for n, _p in self.songs)
488
+ name, n = stem, 2
489
+ while name in taken:
490
+ name, n = "%s_%d" % (stem, n), n + 1
491
+ path = folder + "/" + name + ".json"
492
+ with open(path, "w") as f:
493
+ json.dump(project, f)
494
+ return path
495
+
496
+ def close(self):
497
+ port = self.midi_in
498
+ self.midi_in = None
499
+ if port is not None and hasattr(port, "close"):
500
+ port.close()
501
+ self.device.close()
502
+ self.bus.close()
apps/backline/cast.py ADDED
@@ -0,0 +1,137 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Backline's desk view on a screen across the room.
5
+
6
+ The box draws a desk view on a 1280x720 LVGL display of its own, in memory,
7
+ and hands each finished frame to a cast: a Windows PC's Wireless Display
8
+ app or a Roku's Screen mirroring, over Miracast. The desk there is a panel like any other, so
9
+ it follows the song as it plays and a change made anywhere shows on it.
10
+ The box's own screen, if it has one, carries on as before.
11
+
12
+ target = remote.cast_target(prefs) # {"kind", "host", "name"}
13
+ cast = CastDesk(open_sink(target), box.device)
14
+ while True:
15
+ lv.timer_handler()
16
+ cast.step()
17
+
18
+ The cast itself is ``castdisplay``'s (CPython with ffmpeg, or a board whose
19
+ firmware has castif). The sound stays where the box plays it.
20
+ """
21
+
22
+ import lvgl as lv
23
+
24
+ try:
25
+ from time import ticks_diff, ticks_ms
26
+ except ImportError:
27
+ from multimer import ticks_diff, ticks_ms
28
+
29
+ import hmilink
30
+ from hmilink import local
31
+
32
+ from .desk import Desk
33
+
34
+ SIZE = (1280, 720)
35
+ FPS = 20 # frames a second a Miracast stream carries
36
+ BITRATE = 2_000_000
37
+ NAME = "Backline"
38
+
39
+
40
+ def open_sink(target, size=SIZE, name=NAME, log=None):
41
+ """The cast for ``target`` (`remote.cast_target`), started: a display
42
+ whose frames go to the receiver.
43
+
44
+ Raises:
45
+ ImportError: castdisplay isn't installed.
46
+ ValueError: ``target`` names a kind there's no cast for.
47
+ """
48
+ kind = target["kind"]
49
+ w, h = size
50
+ if kind in ("windows", "roku"):
51
+ from castdisplay.cast_display import CastDisplay
52
+
53
+ return CastDisplay(target["host"], w, h, kind=kind, fps=FPS, bitrate=BITRATE, name=name, log=log)
54
+ raise ValueError("no cast for %r" % (kind,))
55
+
56
+
57
+ class CastDesk:
58
+ """A `Desk` on its own display, drawn into ``sink``'s frame buffer.
59
+
60
+ ``sink`` is any display with ``framebuffers()``, ``show()`` and
61
+ ``close()`` (a castdisplay display, or a stand-in in a test). ``device``
62
+ is the box's ``hmilink.Device``: the desk joins it as a local panel.
63
+ ``fps`` caps how often a changed frame is sent, on the clock
64
+ ``now_ms`` (milliseconds, the real one by default).
65
+ """
66
+
67
+ def __init__(self, sink, device, size=SIZE, fps=None, now_ms=ticks_ms):
68
+ if not lv.is_initialized():
69
+ lv.init()
70
+ self.sink = sink
71
+ self.now_ms = now_ms
72
+ self.size = w, h = size
73
+ self.gap_ms = 1000 // (fps or FPS)
74
+ self.sent = 0 # frames handed to the cast
75
+ self.drawn = 0 # refreshes LVGL finished
76
+ self.dirty = False
77
+ self.last = None
78
+ buf = sink.framebuffers()[0]
79
+ self.disp = lv.display_create(w, h)
80
+ self.disp.set_color_format(lv.COLOR_FORMAT.RGB565)
81
+ # LVGL draws straight into the buffer the cast reads.
82
+ self.disp.set_buffers(buf, None, len(buf), lv.DISPLAY_RENDER_MODE.DIRECT)
83
+ self.disp.set_flush_cb(self._flush)
84
+ prev = lv.display_get_default()
85
+ self.disp.set_default()
86
+ self.screen = lv.obj(None)
87
+ if prev is not None:
88
+ prev.set_default() # the box's own screen stays where new screens go
89
+ self.panel = hmilink.Panel(local.connect(device.add(local.serve())))
90
+ self.desk = Desk(self.screen, size, self.panel)
91
+ lv.screen_load(self.screen)
92
+
93
+ def _flush(self, disp, area, px):
94
+ if disp.flush_is_last():
95
+ self.drawn += 1
96
+ self.dirty = True
97
+ disp.flush_ready()
98
+
99
+ def step(self):
100
+ """One pass: what the box sent, and a changed frame to the cast
101
+ when the last one went long enough ago."""
102
+ self.desk.poll()
103
+ if not self.dirty:
104
+ return
105
+ now = self.now_ms()
106
+ if self.last is not None and ticks_diff(now, self.last) < self.gap_ms:
107
+ return
108
+ self.last = now
109
+ self.dirty = False
110
+ self.sent += 1
111
+ self.sink.show()
112
+
113
+ def stats(self):
114
+ """The cast's own counters, with the frames drawn and sent from here."""
115
+ out = {}
116
+ try:
117
+ out.update(self.sink.stats())
118
+ except Exception: # noqa: BLE001 - a sink with no counters still casts
119
+ pass
120
+ out["drawn"] = self.drawn
121
+ out["handed"] = self.sent
122
+ return out
123
+
124
+ def close(self):
125
+ """Leave the box and end the cast."""
126
+ self.panel.close()
127
+ try:
128
+ self.disp.delete()
129
+ except Exception: # noqa: BLE001 - the cast still ends
130
+ pass
131
+ self.sink.close()
132
+
133
+
134
+ def start(device, target, log=None):
135
+ """Cast the desk of the box with ``device`` to ``target``. Returns the
136
+ `CastDesk`; call its ``step()`` from the UI loop."""
137
+ return CastDesk(open_sink(target, log=log), device, fps=FPS)