Store runtime data inside the config entry in Sense (#119740)

This commit is contained in:
Robert Hillis 2024-06-17 21:43:45 -04:00 committed by GitHub
parent ac51851664
commit faf2a447a4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 37 additions and 55 deletions

View File

@ -1,7 +1,9 @@
"""Support for monitoring a Sense energy sensor.""" """Support for monitoring a Sense energy sensor."""
from dataclasses import dataclass
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import Any
from sense_energy import ( from sense_energy import (
ASyncSenseable, ASyncSenseable,
@ -25,20 +27,16 @@ from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, Upda
from .const import ( from .const import (
ACTIVE_UPDATE_RATE, ACTIVE_UPDATE_RATE,
DOMAIN,
SENSE_CONNECT_EXCEPTIONS, SENSE_CONNECT_EXCEPTIONS,
SENSE_DATA,
SENSE_DEVICE_UPDATE, SENSE_DEVICE_UPDATE,
SENSE_DEVICES_DATA,
SENSE_DISCOVERED_DEVICES_DATA,
SENSE_TIMEOUT_EXCEPTIONS, SENSE_TIMEOUT_EXCEPTIONS,
SENSE_TRENDS_COORDINATOR,
SENSE_WEBSOCKET_EXCEPTIONS, SENSE_WEBSOCKET_EXCEPTIONS,
) )
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
PLATFORMS = [Platform.BINARY_SENSOR, Platform.SENSOR] PLATFORMS = [Platform.BINARY_SENSOR, Platform.SENSOR]
type SenseConfigEntry = ConfigEntry[SenseData]
class SenseDevicesData: class SenseDevicesData:
@ -57,7 +55,17 @@ class SenseDevicesData:
return self._data_by_device.get(sense_device_id) return self._data_by_device.get(sense_device_id)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: @dataclass(kw_only=True, slots=True)
class SenseData:
"""Sense data type."""
data: ASyncSenseable
device_data: SenseDevicesData
trends: DataUpdateCoordinator[None]
discovered: list[dict[str, Any]]
async def async_setup_entry(hass: HomeAssistant, entry: SenseConfigEntry) -> bool:
"""Set up Sense from a config entry.""" """Set up Sense from a config entry."""
entry_data = entry.data entry_data = entry.data
@ -91,7 +99,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
except SENSE_CONNECT_EXCEPTIONS as err: except SENSE_CONNECT_EXCEPTIONS as err:
raise ConfigEntryNotReady(str(err)) from err raise ConfigEntryNotReady(str(err)) from err
sense_devices_data = SenseDevicesData()
try: try:
sense_discovered_devices = await gateway.get_discovered_device_data() sense_discovered_devices = await gateway.get_discovered_device_data()
await gateway.update_realtime() await gateway.update_realtime()
@ -132,12 +139,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"sense.trends-coordinator-refresh", "sense.trends-coordinator-refresh",
) )
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = { entry.runtime_data = SenseData(
SENSE_DATA: gateway, data=gateway,
SENSE_DEVICES_DATA: sense_devices_data, device_data=SenseDevicesData(),
SENSE_TRENDS_COORDINATOR: trends_coordinator, trends=trends_coordinator,
SENSE_DISCOVERED_DEVICES_DATA: sense_discovered_devices, discovered=sense_discovered_devices,
} )
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
@ -152,7 +159,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
data = gateway.get_realtime() data = gateway.get_realtime()
if "devices" in data: if "devices" in data:
sense_devices_data.set_devices_data(data["devices"]) entry.runtime_data.device_data.set_devices_data(data["devices"])
async_dispatcher_send(hass, f"{SENSE_DEVICE_UPDATE}-{gateway.sense_monitor_id}") async_dispatcher_send(hass, f"{SENSE_DEVICE_UPDATE}-{gateway.sense_monitor_id}")
remove_update_callback = async_track_time_interval( remove_update_callback = async_track_time_interval(
@ -173,9 +180,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return True return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: SenseConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok

View File

@ -6,40 +6,29 @@ from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass, BinarySensorDeviceClass,
BinarySensorEntity, BinarySensorEntity,
) )
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import ( from . import SenseConfigEntry
ATTRIBUTION, from .const import ATTRIBUTION, DOMAIN, MDI_ICONS, SENSE_DEVICE_UPDATE
DOMAIN,
MDI_ICONS,
SENSE_DATA,
SENSE_DEVICE_UPDATE,
SENSE_DEVICES_DATA,
SENSE_DISCOVERED_DEVICES_DATA,
)
_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: SenseConfigEntry,
async_add_entities: AddEntitiesCallback, async_add_entities: AddEntitiesCallback,
) -> None: ) -> None:
"""Set up the Sense binary sensor.""" """Set up the Sense binary sensor."""
data = hass.data[DOMAIN][config_entry.entry_id][SENSE_DATA] sense_monitor_id = config_entry.runtime_data.data.sense_monitor_id
sense_devices_data = hass.data[DOMAIN][config_entry.entry_id][SENSE_DEVICES_DATA]
sense_monitor_id = data.sense_monitor_id
sense_devices = hass.data[DOMAIN][config_entry.entry_id][ sense_devices = config_entry.runtime_data.discovered
SENSE_DISCOVERED_DEVICES_DATA device_data = config_entry.runtime_data.device_data
]
devices = [ devices = [
SenseDevice(sense_devices_data, device, sense_monitor_id) SenseDevice(device_data, device, sense_monitor_id)
for device in sense_devices for device in sense_devices
if device["tags"]["DeviceListAllowed"] == "true" if device["tags"]["DeviceListAllowed"] == "true"
] ]

View File

@ -12,11 +12,7 @@ DOMAIN = "sense"
DEFAULT_TIMEOUT = 30 DEFAULT_TIMEOUT = 30
ACTIVE_UPDATE_RATE = 60 ACTIVE_UPDATE_RATE = 60
DEFAULT_NAME = "Sense" DEFAULT_NAME = "Sense"
SENSE_DATA = "sense_data"
SENSE_DEVICE_UPDATE = "sense_devices_update" SENSE_DEVICE_UPDATE = "sense_devices_update"
SENSE_DEVICES_DATA = "sense_devices_data"
SENSE_DISCOVERED_DEVICES_DATA = "sense_discovered_devices"
SENSE_TRENDS_COORDINATOR = "sense_trends_coordinator"
ACTIVE_NAME = "Energy" ACTIVE_NAME = "Energy"
ACTIVE_TYPE = "active" ACTIVE_TYPE = "active"

View File

@ -5,7 +5,6 @@ from homeassistant.components.sensor import (
SensorEntity, SensorEntity,
SensorStateClass, SensorStateClass,
) )
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
PERCENTAGE, PERCENTAGE,
UnitOfElectricPotential, UnitOfElectricPotential,
@ -18,6 +17,7 @@ from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import SenseConfigEntry
from .const import ( from .const import (
ACTIVE_NAME, ACTIVE_NAME,
ACTIVE_TYPE, ACTIVE_TYPE,
@ -34,11 +34,7 @@ from .const import (
PRODUCTION_NAME, PRODUCTION_NAME,
PRODUCTION_PCT_ID, PRODUCTION_PCT_ID,
PRODUCTION_PCT_NAME, PRODUCTION_PCT_NAME,
SENSE_DATA,
SENSE_DEVICE_UPDATE, SENSE_DEVICE_UPDATE,
SENSE_DEVICES_DATA,
SENSE_DISCOVERED_DEVICES_DATA,
SENSE_TRENDS_COORDINATOR,
SOLAR_POWERED_ID, SOLAR_POWERED_ID,
SOLAR_POWERED_NAME, SOLAR_POWERED_NAME,
TO_GRID_ID, TO_GRID_ID,
@ -87,26 +83,23 @@ def sense_to_mdi(sense_icon):
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
config_entry: ConfigEntry, config_entry: SenseConfigEntry,
async_add_entities: AddEntitiesCallback, async_add_entities: AddEntitiesCallback,
) -> None: ) -> None:
"""Set up the Sense sensor.""" """Set up the Sense sensor."""
base_data = hass.data[DOMAIN][config_entry.entry_id] data = config_entry.runtime_data.data
data = base_data[SENSE_DATA] trends_coordinator = config_entry.runtime_data.trends
sense_devices_data = base_data[SENSE_DEVICES_DATA]
trends_coordinator = base_data[SENSE_TRENDS_COORDINATOR]
# Request only in case it takes longer # Request only in case it takes longer
# than 60s # than 60s
await trends_coordinator.async_request_refresh() await trends_coordinator.async_request_refresh()
sense_monitor_id = data.sense_monitor_id sense_monitor_id = data.sense_monitor_id
sense_devices = hass.data[DOMAIN][config_entry.entry_id][ sense_devices = config_entry.runtime_data.discovered
SENSE_DISCOVERED_DEVICES_DATA device_data = config_entry.runtime_data.device_data
]
entities: list[SensorEntity] = [ entities: list[SensorEntity] = [
SenseEnergyDevice(sense_devices_data, device, sense_monitor_id) SenseEnergyDevice(device_data, device, sense_monitor_id)
for device in sense_devices for device in sense_devices
if device["tags"]["DeviceListAllowed"] == "true" if device["tags"]["DeviceListAllowed"] == "true"
] ]