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,690 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Bluetooth Receiver: the board plays what a phone or computer sends it.
5
+
6
+ Pair a phone with the board's name and play anything: music, a podcast, a
7
+ video's sound. The screen shows the cover large, then everything the sender
8
+ says about the track (title, artist, album, track number, genre, length and
9
+ where it's up to) and about the link (the sender's name, the codec and the
10
+ rate). The buttons drive the sender's player (hold a skip button to fast
11
+ forward or rewind), and the volume slider is the one on the phone. Shuffle
12
+ and repeat show the player's modes and change them, when the sender reports
13
+ them. While the phone streams, a spectrum of what plays runs under a
14
+ smaller cover; before it does, the cover takes that room.
15
+
16
+ With the "Phone calls and battery" switch in the header on (it's off until
17
+ you turn it on, and kept in ``config.json``), the board is also the phone's
18
+ hands-free unit, as a car kit is: the phone's battery and signal show at the
19
+ top right, and a call shows a card over the player with the caller's number,
20
+ to answer or decline. An answered call plays through the board's speaker and
21
+ sends its microphones to the phone, and the music comes back when the call
22
+ ends. On a board whose Bluetooth can't carry a
23
+ call's audio (``HandsFree.call_audio`` is False), the card answers and hangs
24
+ up, and you talk on the phone. A ringing call chimes every few
25
+ seconds.
26
+
27
+ A new text chimes once, over the music, whatever the calls setting (but not
28
+ over a call's audio on the board): the app
29
+ reads the phone's message service (MAP) for that, which the phone asks its
30
+ owner to allow the first time. ``"texts": false`` in ``config.json`` leaves
31
+ the phone's messages alone.
32
+
33
+ It needs a firmware with ``btclassic``. The audio goes out through the
34
+ board's ``audio_out`` on the audio pump, so a redraw never holds it up. On a
35
+ computer with no Bluetooth module the app plays a demo: a pretend phone that
36
+ pairs, plays a few tracks and follows the buttons.
37
+ """
38
+
39
+ import json
40
+
41
+ from multimer import ticks_diff, ticks_ms
42
+
43
+ from appkit import data as appdata
44
+ from appkit.shell import is_round
45
+ from controlkit import glyphs
46
+ from touchkit import settings, ui
47
+
48
+ from .chime import Chimes
49
+ from .screen import BANDS, Screen, calls_switch, switch_header
50
+
51
+ UI_MS = 250 # how often the app reads the sink
52
+ BARS_MS = 66 # how often the spectrum moves
53
+ COVER_PX = 200 # AVRCP covers are 200 x 200; a larger one is halved to fit
54
+ COVER_JPEG = 96 * 1024 # room for the cover's JPEG
55
+ # A phone starting a stream sends about twice as fast for a second or two:
56
+ # this rides that out. Half of it is the delay to the speaker.
57
+ BUFFER_MS = 1000
58
+ # Calling the phone's hands-free side when the setting is turned on: the
59
+ # first try waits this long after the unit starts, which a call made at once
60
+ # misses, and there are this many tries in all.
61
+ HF_RETRY_MS = 3000
62
+ HF_TRIES = 3
63
+ RING_MS = 4000 # how often a ringing call chimes
64
+ # The phone's message service, for the new-text chime: the first try waits
65
+ # this long after the music connects, which leaves the phone to set up its
66
+ # other links first. A try the phone hasn't answered in MAP_PENDING_MS is
67
+ # taken as failed.
68
+ MAP_WAIT_MS = 4000
69
+ MAP_TRIES = 3
70
+ MAP_PENDING_MS = 40000
71
+ MAP_BYTES = 4096 # the replies kept: only the phone's answer to notify()
72
+
73
+ state = None # the open app's state, for the console
74
+ # What Android sends for a field it doesn't know, the title included when
75
+ # nothing is playing.
76
+ UNSAID = "Not Provided"
77
+ # A tap moves repeat on the way a phone's player does, and turns shuffle on
78
+ # or off. "group" (a sender's own mode) goes back to off.
79
+ NEXT_REPEAT = {"off": "all", "all": "single"}
80
+ #: The app's settings, kept in ``config.json`` in its data folder. ``calls``
81
+ #: makes the board the phone's hands-free unit: the phone's battery and
82
+ #: signal from that link, and a card for its calls. Off, the board is a
83
+ #: speaker only, and the battery is the one the player reports. ``texts``
84
+ #: chimes for each new text, from the phone's message service.
85
+ DEFAULTS = {"calls": False, "texts": True}
86
+
87
+
88
+ def _said(text):
89
+ """*text*, or "" when the sender says it doesn't know."""
90
+ return "" if text == UNSAID else text
91
+
92
+
93
+ def _open_sink():
94
+ """``(radio, sink, bits, radio_was_on)``: btclassic's, or the demo's on a
95
+ computer. None on a board without btclassic."""
96
+ try:
97
+ import btclassic
98
+ except ImportError:
99
+ if not appdata.desktop():
100
+ return None
101
+ from . import demo
102
+
103
+ return demo.DemoRadio(), demo.DemoSink(), demo, True
104
+ bt = btclassic.Bluetooth()
105
+ was_on = bt.active()
106
+ return bt, btclassic.AudioSink(bt, buffer_ms=BUFFER_MS), btclassic, was_on
107
+
108
+
109
+ def _open_handsfree(bt, sink, bits):
110
+ """The phone's hands-free link, for the calls setting: btclassic's
111
+ ``HandsFree``, or the demo's on a computer. None on a firmware whose
112
+ btclassic has no hands-free unit."""
113
+ demo_unit = getattr(bits, "DemoHandsFree", None)
114
+ if demo_unit is not None:
115
+ return demo_unit(sink)
116
+ make = getattr(bits, "HandsFree", None)
117
+ if make is None:
118
+ print("btreceiver: this btclassic has no HandsFree: no battery, signal or calls")
119
+ return None
120
+ # Stereo frames, the shape the speaker plays. It follows the sink's phone.
121
+ return make(bt, channels=2)
122
+
123
+
124
+ def _open_messages(bt, sink, bits):
125
+ """The phone's message service, for the new-text chime: btclassic's
126
+ ``Messages``, or the demo's on a computer. None on a firmware whose
127
+ btclassic has no message client."""
128
+ demo_msgs = getattr(bits, "DemoMessages", None)
129
+ if demo_msgs is not None:
130
+ return demo_msgs(sink)
131
+ make = getattr(bits, "Messages", None)
132
+ if make is None:
133
+ print("btreceiver: this btclassic has no Messages: no chime for texts")
134
+ return None
135
+ return make(bt, max_bytes=MAP_BYTES)
136
+
137
+
138
+ def _load_config(scope):
139
+ """The app's settings: DEFAULTS, overridden by its ``config.json``."""
140
+ try:
141
+ return settings.config(scope, DEFAULTS)
142
+ except (ValueError, AttributeError): # a scope with no data folder
143
+ return dict(DEFAULTS)
144
+
145
+
146
+ def _save_config(scope, config):
147
+ """Keep *config* in the app's ``config.json``: only what differs from
148
+ DEFAULTS."""
149
+ changed = {k: v for k, v in config.items() if DEFAULTS.get(k) != v}
150
+ try:
151
+ path = appdata.join(scope.data_dir, "config.json")
152
+ with open(path, "w") as f:
153
+ f.write(json.dumps(changed))
154
+ except (OSError, ValueError, AttributeError) as e:
155
+ print("btreceiver: couldn't save the settings:", e)
156
+
157
+
158
+ def _speaker(rate):
159
+ """The board's ``audio_out`` at *rate*, or None where there's none."""
160
+ try:
161
+ import board_peripherals as bp
162
+ from audiodev import AudioFormat
163
+ except ImportError:
164
+ return None
165
+ make = getattr(bp, "audio_out", None)
166
+ if make is None:
167
+ return None
168
+ return make(AudioFormat(rate, 2, 16))
169
+
170
+
171
+ def _microphone(rate):
172
+ """The board's microphones, open, as one 16-bit channel at *rate*, for
173
+ a call. None on a board with no ``pcm_in``."""
174
+ try:
175
+ import board_peripherals as bp
176
+ from audiodev import AudioFormat
177
+ except ImportError:
178
+ return None
179
+ make = getattr(bp, "pcm_in", None)
180
+ if make is None:
181
+ return None
182
+ mic = make(AudioFormat(rate, 1, 16))
183
+ mic.open()
184
+ return mic
185
+
186
+
187
+ def _streaming(sink):
188
+ """Whether audio flows from the sender, whatever its player reports."""
189
+ return sink.connected and bool(getattr(sink, "streaming", False))
190
+
191
+
192
+ def _levels(out, demo_mode):
193
+ """A source of BANDS levels, 0 to 1, for what *out* plays, or None."""
194
+ try:
195
+ if demo_mode:
196
+ from spectrum.fake_music import FakeMusic
197
+
198
+ return FakeMusic(BANDS)
199
+ from spectrum.analyzer import levels_for
200
+
201
+ return levels_for(out)(BANDS)
202
+ except (ImportError, ValueError, AttributeError, OSError) as e:
203
+ print("btreceiver: no spectrum:", e)
204
+ return None
205
+
206
+
207
+ def main(scope):
208
+ global state
209
+ opened = _open_sink()
210
+ if opened is None:
211
+ ui.missing(scope, "missing: btclassic",
212
+ "Bluetooth Receiver needs a firmware with btclassic, the Bluetooth Classic module.")
213
+ return
214
+ bt, sink, bits, was_on = opened
215
+ config = _load_config(scope)
216
+ demo_mode = not hasattr(sink, "readinto")
217
+ name = bt.config("name")
218
+ try:
219
+ pin = bt.config("pin")
220
+ except (ValueError, OSError): # a firmware that doesn't read it back
221
+ pin = None
222
+ status = ui.status(scope)
223
+ status.set_text("demo" if demo_mode else "")
224
+
225
+ def toggle():
226
+ if sink.playing:
227
+ sink.pause()
228
+ else:
229
+ sink.play()
230
+
231
+ def volume(v):
232
+ sink.volume = v
233
+
234
+ def setting(name, value):
235
+ # The sender answers with its new state, which the button then shows.
236
+ try:
237
+ sink.setting(name, value)
238
+ except (OSError, ValueError) as e:
239
+ print("btreceiver: %s:" % name, e)
240
+
241
+ def repeat():
242
+ setting("repeat", NEXT_REPEAT.get(getattr(sink, "repeat", None), "off"))
243
+
244
+ def shuffle():
245
+ setting("shuffle", "all" if getattr(sink, "shuffle", None) == "off" else "off")
246
+
247
+ def answer():
248
+ st["hf"].answer()
249
+
250
+ def hangup():
251
+ st["hf"].hangup()
252
+
253
+ def mute():
254
+ st["muted"] = not st["muted"]
255
+ if st["mic"] is not None:
256
+ st["hf"].uplink(None if st["muted"] else st["mic"])
257
+ show_call()
258
+
259
+ def route_audio():
260
+ # The phone says when the audio has moved; the AUDIO bit follows.
261
+ if st["hf"].audio:
262
+ st["hf"].disconnect_audio()
263
+ else:
264
+ st["hf"].connect_audio()
265
+
266
+ on = {"play": toggle, "next": sink.next, "previous": sink.previous, "seek": sink.seek, "volume": volume,
267
+ "repeat": repeat, "shuffle": shuffle, "answer": answer, "hangup": hangup, "mute": mute,
268
+ "route": route_audio}
269
+ W, H = scope.size
270
+ rect = getattr(scope, "rect", None) or (0, 0, W, H)
271
+ round_ = W == H and tuple(rect[:2]) == (0, 0) and is_round()
272
+ scr = Screen(scope.root, scope.size, on, switch=switch_header(scope) is None, round_=round_)
273
+ st = state = {"sink": sink, "hf": None, "out": None, "rate": 0, "levels": None, "screen": scr, "t0": ticks_ms(),
274
+ "call_out": None, "mic": None, "muted": False, "talking": False, "answered": None,
275
+ "takes_audio": True, "config": config, "chimes": Chimes(), "rang": None, "msgs": None,
276
+ "map_tries": 0, "map_asked": ticks_ms(), "map_pending": False}
277
+ jpeg = bytearray(COVER_JPEG)
278
+ # Covers decode into two buffers made once, taking turns, so LVGL never
279
+ # shows the one being written and a new cover makes no garbage.
280
+ covers = [bytearray(COVER_PX * COVER_PX * 2) for _ in range(2)]
281
+
282
+ def route():
283
+ # Open the speaker at the stream's rate, and again if it changes. A
284
+ # call's audio has the speaker until it ends.
285
+ if st["talking"]:
286
+ return
287
+ rate = sink.sample_rate
288
+ if not rate or rate == st["rate"]:
289
+ return
290
+ if demo_mode: # the pretend phone has no audio: a chime's speaker stays
291
+ st["rate"] = rate
292
+ st["levels"] = _levels(None, True)
293
+ return
294
+ close_out()
295
+ st["rate"] = rate
296
+ if open_out(rate):
297
+ st["levels"] = _levels(st["out"], False)
298
+
299
+ def open_out(rate, music=True):
300
+ # The speaker plays the music and the chimes through one mixer.
301
+ # The demo's pretend phone has no audio: there it plays the chimes
302
+ # alone.
303
+ try:
304
+ out = _speaker(rate)
305
+ if out is None:
306
+ if not demo_mode:
307
+ status.set_text("no audio out")
308
+ return False
309
+ out.play(st["chimes"].mix(rate, sink if music else None))
310
+ st["out"] = out
311
+ except Exception as e: # the screen still follows the sender
312
+ print("btreceiver: no audio out:", e)
313
+ if not demo_mode:
314
+ status.set_text("no audio out")
315
+ return False
316
+ return True
317
+
318
+ def chime(kind):
319
+ # On the board, the call's audio has the speaker, and only the call's
320
+ # own chime goes over it while it rings. With no music yet, the
321
+ # speaker opens for the chime at the phone's usual rate, and stays
322
+ # open for the music to come.
323
+ if st["talking"]:
324
+ if kind == "call" and st["call_out"] is not None:
325
+ print("btreceiver: chime for a call")
326
+ st["chimes"].play(kind)
327
+ return
328
+ if st["out"] is None:
329
+ rate = sink.sample_rate or 44100
330
+ if not demo_mode:
331
+ st["rate"] = rate
332
+ open_out(rate, music=not demo_mode)
333
+ print("btreceiver: chime for a %s" % kind)
334
+ st["chimes"].play(kind)
335
+
336
+ def close_out():
337
+ src = st["levels"]
338
+ st["levels"] = None
339
+ if src is not None and hasattr(src, "close"):
340
+ src.close()
341
+ out = st["out"]
342
+ st["out"] = None
343
+ if out is not None:
344
+ out.stop()
345
+ out.close()
346
+ st["chimes"].close()
347
+
348
+ def route_call():
349
+ # The phone moves a call's audio to the board and back; the speaker
350
+ # follows it, and the microphones go with it. The music's output is
351
+ # closed first: the speaker plays one stream at one rate.
352
+ here = st["hf"].audio
353
+ if here and not st["talking"]:
354
+ close_out()
355
+ st["rate"] = 0
356
+ st["talking"] = True
357
+ if demo_mode:
358
+ return
359
+ rate = st["hf"].sample_rate
360
+ try:
361
+ out = _speaker(rate)
362
+ if out is None:
363
+ status.set_text("no audio out")
364
+ return
365
+ # A phone may bring the call's audio up while it still rings,
366
+ # and send nothing until it's answered: the chime goes over it.
367
+ out.play(st["chimes"].mix(rate, st["hf"]))
368
+ st["call_out"] = out
369
+ except Exception as e:
370
+ print("btreceiver: no call audio out:", e)
371
+ status.set_text("no audio out")
372
+ return
373
+ try:
374
+ mic = _microphone(rate)
375
+ except Exception as e: # the caller still plays; they can't hear us
376
+ print("btreceiver: no microphone for the call:", e)
377
+ mic = None
378
+ st["mic"] = mic
379
+ if mic is not None and not st["muted"]:
380
+ st["hf"].uplink(mic)
381
+ print("btreceiver: call audio on the board at %d Hz, microphone %s" % (rate, "on" if mic else "none"))
382
+ elif not here and st["talking"]:
383
+ drop_call()
384
+ route()
385
+
386
+ def drop_call():
387
+ st["talking"] = False
388
+ if demo_mode:
389
+ return
390
+ mic = st["mic"]
391
+ st["mic"] = None
392
+ if mic is not None:
393
+ st["hf"].uplink(None)
394
+ mic.close()
395
+ out = st["call_out"]
396
+ st["call_out"] = None
397
+ if out is not None:
398
+ out.stop()
399
+ out.close()
400
+ st["chimes"].close()
401
+ print("btreceiver: call audio off the board; sent", st["hf"].stats().get("sent"), "frames")
402
+
403
+ def show_phone():
404
+ if st["hf"].connected:
405
+ scr.show_phone(st["hf"].battery, st["hf"].signal, st["hf"].service)
406
+ else:
407
+ scr.show_phone(None, None, None)
408
+
409
+ def show_call():
410
+ call = st["hf"].call
411
+ if call == "active":
412
+ if st["answered"] is None:
413
+ st["answered"] = ticks_ms()
414
+ else:
415
+ st["answered"] = None
416
+ if call not in ("active", "held"):
417
+ st["muted"] = False
418
+ scr.show_call(call, st["hf"].caller, sink.peer_name, st["hf"].audio, st["muted"], demo_mode or st["mic"] is not None,
419
+ st["takes_audio"])
420
+ show_time()
421
+
422
+ def show_time():
423
+ if st["answered"] is not None:
424
+ scr.show_call_time(ticks_diff(ticks_ms(), st["answered"]))
425
+
426
+ def call_phone():
427
+ # The link follows the sink when the sink connects, but not to a
428
+ # phone that was connected before the unit started: call that one
429
+ # a few times, a while apart. A computer never answers.
430
+ hf = st["hf"]
431
+ if hf.connected or not sink.connected or not hasattr(hf, "connect"):
432
+ st["hf_tries"] = 0
433
+ st["hf_asked"] = ticks_ms()
434
+ return
435
+ if st["hf_tries"] >= HF_TRIES or ticks_diff(ticks_ms(), st["hf_asked"]) < HF_RETRY_MS:
436
+ return
437
+ st["hf_tries"] += 1
438
+ st["hf_asked"] = ticks_ms()
439
+ try:
440
+ hf.connect()
441
+ except OSError as e:
442
+ print("btreceiver: the phone's hands-free link:", e)
443
+
444
+ def follow_phone():
445
+ call_phone()
446
+ changed = st["hf"].changes()
447
+ if changed & (bits.CONNECTION | bits.AUDIO | bits.CALL):
448
+ route_call()
449
+ if changed & (bits.CONNECTION | bits.PHONE):
450
+ show_phone()
451
+ if changed & (bits.CONNECTION | bits.CALL | bits.AUDIO):
452
+ show_call()
453
+ else:
454
+ show_time()
455
+ ring()
456
+
457
+ def ring():
458
+ # A ringing call chimes now and every RING_MS until it's answered or
459
+ # gone, over the phone's own ringtone if it sends one: a phone that
460
+ # rings in band can still send silence.
461
+ hf = st["hf"]
462
+ if hf.call != "incoming":
463
+ st["rang"] = None
464
+ return
465
+ if st["rang"] is None or ticks_diff(ticks_ms(), st["rang"]) >= RING_MS:
466
+ st["rang"] = ticks_ms()
467
+ chime("call")
468
+
469
+ def call_messages():
470
+ # The message service follows the music's phone: asked for a few
471
+ # seconds after it connects, and again, a few times, if that fails.
472
+ # A computer has none, and is let be after MAP_TRIES.
473
+ msgs = st["msgs"]
474
+ now = ticks_ms()
475
+ if msgs.connected or not sink.connected:
476
+ st["map_tries"] = 0
477
+ st["map_asked"] = now
478
+ st["map_pending"] = False
479
+ return
480
+ if st["map_pending"] and ticks_diff(now, st["map_asked"]) < MAP_PENDING_MS:
481
+ return
482
+ if st["map_tries"] >= MAP_TRIES or ticks_diff(now, st["map_asked"]) < MAP_WAIT_MS:
483
+ return
484
+ st["map_tries"] += 1
485
+ st["map_asked"] = now
486
+ st["map_pending"] = True
487
+ try:
488
+ msgs.connect(timeout=0)
489
+ except OSError as e:
490
+ st["map_pending"] = False
491
+ print("btreceiver: the phone's messages:", e)
492
+
493
+ def follow_texts():
494
+ msgs = st["msgs"]
495
+ call_messages()
496
+ changed = msgs.changes()
497
+ if changed & bits.CONNECTION:
498
+ st["map_pending"] = False
499
+ if msgs.connected:
500
+ try:
501
+ msgs.notify()
502
+ print("btreceiver: the phone reports new texts")
503
+ except OSError as e:
504
+ print("btreceiver: the phone won't report new texts:", e)
505
+ if not (changed & bits.NOTIFY or msgs.events):
506
+ return
507
+ new = False
508
+ while True:
509
+ ev = msgs.event()
510
+ if ev is None:
511
+ break
512
+ # A text the phone sent shows up too, in "sent" or "outbox".
513
+ if ev.get("type") == "NewMessage" and ev.get("folder", "inbox").endswith("inbox"):
514
+ new = True
515
+ if new:
516
+ chime("text")
517
+
518
+ def show_cover():
519
+ try:
520
+ n = sink.cover_into(jpeg)
521
+ except ValueError as e: # larger than COVER_JPEG
522
+ print("btreceiver: cover:", e)
523
+ n = 0
524
+ if not n:
525
+ scr.show_cover(None, 0, 0)
526
+ return
527
+ try:
528
+ import jpegio
529
+
530
+ dec = jpegio.JpegDecoder()
531
+ w, h = dec.open(memoryview(jpeg)[:n])
532
+ scale = 0
533
+ while (w >> scale) > COVER_PX or (h >> scale) > COVER_PX:
534
+ scale += 1
535
+ if scale > 3: # the decoder scales down to an eighth at most
536
+ raise ValueError("a %d x %d cover is too large" % (w, h))
537
+ w, h = w >> scale, h >> scale
538
+ covers.reverse()
539
+ px = memoryview(covers[0])[: w * h * 2]
540
+ dec.decode(px, scale)
541
+ except Exception as e:
542
+ print("btreceiver: cover:", e)
543
+ scr.show_cover(None, 0, 0)
544
+ return
545
+ scr.show_cover(px, w, h)
546
+
547
+ def show_link():
548
+ # The sender's name heads the idle screen already. Its battery shows
549
+ # whenever it's connected; the stream's details once the rate is known.
550
+ playing = sink.connected and _said(sink.title)
551
+ link = sink.link() if sink.connected else None
552
+ if link is not None and not sink.sample_rate:
553
+ link["sample_rate"] = 0
554
+ scr.show_source(sink.peer_name if playing else "", link)
555
+
556
+ def show_modes():
557
+ # A firmware whose btclassic can't read them back has neither.
558
+ scr.show_modes(getattr(sink, "repeat", None), getattr(sink, "shuffle", None))
559
+
560
+ def show_all():
561
+ if not sink.connected:
562
+ scr.show_pairing(name, pin)
563
+ return
564
+ title = _said(sink.title)
565
+ if title:
566
+ scr.show_track(title, _said(sink.artist), _said(sink.album), sink.track_number, sink.track_count,
567
+ _said(sink.genre))
568
+ scr.show_status(sink.status)
569
+ elif _streaming(sink):
570
+ # Audio with no title, as a computer sends it: the playing view,
571
+ # named for the sender, so the spectrum shows what plays.
572
+ scr.show_track(sink.peer_name or "Unknown", "", "", None, None, "")
573
+ scr.show_status("playing")
574
+ scr.show_position(None, 0)
575
+ else:
576
+ scr.show_status(None)
577
+ scr.show_idle(sink.peer_name)
578
+ show_link()
579
+
580
+ settings_bit = getattr(bits, "SETTINGS", 0)
581
+
582
+ def open_phone():
583
+ # The calls setting on: the phone's hands-free link, which brings its
584
+ # battery, its signal and its calls.
585
+ hf = _open_handsfree(bt, sink, bits)
586
+ if hf is None:
587
+ return
588
+ st["hf"] = hf
589
+ # A firmware older than HandsFree.call_audio always takes the call's audio.
590
+ st["takes_audio"] = getattr(hf, "call_audio", True)
591
+ st["hf_tries"] = 0
592
+ st["hf_asked"] = ticks_ms()
593
+ follow_phone()
594
+ show_phone()
595
+ show_call()
596
+
597
+ def close_phone():
598
+ # The calls setting off: the link goes, and with it the card and
599
+ # the phone's own battery and signal. The player's battery stays.
600
+ hf = st["hf"]
601
+ if hf is None:
602
+ return
603
+ drop_call()
604
+ st["hf"] = None
605
+ hf.deinit()
606
+ st["answered"] = None
607
+ st["muted"] = False
608
+ scr.show_phone(None, None, None)
609
+ scr.show_call(None, "", "", False, False, False)
610
+ route()
611
+
612
+ def set_calls(on):
613
+ config["calls"] = on
614
+ _save_config(scope, config)
615
+ if on:
616
+ open_phone()
617
+ else:
618
+ close_phone()
619
+
620
+ def follow(t):
621
+ if st["hf"] is not None:
622
+ follow_phone()
623
+ if st["msgs"] is not None:
624
+ follow_texts()
625
+ changed = sink.changes()
626
+ if changed:
627
+ route()
628
+ if changed & (bits.CONNECTION | bits.TRACK | bits.PLAYING | bits.STREAM):
629
+ show_all()
630
+ elif changed & (bits.PEER | bits.STREAM | bits.FORMAT):
631
+ show_link()
632
+ if changed & (bits.CONNECTION | bits.COVER):
633
+ show_cover()
634
+ if changed & bits.VOLUME:
635
+ scr.show_volume(sink.volume)
636
+ if changed & (bits.CONNECTION | settings_bit):
637
+ show_modes()
638
+ if sink.connected and _said(sink.title):
639
+ scr.show_position(sink.position, sink.duration)
640
+
641
+ def bars(t):
642
+ src = st["levels"]
643
+ # The spectrum takes room from the cover only while there's a stream.
644
+ scr.set_bars(src is not None)
645
+ if scr.call_state is not None:
646
+ return # under the card
647
+ if src is None or not (sink.playing or _streaming(sink)):
648
+ scr.show_levels(_SILENT)
649
+ return
650
+ scr.show_levels(src.levels(ticks_diff(ticks_ms(), st["t0"]) / 1000))
651
+
652
+ def close():
653
+ hf = st["hf"]
654
+ if hf is not None:
655
+ drop_call()
656
+ close_out()
657
+ msgs = st["msgs"]
658
+ st["msgs"] = None
659
+ if msgs is not None:
660
+ msgs.deinit()
661
+ # The phone is let go when the app closes, and called back when it
662
+ # opens again. The radio goes back off if it was off.
663
+ if hf is not None:
664
+ hf.deinit()
665
+ sink.deinit()
666
+ if not was_on:
667
+ bt.active(False)
668
+ glyphs.forget()
669
+
670
+ scope.on_close(close)
671
+ show_all()
672
+ show_cover()
673
+ show_modes()
674
+ scr.show_volume(sink.volume)
675
+ route()
676
+ st["switch"] = calls_switch(scope, config["calls"], set_calls, scr.lay)
677
+ if config["calls"]:
678
+ open_phone()
679
+ if config["texts"]:
680
+ try:
681
+ st["msgs"] = _open_messages(bt, sink, bits)
682
+ except OSError as e: # the player and calls go on without it
683
+ print("btreceiver: no chime for texts:", e)
684
+ scope.every(UI_MS, follow)
685
+ scope.every(BARS_MS, bars)
686
+ if not sink.connected:
687
+ print("btreceiver: pair with %s and play" % name)
688
+
689
+
690
+ _SILENT = [0.0] * BANDS
@@ -0,0 +1 @@
1
+ {"name": "btreceiver", "title": "Bluetooth Receiver", "category": "Audio", "icon": "speaker", "color": "#1F5F8B"}