diff --git a/CHANGELOG.md b/CHANGELOG.md index 7292bce..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 @@ -22,6 +30,10 @@ All notable changes to this driver. The format follows 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 2bd50ff..cd16218 100644 --- a/README.md +++ b/README.md @@ -32,10 +32,12 @@ with driver("192.0.2.20") as speaker: |---|---| | `get_facts` | from the speaker info read at `open()` | | `get_interfaces`, `get_interfaces_ip` | one interface, `wlan0`, for the speaker's network connection (see below) | -| `get_playback_state`, `get_current_track` | yes | +| `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 diff --git a/napalm_sonos/sonos_driver.py b/napalm_sonos/sonos_driver.py index a45257c..7734830 100644 --- a/napalm_sonos/sonos_driver.py +++ b/napalm_sonos/sonos_driver.py @@ -27,6 +27,16 @@ 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. @@ -314,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.""" @@ -360,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 31459f3..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, @@ -123,18 +124,39 @@ class TestSonosDriver: 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() @@ -212,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; @@ -254,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."""