Cleanup hass.data in Plugwise (#66096)

This commit is contained in:
Franck Nijhof 2022-02-08 20:17:49 +01:00 committed by GitHub
parent d62e9c2b92
commit dad1dbeb6e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 30 additions and 87 deletions

View file

@ -9,7 +9,6 @@ from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import ( from .const import (
COORDINATOR,
DOMAIN, DOMAIN,
FLAME_ICON, FLAME_ICON,
FLOW_OFF_ICON, FLOW_OFF_ICON,
@ -45,7 +44,7 @@ async def async_setup_entry(
"""Set up the Smile binary_sensors from a config entry.""" """Set up the Smile binary_sensors from a config entry."""
coordinator: PlugwiseDataUpdateCoordinator = hass.data[DOMAIN][ coordinator: PlugwiseDataUpdateCoordinator = hass.data[DOMAIN][
config_entry.entry_id config_entry.entry_id
][COORDINATOR] ]
entities: list[PlugwiseBinarySensorEntity] = [] entities: list[PlugwiseBinarySensorEntity] = []
for device_id, device in coordinator.data.devices.items(): for device_id, device in coordinator.data.devices.items():
@ -77,7 +76,7 @@ async def async_setup_entry(
) )
) )
async_add_entities(entities, True) async_add_entities(entities)
class PlugwiseBinarySensorEntity(PlugwiseEntity, BinarySensorEntity): class PlugwiseBinarySensorEntity(PlugwiseEntity, BinarySensorEntity):

View file

@ -2,7 +2,6 @@
from typing import Any from typing import Any
from plugwise.exceptions import PlugwiseException from plugwise.exceptions import PlugwiseException
from plugwise.smile import Smile
from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import ( from homeassistant.components.climate.const import (
@ -22,7 +21,6 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import ( from .const import (
COORDINATOR,
DEFAULT_MAX_TEMP, DEFAULT_MAX_TEMP,
DEFAULT_MIN_TEMP, DEFAULT_MIN_TEMP,
DOMAIN, DOMAIN,
@ -35,6 +33,7 @@ from .entity import PlugwiseEntity
HVAC_MODES_HEAT_ONLY = [HVAC_MODE_HEAT, HVAC_MODE_AUTO, HVAC_MODE_OFF] HVAC_MODES_HEAT_ONLY = [HVAC_MODE_HEAT, HVAC_MODE_AUTO, HVAC_MODE_OFF]
HVAC_MODES_HEAT_COOL = [HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_AUTO, HVAC_MODE_OFF] HVAC_MODES_HEAT_COOL = [HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_AUTO, HVAC_MODE_OFF]
THERMOSTAT_CLASSES = ["thermostat", "zone_thermostat", "thermostatic_radiator_valve"]
async def async_setup_entry( async def async_setup_entry(
@ -43,28 +42,12 @@ async def async_setup_entry(
async_add_entities: AddEntitiesCallback, async_add_entities: AddEntitiesCallback,
) -> None: ) -> None:
"""Set up the Smile Thermostats from a config entry.""" """Set up the Smile Thermostats from a config entry."""
api = hass.data[DOMAIN][config_entry.entry_id]["api"] coordinator = hass.data[DOMAIN][config_entry.entry_id]
coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR] async_add_entities(
PlugwiseClimateEntity(coordinator, device_id)
entities: list[PlugwiseClimateEntity] = [] for device_id, device in coordinator.data.devices.items()
thermostat_classes = [ if device["class"] in THERMOSTAT_CLASSES
"thermostat", )
"zone_thermostat",
"thermostatic_radiator_valve",
]
for device_id, device in coordinator.data.devices.items():
if device["class"] not in thermostat_classes:
continue
thermostat = PlugwiseClimateEntity(
api,
coordinator,
device_id,
)
entities.append(thermostat)
async_add_entities(entities, True)
class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity): class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
@ -82,7 +65,6 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
def __init__( def __init__(
self, self,
api: Smile,
coordinator: PlugwiseDataUpdateCoordinator, coordinator: PlugwiseDataUpdateCoordinator,
device_id: str, device_id: str,
) -> None: ) -> None:
@ -92,7 +74,6 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
self._attr_unique_id = f"{device_id}-climate" self._attr_unique_id = f"{device_id}-climate"
self._attr_name = coordinator.data.devices[device_id].get("name") self._attr_name = coordinator.data.devices[device_id].get("name")
self._api = api
self._loc_id = coordinator.data.devices[device_id]["location"] self._loc_id = coordinator.data.devices[device_id]["location"]
self._presets = None self._presets = None
@ -104,7 +85,7 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
self._attr_min_temp < temperature < self._attr_max_temp self._attr_min_temp < temperature < self._attr_max_temp
): ):
try: try:
await self._api.set_temperature(self._loc_id, temperature) await self.coordinator.api.set_temperature(self._loc_id, temperature)
self._attr_target_temperature = temperature self._attr_target_temperature = temperature
self.async_write_ha_state() self.async_write_ha_state()
except PlugwiseException: except PlugwiseException:
@ -120,7 +101,7 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
if hvac_mode == HVAC_MODE_AUTO: if hvac_mode == HVAC_MODE_AUTO:
state = SCHEDULE_ON state = SCHEDULE_ON
try: try:
await self._api.set_temperature( await self.coordinator.api.set_temperature(
self._loc_id, climate_data.get("schedule_temperature") self._loc_id, climate_data.get("schedule_temperature")
) )
self._attr_target_temperature = climate_data.get("schedule_temperature") self._attr_target_temperature = climate_data.get("schedule_temperature")
@ -128,7 +109,7 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
LOGGER.error("Error while communicating to device") LOGGER.error("Error while communicating to device")
try: try:
await self._api.set_schedule_state( await self.coordinator.api.set_schedule_state(
self._loc_id, climate_data.get("last_used"), state self._loc_id, climate_data.get("last_used"), state
) )
self._attr_hvac_mode = hvac_mode self._attr_hvac_mode = hvac_mode
@ -142,7 +123,7 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
raise ValueError("No presets available") raise ValueError("No presets available")
try: try:
await self._api.set_preset(self._loc_id, preset_mode) await self.coordinator.api.set_preset(self._loc_id, preset_mode)
self._attr_preset_mode = preset_mode self._attr_preset_mode = preset_mode
self._attr_target_temperature = self._presets.get(preset_mode, "none")[0] self._attr_target_temperature = self._presets.get(preset_mode, "none")[0]
self.async_write_ha_state() self.async_write_ha_state()

View file

@ -9,7 +9,6 @@ DOMAIN = "plugwise"
LOGGER = logging.getLogger(__package__) LOGGER = logging.getLogger(__package__)
API = "api" API = "api"
COORDINATOR = "coordinator"
FLOW_SMILE = "smile (Adam/Anna/P1)" FLOW_SMILE = "smile (Adam/Anna/P1)"
FLOW_STRETCH = "stretch (Stretch)" FLOW_STRETCH = "stretch (Stretch)"
FLOW_TYPE = "flow_type" FLOW_TYPE = "flow_type"

View file

@ -6,7 +6,7 @@ from typing import Any
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from .const import COORDINATOR, DOMAIN from .const import DOMAIN
from .coordinator import PlugwiseDataUpdateCoordinator from .coordinator import PlugwiseDataUpdateCoordinator
@ -14,9 +14,7 @@ async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: ConfigEntry hass: HomeAssistant, entry: ConfigEntry
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Return diagnostics for a config entry.""" """Return diagnostics for a config entry."""
coordinator: PlugwiseDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ coordinator: PlugwiseDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
COORDINATOR
]
return { return {
"gateway": coordinator.data.gateway, "gateway": coordinator.data.gateway,
"devices": coordinator.data.devices, "devices": coordinator.data.devices,

View file

@ -12,6 +12,8 @@ from .coordinator import PlugwiseData, PlugwiseDataUpdateCoordinator
class PlugwiseEntity(CoordinatorEntity[PlugwiseData]): class PlugwiseEntity(CoordinatorEntity[PlugwiseData]):
"""Represent a PlugWise Entity.""" """Represent a PlugWise Entity."""
coordinator: PlugwiseDataUpdateCoordinator
def __init__( def __init__(
self, self,
coordinator: PlugwiseDataUpdateCoordinator, coordinator: PlugwiseDataUpdateCoordinator,

View file

@ -14,14 +14,11 @@ from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import ( from .const import (
COORDINATOR,
DEFAULT_PORT, DEFAULT_PORT,
DEFAULT_USERNAME, DEFAULT_USERNAME,
DOMAIN, DOMAIN,
GATEWAY,
LOGGER, LOGGER,
PLATFORMS_GATEWAY, PLATFORMS_GATEWAY,
PW_TYPE,
SENSOR_PLATFORMS, SENSOR_PLATFORMS,
) )
from .coordinator import PlugwiseDataUpdateCoordinator from .coordinator import PlugwiseDataUpdateCoordinator
@ -63,11 +60,7 @@ async def async_setup_entry_gw(hass: HomeAssistant, entry: ConfigEntry) -> bool:
coordinator = PlugwiseDataUpdateCoordinator(hass, api) coordinator = PlugwiseDataUpdateCoordinator(hass, api)
await coordinator.async_config_entry_first_refresh() await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = { hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
"api": api,
COORDINATOR: coordinator,
PW_TYPE: GATEWAY,
}
device_registry = dr.async_get(hass) device_registry = dr.async_get(hass)
device_registry.async_get_or_create( device_registry.async_get_or_create(

View file

@ -1,8 +1,6 @@
"""Plugwise Sensor component for Home Assistant.""" """Plugwise Sensor component for Home Assistant."""
from __future__ import annotations from __future__ import annotations
from plugwise.smile import Smile
from homeassistant.components.sensor import ( from homeassistant.components.sensor import (
SensorDeviceClass, SensorDeviceClass,
SensorEntity, SensorEntity,
@ -22,15 +20,7 @@ from homeassistant.const import (
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import ( from .const import COOL_ICON, DOMAIN, FLAME_ICON, IDLE_ICON, LOGGER, UNIT_LUMEN
COOL_ICON,
COORDINATOR,
DOMAIN,
FLAME_ICON,
IDLE_ICON,
LOGGER,
UNIT_LUMEN,
)
from .coordinator import PlugwiseDataUpdateCoordinator from .coordinator import PlugwiseDataUpdateCoordinator
from .entity import PlugwiseEntity from .entity import PlugwiseEntity
@ -286,8 +276,7 @@ async def async_setup_entry(
async_add_entities: AddEntitiesCallback, async_add_entities: AddEntitiesCallback,
) -> None: ) -> None:
"""Set up the Smile sensors from a config entry.""" """Set up the Smile sensors from a config entry."""
api = hass.data[DOMAIN][config_entry.entry_id]["api"] coordinator = hass.data[DOMAIN][config_entry.entry_id]
coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]
entities: list[PlugwiseSensorEnity] = [] entities: list[PlugwiseSensorEnity] = []
for device_id, device in coordinator.data.devices.items(): for device_id, device in coordinator.data.devices.items():
@ -300,7 +289,6 @@ async def async_setup_entry(
entities.append( entities.append(
PlugwiseSensorEnity( PlugwiseSensorEnity(
api,
coordinator, coordinator,
device_id, device_id,
description, description,
@ -315,7 +303,6 @@ async def async_setup_entry(
entities.append( entities.append(
PlugwiseAuxSensorEntity( PlugwiseAuxSensorEntity(
api,
coordinator, coordinator,
device_id, device_id,
description, description,
@ -323,7 +310,7 @@ async def async_setup_entry(
) )
break break
async_add_entities(entities, True) async_add_entities(entities)
class PlugwiseSensorEnity(PlugwiseEntity, SensorEntity): class PlugwiseSensorEnity(PlugwiseEntity, SensorEntity):
@ -331,7 +318,6 @@ class PlugwiseSensorEnity(PlugwiseEntity, SensorEntity):
def __init__( def __init__(
self, self,
api: Smile,
coordinator: PlugwiseDataUpdateCoordinator, coordinator: PlugwiseDataUpdateCoordinator,
device_id: str, device_id: str,
description: SensorEntityDescription, description: SensorEntityDescription,
@ -339,7 +325,6 @@ class PlugwiseSensorEnity(PlugwiseEntity, SensorEntity):
"""Initialise the sensor.""" """Initialise the sensor."""
super().__init__(coordinator, device_id) super().__init__(coordinator, device_id)
self.entity_description = description self.entity_description = description
self._api = api
self._attr_unique_id = f"{device_id}-{description.key}" self._attr_unique_id = f"{device_id}-{description.key}"
self._attr_name = ( self._attr_name = (
f"{coordinator.data.devices[device_id].get('name', '')} {description.name}" f"{coordinator.data.devices[device_id].get('name', '')} {description.name}"

View file

@ -3,7 +3,6 @@ from __future__ import annotations
from typing import Any from typing import Any
from plugwise import Smile
from plugwise.exceptions import PlugwiseException from plugwise.exceptions import PlugwiseException
from homeassistant.components.switch import SwitchEntity from homeassistant.components.switch import SwitchEntity
@ -11,7 +10,7 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import COORDINATOR, DOMAIN, LOGGER, SWITCH_ICON from .const import DOMAIN, LOGGER, SWITCH_ICON
from .coordinator import PlugwiseDataUpdateCoordinator from .coordinator import PlugwiseDataUpdateCoordinator
from .entity import PlugwiseEntity from .entity import PlugwiseEntity
@ -22,23 +21,12 @@ async def async_setup_entry(
async_add_entities: AddEntitiesCallback, async_add_entities: AddEntitiesCallback,
) -> None: ) -> None:
"""Set up the Smile switches from a config entry.""" """Set up the Smile switches from a config entry."""
api = hass.data[DOMAIN][config_entry.entry_id]["api"] coordinator = hass.data[DOMAIN][config_entry.entry_id]
coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR] async_add_entities(
PlugwiseSwitchEntity(coordinator, device_id)
entities: list[PlugwiseSwitchEntity] = [] for device_id, device in coordinator.data.devices.items()
for device_id, device in coordinator.data.devices.items(): if "switches" in device and "relay" in device["switches"]
if "switches" not in device or "relay" not in device["switches"]: )
continue
entities.append(
PlugwiseSwitchEntity(
api,
coordinator,
device_id,
)
)
async_add_entities(entities, True)
class PlugwiseSwitchEntity(PlugwiseEntity, SwitchEntity): class PlugwiseSwitchEntity(PlugwiseEntity, SwitchEntity):
@ -48,13 +36,11 @@ class PlugwiseSwitchEntity(PlugwiseEntity, SwitchEntity):
def __init__( def __init__(
self, self,
api: Smile,
coordinator: PlugwiseDataUpdateCoordinator, coordinator: PlugwiseDataUpdateCoordinator,
device_id: str, device_id: str,
) -> None: ) -> None:
"""Set up the Plugwise API.""" """Set up the Plugwise API."""
super().__init__(coordinator, device_id) super().__init__(coordinator, device_id)
self._api = api
self._attr_unique_id = f"{device_id}-plug" self._attr_unique_id = f"{device_id}-plug"
self._members = coordinator.data.devices[device_id].get("members") self._members = coordinator.data.devices[device_id].get("members")
self._attr_is_on = False self._attr_is_on = False
@ -63,7 +49,7 @@ class PlugwiseSwitchEntity(PlugwiseEntity, SwitchEntity):
async def async_turn_on(self, **kwargs: Any) -> None: async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on.""" """Turn the device on."""
try: try:
state_on = await self._api.set_switch_state( state_on = await self.coordinator.api.set_switch_state(
self._dev_id, self._members, "relay", "on" self._dev_id, self._members, "relay", "on"
) )
except PlugwiseException: except PlugwiseException:
@ -76,7 +62,7 @@ class PlugwiseSwitchEntity(PlugwiseEntity, SwitchEntity):
async def async_turn_off(self, **kwargs: Any) -> None: async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the device off.""" """Turn the device off."""
try: try:
state_off = await self._api.set_switch_state( state_off = await self.coordinator.api.set_switch_state(
self._dev_id, self._members, "relay", "off" self._dev_id, self._members, "relay", "off"
) )
except PlugwiseException: except PlugwiseException: