2022-10-04 19:29:07 +00:00
|
|
|
"""Coordinators for the Shelly integration."""
|
2024-03-08 13:33:51 +00:00
|
|
|
|
2022-10-04 19:29:07 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2022-11-15 18:34:45 +00:00
|
|
|
import asyncio
|
2022-11-14 18:58:10 +00:00
|
|
|
from collections.abc import Callable, Coroutine
|
2022-10-06 07:10:58 +00:00
|
|
|
from dataclasses import dataclass
|
2022-10-04 19:29:07 +00:00
|
|
|
from datetime import timedelta
|
2024-05-20 08:43:59 +00:00
|
|
|
from typing import Any, cast
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2022-11-15 21:37:45 +00:00
|
|
|
from aioshelly.ble import async_ensure_ble_enabled, async_stop_scanner
|
2023-08-21 07:49:11 +00:00
|
|
|
from aioshelly.block_device import BlockDevice, BlockUpdateType
|
2024-01-30 08:47:52 +00:00
|
|
|
from aioshelly.const import MODEL_NAMES, MODEL_VALVE
|
2022-10-23 04:57:25 +00:00
|
|
|
from aioshelly.exceptions import DeviceConnectionError, InvalidAuthError, RpcCallError
|
2023-08-21 07:49:11 +00:00
|
|
|
from aioshelly.rpc_device import RpcDevice, RpcUpdateType
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2023-01-21 23:26:54 +00:00
|
|
|
from homeassistant.config_entries import ConfigEntry, ConfigEntryState
|
2024-04-14 15:07:26 +00:00
|
|
|
from homeassistant.const import (
|
|
|
|
ATTR_DEVICE_ID,
|
|
|
|
CONF_HOST,
|
|
|
|
EVENT_HOMEASSISTANT_STOP,
|
|
|
|
Platform,
|
|
|
|
)
|
2022-11-14 18:58:10 +00:00
|
|
|
from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback
|
2024-05-27 10:50:11 +00:00
|
|
|
from homeassistant.helpers import device_registry as dr, issue_registry as ir
|
2022-10-04 19:29:07 +00:00
|
|
|
from homeassistant.helpers.debounce import Debouncer
|
2024-05-27 10:50:11 +00:00
|
|
|
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
|
2022-10-05 12:39:58 +00:00
|
|
|
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2022-11-15 18:34:45 +00:00
|
|
|
from .bluetooth import async_connect_scanner
|
2022-10-04 19:29:07 +00:00
|
|
|
from .const import (
|
|
|
|
ATTR_CHANNEL,
|
|
|
|
ATTR_CLICK_TYPE,
|
|
|
|
ATTR_DEVICE,
|
|
|
|
ATTR_GENERATION,
|
|
|
|
BATTERY_DEVICES_WITH_PERMANENT_CONNECTION,
|
2022-11-15 18:34:45 +00:00
|
|
|
CONF_BLE_SCANNER_MODE,
|
2022-10-04 19:29:07 +00:00
|
|
|
CONF_SLEEP_PERIOD,
|
2022-10-06 07:10:58 +00:00
|
|
|
DOMAIN,
|
2022-10-04 19:29:07 +00:00
|
|
|
DUAL_MODE_LIGHT_MODELS,
|
|
|
|
ENTRY_RELOAD_COOLDOWN,
|
|
|
|
EVENT_SHELLY_CLICK,
|
|
|
|
INPUTS_EVENTS_DICT,
|
|
|
|
LOGGER,
|
2023-07-20 11:11:05 +00:00
|
|
|
MAX_PUSH_UPDATE_FAILURES,
|
2022-10-04 19:29:07 +00:00
|
|
|
MODELS_SUPPORTING_LIGHT_EFFECTS,
|
2023-09-06 06:17:45 +00:00
|
|
|
OTA_BEGIN,
|
|
|
|
OTA_ERROR,
|
|
|
|
OTA_PROGRESS,
|
|
|
|
OTA_SUCCESS,
|
2023-07-20 11:11:05 +00:00
|
|
|
PUSH_UPDATE_ISSUE_ID,
|
2022-10-04 19:29:07 +00:00
|
|
|
REST_SENSORS_UPDATE_INTERVAL,
|
|
|
|
RPC_INPUTS_EVENTS_TYPES,
|
|
|
|
RPC_RECONNECT_INTERVAL,
|
|
|
|
RPC_SENSORS_POLLING_INTERVAL,
|
|
|
|
SHBTN_MODELS,
|
|
|
|
SLEEP_PERIOD_MULTIPLIER,
|
|
|
|
UPDATE_PERIOD_MULTIPLIER,
|
2022-11-15 18:34:45 +00:00
|
|
|
BLEScannerMode,
|
2022-10-04 19:29:07 +00:00
|
|
|
)
|
2024-01-05 23:32:04 +00:00
|
|
|
from .utils import (
|
2024-04-14 15:07:26 +00:00
|
|
|
async_create_issue_unsupported_firmware,
|
|
|
|
get_block_device_sleep_period,
|
2024-01-05 23:32:04 +00:00
|
|
|
get_device_entry_gen,
|
2024-03-21 18:58:56 +00:00
|
|
|
get_http_port,
|
2024-01-05 23:32:04 +00:00
|
|
|
get_rpc_device_wakeup_period,
|
|
|
|
update_device_fw_info,
|
|
|
|
)
|
2023-01-20 07:43:01 +00:00
|
|
|
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2022-10-06 07:10:58 +00:00
|
|
|
@dataclass
|
|
|
|
class ShellyEntryData:
|
|
|
|
"""Class for sharing data within a given config entry."""
|
|
|
|
|
|
|
|
block: ShellyBlockCoordinator | None = None
|
|
|
|
rest: ShellyRestCoordinator | None = None
|
|
|
|
rpc: ShellyRpcCoordinator | None = None
|
|
|
|
rpc_poll: ShellyRpcPollingCoordinator | None = None
|
|
|
|
|
|
|
|
|
2024-05-17 13:42:58 +00:00
|
|
|
type ShellyConfigEntry = ConfigEntry[ShellyEntryData]
|
2022-10-06 07:10:58 +00:00
|
|
|
|
|
|
|
|
2024-05-20 08:43:59 +00:00
|
|
|
class ShellyCoordinatorBase[_DeviceT: BlockDevice | RpcDevice](
|
|
|
|
DataUpdateCoordinator[None]
|
|
|
|
):
|
2023-01-20 07:43:01 +00:00
|
|
|
"""Coordinator for a Shelly device."""
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
def __init__(
|
2023-01-20 07:43:01 +00:00
|
|
|
self,
|
|
|
|
hass: HomeAssistant,
|
2024-05-04 10:41:25 +00:00
|
|
|
entry: ShellyConfigEntry,
|
2023-01-20 07:43:01 +00:00
|
|
|
device: _DeviceT,
|
|
|
|
update_interval: float,
|
2022-10-04 19:29:07 +00:00
|
|
|
) -> None:
|
2023-01-20 07:43:01 +00:00
|
|
|
"""Initialize the Shelly device coordinator."""
|
2022-10-04 19:29:07 +00:00
|
|
|
self.entry = entry
|
|
|
|
self.device = device
|
2023-01-20 07:43:01 +00:00
|
|
|
self.device_id: str | None = None
|
2024-04-14 15:07:26 +00:00
|
|
|
self._pending_platforms: list[Platform] | None = None
|
2023-01-27 08:47:05 +00:00
|
|
|
device_name = device.name if device.initialized else entry.title
|
2023-01-20 07:43:01 +00:00
|
|
|
interval_td = timedelta(seconds=update_interval)
|
|
|
|
super().__init__(hass, LOGGER, name=device_name, update_interval=interval_td)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
self._debounced_reload: Debouncer[Coroutine[Any, Any, None]] = Debouncer(
|
|
|
|
hass,
|
|
|
|
LOGGER,
|
|
|
|
cooldown=ENTRY_RELOAD_COOLDOWN,
|
|
|
|
immediate=False,
|
|
|
|
function=self._async_reload_entry,
|
|
|
|
)
|
2023-05-04 08:34:15 +00:00
|
|
|
entry.async_on_unload(self._debounced_reload.async_shutdown)
|
2023-01-20 07:43:01 +00:00
|
|
|
|
2024-05-19 17:25:12 +00:00
|
|
|
entry.async_on_unload(
|
|
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._handle_ha_stop)
|
|
|
|
)
|
|
|
|
|
2023-01-20 07:43:01 +00:00
|
|
|
@property
|
|
|
|
def model(self) -> str:
|
|
|
|
"""Model of the device."""
|
|
|
|
return cast(str, self.entry.data["model"])
|
|
|
|
|
|
|
|
@property
|
|
|
|
def mac(self) -> str:
|
|
|
|
"""Mac address of the device."""
|
|
|
|
return cast(str, self.entry.unique_id)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def sw_version(self) -> str:
|
|
|
|
"""Firmware version of the device."""
|
|
|
|
return self.device.firmware_version if self.device.initialized else ""
|
|
|
|
|
|
|
|
@property
|
|
|
|
def sleep_period(self) -> int:
|
|
|
|
"""Sleep period of the device."""
|
|
|
|
return self.entry.data.get(CONF_SLEEP_PERIOD, 0)
|
|
|
|
|
2024-04-14 15:07:26 +00:00
|
|
|
def async_setup(self, pending_platforms: list[Platform] | None = None) -> None:
|
2023-01-20 07:43:01 +00:00
|
|
|
"""Set up the coordinator."""
|
2024-04-14 15:07:26 +00:00
|
|
|
self._pending_platforms = pending_platforms
|
2024-05-27 10:50:11 +00:00
|
|
|
dev_reg = dr.async_get(self.hass)
|
2023-01-20 07:43:01 +00:00
|
|
|
device_entry = dev_reg.async_get_or_create(
|
|
|
|
config_entry_id=self.entry.entry_id,
|
|
|
|
name=self.name,
|
2023-01-21 23:26:54 +00:00
|
|
|
connections={(CONNECTION_NETWORK_MAC, self.mac)},
|
2023-01-20 07:43:01 +00:00
|
|
|
manufacturer="Shelly",
|
2024-01-30 08:47:52 +00:00
|
|
|
model=MODEL_NAMES.get(self.model, self.model),
|
2023-01-20 07:43:01 +00:00
|
|
|
sw_version=self.sw_version,
|
2024-01-05 23:32:04 +00:00
|
|
|
hw_version=f"gen{get_device_entry_gen(self.entry)} ({self.model})",
|
2024-03-21 18:58:56 +00:00
|
|
|
configuration_url=f"http://{self.entry.data[CONF_HOST]}:{get_http_port(self.entry.data)}",
|
2023-01-20 07:43:01 +00:00
|
|
|
)
|
|
|
|
self.device_id = device_entry.id
|
|
|
|
|
2024-05-19 17:25:12 +00:00
|
|
|
async def shutdown(self) -> None:
|
|
|
|
"""Shutdown the coordinator."""
|
|
|
|
await self.device.shutdown()
|
|
|
|
|
|
|
|
async def _handle_ha_stop(self, _event: Event) -> None:
|
|
|
|
"""Handle Home Assistant stopping."""
|
|
|
|
LOGGER.debug("Stopping RPC device coordinator for %s", self.name)
|
|
|
|
await self.shutdown()
|
|
|
|
|
2024-04-29 13:03:57 +00:00
|
|
|
async def _async_device_connect_task(self) -> bool:
|
|
|
|
"""Connect to a Shelly device task."""
|
2024-04-14 15:07:26 +00:00
|
|
|
LOGGER.debug("Connecting to Shelly Device - %s", self.name)
|
|
|
|
try:
|
|
|
|
await self.device.initialize()
|
|
|
|
update_device_fw_info(self.hass, self.device, self.entry)
|
|
|
|
except DeviceConnectionError as err:
|
2024-04-29 13:03:57 +00:00
|
|
|
LOGGER.debug(
|
|
|
|
"Error connecting to Shelly device %s, error: %r", self.name, err
|
|
|
|
)
|
|
|
|
return False
|
2024-04-14 15:07:26 +00:00
|
|
|
except InvalidAuthError:
|
|
|
|
self.entry.async_start_reauth(self.hass)
|
2024-04-29 13:03:57 +00:00
|
|
|
return False
|
2024-04-14 15:07:26 +00:00
|
|
|
|
|
|
|
if not self.device.firmware_supported:
|
|
|
|
async_create_issue_unsupported_firmware(self.hass, self.entry)
|
2024-04-29 13:03:57 +00:00
|
|
|
return False
|
2024-04-14 15:07:26 +00:00
|
|
|
|
|
|
|
if not self._pending_platforms:
|
2024-04-29 13:03:57 +00:00
|
|
|
return True
|
2024-04-14 15:07:26 +00:00
|
|
|
|
|
|
|
LOGGER.debug("Device %s is online, resuming setup", self.entry.title)
|
|
|
|
platforms = self._pending_platforms
|
|
|
|
self._pending_platforms = None
|
|
|
|
|
|
|
|
data = {**self.entry.data}
|
|
|
|
|
|
|
|
# Update sleep_period
|
|
|
|
old_sleep_period = data[CONF_SLEEP_PERIOD]
|
|
|
|
if isinstance(self.device, RpcDevice):
|
|
|
|
new_sleep_period = get_rpc_device_wakeup_period(self.device.status)
|
|
|
|
elif isinstance(self.device, BlockDevice):
|
|
|
|
new_sleep_period = get_block_device_sleep_period(self.device.settings)
|
|
|
|
|
|
|
|
if new_sleep_period != old_sleep_period:
|
|
|
|
data[CONF_SLEEP_PERIOD] = new_sleep_period
|
|
|
|
self.hass.config_entries.async_update_entry(self.entry, data=data)
|
|
|
|
|
|
|
|
# Resume platform setup
|
Ensure config entries are not unloaded while their platforms are setting up (#118767)
* Report non-awaited/non-locked config entry platform forwards
Its currently possible for config entries to be reloaded while their platforms
are being forwarded if platform forwards are not awaited or done after the
config entry is setup since the lock will not be held in this case.
In https://developers.home-assistant.io/blog/2022/07/08/config_entry_forwards
we advised to await platform forwards to ensure this does not happen, however
for sleeping devices and late discovered devices, platform forwards may happen
later.
If config platform forwards are happening during setup, they should be awaited
If config entry platform forwards are not happening during setup, instead
async_late_forward_entry_setups should be used which will hold the lock to
prevent the config entry from being unloaded while its platforms are being
setup
* Report non-awaited/non-locked config entry platform forwards
Its currently possible for config entries to be reloaded while their platforms
are being forwarded if platform forwards are not awaited or done after the
config entry is setup since the lock will not be held in this case.
In https://developers.home-assistant.io/blog/2022/07/08/config_entry_forwards
we advised to await platform forwards to ensure this does not happen, however
for sleeping devices and late discovered devices, platform forwards may happen
later.
If config platform forwards are happening during setup, they should be awaited
If config entry platform forwards are not happening during setup, instead
async_late_forward_entry_setups should be used which will hold the lock to
prevent the config entry from being unloaded while its platforms are being
setup
* run with error on to find them
* cert_exp, hold lock
* cert_exp, hold lock
* shelly async_late_forward_entry_setups
* compact
* compact
* found another
* patch up mobileapp
* patch up hue tests
* patch up smartthings
* fix mqtt
* fix esphome
* zwave_js
* mqtt
* rework
* fixes
* fix mocking
* fix mocking
* do not call async_forward_entry_setup directly
* docstrings
* docstrings
* docstrings
* add comments
* doc strings
* fixed all in core, turn off strict
* coverage
* coverage
* missing
* coverage
2024-06-05 01:34:39 +00:00
|
|
|
await self.hass.config_entries.async_late_forward_entry_setups(
|
|
|
|
self.entry, platforms
|
|
|
|
)
|
2024-04-14 15:07:26 +00:00
|
|
|
|
2024-04-29 13:03:57 +00:00
|
|
|
return True
|
|
|
|
|
2023-01-20 07:43:01 +00:00
|
|
|
async def _async_reload_entry(self) -> None:
|
|
|
|
"""Reload entry."""
|
|
|
|
self._debounced_reload.async_cancel()
|
|
|
|
LOGGER.debug("Reloading entry %s", self.name)
|
|
|
|
await self.hass.config_entries.async_reload(self.entry.entry_id)
|
|
|
|
|
2024-03-25 21:27:44 +00:00
|
|
|
async def async_shutdown_device_and_start_reauth(self) -> None:
|
|
|
|
"""Shutdown Shelly device and start reauth flow."""
|
|
|
|
# not running disconnect events since we have auth error
|
|
|
|
# and won't be able to send commands to the device
|
|
|
|
self.last_update_success = False
|
2024-05-19 17:25:12 +00:00
|
|
|
await self.shutdown()
|
2024-03-25 21:27:44 +00:00
|
|
|
self.entry.async_start_reauth(self.hass)
|
|
|
|
|
2023-01-20 07:43:01 +00:00
|
|
|
|
|
|
|
class ShellyBlockCoordinator(ShellyCoordinatorBase[BlockDevice]):
|
|
|
|
"""Coordinator for a Shelly block based device."""
|
|
|
|
|
|
|
|
def __init__(
|
2024-05-04 10:41:25 +00:00
|
|
|
self, hass: HomeAssistant, entry: ShellyConfigEntry, device: BlockDevice
|
2023-01-20 07:43:01 +00:00
|
|
|
) -> None:
|
|
|
|
"""Initialize the Shelly block device coordinator."""
|
|
|
|
self.entry = entry
|
|
|
|
if self.sleep_period:
|
|
|
|
update_interval = SLEEP_PERIOD_MULTIPLIER * self.sleep_period
|
|
|
|
else:
|
|
|
|
update_interval = (
|
|
|
|
UPDATE_PERIOD_MULTIPLIER * device.settings["coiot"]["update_period"]
|
|
|
|
)
|
|
|
|
super().__init__(hass, entry, device, update_interval)
|
|
|
|
|
2022-10-04 19:29:07 +00:00
|
|
|
self._last_cfg_changed: int | None = None
|
|
|
|
self._last_mode: str | None = None
|
2024-04-14 15:07:26 +00:00
|
|
|
self._last_effect: str | None = None
|
2023-01-20 07:43:01 +00:00
|
|
|
self._last_input_events_count: dict = {}
|
2023-02-15 09:21:53 +00:00
|
|
|
self._last_target_temp: float | None = None
|
2023-07-20 11:11:05 +00:00
|
|
|
self._push_update_failures: int = 0
|
2023-09-23 14:03:57 +00:00
|
|
|
self._input_event_listeners: list[Callable[[dict[str, Any]], None]] = []
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
entry.async_on_unload(
|
|
|
|
self.async_add_listener(self._async_device_updates_handler)
|
|
|
|
)
|
|
|
|
|
2023-09-23 14:03:57 +00:00
|
|
|
@callback
|
|
|
|
def async_subscribe_input_events(
|
|
|
|
self, input_event_callback: Callable[[dict[str, Any]], None]
|
|
|
|
) -> CALLBACK_TYPE:
|
|
|
|
"""Subscribe to input events."""
|
|
|
|
|
|
|
|
def _unsubscribe() -> None:
|
|
|
|
self._input_event_listeners.remove(input_event_callback)
|
|
|
|
|
|
|
|
self._input_event_listeners.append(input_event_callback)
|
|
|
|
|
|
|
|
return _unsubscribe
|
|
|
|
|
2022-10-04 19:29:07 +00:00
|
|
|
@callback
|
|
|
|
def _async_device_updates_handler(self) -> None:
|
|
|
|
"""Handle device updates."""
|
|
|
|
if not self.device.initialized:
|
|
|
|
return
|
|
|
|
|
|
|
|
# For buttons which are battery powered - set initial value for last_event_count
|
|
|
|
if self.model in SHBTN_MODELS and self._last_input_events_count.get(1) is None:
|
|
|
|
for block in self.device.blocks:
|
|
|
|
if block.type != "device":
|
|
|
|
continue
|
|
|
|
|
2024-04-14 15:07:26 +00:00
|
|
|
wakeup_event = cast(list, block.wakeupEvent)
|
|
|
|
if len(wakeup_event) == 1 and wakeup_event[0] == "button":
|
2022-10-04 19:29:07 +00:00
|
|
|
self._last_input_events_count[1] = -1
|
|
|
|
|
|
|
|
break
|
|
|
|
|
|
|
|
# Check for input events and config change
|
|
|
|
cfg_changed = 0
|
|
|
|
for block in self.device.blocks:
|
2024-03-16 14:18:41 +00:00
|
|
|
if block.type == "device" and block.cfgChanged is not None:
|
2024-04-14 15:07:26 +00:00
|
|
|
cfg_changed = cast(int, block.cfgChanged)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2023-04-25 20:20:59 +00:00
|
|
|
# Shelly TRV sends information about changing the configuration for no
|
|
|
|
# reason, reloading the config entry is not needed for it.
|
2023-11-24 18:55:00 +00:00
|
|
|
if self.model == MODEL_VALVE:
|
2023-04-25 20:20:59 +00:00
|
|
|
self._last_cfg_changed = None
|
2023-02-15 09:21:53 +00:00
|
|
|
|
2022-10-04 19:29:07 +00:00
|
|
|
# For dual mode bulbs ignore change if it is due to mode/effect change
|
|
|
|
if self.model in DUAL_MODE_LIGHT_MODELS:
|
|
|
|
if "mode" in block.sensor_ids:
|
|
|
|
if self._last_mode != block.mode:
|
|
|
|
self._last_cfg_changed = None
|
|
|
|
self._last_mode = block.mode
|
|
|
|
|
|
|
|
if self.model in MODELS_SUPPORTING_LIGHT_EFFECTS:
|
|
|
|
if "effect" in block.sensor_ids:
|
|
|
|
if self._last_effect != block.effect:
|
|
|
|
self._last_cfg_changed = None
|
|
|
|
self._last_effect = block.effect
|
|
|
|
|
|
|
|
if (
|
|
|
|
"inputEvent" not in block.sensor_ids
|
|
|
|
or "inputEventCnt" not in block.sensor_ids
|
|
|
|
):
|
2022-11-24 18:07:19 +00:00
|
|
|
LOGGER.debug("Skipping non-input event block %s", block.description)
|
2022-10-04 19:29:07 +00:00
|
|
|
continue
|
|
|
|
|
|
|
|
channel = int(block.channel or 0) + 1
|
|
|
|
event_type = block.inputEvent
|
|
|
|
last_event_count = self._last_input_events_count.get(channel)
|
|
|
|
self._last_input_events_count[channel] = block.inputEventCnt
|
|
|
|
|
|
|
|
if (
|
|
|
|
last_event_count is None
|
|
|
|
or last_event_count == block.inputEventCnt
|
|
|
|
or event_type == ""
|
|
|
|
):
|
2022-11-24 18:07:19 +00:00
|
|
|
LOGGER.debug("Skipping block event %s", event_type)
|
2022-10-04 19:29:07 +00:00
|
|
|
continue
|
|
|
|
|
|
|
|
if event_type in INPUTS_EVENTS_DICT:
|
2023-09-23 14:03:57 +00:00
|
|
|
for event_callback in self._input_event_listeners:
|
|
|
|
event_callback(
|
|
|
|
{"channel": channel, "event": INPUTS_EVENTS_DICT[event_type]}
|
|
|
|
)
|
2022-10-04 19:29:07 +00:00
|
|
|
self.hass.bus.async_fire(
|
|
|
|
EVENT_SHELLY_CLICK,
|
|
|
|
{
|
|
|
|
ATTR_DEVICE_ID: self.device_id,
|
|
|
|
ATTR_DEVICE: self.device.settings["device"]["hostname"],
|
|
|
|
ATTR_CHANNEL: channel,
|
|
|
|
ATTR_CLICK_TYPE: INPUTS_EVENTS_DICT[event_type],
|
|
|
|
ATTR_GENERATION: 1,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
if self._last_cfg_changed is not None and cfg_changed > self._last_cfg_changed:
|
|
|
|
LOGGER.info(
|
|
|
|
"Config for %s changed, reloading entry in %s seconds",
|
|
|
|
self.name,
|
|
|
|
ENTRY_RELOAD_COOLDOWN,
|
|
|
|
)
|
2024-02-21 15:47:36 +00:00
|
|
|
self._debounced_reload.async_schedule_call()
|
2022-10-04 19:29:07 +00:00
|
|
|
self._last_cfg_changed = cfg_changed
|
|
|
|
|
|
|
|
async def _async_update_data(self) -> None:
|
|
|
|
"""Fetch data."""
|
2023-01-20 07:43:01 +00:00
|
|
|
if self.sleep_period:
|
2022-10-04 19:29:07 +00:00
|
|
|
# Sleeping device, no point polling it, just mark it unavailable
|
2022-10-05 12:39:58 +00:00
|
|
|
raise UpdateFailed(
|
2023-01-20 07:43:01 +00:00
|
|
|
f"Sleeping device did not update within {self.sleep_period} seconds interval"
|
2022-10-04 19:29:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
LOGGER.debug("Polling Shelly Block Device - %s", self.name)
|
|
|
|
try:
|
2022-10-20 12:08:48 +00:00
|
|
|
await self.device.update()
|
|
|
|
except DeviceConnectionError as err:
|
2024-05-08 21:54:49 +00:00
|
|
|
raise UpdateFailed(f"Error fetching data: {err!r}") from err
|
2022-10-20 12:08:48 +00:00
|
|
|
except InvalidAuthError:
|
2024-03-25 21:27:44 +00:00
|
|
|
await self.async_shutdown_device_and_start_reauth()
|
2023-08-21 20:27:36 +00:00
|
|
|
|
|
|
|
@callback
|
|
|
|
def _async_handle_update(
|
|
|
|
self, device_: BlockDevice, update_type: BlockUpdateType
|
|
|
|
) -> None:
|
|
|
|
"""Handle device update."""
|
2024-05-18 23:05:51 +00:00
|
|
|
LOGGER.debug("Shelly %s handle update, type: %s", self.name, update_type)
|
2024-04-14 15:07:26 +00:00
|
|
|
if update_type is BlockUpdateType.ONLINE:
|
2024-04-28 16:19:38 +00:00
|
|
|
self.entry.async_create_background_task(
|
|
|
|
self.hass,
|
2024-04-29 13:03:57 +00:00
|
|
|
self._async_device_connect_task(),
|
2024-04-28 16:19:38 +00:00
|
|
|
"block device online",
|
|
|
|
eager_start=True,
|
|
|
|
)
|
2024-04-14 15:07:26 +00:00
|
|
|
elif update_type is BlockUpdateType.COAP_PERIODIC:
|
2023-08-21 20:27:36 +00:00
|
|
|
self._push_update_failures = 0
|
|
|
|
ir.async_delete_issue(
|
|
|
|
self.hass,
|
|
|
|
DOMAIN,
|
|
|
|
PUSH_UPDATE_ISSUE_ID.format(unique=self.mac),
|
|
|
|
)
|
2024-04-14 15:07:26 +00:00
|
|
|
elif update_type is BlockUpdateType.COAP_REPLY:
|
2023-07-20 11:11:05 +00:00
|
|
|
self._push_update_failures += 1
|
2023-08-21 20:27:36 +00:00
|
|
|
if self._push_update_failures == MAX_PUSH_UPDATE_FAILURES:
|
2023-07-20 11:11:05 +00:00
|
|
|
LOGGER.debug(
|
|
|
|
"Creating issue %s", PUSH_UPDATE_ISSUE_ID.format(unique=self.mac)
|
|
|
|
)
|
|
|
|
ir.async_create_issue(
|
|
|
|
self.hass,
|
|
|
|
DOMAIN,
|
|
|
|
PUSH_UPDATE_ISSUE_ID.format(unique=self.mac),
|
|
|
|
is_fixable=False,
|
|
|
|
is_persistent=False,
|
|
|
|
severity=ir.IssueSeverity.ERROR,
|
|
|
|
learn_more_url="https://www.home-assistant.io/integrations/shelly/#shelly-device-configuration-generation-1",
|
|
|
|
translation_key="push_update_failure",
|
|
|
|
translation_placeholders={
|
|
|
|
"device_name": self.entry.title,
|
|
|
|
"ip_address": self.device.ip_address,
|
|
|
|
},
|
|
|
|
)
|
2023-08-21 20:27:36 +00:00
|
|
|
LOGGER.debug(
|
|
|
|
"Push update failures for %s: %s", self.name, self._push_update_failures
|
|
|
|
)
|
2023-08-21 07:49:11 +00:00
|
|
|
self.async_set_updated_data(None)
|
|
|
|
|
2024-04-14 15:07:26 +00:00
|
|
|
def async_setup(self, pending_platforms: list[Platform] | None = None) -> None:
|
2022-10-05 12:39:58 +00:00
|
|
|
"""Set up the coordinator."""
|
2024-04-14 15:07:26 +00:00
|
|
|
super().async_setup(pending_platforms)
|
2023-08-21 07:49:11 +00:00
|
|
|
self.device.subscribe_updates(self._async_handle_update)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
|
2023-01-20 07:43:01 +00:00
|
|
|
class ShellyRestCoordinator(ShellyCoordinatorBase[BlockDevice]):
|
2022-10-05 12:39:58 +00:00
|
|
|
"""Coordinator for a Shelly REST device."""
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
def __init__(
|
2024-05-04 10:41:25 +00:00
|
|
|
self, hass: HomeAssistant, device: BlockDevice, entry: ShellyConfigEntry
|
2022-10-04 19:29:07 +00:00
|
|
|
) -> None:
|
2022-10-05 12:39:58 +00:00
|
|
|
"""Initialize the Shelly REST device coordinator."""
|
2023-01-20 07:43:01 +00:00
|
|
|
update_interval = REST_SENSORS_UPDATE_INTERVAL
|
2022-10-04 19:29:07 +00:00
|
|
|
if (
|
|
|
|
device.settings["device"]["type"]
|
|
|
|
in BATTERY_DEVICES_WITH_PERMANENT_CONNECTION
|
|
|
|
):
|
|
|
|
update_interval = (
|
|
|
|
SLEEP_PERIOD_MULTIPLIER * device.settings["coiot"]["update_period"]
|
|
|
|
)
|
2023-01-20 07:43:01 +00:00
|
|
|
super().__init__(hass, entry, device, update_interval)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
async def _async_update_data(self) -> None:
|
|
|
|
"""Fetch data."""
|
2022-10-20 12:08:48 +00:00
|
|
|
LOGGER.debug("REST update for %s", self.name)
|
2022-10-04 19:29:07 +00:00
|
|
|
try:
|
2022-10-20 12:08:48 +00:00
|
|
|
await self.device.update_status()
|
|
|
|
|
|
|
|
if self.device.status["uptime"] > 2 * REST_SENSORS_UPDATE_INTERVAL:
|
|
|
|
return
|
|
|
|
await self.device.update_shelly()
|
|
|
|
except DeviceConnectionError as err:
|
2024-05-08 21:54:49 +00:00
|
|
|
raise UpdateFailed(f"Error fetching data: {err!r}") from err
|
2022-10-20 12:08:48 +00:00
|
|
|
except InvalidAuthError:
|
2024-03-25 21:27:44 +00:00
|
|
|
await self.async_shutdown_device_and_start_reauth()
|
2022-10-20 12:08:48 +00:00
|
|
|
else:
|
2023-10-04 09:00:17 +00:00
|
|
|
update_device_fw_info(self.hass, self.device, self.entry)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
|
2023-01-20 07:43:01 +00:00
|
|
|
class ShellyRpcCoordinator(ShellyCoordinatorBase[RpcDevice]):
|
2022-10-05 12:39:58 +00:00
|
|
|
"""Coordinator for a Shelly RPC based device."""
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
def __init__(
|
2024-05-04 10:41:25 +00:00
|
|
|
self, hass: HomeAssistant, entry: ShellyConfigEntry, device: RpcDevice
|
2022-10-04 19:29:07 +00:00
|
|
|
) -> None:
|
2022-10-05 12:39:58 +00:00
|
|
|
"""Initialize the Shelly RPC device coordinator."""
|
2023-01-20 07:43:01 +00:00
|
|
|
self.entry = entry
|
|
|
|
if self.sleep_period:
|
|
|
|
update_interval = SLEEP_PERIOD_MULTIPLIER * self.sleep_period
|
2022-10-18 19:42:22 +00:00
|
|
|
else:
|
|
|
|
update_interval = RPC_RECONNECT_INTERVAL
|
2023-01-20 07:43:01 +00:00
|
|
|
super().__init__(hass, entry, device, update_interval)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2023-01-20 07:43:01 +00:00
|
|
|
self.connected = False
|
2022-11-15 18:34:45 +00:00
|
|
|
self._disconnected_callbacks: list[CALLBACK_TYPE] = []
|
|
|
|
self._connection_lock = asyncio.Lock()
|
2022-11-14 18:58:10 +00:00
|
|
|
self._event_listeners: list[Callable[[dict[str, Any]], None]] = []
|
2023-09-06 06:17:45 +00:00
|
|
|
self._ota_event_listeners: list[Callable[[dict[str, Any]], None]] = []
|
2023-09-17 22:38:08 +00:00
|
|
|
self._input_event_listeners: list[Callable[[dict[str, Any]], None]] = []
|
2023-01-20 07:43:01 +00:00
|
|
|
|
2022-11-15 18:34:45 +00:00
|
|
|
entry.async_on_unload(entry.add_update_listener(self._async_update_listener))
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2022-10-28 16:48:27 +00:00
|
|
|
def update_sleep_period(self) -> bool:
|
|
|
|
"""Check device sleep period & update if changed."""
|
|
|
|
if (
|
|
|
|
not self.device.initialized
|
|
|
|
or not (wakeup_period := get_rpc_device_wakeup_period(self.device.status))
|
2023-01-20 07:43:01 +00:00
|
|
|
or wakeup_period == self.sleep_period
|
2022-10-28 16:48:27 +00:00
|
|
|
):
|
|
|
|
return False
|
|
|
|
|
|
|
|
data = {**self.entry.data}
|
|
|
|
data[CONF_SLEEP_PERIOD] = wakeup_period
|
|
|
|
self.hass.config_entries.async_update_entry(self.entry, data=data)
|
|
|
|
|
|
|
|
update_interval = SLEEP_PERIOD_MULTIPLIER * wakeup_period
|
|
|
|
self.update_interval = timedelta(seconds=update_interval)
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
2023-09-06 06:17:45 +00:00
|
|
|
@callback
|
|
|
|
def async_subscribe_ota_events(
|
|
|
|
self, ota_event_callback: Callable[[dict[str, Any]], None]
|
|
|
|
) -> CALLBACK_TYPE:
|
|
|
|
"""Subscribe to OTA events."""
|
|
|
|
|
|
|
|
def _unsubscribe() -> None:
|
|
|
|
self._ota_event_listeners.remove(ota_event_callback)
|
|
|
|
|
|
|
|
self._ota_event_listeners.append(ota_event_callback)
|
|
|
|
|
|
|
|
return _unsubscribe
|
|
|
|
|
2023-09-17 22:38:08 +00:00
|
|
|
@callback
|
|
|
|
def async_subscribe_input_events(
|
|
|
|
self, input_event_callback: Callable[[dict[str, Any]], None]
|
|
|
|
) -> CALLBACK_TYPE:
|
|
|
|
"""Subscribe to input events."""
|
|
|
|
|
|
|
|
def _unsubscribe() -> None:
|
|
|
|
self._input_event_listeners.remove(input_event_callback)
|
|
|
|
|
|
|
|
self._input_event_listeners.append(input_event_callback)
|
|
|
|
|
|
|
|
return _unsubscribe
|
|
|
|
|
2022-10-04 19:29:07 +00:00
|
|
|
@callback
|
2022-11-14 18:58:10 +00:00
|
|
|
def async_subscribe_events(
|
|
|
|
self, event_callback: Callable[[dict[str, Any]], None]
|
|
|
|
) -> CALLBACK_TYPE:
|
|
|
|
"""Subscribe to events."""
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2022-11-14 18:58:10 +00:00
|
|
|
def _unsubscribe() -> None:
|
|
|
|
self._event_listeners.remove(event_callback)
|
2022-10-28 16:48:27 +00:00
|
|
|
|
2022-11-14 18:58:10 +00:00
|
|
|
self._event_listeners.append(event_callback)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2022-11-14 18:58:10 +00:00
|
|
|
return _unsubscribe
|
|
|
|
|
2022-11-15 18:34:45 +00:00
|
|
|
async def _async_update_listener(
|
2024-05-04 10:41:25 +00:00
|
|
|
self, hass: HomeAssistant, entry: ShellyConfigEntry
|
2022-11-15 18:34:45 +00:00
|
|
|
) -> None:
|
|
|
|
"""Reconfigure on update."""
|
|
|
|
async with self._connection_lock:
|
|
|
|
if self.connected:
|
|
|
|
self._async_run_disconnected_events()
|
|
|
|
await self._async_run_connected_events()
|
|
|
|
|
2022-11-14 18:58:10 +00:00
|
|
|
@callback
|
|
|
|
def _async_device_event_handler(self, event_data: dict[str, Any]) -> None:
|
|
|
|
"""Handle device events."""
|
|
|
|
events: list[dict[str, Any]] = event_data["events"]
|
|
|
|
for event in events:
|
2022-10-04 19:29:07 +00:00
|
|
|
event_type = event.get("event")
|
|
|
|
if event_type is None:
|
|
|
|
continue
|
|
|
|
|
2022-11-14 18:58:10 +00:00
|
|
|
for event_callback in self._event_listeners:
|
|
|
|
event_callback(event)
|
|
|
|
|
2022-10-04 19:29:07 +00:00
|
|
|
if event_type == "config_changed":
|
2022-11-15 18:34:45 +00:00
|
|
|
self.update_sleep_period()
|
2022-10-04 19:29:07 +00:00
|
|
|
LOGGER.info(
|
|
|
|
"Config for %s changed, reloading entry in %s seconds",
|
|
|
|
self.name,
|
|
|
|
ENTRY_RELOAD_COOLDOWN,
|
|
|
|
)
|
2024-02-21 15:47:36 +00:00
|
|
|
self._debounced_reload.async_schedule_call()
|
2022-10-04 19:29:07 +00:00
|
|
|
elif event_type in RPC_INPUTS_EVENTS_TYPES:
|
2023-09-17 22:38:08 +00:00
|
|
|
for event_callback in self._input_event_listeners:
|
|
|
|
event_callback(event)
|
2022-10-04 19:29:07 +00:00
|
|
|
self.hass.bus.async_fire(
|
|
|
|
EVENT_SHELLY_CLICK,
|
|
|
|
{
|
|
|
|
ATTR_DEVICE_ID: self.device_id,
|
|
|
|
ATTR_DEVICE: self.device.hostname,
|
|
|
|
ATTR_CHANNEL: event["id"] + 1,
|
|
|
|
ATTR_CLICK_TYPE: event["event"],
|
|
|
|
ATTR_GENERATION: 2,
|
|
|
|
},
|
|
|
|
)
|
2023-09-06 06:17:45 +00:00
|
|
|
elif event_type in (OTA_BEGIN, OTA_ERROR, OTA_PROGRESS, OTA_SUCCESS):
|
|
|
|
for event_callback in self._ota_event_listeners:
|
|
|
|
event_callback(event)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
async def _async_update_data(self) -> None:
|
|
|
|
"""Fetch data."""
|
2022-10-28 16:48:27 +00:00
|
|
|
if self.update_sleep_period():
|
|
|
|
return
|
|
|
|
|
2023-01-20 07:43:01 +00:00
|
|
|
if self.sleep_period:
|
2022-10-18 19:42:22 +00:00
|
|
|
# Sleeping device, no point polling it, just mark it unavailable
|
|
|
|
raise UpdateFailed(
|
2023-01-20 07:43:01 +00:00
|
|
|
f"Sleeping device did not update within {self.sleep_period} seconds interval"
|
2022-10-18 19:42:22 +00:00
|
|
|
)
|
2022-10-04 19:29:07 +00:00
|
|
|
if self.device.connected:
|
|
|
|
return
|
|
|
|
|
2024-04-29 13:03:57 +00:00
|
|
|
if not await self._async_device_connect_task():
|
|
|
|
raise UpdateFailed("Device reconnect error")
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2024-05-18 23:05:51 +00:00
|
|
|
async def _async_disconnected(self, reconnect: bool) -> None:
|
2022-11-15 18:34:45 +00:00
|
|
|
"""Handle device disconnected."""
|
2023-01-20 07:43:01 +00:00
|
|
|
# Sleeping devices send data and disconnect
|
2023-01-18 23:11:40 +00:00
|
|
|
# There are no disconnect events for sleeping devices
|
2023-01-20 07:43:01 +00:00
|
|
|
if self.sleep_period:
|
2023-01-18 23:11:40 +00:00
|
|
|
return
|
|
|
|
|
2022-11-15 18:34:45 +00:00
|
|
|
async with self._connection_lock:
|
|
|
|
if not self.connected: # Already disconnected
|
|
|
|
return
|
|
|
|
self.connected = False
|
|
|
|
self._async_run_disconnected_events()
|
2024-05-18 23:05:51 +00:00
|
|
|
# Try to reconnect right away if triggered by disconnect event
|
|
|
|
if reconnect:
|
2022-12-12 07:33:58 +00:00
|
|
|
await self.async_request_refresh()
|
2022-11-15 18:34:45 +00:00
|
|
|
|
2022-11-14 18:58:10 +00:00
|
|
|
@callback
|
2022-11-15 18:34:45 +00:00
|
|
|
def _async_run_disconnected_events(self) -> None:
|
|
|
|
"""Run disconnected events.
|
|
|
|
|
|
|
|
This will be executed on disconnect or when the config entry
|
|
|
|
is updated.
|
|
|
|
"""
|
|
|
|
for disconnected_callback in self._disconnected_callbacks:
|
|
|
|
disconnected_callback()
|
|
|
|
self._disconnected_callbacks.clear()
|
|
|
|
|
|
|
|
async def _async_connected(self) -> None:
|
|
|
|
"""Handle device connected."""
|
|
|
|
async with self._connection_lock:
|
|
|
|
if self.connected: # Already connected
|
|
|
|
return
|
|
|
|
self.connected = True
|
|
|
|
await self._async_run_connected_events()
|
|
|
|
|
|
|
|
async def _async_run_connected_events(self) -> None:
|
|
|
|
"""Run connected events.
|
|
|
|
|
|
|
|
This will be executed on connect or when the config entry
|
|
|
|
is updated.
|
|
|
|
"""
|
2023-01-20 07:43:01 +00:00
|
|
|
if not self.sleep_period:
|
2023-01-09 22:16:14 +00:00
|
|
|
await self._async_connect_ble_scanner()
|
2022-11-15 18:34:45 +00:00
|
|
|
|
|
|
|
async def _async_connect_ble_scanner(self) -> None:
|
|
|
|
"""Connect BLE scanner."""
|
|
|
|
ble_scanner_mode = self.entry.options.get(
|
|
|
|
CONF_BLE_SCANNER_MODE, BLEScannerMode.DISABLED
|
|
|
|
)
|
2023-11-24 18:56:15 +00:00
|
|
|
if ble_scanner_mode == BLEScannerMode.DISABLED and self.connected:
|
2022-11-15 21:22:33 +00:00
|
|
|
await async_stop_scanner(self.device)
|
2022-11-14 18:58:10 +00:00
|
|
|
return
|
2022-11-15 21:37:45 +00:00
|
|
|
if await async_ensure_ble_enabled(self.device):
|
|
|
|
# BLE enable required a reboot, don't bother connecting
|
|
|
|
# the scanner since it will be disconnected anyway
|
|
|
|
return
|
2022-11-15 18:34:45 +00:00
|
|
|
self._disconnected_callbacks.append(
|
|
|
|
await async_connect_scanner(self.hass, self, ble_scanner_mode)
|
|
|
|
)
|
2022-11-14 18:58:10 +00:00
|
|
|
|
2022-11-15 18:34:45 +00:00
|
|
|
@callback
|
2023-08-21 07:49:11 +00:00
|
|
|
def _async_handle_update(
|
|
|
|
self, device_: RpcDevice, update_type: RpcUpdateType
|
|
|
|
) -> None:
|
2022-11-15 18:34:45 +00:00
|
|
|
"""Handle device update."""
|
2024-05-18 23:05:51 +00:00
|
|
|
LOGGER.debug("Shelly %s handle update, type: %s", self.name, update_type)
|
2024-04-14 15:07:26 +00:00
|
|
|
if update_type is RpcUpdateType.ONLINE:
|
2024-04-28 16:19:38 +00:00
|
|
|
self.entry.async_create_background_task(
|
|
|
|
self.hass,
|
2024-04-29 13:03:57 +00:00
|
|
|
self._async_device_connect_task(),
|
2024-04-28 16:19:38 +00:00
|
|
|
"rpc device online",
|
|
|
|
eager_start=True,
|
|
|
|
)
|
2024-04-14 15:07:26 +00:00
|
|
|
elif update_type is RpcUpdateType.INITIALIZED:
|
2024-04-28 16:19:38 +00:00
|
|
|
self.entry.async_create_background_task(
|
|
|
|
self.hass, self._async_connected(), "rpc device init", eager_start=True
|
|
|
|
)
|
2023-01-24 16:38:27 +00:00
|
|
|
self.async_set_updated_data(None)
|
2023-08-21 07:49:11 +00:00
|
|
|
elif update_type is RpcUpdateType.DISCONNECTED:
|
2024-04-28 16:19:38 +00:00
|
|
|
self.entry.async_create_background_task(
|
|
|
|
self.hass,
|
2024-05-18 23:05:51 +00:00
|
|
|
self._async_disconnected(True),
|
2024-04-28 16:19:38 +00:00
|
|
|
"rpc device disconnected",
|
|
|
|
eager_start=True,
|
|
|
|
)
|
2023-08-21 07:49:11 +00:00
|
|
|
elif update_type is RpcUpdateType.STATUS:
|
2022-12-27 21:50:57 +00:00
|
|
|
self.async_set_updated_data(None)
|
2023-10-04 09:00:17 +00:00
|
|
|
if self.sleep_period:
|
|
|
|
update_device_fw_info(self.hass, self.device, self.entry)
|
2023-08-21 07:49:11 +00:00
|
|
|
elif update_type is RpcUpdateType.EVENT and (event := self.device.event):
|
2022-11-14 18:58:10 +00:00
|
|
|
self._async_device_event_handler(event)
|
|
|
|
|
2024-04-14 15:07:26 +00:00
|
|
|
def async_setup(self, pending_platforms: list[Platform] | None = None) -> None:
|
2022-10-05 12:39:58 +00:00
|
|
|
"""Set up the coordinator."""
|
2024-04-14 15:07:26 +00:00
|
|
|
super().async_setup(pending_platforms)
|
2022-11-14 18:58:10 +00:00
|
|
|
self.device.subscribe_updates(self._async_handle_update)
|
2022-11-15 18:34:45 +00:00
|
|
|
if self.device.initialized:
|
|
|
|
# If we are already initialized, we are connected
|
2024-04-28 16:19:38 +00:00
|
|
|
self.entry.async_create_task(
|
|
|
|
self.hass, self._async_connected(), eager_start=True
|
|
|
|
)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
async def shutdown(self) -> None:
|
2022-10-05 12:39:58 +00:00
|
|
|
"""Shutdown the coordinator."""
|
2022-12-07 03:57:54 +00:00
|
|
|
if self.device.connected:
|
2023-06-14 21:00:21 +00:00
|
|
|
try:
|
|
|
|
await async_stop_scanner(self.device)
|
|
|
|
except InvalidAuthError:
|
2024-05-19 17:25:12 +00:00
|
|
|
self.entry.async_start_reauth(self.hass)
|
2024-03-25 21:27:44 +00:00
|
|
|
return
|
2024-05-19 17:25:12 +00:00
|
|
|
await super().shutdown()
|
2024-05-18 23:05:51 +00:00
|
|
|
await self._async_disconnected(False)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
|
2023-01-20 07:43:01 +00:00
|
|
|
class ShellyRpcPollingCoordinator(ShellyCoordinatorBase[RpcDevice]):
|
2022-10-05 12:39:58 +00:00
|
|
|
"""Polling coordinator for a Shelly RPC based device."""
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
def __init__(
|
2024-05-04 10:41:25 +00:00
|
|
|
self, hass: HomeAssistant, entry: ShellyConfigEntry, device: RpcDevice
|
2022-10-04 19:29:07 +00:00
|
|
|
) -> None:
|
|
|
|
"""Initialize the RPC polling coordinator."""
|
2023-01-20 07:43:01 +00:00
|
|
|
super().__init__(hass, entry, device, RPC_SENSORS_POLLING_INTERVAL)
|
2022-10-04 19:29:07 +00:00
|
|
|
|
|
|
|
async def _async_update_data(self) -> None:
|
|
|
|
"""Fetch data."""
|
|
|
|
if not self.device.connected:
|
2022-10-05 12:39:58 +00:00
|
|
|
raise UpdateFailed("Device disconnected")
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2022-10-20 12:08:48 +00:00
|
|
|
LOGGER.debug("Polling Shelly RPC Device - %s", self.name)
|
2022-10-04 19:29:07 +00:00
|
|
|
try:
|
2022-10-20 12:08:48 +00:00
|
|
|
await self.device.update_status()
|
2022-10-23 04:57:25 +00:00
|
|
|
except (DeviceConnectionError, RpcCallError) as err:
|
2024-05-08 21:54:49 +00:00
|
|
|
raise UpdateFailed(f"Device disconnected: {err!r}") from err
|
2022-10-20 12:08:48 +00:00
|
|
|
except InvalidAuthError:
|
2024-03-25 21:27:44 +00:00
|
|
|
await self.async_shutdown_device_and_start_reauth()
|
2022-10-04 19:29:07 +00:00
|
|
|
|
2022-10-06 07:10:58 +00:00
|
|
|
|
|
|
|
def get_block_coordinator_by_device_id(
|
|
|
|
hass: HomeAssistant, device_id: str
|
|
|
|
) -> ShellyBlockCoordinator | None:
|
|
|
|
"""Get a Shelly block device coordinator for the given device id."""
|
2024-05-27 10:50:11 +00:00
|
|
|
dev_reg = dr.async_get(hass)
|
2022-10-06 07:10:58 +00:00
|
|
|
if device := dev_reg.async_get(device_id):
|
|
|
|
for config_entry in device.config_entries:
|
2024-05-04 10:41:25 +00:00
|
|
|
entry = hass.config_entries.async_get_entry(config_entry)
|
|
|
|
if (
|
|
|
|
entry
|
2024-06-04 16:40:18 +00:00
|
|
|
and entry.state is ConfigEntryState.LOADED
|
|
|
|
and hasattr(entry, "runtime_data")
|
2024-05-04 10:41:25 +00:00
|
|
|
and isinstance(entry.runtime_data, ShellyEntryData)
|
|
|
|
and (coordinator := entry.runtime_data.block)
|
|
|
|
):
|
2022-10-06 07:10:58 +00:00
|
|
|
return coordinator
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def get_rpc_coordinator_by_device_id(
|
|
|
|
hass: HomeAssistant, device_id: str
|
|
|
|
) -> ShellyRpcCoordinator | None:
|
|
|
|
"""Get a Shelly RPC device coordinator for the given device id."""
|
2024-05-27 10:50:11 +00:00
|
|
|
dev_reg = dr.async_get(hass)
|
2022-10-06 07:10:58 +00:00
|
|
|
if device := dev_reg.async_get(device_id):
|
|
|
|
for config_entry in device.config_entries:
|
2024-05-04 10:41:25 +00:00
|
|
|
entry = hass.config_entries.async_get_entry(config_entry)
|
|
|
|
if (
|
|
|
|
entry
|
2024-06-04 16:40:18 +00:00
|
|
|
and entry.state is ConfigEntryState.LOADED
|
|
|
|
and hasattr(entry, "runtime_data")
|
2024-05-04 10:41:25 +00:00
|
|
|
and isinstance(entry.runtime_data, ShellyEntryData)
|
|
|
|
and (coordinator := entry.runtime_data.rpc)
|
|
|
|
):
|
2022-10-06 07:10:58 +00:00
|
|
|
return coordinator
|
|
|
|
|
|
|
|
return None
|
2022-12-14 00:22:34 +00:00
|
|
|
|
|
|
|
|
2024-05-04 10:41:25 +00:00
|
|
|
async def async_reconnect_soon(hass: HomeAssistant, entry: ShellyConfigEntry) -> None:
|
2022-12-14 00:22:34 +00:00
|
|
|
"""Try to reconnect soon."""
|
|
|
|
if (
|
2023-01-20 19:27:31 +00:00
|
|
|
not entry.data.get(CONF_SLEEP_PERIOD)
|
|
|
|
and not hass.is_stopping
|
2023-01-21 23:26:54 +00:00
|
|
|
and entry.state == ConfigEntryState.LOADED
|
2024-05-04 10:41:25 +00:00
|
|
|
and (coordinator := entry.runtime_data.rpc)
|
2022-12-14 00:22:34 +00:00
|
|
|
):
|
2024-04-28 16:19:38 +00:00
|
|
|
entry.async_create_background_task(
|
|
|
|
hass,
|
|
|
|
coordinator.async_request_refresh(),
|
|
|
|
"reconnect soon",
|
|
|
|
eager_start=True,
|
|
|
|
)
|