Use UpdateFailedUnreachable in Shelly (#192673)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shay Levy
2026-11-14 20:23:13 +02:00
committed by GitHub
co-authored by Claude Opus 5.5
parent b4fcbd6a79
commit 5d042e5bc8
3 changed files with 121 additions and 32 deletions
+36 -21
View File
@@ -33,7 +33,11 @@ from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback
from homeassistant.helpers import device_registry as dr, issue_registry as ir
from homeassistant.helpers.debounce import Debouncer
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, format_mac
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator,
UpdateFailed,
UpdateFailedUnreachable,
)
from homeassistant.util import dt as dt_util
from .bluetooth import async_connect_scanner
@@ -425,7 +429,7 @@ class ShellyBlockCoordinator(ShellyCoordinatorBase[BlockDevice]):
"""Fetch data."""
if self.sleep_period:
# Sleeping device, no point polling it, just mark it unavailable
raise UpdateFailed(
raise UpdateFailedUnreachable(
translation_domain=DOMAIN,
translation_key="update_error_sleeping_device",
translation_placeholders={
@@ -438,10 +442,9 @@ class ShellyBlockCoordinator(ShellyCoordinatorBase[BlockDevice]):
try:
await self.device.update()
except DeviceConnectionError as err:
raise UpdateFailed(
raise UpdateFailedUnreachable(
translation_domain=DOMAIN,
translation_key="update_error",
translation_placeholders={"device": self.name},
translation_key="update_error_unreachable",
) from err
except InvalidAuthError:
await self.async_shutdown_device_and_start_reauth()
@@ -521,11 +524,16 @@ class ShellyRestCoordinator(ShellyCoordinatorBase[BlockDevice]):
if self.device.status["uptime"] > 2 * REST_SENSORS_UPDATE_INTERVAL:
return
await self.device.update_shelly()
except (DeviceConnectionError, MacAddressMismatchError) as err:
raise UpdateFailed(
except DeviceConnectionError as err:
raise UpdateFailedUnreachable(
translation_domain=DOMAIN,
translation_key="update_error",
translation_placeholders={"device": self.name},
translation_key="update_error_unreachable",
) from err
except MacAddressMismatchError as err:
raise UpdateFailedUnreachable(
translation_domain=DOMAIN,
translation_key="update_error_mac_mismatch",
translation_placeholders={"host": self.device.ip_address},
) from err
except InvalidAuthError:
await self.async_shutdown_device_and_start_reauth()
@@ -757,7 +765,7 @@ class ShellyRpcCoordinator(ShellyCoordinatorBase[RpcDevice]):
if self.sleep_period:
# Sleeping device, no point polling it, just mark it unavailable
raise UpdateFailed(
raise UpdateFailedUnreachable(
translation_domain=DOMAIN,
translation_key="update_error_sleeping_device",
translation_placeholders={
@@ -780,10 +788,9 @@ class ShellyRpcCoordinator(ShellyCoordinatorBase[RpcDevice]):
self.name,
)
return
raise UpdateFailed(
raise UpdateFailedUnreachable(
translation_domain=DOMAIN,
translation_key="update_error_reconnect_error",
translation_placeholders={"device": self.name},
translation_key="update_error_reconnect",
)
async def _async_disconnected(self, reconnect: bool) -> None:
@@ -981,16 +988,20 @@ class ShellyRpcPollingCoordinator(ShellyCoordinatorBase[RpcDevice]):
"""Fetch data."""
# The websocket is connected before initialization completes on reconnect
if not self.device.connected or not self.device.initialized:
raise UpdateFailed(
raise UpdateFailedUnreachable(
translation_domain=DOMAIN,
translation_key="update_error_device_disconnected",
translation_placeholders={"device": self.name},
translation_key="update_error_disconnected",
)
LOGGER.debug("Polling Shelly RPC Device - %s", self.name)
try:
await self.device.poll()
except (DeviceConnectionError, RpcCallError) as err:
except DeviceConnectionError as err:
raise UpdateFailedUnreachable(
translation_domain=DOMAIN,
translation_key="update_error_unreachable",
) from err
except RpcCallError as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="update_error",
@@ -1015,16 +1026,20 @@ class ShellyBluTrvUpdateCoordinator(ShellyCoordinatorBase[RpcDevice]):
async def _async_update_data(self) -> None:
"""Fetch the latest firmware available for BLU TRV devices."""
if not self.device.connected:
raise UpdateFailed(
raise UpdateFailedUnreachable(
translation_domain=DOMAIN,
translation_key="update_error_device_disconnected",
translation_placeholders={"device": self.name},
translation_key="update_error_disconnected",
)
LOGGER.debug("Checking for BLU TRV firmware update - %s", self.name)
try:
self.available_firmware = await self.device.blu_trv_check_for_updates()
except (DeviceConnectionError, RpcCallError) as err:
except DeviceConnectionError as err:
raise UpdateFailedUnreachable(
translation_domain=DOMAIN,
translation_key="update_error_unreachable",
) from err
except RpcCallError as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="update_error",
+10 -4
View File
@@ -918,14 +918,20 @@
"update_error": {
"message": "An error occurred while retrieving data from {device}"
},
"update_error_device_disconnected": {
"message": "An error occurred while retrieving data from {device} because it is disconnected"
"update_error_disconnected": {
"message": "The device is disconnected"
},
"update_error_reconnect_error": {
"message": "An error occurred while reconnecting to {device}"
"update_error_mac_mismatch": {
"message": "A different device responded at {host}"
},
"update_error_reconnect": {
"message": "The device could not be reconnected"
},
"update_error_sleeping_device": {
"message": "Sleeping device {device} did not update within {period} seconds interval"
},
"update_error_unreachable": {
"message": "The device cannot be reached"
}
},
"issues": {
+75 -7
View File
@@ -1,6 +1,7 @@
"""Tests for Shelly coordinator."""
from datetime import timedelta
import logging
from typing import Any
from unittest.mock import AsyncMock, Mock, call, patch
@@ -58,7 +59,8 @@ from . import (
register_entity,
)
RECONNECT_ERROR = "An error occurred while reconnecting to Test name"
RECONNECT_ERROR = "The device could not be reconnected"
SHELLY_LOGGER = "homeassistant.components.shelly"
RELAY_BLOCK_ID = 0
LIGHT_BLOCK_ID = 2
SENSOR_BLOCK_ID = 3
@@ -257,6 +259,7 @@ async def test_block_polling_connection_error(
freezer: FrozenDateTimeFactory,
mock_block_device: Mock,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test block device polling connection error."""
monkeypatch.setattr(
@@ -278,15 +281,36 @@ async def test_block_polling_connection_error(
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
assert (
SHELLY_LOGGER,
logging.INFO,
"Test name is unavailable: The device cannot be reached",
) in caplog.record_tuples
@pytest.mark.parametrize("exc", [DeviceConnectionError, MacAddressMismatchError])
@pytest.mark.parametrize(
("exc", "message"),
[
pytest.param(
DeviceConnectionError,
"Test name is unavailable: The device cannot be reached",
id="unreachable",
),
pytest.param(
MacAddressMismatchError,
"Test name is unavailable: A different device responded at 10.10.10.11",
id="mac_mismatch",
),
],
)
async def test_block_rest_update_connection_error(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_block_device: Mock,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
exc: Exception,
message: str,
) -> None:
"""Test block REST update connection error."""
entity_id = register_entity(hass, BINARY_SENSOR_DOMAIN, "test_name_cloud", "cloud")
@@ -303,6 +327,7 @@ async def test_block_rest_update_connection_error(
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
assert (SHELLY_LOGGER, logging.INFO, message) in caplog.record_tuples
async def test_block_sleeping_device_no_periodic_updates(
@@ -939,6 +964,7 @@ async def test_rpc_reconnect_error(
freezer: FrozenDateTimeFactory,
mock_rpc_device: Mock,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
exc: Exception,
) -> None:
"""Test RPC reconnect error."""
@@ -960,6 +986,11 @@ async def test_rpc_reconnect_error(
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
assert (
SHELLY_LOGGER,
logging.INFO,
f"Test name is unavailable: {RECONNECT_ERROR}",
) in caplog.record_tuples
def _inject_ota_event(
@@ -1087,11 +1118,33 @@ async def test_rpc_error_running_connected_events(
assert state.state == STATE_ON
@pytest.mark.parametrize(
("exc", "level", "message"),
[
pytest.param(
DeviceConnectionError,
logging.INFO,
"Test name is unavailable: The device cannot be reached",
id="unreachable",
),
pytest.param(
RpcCallError(999),
logging.ERROR,
"Error fetching Test name data: An error occurred while retrieving "
"data from Test name",
id="rpc_call_error",
),
],
)
async def test_rpc_polling_connection_error(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_rpc_device: Mock,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
exc: Exception,
level: int,
message: str,
) -> None:
"""Test RPC polling connection error."""
entity_id = register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "wifi-rssi")
@@ -1100,9 +1153,7 @@ async def test_rpc_polling_connection_error(
monkeypatch.setattr(
mock_rpc_device,
"poll",
AsyncMock(
side_effect=DeviceConnectionError,
),
AsyncMock(side_effect=exc),
)
assert (state := hass.states.get(entity_id))
@@ -1112,6 +1163,7 @@ async def test_rpc_polling_connection_error(
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
assert (SHELLY_LOGGER, level, message) in caplog.record_tuples
async def test_rpc_polling_disconnected(
@@ -1119,6 +1171,7 @@ async def test_rpc_polling_disconnected(
freezer: FrozenDateTimeFactory,
mock_rpc_device: Mock,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test RPC polling device disconnected."""
entity_id = register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "wifi-rssi")
@@ -1133,6 +1186,11 @@ async def test_rpc_polling_disconnected(
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
assert (
SHELLY_LOGGER,
logging.INFO,
"Test name is unavailable: The device is disconnected",
) in caplog.record_tuples
async def test_rpc_polling_not_initialized(
@@ -1306,7 +1364,12 @@ async def test_block_sleeping_device_connection_error(
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert "Sleeping device Test name did not update" in caplog.text
assert (
SHELLY_LOGGER,
logging.INFO,
"Test name is unavailable: Sleeping device Test name did not update "
f"within {sleep_period} seconds interval",
) in caplog.record_tuples
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
@@ -1360,7 +1423,12 @@ async def test_rpc_sleeping_device_connection_error(
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert "Sleeping device Test name did not update" in caplog.text
assert (
SHELLY_LOGGER,
logging.INFO,
"Test name is unavailable: Sleeping device Test name did not update "
f"within {sleep_period} seconds interval",
) in caplog.record_tuples
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE