Add cloudhook support to switchbot_cloud webhook (#174566)

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Steve Rice
2026-06-23 21:50:08 -04:00
committed by GitHub
co-authored by Claude Opus 4.8
parent adf2f2854c
commit 10fe3dc13f
4 changed files with 470 additions and 10 deletions
@@ -16,7 +16,7 @@ from switchbot_api import (
SwitchBotDeviceOfflineError,
)
from homeassistant.components import webhook
from homeassistant.components import cloud, webhook
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_API_TOKEN, CONF_WEBHOOK_ID, Platform
from homeassistant.core import HomeAssistant
@@ -26,7 +26,7 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.network import NoURLAvailableError
from homeassistant.helpers.typing import ConfigType
from .const import DEVICE_SUPPORT_MAP, DOMAIN, ENTRY_TITLE
from .const import CONF_CLOUDHOOK_URL, DEVICE_SUPPORT_MAP, DOMAIN, ENTRY_TITLE
from .coordinator import SwitchBotCoordinator
from .service import async_register_services
@@ -392,6 +392,22 @@ async def async_setup_entry(
await _initialize_webhook(hass, entry, api, coordinators_by_id)
async def _handle_cloud_connection_change(
state: cloud.CloudConnectionState,
) -> None:
"""Re-register the SwitchBot webhook when the cloud (re)connects.
On a local-only install the cloud may only become available after this
entry is set up. When that happens we create (and persist) a cloudhook
and re-register it with SwitchBot's cloud so push devices work.
"""
if state is cloud.CloudConnectionState.CLOUD_CONNECTED:
await _initialize_webhook(hass, entry, api, coordinators_by_id)
entry.async_on_unload(
cloud.async_listen_connection_change(hass, _handle_cloud_connection_change)
)
return True
@@ -427,11 +443,7 @@ async def _initialize_webhook(
hass.config_entries.async_update_entry(entry, data=new_data)
try:
webhook_url = webhook.async_generate_url(
hass,
entry.data[CONF_WEBHOOK_ID],
allow_internal=False,
)
webhook_url = await _async_get_webhook_url(hass, entry)
except NoURLAvailableError:
_LOGGER.warning(
"SwitchBot Cloud webhook not configured because no external URL is available"
@@ -493,6 +505,55 @@ async def _initialize_webhook(
_LOGGER.error("Failed to connect Switchbot cloud device: %s", e)
async def _async_get_webhook_url(
hass: HomeAssistant, entry: SwitchbotCloudConfigEntry
) -> str:
"""Return the URL to register with SwitchBot's cloud for this entry.
When a Nabu Casa cloud subscription is active we create (and persist) a
cloudhook and prefer it, so local-only installs without a public
``external_url`` can still receive SwitchBot push events. Creating a
cloudhook requires the cloud connection to be established; when a
subscription is active but not yet connected, we fall back to the local URL
and let the connection-change listener create the cloudhook once connected.
Without a subscription we use the locally generated webhook URL.
"""
if cloud.async_active_subscription(hass):
if CONF_CLOUDHOOK_URL in entry.data:
return str(entry.data[CONF_CLOUDHOOK_URL])
if cloud.async_is_connected(hass):
webhook_id = entry.data[CONF_WEBHOOK_ID]
# A previous run may have left a cloudhook registered for this
# webhook id; delete it so we can create a fresh one.
with contextlib.suppress(cloud.CloudNotAvailable):
await cloud.async_delete_cloudhook(hass, webhook_id)
cloudhook_url = await cloud.async_create_cloudhook(hass, webhook_id)
hass.config_entries.async_update_entry(
entry, data={**entry.data, CONF_CLOUDHOOK_URL: cloudhook_url}
)
_LOGGER.debug("Created SwitchBot Cloud cloudhook: %s", cloudhook_url)
return cloudhook_url
return webhook.async_generate_url(
hass,
entry.data[CONF_WEBHOOK_ID],
allow_internal=False,
)
async def async_remove_entry(
hass: HomeAssistant, entry: SwitchbotCloudConfigEntry
) -> None:
"""Clean up the cloudhook (if any) when the entry is removed."""
if CONF_CLOUDHOOK_URL not in entry.data:
return
with contextlib.suppress(cloud.CloudNotAvailable):
await cloud.async_delete_cloudhook(hass, entry.data[CONF_WEBHOOK_ID])
_LOGGER.debug(
"Removed SwitchBot Cloud cloudhook (%s)", entry.data[CONF_WEBHOOK_ID]
)
def _create_handle_webhook(
coordinators_by_id: dict[str, SwitchBotCoordinator],
) -> Callable[[HomeAssistant, str, web.Request], Awaitable[None]]:
@@ -11,6 +11,8 @@ DOMAIN: Final = "switchbot_cloud"
ENTRY_TITLE = "SwitchBot Cloud"
DEFAULT_SCAN_INTERVAL = timedelta(seconds=600)
CONF_CLOUDHOOK_URL: Final = "cloudhook_url"
SENSOR_KIND_TEMPERATURE = "temperature"
SENSOR_KIND_HUMIDITY = "humidity"
SENSOR_KIND_BATTERY = "battery"
@@ -1,6 +1,7 @@
{
"domain": "switchbot_cloud",
"name": "SwitchBot Cloud",
"after_dependencies": ["cloud"],
"codeowners": [
"@SeraphicRav",
"@laurence-presland",
+399 -3
View File
@@ -12,19 +12,48 @@ from switchbot_api import (
SwitchBotConnectionError,
)
from homeassistant.components import cloud
from homeassistant.components.cloud import CloudNotAvailable
from homeassistant.components.switchbot_cloud import SwitchBotAPI
from homeassistant.components.switchbot_cloud.const import DEFAULT_SCAN_INTERVAL
from homeassistant.components.switchbot_cloud.const import (
CONF_CLOUDHOOK_URL,
DEFAULT_SCAN_INTERVAL,
DOMAIN,
)
from homeassistant.components.webhook import DOMAIN as WEBHOOK_DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_WEBHOOK_ID, EVENT_HOMEASSISTANT_START
from homeassistant.const import (
CONF_API_KEY,
CONF_API_TOKEN,
CONF_WEBHOOK_ID,
EVENT_HOMEASSISTANT_START,
)
from homeassistant.core import HomeAssistant
from homeassistant.core_config import async_process_ha_core_config
from . import configure_integration
from tests.common import async_fire_time_changed
from tests.common import (
MockConfigEntry,
async_fire_time_changed,
async_mock_cloud_connection_status,
)
from tests.components.cloud import mock_cloud
from tests.typing import ClientSessionGenerator
CLOUDHOOK_URL = "https://hooks.nabu.casa/ABCD"
def _water_detector() -> Device:
"""Return a webhook-manageable device (Water Detector)."""
return Device(
version="V1.0",
deviceId="water-detector-1",
deviceName="water-detector-name-1",
deviceType="Water Detector",
hubDeviceId="test-hub-id",
)
@pytest.fixture
def mock_list_devices():
@@ -350,3 +379,370 @@ async def test_setup_entry_skips_webhook_without_external_url(
mock_setup_webhook.assert_not_called()
assert entry.data[CONF_WEBHOOK_ID] not in hass.data.get(WEBHOOK_DOMAIN, {})
assert "no external URL is available" in caplog.text
async def test_setup_creates_cloudhook_when_cloud_active(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
mock_get_webook_configuration,
mock_delete_webhook,
mock_setup_webhook,
) -> None:
"""Test a cloudhook is created and registered when cloud is active.
This is the local-only-HA case: no external_url is configured, but a Nabu
Casa subscription is active, so SwitchBot should be given the cloudhook URL.
"""
await mock_cloud(hass)
await hass.async_block_till_done()
mock_get_webook_configuration.return_value = {"urls": []}
mock_list_devices.return_value = [_water_detector()]
mock_get_status.return_value = {"battery": 100}
mock_delete_webhook.return_value = {}
mock_setup_webhook.return_value = {}
with (
patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
patch("homeassistant.components.cloud.async_is_connected", return_value=True),
patch.object(cloud, "async_active_subscription", return_value=True),
patch(
"homeassistant.components.cloud.async_create_cloudhook",
return_value=CLOUDHOOK_URL,
) as fake_create_cloudhook,
patch("homeassistant.components.cloud.async_delete_cloudhook"),
):
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
# Cloudhook was created and persisted in entry.data ...
fake_create_cloudhook.assert_called_once()
assert entry.data[CONF_CLOUDHOOK_URL] == CLOUDHOOK_URL
# ... and registered with SwitchBot's cloud.
mock_setup_webhook.assert_called_once_with(CLOUDHOOK_URL)
async def test_setup_reuses_persisted_cloudhook(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
mock_get_webook_configuration,
mock_delete_webhook,
mock_setup_webhook,
) -> None:
"""Test a previously persisted cloudhook is reused, not recreated."""
await mock_cloud(hass)
await hass.async_block_till_done()
# SwitchBot already has the cloudhook registered (so nothing to re-add).
mock_get_webook_configuration.return_value = {"urls": [CLOUDHOOK_URL]}
mock_list_devices.return_value = [_water_detector()]
mock_get_status.return_value = {"battery": 100}
mock_setup_webhook.return_value = {}
# An entry that already has both a webhook id and a persisted cloudhook.
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_API_TOKEN: "test-token",
CONF_API_KEY: "test-api-key",
CONF_WEBHOOK_ID: "test-webhook-id",
CONF_CLOUDHOOK_URL: CLOUDHOOK_URL,
},
entry_id="123456",
unique_id="123456",
)
entry.add_to_hass(hass)
with (
patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
patch("homeassistant.components.cloud.async_is_connected", return_value=True),
patch.object(cloud, "async_active_subscription", return_value=True),
patch(
"homeassistant.components.cloud.async_create_cloudhook",
return_value=CLOUDHOOK_URL,
) as fake_create_cloudhook,
patch("homeassistant.components.cloud.async_delete_cloudhook"),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
# No new cloudhook should have been created and SwitchBot's already-set
# URL (the cloudhook) needs no re-registration.
fake_create_cloudhook.assert_not_called()
mock_setup_webhook.assert_not_called()
assert entry.data[CONF_CLOUDHOOK_URL] == CLOUDHOOK_URL
async def test_setup_falls_back_to_local_url_without_cloud(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
mock_get_webook_configuration,
mock_delete_webhook,
mock_setup_webhook,
) -> None:
"""Test the local external URL is used when no cloud subscription exists."""
await async_process_ha_core_config(
hass,
{"external_url": "https://example.com"},
)
mock_get_webook_configuration.return_value = {"urls": []}
mock_list_devices.return_value = [_water_detector()]
mock_get_status.return_value = {"battery": 100}
mock_delete_webhook.return_value = {}
mock_setup_webhook.return_value = {}
with patch.object(cloud, "async_active_subscription", return_value=False):
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert CONF_CLOUDHOOK_URL not in entry.data
mock_setup_webhook.assert_called_once()
registered_url = mock_setup_webhook.call_args[0][0]
assert registered_url.startswith("https://example.com")
async def test_cloud_connects_after_setup(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
mock_get_webook_configuration,
mock_delete_webhook,
mock_setup_webhook,
) -> None:
"""Test a cloudhook is created when the cloud connects after setup.
On a local-only install the cloud may only become available after the entry
has already been set up; the integration must react to the connection
change and register the cloudhook with SwitchBot.
"""
await mock_cloud(hass)
await hass.async_block_till_done()
mock_get_webook_configuration.return_value = {"urls": []}
mock_list_devices.return_value = [_water_detector()]
mock_get_status.return_value = {"battery": 100}
mock_delete_webhook.return_value = {}
mock_setup_webhook.return_value = {}
# Cloud is not active at setup time.
with patch.object(cloud, "async_active_subscription", return_value=False):
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert CONF_CLOUDHOOK_URL not in entry.data
# Cloud becomes active and connects.
with (
patch("homeassistant.components.cloud.async_is_connected", return_value=True),
patch.object(cloud, "async_active_subscription", return_value=True),
patch(
"homeassistant.components.cloud.async_create_cloudhook",
return_value=CLOUDHOOK_URL,
) as fake_create_cloudhook,
patch("homeassistant.components.cloud.async_delete_cloudhook"),
):
async_mock_cloud_connection_status(hass, True)
await hass.async_block_till_done()
fake_create_cloudhook.assert_called_once()
assert entry.data[CONF_CLOUDHOOK_URL] == CLOUDHOOK_URL
mock_setup_webhook.assert_called_with(CLOUDHOOK_URL)
async def test_setup_active_subscription_not_connected(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
mock_get_webook_configuration,
mock_delete_webhook,
mock_setup_webhook,
) -> None:
"""Test no cloudhook is created while the cloud is not yet connected.
``async_active_subscription`` is true as soon as the user is logged in with a
valid subscription, but ``async_create_cloudhook`` raises ``CloudNotConnected``
until the cloud connection is established. Setup must not call it (which would
propagate and abort setup); the connection-change listener creates the
cloudhook once connected.
"""
await mock_cloud(hass)
await hass.async_block_till_done()
mock_get_webook_configuration.return_value = {"urls": []}
mock_list_devices.return_value = [_water_detector()]
mock_get_status.return_value = {"battery": 100}
mock_delete_webhook.return_value = {}
mock_setup_webhook.return_value = {}
# Subscription active, but the cloud connection is not established yet.
with (
patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
patch("homeassistant.components.cloud.async_is_connected", return_value=False),
patch.object(cloud, "async_active_subscription", return_value=True),
patch(
"homeassistant.components.cloud.async_create_cloudhook",
side_effect=cloud.CloudNotConnected,
) as fake_create_cloudhook,
patch("homeassistant.components.cloud.async_delete_cloudhook"),
):
entry = await configure_integration(hass)
await hass.async_block_till_done()
# Setup completed without aborting, and no cloudhook was created.
assert entry.state is ConfigEntryState.LOADED
fake_create_cloudhook.assert_not_called()
assert CONF_CLOUDHOOK_URL not in entry.data
# Once the cloud connects, the cloudhook is created and registered.
with (
patch("homeassistant.components.cloud.async_is_connected", return_value=True),
patch.object(cloud, "async_active_subscription", return_value=True),
patch(
"homeassistant.components.cloud.async_create_cloudhook",
return_value=CLOUDHOOK_URL,
) as fake_create_cloudhook,
patch("homeassistant.components.cloud.async_delete_cloudhook"),
):
async_mock_cloud_connection_status(hass, True)
await hass.async_block_till_done()
fake_create_cloudhook.assert_called_once()
assert entry.data[CONF_CLOUDHOOK_URL] == CLOUDHOOK_URL
mock_setup_webhook.assert_called_with(CLOUDHOOK_URL)
async def test_cloudhook_deleted_on_entry_removal(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
mock_get_webook_configuration,
mock_delete_webhook,
mock_setup_webhook,
) -> None:
"""Test the cloudhook is deleted when the config entry is removed."""
await mock_cloud(hass)
await hass.async_block_till_done()
mock_get_webook_configuration.return_value = {"urls": []}
mock_list_devices.return_value = [_water_detector()]
mock_get_status.return_value = {"battery": 100}
mock_delete_webhook.return_value = {}
mock_setup_webhook.return_value = {}
with (
patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
patch("homeassistant.components.cloud.async_is_connected", return_value=True),
patch.object(cloud, "async_active_subscription", return_value=True),
patch(
"homeassistant.components.cloud.async_create_cloudhook",
return_value=CLOUDHOOK_URL,
),
patch(
"homeassistant.components.cloud.async_delete_cloudhook"
) as fake_delete_cloudhook,
):
entry = await configure_integration(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert entry.data[CONF_CLOUDHOOK_URL] == CLOUDHOOK_URL
# Ignore the pre-create cleanup delete that happened during setup; we
# only care that removal deletes the cloudhook.
fake_delete_cloudhook.reset_mock()
await hass.config_entries.async_remove(entry.entry_id)
await hass.async_block_till_done()
fake_delete_cloudhook.assert_called_once_with(hass, entry.data[CONF_WEBHOOK_ID])
async def test_remove_entry_without_cloudhook_skips_delete(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
mock_get_webook_configuration,
mock_delete_webhook,
mock_setup_webhook,
) -> None:
"""Test no cloudhook delete is attempted when none was created."""
await async_process_ha_core_config(
hass,
{"external_url": "https://example.com"},
)
mock_get_webook_configuration.return_value = {"urls": []}
mock_list_devices.return_value = [_water_detector()]
mock_get_status.return_value = {"battery": 100}
mock_delete_webhook.return_value = {}
mock_setup_webhook.return_value = {}
with (
patch.object(cloud, "async_active_subscription", return_value=False),
patch(
"homeassistant.components.cloud.async_delete_cloudhook"
) as fake_delete_cloudhook,
):
entry = await configure_integration(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert CONF_CLOUDHOOK_URL not in entry.data
await hass.config_entries.async_remove(entry.entry_id)
await hass.async_block_till_done()
fake_delete_cloudhook.assert_not_called()
async def test_remove_entry_with_cloud_unavailable(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
mock_get_webook_configuration,
mock_delete_webhook,
mock_setup_webhook,
) -> None:
"""Test CloudNotAvailable is handled gracefully on entry removal."""
await mock_cloud(hass)
await hass.async_block_till_done()
mock_get_webook_configuration.return_value = {"urls": []}
mock_list_devices.return_value = [_water_detector()]
mock_get_status.return_value = {"battery": 100}
mock_delete_webhook.return_value = {}
mock_setup_webhook.return_value = {}
with (
patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
patch("homeassistant.components.cloud.async_is_connected", return_value=True),
patch.object(cloud, "async_active_subscription", return_value=True),
patch(
"homeassistant.components.cloud.async_create_cloudhook",
return_value=CLOUDHOOK_URL,
),
patch(
"homeassistant.components.cloud.async_delete_cloudhook",
side_effect=CloudNotAvailable(),
),
):
entry = await configure_integration(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert entry.data[CONF_CLOUDHOOK_URL] == CLOUDHOOK_URL
# Should not raise even though delete raises CloudNotAvailable.
await hass.config_entries.async_remove(entry.entry_id)
await hass.async_block_till_done()
assert not hass.config_entries.async_entries("switchbot_cloud")