Compare commits

...
16 Commits
Author SHA1 Message Date
christianmanivong 17c3817dc5 Merge pull request 'fix(driver): load_replace_candidate is None, not a stub that raises (NetOrk/netork#2503)' (#17) from fix/no-config-replace into main
driver / standard (push) Successful in 15s
driver / lint (push) Successful in 12s
driver / types (push) Successful in 50s
driver / test (3.12) (push) Successful in 4m3s
driver / lowest (push) Successful in 3m32s
driver / test (3.13) (push) Successful in 3m54s
driver / build (push) Successful in 25s
driver / security (push) Successful in 1m1s
CI / driver (push) Successful in 5m32s
driver / publish (push) Skipped
2026-11-13 21:39:05 +00:00
Christian Manivong 3994a4bfc9 fix(driver): load_replace_candidate is None, not a stub that raises (NetOrk/netork#2503)
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 17s
driver / types (pull_request) Successful in 1m6s
driver / test (3.12) (pull_request) Successful in 4m16s
driver / test (3.13) (pull_request) Successful in 4m3s
driver / lowest (pull_request) Successful in 3m34s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 58s
CI / driver (pull_request) Successful in 5m38s
driver / publish (pull_request) Skipped
The driver cannot replace a device's configuration, and said so with a
load_replace_candidate that raised NotImplementedError. A method that only
raises still looks like a replace to anyone who asks whether the driver has
one: netOrk offered a config restore for these devices that could only fail.

None is how a driver switches off a method, the convention netOrk's
capability checks and napalm-device-types follow, so asking now says no.
Nothing in the driver calls it.
2026-11-13 21:45:24 +01:00
christianmanivong 0cc2e5a685 Merge pull request 'fix(driver): leave get_interfaces_ip and cli to NAPALM's stubs' (#16) from fix/interfaces-ip-prefix into main
driver / standard (push) Successful in 15s
driver / lint (push) Successful in 13s
driver / types (push) Successful in 54s
driver / test (3.12) (push) Successful in 4m5s
driver / lowest (push) Successful in 3m43s
driver / test (3.13) (push) Successful in 4m7s
driver / build (push) Successful in 27s
driver / security (push) Successful in 1m1s
CI / driver (push) Successful in 5m34s
driver / publish (push) Skipped
2026-11-12 19:06:14 +00:00
Christian Manivong 397917a174 fix(driver): leave get_interfaces_ip and cli to NAPALM's stubs
driver / standard (pull_request) Successful in 22s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m3s
driver / test (3.12) (pull_request) Successful in 4m13s
driver / test (3.13) (pull_request) Successful in 4m5s
driver / lowest (pull_request) Successful in 3m38s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m19s
CI / driver (pull_request) Successful in 6m10s
driver / publish (pull_request) Skipped
get_interfaces_ip reported the speaker's address with a prefix length
of 24 it never read: the speaker info has no netmask, and SoCo offers
no reading for one, so a speaker in a /23 or /25 network was reported
wrongly. cli answered [] -- not even NAPALM's dict shape -- for a
speaker that has no CLI. Both overrides are gone; NAPALM's stubs raise
NotImplementedError.

Closes #15
2026-11-12 19:23:25 +01:00
christianmanivong bb55884216 Merge pull request 'fix(driver): leave unsupported getters to NAPALM's stubs' (#14) from fix/get-config-stub into main
driver / standard (push) Successful in 16s
driver / lint (push) Successful in 14s
driver / types (push) Successful in 1m15s
driver / test (3.12) (push) Successful in 4m23s
driver / test (3.13) (push) Successful in 4m13s
driver / lowest (push) Successful in 3m41s
driver / build (push) Successful in 35s
driver / security (push) Successful in 1m17s
CI / driver (push) Successful in 6m10s
driver / publish (push) Skipped
2026-11-12 18:14:09 +00:00
Christian Manivong 56e0560eb2 fix(driver): leave unsupported getters to NAPALM's stubs
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 1m0s
driver / test (3.13) (pull_request) Successful in 4m13s
driver / test (3.12) (pull_request) Successful in 4m15s
driver / lowest (pull_request) Successful in 3m42s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 1m8s
CI / driver (pull_request) Successful in 5m38s
driver / publish (pull_request) Skipped
get_config() overrode NAPALM's stub with `return {}` and took no
arguments, so get_config(retrieve="running") raised TypeError, which a
caller reports as a failed configuration backup on every poll. The
other getters a speaker has nothing for (environment, optics, routing,
ARP, MAC table, LLDP, NTP, SNMP, BGP, probes, users, network instances,
firewall policies) had the same shape: an empty answer reads as
"implemented, nothing there", and get_route_to() required an argument
NAPALM defaults.

All of them are gone; NAPALM's stubs raise NotImplementedError.

Closes #13
2026-11-12 18:54:07 +01:00
christianmanivong a86fb6cc3e Merge pull request 'fix: wired is unknown, media contract shapes, raise on failed reads (#2, #11)' (#12) from fix/bugs-2026-11-02b into main
driver / standard (push) Successful in 19s
driver / lint (push) Successful in 16s
driver / types (push) Successful in 1m13s
driver / test (3.12) (push) Successful in 4m24s
driver / test (3.13) (push) Successful in 4m17s
driver / lowest (push) Successful in 3m51s
driver / build (push) Successful in 37s
driver / security (push) Successful in 1m25s
CI / driver (push) Successful in 6m9s
driver / publish (push) Skipped
2026-11-02 09:14:50 +00:00
Christian Manivong 218e2c7a7b fix(driver): follow the media contract's shapes, raise on failed reads
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
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
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
christianmanivong 7a9acd5bbb Merge pull request 'fix(driver): raise from getters instead of answering defaults (#9)' (#10) from fix/bugs-2026-11-02 into main
driver / standard (push) Successful in 19s
driver / lint (push) Successful in 17s
driver / types (push) Successful in 1m9s
driver / test (3.12) (push) Successful in 3m33s
driver / lowest (push) Successful in 2m58s
driver / test (3.13) (push) Successful in 3m41s
driver / build (push) Successful in 32s
driver / security (push) Successful in 1m10s
CI / driver (push) Successful in 5m16s
driver / publish (push) Skipped
2026-11-02 08:23:39 +00:00
Christian Manivong 15ba670a02 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
2026-11-02 08:38:28 +01:00
christianmanivong 8d5ed7e2c4 Merge pull request 'fix(driver): refuse media controls when not connected (#2)' (#8) from fix/bugs-2026-11 into main
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 17s
driver / types (push) Successful in 1m30s
driver / test (3.12) (push) Successful in 3m6s
driver / test (3.13) (push) Successful in 3m1s
driver / lowest (push) Successful in 2m22s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m2s
CI / driver (push) Successful in 4m43s
driver / publish (push) Skipped
2026-11-01 22:00:43 +00:00
Christian Manivong 322b7cd688 fix(driver): refuse media controls when not connected
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m18s
driver / test (3.12) (pull_request) Successful in 3m14s
driver / test (3.13) (pull_request) Successful in 2m54s
driver / lowest (pull_request) Successful in 2m23s
driver / build (pull_request) Successful in 35s
driver / security (pull_request) Successful in 1m11s
CI / driver (pull_request) Successful in 4m53s
driver / publish (pull_request) Skipped
play() and the other controls returned silently without a device, so
a control that did nothing looked like it had worked. They now raise
ConnectionClosedException. get_arp_table() takes NAPALM's vrf
argument, and the module docstring moves above the imports so
__doc__ is set again.

The wired-speaker part of the issue stays open: SoCo's
deviceProperties is a UPnP service, not a dict with WifiMode, so
renaming the attribute alone would still never report eth0.

Refs #2
2026-11-01 21:53:55 +01:00
christianmanivong 0ed6a7093d Merge pull request 'chore: Python 3.12 is the floor (NAPALM/driver-standard#6)' (#7) from chore/python-312-floor into main
driver / standard (push) Successful in 14s
driver / lint (push) Successful in 14s
driver / types (push) Successful in 58s
driver / test (3.12) (push) Successful in 2m51s
driver / test (3.13) (push) Successful in 2m45s
driver / lowest (push) Successful in 2m16s
driver / build (push) Successful in 27s
driver / security (push) Successful in 58s
CI / driver (push) Successful in 4m17s
driver / publish (push) Skipped
2026-10-27 10:40:18 +00:00
Christian Manivong d92dc21cdd fix: the floor on napalm is 5.1 (NAPALM/driver-standard#6)
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 59s
driver / test (3.12) (pull_request) Successful in 2m48s
driver / lowest (pull_request) Successful in 2m21s
driver / test (3.13) (pull_request) Successful in 2m41s
driver / security (pull_request) Successful in 53s
driver / build (pull_request) Successful in 32s
CI / driver (pull_request) Successful in 4m8s
driver / publish (pull_request) Skipped
napalm 5.0 and older import pkg_resources, which a Python 3.12 venv no
longer has, so the lowest job failed on them.
2026-10-27 10:49:31 +01:00
Christian Manivong e3ef8b87c1 chore: Python 3.12 is the floor (NAPALM/driver-standard#6)
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 1m1s
driver / lowest (pull_request) Failing after 19s
driver / security (pull_request) Successful in 52s
driver / build (pull_request) Successful in 24s
driver / test (3.12) (pull_request) Successful in 2m49s
driver / test (3.13) (pull_request) Successful in 2m42s
CI / driver (pull_request) Failing after 3m32s
driver / publish (pull_request) Skipped
netOrk runs every driver in its own containers on Python 3.12, so 3.10
and 3.11 are no longer supported or tested. requires-python, mypy and
ruff move to 3.12, along with what ruff's pyupgrade rules then rewrite.
2026-10-27 10:19:00 +01:00
6 changed files with 484 additions and 285 deletions

No files matched your search

+53
View File
@@ -6,6 +6,59 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Changed
- `load_replace_candidate` is `None` instead of a method that raises
`NotImplementedError`, so a caller that asks whether the driver can replace a
configuration gets no. netOrk offered a config restore for these devices that
could only fail (NetOrk/netork#2503).
- **Breaking:** `get_playback_state()` and `get_zone_info()` return the shapes of
napalm-device-types' media contract. `get_playback_state()` is
`{"state": "playing"|"paused"|"stopped"|"transitioning", "source": "radio"|…}`
instead of SoCo's transport string (`"PAUSED_PLAYBACK"`); a speaker with nothing
queued is `stopped`, and a state outside the four raises `CommandErrorException`.
`get_zone_info()` is a list with one `{"name", "coordinator", "members"}` entry for
the speaker's group instead of the speaker's details, which stay in `get_facts()`
(#11).
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
3.12 venv no longer has.
- **Breaking:** the NAPALM getters a speaker has nothing for are no longer overridden:
`get_config()`, `get_environment()`, `get_optics()`, the routing, ARP, MAC table, LLDP,
NTP, SNMP, BGP, probe, user, network-instance and firewall-policy getters raise
NAPALM's `NotImplementedError` instead of answering `{}` or `[]`. An empty answer read
as "implemented, nothing there", and `get_config()` and `get_route_to()` did not even
take NAPALM's arguments: `get_config(retrieve="running")` raised `TypeError`, which a
caller reported as a failed configuration backup on every poll (#13).
- **Breaking:** `get_interfaces_ip()` and `cli()` are left to NAPALM's stubs and raise
`NotImplementedError`. `get_interfaces_ip()` reported the speaker's address with a
prefix length of 24 it never read -- the speaker reports none, and SoCo has no reading
for one -- so a speaker in any other network size was reported wrongly. `cli()`
answered `[]`, not even NAPALM's dict shape, for a speaker that has no CLI (#15).
### Fixed
- `play()`, `pause()`, `stop()`, `next_track()`, `previous_track()`, `set_volume()`
and `set_mute()` raise `ConnectionClosedException` when the driver is not connected,
instead of returning as if the speaker had done it (#2).
- `get_arp_table()` takes NAPALM's `vrf` argument (#2).
- The driver module carries its docstring again (`__doc__` was `None`) (#2).
- `get_facts()`, `get_interfaces()` and `get_interfaces_ip()` no longer guess whether the
speaker is wired: SoCo offers no reading for it, and the check looked for an attribute
SoCo does not have, so it never found `eth0` anyway. The speaker reports one
interface, `wlan0`, described as "Network (wired or wireless unknown)" (#2).
- `get_group_info()` and `get_zone_info()` raise instead of answering `{}` when the
driver is not connected (`ConnectionClosedException`) or the read fails
(`ConnectionException`, `CommandErrorException`); `{}` / `[]` now only means the
speaker is in no group (#11).
- `get_playback_state()` reports the speaker's real transport state (`PLAYING`,
`PAUSED_PLAYBACK`, `STOPPED`, `TRANSITIONING`); it called a method SoCo does not
have and answered `STOPPED` for every speaker (#9).
- `get_volume()`, `get_mute()`, `get_playback_state()` and `get_current_track()` raise
instead of answering `0`, `False`, `STOPPED` or `{}`: `ConnectionClosedException`
when the driver is not connected, `ConnectionException` when the speaker cannot be
reached, `CommandErrorException` when it refuses the request. An unreachable speaker
no longer reads as a silent, stopped one (#9).
## [0.3.0] - 2026-10-23
The first release on PyPI.
+17 -6
View File
@@ -31,17 +31,28 @@ with driver("192.0.2.20") as speaker:
| Getter / action | |
|---|---|
| `get_facts` | from the speaker info read at `open()` |
| `get_interfaces`, `get_interfaces_ip` | `eth0` when the speaker is wired, always `wlan0` |
| `get_playback_state`, `get_current_track` | yes |
| `get_interfaces` | one interface, `wlan0`, for the speaker's network connection (see below) |
| `get_playback_state` | `{"state": "playing"\|"paused"\|"stopped"\|"transitioning", "source": …}` (media contract) |
| `get_current_track` | yes |
| `get_volume`, `set_volume`, `get_mute`, `set_mute` | yes |
| `play`, `pause`, `stop`, `next_track`, `previous_track` | yes |
| `get_group_info`, `get_zone_info` | yes |
| `get_zone_info` | `[{"name", "coordinator", "members"}]` (media contract) |
| `get_group_info` | the group's coordinator and members with uid and address |
Whether a speaker is wired or wireless is **not known**: SoCo offers no reading for it
(`deviceProperties` is the UPnP service of that name, and none of its actions says), so
the driver reports no `eth0`. The one interface keeps the name `wlan0`; it stands for the
speaker's connection, whatever its medium.
## Not supported
Configuration management (`load_replace_candidate` and `load_merge_candidate` raise
`NotImplementedError`), the CLI, and every routing, LLDP, ARP, NTP, SNMP, BGP, user
and environment getter: they return empty results.
Configuration management (`load_replace_candidate` is `None`, `load_merge_candidate`
raises `NotImplementedError`), configuration export (`get_config`), the CLI (`cli`, NAPALM's
stub), the interface addresses (`get_interfaces_ip`: the speaker reports no prefix
length, and SoCo has no reading for one), and every routing, LLDP, ARP, MAC table, NTP, SNMP, BGP, optics, probe, user, network-instance,
firewall-policy and environment getter. The driver leaves those getters to NAPALM,
whose stubs raise `NotImplementedError`: a speaker has no such data, and an empty
answer would read as "read, nothing there".
## Installation
+139 -244
View File
@@ -1,12 +1,3 @@
from __future__ import annotations
import logging
import socket
from typing import Any
from napalm.base.exceptions import ConnectionException
from napalm_device_types import FingerprintRule, MediaDriver, PortSpec
"""NAPALM driver for Sonos speakers.
Provides network-automation-style access to Sonos speakers via the
@@ -14,8 +5,38 @@ 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.
@@ -72,6 +93,12 @@ class SonosDriver(MediaDriver):
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:
@@ -96,54 +123,29 @@ class SonosDriver(MediaDriver):
"hostname": info.get("player_name", self.hostname),
"fqdn": info.get("ip_address", self.hostname),
"uptime": 0,
"interface_list": self._detect_interfaces(info),
"interface_list": [_INTERFACE],
}
def _detect_interfaces(self, info: dict[str, Any]) -> list[str]:
ifaces: list[str] = []
has_eth = self._check_wired_connection()
if has_eth:
ifaces.append("eth0")
ifaces.append("wlan0")
return ifaces
def _check_wired_connection(self) -> bool:
if self._device is None:
return False
try:
props = self._device.device_properties
if isinstance(props, dict):
wifimode = props.get("WifiMode", "")
return wifimode in ("0", "", None)
except Exception:
# Broad catch: SoCo device_properties may fail for many reasons
logger.debug("Sonos device properties: ignored", exc_info=True)
return False
def get_interfaces(self) -> dict[str, dict[str, Any]]:
"""Return interface information for this speaker."""
"""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)
has_eth = self._check_wired_connection()
interfaces: dict[str, dict[str, Any]] = {}
if has_eth:
interfaces["eth0"] = {
"is_up": is_up,
"is_enabled": True,
"description": "Ethernet",
"last_flapped": -1.0,
"speed": 100,
"mtu": 1500,
"mac_address": mac,
}
interfaces["wlan0"] = {
interfaces[_INTERFACE] = {
"is_up": is_up,
"is_enabled": True,
"description": "WiFi",
"description": "Network (wired or wireless unknown)",
"last_flapped": -1.0,
"speed": 0,
"mtu": 1500,
@@ -151,61 +153,6 @@ class SonosDriver(MediaDriver):
}
return interfaces
def get_interfaces_ip(self) -> dict[str, dict[str, Any]]:
"""Return IP address information for the speaker interfaces."""
if not self._speaker_info:
return {}
info = self._speaker_info
ip = info.get("ip_address", self.hostname)
has_eth = self._check_wired_connection()
ipv4_entry = {
ip: {
"prefix_length": 24,
}
}
interfaces: dict[str, Any] = {}
if has_eth:
interfaces["eth0"] = {"ipv4": ipv4_entry, "ipv6": {}}
interfaces["wlan0"] = {"ipv4": ipv4_entry, "ipv6": {}}
return interfaces
def get_arp_table(self) -> 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,
@@ -236,54 +183,6 @@ class SonosDriver(MediaDriver):
"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
@@ -292,9 +191,9 @@ class SonosDriver(MediaDriver):
"""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")
#: No config replace: switched off rather than a stub that raises, so asking
#: whether the driver has one says no (NetOrk/netork#2503).
load_replace_candidate = None # type: ignore[assignment]
def load_merge_candidate(self, filename: str = "", config: str = "") -> None:
"""Load a merge candidate (not supported on Sonos)."""
@@ -308,130 +207,126 @@ 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) -> 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."""
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)."""
if self._device is None:
return
volume = max(0, min(100, volume))
self._device.volume = volume
self._connected_device().volume = max(0, min(100, volume))
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."""
if self._device is None:
return
self._device.mute = muted
self._connected_device().mute = muted
def play(self) -> None:
"""Start playback."""
if self._device is None:
return
self._device.play()
self._connected_device().play()
def pause(self) -> None:
"""Pause playback."""
if self._device is None:
return
self._device.pause()
self._connected_device().pause()
def stop(self) -> None:
"""Stop playback."""
if self._device is None:
return
self._device.stop()
self._connected_device().stop()
def next_track(self) -> None:
"""Skip to the next track."""
if self._device is None:
return
self._device.next()
self._connected_device().next()
def previous_track(self) -> None:
"""Go back to the previous track."""
if self._device is None:
return
self._device.previous()
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 {}
"""Return the Sonos group this speaker belongs to: its coordinator and members.
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 {}
``{}`` 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),
}
]
+4 -6
View File
@@ -8,15 +8,13 @@ version = "0.3.0"
description = "NAPALM driver for Sonos speakers (SoCo)."
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.10"
requires-python = ">=3.12"
authors = [
{ name = "Christian Manivong" },
]
classifiers = [
"Topic :: Utilities",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Operating System :: POSIX :: Linux",
@@ -24,7 +22,7 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"napalm>=4.0.0",
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm-device-types>=4.21.1",
"soco>=0.30.0",
]
@@ -49,7 +47,7 @@ napalm_sonos = ["py.typed"]
[tool.ruff]
line-length = 100
target-version = "py310"
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
@@ -59,7 +57,7 @@ select = ["E", "F", "I", "UP", "B"]
"tests/**" = ["E501"]
[tool.mypy]
python_version = "3.10"
python_version = "3.12"
strict = true
# napalm itself is untyped, so every driver subclasses Any.
disallow_subclassing_any = false
+17
View File
@@ -0,0 +1,17 @@
"""The driver cannot replace a device's configuration, and says so by not having the method.
A ``load_replace_candidate`` that only raises looks like a replace to anyone who asks
whether the driver has one: netOrk offered a config restore for these devices that
could only fail (NetOrk/netork#2503). ``None`` is how a driver switches off a method
it would otherwise inherit, the convention of napalm-device-types and netOrk's
capability checks.
"""
from __future__ import annotations
from napalm_sonos import SonosDriver
def test_the_driver_has_no_config_replace():
assert SonosDriver.load_replace_candidate is None
assert not callable(getattr(SonosDriver, "load_replace_candidate", None))
+254 -29
View File
@@ -1,6 +1,16 @@
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock, PropertyMock, patch
from napalm.base.exceptions import ConnectionException
import pytest
import requests
import soco
import soco.groups
from napalm.base import NetworkDriver
from napalm.base.exceptions import (
CommandErrorException,
ConnectionClosedException,
ConnectionException,
)
from soco.exceptions import SoCoUPnPException
from napalm_sonos import SonosDriver
@@ -22,11 +32,16 @@ def create_mock_speaker_info():
class TestSonosDriver:
def setup_method(self):
self.driver = SonosDriver("192.168.1.100")
self.mock_device = MagicMock()
# spec: a call to a method SoCo does not have fails instead of being invented (#9).
self.mock_device = MagicMock(spec=soco.SoCo)
self.mock_device.get_speaker_info.return_value = create_mock_speaker_info()
self.mock_device.volume = 30
self.mock_device.mute = False
self.mock_device.get_playback_state.return_value = "PLAYING"
self.mock_device.get_current_transport_info.return_value = {
"current_transport_state": "PLAYING",
"current_transport_status": "OK",
"current_transport_speed": "1",
}
self.mock_device.get_current_track_info.return_value = {
"title": "Test Song",
"artist": "Test Artist",
@@ -93,19 +108,87 @@ class TestSonosDriver:
assert ifaces["wlan0"]["is_up"] is True
assert ifaces["wlan0"]["mac_address"] == "00:0E:58:AB:CD:EF"
def test_get_interfaces_ip(self):
ifaces_ip = self.driver.get_interfaces_ip()
assert "wlan0" in ifaces_ip
assert "192.168.1.100" in ifaces_ip["wlan0"]["ipv4"]
def test_a_speaker_reports_no_eth0(self):
"""SoCo has no reading that tells wired from wireless (#2): the driver no
longer guesses, not even from a dict-like WifiMode it used to look for."""
self.mock_device.device_properties = {"WifiMode": "0"}
def test_get_playback_state(self):
state = self.driver.get_playback_state()
assert state == "PLAYING"
with patch("socket.create_connection"):
interfaces = self.driver.get_interfaces()
assert "eth0" not in self.driver.get_facts()["interface_list"]
assert "eth0" not in interfaces
assert list(interfaces) == ["wlan0"]
def test_get_playback_state_has_the_contracts_shape(self):
"""``{"state", "source"}`` as napalm-device-types' MediaDriver declares it (#11)."""
self.mock_device.music_source = "RADIO"
assert self.driver.get_playback_state() == {"state": "playing", "source": "radio"}
@pytest.mark.parametrize(
("transport", "state"),
[
("PLAYING", "playing"),
("PAUSED_PLAYBACK", "paused"),
("STOPPED", "stopped"),
("TRANSITIONING", "transitioning"),
("NO_MEDIA_PRESENT", "stopped"),
],
)
def test_get_playback_state_reads_the_transport_state(self, transport, state):
"""SoCo has no get_playback_state(); the state is in the transport info (#9)."""
self.mock_device.music_source = "NONE"
self.mock_device.get_current_transport_info.return_value = {
"current_transport_state": transport,
"current_transport_status": "OK",
"current_transport_speed": "1",
}
assert self.driver.get_playback_state()["state"] == state
def test_a_transport_state_outside_the_contract_raises(self):
self.mock_device.music_source = "NONE"
self.mock_device.get_current_transport_info.return_value = {
"current_transport_state": "RECORDING"
}
with pytest.raises(CommandErrorException, match="RECORDING"):
self.driver.get_playback_state()
def test_get_volume(self):
vol = self.driver.get_volume()
assert vol == 30
def test_a_refused_upnp_read_raises(self):
"""A speaker that refuses the read is not a stopped one (#9)."""
self.mock_device.get_current_transport_info.side_effect = SoCoUPnPException(
"UPnP Error 701", "701", "<error/>"
)
with pytest.raises(CommandErrorException) as exc:
self.driver.get_playback_state()
assert isinstance(exc.value.__cause__, SoCoUPnPException)
def test_an_unreachable_speaker_raises_instead_of_reading_silent(self):
"""An unreachable speaker read as volume 0 and not muted (#9)."""
type(self.mock_device).volume = PropertyMock(
side_effect=requests.exceptions.ConnectTimeout("timed out")
)
with pytest.raises(ConnectionException) as exc:
self.driver.get_volume()
assert isinstance(exc.value.__cause__, requests.exceptions.ConnectTimeout)
def test_a_failed_mute_read_raises(self):
type(self.mock_device).mute = PropertyMock(
side_effect=requests.exceptions.ConnectionError("refused")
)
with pytest.raises(ConnectionException):
self.driver.get_mute()
def test_a_failed_track_read_raises(self):
self.mock_device.get_current_track_info.side_effect = requests.exceptions.ReadTimeout(
"timed out"
)
with pytest.raises(ConnectionException):
self.driver.get_current_track()
def test_set_volume(self):
self.driver.set_volume(50)
assert self.mock_device.volume == 50
@@ -146,30 +229,64 @@ class TestSonosDriver:
assert track["title"] == "Test Song"
assert track["artist"] == "Test Artist"
def _group(self, *others: tuple[str, str]) -> None:
"""This speaker ("Living Room") leads a group with *others* (name, uid)."""
self.mock_device.player_name = "Living Room"
self.mock_device.uid = "RINCON_000E58ABCDE01400"
self.mock_device.ip_address = "192.168.1.100"
members = [self.mock_device]
for name, uid in others:
member = MagicMock(spec=soco.SoCo)
member.player_name, member.uid, member.ip_address = name, uid, "192.168.1.101"
members.append(member)
group = MagicMock(spec=soco.groups.ZoneGroup)
group.coordinator = self.mock_device
group.members = set(members)
self.mock_device.group = group
def test_get_group_info(self):
mock_coordinator = MagicMock()
mock_coordinator.player_name = "Living Room"
mock_coordinator.uid = "RINCON_000E58ABCDE01400"
mock_member = MagicMock()
mock_member.player_name = "Kitchen"
mock_member.uid = "RINCON_000E58ABCDE01401"
mock_member.ip_address = "192.168.1.101"
mock_group = MagicMock()
mock_group.coordinator = mock_coordinator
mock_group.members = [mock_coordinator, mock_member]
self.mock_device.group = mock_group
self._group(("Kitchen", "RINCON_000E58ABCDE01401"))
group = self.driver.get_group_info()
assert group["coordinator"] == "Living Room"
assert len(group["members"]) == 2
def test_get_zone_info(self):
zone = self.driver.get_zone_info()
assert zone["player_name"] == "Living Room"
assert zone["model_name"] == "Sonos One"
assert zone["ip_address"] == "192.168.1.100"
def test_get_zone_info_has_the_contracts_shape(self):
"""A list of ``{"name", "coordinator", "members"}``, the others by name (#11)."""
self._group(("Kitchen", "RINCON_000E58ABCDE01401"))
assert self.driver.get_zone_info() == [
{"name": "Living Room", "coordinator": True, "members": ["Kitchen"]}
]
def test_a_member_is_no_coordinator(self):
self._group(("Kitchen", "RINCON_000E58ABCDE01401"))
kitchen = next(m for m in self.mock_device.group.members if m is not self.mock_device)
self.mock_device.group.coordinator = kitchen
zone = self.driver.get_zone_info()[0]
assert (zone["coordinator"], zone["members"]) == (False, ["Kitchen"])
def test_a_speaker_alone_is_a_zone_without_other_members(self):
self._group()
assert self.driver.get_zone_info() == [
{"name": "Living Room", "coordinator": True, "members": []}
]
def test_a_speaker_in_no_group_has_neither(self):
self.mock_device.group = None
assert (self.driver.get_zone_info(), self.driver.get_group_info()) == ([], {})
@pytest.mark.parametrize("getter", ["get_zone_info", "get_group_info"])
def test_a_failed_group_read_raises(self, getter):
"""It read as "no group" / "no zone" (#11)."""
type(self.mock_device).group = PropertyMock(
side_effect=requests.exceptions.ConnectTimeout("timed out")
)
with pytest.raises(ConnectionException):
getattr(self.driver, getter)()
def test_the_media_controls_are_methods_not_a_string_dispatch(self):
"""run_device_action returned another shape than its contract and is gone;
@@ -179,3 +296,111 @@ class TestSonosDriver:
self.driver.set_volume(42)
self.mock_device.play.assert_called_once()
assert self.mock_device.volume == 42
@pytest.mark.parametrize(
"getter",
[
lambda d: d.get_volume(),
lambda d: d.get_mute(),
lambda d: d.get_playback_state(),
lambda d: d.get_current_track(),
lambda d: d.get_group_info(),
lambda d: d.get_zone_info(),
],
ids=[
"get_volume",
"get_mute",
"get_playback_state",
"get_current_track",
"get_group_info",
"get_zone_info",
],
)
def test_a_getter_refuses_when_not_connected(getter):
"""A default (0, False, "STOPPED", {}) made a driver never opened read as a quiet speaker."""
with pytest.raises(ConnectionClosedException):
getter(SonosDriver("192.168.1.100"))
def test_the_driver_module_has_its_docstring():
import napalm_sonos.sonos_driver as module
assert module.__doc__ and "Sonos" in module.__doc__
#: NAPALM getters a speaker has nothing for. Each stays NAPALM's own stub, which raises
#: NotImplementedError: an override answering {} or [] reads as "implemented, nothing
#: there" to a caller that asks whether the driver has its own getter (#13).
_NOT_SUPPORTED_GETTERS = [
"get_arp_table",
"get_bgp_config",
"get_bgp_neighbors",
"get_bgp_neighbors_detail",
"get_config",
"get_environment",
"get_firewall_policies",
# The speaker reports no prefix length; it was always given as 24 (#15).
"get_interfaces_ip",
"get_lldp_neighbors",
"get_lldp_neighbors_detail",
"get_mac_address_table",
"get_network_instances",
"get_ntp_peers",
"get_ntp_servers",
"get_ntp_stats",
"get_optics",
"get_probes_config",
"get_probes_results",
"get_route_to",
"get_snmp_information",
"get_users",
]
@pytest.mark.parametrize("getter", _NOT_SUPPORTED_GETTERS)
def test_an_unsupported_getter_is_napalms_stub(getter):
assert getattr(SonosDriver, getter) is getattr(NetworkDriver, getter)
def test_cli_is_napalms_stub():
"""A speaker has no CLI; `[]` was not even NAPALM's dict shape (#15)."""
assert SonosDriver.cli is NetworkDriver.cli
with pytest.raises(NotImplementedError):
SonosDriver("192.0.2.20").cli(["show version"])
def test_get_interfaces_ip_says_not_implemented():
with pytest.raises(NotImplementedError):
SonosDriver("192.0.2.20").get_interfaces_ip()
def test_get_config_with_napalms_arguments_says_not_implemented():
"""`get_config(retrieve="running")` raised TypeError, read as a failed backup (#13)."""
with pytest.raises(NotImplementedError):
SonosDriver("192.0.2.20").get_config(retrieve="running")
def test_get_route_to_with_napalms_defaults_says_not_implemented():
"""The override required `destination`; NAPALM's getter defaults it (#13)."""
with pytest.raises(NotImplementedError):
SonosDriver("192.0.2.20").get_route_to()
@pytest.mark.parametrize(
"control",
[
lambda d: d.play(),
lambda d: d.pause(),
lambda d: d.stop(),
lambda d: d.next_track(),
lambda d: d.previous_track(),
lambda d: d.set_volume(10),
lambda d: d.set_mute(True),
],
ids=["play", "pause", "stop", "next_track", "previous_track", "set_volume", "set_mute"],
)
def test_a_media_control_refuses_when_not_connected(control):
"""Returning silently made a control that did nothing look like it had worked."""
with pytest.raises(ConnectionClosedException):
control(SonosDriver("192.168.1.100"))