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 .const import (
COORDINATOR,
DOMAIN,
FLAME_ICON,
FLOW_OFF_ICON,
@ -45,7 +44,7 @@ async def async_setup_entry(
"""Set up the Smile binary_sensors from a config entry."""
coordinator: PlugwiseDataUpdateCoordinator = hass.data[DOMAIN][
config_entry.entry_id
][COORDINATOR]
]
entities: list[PlugwiseBinarySensorEntity] = []
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):

View File

@ -2,7 +2,6 @@
from typing import Any
from plugwise.exceptions import PlugwiseException
from plugwise.smile import Smile
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
@ -22,7 +21,6 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import (
COORDINATOR,
DEFAULT_MAX_TEMP,
DEFAULT_MIN_TEMP,
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_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(
@ -43,28 +42,12 @@ async def async_setup_entry(
async_add_entities: AddEntitiesCallback,
) -> None:
"""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]
entities: list[PlugwiseClimateEntity] = []
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)
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
PlugwiseClimateEntity(coordinator, device_id)
for device_id, device in coordinator.data.devices.items()
if device["class"] in THERMOSTAT_CLASSES
)
class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
@ -82,7 +65,6 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
def __init__(
self,
api: Smile,
coordinator: PlugwiseDataUpdateCoordinator,
device_id: str,
) -> None:
@ -92,7 +74,6 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
self._attr_unique_id = f"{device_id}-climate"
self._attr_name = coordinator.data.devices[device_id].get("name")
self._api = api
self._loc_id = coordinator.data.devices[device_id]["location"]
self._presets = None
@ -104,7 +85,7 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
self._attr_min_temp < temperature < self._attr_max_temp
):
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.async_write_ha_state()
except PlugwiseException:
@ -120,7 +101,7 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
if hvac_mode == HVAC_MODE_AUTO:
state = SCHEDULE_ON
try:
await self._api.set_temperature(
await self.coordinator.api.set_temperature(
self._loc_id, 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")
try:
await self._api.set_schedule_state(
await self.coordinator.api.set_schedule_state(
self._loc_id, climate_data.get("last_used"), state
)
self._attr_hvac_mode = hvac_mode
@ -142,7 +123,7 @@ class PlugwiseClimateEntity(PlugwiseEntity, ClimateEntity):
raise ValueError("No presets available")
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_target_temperature = self._presets.get(preset_mode, "none")[0]
self.async_write_ha_state()

View File

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

View File

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

View File

@ -12,6 +12,8 @@ from .coordinator import PlugwiseData, PlugwiseDataUpdateCoordinator
class PlugwiseEntity(CoordinatorEntity[PlugwiseData]):
"""Represent a PlugWise Entity."""
coordinator: PlugwiseDataUpdateCoordinator
def __init__(
self,
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 .const import (
COORDINATOR,
DEFAULT_PORT,
DEFAULT_USERNAME,
DOMAIN,
GATEWAY,
LOGGER,
PLATFORMS_GATEWAY,
PW_TYPE,
SENSOR_PLATFORMS,
)
from .coordinator import PlugwiseDataUpdateCoordinator
@ -63,11 +60,7 @@ async def async_setup_entry_gw(hass: HomeAssistant, entry: ConfigEntry) -> bool:
coordinator = PlugwiseDataUpdateCoordinator(hass, api)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
"api": api,
COORDINATOR: coordinator,
PW_TYPE: GATEWAY,
}
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
device_registry = dr.async_get(hass)
device_registry.async_get_or_create(

View File

@ -1,8 +1,6 @@
"""Plugwise Sensor component for Home Assistant."""
from __future__ import annotations
from plugwise.smile import Smile
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
@ -22,15 +20,7 @@ from homeassistant.const import (
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import (
COOL_ICON,
COORDINATOR,
DOMAIN,
FLAME_ICON,
IDLE_ICON,
LOGGER,
UNIT_LUMEN,
)
from .const import COOL_ICON, DOMAIN, FLAME_ICON, IDLE_ICON, LOGGER, UNIT_LUMEN
from .coordinator import PlugwiseDataUpdateCoordinator
from .entity import PlugwiseEntity
@ -286,8 +276,7 @@ async def async_setup_entry(
async_add_entities: AddEntitiesCallback,
) -> None:
"""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]
coordinator = hass.data[DOMAIN][config_entry.entry_id]
entities: list[PlugwiseSensorEnity] = []
for device_id, device in coordinator.data.devices.items():
@ -300,7 +289,6 @@ async def async_setup_entry(
entities.append(
PlugwiseSensorEnity(
api,
coordinator,
device_id,
description,
@ -315,7 +303,6 @@ async def async_setup_entry(
entities.append(
PlugwiseAuxSensorEntity(
api,
coordinator,
device_id,
description,
@ -323,7 +310,7 @@ async def async_setup_entry(
)
break
async_add_entities(entities, True)
async_add_entities(entities)
class PlugwiseSensorEnity(PlugwiseEntity, SensorEntity):
@ -331,7 +318,6 @@ class PlugwiseSensorEnity(PlugwiseEntity, SensorEntity):
def __init__(
self,
api: Smile,
coordinator: PlugwiseDataUpdateCoordinator,
device_id: str,
description: SensorEntityDescription,
@ -339,7 +325,6 @@ class PlugwiseSensorEnity(PlugwiseEntity, SensorEntity):
"""Initialise the sensor."""
super().__init__(coordinator, device_id)
self.entity_description = description
self._api = api
self._attr_unique_id = f"{device_id}-{description.key}"
self._attr_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 plugwise import Smile
from plugwise.exceptions import PlugwiseException
from homeassistant.components.switch import SwitchEntity
@ -11,7 +10,7 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
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 .entity import PlugwiseEntity
@ -22,23 +21,12 @@ async def async_setup_entry(
async_add_entities: AddEntitiesCallback,
) -> None:
"""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]
entities: list[PlugwiseSwitchEntity] = []
for device_id, device in coordinator.data.devices.items():
if "switches" not in device or "relay" not in device["switches"]:
continue
entities.append(
PlugwiseSwitchEntity(
api,
coordinator,
device_id,
)
)
async_add_entities(entities, True)
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
PlugwiseSwitchEntity(coordinator, device_id)
for device_id, device in coordinator.data.devices.items()
if "switches" in device and "relay" in device["switches"]
)
class PlugwiseSwitchEntity(PlugwiseEntity, SwitchEntity):
@ -48,13 +36,11 @@ class PlugwiseSwitchEntity(PlugwiseEntity, SwitchEntity):
def __init__(
self,
api: Smile,
coordinator: PlugwiseDataUpdateCoordinator,
device_id: str,
) -> None:
"""Set up the Plugwise API."""
super().__init__(coordinator, device_id)
self._api = api
self._attr_unique_id = f"{device_id}-plug"
self._members = coordinator.data.devices[device_id].get("members")
self._attr_is_on = False
@ -63,7 +49,7 @@ class PlugwiseSwitchEntity(PlugwiseEntity, SwitchEntity):
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
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"
)
except PlugwiseException:
@ -76,7 +62,7 @@ class PlugwiseSwitchEntity(PlugwiseEntity, SwitchEntity):
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the device off."""
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"
)
except PlugwiseException: