"""NAPALM driver for Sonos speakers. Provides network-automation-style access to Sonos speakers via the SoCo library, exposing NAPALM standard methods alongside Sonos-specific media-playback controls. """ from __future__ import annotations import logging import socket from collections.abc import Callable from typing import Any, TypeVar 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__) #: The speaker's one network connection. Wired or wireless is not known (#2). _INTERFACE = "wlan0" #: UPnP AVTransport states, as napalm-device-types' media contract names them. #: NO_MEDIA_PRESENT is a speaker with nothing queued: stopped. _PLAYBACK_STATES = { "PLAYING": "playing", "PAUSED_PLAYBACK": "paused", "STOPPED": "stopped", "TRANSITIONING": "transitioning", "NO_MEDIA_PRESENT": "stopped", } class SonosDriver(MediaDriver): """NAPALM driver for controlling Sonos speakers. Implements the standard NAPALM interface plus media-playback methods (play, pause, volume, etc.) using the SoCo library. """ VENDOR = "Sonos" DRIVER_NAME = "sonos" OUI_PREFIXES = ["00:0E:58", "34:7E:5C", "78:28:CA", "5C:AA:FD", "94:9F:3E", "48:A6:B8"] PORT_SPECS = [ PortSpec("http", 1400, ("/xml/device_description.xml",), weight=9.0, mandatory=True), PortSpec("https", 1443, weight=4.0), ] HTTP_FINGERPRINT = [ FingerprintRule("sonos", weight=8.0, mandatory=True), FingerprintRule("rincon", weight=5.0), ] # A Sonos speaker takes no login: username and password exist only for NAPALM's # constructor signature, and the empty default is no credential. def __init__( # nosec B107 self, hostname: str, username: str = "", password: str = "", timeout: int = 60, optional_args: dict[str, Any] | None = None, ) -> None: """Initialise the driver with connection details.""" self.hostname = hostname self.username = username self.password = password self.timeout = timeout self.optional_args = optional_args or {} self._device: Any = None self._speaker_info: dict[str, Any] | None = None def open(self) -> None: """Open a connection to the Sonos speaker.""" try: from soco import SoCo self._device = SoCo(self.hostname) self._speaker_info = self._device.get_speaker_info() except Exception as e: # Broad catch: SoCo can raise a variety of transport/XML errors raise ConnectionException(f"Cannot connect to Sonos at {self.hostname}: {e}") from e def close(self) -> None: """Close the connection to the Sonos speaker.""" self._device = None self._speaker_info = None def _connected_device(self) -> Any: """Return the SoCo device; raise if :meth:`open` has not connected it.""" if self._device is None: raise ConnectionClosedException(f"Sonos at {self.hostname} is not connected") return self._device def is_alive(self) -> dict[str, bool]: """Check whether the speaker is reachable on the network.""" if self._device is None: return {"is_alive": False} try: sock = socket.create_connection((self.hostname, 1400), timeout=5) sock.close() return {"is_alive": True} except OSError: return {"is_alive": False} def get_facts(self) -> dict[str, Any]: """Return device facts gathered during connection.""" if not self._speaker_info: return {} info = self._speaker_info return { "vendor": self.VENDOR, "model": info.get("model_name", "Unknown"), "serial_number": info.get("serial_number", ""), "os_version": info.get("software_version", ""), "hostname": info.get("player_name", self.hostname), "fqdn": info.get("ip_address", self.hostname), "uptime": 0, "interface_list": [_INTERFACE], } def get_interfaces(self) -> dict[str, dict[str, Any]]: """Return the speaker's one network connection, as ``wlan0``. Whether the speaker is wired or wireless is not known: SoCo offers no reading for it (``deviceProperties`` is a UPnP service whose actions do not say), so the driver reports no ``eth0`` and does not guess. The name ``wlan0`` is kept for continuity; it stands for the connection, whatever its medium. """ if not self._speaker_info: return {} info = self._speaker_info mac = info.get("mac_address", "") is_up = self.is_alive().get("is_alive", False) interfaces: dict[str, dict[str, Any]] = {} interfaces[_INTERFACE] = { "is_up": is_up, "is_enabled": True, "description": "Network (wired or wireless unknown)", "last_flapped": -1.0, "speed": 0, "mtu": 1500, "mac_address": mac, } return interfaces def ping( self, destination: str, source: str = "", ttl: int = 255, timeout: int = 2, size: int = 64, count: int = 5, vrf: str = "", ) -> dict[str, Any]: """Ping a destination (not supported on Sonos).""" return { "success": {}, "error": "Not supported on Sonos", } def traceroute( self, destination: str, source: str = "", ttl: int = 255, timeout: int = 2, vrf: str = "", ) -> dict[str, Any]: """Run traceroute (not supported on Sonos).""" return { "success": {}, "error": "Not supported on Sonos", } def commit_config(self) -> None: """Commit the candidate config (no-op on Sonos).""" pass def discard_config(self) -> None: """Discard the candidate config (no-op on Sonos).""" pass def load_replace_candidate(self, filename: str = "", config: str = "") -> None: """Load a replacement config (not supported on Sonos).""" raise NotImplementedError("Sonos does not support config replacement") def load_merge_candidate(self, filename: str = "", config: str = "") -> None: """Load a merge candidate (not supported on Sonos).""" raise NotImplementedError("Sonos does not support config merge") def compare_config(self) -> str: """Compare candidate with active config (no-op on Sonos).""" return "" def rollback(self) -> None: """Roll back to the previous config (no-op on Sonos).""" pass 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 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) -> dict[str, str]: """Return the transport state and the source, as the media contract shapes it. * state (string) - ``"playing"``, ``"paused"``, ``"stopped"`` or ``"transitioning"`` * source (string) - SoCo's music source in lower case: ``"library"``, ``"radio"``, ``"line_in"``, ``"tv"``, ``"airplay"``, ``"none"``, … :raises CommandErrorException: for a transport state outside these four (UPnP's recording states), or when the speaker refuses the read. """ info = self._read("the playback state", lambda d: d.get_current_transport_info()) transport = str(info["current_transport_state"]) if transport not in _PLAYBACK_STATES: raise CommandErrorException( f"Sonos at {self.hostname} reports transport state {transport!r}" ) source = str(self._read("the music source", lambda d: d.music_source)) return {"state": _PLAYBACK_STATES[transport], "source": source.lower()} def get_current_track(self) -> dict[str, Any]: """Return information about the currently playing track.""" 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).""" return int(self._read("the volume", lambda d: d.volume)) def set_volume(self, volume: int) -> None: """Set the volume (0-100).""" self._connected_device().volume = max(0, min(100, volume)) def get_mute(self) -> bool: """Return whether the speaker is muted.""" return bool(self._read("the mute state", lambda d: d.mute)) def set_mute(self, muted: bool) -> None: """Mute or unmute the speaker.""" self._connected_device().mute = muted def play(self) -> None: """Start playback.""" self._connected_device().play() def pause(self) -> None: """Pause playback.""" self._connected_device().pause() def stop(self) -> None: """Stop playback.""" self._connected_device().stop() def next_track(self) -> None: """Skip to the next track.""" self._connected_device().next() def previous_track(self) -> None: """Go back to the previous track.""" self._connected_device().previous() def get_group_info(self) -> dict[str, Any]: """Return the Sonos group this speaker belongs to: its coordinator and members. ``{}`` for a speaker in no group. """ return self._read("the group", _group_info) def get_zone_info(self) -> list[dict[str, Any]]: """Return the zone this speaker plays in, as the media contract shapes it. One entry: ``name`` (the speaker's room), ``coordinator`` (whether it leads its group) and ``members`` (the names of the other speakers in the group). ``[]`` for a speaker in no group. """ return self._read("the zone", _zone_info) def _group_info(device: Any) -> dict[str, Any]: group = device.group if group is None: return {} coordinator = group.coordinator return { "coordinator": coordinator.player_name if coordinator else "", "coordinator_uid": coordinator.uid if coordinator else "", "members": [ {"name": m.player_name, "uid": m.uid, "ip_address": m.ip_address} for m in group.members ], } def _zone_info(device: Any) -> list[dict[str, Any]]: group = device.group if group is None: return [] uid = device.uid coordinator = group.coordinator return [ { "name": device.player_name, "coordinator": coordinator is not None and coordinator.uid == uid, "members": sorted(m.player_name for m in group.members if m.uid != uid), } ]