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.
- apps/__init__.py +5 -0
- apps/about/__init__.py +257 -0
- apps/about/app.json +1 -0
- apps/about/credits.py +12 -0
- apps/about/facts.py +398 -0
- apps/about/fonts/OFL.txt +93 -0
- apps/about/fonts/latin1_14.bin +0 -0
- apps/about/fonts/latin1_16.bin +0 -0
- apps/about/fonts/latin1_24.bin +0 -0
- apps/about/fonts/latin1_32.bin +0 -0
- apps/about/fonts/latin1_40.bin +0 -0
- apps/backline/__init__.py +58 -0
- apps/backline/app.json +1 -0
- apps/backline/app.py +475 -0
- apps/backline/art.py +717 -0
- apps/backline/ask.py +781 -0
- apps/backline/box.py +502 -0
- apps/backline/cast.py +137 -0
- apps/backline/desk/__init__.py +329 -0
- apps/backline/desk/editor.py +331 -0
- apps/backline/desk/grid.py +154 -0
- apps/backline/desk/look.py +169 -0
- apps/backline/desk/pedals.py +102 -0
- apps/backline/desk/perform.py +157 -0
- apps/backline/desk/prompt.py +210 -0
- apps/backline/desk/strip.py +159 -0
- apps/backline/desk_main.py +226 -0
- apps/backline/engine.py +622 -0
- apps/backline/floor.py +509 -0
- apps/backline/footswitch.py +119 -0
- apps/backline/glyphs.py +82 -0
- apps/backline/kits.py +428 -0
- apps/backline/midipedal.py +362 -0
- apps/backline/page_data.py +413 -0
- apps/backline/parts.py +145 -0
- apps/backline/pedal.py +107 -0
- apps/backline/remote.py +134 -0
- apps/backline/songs/ballad_68.json +1 -0
- apps/backline/songs/bossa.json +1 -0
- apps/backline/songs/country_train.json +1 -0
- apps/backline/songs/funk.json +1 -0
- apps/backline/songs/metal.json +1 -0
- apps/backline/songs/pop.json +1 -0
- apps/backline/songs/rock.json +1 -0
- apps/backline/songs/shuffle.json +1 -0
- apps/battery/__init__.py +101 -0
- apps/battery/app.json +1 -0
- apps/bit_world/act_deck.py +683 -0
- apps/bit_world/act_game.py +762 -0
- apps/bit_world/act_pet.py +1032 -0
- apps/bit_world/app.json +1 -0
- apps/bit_world/bit_output.py +45 -0
- apps/bit_world/bit_palette.py +503 -0
- apps/bit_world/bit_sound.py +431 -0
- apps/bit_world/bit_sprites.py +632 -0
- apps/bit_world/bit_world.py +534 -0
- apps/btreceiver/__init__.py +690 -0
- apps/btreceiver/app.json +1 -0
- apps/btreceiver/chime.py +155 -0
- apps/btreceiver/demo.py +529 -0
- apps/btreceiver/screen.py +633 -0
- apps/camera/__init__.py +316 -0
- apps/camera/app.json +1 -0
- apps/card/__init__.py +113 -0
- apps/card/app.json +1 -0
- apps/cast/__init__.py +631 -0
- apps/cast/app.json +1 -0
- apps/cast/receivers.py +193 -0
- apps/chess/__init__.py +18 -0
- apps/chess/app.json +1 -0
- apps/chess/app.py +922 -0
- apps/chess/art.py +323 -0
- apps/chess/ble.py +411 -0
- apps/chess/engine.py +925 -0
- apps/chess/game.py +327 -0
- apps/chess/net.py +261 -0
- apps/clock/__init__.py +38 -0
- apps/clock/app.json +1 -0
- apps/detect/__init__.py +214 -0
- apps/detect/app.json +1 -0
- apps/fmsynth/__init__.py +41 -0
- apps/fmsynth/algorithms.py +61 -0
- apps/fmsynth/app.json +1 -0
- apps/fmsynth/app.py +355 -0
- apps/fmsynth/editor.py +206 -0
- apps/fmsynth/engine.py +257 -0
- apps/fmsynth/meters.py +262 -0
- apps/fmsynth/midi.py +375 -0
- apps/fmsynth/panel_view.py +1071 -0
- apps/fmsynth/patches/fmsynth-01.syx +0 -0
- apps/fmsynth/settings.py +138 -0
- apps/fmsynth/voice.py +398 -0
- apps/gamepad/__init__.py +685 -0
- apps/gamepad/app.json +1 -0
- apps/gamepad/pad.py +94 -0
- apps/gamepad/watch.py +352 -0
- apps/hidden/__init__.py +72 -0
- apps/hidden/app.json +1 -0
- apps/home/__init__.py +483 -0
- apps/home/app.json +1 -0
- apps/home/main.py +36 -0
- apps/homeassistant/__init__.py +213 -0
- apps/homeassistant/api.py +104 -0
- apps/homeassistant/app.json +1 -0
- apps/huey/__init__.py +287 -0
- apps/huey/acting.py +184 -0
- apps/huey/actor.py +194 -0
- apps/huey/app.json +1 -0
- apps/huey/client.py +125 -0
- apps/huey/servers.py +121 -0
- apps/huey/settings.example.json +8 -0
- apps/huey/settings.py +97 -0
- apps/huey/turn.py +504 -0
- apps/huey/voice.py +217 -0
- apps/info/__init__.py +810 -0
- apps/info/app.json +1 -0
- apps/lora/__init__.py +62 -0
- apps/lora/app.json +1 -0
- apps/manifest.py +71 -0
- apps/medialink_baby_monitor/__init__.py +222 -0
- apps/medialink_baby_monitor/app.json +1 -0
- apps/medialink_doorbell/__init__.py +251 -0
- apps/medialink_doorbell/app.json +1 -0
- apps/medialink_hands_free/__init__.py +217 -0
- apps/medialink_hands_free/app.json +1 -0
- apps/medialink_surveillance_camera/__init__.py +258 -0
- apps/medialink_surveillance_camera/app.json +1 -0
- apps/medialink_video_doorbell/__init__.py +289 -0
- apps/medialink_video_doorbell/app.json +1 -0
- apps/medialink_videophone/__init__.py +273 -0
- apps/medialink_videophone/app.json +1 -0
- apps/medialink_walkie_talkie/__init__.py +228 -0
- apps/medialink_walkie_talkie/app.json +1 -0
- apps/midicontroller/__init__.py +774 -0
- apps/midicontroller/app.json +1 -0
- apps/midicontroller/links.py +421 -0
- apps/midicontroller/surface.py +343 -0
- apps/midiengine/__init__.py +977 -0
- apps/midiengine/app.json +1 -0
- apps/midiengine/banks.py +85 -0
- apps/midiengine/midiin.py +165 -0
- apps/midiengine/player.py +392 -0
- apps/midiengine/umidiparser.py +1413 -0
- apps/mp3/__init__.py +240 -0
- apps/mp3/app.json +1 -0
- apps/perch/__init__.py +119 -0
- apps/perch/app.json +1 -0
- apps/perch/huey.py +481 -0
- apps/perch/huey_props.py +386 -0
- apps/perch/huey_shift.py +42 -0
- apps/perch/huey_views.py +296 -0
- apps/perch/scene_bench.py +680 -0
- apps/perch/scene_coast.py +479 -0
- apps/perch/scene_desk.py +492 -0
- apps/perch/stage.py +1274 -0
- apps/perch/vec.py +366 -0
- apps/repl/__init__.py +325 -0
- apps/repl/app.json +1 -0
- apps/roku/__init__.py +156 -0
- apps/roku/app.json +1 -0
- apps/rokucam/__init__.py +362 -0
- apps/rokucam/app.json +1 -0
- apps/security/__init__.py +261 -0
- apps/security/app.json +1 -0
- apps/settings/__init__.py +221 -0
- apps/settings/app.json +1 -0
- apps/shell/__init__.py +33 -0
- apps/shell/app.json +1 -0
- apps/spotify/__init__.py +669 -0
- apps/spotify/app.json +1 -0
- apps/spotify/screen.py +82 -0
- apps/steps/__init__.py +58 -0
- apps/steps/app.json +1 -0
- apps/stompbox/__init__.py +31 -0
- apps/stompbox/app.json +1 -0
- apps/stompbox/app.py +668 -0
- apps/stompbox/boards.json +20 -0
- apps/stompbox/effects.py +241 -0
- apps/stompbox/engine.py +340 -0
- apps/stompbox/footswitch.py +331 -0
- apps/stompbox/inputs.py +449 -0
- apps/stompbox/meter.py +72 -0
- apps/stompbox/outputs.py +135 -0
- apps/stompbox/pedals.txt +45 -0
- apps/stompbox/presets.py +106 -0
- apps/stompbox/styles.py +135 -0
- apps/stompbox/ui.py +817 -0
- apps/stompbox/wavfile.py +73 -0
- apps/synthstation/__init__.py +20 -0
- apps/synthstation/app.json +1 -0
- apps/synthstation/audio.py +397 -0
- apps/synthstation/catalog.py +50 -0
- apps/synthstation/meters.py +136 -0
- apps/synthstation/midi.py +380 -0
- apps/synthstation/pads.py +177 -0
- apps/synthstation/parts.py +128 -0
- apps/synthstation/station.py +1069 -0
- apps/system/__init__.py +11 -0
- apps/system/app.json +1 -0
- apps/touchcal/__init__.py +324 -0
- apps/touchcal/app.json +1 -0
- apps/touchcal/fit.py +262 -0
- apps/wake/__init__.py +268 -0
- apps/wake/app.json +1 -0
- apps/wake/feed.py +155 -0
- apps/watch/__init__.py +355 -0
- apps/watch/app.json +1 -0
- apps/watch/faces.py +35 -0
- apps/watch/wheel.py +157 -0
- apps/weather/__init__.py +278 -0
- apps/weather/app.json +1 -0
- apps/weather/icons.py +172 -0
- apps/weather/sizing.py +71 -0
- apps/weather/zippad.py +172 -0
- omnipython_apps-0.1.4.dev8.dist-info/METADATA +33 -0
- omnipython_apps-0.1.4.dev8.dist-info/RECORD +218 -0
- omnipython_apps-0.1.4.dev8.dist-info/WHEEL +5 -0
- omnipython_apps-0.1.4.dev8.dist-info/top_level.txt +1 -0
apps/spotify/__init__.py
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""Spotify: the board is a Spotify Connect speaker (earful), and the screen
|
|
5
|
+
is its remote (say-so, Spotify's Web API).
|
|
6
|
+
|
|
7
|
+
Where the firmware has earful, the board is a speaker as well as the
|
|
8
|
+
remote; without it, the app is the remote alone, for whatever device
|
|
9
|
+
Spotify is playing on. That's decided when the app opens.
|
|
10
|
+
|
|
11
|
+
The screen looks like Bluetooth Receiver's: the cover on the left, beside
|
|
12
|
+
it the device Spotify plays on and the track, a progress line, round
|
|
13
|
+
transport buttons and a volume slider. While the board is the speaker, a
|
|
14
|
+
spectrum of what it plays sits under the cover; while Spotify plays
|
|
15
|
+
somewhere else, the cover takes that space. "Play here" moves playback to
|
|
16
|
+
the board. Every Web API call runs on ``scope.worker``, so a slow answer
|
|
17
|
+
never freezes the screen.
|
|
18
|
+
|
|
19
|
+
Its data folder (``/data/spotify`` on the board) holds:
|
|
20
|
+
|
|
21
|
+
``sayso.local.json`` and ``tokens.json``
|
|
22
|
+
say-so's Spotify app credentials and the account's tokens, made once
|
|
23
|
+
with say-so's own login on a computer. The tokens are read and
|
|
24
|
+
refreshed here, whatever path ``sayso.local.json`` names.
|
|
25
|
+
``earful.credentials``
|
|
26
|
+
The speaker's pairing, written here after a phone first plays to it.
|
|
27
|
+
Until a phone has picked the speaker once (Spotify's devices button),
|
|
28
|
+
Spotify refuses to start it from the Web API.
|
|
29
|
+
``config.json`` (optional)
|
|
30
|
+
``{"name": "Kitchen", "volume": 60}``: the speaker's name, and its
|
|
31
|
+
volume when it starts.
|
|
32
|
+
|
|
33
|
+
On a computer the speaker plays on the sound output chosen in the picker
|
|
34
|
+
(``audio.out``), and moves to another when it's chosen while the app runs.
|
|
35
|
+
A board's output follows that choice itself.
|
|
36
|
+
|
|
37
|
+
On close it stops the speaker (its threads, the pairing server and mDNS),
|
|
38
|
+
the audio pump stream and say-so's sockets; the worker drops what it had
|
|
39
|
+
queued. Wi-Fi stays joined: it's shared, like the display.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
import sys
|
|
43
|
+
|
|
44
|
+
from appkit import connections
|
|
45
|
+
from appkit import data as appdata
|
|
46
|
+
from appkit import net as appnet
|
|
47
|
+
from appkit.shell import is_round
|
|
48
|
+
from multimer import ticks_diff, ticks_ms
|
|
49
|
+
|
|
50
|
+
import spectrum
|
|
51
|
+
from controlkit import glyphs
|
|
52
|
+
from touchkit import net, settings, ui
|
|
53
|
+
from touchkit.clock import sleep_ms
|
|
54
|
+
|
|
55
|
+
from .screen import BANDS, Screen
|
|
56
|
+
|
|
57
|
+
# A desktop's speaker has a name of its own, so it never takes the board's place in Spotify's devices.
|
|
58
|
+
DEFAULTS = {"name": "PyDevices desktop" if appdata.desktop() else "PyDevices", "volume": 70}
|
|
59
|
+
CRED_FILE = "earful.credentials"
|
|
60
|
+
CONFIG = "sayso.local.json"
|
|
61
|
+
TOKENS = "tokens.json"
|
|
62
|
+
PUMP_MS = 10
|
|
63
|
+
POLL_MS = 5000
|
|
64
|
+
# While the board plays, the screen follows earful itself and Spotify is asked
|
|
65
|
+
# far less often: the worker's request and JSON parse share the interpreter
|
|
66
|
+
# with the screen and the spectrum, and stalled them on every poll.
|
|
67
|
+
POLL_HERE_MS = 20000
|
|
68
|
+
BARS_MS = 66 # how often the spectrum moves
|
|
69
|
+
RING_SECONDS = 4
|
|
70
|
+
SILENCE = bytes(4 * 44100 * PUMP_MS // 1000) # 10 ms of 44.1 kHz stereo 16-bit
|
|
71
|
+
ART = 150 # the least a cover is decoded to: half Spotify's 300 px one
|
|
72
|
+
|
|
73
|
+
state = None # the open app's state, for the console
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class _PumpPCM:
|
|
77
|
+
"""earful's view of an audiodev pump stream: earful calls write, space,
|
|
78
|
+
service and set_volume as real methods."""
|
|
79
|
+
|
|
80
|
+
def __init__(self, stream, transport):
|
|
81
|
+
self._stream = stream
|
|
82
|
+
self._transport = transport
|
|
83
|
+
|
|
84
|
+
def write(self, buf):
|
|
85
|
+
return self._stream.write(buf)
|
|
86
|
+
|
|
87
|
+
def space(self):
|
|
88
|
+
return self._stream.space()
|
|
89
|
+
|
|
90
|
+
def queued_size(self):
|
|
91
|
+
return self._stream.level()
|
|
92
|
+
|
|
93
|
+
def service(self):
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
def clear(self):
|
|
97
|
+
# earful calls this when it clears its own ring (pause, skip, seek):
|
|
98
|
+
# without it the pump plays out what it holds, seconds of it.
|
|
99
|
+
ring = self._stream.ring
|
|
100
|
+
if ring is not None:
|
|
101
|
+
ring.clear()
|
|
102
|
+
|
|
103
|
+
def set_volume(self, volume):
|
|
104
|
+
self._transport.set_volume(volume)
|
|
105
|
+
|
|
106
|
+
def open(self):
|
|
107
|
+
pass
|
|
108
|
+
|
|
109
|
+
def close(self):
|
|
110
|
+
self._stream.deinit()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _pump_pcm(fmt, device=None):
|
|
114
|
+
"""The speaker's PCM output. A computer names *device*, the sound output
|
|
115
|
+
chosen in the picker; a board's follows that choice itself and takes none."""
|
|
116
|
+
from audiodev import pump
|
|
117
|
+
from boarddev import pcm_out
|
|
118
|
+
|
|
119
|
+
out = transport = pcm_out(fmt, **({} if device is None else {"device": device}))
|
|
120
|
+
while transport is not None and getattr(transport, "wire", None) is None:
|
|
121
|
+
transport = getattr(transport, "_inner", None)
|
|
122
|
+
if transport is None:
|
|
123
|
+
# No I2S wire to pump: a desktop, whose audio out earful writes to itself.
|
|
124
|
+
out.open()
|
|
125
|
+
return out
|
|
126
|
+
driver = pump.BusioDriver(
|
|
127
|
+
transport.wire, fmt, power=getattr(transport, "audio_power", None), volume=transport.volume, transport=transport
|
|
128
|
+
)
|
|
129
|
+
frames = 256
|
|
130
|
+
stream = pump.attach_stream(fmt, driver=driver, frames=frames, capacity=max(2, fmt.rate * RING_SECONDS // frames))
|
|
131
|
+
return _PumpPCM(stream, transport)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _move_pcm(dev, old, fmt, device):
|
|
135
|
+
"""A computer's speaker moves to *device*: earful plays on a new output
|
|
136
|
+
from here, and the one it left is closed. Raises, leaving *old* in
|
|
137
|
+
place, if the device can't be opened."""
|
|
138
|
+
new = _pump_pcm(fmt, device)
|
|
139
|
+
try:
|
|
140
|
+
dev.attach(new)
|
|
141
|
+
except Exception:
|
|
142
|
+
new.close()
|
|
143
|
+
raise
|
|
144
|
+
old.close()
|
|
145
|
+
return new
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _read(path):
|
|
149
|
+
try:
|
|
150
|
+
with open(path, "rb") as f:
|
|
151
|
+
return f.read()
|
|
152
|
+
except OSError:
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _client(folder, dev):
|
|
157
|
+
"""say-so's Web API client from the data folder's files. Never starts a
|
|
158
|
+
browser login: with no usable token it raises.
|
|
159
|
+
|
|
160
|
+
Joined with this board's speaker when there is one (say-so's local
|
|
161
|
+
device): a command with no device_id goes straight to it instead of
|
|
162
|
+
through Spotify, so pass the other device's id when playback is
|
|
163
|
+
elsewhere."""
|
|
164
|
+
from sayso import auth as sa
|
|
165
|
+
from sayso.client import SpotifyClient
|
|
166
|
+
|
|
167
|
+
config = sa.load_config(folder + "/" + CONFIG)
|
|
168
|
+
client_id, client_secret = sa.credentials_from_config(config)
|
|
169
|
+
cache = sa.TokenCache(folder + "/" + TOKENS)
|
|
170
|
+
cached = cache.load()
|
|
171
|
+
refresh = cached.get("refresh_token")
|
|
172
|
+
if not refresh:
|
|
173
|
+
raise sa.SpotifyConfigError("no refresh token in %s/%s: log in with say-so on a computer first" % (folder, TOKENS))
|
|
174
|
+
auth = sa.AuthorizationCodeAuth(
|
|
175
|
+
client_id,
|
|
176
|
+
client_secret,
|
|
177
|
+
sa.redirect_uri_from_config(config, cached),
|
|
178
|
+
scope=sa.scopes_from_config(config, cached),
|
|
179
|
+
refresh_token=refresh,
|
|
180
|
+
token_cache=cache,
|
|
181
|
+
)
|
|
182
|
+
if dev is None:
|
|
183
|
+
return SpotifyClient(auth=auth)
|
|
184
|
+
return SpotifyClient(auth=auth, local_device=dev)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _speaker_available():
|
|
188
|
+
try:
|
|
189
|
+
import earful
|
|
190
|
+
except ImportError:
|
|
191
|
+
return False
|
|
192
|
+
return bool(earful.available())
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def main(scope):
|
|
196
|
+
global state
|
|
197
|
+
try:
|
|
198
|
+
appnet.sockets()
|
|
199
|
+
except ImportError as e:
|
|
200
|
+
# A browser page: sayso and earful reach Spotify over sockets.
|
|
201
|
+
ui.missing(scope, "no sockets", "Spotify reaches Spotify's servers over sockets, and this Python has none: %s. "
|
|
202
|
+
"Run it on a board with Wi-Fi or on a computer." % (e,))
|
|
203
|
+
return
|
|
204
|
+
from audiodev import AudioFormat
|
|
205
|
+
|
|
206
|
+
FORMAT = AudioFormat(44100, 2, 16)
|
|
207
|
+
conf = settings.config(scope, DEFAULTS)
|
|
208
|
+
NAME = conf["name"]
|
|
209
|
+
folder = scope.data_dir
|
|
210
|
+
cred_path = folder + "/" + CRED_FILE
|
|
211
|
+
root = scope.root
|
|
212
|
+
status = ui.status(scope)
|
|
213
|
+
W, H = scope.size
|
|
214
|
+
speaker = _speaker_available()
|
|
215
|
+
st = state = {
|
|
216
|
+
"phase": "wifi", "dev": None, "pcm": None, "client": None, "pb": None, "my_id": None,
|
|
217
|
+
"saved": _read(cred_path) if speaker else None, "err": None, "vol": conf["volume"], "ticks": 0,
|
|
218
|
+
"events": None, "active": False,
|
|
219
|
+
# what Spotify last said: playing, and (progress_ms, ticks_ms) to count on from
|
|
220
|
+
"playing": False, "base": None, "art_url": None, "speaker": speaker,
|
|
221
|
+
"host_audio": False, "device": None, "levels": None, "t0": ticks_ms(),
|
|
222
|
+
} # fmt: skip
|
|
223
|
+
w = scope.worker
|
|
224
|
+
on = {"play": lambda: toggle(), "next": lambda: skip(True), "previous": lambda: skip(False),
|
|
225
|
+
"volume": lambda v: volume(v), "here": lambda: play_here()} # fmt: skip
|
|
226
|
+
rect = getattr(scope, "rect", None) or (0, 0, W, H)
|
|
227
|
+
round_ = W == H and tuple(rect[:2]) == (0, 0) and is_round()
|
|
228
|
+
scr = st["screen"] = Screen(root, (W, H), on, speaker=speaker, round_=round_)
|
|
229
|
+
scr.show_volume(st["vol"])
|
|
230
|
+
# A cover is decoded at the size it shows, or to the next half of it.
|
|
231
|
+
art_px = max(ART, scr.lay.cover[2] * 3 // 2)
|
|
232
|
+
|
|
233
|
+
# -- the speaker (earful) ----------------------------------------------------
|
|
234
|
+
|
|
235
|
+
def moved(endpoints):
|
|
236
|
+
# Another sound output was chosen. A computer's speaker plays on it
|
|
237
|
+
# from here; a board's pump follows the choice itself.
|
|
238
|
+
st["device"] = connections.device(endpoints)
|
|
239
|
+
if st["dev"] is None or not st["host_audio"]:
|
|
240
|
+
return
|
|
241
|
+
try:
|
|
242
|
+
st["pcm"] = _move_pcm(st["dev"], st["pcm"], FORMAT, st["device"])
|
|
243
|
+
except (OSError, ImportError, ValueError, TypeError) as e:
|
|
244
|
+
status.set_text("Can't play on that output: %s" % (e,))
|
|
245
|
+
|
|
246
|
+
st["device"] = connections.device(scope.follow("audio.out", moved))
|
|
247
|
+
|
|
248
|
+
def start_speaker():
|
|
249
|
+
import earful
|
|
250
|
+
|
|
251
|
+
pcm = _pump_pcm(FORMAT, st["device"])
|
|
252
|
+
st["pcm"] = pcm
|
|
253
|
+
st["host_audio"] = not isinstance(pcm, _PumpPCM)
|
|
254
|
+
if st["saved"]:
|
|
255
|
+
earful.set_credentials(st["saved"])
|
|
256
|
+
dev = earful.Device(name=NAME, bitrate=160)
|
|
257
|
+
dev.volume = st["vol"]
|
|
258
|
+
dev.start()
|
|
259
|
+
dev.attach(pcm)
|
|
260
|
+
st["dev"] = dev
|
|
261
|
+
# earful's state events, where this firmware has them; without, the
|
|
262
|
+
# app polls Spotify as before.
|
|
263
|
+
st["events"] = getattr(dev, "events", None)
|
|
264
|
+
|
|
265
|
+
def pump(t):
|
|
266
|
+
dev = st["dev"]
|
|
267
|
+
if dev is None:
|
|
268
|
+
return
|
|
269
|
+
dev.service()
|
|
270
|
+
if st["host_audio"]:
|
|
271
|
+
# A host's queued sink stalls without a keepalive until playback starts.
|
|
272
|
+
pcm = st["pcm"]
|
|
273
|
+
if not dev.playing and pcm.queued_size() < 4 * len(SILENCE):
|
|
274
|
+
pcm.write(SILENCE)
|
|
275
|
+
pcm.service()
|
|
276
|
+
events = st["events"]
|
|
277
|
+
if events is not None:
|
|
278
|
+
batch = events() # an empty tuple, without allocating, when nothing changed
|
|
279
|
+
if batch:
|
|
280
|
+
follow(batch)
|
|
281
|
+
st["ticks"] += 1
|
|
282
|
+
if st["ticks"] % 100 == 0:
|
|
283
|
+
save_creds()
|
|
284
|
+
|
|
285
|
+
def save_creds():
|
|
286
|
+
# earful pairs in RAM; the app keeps it in its data folder. Rewritten
|
|
287
|
+
# only when it changed (a new pairing), so the flash sees one write.
|
|
288
|
+
import earful
|
|
289
|
+
|
|
290
|
+
if not earful.has_credentials():
|
|
291
|
+
return
|
|
292
|
+
blob = earful.credentials()
|
|
293
|
+
if blob and blob != st["saved"]:
|
|
294
|
+
try:
|
|
295
|
+
with open(cred_path, "wb") as f:
|
|
296
|
+
f.write(blob)
|
|
297
|
+
st["saved"] = blob
|
|
298
|
+
print("spotify: pairing saved")
|
|
299
|
+
except OSError as e:
|
|
300
|
+
print("spotify: pairing not saved:", e)
|
|
301
|
+
|
|
302
|
+
# -- the remote (say-so) ---------------------------------------------------------
|
|
303
|
+
|
|
304
|
+
def api(work, done=None, key=None):
|
|
305
|
+
def finished(value, error):
|
|
306
|
+
if error is not None:
|
|
307
|
+
st["err"] = error
|
|
308
|
+
status.set_text("Web API: %s" % (str(error)[:60],))
|
|
309
|
+
if done is not None:
|
|
310
|
+
done(value, error)
|
|
311
|
+
|
|
312
|
+
w.submit(work, finished, key=key)
|
|
313
|
+
|
|
314
|
+
def follow(batch):
|
|
315
|
+
# What earful told Spotify, at once: no poll needed to see a pause or a skip.
|
|
316
|
+
for kind, value in batch:
|
|
317
|
+
if kind == "active":
|
|
318
|
+
st["here"] = st["active"] = bool(value)
|
|
319
|
+
if not value:
|
|
320
|
+
poll() # moved elsewhere: ask Spotify where
|
|
321
|
+
show()
|
|
322
|
+
|
|
323
|
+
def poll(t=None):
|
|
324
|
+
if st["client"] is None or w.pending("poll"):
|
|
325
|
+
return
|
|
326
|
+
if t is not None and st["active"]:
|
|
327
|
+
return # this board is Spotify's active device and earful tells us what changes
|
|
328
|
+
if t is not None and playing_here():
|
|
329
|
+
now = ticks_ms()
|
|
330
|
+
if ticks_diff(now, st.get("polled", 0)) < POLL_HERE_MS:
|
|
331
|
+
return
|
|
332
|
+
st["polled"] = ticks_ms()
|
|
333
|
+
c = st["client"]
|
|
334
|
+
look_for_me = speaker and st["my_id"] is None
|
|
335
|
+
|
|
336
|
+
def work():
|
|
337
|
+
pb = c.current_playback()
|
|
338
|
+
if not look_for_me:
|
|
339
|
+
return pb, None # each call is 1-2 s from the board: skip what we know
|
|
340
|
+
my = None
|
|
341
|
+
try:
|
|
342
|
+
for d in c.devices():
|
|
343
|
+
if d.name == NAME and d.id: # say-so lists the joined speaker too, without an id
|
|
344
|
+
my = d.id
|
|
345
|
+
except Exception:
|
|
346
|
+
pass
|
|
347
|
+
return pb, my
|
|
348
|
+
|
|
349
|
+
def done(value, error):
|
|
350
|
+
if error is None:
|
|
351
|
+
pb, my = value
|
|
352
|
+
st["pb"] = pb
|
|
353
|
+
d = getattr(pb, "device", None)
|
|
354
|
+
if d is not None and d.name != NAME and st.get("here"):
|
|
355
|
+
st["here"] = False # moved elsewhere (a phone, say)
|
|
356
|
+
status.set_text("")
|
|
357
|
+
st["playing"] = bool(pb is not None and pb.is_playing)
|
|
358
|
+
v = getattr(d, "volume_percent", None)
|
|
359
|
+
if v is not None and not playing_here() and ("vol_at" not in st or ticks_diff(ticks_ms(), st["vol_at"]) > POLL_MS):
|
|
360
|
+
st["vol"] = v # the other device's own volume
|
|
361
|
+
scr.show_volume(v)
|
|
362
|
+
st["base"] = ((pb.progress_ms or 0) if pb is not None else 0, ticks_ms())
|
|
363
|
+
if my:
|
|
364
|
+
st["my_id"] = my
|
|
365
|
+
show()
|
|
366
|
+
|
|
367
|
+
api(work, done, key="poll")
|
|
368
|
+
|
|
369
|
+
def shown_ms(dur):
|
|
370
|
+
# Between polls the clock counts on by itself.
|
|
371
|
+
base = st["base"]
|
|
372
|
+
if base is None:
|
|
373
|
+
return 0
|
|
374
|
+
pos, at = base
|
|
375
|
+
if st["playing"]:
|
|
376
|
+
pos += ticks_diff(ticks_ms(), at)
|
|
377
|
+
return min(pos, dur) if dur else pos
|
|
378
|
+
|
|
379
|
+
def target():
|
|
380
|
+
# None reaches this board's speaker directly; elsewhere, name the device.
|
|
381
|
+
if playing_here():
|
|
382
|
+
return None
|
|
383
|
+
d = getattr(st["pb"], "device", None)
|
|
384
|
+
return d.id if d is not None else None
|
|
385
|
+
|
|
386
|
+
# -- the cover ------------------------------------------------------------------
|
|
387
|
+
|
|
388
|
+
def art_url():
|
|
389
|
+
dev = st["dev"]
|
|
390
|
+
if playing_here() and dev.art:
|
|
391
|
+
# earful has the 640 px cover; the 300 px one is the same image
|
|
392
|
+
return dev.art.replace("ab67616d0000b273", "ab67616d00001e02")
|
|
393
|
+
album = getattr(getattr(st["pb"], "item", None), "album", None)
|
|
394
|
+
best = None
|
|
395
|
+
for im in getattr(album, "images", None) or ():
|
|
396
|
+
if best is None or abs((im.width or 0) - 300) < abs((best.width or 0) - 300):
|
|
397
|
+
best = im
|
|
398
|
+
return getattr(best, "url", None)
|
|
399
|
+
|
|
400
|
+
def want_art():
|
|
401
|
+
# Fetched afresh for every track, on the worker; nothing is cached.
|
|
402
|
+
url = art_url()
|
|
403
|
+
if url == st["art_url"]:
|
|
404
|
+
return
|
|
405
|
+
st["art_url"] = url
|
|
406
|
+
if not url:
|
|
407
|
+
scr.show_cover(None, 0, 0)
|
|
408
|
+
return
|
|
409
|
+
|
|
410
|
+
def work():
|
|
411
|
+
r = appnet.requests().get(url)
|
|
412
|
+
try:
|
|
413
|
+
data = r.content
|
|
414
|
+
finally:
|
|
415
|
+
r.close()
|
|
416
|
+
return (url,) + ui.decode_jpeg(data, art_px, art_px)
|
|
417
|
+
|
|
418
|
+
def done(value, error):
|
|
419
|
+
if error is not None:
|
|
420
|
+
print("spotify: cover:", error)
|
|
421
|
+
return
|
|
422
|
+
u, pixels, aw, ah = value
|
|
423
|
+
if u != st["art_url"]:
|
|
424
|
+
return # a later track's cover is on its way
|
|
425
|
+
scr.show_cover(pixels, aw, ah)
|
|
426
|
+
|
|
427
|
+
w.submit(work, done, key="art")
|
|
428
|
+
|
|
429
|
+
def show():
|
|
430
|
+
# Spotify's word on what plays where, also when it plays here: the
|
|
431
|
+
# speaker's own playing and position don't follow audio the pump plays.
|
|
432
|
+
pb = st["pb"]
|
|
433
|
+
dev = st["dev"]
|
|
434
|
+
playing = st["playing"]
|
|
435
|
+
here = playing_here()
|
|
436
|
+
album = meta = ""
|
|
437
|
+
if here and dev.title:
|
|
438
|
+
# earful knows the track, the position and whether it plays the
|
|
439
|
+
# moment they change; Spotify's answer comes a poll later.
|
|
440
|
+
title, artist = dev.title, dev.artist
|
|
441
|
+
album = getattr(dev, "album", "") or ""
|
|
442
|
+
dur = dev.duration or 0
|
|
443
|
+
pos = min(dev.position or 0, dur) if dur else (dev.position or 0)
|
|
444
|
+
playing = st["playing"] = bool(dev.playing)
|
|
445
|
+
where = NAME + " (this board)"
|
|
446
|
+
elif pb is not None and getattr(pb, "item", None) is not None:
|
|
447
|
+
item = pb.item
|
|
448
|
+
title = item.name
|
|
449
|
+
artist = ", ".join(a.name for a in (getattr(item, "artists", None) or ()))
|
|
450
|
+
album = getattr(getattr(item, "album", None), "name", None) or ""
|
|
451
|
+
number = getattr(item, "track_number", None)
|
|
452
|
+
meta = "TRACK %d" % number if number else ""
|
|
453
|
+
dur = getattr(item, "duration_ms", 0) or 0
|
|
454
|
+
pos = shown_ms(dur)
|
|
455
|
+
d = getattr(pb, "device", None)
|
|
456
|
+
where = (d.name or "?") if d is not None else "?"
|
|
457
|
+
if speaker and where == NAME:
|
|
458
|
+
where += " (this board)"
|
|
459
|
+
elif dev is not None and dev.track:
|
|
460
|
+
title, artist = dev.title, dev.artist
|
|
461
|
+
dur = dev.duration or 0
|
|
462
|
+
pos = shown_ms(dur)
|
|
463
|
+
where = NAME + " (this board)"
|
|
464
|
+
else:
|
|
465
|
+
title = None
|
|
466
|
+
where = None
|
|
467
|
+
# The spectrum shows while this board plays and has a tap on its audio.
|
|
468
|
+
scr.set_bars(here and st["levels"] is not None)
|
|
469
|
+
if title is None:
|
|
470
|
+
scr.show_nothing("Play something in Spotify." + ("" if st["dev"] is None else " Or tap Play here."))
|
|
471
|
+
else:
|
|
472
|
+
scr.show_track(title, artist, album, meta, playing)
|
|
473
|
+
scr.show_position(pos, dur)
|
|
474
|
+
scr.show_device(where or ("" if st["client"] is None else "No device playing"), speaker and not here)
|
|
475
|
+
want_art()
|
|
476
|
+
|
|
477
|
+
def playing_here():
|
|
478
|
+
dev = st["dev"]
|
|
479
|
+
if dev is None or not dev.track:
|
|
480
|
+
return False
|
|
481
|
+
if st.get("here"): # moved here, Spotify's next answer not in yet
|
|
482
|
+
return True
|
|
483
|
+
return st["pb"] is not None and getattr(getattr(st["pb"], "device", None), "name", None) == NAME
|
|
484
|
+
|
|
485
|
+
def toggle():
|
|
486
|
+
c = st["client"]
|
|
487
|
+
if c is None:
|
|
488
|
+
return
|
|
489
|
+
playing = st["playing"]
|
|
490
|
+
dur = getattr(getattr(st["pb"], "item", None), "duration_ms", 0) or 0
|
|
491
|
+
st["base"] = (shown_ms(dur), ticks_ms())
|
|
492
|
+
st["playing"] = not playing # at once; the next poll corrects it
|
|
493
|
+
show()
|
|
494
|
+
dev_id = target()
|
|
495
|
+
api((lambda: c.pause(dev_id)) if playing else (lambda: c.play(dev_id)), lambda v, e: poll(), key="toggle")
|
|
496
|
+
|
|
497
|
+
def skip(forward):
|
|
498
|
+
c = st["client"]
|
|
499
|
+
if c is not None:
|
|
500
|
+
dev_id = target()
|
|
501
|
+
api(
|
|
502
|
+
(lambda: c.next_track(dev_id)) if forward else (lambda: c.previous_track(dev_id)),
|
|
503
|
+
lambda v, e: poll(),
|
|
504
|
+
key="skip",
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
def volume(v):
|
|
508
|
+
# The slider, 0 to 100. While it moves, a newer value replaces one
|
|
509
|
+
# still waiting for the worker.
|
|
510
|
+
st["vol"] = v
|
|
511
|
+
st["vol_at"] = ticks_ms()
|
|
512
|
+
c = st["client"]
|
|
513
|
+
dev = st["dev"]
|
|
514
|
+
if dev is not None and playing_here():
|
|
515
|
+
dev.volume = st["vol"] # the board's own: no round trip
|
|
516
|
+
elif c is not None:
|
|
517
|
+
v = st["vol"]
|
|
518
|
+
dev_id = target()
|
|
519
|
+
api(lambda: c.volume(v, dev_id), key="volume")
|
|
520
|
+
|
|
521
|
+
def play_here():
|
|
522
|
+
c = st["client"]
|
|
523
|
+
if c is None or st["dev"] is None:
|
|
524
|
+
return
|
|
525
|
+
status.set_text("moving playback here...")
|
|
526
|
+
|
|
527
|
+
def work():
|
|
528
|
+
my = st["my_id"]
|
|
529
|
+
if my is None:
|
|
530
|
+
for d in c.devices():
|
|
531
|
+
if d.name == NAME and d.id: # say-so lists the joined speaker too, without an id
|
|
532
|
+
my = d.id
|
|
533
|
+
if my is None:
|
|
534
|
+
raise OSError("Spotify doesn't list %s yet: pick it once on your phone" % NAME)
|
|
535
|
+
# Just after the speaker comes up the Web API answers 404 for a
|
|
536
|
+
# few seconds, though Spotify already has it.
|
|
537
|
+
for attempt in range(3):
|
|
538
|
+
try:
|
|
539
|
+
c.transfer_playback([my], play=True)
|
|
540
|
+
break
|
|
541
|
+
except Exception as e:
|
|
542
|
+
if attempt == 2 or "404" not in str(e):
|
|
543
|
+
raise
|
|
544
|
+
sleep_ms(1500)
|
|
545
|
+
return my
|
|
546
|
+
|
|
547
|
+
def done(value, error):
|
|
548
|
+
if error is None:
|
|
549
|
+
st["my_id"] = value
|
|
550
|
+
st["here"] = True
|
|
551
|
+
status.set_text("playing on %s" % NAME)
|
|
552
|
+
if st["dev"] is not None:
|
|
553
|
+
st["dev"].volume = st["vol"] # a transfer brings the phone's volume
|
|
554
|
+
poll()
|
|
555
|
+
|
|
556
|
+
api(work, done, key="here")
|
|
557
|
+
|
|
558
|
+
# -- start up, one step per tick --------------------------------------------------
|
|
559
|
+
|
|
560
|
+
def connect_client():
|
|
561
|
+
st["phase"] = "client"
|
|
562
|
+
dev = st["dev"]
|
|
563
|
+
|
|
564
|
+
def done(value, error):
|
|
565
|
+
st["phase"] = "ready"
|
|
566
|
+
if error is None:
|
|
567
|
+
st["client"] = value
|
|
568
|
+
poll()
|
|
569
|
+
else:
|
|
570
|
+
status.set_text("no remote: %s" % (str(error)[:40],))
|
|
571
|
+
|
|
572
|
+
api(lambda: _client(folder, dev), done, key="client")
|
|
573
|
+
|
|
574
|
+
def setup(t):
|
|
575
|
+
phase = st["phase"]
|
|
576
|
+
if phase == "wifi":
|
|
577
|
+
if net.up():
|
|
578
|
+
rssi = net.rssi()
|
|
579
|
+
status.set_text("Wi-Fi %s dBm" % rssi if rssi else "Wi-Fi up")
|
|
580
|
+
if speaker:
|
|
581
|
+
# The speaker stamps what it tells Spotify with the clock.
|
|
582
|
+
if appdata.desktop():
|
|
583
|
+
st["phase"] = "speaker" # the computer's clock is right already
|
|
584
|
+
else:
|
|
585
|
+
st["phase"] = "ntp"
|
|
586
|
+
api(net.ntp, lambda v, e: st.__setitem__("phase", "speaker"), key="ntp")
|
|
587
|
+
else:
|
|
588
|
+
status.set_text("remote only: this firmware has no speaker")
|
|
589
|
+
connect_client()
|
|
590
|
+
else:
|
|
591
|
+
status.set_text("joining Wi-Fi...")
|
|
592
|
+
return
|
|
593
|
+
if phase == "speaker":
|
|
594
|
+
try:
|
|
595
|
+
start_speaker()
|
|
596
|
+
except Exception as e:
|
|
597
|
+
status.set_text("speaker failed: %s" % (e,))
|
|
598
|
+
sys.print_exception(e)
|
|
599
|
+
st["phase"] = "failed"
|
|
600
|
+
return
|
|
601
|
+
status.set_text("speaker %s up" % NAME)
|
|
602
|
+
scope.every(PUMP_MS, pump)
|
|
603
|
+
if not st["host_audio"]:
|
|
604
|
+
# The spectrum reads what the pump plays; a computer's own
|
|
605
|
+
# audio out has no tap, and so no spectrum.
|
|
606
|
+
try:
|
|
607
|
+
st["levels"] = spectrum.pump_tap(44100, 2)(BANDS)
|
|
608
|
+
except (ImportError, ValueError, AttributeError, OSError) as e:
|
|
609
|
+
print("spotify: no spectrum:", e)
|
|
610
|
+
connect_client()
|
|
611
|
+
return
|
|
612
|
+
if phase in ("ready", "failed"):
|
|
613
|
+
t.deinit()
|
|
614
|
+
# "ntp" and "client" wait for the worker
|
|
615
|
+
|
|
616
|
+
def close():
|
|
617
|
+
src = st["levels"]
|
|
618
|
+
st["levels"] = None
|
|
619
|
+
if src is not None:
|
|
620
|
+
src.close()
|
|
621
|
+
dev = st["dev"]
|
|
622
|
+
st["dev"] = None
|
|
623
|
+
if dev is not None:
|
|
624
|
+
try:
|
|
625
|
+
save_creds()
|
|
626
|
+
except Exception:
|
|
627
|
+
pass
|
|
628
|
+
dev.stop() # its threads, the pairing server, mDNS
|
|
629
|
+
pcm = st["pcm"]
|
|
630
|
+
st["pcm"] = None
|
|
631
|
+
if pcm is not None:
|
|
632
|
+
pcm.close() # the last pump client: the pump stops and the codec powers down
|
|
633
|
+
st["client"] = None
|
|
634
|
+
dev = pcm = None
|
|
635
|
+
w.cancel()
|
|
636
|
+
try:
|
|
637
|
+
from sayso import transport
|
|
638
|
+
|
|
639
|
+
# say-so's kept-alive TLS sockets, unless the worker is mid-request
|
|
640
|
+
# (a request in flight finishes on its own and is dropped)
|
|
641
|
+
if not w.busy:
|
|
642
|
+
transport.close_connections()
|
|
643
|
+
except Exception as e:
|
|
644
|
+
print("spotify: sockets:", e)
|
|
645
|
+
glyphs.forget()
|
|
646
|
+
|
|
647
|
+
scope.on_close(close)
|
|
648
|
+
show()
|
|
649
|
+
scope.every(300, setup)
|
|
650
|
+
scope.every(POLL_MS, poll)
|
|
651
|
+
|
|
652
|
+
def clock(t):
|
|
653
|
+
dev = st["dev"]
|
|
654
|
+
if dev is not None and dev.track != st.get("track"):
|
|
655
|
+
st["track"] = dev.track
|
|
656
|
+
if playing_here():
|
|
657
|
+
st["base"] = (0, ticks_ms()) # a new track starts from 0:00
|
|
658
|
+
show()
|
|
659
|
+
elif st["playing"] or playing_here():
|
|
660
|
+
show()
|
|
661
|
+
|
|
662
|
+
scope.every(500, clock)
|
|
663
|
+
|
|
664
|
+
def bars(t):
|
|
665
|
+
src = st["levels"]
|
|
666
|
+
if src is not None and scr.bars_on:
|
|
667
|
+
scr.show_levels(src.levels(ticks_diff(ticks_ms(), st["t0"]) / 1000))
|
|
668
|
+
|
|
669
|
+
scope.every(BARS_MS, bars)
|
apps/spotify/app.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name": "spotify", "title": "Spotify", "category": "Audio", "icon": "queue_music", "color": "#1E8C4E"}
|