Files
napalm-sonos/napalm_sonos/sonos_driver.py
T
Christian Manivong 53ea5f051f fix(driver): stop guessing whether a speaker is wired
The wired check read device_properties, which SoCo does not have
(deviceProperties is the UPnP service, and none of its actions says
wired or wireless), and swallowed the AttributeError, so eth0 was never
reported and the guess served nothing. It is gone: a speaker reports
its one connection as wlan0, described as of unknown medium, and the
README and the getter docstrings say that wired vs. wireless is not
known.

Closes #2
2026-11-02 09:26:58 +01:00

406 lines
14 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"
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) -> 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."""
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 information about the Sonos group this speaker belongs to."""
if self._device is None:
return {}
try:
group = self._device.group
coordinator = group.coordinator
members = group.members
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 members
],
}
except Exception:
# Broad catch: SoCo group/network operations can fail in many ways
return {}
def get_zone_info(self) -> dict[str, Any]:
"""Return detailed zone/speaker information."""
if self._device is None:
return {}
try:
info = self._speaker_info or {}
return {
"player_name": info.get("player_name", ""),
"zone_name": info.get("zone_name", ""),
"uid": info.get("uid", ""),
"model_name": info.get("model_name", ""),
"software_version": info.get("software_version", ""),
"hardware_version": info.get("hardware_version", ""),
"serial_number": info.get("serial_number", ""),
"mac_address": info.get("mac_address", ""),
"ip_address": info.get("ip_address", self.hostname),
}
except Exception:
# Broad catch: speaker_info dict access is safe, but keep for safety
return {}