Files
napalm-sonos/napalm_sonos/sonos_driver.py
T
Christian Manivong 218e2c7a7b
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m9s
driver / test (3.12) (pull_request) Successful in 4m21s
driver / test (3.13) (pull_request) Successful in 4m16s
driver / lowest (pull_request) Successful in 3m46s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m14s
CI / driver (pull_request) Successful in 6m10s
driver / publish (pull_request) Skipped
fix(driver): follow the media contract's shapes, raise on failed reads
get_playback_state returned SoCo's transport string and get_zone_info
the speaker's details, where napalm-device-types' MediaDriver declares
{"state", "source"} and a list of {"name", "coordinator", "members"}.
Both now return those shapes; the speaker's details stay in get_facts.

get_group_info and get_zone_info caught every exception and answered
{}, so a failed read looked like a speaker in no group. They now raise
like the other getters (#9); {} and [] mean no group.

Closes #11
2026-11-02 09:28:39 +01:00

431 lines
15 KiB
Python

"""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 get_interfaces_ip(self) -> dict[str, dict[str, Any]]:
"""Return the speaker's address, on its one connection (see :meth:`get_interfaces`)."""
if not self._speaker_info:
return {}
info = self._speaker_info
ip = info.get("ip_address", self.hostname)
ipv4_entry = {
ip: {
"prefix_length": 24,
}
}
return {_INTERFACE: {"ipv4": ipv4_entry, "ipv6": {}}}
def get_arp_table(self, vrf: str = "") -> list[dict[str, Any]]:
"""Return the ARP table (not supported on Sonos)."""
return []
def get_lldp_neighbors(self) -> dict[str, Any]:
"""Return LLDP neighbors (not supported on Sonos)."""
return {}
def get_lldp_neighbors_detail(self, interface: str = "") -> dict[str, Any]:
"""Return detailed LLDP neighbors (not supported on Sonos)."""
return {}
def get_config(self) -> dict[str, Any]:
"""Return the device config (not supported on Sonos)."""
return {}
def get_environment(self) -> dict[str, Any]:
"""Return environment/power info (not supported on Sonos)."""
return {}
def get_optics(self) -> dict[str, Any]:
"""Return optics info (not supported on Sonos)."""
return {}
def get_ntp_peers(self) -> dict[str, str | None]:
"""Return NTP peers (not supported on Sonos)."""
return {}
def get_ntp_servers(self) -> dict[str, str | None]:
"""Return NTP servers (not supported on Sonos)."""
return {}
def get_ntp_stats(self) -> list[dict[str, Any]]:
"""Return NTP stats (not supported on Sonos)."""
return []
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 get_route_to(self, destination: str) -> list[dict[str, Any]]:
"""Return routing table (not supported on Sonos)."""
return []
def get_snmp_information(self) -> dict[str, Any]:
"""Return SNMP info (not supported on Sonos)."""
return {}
def get_users(self) -> dict[str, Any]:
"""Return user accounts (not supported on Sonos)."""
return {}
def get_network_instances(self, name: str = "") -> dict[str, Any]:
"""Return network instances / VRFs (not supported on Sonos)."""
return {}
def get_bgp_config(self, group: str = "") -> dict[str, Any]:
"""Return BGP config (not supported on Sonos)."""
return {}
def get_bgp_neighbors(self) -> dict[str, Any]:
"""Return BGP neighbors (not supported on Sonos)."""
return {}
def get_bgp_neighbors_detail(self, neighbor_address: str = "") -> dict[str, Any]:
"""Return detailed BGP neighbor info (not supported on Sonos)."""
return {}
def get_probes_config(self) -> dict[str, Any]:
"""Return probe config (not supported on Sonos)."""
return {}
def get_probes_results(self) -> dict[str, Any]:
"""Return probe results (not supported on Sonos)."""
return {}
def get_mac_address_table(self) -> list[dict[str, Any]]:
"""Return MAC address table (not supported on Sonos)."""
return []
def get_firewall_policies(self) -> dict[str, Any]:
"""Return firewall policies (not supported on Sonos)."""
return {}
def cli(self, commands: list[str]) -> list[dict[str, Any]]:
"""Run CLI commands (not supported on Sonos)."""
return []
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),
}
]