Use runtime_data in rachio (#144896)

This commit is contained in:
epenet 2025-05-14 16:46:36 +02:00 committed by GitHub
parent 11644d48ee
commit 4bc5987f36
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 30 additions and 32 deletions

View File

@ -7,13 +7,12 @@ from rachiopy import Rachio
from requests.exceptions import ConnectTimeout from requests.exceptions import ConnectTimeout
from homeassistant.components import cloud from homeassistant.components import cloud
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_WEBHOOK_ID, Platform from homeassistant.const import CONF_API_KEY, CONF_WEBHOOK_ID, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from .const import CONF_CLOUDHOOK_URL, CONF_MANUAL_RUN_MINS, DOMAIN from .const import CONF_CLOUDHOOK_URL, CONF_MANUAL_RUN_MINS
from .device import RachioPerson from .device import RachioConfigEntry, RachioPerson
from .webhooks import ( from .webhooks import (
async_get_or_create_registered_webhook_id_and_url, async_get_or_create_registered_webhook_id_and_url,
async_register_webhook, async_register_webhook,
@ -25,21 +24,20 @@ _LOGGER = logging.getLogger(__name__)
PLATFORMS = [Platform.BINARY_SENSOR, Platform.CALENDAR, Platform.SWITCH] PLATFORMS = [Platform.BINARY_SENSOR, Platform.CALENDAR, Platform.SWITCH]
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: RachioConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
async_unregister_webhook(hass, entry) async_unregister_webhook(hass, entry)
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok return unload_ok
async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: async def async_remove_entry(hass: HomeAssistant, entry: RachioConfigEntry) -> None:
"""Remove a rachio config entry.""" """Remove a rachio config entry."""
if CONF_CLOUDHOOK_URL in entry.data: if CONF_CLOUDHOOK_URL in entry.data:
await cloud.async_delete_cloudhook(hass, entry.data[CONF_WEBHOOK_ID]) await cloud.async_delete_cloudhook(hass, entry.data[CONF_WEBHOOK_ID])
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: RachioConfigEntry) -> bool:
"""Set up the Rachio config entry.""" """Set up the Rachio config entry."""
config = entry.data config = entry.data
@ -97,7 +95,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await base.schedule_coordinator.async_config_entry_first_refresh() await base.schedule_coordinator.async_config_entry_first_refresh()
# Enable platform # Enable platform
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = person entry.runtime_data = person
async_register_webhook(hass, entry) async_register_webhook(hass, entry)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

View File

@ -10,7 +10,6 @@ from homeassistant.components.binary_sensor import (
BinarySensorEntity, BinarySensorEntity,
BinarySensorEntityDescription, BinarySensorEntityDescription,
) )
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
@ -18,7 +17,6 @@ from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import ( from .const import (
DOMAIN as DOMAIN_RACHIO,
KEY_BATTERY, KEY_BATTERY,
KEY_DETECT_FLOW, KEY_DETECT_FLOW,
KEY_DEVICE_ID, KEY_DEVICE_ID,
@ -33,7 +31,7 @@ from .const import (
STATUS_ONLINE, STATUS_ONLINE,
) )
from .coordinator import RachioUpdateCoordinator from .coordinator import RachioUpdateCoordinator
from .device import RachioIro, RachioPerson from .device import RachioConfigEntry, RachioIro
from .entity import RachioDevice, RachioHoseTimerEntity from .entity import RachioDevice, RachioHoseTimerEntity
from .webhooks import ( from .webhooks import (
SUBTYPE_COLD_REBOOT, SUBTYPE_COLD_REBOOT,
@ -109,7 +107,7 @@ HOSE_TIMER_BINARY_SENSOR_TYPES: tuple[RachioHoseTimerBinarySensorDescription, ..
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
config_entry: ConfigEntry, config_entry: RachioConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback, async_add_entities: AddConfigEntryEntitiesCallback,
) -> None: ) -> None:
"""Set up the Rachio binary sensors.""" """Set up the Rachio binary sensors."""
@ -117,9 +115,11 @@ async def async_setup_entry(
async_add_entities(entities) async_add_entities(entities)
def _create_entities(hass: HomeAssistant, config_entry: ConfigEntry) -> list[Entity]: def _create_entities(
hass: HomeAssistant, config_entry: RachioConfigEntry
) -> list[Entity]:
entities: list[Entity] = [] entities: list[Entity] = []
person: RachioPerson = hass.data[DOMAIN_RACHIO][config_entry.entry_id] person = config_entry.runtime_data
entities.extend( entities.extend(
RachioControllerBinarySensor(controller, description) RachioControllerBinarySensor(controller, description)
for controller in person.controllers for controller in person.controllers

View File

@ -9,7 +9,6 @@ from homeassistant.components.calendar import (
CalendarEntityFeature, CalendarEntityFeature,
CalendarEvent, CalendarEvent,
) )
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
@ -17,7 +16,6 @@ from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from .const import ( from .const import (
DOMAIN,
KEY_ADDRESS, KEY_ADDRESS,
KEY_DURATION_SECONDS, KEY_DURATION_SECONDS,
KEY_ID, KEY_ID,
@ -33,18 +31,18 @@ from .const import (
KEY_VALVE_NAME, KEY_VALVE_NAME,
) )
from .coordinator import RachioScheduleUpdateCoordinator from .coordinator import RachioScheduleUpdateCoordinator
from .device import RachioPerson from .device import RachioConfigEntry
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
config_entry: ConfigEntry, config_entry: RachioConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback, async_add_entities: AddConfigEntryEntitiesCallback,
) -> None: ) -> None:
"""Set up entry for Rachio smart hose timer calendar.""" """Set up entry for Rachio smart hose timer calendar."""
person: RachioPerson = hass.data[DOMAIN][config_entry.entry_id] person = config_entry.runtime_data
async_add_entities( async_add_entities(
RachioCalendarEntity(base_station.schedule_coordinator, base_station) RachioCalendarEntity(base_station.schedule_coordinator, base_station)
for base_station in person.base_stations for base_station in person.base_stations

View File

@ -57,11 +57,13 @@ RESUME_SERVICE_SCHEMA = vol.Schema({vol.Optional(ATTR_DEVICES): cv.string})
STOP_SERVICE_SCHEMA = vol.Schema({vol.Optional(ATTR_DEVICES): cv.string}) STOP_SERVICE_SCHEMA = vol.Schema({vol.Optional(ATTR_DEVICES): cv.string})
type RachioConfigEntry = ConfigEntry[RachioPerson]
class RachioPerson: class RachioPerson:
"""Represent a Rachio user.""" """Represent a Rachio user."""
def __init__(self, rachio: Rachio, config_entry: ConfigEntry) -> None: def __init__(self, rachio: Rachio, config_entry: RachioConfigEntry) -> None:
"""Create an object from the provided API instance.""" """Create an object from the provided API instance."""
# Use API token to get user ID # Use API token to get user ID
self.rachio = rachio self.rachio = rachio

View File

@ -9,7 +9,6 @@ from typing import Any
import voluptuous as vol import voluptuous as vol
from homeassistant.components.switch import SwitchEntity from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ENTITY_ID, ATTR_ID from homeassistant.const import ATTR_ENTITY_ID, ATTR_ID
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, ServiceCall, callback from homeassistant.core import CALLBACK_TYPE, HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
@ -57,7 +56,7 @@ from .const import (
SLOPE_SLIGHT, SLOPE_SLIGHT,
SLOPE_STEEP, SLOPE_STEEP,
) )
from .device import RachioPerson from .device import RachioConfigEntry
from .entity import RachioDevice, RachioHoseTimerEntity from .entity import RachioDevice, RachioHoseTimerEntity
from .webhooks import ( from .webhooks import (
SUBTYPE_RAIN_DELAY_OFF, SUBTYPE_RAIN_DELAY_OFF,
@ -99,7 +98,7 @@ START_MULTIPLE_ZONES_SCHEMA = vol.Schema(
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
config_entry: ConfigEntry, config_entry: RachioConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback, async_add_entities: AddConfigEntryEntitiesCallback,
) -> None: ) -> None:
"""Set up the Rachio switches.""" """Set up the Rachio switches."""
@ -117,7 +116,7 @@ async def async_setup_entry(
def start_multiple(service: ServiceCall) -> None: def start_multiple(service: ServiceCall) -> None:
"""Service to start multiple zones in sequence.""" """Service to start multiple zones in sequence."""
zones_list = [] zones_list = []
person = hass.data[DOMAIN][config_entry.entry_id] person = config_entry.runtime_data
entity_id = service.data[ATTR_ENTITY_ID] entity_id = service.data[ATTR_ENTITY_ID]
duration = iter(service.data[ATTR_DURATION]) duration = iter(service.data[ATTR_DURATION])
default_time = service.data[ATTR_DURATION][0] default_time = service.data[ATTR_DURATION][0]
@ -173,9 +172,11 @@ async def async_setup_entry(
) )
def _create_entities(hass: HomeAssistant, config_entry: ConfigEntry) -> list[Entity]: def _create_entities(
hass: HomeAssistant, config_entry: RachioConfigEntry
) -> list[Entity]:
entities: list[Entity] = [] entities: list[Entity] = []
person: RachioPerson = hass.data[DOMAIN][config_entry.entry_id] person = config_entry.runtime_data
# Fetch the schedule once at startup # Fetch the schedule once at startup
# in order to avoid every zone doing it # in order to avoid every zone doing it
for controller in person.controllers: for controller in person.controllers:

View File

@ -5,7 +5,6 @@ from __future__ import annotations
from aiohttp import web from aiohttp import web
from homeassistant.components import cloud, webhook from homeassistant.components import cloud, webhook
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_WEBHOOK_ID, URL_API from homeassistant.const import CONF_WEBHOOK_ID, URL_API
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
@ -21,7 +20,7 @@ from .const import (
SIGNAL_RACHIO_SCHEDULE_UPDATE, SIGNAL_RACHIO_SCHEDULE_UPDATE,
SIGNAL_RACHIO_ZONE_UPDATE, SIGNAL_RACHIO_ZONE_UPDATE,
) )
from .device import RachioPerson from .device import RachioConfigEntry
# Device webhook values # Device webhook values
TYPE_CONTROLLER_STATUS = "DEVICE_STATUS" TYPE_CONTROLLER_STATUS = "DEVICE_STATUS"
@ -83,7 +82,7 @@ SIGNAL_MAP = {
@callback @callback
def async_register_webhook(hass: HomeAssistant, entry: ConfigEntry) -> None: def async_register_webhook(hass: HomeAssistant, entry: RachioConfigEntry) -> None:
"""Register a webhook.""" """Register a webhook."""
webhook_id: str = entry.data[CONF_WEBHOOK_ID] webhook_id: str = entry.data[CONF_WEBHOOK_ID]
@ -91,7 +90,7 @@ def async_register_webhook(hass: HomeAssistant, entry: ConfigEntry) -> None:
hass: HomeAssistant, webhook_id: str, request: web.Request hass: HomeAssistant, webhook_id: str, request: web.Request
) -> web.Response: ) -> web.Response:
"""Handle webhook calls from the server.""" """Handle webhook calls from the server."""
person: RachioPerson = hass.data[DOMAIN][entry.entry_id] person = entry.runtime_data
data = await request.json() data = await request.json()
try: try:
@ -114,14 +113,14 @@ def async_register_webhook(hass: HomeAssistant, entry: ConfigEntry) -> None:
@callback @callback
def async_unregister_webhook(hass: HomeAssistant, entry: ConfigEntry) -> None: def async_unregister_webhook(hass: HomeAssistant, entry: RachioConfigEntry) -> None:
"""Unregister a webhook.""" """Unregister a webhook."""
webhook_id: str = entry.data[CONF_WEBHOOK_ID] webhook_id: str = entry.data[CONF_WEBHOOK_ID]
webhook.async_unregister(hass, webhook_id) webhook.async_unregister(hass, webhook_id)
async def async_get_or_create_registered_webhook_id_and_url( async def async_get_or_create_registered_webhook_id_and_url(
hass: HomeAssistant, entry: ConfigEntry hass: HomeAssistant, entry: RachioConfigEntry
) -> str: ) -> str:
"""Generate webhook url.""" """Generate webhook url."""
config = entry.data.copy() config = entry.data.copy()