diff --git a/meshterm/services/battery_service.py b/meshterm/services/battery_service.py index 8e939a7..72d9894 100644 --- a/meshterm/services/battery_service.py +++ b/meshterm/services/battery_service.py @@ -326,12 +326,19 @@ class BatteryService: delay = POLL_S try: delay = await self._poll() + self._tell_sound() except asyncio.CancelledError: raise except Exception as exc: # noqa: BLE001 - a bad read must not stop the loop self._ctx.log.debug("battery poller: read failed: %s", exc) await asyncio.sleep(delay) + def _tell_sound(self) -> None: + """Give the new reading to the sound service, which plays the battery-low sound.""" + sound = getattr(self._ctx, "sound", None) + if sound is not None and self._reading is not None: + sound.note_battery(self._reading.percent, charging=self._reading.charging) + async def _poll(self) -> float: """One pass: read the pack, estimate the charge, and calculate the charging trend again. diff --git a/meshterm/services/sound.py b/meshterm/services/sound.py index bd35b5b..8a5eefa 100644 --- a/meshterm/services/sound.py +++ b/meshterm/services/sound.py @@ -32,6 +32,7 @@ notification is silent, and only the flash can show it. from __future__ import annotations +import asyncio import logging import os import shutil @@ -45,6 +46,7 @@ from enum import Enum from pathlib import Path from typing import TYPE_CHECKING +from ..core.events import EventKind, MeshEvent from ..platforms import get_platform if TYPE_CHECKING: @@ -81,6 +83,18 @@ THEMES: dict[str, dict[SoundEvent, str]] = { }, } +#: The seconds between a packet heard and its tick. A received message arrives as a packet +#: first, then as a message. The wait lets the sound of the message start first, and then +#: the tick sees that sound and does not play (refer to :data:`TICK_GAP_S`). Thus a message +#: plays only its own sound (JP, 2026-11-20: "a sound for packets that don't already make +#: sound"). +TICK_DELAY_S = 0.15 + +#: How many points above the ``battery_low_pct`` threshold the battery must rise before the +#: battery-low sound can play again. Without this margin, a reading that moves by one point +#: around the threshold plays the sound at each poll. +BATTERY_REARM_PCT = 5 + #: The minimum seconds between the start of a sound and a packet tick. It limits the tick #: to four each second on a busy mesh, and a tick does not play over the start of another #: sound (JP, 2026-11-20). @@ -237,6 +251,37 @@ class SoundService: self._last_sound = float("-inf") self._bell: Callable[[], None] | None = None self._flash: Callable[[], None] | None = None + self._battery_armed = True + self._tick_pending = False + self._unsubscribe: Callable[[], None] | None = None + + def start(self) -> None: + """Listen to the packets heard, for the packet tick. The interactive session calls it.""" + events = getattr(self._ctx, "events", None) + if self._unsubscribe is None and events is not None: + self._unsubscribe = events.subscribe(self._on_packet, EventKind.OBSERVATION) + + def stop(self) -> None: + """Stop listening to the packets heard.""" + if self._unsubscribe is not None: + self._unsubscribe() + self._unsubscribe = None + + def _on_packet(self, event: MeshEvent) -> None: + """Schedule the tick of a packet heard, if the tick is on (refer to TICK_DELAY_S).""" + if self._tick_pending or not self._prefs.packet_tick or not self.enabled: + return + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return + self._tick_pending = True + loop.call_later(TICK_DELAY_S, self._tick) + + def _tick(self) -> None: + """Play the packet tick, unless another sound started a short time ago.""" + self._tick_pending = False + self.notify(SoundEvent.PACKET_TICK) def set_hooks( self, @@ -303,6 +348,25 @@ class SoundService: self._flash() return audible + def note_battery(self, percent: int, *, charging: bool) -> None: + """Play the battery-low sound one time when the battery goes below the threshold. + + The battery service calls this method after each reading. The sound plays when the + level goes below ``battery_low_pct`` while the pack does not charge. It can play + again only after the level rises :data:`BATTERY_REARM_PCT` points above the + threshold, or the pack charges. + + Args: + percent: The level of the battery, from 0 to 100. + charging: Whether the pack takes charge now. + """ + threshold = int(self._prefs.battery_low_pct) + if charging or percent >= threshold + BATTERY_REARM_PCT: + self._battery_armed = True + elif percent < threshold and self._battery_armed: + self._battery_armed = False + self.notify(SoundEvent.BATTERY_LOW) + def preview( self, event: SoundEvent = SoundEvent.CHANNEL_MESSAGE, volume: int | None = None ) -> bool: diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 759818c..584336b 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -1176,6 +1176,9 @@ async def _resume_monitor(ctx: AppContext) -> Exception | None: # reads, and it skips silently without a device, so it is also safe to run from the # start. await ctx.battery.start() + # The packet tick listens to the packets heard. It does nothing while its preference is + # off. + ctx.sound.start() # The place finder reads only stored locations and the network (tiles, Nominatim), never # the device. Its first read waits some seconds, so it does not slow the start. await ctx.places.start() diff --git a/tests/test_sound.py b/tests/test_sound.py index d6fdd12..26ac031 100644 --- a/tests/test_sound.py +++ b/tests/test_sound.py @@ -3,6 +3,8 @@ from __future__ import annotations +import asyncio +import time import wave from pathlib import Path from types import SimpleNamespace @@ -233,3 +235,69 @@ def test_toggle_changes_and_saves_the_preference(tmp_path: Path) -> None: assert Preferences.load(tmp_path / "preferences.toml").sound_muted is True assert service.toggle() is True # on again assert Preferences.load(tmp_path / "preferences.toml").sound_muted is False + + +def test_the_battery_sound_plays_once_below_the_threshold(tmp_path: Path) -> None: + """The sound plays when the level goes below 25%, and not again at the next reading.""" + service, player, _, _, _ = _service(tmp_path) + service.note_battery(30, charging=False) + assert player.played == [] + service.note_battery(24, charging=False) + service.note_battery(23, charging=False) + assert [p.name.split("-")[1] for p in player.played] == ["LowBattery"] + + +def test_the_battery_sound_rearms_above_the_margin_or_on_charge(tmp_path: Path) -> None: + """A level near the threshold does not rearm it. Five points above, or a charge, does.""" + service, player, _, _, _ = _service(tmp_path) + service.note_battery(20, charging=False) + service.note_battery(27, charging=False) # not 5 points above 25: still played once + service.note_battery(20, charging=False) + assert len(player.played) == 1 + service.note_battery(30, charging=False) + service.note_battery(20, charging=False) + assert len(player.played) == 2 + service.note_battery(20, charging=True) + service.note_battery(19, charging=False) + assert len(player.played) == 3 + + +def test_a_packet_heard_ticks_after_a_short_wait(tmp_path: Path) -> None: + """With the tick on, a packet heard plays the tick after TICK_DELAY_S.""" + + async def run() -> list[Path]: + service, player, _, _, _ = _service(tmp_path, packet_tick=True) + service._clock = time.monotonic + service._on_packet(None) # type: ignore[arg-type] + service._on_packet(None) # type: ignore[arg-type] - one tick is already waiting + await asyncio.sleep(sound.TICK_DELAY_S + 0.1) + return player.played + + played = asyncio.run(run()) + assert [p.name.split("-")[1] for p in played] == ["Effect_Tick"] + + +def test_a_message_sound_in_the_wait_cancels_the_tick(tmp_path: Path) -> None: + """The packet of a message ticks no tick when the message plays its own sound.""" + + async def run() -> list[Path]: + service, player, _, _, _ = _service(tmp_path, packet_tick=True) + service._clock = time.monotonic + service._on_packet(None) # type: ignore[arg-type] + service.notify(SoundEvent.DIRECT_MESSAGE) + await asyncio.sleep(sound.TICK_DELAY_S + 0.1) + return player.played + + played = asyncio.run(run()) + assert [p.name.split("-")[1] for p in played] == ["Carme"] + + +def test_no_tick_is_scheduled_when_the_tick_is_off(tmp_path: Path) -> None: + """With the tick off (the default), a packet heard schedules nothing.""" + + async def run() -> bool: + service, _, _, _, _ = _service(tmp_path) + service._on_packet(None) # type: ignore[arg-type] + return service._tick_pending + + assert asyncio.run(run()) is False