From 209fbfc6b5eefcc553c543d2255eb0b60809d1ad Mon Sep 17 00:00:00 2001 From: Fabian Thanner <79412976+thannerfabian@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:45:59 +0100 Subject: [PATCH] Add TPLink Omada VPN policy switches (#174549) Co-authored-by: Claude Sonnet 4.6 Co-authored-by: Markus Tuominen <3738613+Markus98@users.noreply.github.com> --- .../components/tplink_omada/controller.py | 11 ++ .../components/tplink_omada/coordinator.py | 20 ++ .../components/tplink_omada/icons.json | 3 + .../components/tplink_omada/switch.py | 99 ++++++++++ tests/components/tplink_omada/conftest.py | 11 ++ .../tplink_omada/fixtures/vpn-policies.json | 20 ++ .../tplink_omada/snapshots/test_switch.ambr | 100 ++++++++++ tests/components/tplink_omada/test_switch.py | 177 +++++++++++++++++- 8 files changed, 439 insertions(+), 2 deletions(-) create mode 100644 tests/components/tplink_omada/fixtures/vpn-policies.json diff --git a/homeassistant/components/tplink_omada/controller.py b/homeassistant/components/tplink_omada/controller.py index 4060699e6157..71fad3103f6a 100644 --- a/homeassistant/components/tplink_omada/controller.py +++ b/homeassistant/components/tplink_omada/controller.py @@ -18,6 +18,7 @@ from .coordinator import ( OmadaDevicesCoordinator, OmadaGatewayCoordinator, OmadaSwitchPortCoordinator, + OmadaVpnPoliciesCoordinator, ) @@ -25,6 +26,7 @@ class OmadaSiteController: """Controller for the Omada SDN site.""" _gateway_coordinator: OmadaGatewayCoordinator | None = None + _vpn_policies_coordinator: OmadaVpnPoliciesCoordinator | None = None def __init__( self, @@ -66,6 +68,10 @@ class OmadaSiteController: self._hass, self._config_entry, self._omada_client, gateway.mac ) await self._gateway_coordinator.async_config_entry_first_refresh() + self._vpn_policies_coordinator = OmadaVpnPoliciesCoordinator( + self._hass, self._config_entry, self._omada_client + ) + await self._vpn_policies_coordinator.async_config_entry_first_refresh() await self.clients_coordinator.async_config_entry_first_refresh() @@ -157,3 +163,8 @@ class OmadaSiteController: def clients_coordinator(self) -> OmadaClientsCoordinator: """Gets the coordinator for site's clients.""" return self._clients_coordinator + + @property + def vpn_policies_coordinator(self) -> OmadaVpnPoliciesCoordinator | None: + """Gets the coordinator for site's VPN policies, or None if there is no gateway.""" + return self._vpn_policies_coordinator diff --git a/homeassistant/components/tplink_omada/coordinator.py b/homeassistant/components/tplink_omada/coordinator.py index 3388da0811b4..ced8664817fd 100644 --- a/homeassistant/components/tplink_omada/coordinator.py +++ b/homeassistant/components/tplink_omada/coordinator.py @@ -11,6 +11,7 @@ from tplink_omada_client import ( OmadaControllerUpdateInfo, OmadaSiteClient, OmadaSwitchPortDetails, + OmadaVpnPolicy, ) from tplink_omada_client.clients import OmadaWirelessClient from tplink_omada_client.devices import ( @@ -38,6 +39,7 @@ POLL_DEVICES = 300 POLL_CONTROLLER = 300 POLL_CONTROLLER_UPDATE = 3600 POLL_UPGRADE = 60 +POLL_VPN = 300 class OmadaCoordinator[_T](DataUpdateCoordinator[dict[str, _T]]): @@ -238,6 +240,24 @@ class OmadaClientsCoordinator(OmadaCoordinator[OmadaWirelessClient]): } +class OmadaVpnPoliciesCoordinator(OmadaCoordinator[OmadaVpnPolicy]): + """Coordinator for getting details about the site's VPN policies.""" + + def __init__( + self, + hass: HomeAssistant, + config_entry: OmadaConfigEntry, + omada_client: OmadaSiteClient, + ) -> None: + """Initialize my coordinator.""" + super().__init__(hass, config_entry, omada_client, "VpnPolicies", POLL_VPN) + + @override + async def poll_update(self) -> dict[str, OmadaVpnPolicy]: + """Poll the site's current VPN policies.""" + return {p.unique_id: p for p in await self.omada_client.get_vpn_policies()} + + class FirmwareUpdateStatus(NamedTuple): """Firmware update information for Omada SDN devices.""" diff --git a/homeassistant/components/tplink_omada/icons.json b/homeassistant/components/tplink_omada/icons.json index f0c6668abac1..fe68f8da64fd 100644 --- a/homeassistant/components/tplink_omada/icons.json +++ b/homeassistant/components/tplink_omada/icons.json @@ -20,6 +20,9 @@ "poe_control": { "default": "mdi:ethernet" }, + "vpn_policy": { + "default": "mdi:vpn" + }, "wan_connect_ipv4": { "default": "mdi:wan" }, diff --git a/homeassistant/components/tplink_omada/switch.py b/homeassistant/components/tplink_omada/switch.py index f4fd64eb3a64..e4c74848bba3 100644 --- a/homeassistant/components/tplink_omada/switch.py +++ b/homeassistant/components/tplink_omada/switch.py @@ -8,6 +8,7 @@ from typing import Any, override from tplink_omada_client import ( GatewayPortSettings, OmadaSiteClient, + OmadaVpnPolicy, PortProfileOverrides, SwitchPortSettings, ) @@ -34,6 +35,7 @@ from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.typing import Undefined from . import OmadaConfigEntry from .const import DOMAIN @@ -41,6 +43,7 @@ from .coordinator import ( OmadaCoordinator, OmadaGatewayCoordinator, OmadaSwitchPortCoordinator, + OmadaVpnPoliciesCoordinator, ) from .entity import OmadaDeviceEntity, get_switch_port_base_name @@ -125,6 +128,32 @@ async def async_setup_entry( entity_callback=_create_gateway_port_entities, ) + gateway_coordinator = controller.gateway_coordinator + vpn_coordinator = controller.vpn_policies_coordinator + if gateway_coordinator and vpn_coordinator: + gateway = next(iter(gateway_coordinator.data.values())) + known_policy_keys: set[str] = set() + + @callback + def _async_add_vpn_entities() -> None: + new_policies = [ + policy + for policy_key, policy in vpn_coordinator.data.items() + if policy_key not in known_policy_keys + ] + if not new_policies: + return + known_policy_keys.update(policy.unique_id for policy in new_policies) + async_add_entities( + OmadaVpnSwitch(vpn_coordinator, gateway, policy) + for policy in new_policies + ) + + config_entry.async_on_unload( + vpn_coordinator.async_add_listener(_async_add_vpn_entities) + ) + _async_add_vpn_entities() + @dataclass(frozen=True, kw_only=True) class OmadaDevicePortSwitchEntityDescription[ @@ -354,3 +383,73 @@ class OmadaDevicePortSwitchEntity[ """Handle updated data from the coordinator.""" self._do_update() self.async_write_ha_state() + + +class OmadaVpnSwitch( + OmadaDeviceEntity[OmadaVpnPoliciesCoordinator], + SwitchEntity, +): + """Switch entity for enabling and disabling an Omada VPN policy.""" + + _attr_translation_key = "vpn_policy" + + def __init__( + self, + coordinator: OmadaVpnPoliciesCoordinator, + gateway: OmadaGateway, + policy: OmadaVpnPolicy, + ) -> None: + """Initialize the VPN policy switch.""" + super().__init__(coordinator, gateway) + self._policy_id = policy.policy_id + self._policy_key = policy.unique_id + self._attr_unique_id = f"{gateway.mac}_vpn_{policy.unique_id}" + self._attr_name = policy.name + self._attr_is_on = policy.enabled + + @property + @override + def available(self) -> bool: + """Return true if the VPN policy still exists on the controller.""" + return super().available and self._policy_key in self.coordinator.data + + @property + @override + def name(self) -> str | Undefined | None: + """Return the current name of the VPN policy.""" + if policy := self.coordinator.data.get(self._policy_key): + return policy.name + return super().name + + @callback + @override + def _handle_coordinator_update(self) -> None: + """Handle updated data from the coordinator.""" + if policy := self.coordinator.data.get(self._policy_key): + self._attr_is_on = policy.enabled + super()._handle_coordinator_update() + + @override + async def async_turn_on(self, **kwargs: Any) -> None: + """Enable the VPN policy.""" + await self._async_set_enabled(True) + + @override + async def async_turn_off(self, **kwargs: Any) -> None: + """Disable the VPN policy.""" + await self._async_set_enabled(False) + + async def _async_set_enabled(self, enabled: bool) -> None: + try: + await self.coordinator.omada_client.set_vpn_policy_enabled( + self._policy_id, enabled + ) + except OmadaClientException as ex: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="switch_action_failed", + ) from ex + + self._attr_is_on = enabled + self.async_write_ha_state() + await self.coordinator.async_request_refresh() diff --git a/tests/components/tplink_omada/conftest.py b/tests/components/tplink_omada/conftest.py index 6da1194d8b88..d781609c6487 100644 --- a/tests/components/tplink_omada/conftest.py +++ b/tests/components/tplink_omada/conftest.py @@ -14,6 +14,8 @@ from tplink_omada_client import ( OmadaControllerStatus, OmadaControllerUpdateInfo, OmadaSite, + OmadaVpnCategory, + OmadaVpnPolicy, ) from tplink_omada_client.clients import ( OmadaConnectedClient, @@ -105,6 +107,13 @@ async def mock_omada_site_client(hass: HomeAssistant) -> AsyncGenerator[AsyncMoc site_client.get_firmware_details = AsyncMock(side_effect=get_firmware_details) site_client.start_firmware_upgrade = AsyncMock() + vpn_data = await async_load_json_array_fixture(hass, "vpn-policies.json", DOMAIN) + vpn_policies = [ + OmadaVpnPolicy(OmadaVpnCategory(p["category"]), p["data"]) for p in vpn_data + ] + site_client.get_vpn_policies = AsyncMock(return_value=vpn_policies) + site_client.set_vpn_policy_enabled = AsyncMock() + async def async_empty() -> AsyncGenerator: for c in (): yield c @@ -125,6 +134,8 @@ def mock_omada_clients_only_site_client(hass: HomeAssistant) -> Generator[AsyncM site_client.get_switches = AsyncMock(return_value=[]) site_client.get_devices = AsyncMock(return_value=[]) site_client.get_switch_ports = AsyncMock(return_value=[]) + site_client.get_vpn_policies = AsyncMock(return_value=[]) + site_client.set_vpn_policy_enabled = AsyncMock() site_client.get_client = AsyncMock(side_effect=partial(_get_mock_client, hass)) site_client.get_known_clients.side_effect = partial(_get_mock_known_clients, hass) diff --git a/tests/components/tplink_omada/fixtures/vpn-policies.json b/tests/components/tplink_omada/fixtures/vpn-policies.json new file mode 100644 index 000000000000..e60649f74a2b --- /dev/null +++ b/tests/components/tplink_omada/fixtures/vpn-policies.json @@ -0,0 +1,20 @@ +[ + { + "category": "server", + "data": { + "id": "vpn-server-1", + "name": "Road Warriors", + "status": true, + "vpnType": 3 + } + }, + { + "category": "site_to_site", + "data": { + "id": "vpn-s2s-1", + "name": "Branch Office", + "status": false, + "vpnType": 2 + } + } +] diff --git a/tests/components/tplink_omada/snapshots/test_switch.ambr b/tests/components/tplink_omada/snapshots/test_switch.ambr index 53f1b67ec410..8f60584ff299 100644 --- a/tests/components/tplink_omada/snapshots/test_switch.ambr +++ b/tests/components/tplink_omada/snapshots/test_switch.ambr @@ -151,3 +151,103 @@ 'unit_of_measurement': None, }) # --- +# name: test_vpn_switches[switch.test_router_branch_office-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.test_router_branch_office', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Branch Office', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Branch Office', + 'platform': 'tplink_omada', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'vpn_policy', + 'unique_id': 'AA-BB-CC-DD-EE-FF_vpn_site_to_site_vpn-s2s-1', + 'unit_of_measurement': None, + }) +# --- +# name: test_vpn_switches[switch.test_router_branch_office] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Test Router Branch Office', + }), + 'context': , + 'entity_id': 'switch.test_router_branch_office', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_vpn_switches[switch.test_router_road_warriors-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.test_router_road_warriors', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Road Warriors', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Road Warriors', + 'platform': 'tplink_omada', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'vpn_policy', + 'unique_id': 'AA-BB-CC-DD-EE-FF_vpn_server_vpn-server-1', + 'unit_of_measurement': None, + }) +# --- +# name: test_vpn_switches[switch.test_router_road_warriors] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Test Router Road Warriors', + }), + 'context': , + 'entity_id': 'switch.test_router_road_warriors', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- diff --git a/tests/components/tplink_omada/test_switch.py b/tests/components/tplink_omada/test_switch.py index 94ab3aa092e6..634505ab46b3 100644 --- a/tests/components/tplink_omada/test_switch.py +++ b/tests/components/tplink_omada/test_switch.py @@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed from syrupy.assertion import SnapshotAssertion -from tplink_omada_client import SwitchPortSettings +from tplink_omada_client import OmadaVpnCategory, OmadaVpnPolicy, SwitchPortSettings from tplink_omada_client.definitions import PoEMode from tplink_omada_client.devices import ( OmadaGateway, @@ -23,7 +23,7 @@ from tplink_omada_client.exceptions import InvalidDevice, OmadaClientException from homeassistant.components import switch from homeassistant.components.tplink_omada.const import DOMAIN from homeassistant.components.tplink_omada.coordinator import POLL_GATEWAY -from homeassistant.const import ATTR_ENTITY_ID +from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant, ServiceResponse from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er @@ -226,6 +226,8 @@ async def test_gateway_port_poe_switch( "set_gateway_wan_port_connect_state", ), ("switch.test_router_port_5_poe", "turn_off", "set_gateway_port_settings"), + ("switch.test_router_road_warriors", "turn_off", "set_vpn_policy_enabled"), + ("switch.test_router_branch_office", "turn_on", "set_vpn_policy_enabled"), ], ) async def test_switch_action_failure_is_translated( @@ -429,3 +431,174 @@ async def call_service( return await hass.services.async_call( switch.DOMAIN, service, {ATTR_ENTITY_ID: entity_id}, blocking=True ) + + +VPN_SERVER_ENTITY_ID = "switch.test_router_road_warriors" +VPN_S2S_ENTITY_ID = "switch.test_router_branch_office" + + +def _build_vpn_policies( + server_enabled: bool, site_to_site_enabled: bool +) -> list[OmadaVpnPolicy]: + """Build the mocked VPN policy list with the given enabled states.""" + return [ + OmadaVpnPolicy( + OmadaVpnCategory.SERVER, + { + "id": "vpn-server-1", + "name": "Road Warriors", + "status": server_enabled, + "vpnType": 3, + }, + ), + OmadaVpnPolicy( + OmadaVpnCategory.SITE_TO_SITE, + { + "id": "vpn-s2s-1", + "name": "Branch Office", + "status": site_to_site_enabled, + "vpnType": 2, + }, + ), + ] + + +async def test_vpn_switches( + hass: HomeAssistant, + init_integration: MockConfigEntry, + snapshot: SnapshotAssertion, + entity_registry: er.EntityRegistry, +) -> None: + """Test VPN policy switches are created with the expected state.""" + for entity_id in (VPN_SERVER_ENTITY_ID, VPN_S2S_ENTITY_ID): + entity = hass.states.get(entity_id) + assert entity == snapshot(name=entity_id) + entry = entity_registry.async_get(entity_id) + assert entry == snapshot(name=f"{entity_id}-entry") + + +@pytest.mark.parametrize( + ("entity_id", "service", "policy_id", "enabled", "expected_state"), + [ + pytest.param( + VPN_SERVER_ENTITY_ID, + "turn_off", + "vpn-server-1", + False, + STATE_OFF, + id="turn_off", + ), + pytest.param( + VPN_S2S_ENTITY_ID, "turn_on", "vpn-s2s-1", True, STATE_ON, id="turn_on" + ), + ], +) +async def test_vpn_switch_toggle( + hass: HomeAssistant, + mock_omada_site_client: MagicMock, + init_integration: MockConfigEntry, + entity_id: str, + service: str, + policy_id: str, + enabled: bool, + expected_state: str, +) -> None: + """Test enabling and disabling a VPN policy.""" + mock_omada_site_client.get_vpn_policies.return_value = _build_vpn_policies( + server_enabled=enabled, site_to_site_enabled=enabled + ) + + await call_service(hass, service, entity_id) + mock_omada_site_client.set_vpn_policy_enabled.assert_called_once_with( + policy_id, enabled + ) + + await hass.async_block_till_done() + entity = hass.states.get(entity_id) + assert entity and entity.state == expected_state + + +async def test_vpn_switch_optimistic_state( + hass: HomeAssistant, + mock_omada_site_client: MagicMock, + init_integration: MockConfigEntry, +) -> None: + """Test a toggle within the refresh cooldown still shows the requested state.""" + mock_omada_site_client.get_vpn_policies.return_value = _build_vpn_policies( + server_enabled=False, site_to_site_enabled=False + ) + await call_service(hass, "turn_off", VPN_SERVER_ENTITY_ID) + # The refresh after this call is debounced, so the state must be set optimistically + await call_service(hass, "turn_on", VPN_SERVER_ENTITY_ID) + + entity = hass.states.get(VPN_SERVER_ENTITY_ID) + assert entity and entity.state == "on" + + +async def test_vpn_switch_renamed( + hass: HomeAssistant, + mock_omada_site_client: MagicMock, + init_integration: MockConfigEntry, +) -> None: + """Test a VPN switch picks up a policy renamed on the controller.""" + mock_omada_site_client.get_vpn_policies.return_value = [ + OmadaVpnPolicy( + OmadaVpnCategory.SERVER, + { + "id": "vpn-server-1", + "name": "Remote Staff", + "status": True, + "vpnType": 3, + }, + ) + ] + async_fire_time_changed(hass, utcnow() + POLL_INTERVAL) + await hass.async_block_till_done() + + entity = hass.states.get(VPN_SERVER_ENTITY_ID) + assert entity and entity.attributes["friendly_name"] == "Test Router Remote Staff" + + +async def test_vpn_switch_added_dynamically( + hass: HomeAssistant, + mock_omada_site_client: MagicMock, + init_integration: MockConfigEntry, +) -> None: + """Test that a new VPN policy discovered after setup creates a new switch entity.""" + new_entity_id = "switch.test_router_new_policy" + assert hass.states.get(new_entity_id) is None + + mock_omada_site_client.get_vpn_policies.return_value = [ + *_build_vpn_policies(server_enabled=True, site_to_site_enabled=False), + OmadaVpnPolicy( + OmadaVpnCategory.SERVER, + { + "id": "vpn-new-1", + "name": "New Policy", + "status": True, + "vpnType": 3, + }, + ), + ] + async_fire_time_changed(hass, utcnow() + POLL_INTERVAL) + await hass.async_block_till_done() + + entity = hass.states.get(new_entity_id) + assert entity is not None + assert entity.state == "on" + + +async def test_vpn_switch_unavailable_when_policy_removed( + hass: HomeAssistant, + mock_omada_site_client: MagicMock, + init_integration: MockConfigEntry, +) -> None: + """Test a VPN switch becomes unavailable when its policy disappears.""" + assert hass.states.get(VPN_SERVER_ENTITY_ID).state == "on" + + mock_omada_site_client.get_vpn_policies.return_value = [] + async_fire_time_changed(hass, utcnow() + POLL_INTERVAL) + await hass.async_block_till_done() + + entity = hass.states.get(VPN_SERVER_ENTITY_ID) + assert entity and entity.state == "unavailable"