diff --git a/ROADMAP.md b/ROADMAP.md index c354a86..a9d685f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -38,6 +38,11 @@ keyboard sends it over MIDI, the way a hardware tone module does. - A tuner, and several effect slots with saved presets, so Stompbox is more than one airwindows effect at a time. +## Bluetooth Receiver + +- Calls' audio through the speaker and microphones on ESP32-S31 boards, once + that chip's Bluetooth controller carries a call's audio link reliably. + ## Clock - More faces on the clock, and a way to pick a face that's saved. diff --git a/apps/btreceiver/README.md b/apps/btreceiver/README.md index 6ddfbba..e28ea3f 100644 --- a/apps/btreceiver/README.md +++ b/apps/btreceiver/README.md @@ -7,6 +7,9 @@ speaker. Pair a phone or a computer with it and play anything. The screen shows the cover large, and beside it everything the sender says: title, artist, album, track number and count, genre, where the track is up to, and the codec and rate of the stream. A line the sender leaves empty isn't shown. +With **Phone calls and battery** turned on, the board is also the phone's +hands-free unit: its battery and signal show at the top, and its calls show +on the screen. ## On a board @@ -21,11 +24,11 @@ needs audiodsp's `audiometer`; without it the app plays with no spectrum. Made for an 800 x 480 screen. The cover and its buffers take about 350 KB, so it wants a board with PSRAM. -![Bluetooth Receiver on an ESP32-S31 board with a 4.3-inch screen: the track beside its cover (blurred here), the phone's battery at the top right, and shuffle and repeat both lit](docs/images/board.png) +![Bluetooth Receiver on an ESP32-S31 board with a 4.3-inch screen: the track beside its cover, the Phone calls and battery switch on at the top right, and the phone's signal bars and battery above the title](docs/images/board.png) -Here it runs on an ESP32-S31 board with a 4.3-inch screen. Shuffle and -repeat were turned on from the phone, and the buttons on the board follow -them. +Here it runs on an ESP32-S31 board with a 4.3-inch screen, with Phone calls +and battery turned on. The phone had no mobile service when this was +taken, so the status reads No service. ## Use it @@ -42,8 +45,21 @@ track, marked with a small 1. Each lights in the screen's colour while it's on, and follows the phone when you change it there. A phone that doesn't report them shows neither. -The phone's battery shows at the top right whenever the phone reports it, -amber when it runs low, and a weak signal is shown beside it. +The phone's battery shows at the top right whenever its player reports it, +amber when it runs low, and a weak Bluetooth link is noted beside it. + +## Phone calls and battery + +The switch at the top right, **Phone calls and battery**, is off until you +turn it on, on every board, and the board remembers it the next time the app +opens. Off, the board is a speaker and nothing more. + +On, the board also connects as the phone's hands-free unit, the way a car +kit does. The phone's battery and its signal show at the top right while it's +connected, the battery amber when it runs low, and its calls show on the +screen ([Calls](#calls) below). The phone gives these over its hands-free +link, so allow Calls for the board in the phone's Bluetooth settings. A +computer has no hands-free side, and shows neither. Closing the app lets the phone go. @@ -71,6 +87,33 @@ volume sits beside the play button. ![A long title on two lines, with the battery icon in amber at the top right and no shuffle or repeat](docs/images/long.png) +## Calls + +Calls come to the board with Phone calls and battery turned on. + +![An incoming call: a card over the player with a thin handset in rings, the caller's number large, and red decline and green answer rings](docs/images/incoming.png) + +A call shows a card over the player with the caller's number, and the phone +pauses its music. Answer it on the card and the call plays through the +board's speaker while the board's microphones go to the phone; decline it +and the card goes. + +![An answered call: the number, the call's time, and thin mute, use phone and red hang up rings](docs/images/call.png) + +While you talk, the card counts the call's time. Mute turns the board's +microphones off, Use phone takes the call back to the phone (and Use speaker +brings it back), and Hang up ends it. When the call ends the music plays +again where it was. The call's audio needs a board whose `pcm_in` records +while `audio_out` plays; on one that can't, you hear the caller but they +can't hear you, and the card says so. + +On an ESP32-S31 board the call's audio stays on the phone for now, because +that chip's Bluetooth can't yet carry it reliably. The card still shows the +caller, and answers, declines and hangs up; you talk on the phone, and the +card says so. The same goes for any board whose `HandsFree.call_audio` is +False, such as the Pico W. On an ESP32-S31 board with the setting on, a +call made through an internet calling app on the phone can reset the board. + ## On a computer On a computer, with no `btclassic`, the app plays a demo: a pretend phone @@ -82,7 +125,7 @@ PYTHONPATH=lib python -c "import appkit; appkit.run('btreceiver')" ``` `BTRECEIVER_DEMO` holds the demo in one state (`pairing`, `idle`, -`playing`, `paused`, `nocover` or `long`), and +`playing`, `paused`, `nocover`, `long`, `incoming` or `call`), and [`tools/shots.py`](tools/shots.py) saves a picture of each in [`docs/images`](docs/images), where this page's pictures live: diff --git a/apps/btreceiver/__init__.py b/apps/btreceiver/__init__.py index 09286ec..90ad296 100644 --- a/apps/btreceiver/__init__.py +++ b/apps/btreceiver/__init__.py @@ -12,19 +12,31 @@ and repeat show the player's modes and change them, when the sender reports them. A spectrum of what plays runs under the title. +With the "Phone calls and battery" switch in the header on (it's off until +you turn it on, and kept in ``config.json``), the board is also the phone's +hands-free unit, as a car kit is: the phone's battery and signal show at the +top right, and a call shows a card over the player with the caller's number, +to answer or decline. An answered call plays through the board's speaker and +sends its microphones to the phone, and the music comes back when the call +ends. On a board whose Bluetooth can't carry a +call's audio (``HandsFree.call_audio`` is False), the card answers and hangs +up, and you talk on the phone. + It needs a firmware with ``btclassic``. The audio goes out through the board's ``audio_out`` on the audio pump, so a redraw never holds it up. On a computer with no Bluetooth module the app plays a demo: a pretend phone that pairs, plays a few tracks and follows the buttons. """ +import json + from multimer import ticks_diff, ticks_ms from appkit import data as appdata -from touchkit import ui +from touchkit import settings, ui from . import glyphs -from .screen import BANDS, Screen +from .screen import BANDS, Screen, calls_switch UI_MS = 250 # how often the app reads the sink BARS_MS = 66 # how often the spectrum moves @@ -33,6 +45,11 @@ # A phone starting a stream sends about twice as fast for a second or two: # this rides that out. Half of it is the delay to the speaker. BUFFER_MS = 1000 +# Calling the phone's hands-free side when the setting is turned on: the +# first try waits this long after the unit starts, which a call made at once +# misses, and there are this many tries in all. +HF_RETRY_MS = 3000 +HF_TRIES = 3 state = None # the open app's state, for the console # What Android sends for a field it doesn't know, the title included when @@ -41,6 +58,11 @@ # A tap moves repeat on the way a phone's player does, and turns shuffle on # or off. "group" (a sender's own mode) goes back to off. NEXT_REPEAT = {"off": "all", "all": "single"} +#: The app's settings, kept in ``config.json`` in its data folder. ``calls`` +#: makes the board the phone's hands-free unit: the phone's battery and +#: signal from that link, and a card for its calls. Off, the board is a +#: speaker only, and the battery is the one the player reports. +DEFAULTS = {"calls": False} def _said(text): @@ -64,6 +86,41 @@ def _open_sink(): return bt, btclassic.AudioSink(bt, buffer_ms=BUFFER_MS), btclassic, was_on +def _open_handsfree(bt, sink, bits): + """The phone's hands-free link, for the calls setting: btclassic's + ``HandsFree``, or the demo's on a computer. None on a firmware whose + btclassic has no hands-free unit.""" + demo_unit = getattr(bits, "DemoHandsFree", None) + if demo_unit is not None: + return demo_unit(sink) + make = getattr(bits, "HandsFree", None) + if make is None: + print("btreceiver: this btclassic has no HandsFree: no battery, signal or calls") + return None + # Stereo frames, the shape the speaker plays. It follows the sink's phone. + return make(bt, channels=2) + + +def _load_config(scope): + """The app's settings: DEFAULTS, overridden by its ``config.json``.""" + try: + return settings.config(scope, DEFAULTS) + except (ValueError, AttributeError): # a scope with no data folder + return dict(DEFAULTS) + + +def _save_config(scope, config): + """Keep *config* in the app's ``config.json``: only what differs from + DEFAULTS.""" + changed = {k: v for k, v in config.items() if DEFAULTS.get(k) != v} + try: + path = appdata.join(scope.data_dir, "config.json") + with open(path, "w") as f: + f.write(json.dumps(changed)) + except (OSError, ValueError, AttributeError) as e: + print("btreceiver: couldn't save the settings:", e) + + def _speaker(rate): """The board's ``audio_out`` at *rate*, or None where there's none.""" try: @@ -77,6 +134,22 @@ def _speaker(rate): return make(AudioFormat(rate, 2, 16)) +def _microphone(rate): + """The board's microphones, open, as one 16-bit channel at *rate*, for + a call. None on a board with no ``pcm_in``.""" + try: + import board_peripherals as bp + from audiodev import AudioFormat + except ImportError: + return None + make = getattr(bp, "pcm_in", None) + if make is None: + return None + mic = make(AudioFormat(rate, 1, 16)) + mic.open() + return mic + + def _levels(out, demo_mode): """A source of BANDS levels, 0 to 1, for what *out* plays, or None.""" try: @@ -100,6 +173,7 @@ def main(scope): "Bluetooth Receiver needs a firmware with btclassic, the Bluetooth Classic module.") return bt, sink, bits, was_on = opened + config = _load_config(scope) demo_mode = not hasattr(sink, "readinto") name = bt.config("name") try: @@ -131,17 +205,42 @@ def repeat(): def shuffle(): setting("shuffle", "all" if getattr(sink, "shuffle", None) == "off" else "off") + def answer(): + st["hf"].answer() + + def hangup(): + st["hf"].hangup() + + def mute(): + st["muted"] = not st["muted"] + if st["mic"] is not None: + st["hf"].uplink(None if st["muted"] else st["mic"]) + show_call() + + def route_audio(): + # The phone says when the audio has moved; the AUDIO bit follows. + if st["hf"].audio: + st["hf"].disconnect_audio() + else: + st["hf"].connect_audio() + on = {"play": toggle, "next": sink.next, "previous": sink.previous, "seek": sink.seek, "volume": volume, - "repeat": repeat, "shuffle": shuffle} + "repeat": repeat, "shuffle": shuffle, "answer": answer, "hangup": hangup, "mute": mute, + "route": route_audio} scr = Screen(scope.root, scope.size, on) - st = state = {"sink": sink, "out": None, "rate": 0, "levels": None, "screen": scr, "t0": ticks_ms()} + st = state = {"sink": sink, "hf": None, "out": None, "rate": 0, "levels": None, "screen": scr, "t0": ticks_ms(), + "call_out": None, "mic": None, "muted": False, "talking": False, "answered": None, + "takes_audio": True, "config": config} jpeg = bytearray(COVER_JPEG) # Covers decode into two buffers made once, taking turns, so LVGL never # shows the one being written and a new cover makes no garbage. covers = [bytearray(COVER_PX * COVER_PX * 2) for _ in range(2)] def route(): - # Open the speaker at the stream's rate, and again if it changes. + # Open the speaker at the stream's rate, and again if it changes. A + # call's audio has the speaker until it ends. + if st["talking"]: + return rate = sink.sample_rate if not rate or rate == st["rate"]: return @@ -174,6 +273,111 @@ def close_out(): out.stop() out.close() + def route_call(): + # The phone moves a call's audio to the board and back; the speaker + # follows it, and the microphones go with it. The music's output is + # closed first: the speaker plays one stream at one rate. + here = st["hf"].audio + if here and not st["talking"]: + close_out() + st["rate"] = 0 + st["talking"] = True + if demo_mode: + return + rate = st["hf"].sample_rate + try: + out = _speaker(rate) + if out is None: + status.set_text("no audio out") + return + out.play(st["hf"]) + st["call_out"] = out + except Exception as e: + print("btreceiver: no call audio out:", e) + status.set_text("no audio out") + return + try: + mic = _microphone(rate) + except Exception as e: # the caller still plays; they can't hear us + print("btreceiver: no microphone for the call:", e) + mic = None + st["mic"] = mic + if mic is not None and not st["muted"]: + st["hf"].uplink(mic) + print("btreceiver: call audio on the board at %d Hz, microphone %s" % (rate, "on" if mic else "none")) + elif not here and st["talking"]: + drop_call() + route() + + def drop_call(): + st["talking"] = False + if demo_mode: + return + mic = st["mic"] + st["mic"] = None + if mic is not None: + st["hf"].uplink(None) + mic.close() + out = st["call_out"] + st["call_out"] = None + if out is not None: + out.stop() + out.close() + print("btreceiver: call audio off the board; sent", st["hf"].stats().get("sent"), "frames") + + def show_phone(): + if st["hf"].connected: + scr.show_phone(st["hf"].battery, st["hf"].signal, st["hf"].service) + else: + scr.show_phone(None, None, None) + + def show_call(): + call = st["hf"].call + if call == "active": + if st["answered"] is None: + st["answered"] = ticks_ms() + else: + st["answered"] = None + if call not in ("active", "held"): + st["muted"] = False + scr.show_call(call, st["hf"].caller, sink.peer_name, st["hf"].audio, st["muted"], demo_mode or st["mic"] is not None, + st["takes_audio"]) + show_time() + + def show_time(): + if st["answered"] is not None: + scr.show_call_time(ticks_diff(ticks_ms(), st["answered"])) + + def call_phone(): + # The link follows the sink when the sink connects, but not to a + # phone that was connected before the unit started: call that one + # a few times, a while apart. A computer never answers. + hf = st["hf"] + if hf.connected or not sink.connected or not hasattr(hf, "connect"): + st["hf_tries"] = 0 + st["hf_asked"] = ticks_ms() + return + if st["hf_tries"] >= HF_TRIES or ticks_diff(ticks_ms(), st["hf_asked"]) < HF_RETRY_MS: + return + st["hf_tries"] += 1 + st["hf_asked"] = ticks_ms() + try: + hf.connect() + except OSError as e: + print("btreceiver: the phone's hands-free link:", e) + + def follow_phone(): + call_phone() + changed = st["hf"].changes() + if changed & (bits.CONNECTION | bits.AUDIO | bits.CALL): + route_call() + if changed & (bits.CONNECTION | bits.PHONE): + show_phone() + if changed & (bits.CONNECTION | bits.CALL | bits.AUDIO): + show_call() + else: + show_time() + def show_cover(): try: n = sink.cover_into(jpeg) @@ -232,7 +436,47 @@ def show_all(): settings_bit = getattr(bits, "SETTINGS", 0) + def open_phone(): + # The calls setting on: the phone's hands-free link, which brings its + # battery, its signal and its calls. + hf = _open_handsfree(bt, sink, bits) + if hf is None: + return + st["hf"] = hf + # A firmware older than HandsFree.call_audio always takes the call's audio. + st["takes_audio"] = getattr(hf, "call_audio", True) + st["hf_tries"] = 0 + st["hf_asked"] = ticks_ms() + follow_phone() + show_phone() + show_call() + + def close_phone(): + # The calls setting off: the link goes, and with it the card and + # the phone's own battery and signal. The player's battery stays. + hf = st["hf"] + if hf is None: + return + drop_call() + st["hf"] = None + hf.deinit() + st["answered"] = None + st["muted"] = False + scr.show_phone(None, None, None) + scr.show_call(None, "", "", False, False, False) + route() + + def set_calls(on): + config["calls"] = on + _save_config(scope, config) + if on: + open_phone() + else: + close_phone() + def follow(t): + if st["hf"] is not None: + follow_phone() changed = sink.changes() if changed: route() @@ -251,15 +495,22 @@ def follow(t): def bars(t): src = st["levels"] + if scr.call_state is not None: + return # under the card if src is None or not sink.playing: scr.show_levels(_SILENT) return scr.show_levels(src.levels(ticks_diff(ticks_ms(), st["t0"]) / 1000)) def close(): + hf = st["hf"] + if hf is not None: + drop_call() close_out() # The phone is let go when the app closes, and called back when it # opens again. The radio goes back off if it was off. + if hf is not None: + hf.deinit() sink.deinit() if not was_on: bt.active(False) @@ -271,6 +522,9 @@ def close(): show_modes() scr.show_volume(sink.volume) route() + st["switch"] = calls_switch(scope, config["calls"], set_calls) + if config["calls"]: + open_phone() scope.every(UI_MS, follow) scope.every(BARS_MS, bars) if not sink.connected: diff --git a/apps/btreceiver/demo.py b/apps/btreceiver/demo.py index 959ad1e..bca3917 100644 --- a/apps/btreceiver/demo.py +++ b/apps/btreceiver/demo.py @@ -8,12 +8,15 @@ the app opens, plays a short list of made-up tracks, moves their position along and follows play, pause, next, previous, volume, repeat and shuffle. Its covers are drawn by svgio and made into JPEGs by jpegio, so the app decodes them the -way it decodes a phone's. +way it decodes a phone's. `DemoHandsFree` answers like +``btclassic.HandsFree``: the phone's battery and signal, and its calls. ``BTRECEIVER_DEMO`` holds it in one state, for screenshots: ``pairing``, -``idle``, ``playing``, ``paused``, ``nocover`` (a podcast with no cover) -or ``long`` (a long title, with every line filled in). Without it the demo runs -through pairing, connecting and playing on its own. +``idle``, ``playing``, ``paused``, ``nocover`` (a podcast with no cover, from +a sender with no hands-free link), ``long`` (a long title, with every line +filled in, and a low battery), ``incoming`` (a call ringing) or ``call`` (a +call answered on the board). Without it the demo runs through pairing, +connecting and playing on its own. """ import os @@ -29,6 +32,9 @@ PEER = 128 COVER = 256 SETTINGS = 1 << 26 +PHONE = 512 +CALL = 1024 +AUDIO = 2048 PAIR_MS = 4000 # how long the demo waits to be paired, from the app opening PLAY_MS = 2500 # and then before it plays @@ -140,7 +146,7 @@ def __init__(self, state=None): "long": (None, None)}.get(self.state, ("off", "off")) self._clear_track() st = self.state - if st in ("idle", "playing", "paused", "nocover", "long"): + if st in ("idle", "playing", "paused", "nocover", "long", "incoming", "call"): self._connect() if st != "idle": self._load({"nocover": 3, "long": 2}.get(st, 0)) @@ -321,3 +327,118 @@ def _cover(self): if c is None: c = self._covers[self._index] = cover_jpeg(spec) return c + + +# The phone's battery and signal, 0 to 5, in each held state. A sender with no +# hands-free link, such as a computer, reports neither. +_PHONE = {"idle": (3, 4), "playing": (4, 3), "paused": (5, 4), "long": (1, 1), "incoming": (4, 3), "call": (4, 3)} +CALLER = "+1 206 555 0143" + + +class DemoHandsFree: + """A pretend ``btclassic.HandsFree`` that follows *sink*'s phone. + + It links when the sink connects, reports a battery and a signal, and in + the ``incoming`` and ``call`` states has a call. The phone pauses its + music for a call and plays it again after, as a real one does. + """ + + def __init__(self, sink, state=None, call_audio=True): + self.sink = sink + # False is a board whose Bluetooth can't carry a call's audio: the + # call stays on the phone. + self.call_audio = call_audio + self.state = state if state is not None else sink.state + self._bits = 0 + self.connected = False + self.peer = None + self.battery = None + self.signal = None + self.service = None + self.operator = "" + self.call = None + self.caller = "" + self.audio = False + self.sample_rate = 0 + self.mic = None # what uplink() was last given + self._resume = False + self._followed = False # the sink's connection, as last seen + if self.state == "incoming": + self._follow() + self._ring() + elif self.state == "call": + self._follow() + self._ring() + self.answer() + + def changes(self): + self._follow() + bits, self._bits = self._bits, 0 + return bits + + def answer(self): + if self.call == "incoming": + self.call = "active" + self._audio(True) + self._bits |= CALL + + def hangup(self): + if self.call in ("incoming", "dialing", "alerting", "active", "held"): + self.call = "idle" + self._audio(False) + self._bits |= CALL + if self._resume: + self._resume = False + self.sink.play() + + def connect_audio(self): + if not self.call_audio: + raise OSError("this board doesn't take calls' audio") + if self.call in ("active", "dialing", "alerting"): + self._audio(True) + + def disconnect_audio(self): + self._audio(False) + + def uplink(self, mic): + self.mic = mic + + def stats(self): + return {"sent": 0, "unsent": 0} + + def deinit(self): + self._audio(False) + self.connected = False + self.call = None + + # -- the pretend phone ---------------------------------------------- + + def _follow(self): + # The hands-free link comes up and goes down with the music's. + if self.sink.connected == self._followed: + return + self._followed = self.sink.connected + # A computer has no hands-free side: the nocover state's sender. + self.connected = self._followed and self.state != "nocover" + level = _PHONE.get(self.state, (4, 3)) if self.connected else (None, None) + self.battery, self.signal = level + self.service = None if level[1] is None else True + self.operator = "Northwind" if self.connected else "" + self.peer = self.sink.peer if self.connected else None + self.call = "idle" if self.connected else None + self._bits |= CONNECTION | PHONE | CALL + + def _ring(self): + self.call = "incoming" + self.caller = CALLER + self._bits |= CALL + if self.sink.playing: + self._resume = True + self.sink.pause() + + def _audio(self, on): + if on == self.audio or (on and not self.call_audio): + return + self.audio = on + self.sample_rate = 16000 if on else 0 + self._bits |= AUDIO diff --git a/apps/btreceiver/docs/images/board.png b/apps/btreceiver/docs/images/board.png index 82ad0cd..1703b04 100644 Binary files a/apps/btreceiver/docs/images/board.png and b/apps/btreceiver/docs/images/board.png differ diff --git a/apps/btreceiver/docs/images/call.png b/apps/btreceiver/docs/images/call.png new file mode 100644 index 0000000..f7c7d9a Binary files /dev/null and b/apps/btreceiver/docs/images/call.png differ diff --git a/apps/btreceiver/docs/images/idle.png b/apps/btreceiver/docs/images/idle.png index 68bed2f..c929120 100644 Binary files a/apps/btreceiver/docs/images/idle.png and b/apps/btreceiver/docs/images/idle.png differ diff --git a/apps/btreceiver/docs/images/incoming.png b/apps/btreceiver/docs/images/incoming.png new file mode 100644 index 0000000..5b34c4a Binary files /dev/null and b/apps/btreceiver/docs/images/incoming.png differ diff --git a/apps/btreceiver/docs/images/long.png b/apps/btreceiver/docs/images/long.png index a05a314..ead182a 100644 Binary files a/apps/btreceiver/docs/images/long.png and b/apps/btreceiver/docs/images/long.png differ diff --git a/apps/btreceiver/docs/images/nocover.png b/apps/btreceiver/docs/images/nocover.png index fd7c71f..59ac6ba 100644 Binary files a/apps/btreceiver/docs/images/nocover.png and b/apps/btreceiver/docs/images/nocover.png differ diff --git a/apps/btreceiver/docs/images/pairing.png b/apps/btreceiver/docs/images/pairing.png index 4b0193f..ac18d6a 100644 Binary files a/apps/btreceiver/docs/images/pairing.png and b/apps/btreceiver/docs/images/pairing.png differ diff --git a/apps/btreceiver/docs/images/paused.png b/apps/btreceiver/docs/images/paused.png index 9262355..e653fd9 100644 Binary files a/apps/btreceiver/docs/images/paused.png and b/apps/btreceiver/docs/images/paused.png differ diff --git a/apps/btreceiver/docs/images/playing.png b/apps/btreceiver/docs/images/playing.png index f4eae59..1a5eaad 100644 Binary files a/apps/btreceiver/docs/images/playing.png and b/apps/btreceiver/docs/images/playing.png differ diff --git a/apps/btreceiver/glyphs.py b/apps/btreceiver/glyphs.py index 4274cd2..8908419 100644 --- a/apps/btreceiver/glyphs.py +++ b/apps/btreceiver/glyphs.py @@ -14,6 +14,10 @@ _HEAD = '' _LINE = 'fill="none" stroke="#fff" stroke-width="%s" stroke-linecap="round" stroke-linejoin="round"' +_HANDSET = ("M6.2 3.5h2.6l1.4 3.8-1.9 1.4a11.5 11.5 0 0 0 7 7l1.4-1.9 3.8 1.4v2.6c0 1.1-.9 2-2 2" + "A16.3 16.3 0 0 1 4.2 5.5c0-1.1.9-2 2-2z") +_MIC = ("M12 3.2c1.5 0 2.7 1.2 2.7 2.7v5.6c0 1.5-1.2 2.7-2.7 2.7s-2.7-1.2-2.7-2.7V5.9c0-1.5 1.2-2.7 2.7-2.7z" + "M6 11a6 6 0 0 0 12 0M12 17v3.6") SVG = { "play": '', @@ -27,6 +31,14 @@ "bluetooth": '', "volume": '' '', + # A call's buttons: answer, hang up, the microphone, and the phone that + # takes the call's audio back. + "handset": '', + "hangup": '', + "mic": '', + "mic_off": '', + "phone": '', # Drawn large, where a cover goes: a fine line at that size. "note": '' '', diff --git a/apps/btreceiver/screen.py b/apps/btreceiver/screen.py index 297dc8b..923997c 100644 --- a/apps/btreceiver/screen.py +++ b/apps/btreceiver/screen.py @@ -1,11 +1,12 @@ # SPDX-FileCopyrightText: 2026 Brad Barnett # # SPDX-License-Identifier: MIT -"""The receiver's screen: the cover, what's playing, and the transport. +"""The receiver's screen: the cover, what's playing, the transport, and calls. `Screen` builds every widget once and then only changes them: a new track sets some labels, a new cover sets one image, and the spectrum moves a few -bars. Nothing here talks to Bluetooth; the app hands it what the sink says. +bars. A call shows a card over the player until it ends. Nothing here talks +to Bluetooth; the app hands it what the sink and the hands-free unit say. """ import lvgl as lv @@ -22,14 +23,29 @@ LINE = 0x3A4458 # the thin outlines TEAL = 0x4DB6AC # the accent until a cover gives one AMBER = 0xFFB74D # a warning about the sender: its battery, its signal +GREEN = 0x66BB6A # answer +RED = 0xEF5350 # decline and hang up BANDS = 24 WEAK_DB = -10 # a link this far below the radio's ideal range is weak -# The sender's battery as AVRCP reports it, a state rather than a percentage, -# and the icon and colour for each. A sender that reports none shows none. -BATTERY = {"full": ("battery_full", MUTED), "normal": ("battery_5_bar", MUTED), - "warning": ("battery_2_bar", AMBER), "critical": ("battery_0_bar", AMBER), - "external": ("battery_charging_full", MUTED)} +# The phone's battery as its hands-free link reports it, 0 to 5, and the icon +# for each. At LOW_BATTERY or under it turns amber. A sender with no +# hands-free link, such as a computer, reports none. +BATTERY = ("battery_0_bar", "battery_1_bar", "battery_2_bar", "battery_4_bar", "battery_5_bar", "battery_full") +LOW_BATTERY = 1 +# The sender's battery as AVRCP reports it, a state rather than a level, and +# the icon and colour for each: what shows without the hands-free link's. A +# sender that reports neither shows none. +PLAYER_BATTERY = {"full": ("battery_full", MUTED), "normal": ("battery_5_bar", MUTED), + "warning": ("battery_2_bar", AMBER), "critical": ("battery_0_bar", AMBER), + "external": ("battery_charging_full", MUTED)} +SIGNAL_BARS = 4 # the phone's signal, 0 to 5, as this many bars +# What the card says over the caller for each of HandsFree's call states. +# The calls setting's label, beside its switch in the header. +CALLS_LABEL = "Phone calls and battery" +STATUS_W = 120 # the shell's status line, moved to the label's left +CALL_WORDS = {"incoming": "INCOMING CALL", "dialing": "CALLING", "alerting": "RINGING", "active": "ON A CALL", + "held": "ON HOLD"} def _font(*sizes): @@ -144,6 +160,7 @@ def _show(obj, on): SPECTRUM = (416, 246, 360, 30) PROGRESS = (416, 292, 360) TRANSPORT = (416, 326, 56, 72, 14) # x, y, small ring, play ring, gap +CALL_BUTTONS = (416, 300, 64, 80, 40) # x, y, small ring, main ring, gap VOLUME = (650, 362, 126) # x, middle y, width # Shuffle and repeat sit over the volume, which moves down to make room; the # two rows stay centred on the play button. @@ -157,7 +174,9 @@ class Screen: """Everything on the receiver's screen, in *root* (*size* pixels). *on* maps ``"play"``, ``"next"``, ``"previous"``, ``"seek"``, ``"repeat"``, - ``"shuffle"`` and ``"volume"`` to what the buttons and the slider do. + ``"shuffle"`` and ``"volume"`` to what the buttons and the slider do, and + ``"answer"``, ``"hangup"``, ``"mute"`` and ``"route"`` to the call card's + buttons. """ def __init__(self, root, size, on): @@ -168,6 +187,11 @@ def __init__(self, root, size, on): self._dragging = False self._title_text = None self._pos_text = None + self._link_notes = [] + self._phone_notes = [] + self._phone_battery = None + self._player_battery = None + self.call_state = None root.remove_flag(lv.obj.FLAG.SCROLLABLE) root.set_style_bg_opa(lv.OPA.COVER, 0) root.set_style_bg_grad_dir(lv.GRAD_DIR.VER, 0) @@ -183,6 +207,10 @@ def __init__(self, root, size, on): self._build_modes() x, y, w, h = SPECTRUM self.bars = SpectrumBars(root, x, y, w, h, BLACK, bands=BANDS, gap=w // BANDS * 3 // 5, color=TEAL) + self._build_call(size) + # The sender's line stays over the call card: the battery always shows. + for o in (self.src_mark, self.src_name, self.signal, self.battery, self.warn): + o.move_foreground() self.set_accent(TEAL) # -- building ------------------------------------------------------- @@ -258,8 +286,21 @@ def _build_text(self): self.battery.set_pos(cx + cw - 22, SOURCE_Y - 3) self.battery_state = None _show(self.battery, False) + # The phone's signal beside it: thin bars, filled up to the level. + sig = self.signal = _box(root, cx + cw - 56, SOURCE_Y + 3, 4 * SIGNAL_BARS + 3 * (SIGNAL_BARS - 1), 14) + self.signal_bars = [] + for i in range(SIGNAL_BARS): + h = 5 + i * 3 + bar = _box(sig, i * 7, 14 - h, 4, h) + bar.set_style_radius(1, 0) + bar.set_style_border_width(1, 0) + bar.set_style_border_color(lv.color_hex(MUTED), 0) + bar.set_style_bg_color(lv.color_hex(MUTED), 0) + self.signal_bars.append(bar) + self.signal_state = None + _show(sig, False) self.warn = _label(root, F_SMALL, AMBER) - self.warn.set_width(cw - 150 - 34) + self.warn.set_width(cw - 150 - 68) self.warn.set_style_text_align(lv.TEXT_ALIGN.RIGHT, 0) self.warn.set_pos(cx + 150, SOURCE_Y + 1) # What's playing, top down, each line only when it has something. @@ -473,20 +514,47 @@ def show_source(self, name, link): if rssi is not None and rssi <= WEAK_DB: notes.append("Weak signal") self.codec.set_text(" / ".join(parts)) - self.warn.set_text(" / ".join(notes)) - self.show_battery(link.get("battery") if link else None) - - def show_battery(self, state): - """The sender's battery icon for *state*, AVRCP's report, or none.""" + self._link_notes = notes + self._notes() + self._player_battery = link.get("battery") if link else None + self._show_battery() + + def show_phone(self, battery, signal, service): + """The phone's battery and signal from its hands-free link, each 0 to + 5 or None for none, and whether it has network service (None when it + hasn't said). Its battery shows in place of the player's.""" + self._phone_battery = battery + self._show_battery() + state = (signal, service) + if state != self.signal_state: + self.signal_state = state + _show(self.signal, signal is not None) + if signal is not None: + lit = 0 if service is False else (max(0, min(5, signal)) * SIGNAL_BARS + 2) // 5 + for i, bar in enumerate(self.signal_bars): + bar.set_style_bg_opa(lv.OPA.COVER if i < lit else lv.OPA.TRANSP, 0) + self._phone_notes = ["No service"] if service is False else [] + self._notes() + + def _notes(self): + self.warn.set_text(" / ".join(self._phone_notes + self._link_notes)) + + def _show_battery(self): + # The hands-free link's level, 0 to 5, else the player's state. + state = self._phone_battery if self._phone_battery is not None else self._player_battery if state == self.battery_state: return self.battery_state = state - kind = BATTERY.get(state) - if kind is None: + if state is None or (isinstance(state, str) and state not in PLAYER_BATTERY): _show(self.battery, False) return - self.battery.set_src(lvicons.dsc(kind[0], 24)) - self.battery.set_style_image_recolor(lv.color_hex(kind[1]), 0) + if isinstance(state, str): + icon, colour = PLAYER_BATTERY[state] + else: + level = max(0, min(5, state)) + icon, colour = BATTERY[level], AMBER if level <= LOW_BATTERY else MUTED + self.battery.set_src(lvicons.dsc(icon, 24)) + self.battery.set_style_image_recolor(lv.color_hex(colour), 0) _show(self.battery, True) def show_modes(self, repeat, shuffle): @@ -548,6 +616,65 @@ def show_cover(self, pixels, w, h): def show_levels(self, levels): self.bars.set_levels(levels) + def show_call(self, state, caller, phone, here, muted, mic, takes=True): + """The call card for HandsFree's call *state*, or none for ``None`` + and ``"idle"``. + + *caller* is the other side's number, *phone* the phone's name, *here* + whether the call's audio is on the board, *muted* whether the + microphone is off, and *mic* whether the board has one to send. + *takes* is False on a board that can't take a call's audio at all: + the card then answers and hangs up only, and the call stays on the + phone. + """ + on = state in CALL_WORDS + self.call_state = state if on else None + _show(self.card, on) + if not on: + return + ringing = state == "incoming" + self.call_word.set_text(CALL_WORDS[state]) + self.caller.set_text(caller or "Unknown number") + self.call_phone.set_text("on %s" % phone if phone else "") + _show(self.call_phone, bool(phone)) + if not takes: + note = "The call's audio stays on the phone" + elif ringing: + note = "Answer here to talk through this speaker" + elif not here: + note = "Talking on the phone" + elif not mic: + note = "This board can't send its microphones: the caller can't hear you" + elif muted: + note = "Microphones off" + else: + note = "Talking through this speaker and its microphones" + self.call_note.set_text(note) + _show(self.call_time, state == "active") + colour = GREEN if ringing else self.accent + for ring in self.call_rings: + ring.set_style_border_color(lv.color_hex(colour), 0) + glyphs.tint(self.call_mark, lv.color_hex(colour)) + self.call_word.set_style_text_color(lv.color_hex(colour), 0) + for b in (self.answer, self.decline): + _show(b.obj, ringing) + for b in (self.mute, self.route): + _show(b.obj, not ringing and takes) + _show(self.hang.obj, not ringing) + for lbl in self.ring_labels: + _show(lbl, ringing) + for i, lbl in enumerate(self.call_labels): + _show(lbl, not ringing and (takes or i == 2)) + self.mute.set_icon(glyphs.image("mic_off" if muted else "mic", self._icon_small)) + self.mute.set_enabled(here and mic) + self.call_labels[0].set_text("Unmute" if muted else "Mute") + self.route.set_icon(glyphs.image("phone" if here else "volume", self._icon_small)) + self.call_labels[1].set_text("Use phone" if here else "Use speaker") + + def show_call_time(self, ms): + """How long the call has been answered.""" + self.call_time.set_text(clock(ms)) + # -- inside --------------------------------------------------------- def _place_modes(self): @@ -568,6 +695,66 @@ def _paint_modes(self): _show(self.repeat_one, repeat == "single") self.repeat_one.set_style_text_color(lv.color_hex(self.accent), 0) + def _build_call(self, size): + """The call card: over everything but the sender's line, hidden + until a call.""" + on = self.on + card = self.card = _box(self.root, 0, 0, size[0], size[1]) + card.add_flag(lv.obj.FLAG.CLICKABLE) # nothing under it takes a touch + card.set_style_bg_opa(lv.OPA.COVER, 0) + card.set_style_bg_color(lv.color_hex(BG), 0) + x, y, s = COVER + rings = _box(card, x, y, s, s) + self.call_rings = [] + ring = PAIR_RING + for d, opa in ((ring, 50), (ring * 7 // 10, 90), (ring * 2 // 5, 255)): + c = _box(rings, (s - d) // 2, (s - d) // 2, d, d) + c.set_style_radius(lv.RADIUS_CIRCLE, 0) + c.set_style_border_width(1, 0) + c.set_style_border_opa(opa, 0) + self.call_rings.append(c) + self.call_mark = glyphs.tinted(rings, "handset", ring // 4, lv.color_hex(GREEN)) + self.call_mark.center() + col = _box(card, COL_X, TEXT_Y, COL_W, 230) + col.set_flex_flow(lv.FLEX_FLOW.COLUMN) + col.set_style_pad_row(8, 0) + self.call_word = _label(col, F_SMALL, GREEN, 2) + self.caller = _label(col, F_HUGE, TEXT) + self.caller.set_width(COL_W) + self.caller.set_long_mode(lv.label.LONG_MODE.DOTS) + self.call_phone = _label(col, F_BODY, SUB) + self.call_time = _label(col, F_BIG, MUTED, 1) + self.call_note = _label(col, F_SMALL, MUTED) + self.call_note.set_width(COL_W) + bx, by, small, big, gap = CALL_BUTTONS + self._icon_small = small * 3 // 8 + dy = (big - small) // 2 + + def button(x, y, d, icon, colour, fn): + return RingButton(card, x, y, d, BLACK, icon=glyphs.image(icon, d * 3 // 8), on_press=lambda b: fn(), + color=colour, ring=1 if d == small else 2, hit=max(d, 84)) + + def caption(x, d, text): + lbl = _label(card, F_SMALL, MUTED) + lbl.set_width(d + gap) + lbl.set_style_text_align(lv.TEXT_ALIGN.CENTER, 0) + lbl.set_pos(x - gap // 2, by + big + 10) + lbl.set_text(text) + return lbl + + # Ringing: decline, then answer. + self.decline = button(bx, by, big, "hangup", RED, lambda: on["hangup"]()) + self.answer = button(bx + big + gap * 2, by, big, "handset", GREEN, lambda: on["answer"]()) + self.ring_labels = [caption(bx, big, "Decline"), caption(bx + big + gap * 2, big, "Answer")] + # Answered: mute, where the audio goes, and hang up. + self.mute = button(bx, by + dy, small, "mic", 0xDCE3EC, lambda: on["mute"]()) + self.route = button(bx + small + gap, by + dy, small, "phone", 0xDCE3EC, lambda: on["route"]()) + hx = bx + 2 * (small + gap) + self.hang = button(hx, by, big, "hangup", RED, lambda: on["hangup"]()) + self.call_labels = [caption(bx, small, "Mute"), caption(bx + small + gap, small, "Use phone"), + caption(hx, big, "Hang up")] + _show(card, False) + def _pairing(self, on): _show(self.pair, on) _show(self.steps, on) @@ -614,3 +801,40 @@ def _playback(self, on, transport=None): _show(o, t) self._modes_on = t self._place_modes() + + +def calls_switch(scope, on, changed): + """The calls setting, a labelled switch at the right of the shell's + header (or the top right of the app's area without one), *on* or off. + *changed* gets the new setting each time it's flipped. The status line + moves to its left.""" + header = getattr(scope, "header", None) + parent = header or scope.root + sw = lv.switch(parent) + sw.set_size(48, 26) + if header is not None: + sw.align(lv.ALIGN.RIGHT_MID, -16, 0) + else: + sw.align(lv.ALIGN.TOP_RIGHT, -16, 8) + sw.set_style_bg_color(lv.color_hex(LINE), lv.PART.MAIN) + sw.set_style_bg_color(lv.color_hex(TEAL), lv.PART.INDICATOR | lv.STATE.CHECKED) + sw.set_style_bg_color(lv.color_hex(TEXT), lv.PART.KNOB) + sw.set_ext_click_area(12) + if on: + sw.add_state(lv.STATE.CHECKED) + lbl = _label(parent, F_SMALL, SUB) + lbl.set_text(CALLS_LABEL) + lbl.align_to(sw, lv.ALIGN.OUT_LEFT_MID, -10, 0) + status = getattr(scope, "status", None) + if status is not None: + # Its text changes after this: right-aligned in a fixed width, it + # stays clear of the label. + status.set_width(STATUS_W) + status.set_style_text_align(lv.TEXT_ALIGN.RIGHT, 0) + status.align_to(lbl, lv.ALIGN.OUT_LEFT_MID, -24, 0) + + def flipped(e): + changed(sw.has_state(lv.STATE.CHECKED)) + + sw.add_event_cb(flipped, lv.EVENT.VALUE_CHANGED, None) + return sw diff --git a/apps/btreceiver/tools/shots.py b/apps/btreceiver/tools/shots.py index cf25087..f03a9dd 100644 --- a/apps/btreceiver/tools/shots.py +++ b/apps/btreceiver/tools/shots.py @@ -7,17 +7,21 @@ Run it from the repository's root with CPython, lvgl, svgio, jpegio and Pillow. The states are the demo's: pairing, idle, playing, paused, -nocover and long. Each one opens the app under Home's shell, the way a board shows +nocover, long, incoming and call. Each one opens the app under Home's shell, the way a board shows it, waits for the demo to settle and saves ``OUT_DIR/.png``. No window opens. With no OUT_DIR the pictures replace the README's, in the app's ``docs/images``. """ +import json import os +import shutil import subprocess import sys +import tempfile -STATES = ("pairing", "idle", "playing", "paused", "nocover", "long") +STATES = ("pairing", "idle", "playing", "paused", "nocover", "long", "incoming", "call") +CALL_STATES = ("incoming", "call") # shown with the calls setting on WAIT_MS = 1500 DOCS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "docs", "images") @@ -28,8 +32,14 @@ def one(out, state, size): sys.path.insert(0, os.path.join(root, "lib")) sys.path.insert(0, root) w, h = size.split("x") + # The calls setting from a data folder of its own: on for the call + # states, off (the default) for the rest. + data = tempfile.mkdtemp() + os.makedirs(os.path.join(data, "btreceiver")) + with open(os.path.join(data, "btreceiver", "config.json"), "w") as f: + json.dump({"calls": state in CALL_STATES}, f) os.environ.update({"OMNIPYTHON_WIDTH": w, "OMNIPYTHON_HEIGHT": h, "OMNIPYTHON_SCALE": "1", - "SDL_VIDEODRIVER": "dummy", "BTRECEIVER_DEMO": state}) + "SDL_VIDEODRIVER": "dummy", "BTRECEIVER_DEMO": state, "APPKIT_DATA": data}) import lvgl as lv from PIL import Image @@ -74,6 +84,7 @@ def _poll(): path = os.path.join(out, state + ".png") img.save(path) print("saved", path, flush=True) + shutil.rmtree(data, ignore_errors=True) os._exit(0) timer = lv.timer_create(poll, 50, None) # kept: a dropped timer is deleted diff --git a/tests/btreceiver_contract.py b/tests/btreceiver_contract.py index c7221be..8a4c427 100644 --- a/tests/btreceiver_contract.py +++ b/tests/btreceiver_contract.py @@ -6,11 +6,12 @@ python tests/btreceiver_contract.py (from tests/, with lib/ and the root on the path) The app runs under the shell's header on an 800 x 480 display in memory, with -the demo's pretend phone in place of btclassic. Each state is checked through +the demo's pretend phone and hands-free unit in place of btclassic. Each state is checked through the screen's own widgets: what shows, what's hidden, and what the buttons and the slider send back. Prints PASS or FAIL per check, then ALL PASSED. """ +import os import sys sys.path.insert(0, "..") @@ -53,10 +54,28 @@ def check(name, ok, why=""): failures.append(name) +DATA = "_btreceiver_data" # the app's data folder, in tests/, removed at the end + + +def forget_settings(): + try: + os.remove(DATA + "/config.json") + except OSError: + pass + + +try: + os.mkdir(DATA) +except OSError: + pass +forget_settings() + + class Scope: """What the launcher's shell hands an app: a root under the header, timers.""" name = "btreceiver" + data_dir = DATA def __init__(self): self.scr = ui.plain(lv.obj(lv.screen_active())) @@ -88,16 +107,47 @@ def close(self): self.scr.delete() -def opened(state): - """The app open on a demo phone held in *state*: ``(scope, sink, screen)``.""" +opens = [] # each hands-free unit the app opened + + +def opened(state, call_audio=True, calls=True): + """The app open on a demo phone held in *state*: ``(scope, sink, screen)``. + *calls* is the calls setting, saved before it opens (None: left as it + is). The phone's hands-free unit is ``app.state["hf"]``, None with the + setting off; *call_audio* False is a board that can't take a call's + audio.""" sink = demo.DemoSink(state) + + def handsfree(bt, s, bits): + hf = demo.DemoHandsFree(sink, call_audio=call_audio) + opens.append(hf) + return hf + app._open_sink = lambda: (demo.DemoRadio("kitchen-speaker"), sink, demo, True) + app._open_handsfree = handsfree scope = Scope() + if calls is not None: + app._save_config(scope, {"calls": calls}) app.main(scope) scope.run() return scope, sink, app.state["screen"] +def colour(img): + return img.get_style_image_recolor(0).to_int() & 0xFFFFFF + + +def battery_is(scope, scr, hf, level): + hf.battery = level + hf._bits |= demo.PHONE + scope.run() + return scr.battery_state == level + + +def lit(scr): + return sum(1 for b in scr.signal_bars if b.get_style_bg_opa(0) == lv.OPA.COVER) + + def shown(obj): return not obj.has_flag(lv.obj.FLAG.HIDDEN) @@ -124,6 +174,8 @@ def tap(obj): not shown(scr.play.obj) and not shown(scr.vol) and not shown(scr.track) and not shown(scr.bars.obj)) check("pairing shows the rings, not the cover", shown(scr.pair) and not shown(scr.cover_box)) check("pairing hides shuffle and repeat", not shown(scr.shuffle) and not shown(scr.repeat)) +check("pairing shows no battery or signal: no phone yet", not shown(scr.battery) and not shown(scr.signal)) +check("pairing shows no call card", not shown(scr.card)) scope.close() # ---- Connected, nothing playing ----------------------------------------------- @@ -133,7 +185,7 @@ def tap(obj): check("idle says it's connected", text(scr.eyebrow) == "CONNECTED", text(scr.eyebrow)) check("idle doesn't repeat the phone's name above it", scr.src_name.get_text() == "", scr.src_name.get_text()) check("idle offers play, and no progress", shown(scr.play.obj) and not shown(scr.track)) -check("idle shows the battery too, here charging", shown(scr.battery) and scr.battery_state == "external", +check("idle shows the phone's battery from its hands-free link", shown(scr.battery) and scr.battery_state == 3, str(scr.battery_state)) sink.title = "Not Provided" # what Android sends with nothing playing sink._bits |= demo.TRACK @@ -153,14 +205,29 @@ def tap(obj): check("the track number, count and genre show", text(scr.meta) == "TRACK 3 OF 11 / SYNTHWAVE", text(scr.meta)) check("the status shows", text(scr.eyebrow) == "NOW PLAYING", text(scr.eyebrow)) check("the sender's name heads the column", scr.src_name.get_text() == "Galaxy S21", scr.src_name.get_text()) -check("the phone's battery shows when it reports one", shown(scr.battery) and scr.battery_state == "normal", +hf = app.state["hf"] +check("the phone's battery shows, at its level", shown(scr.battery) and scr.battery_state == 4, str(scr.battery_state)) -sink.battery = "warning" -sink._bits |= demo.PEER +check("a battery above 1 of 5 is grey", colour(scr.battery) == screenmod.MUTED, "%06x" % colour(scr.battery)) +for level in (5, 2): + check("a battery of %d of 5 shows and is grey" % level, + battery_is(scope, scr, hf, level) and shown(scr.battery) and colour(scr.battery) == screenmod.MUTED, + "%s %06x" % (scr.battery_state, colour(scr.battery))) +for level in (1, 0): + check("a battery of %d of 5 shows in amber" % level, + battery_is(scope, scr, hf, level) and shown(scr.battery) and colour(scr.battery) == screenmod.AMBER, + "%s %06x" % (scr.battery_state, colour(scr.battery))) +check("each battery level has its own icon", len(set(screenmod.BATTERY)) == 6) +check("the phone's signal shows as bars", shown(scr.signal) and lit(scr) == 2, str(lit(scr))) +hf.service = False +hf._bits |= demo.PHONE +scope.run() +check("no service empties the bars and says so", lit(scr) == 0 and scr.warn.get_text() == "No service", + scr.warn.get_text()) +hf.service = True +hf._bits |= demo.PHONE scope.run() -check("a low battery shows in amber", - scr.battery.get_style_image_recolor(0).to_int() & 0xFFFFFF == screenmod.AMBER, - "%06x" % (scr.battery.get_style_image_recolor(0).to_int() & 0xFFFFFF)) +check("service back, the bars and the note follow", lit(scr) == 2 and scr.warn.get_text() == "", scr.warn.get_text()) check("the codec, rate and channels show", text(scr.codec) == "SBC / 44.1 kHz / Joint stereo", text(scr.codec)) check("the position and length show", text(scr.t_pos) == "1:42" and text(scr.t_len) == "4:12", "%s %s" % (text(scr.t_pos), text(scr.t_len))) @@ -234,11 +301,140 @@ def volume_y(): scope, sink, scr = opened("nocover") check("with no cover, the placeholder shows", not shown(scr.art) and shown(scr.note)) -check("a phone that reports no battery shows none", not shown(scr.battery)) +check("a sender with no hands-free link shows no battery or signal", not shown(scr.battery) and not shown(scr.signal)) check("with no cover, the colour goes back to the default", scr.accent == screenmod.TEAL, "%06x" % scr.accent) check("a podcast's length shows", text(scr.t_len) == "45:12", text(scr.t_len)) check("a length over an hour reads h:mm:ss", screenmod.clock(3725000) == "1:02:05", screenmod.clock(3725000)) scope.close() +# ---- A call ------------------------------------------------------------------ + +scope, sink, scr = opened("incoming") +hf = app.state["hf"] +check("an incoming call shows the card", shown(scr.card) and text(scr.call_word) == "INCOMING CALL", text(scr.call_word)) +check("the card shows the caller's number", text(scr.caller) == demo.CALLER, text(scr.caller)) +check("the card names the phone", text(scr.call_phone) == "on Galaxy S21", text(scr.call_phone)) +check("ringing offers answer and decline, not hang up", + shown(scr.answer.obj) and shown(scr.decline.obj) and not shown(scr.hang.obj) and not shown(scr.mute.obj)) +check("the battery shows over the card", shown(scr.battery) and scr.battery_state == 4, str(scr.battery_state)) +check("the phone paused its music for the call", not sink.playing) +tap(scr.answer.obj) +scope.run() +check("answer answers the call", hf.call == "active" and text(scr.call_word) == "ON A CALL", text(scr.call_word)) +check("the call's audio comes to the board", hf.audio and app.state["talking"]) +check("an answered call offers mute, the phone and hang up", + shown(scr.hang.obj) and shown(scr.mute.obj) and shown(scr.route.obj) and not shown(scr.answer.obj)) +check("an answered call shows its time", (text(scr.call_time) or "").startswith("0:"), str(text(scr.call_time))) +tap(scr.mute.obj) +scope.run() +check("mute turns the microphones off", app.state["muted"] and scr.call_labels[0].get_text() == "Unmute", + scr.call_labels[0].get_text()) +tap(scr.mute.obj) +scope.run() +check("and on again", not app.state["muted"] and scr.call_labels[0].get_text() == "Mute") +tap(scr.route.obj) +scope.run() +check("use phone hands the call's audio back", not hf.audio and not app.state["talking"] + and text(scr.call_note) == "Talking on the phone", str(text(scr.call_note))) +check("with the audio on the phone, mute is off and the button offers the speaker", + not scr.mute.enabled and scr.call_labels[1].get_text() == "Use speaker", scr.call_labels[1].get_text()) +tap(scr.route.obj) +scope.run() +check("use speaker brings it back", hf.audio and app.state["talking"]) +tap(scr.hang.obj) +scope.run() +check("hang up ends the call and the card goes", hf.call == "idle" and not shown(scr.card)) +check("the music plays again after the call", sink.playing and not app.state["talking"]) +check("the player is back with its track", text(scr.title) == "Neon Tides" and text(scr.eyebrow) == "NOW PLAYING", + "%s %s" % (text(scr.title), text(scr.eyebrow))) +scope.close() + +scope, sink, scr = opened("incoming") +hf = app.state["hf"] +tap(scr.decline.obj) +scope.run() +check("decline rejects the call and the card goes", hf.call == "idle" and not shown(scr.card)) +check("the music plays again after a declined call", sink.playing) +scope.close() + +scope, sink, scr = opened("call") +hf = app.state["hf"] +check("a call answered on the board shows the card with its time", shown(scr.card) and text(scr.call_word) == "ON A CALL" + and text(scr.call_time) is not None) +scope.close() +check("closing the app during a call lets the hands-free link go", not hf.connected and not hf.audio) + +# ---- A call on a board that can't take its audio ------------------------------ + +scope, sink, scr = opened("incoming", call_audio=False) +hf = app.state["hf"] +check("without call audio, the card still rings with answer and decline", + shown(scr.card) and shown(scr.answer.obj) and shown(scr.decline.obj)) +check("without call audio, the card says the audio stays on the phone", + text(scr.call_note) == "The call's audio stays on the phone", str(text(scr.call_note))) +tap(scr.answer.obj) +scope.run() +check("without call audio, answer answers and the audio stays on the phone", + hf.call == "active" and not hf.audio and not app.state["talking"] and app.state["call_out"] is None) +check("without call audio, an answered call offers hang up only", + shown(scr.hang.obj) and not shown(scr.mute.obj) and not shown(scr.route.obj) + and not shown(scr.call_labels[0]) and not shown(scr.call_labels[1]) and shown(scr.call_labels[2])) +check("without call audio, the call still shows its time", (text(scr.call_time) or "").startswith("0:"), + str(text(scr.call_time))) +tap(scr.hang.obj) +scope.run() +check("without call audio, hang up ends the call and the music plays again", + hf.call == "idle" and not shown(scr.card) and sink.playing) +scope.close() + +# ---- The calls setting ------------------------------------------------------- + +forget_settings() +del opens[:] +scope, sink, scr = opened("playing", calls=None) +sw = app.state["switch"] +check("the calls setting starts off", not sw.has_state(lv.STATE.CHECKED) and not app.state["config"]["calls"]) +check("its label says what it does", screenmod.CALLS_LABEL in [ + sw.get_parent().get_child(i).get_text() for i in range(sw.get_parent().get_child_count()) + if sw.get_parent().get_child(i).has_class(lv.label_class)]) +check("it sits in the header", sw.get_parent() is scope.header) +check("off, no hands-free link is opened", app.state["hf"] is None and not opens, str(len(opens))) +check("off, the player's battery shows", shown(scr.battery) and scr.battery_state == "normal", str(scr.battery_state)) +sink.battery = "warning" +sink._bits |= demo.PEER +scope.run() +check("off, a low player battery shows in amber", colour(scr.battery) == screenmod.AMBER, + "%06x" % colour(scr.battery)) +check("off, no signal shows", not shown(scr.signal)) +sink.battery = "normal" +sink._bits |= demo.PEER +tap(sw) +scope.run() +hf = app.state["hf"] +check("on, the hands-free link opens", hf is not None and hf.connected and len(opens) == 1, str(len(opens))) +check("on, the phone's battery and signal show", scr.battery_state == 4 and shown(scr.signal), + str(scr.battery_state)) +check("on, the setting is saved", app._load_config(scope)["calls"] is True) +tap(sw) +scope.run() +check("off again, the link goes", app.state["hf"] is None and not hf.connected) +check("off again, the player's battery is back and the signal goes", + scr.battery_state == "normal" and not shown(scr.signal), str(scr.battery_state)) +check("off again, the setting is saved", app._load_config(scope)["calls"] is False) +tap(sw) +scope.run() +scope.close() +scope, sink, scr = opened("playing", calls=None) +check("the setting is kept when the app opens again", + app.state["switch"].has_state(lv.STATE.CHECKED) and app.state["hf"] is not None) +scope.close() +forget_settings() +scope, sink, scr = opened("nocover", calls=False) +check("a sender that reports no battery shows none", not shown(scr.battery)) +scope.close() + +forget_settings() +os.rmdir(DATA) + print("FAILED: %d" % len(failures) if failures else "ALL PASSED") sys.exit(1 if failures else 0)