From c29f4b9b27726c2d2a3a2079ce5b1ab0b5711f6e Mon Sep 17 00:00:00 2001 From: Danielle McLean Date: Mon, 29 Jul 2024 10:55:27 +1000 Subject: [PATCH] Add 'heartbeat' to MPD client, so we notice if we disconnect --- src/mpd_now_playable/mpd/listener.py | 16 +++++++++++++--- stubs/mpd/asyncio.pyi | 1 + 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/mpd_now_playable/mpd/listener.py b/src/mpd_now_playable/mpd/listener.py index 23f774b..603dfe5 100644 --- a/src/mpd_now_playable/mpd/listener.py +++ b/src/mpd_now_playable/mpd/listener.py @@ -11,6 +11,7 @@ from ..playback import Playback from ..playback.state import PlaybackState from ..player import Player from ..song_receiver import Receiver +from ..tools.asyncio import run_background_task from .artwork_cache import MpdArtworkCache from .convert.to_playback import to_playback from .types import MpdState @@ -37,16 +38,25 @@ class MpdStateListener(Player): print("Authorising to MPD with your password...") await self.client.password(conf.password.get_secret_value()) print(f"Connected to MPD v{self.client.mpd_version}") + run_background_task(self.heartbeat()) + + async def heartbeat(self) -> None: + while True: + await self.client.ping() + await asyncio.sleep(10) async def refresh(self) -> None: await self.update_receivers() async def loop(self, receivers: Iterable[Receiver]) -> None: self.receivers = receivers - # notify our receivers of the initial state MPD is in when this script loads up. + # Notify our receivers of the initial state MPD is in when this script loads up. await self.update_receivers() - # then wait for stuff to change in MPD. :) - async for _ in self.client.idle(): + # And then wait for stuff to change in MPD. :) + async for subsystems in self.client.idle(): + # If no subsystems actually changed, we don't need to update the receivers. + if not subsystems: + continue self.idle_count += 1 await self.update_receivers() diff --git a/stubs/mpd/asyncio.pyi b/stubs/mpd/asyncio.pyi index 6968141..1193ba7 100644 --- a/stubs/mpd/asyncio.pyi +++ b/stubs/mpd/asyncio.pyi @@ -9,6 +9,7 @@ class MPDClient(MPDClientBase): def __init__(self) -> None: ... async def connect(self, host: str, port: int = ...) -> None: ... + async def ping(self) -> None: ... async def password(self, password: str) -> None: ... def idle(self, subsystems: Sequence[str] = ...) -> AsyncIterator[Sequence[str]]: ... async def status(self) -> types.StatusResponse: ...