diff --git a/CHANGELOG.md b/CHANGELOG.md index 72272e4..bd37c8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ All notable changes to this driver. The format follows ## [Unreleased] ### Changed +- **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 @@ -18,6 +26,14 @@ All notable changes to this driver. The format follows 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). diff --git a/README.md b/README.md index 5c6cb0a..cd16218 100644 --- a/README.md +++ b/README.md @@ -31,11 +31,18 @@ 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`, `get_interfaces_ip` | 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 diff --git a/napalm_sonos/sonos_driver.py b/napalm_sonos/sonos_driver.py index 6046aff..7734830 100644 --- a/napalm_sonos/sonos_driver.py +++ b/napalm_sonos/sonos_driver.py @@ -24,6 +24,19 @@ _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. @@ -110,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, @@ -166,23 +154,18 @@ class SonosDriver(MediaDriver): return interfaces def get_interfaces_ip(self) -> dict[str, dict[str, Any]]: - """Return IP address information for the speaker interfaces.""" + """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) - 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 + 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).""" @@ -341,10 +324,25 @@ class SonosDriver(MediaDriver): 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.""" + 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()) - return str(info["current_transport_state"]) + 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.""" @@ -387,46 +385,46 @@ class SonosDriver(MediaDriver): 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), + } + ] diff --git a/tests/test_sonos.py b/tests/test_sonos.py index 4acd460..1e6c3b5 100644 --- a/tests/test_sonos.py +++ b/tests/test_sonos.py @@ -3,6 +3,7 @@ from unittest.mock import MagicMock, PropertyMock, patch import pytest import requests import soco +import soco.groups from napalm.base.exceptions import ( CommandErrorException, ConnectionClosedException, @@ -106,23 +107,56 @@ class TestSonosDriver: assert ifaces["wlan0"]["is_up"] is True assert ifaces["wlan0"]["mac_address"] == "00:0E:58:AB:CD:EF" + 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"} + + 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 "eth0" not in self.driver.get_interfaces_ip() + assert list(interfaces) == ["wlan0"] + 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_get_playback_state(self): - state = self.driver.get_playback_state() - assert state == "PLAYING" + 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" - def test_get_playback_state_reads_the_transport_state(self): + 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": "PAUSED_PLAYBACK", + "current_transport_state": transport, "current_transport_status": "OK", "current_transport_speed": "1", } - assert self.driver.get_playback_state() == "PAUSED_PLAYBACK" + 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() @@ -200,30 +234,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; @@ -242,8 +310,17 @@ class TestSonosDriver: 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", ], - ids=["get_volume", "get_mute", "get_playback_state", "get_current_track"], ) def test_a_getter_refuses_when_not_connected(getter): """A default (0, False, "STOPPED", {}) made a driver never opened read as a quiet speaker."""