fix(driver): raise from getters instead of answering defaults
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m21s
driver / test (3.12) (pull_request) Successful in 3m44s
driver / test (3.13) (pull_request) Successful in 3m19s
driver / lowest (pull_request) Successful in 2m49s
driver / build (pull_request) Successful in 37s
driver / security (pull_request) Successful in 1m16s
CI / driver (pull_request) Successful in 5m32s
driver / publish (pull_request) Skipped

get_volume, get_mute, get_playback_state and get_current_track
answered 0, False, "STOPPED" and {} when the driver was not connected
or the read failed, so an unreachable speaker looked like a silent,
stopped one. They now raise ConnectionClosedException, or
ConnectionException / CommandErrorException with the SoCo error as
the cause.

get_playback_state called get_playback_state() on the SoCo object,
which SoCo does not have; the AttributeError was swallowed and every
speaker read as STOPPED. It now reads current_transport_state from
get_current_transport_info(). The tests mock the speaker with
MagicMock(spec=soco.SoCo), so a call to a method SoCo lacks fails.

Closes #9
This commit is contained in:
Christian Manivong committed 2026-11-02 08:38:28 +01:00
1 parent 8d5ed7e2c4
commit 15ba670a02
3 files changed
+116 -35

No files matched your search

+35 -31
View File
@@ -9,10 +9,18 @@ from __future__ import annotations
import logging
import socket
from typing import Any
from collections.abc import Callable
from typing import Any, TypeVar
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
from napalm.base.exceptions import (
CommandErrorException,
ConnectionClosedException,
ConnectionException,
)
from napalm_device_types import FingerprintRule, MediaDriver, PortSpec
from soco.exceptions import SoCoException
_T = TypeVar("_T")
logger = logging.getLogger(__name__)
@@ -314,35 +322,37 @@ class SonosDriver(MediaDriver):
"""Roll back to the previous config (no-op on Sonos)."""
pass
def get_playback_state(self) -> str:
"""Return the current playback state (PLAYING, PAUSED_PLAYBACK, STOPPED)."""
if self._device is None:
return "STOPPED"
def _read(self, what: str, read: Callable[[Any], _T]) -> _T:
"""Run one read against the connected speaker; a failed read raises.
Network errors (``requests``' exceptions are ``OSError``) become
``ConnectionException``, an error the speaker answered with becomes
``CommandErrorException``; the cause stays attached.
"""
device = self._connected_device()
try:
return self._device.get_playback_state()
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return "STOPPED"
return read(device)
except OSError as exc:
raise ConnectionException(
f"Cannot read {what} from Sonos at {self.hostname}: {exc}"
) from exc
except SoCoException as exc:
raise CommandErrorException(
f"Sonos at {self.hostname} refused to report {what}: {exc}"
) from exc
def get_playback_state(self) -> str:
"""Return the transport state: PLAYING, PAUSED_PLAYBACK, STOPPED or TRANSITIONING."""
info = self._read("the playback state", lambda d: d.get_current_transport_info())
return str(info["current_transport_state"])
def get_current_track(self) -> dict[str, Any]:
"""Return information about the currently playing track."""
if self._device is None:
return {}
try:
return self._device.get_current_track_info()
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return {}
return dict(self._read("the current track", lambda d: d.get_current_track_info()))
def get_volume(self) -> int:
"""Return the current volume (0-100)."""
if self._device is None:
return 0
try:
return self._device.volume
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return 0
return int(self._read("the volume", lambda d: d.volume))
def set_volume(self, volume: int) -> None:
"""Set the volume (0-100)."""
@@ -350,13 +360,7 @@ class SonosDriver(MediaDriver):
def get_mute(self) -> bool:
"""Return whether the speaker is muted."""
if self._device is None:
return False
try:
return bool(self._device.mute)
except Exception:
# Broad catch: SoCo transport errors are unpredictable
return False
return bool(self._read("the mute state", lambda d: d.mute))
def set_mute(self, muted: bool) -> None:
"""Mute or unmute the speaker."""