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,82 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Backline's icons, and what it shows on the status bar.
5
+
6
+ Each place an icon goes has a role here, and each role lists the Material
7
+ Symbols it can use, best first, then a glyph of LVGL's own font. The first
8
+ name the firmware's `icons` font has is drawn (``icons.has`` decides), and
9
+ with none of them the glyph is drawn as text, so a board whose firmware
10
+ is older than an icon still shows something in its place.
11
+
12
+ `bar_reading` is what the app's item on appkit's status bar shows while a
13
+ song plays: a dot, the part and the tempo.
14
+ """
15
+
16
+ import icons
17
+ import lvgl as lv
18
+ from icons import lvgl as lvicons
19
+
20
+ #: role: (icon names, best first; the glyph drawn when the font has none of them)
21
+ ICONS = {
22
+ "desk": (("view_module", "grid_on"), lv.SYMBOL.LIST),
23
+ "floor": (("footprint", "speed"), lv.SYMBOL.LEFT),
24
+ "songs": (("playlist_play", "queue_music"), lv.SYMBOL.LIST),
25
+ "form": (("timeline",), lv.SYMBOL.RIGHT),
26
+ "grid": (("view_module", "grid_on"), lv.SYMBOL.LIST),
27
+ "record": (("mic_external_on", "mic"), lv.SYMBOL.AUDIO),
28
+ "cast": (("cast_connected", "cast"), lv.SYMBOL.WIFI),
29
+ "remote": (("smartphone", "devices"), lv.SYMBOL.WIFI),
30
+ "loop": (("repeat_one", "repeat"), lv.SYMBOL.LOOP),
31
+ "playing": (("queue_music",), lv.SYMBOL.PLAY),
32
+ "prompt": (("auto_awesome",), lv.SYMBOL.EDIT),
33
+ }
34
+ DOT = "•" # a bullet, in every built-in Montserrat
35
+ FONT_SIZES = (14, 16, 24, 32, 40)
36
+
37
+
38
+ def pick(role):
39
+ """The first icon name for ``role`` that the font has, or None."""
40
+ for name in ICONS[role][0]:
41
+ if icons.has(name):
42
+ return name
43
+ return None
44
+
45
+
46
+ def glyph_font(px):
47
+ """The largest built-in font no taller than ``px``, else the smallest."""
48
+ best = None
49
+ for size in FONT_SIZES:
50
+ f = getattr(lv, "font_montserrat_%d" % size, None)
51
+ if f is not None and (best is None or size <= px):
52
+ best = f
53
+ return best or lv.font_get_default()
54
+
55
+
56
+ def show(parent, role, size, color):
57
+ """The icon for ``role`` on ``parent``, ``size`` pixels square in ``color``
58
+ (an ``lv.color_t``): an ``lv.image``, or an ``lv.label`` holding the glyph
59
+ when the font has none of the role's icons."""
60
+ name = pick(role)
61
+ if name is not None:
62
+ return lvicons.image(parent, name, size, color)
63
+ lbl = lv.label(parent)
64
+ lbl.set_style_text_font(glyph_font(size), 0)
65
+ lbl.set_style_text_color(color, 0)
66
+ lbl.set_text(ICONS[role][1])
67
+ return lbl
68
+
69
+
70
+ def bar_reading(t):
71
+ """``(icon, text)`` for the status bar from the box's telemetry ``t``,
72
+ or None while the song is stopped. The icon is the cast's while the
73
+ desk is cast; where the font has no icon for it, the glyph leads the
74
+ text instead."""
75
+ if not t.get("playing"):
76
+ return None
77
+ role = "cast" if t.get("cast") else "playing"
78
+ name = pick(role)
79
+ text = "%s %s %d" % (DOT, (t.get("part") or "").upper(), int(t.get("tempo", 0) + 0.5))
80
+ if name is None:
81
+ text = ICONS[role][1] + " " + text
82
+ return name, text
apps/backline/kits.py ADDED
@@ -0,0 +1,428 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Backline's drum sounds: one interface over two kinds of kit.
5
+
6
+ - The drum kit of a SoundFont bank (`SoundFontKit`), through
7
+ audioinstruments' ``soundfont_drums``. The ``soundfont`` kit, the one
8
+ Backline starts on, plays ``$SOUNDFONT`` when that is set, and otherwise
9
+ Backline's own bank, `DEFAULT_BANK`: a small General MIDI drum kit made from
10
+ the FreePats synthesizer percussion (CC0). A firmware can carry the bank
11
+ frozen in as `FROZEN_MODULE`, and Backline then plays it from flash.
12
+ Otherwise, installing Backline on a board with omip puts the bank in the
13
+ app's ``soundfonts`` folder; with pip, or in a frozen firmware, Backline
14
+ fetches it on its first start (`fetch_default`).
15
+ Every other ``.sf2`` in a ``soundfonts`` folder is a kit of its own:
16
+ ``~/soundfonts`` on a computer, or the card's, flash's or the data root's
17
+ on a board.
18
+ - A drum machine from audioinstruments (`DrumMachineKit`): ``rhythm606``,
19
+ ``rhythm78``, ``rhythm808``, ``rhythm909`` and ``electronic_drums5``.
20
+
21
+ Every kit has ``name``, ``output`` (what the output plays),
22
+ ``note_on(pitch, velocity, delay=0)`` with the delay in frames, ``fill()``,
23
+ ``timed`` (True when it honours the delay) and ``close()``. `Bus` is the
24
+ output the app plays, so a kit can be swapped while the song runs.
25
+ """
26
+
27
+ import os
28
+ import sys
29
+
30
+ try:
31
+ import hashlib
32
+ except ImportError: # pragma: no cover - every port Backline runs on has it
33
+ hashlib = None
34
+
35
+ RATE = 48000
36
+ CHANNELS = 2
37
+ BLOCK = 256
38
+ MACHINES = ("rhythm808", "rhythm909", "rhythm606", "rhythm78", "electronic_drums5")
39
+ NAMES = {"rhythm808": "Rhythm 808", "rhythm909": "Rhythm 909", "rhythm606": "Rhythm 606",
40
+ "rhythm78": "Rhythm 78", "electronic_drums5": "Electronic Drums 5"}
41
+ SOUNDFONT = "soundfont"
42
+ #: The kit Backline plays when nothing names one.
43
+ DEFAULT = SOUNDFONT
44
+ #: Backline's own bank, which the ``soundfont`` kit plays unless ``$SOUNDFONT``
45
+ #: names another. ``tools/backline/make_drums.py`` makes it; it is published
46
+ #: at `DEFAULT_URL` and checked against `DEFAULT_SHA256` when fetched.
47
+ DEFAULT_BANK = "backline-drums.sf2"
48
+ DEFAULT_TITLE = "Backline Drums"
49
+ DEFAULT_URL = "https://github.com/PyDevices/lib/releases/download/backline-drums-1/" + DEFAULT_BANK
50
+ DEFAULT_SHA256 = "6f719656ecfa2b5ae8946402bb64c532086d682bad75816d7c6d58741b1ae095"
51
+ DEFAULT_BYTES = 1657008
52
+ #: The module a firmware freezes `DEFAULT_BANK` into, its ``BANK`` the bank's
53
+ #: bytes (audioinstruments' ``tools/freeze_soundfont.py`` makes it). When it is
54
+ #: there the ``soundfont`` kit plays the bank in place, from flash, and
55
+ #: nothing is fetched.
56
+ FROZEN_MODULE = "backline_drums"
57
+ #: Backline's data folder, which the app sets from its scope; a computer keeps
58
+ #: the fetched bank there. Leaving the import of appkit to the app keeps this
59
+ #: module, and the box, free of LVGL.
60
+ data_folder = None
61
+ DESKTOP = sys.implementation.name == "cpython" or sys.platform in (
62
+ "linux", "darwin", "win32", "cygwin", "freebsd", "openbsd", "netbsd")
63
+
64
+
65
+ def getenv(name):
66
+ fn = getattr(os, "getenv", None)
67
+ return fn(name) if fn is not None else None
68
+
69
+
70
+ def home():
71
+ return (getenv("USERPROFILE") or getenv("HOME") or "").replace("\\", "/")
72
+
73
+
74
+ def _here():
75
+ """This app's folder, where omip puts the bank, or None in a frozen firmware."""
76
+ path = globals().get("__file__", "").replace("\\", "/")
77
+ return path.rsplit("/", 1)[0] if "/" in path else None
78
+
79
+
80
+ def _exists(path):
81
+ try:
82
+ os.stat(path)
83
+ return True
84
+ except OSError:
85
+ return False
86
+
87
+
88
+ def _listdir(folder):
89
+ try:
90
+ return sorted(os.listdir(folder))
91
+ except OSError:
92
+ return []
93
+
94
+
95
+ def bank_folders():
96
+ """Where other SoundFonts are found: ``~/soundfonts`` on a computer, the
97
+ ``soundfonts`` folder on the card, flash and data root of a board."""
98
+ if DESKTOP:
99
+ return [home() + "/soundfonts"]
100
+ from appkit import places
101
+
102
+ return places.folders("soundfonts")
103
+
104
+
105
+ def default_folders():
106
+ """Where `DEFAULT_BANK` is looked for, in order: the app's own
107
+ ``soundfonts`` folder (omip's install), then `data_folder` on a computer,
108
+ or the board's ``soundfonts`` folders (`fetch_default`'s)."""
109
+ here = _here()
110
+ found = [here + "/soundfonts"] if here else []
111
+ if DESKTOP:
112
+ return found + ([data_folder] if data_folder else [])
113
+ return found + bank_folders()
114
+
115
+
116
+ def default_bank():
117
+ """Where Backline's own bank is, or None before it has been fetched."""
118
+ for folder in default_folders():
119
+ if _exists(folder + "/" + DEFAULT_BANK):
120
+ return folder + "/" + DEFAULT_BANK
121
+ return None
122
+
123
+
124
+ def reads_from_memory():
125
+ """Whether this audioinstruments plays a bank held in memory, such as one
126
+ frozen into the firmware; an older one opens banks from files only."""
127
+ try:
128
+ import audioinstruments._rack._sf2 # noqa: F401 - a full name, past _rack's lazy attributes
129
+ except ImportError:
130
+ return False
131
+ return hasattr(sys.modules["audioinstruments._rack._sf2"].SoundFont, "sample_view")
132
+
133
+
134
+ def frozen_bank():
135
+ """Backline's bank frozen into the firmware, as bytes, or None when there
136
+ is none or this audioinstruments can't play it (`reads_from_memory`)."""
137
+ try:
138
+ module = __import__(FROZEN_MODULE)
139
+ except ImportError:
140
+ return None
141
+ bank = getattr(module, "BANK", None)
142
+ return bank if bank is not None and reads_from_memory() else None
143
+
144
+
145
+ def where():
146
+ """Where to put `DEFAULT_BANK` by hand, for a message."""
147
+ folders = default_folders()
148
+ return folders[-1] if folders else "a soundfonts folder"
149
+
150
+
151
+ def find_bank():
152
+ """The bank the ``soundfont`` kit plays: ``$SOUNDFONT``, else the bank
153
+ frozen into the firmware (`frozen_bank`, as bytes), else `default_bank`."""
154
+ return getenv("SOUNDFONT") or frozen_bank() or default_bank()
155
+
156
+
157
+ def other_banks():
158
+ """Every other ``.sf2`` in `bank_folders`, each a kit of its own."""
159
+ found = []
160
+ for folder in bank_folders():
161
+ for name in _listdir(folder):
162
+ if name.lower().endswith(".sf2") and name != DEFAULT_BANK:
163
+ found.append(folder + "/" + name)
164
+ return found
165
+
166
+
167
+ def _fetch_folder():
168
+ if DESKTOP:
169
+ if not data_folder:
170
+ raise OSError("Backline has no data folder to fetch its bank into")
171
+ return data_folder
172
+ from appkit import places
173
+
174
+ return places.write_folder("soundfonts")
175
+
176
+
177
+ def _http_get(url, write):
178
+ """Stream ``url`` into ``write``, following redirects; the HTTP status."""
179
+ from appkit import net
180
+
181
+ r = net.requests().get(url, timeout=30)
182
+ try:
183
+ if r.status_code == 200:
184
+ if hasattr(r, "iter_content"): # requests on a computer, adafruit_requests
185
+ for chunk in r.iter_content(4096):
186
+ write(chunk)
187
+ else: # MicroPython's requests: the socket
188
+ while True:
189
+ chunk = r.raw.read(1024)
190
+ if not chunk:
191
+ break
192
+ write(chunk)
193
+ return r.status_code
194
+ finally:
195
+ r.close()
196
+
197
+
198
+ #: Where this runs, as ``sys.platform`` says.
199
+ PLATFORM = sys.platform
200
+
201
+
202
+ def _default_url():
203
+ """Where the default bank is fetched from: the release file, or in a
204
+ browser, which can't download from GitHub's release files (they send no CORS
205
+ header), the page's own folder, where its build puts a copy."""
206
+ if PLATFORM in ("webassembly", "emscripten"):
207
+ import js
208
+
209
+ return str(js.URL.new(DEFAULT_BANK, js.document.baseURI).href)
210
+ return DEFAULT_URL
211
+
212
+
213
+ def _verify(got, sha256, url):
214
+ if got != sha256:
215
+ raise OSError("%s is not Backline's bank: its SHA-256 is %s" % (url, got))
216
+
217
+
218
+ def fetch_default(folder=None, url=None, sha256=None, get=None):
219
+ """Download Backline's bank once, check it, and return where it is.
220
+
221
+ It goes to ``folder``: by default `data_folder` on a computer, or
222
+ the first ``soundfonts`` folder that takes a file on a board (the card's,
223
+ when one is in). The file takes its name only once its SHA-256 matches, so
224
+ a failed or tampered download leaves nothing behind.
225
+
226
+ Args:
227
+ folder (str): Where to put it.
228
+ url (str): Where to fetch it from; `DEFAULT_URL` by default, or in a
229
+ browser the file beside the page.
230
+ sha256 (str): The hex digest it must have; `DEFAULT_SHA256` by default.
231
+ get: ``get(url, write)`` streams the body into ``write`` and returns
232
+ the HTTP status; by default urllib on CPython, requests on a board.
233
+
234
+ Raises:
235
+ OSError: no network, an HTTP error, or the wrong bytes.
236
+ """
237
+ folder = folder or _fetch_folder()
238
+ url = url or _default_url()
239
+ sha256 = sha256 or DEFAULT_SHA256
240
+ path = folder + "/" + DEFAULT_BANK
241
+ part = path + ".part"
242
+ digest = hashlib.sha256()
243
+ try:
244
+ with open(part, "wb") as f:
245
+
246
+ def write(chunk):
247
+ digest.update(chunk)
248
+ f.write(chunk)
249
+
250
+ status = (get or _http_get)(url, write)
251
+ if status != 200:
252
+ raise OSError("HTTP %s from %s" % (status, url))
253
+ _verify("".join("%02x" % b for b in digest.digest()), sha256, url)
254
+ try:
255
+ os.remove(path)
256
+ except OSError:
257
+ pass
258
+ os.rename(part, path)
259
+ except BaseException:
260
+ try:
261
+ os.remove(part)
262
+ except OSError:
263
+ pass
264
+ raise
265
+ return path
266
+
267
+
268
+ #: General MIDI's drum notes, for a kit that doesn't name its own.
269
+ GM_DRUMS = (
270
+ (35, "Kick 2"), (36, "Kick"), (37, "Side Stick"), (38, "Snare"), (39, "Clap"), (40, "Snare 2"),
271
+ (41, "Low Floor Tom"), (42, "Closed Hat"), (43, "Floor Tom"), (44, "Pedal Hat"), (45, "Low Tom"),
272
+ (46, "Open Hat"), (47, "Low Mid Tom"), (48, "High Mid Tom"), (49, "Crash"), (50, "High Tom"),
273
+ (51, "Ride"), (52, "China"), (53, "Ride Bell"), (54, "Tambourine"), (55, "Splash"), (56, "Cowbell"),
274
+ (57, "Crash 2"), (59, "Ride 2"), (60, "High Bongo"), (61, "Low Bongo"), (62, "Mute Conga"),
275
+ (63, "Open Conga"), (64, "Low Conga"), (69, "Cabasa"), (70, "Maracas"), (75, "Claves"),
276
+ )
277
+ SOURCES = (("soundfont", "SoundFont"), ("machine", "Drum machines"))
278
+
279
+
280
+ def source(spec):
281
+ """Which kind kit ``spec`` is: ``"soundfont"`` or ``"machine"``."""
282
+ if spec == SOUNDFONT or spec.startswith(SOUNDFONT + ":"):
283
+ return "soundfont"
284
+ return "machine"
285
+
286
+
287
+ def title(spec):
288
+ """What a screen calls kit ``spec``."""
289
+ if spec in NAMES:
290
+ return NAMES[spec]
291
+ if spec == SOUNDFONT and not getenv("SOUNDFONT"):
292
+ return DEFAULT_TITLE
293
+ path = spec.split(":", 1)[1] if ":" in spec else (find_bank() or "")
294
+ name = path.replace("\\", "/").rstrip("/").rsplit("/", 1)[-1]
295
+ if name.lower().endswith(".sf2"):
296
+ name = name[:-4]
297
+ return name or spec
298
+
299
+
300
+ def describe(specs):
301
+ """``[{"spec", "name", "source"}]`` for each kit spec, as panels list them."""
302
+ return [{"spec": s, "name": title(s), "source": source(s)} for s in specs]
303
+
304
+
305
+ def available():
306
+ """Every kit this device can play, as the specs `open_kit` takes: the
307
+ ``soundfont`` kit first, then the drum machines, then the other banks."""
308
+ return [SOUNDFONT] + list(MACHINES) + [SOUNDFONT + ":" + b for b in other_banks()]
309
+
310
+
311
+ def open_kit(spec, rate=RATE):
312
+ """A kit from its spec: ``"soundfont"``, ``"soundfont:/path/bank.sf2"``
313
+ or a drum machine's name."""
314
+ if spec in MACHINES:
315
+ return DrumMachineKit(spec, rate)
316
+ if spec == SOUNDFONT:
317
+ bank = find_bank()
318
+ if not bank:
319
+ raise OSError("%s isn't here yet: it is fetched from %s, or put it in %s" % (
320
+ DEFAULT_BANK, DEFAULT_URL, where()))
321
+ return SoundFontKit(bank, rate, spec)
322
+ if spec.startswith(SOUNDFONT + ":"):
323
+ return SoundFontKit(spec[len(SOUNDFONT) + 1:], rate, spec)
324
+ raise ValueError("no kit %r" % (spec,))
325
+
326
+
327
+ class DrumMachineKit:
328
+ """One of audioinstruments' drum machines."""
329
+
330
+ timed = False
331
+
332
+ def __init__(self, machine, rate=RATE):
333
+ import audioinstruments
334
+
335
+ self.spec = machine
336
+ self.name = NAMES.get(machine, machine)
337
+ self.inst = audioinstruments.create(machine, rate, CHANNELS)
338
+ self.output = self.inst.output
339
+ self._fill = getattr(self.inst, "fill", None)
340
+
341
+ def voices(self):
342
+ """``[(pitch, name)]``: the drum notes this kit plays."""
343
+ import audioinstruments
344
+
345
+ mod = getattr(audioinstruments, self.spec, None)
346
+ if mod is None:
347
+ try:
348
+ mod = __import__("audioinstruments." + self.spec, None, None, ["NOTE_MAP"])
349
+ except ImportError:
350
+ mod = None
351
+ table = getattr(mod, "NOTE_MAP", None)
352
+ return [list(v) for v in table] if table else [list(v) for v in GM_DRUMS]
353
+
354
+ def note_on(self, pitch, velocity, delay=0):
355
+ self.inst.note_on(pitch, velocity)
356
+
357
+ def fill(self):
358
+ if self._fill is not None:
359
+ self._fill()
360
+
361
+ def close(self):
362
+ if self.inst is not None:
363
+ self.inst.deinit()
364
+ self.inst = None
365
+
366
+
367
+ class SoundFontKit(DrumMachineKit):
368
+ """The standard drum kit of a SoundFont bank: a path, or Backline's own
369
+ bank's bytes when the firmware carries it frozen in."""
370
+
371
+ def __init__(self, bank, rate=RATE, spec=None):
372
+ import audioinstruments
373
+
374
+ self.spec = spec or SOUNDFONT + ":" + bank
375
+ self.bank = bank
376
+ name = bank.replace("\\", "/").rsplit("/", 1)[-1] if isinstance(bank, str) else DEFAULT_BANK
377
+ if name == DEFAULT_BANK:
378
+ self.name = DEFAULT_TITLE
379
+ else:
380
+ self.name = name[:-4] if name.lower().endswith(".sf2") else name
381
+ self.inst = audioinstruments.create("soundfont_drums", rate, CHANNELS, bank=bank)
382
+ self.output = self.inst.output
383
+ self._fill = getattr(self.inst, "fill", None)
384
+
385
+ def voices(self):
386
+ return [list(v) for v in GM_DRUMS]
387
+
388
+
389
+ class Bus:
390
+ """What the output plays: one mixer voice, whatever kit is on it."""
391
+
392
+ def __init__(self, rate=RATE, level=0.9):
393
+ import audiomixer
394
+
395
+ self.mixer = audiomixer.Mixer(voice_count=1, sample_rate=rate, channel_count=CHANNELS,
396
+ bits_per_sample=16, samples_signed=True, buffer_size=BLOCK * 4)
397
+ self.mixer.voice[0].level = level
398
+ self.output = self.mixer
399
+ self.kit = None
400
+
401
+ def attach(self, kit):
402
+ """Play ``kit`` from now on; the one before is closed."""
403
+ old = self.kit
404
+ self.kit = kit
405
+ self.mixer.voice[0].play(kit.output, loop=True)
406
+ if old is not None and old is not kit:
407
+ old.close()
408
+
409
+ def detach(self):
410
+ """Play nothing, and close the kit that played."""
411
+ old, self.kit = self.kit, None
412
+ if old is not None:
413
+ self.mixer.voice[0].stop()
414
+ old.close()
415
+
416
+ def fill(self):
417
+ if self.kit is not None:
418
+ self.kit.fill()
419
+
420
+ def level(self, level):
421
+ """The whole kit's level, 0 to 1."""
422
+ self.mixer.voice[0].level = max(0.0, min(1.0, level))
423
+
424
+ def close(self):
425
+ self.mixer.voice[0].stop()
426
+ if self.kit is not None:
427
+ self.kit.close()
428
+ self.kit = None