Update plugwise to async and config_flow (#33691)

* Update plugwise async, config_flow and multi entity

* Update battery percentage

* Fix yamllint on services

* Fix yamllint on services

* Fix formatting for pyupgrade

* Update homeassistant/components/plugwise/__init__.py

Co-Authored-By: Robert Svensson <Kane610@users.noreply.github.com>

* Add try/except on setup

* Bump module version, battery version and valve position

* Removing sensor, switch, water_heater for later (child) PRs

* Catchup and version bump

* Remove title from strings.json

* Readd already reviewd await try/except

* Readd already reviewed config_flow

* Fix pylint

* Fix per 0.109 translations

* Remove unused import from merge

* Update plugwise async, config_flow and multi entity

* Update battery percentage

* Fix yamllint on services

* Fix yamllint on services

* Bump module version

* Bump module version, battery version and valve position

* Removing sensor, switch, water_heater for later (child) PRs

* Catchup and version bump

* Remove title from strings.json

* Fix pylint

* Fix per 0.109 translations

* Translations and config_flow, module version bump with required changes

* Translations and config_flow, module version bump with required changes

* Fix requirements

* Fix requirements

* Fix pylint

* Fix pylint

* Update homeassistant/components/plugwise/__init__.py

Improvement

Co-authored-by: J. Nick Koston <nick@koston.org>

* Update homeassistant/components/plugwise/__init__.py

Improvement

Co-authored-by: J. Nick Koston <nick@koston.org>

* Update homeassistant/components/plugwise/__init__.py

Improvement

Co-authored-by: J. Nick Koston <nick@koston.org>

* Include configentrynotready on import

* Update __init__.py

* DataUpdateCoordinator and comment non-PR-platforms

* Fix reqs

* Rename devices variable in favor of entities

* Rework updates with DataUpdateCoordinator

* Peer review

* Peer review second part

* Cleanup comments and redundant code

* Added required config_flow test

* Peer review third part

* Update service was replaced by DataUpdateCoordinator

* Corrected testing, version bump for InvalidAuth, move uniq_id

* Remove according to review

* Await connect (py38)

* Remove unneccesary code

* Show only when multiple

* Improve config_flow, rename consts

* Update homeassistant/components/plugwise/climate.py

Co-authored-by: J. Nick Koston <nick@koston.org>

* Update homeassistant/components/plugwise/climate.py

Co-authored-by: J. Nick Koston <nick@koston.org>

* Process review comments

Co-authored-by: Robert Svensson <Kane610@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
Tom 2020-05-28 17:52:25 +02:00 committed by GitHub
parent 5c516ad013
commit 7e693afcf3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 638 additions and 191 deletions

View file

@ -1,11 +1,11 @@
"""Plugwise Climate component for Home Assistant."""
import logging
from typing import Dict
import haanna
import voluptuous as vol
from Plugwise_Smile.Smile import Smile
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_COOL,
CURRENT_HVAC_HEAT,
@ -13,129 +13,140 @@ from homeassistant.components.climate.const import (
HVAC_MODE_AUTO,
HVAC_MODE_HEAT,
HVAC_MODE_HEAT_COOL,
HVAC_MODE_OFF,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import (
ATTR_TEMPERATURE,
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
TEMP_CELSIUS,
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
from . import SmileGateway
from .const import (
DEFAULT_MAX_TEMP,
DEFAULT_MIN_TEMP,
DOMAIN,
SCHEDULE_OFF,
SCHEDULE_ON,
THERMOSTAT_ICON,
)
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
HVAC_MODES_HEAT_ONLY = [HVAC_MODE_HEAT, HVAC_MODE_AUTO]
HVAC_MODES_HEAT_COOL = [HVAC_MODE_HEAT_COOL, HVAC_MODE_AUTO]
SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
_LOGGER = logging.getLogger(__name__)
# Configuration directives
CONF_MIN_TEMP = "min_temp"
CONF_MAX_TEMP = "max_temp"
CONF_LEGACY = "legacy_anna"
# Default directives
DEFAULT_NAME = "Plugwise Thermostat"
DEFAULT_USERNAME = "smile"
DEFAULT_TIMEOUT = 10
DEFAULT_PORT = 80
DEFAULT_ICON = "mdi:thermometer"
DEFAULT_MIN_TEMP = 4
DEFAULT_MAX_TEMP = 30
async def async_setup_entry(hass, config_entry, async_add_entities):
"""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"]
# HVAC modes
HVAC_MODES_1 = [HVAC_MODE_HEAT, HVAC_MODE_AUTO]
HVAC_MODES_2 = [HVAC_MODE_HEAT_COOL, HVAC_MODE_AUTO]
# Read platform configuration
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_LEGACY, default=False): cv.boolean,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
vol.Optional(CONF_MIN_TEMP, default=DEFAULT_MIN_TEMP): cv.positive_int,
vol.Optional(CONF_MAX_TEMP, default=DEFAULT_MAX_TEMP): cv.positive_int,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Add the Plugwise (Anna) Thermostat."""
api = haanna.Haanna(
config[CONF_USERNAME],
config[CONF_PASSWORD],
config[CONF_HOST],
config[CONF_PORT],
config[CONF_LEGACY],
)
try:
api.ping_anna_thermostat()
except OSError:
_LOGGER.debug("Ping failed, retrying later", exc_info=True)
raise PlatformNotReady
devices = [
ThermostatDevice(
api, config[CONF_NAME], config[CONF_MIN_TEMP], config[CONF_MAX_TEMP]
)
entities = []
thermostat_classes = [
"thermostat",
"zone_thermostat",
"thermostatic_radiator_valve",
]
add_entities(devices, True)
all_entities = api.get_all_devices()
for dev_id, device in all_entities.items():
if device["class"] not in thermostat_classes:
continue
thermostat = PwThermostat(
api,
coordinator,
device["name"],
dev_id,
device["location"],
device["class"],
DEFAULT_MIN_TEMP,
DEFAULT_MAX_TEMP,
)
entities.append(thermostat)
async_add_entities(entities, True)
class ThermostatDevice(ClimateEntity):
"""Representation of the Plugwise thermostat."""
class PwThermostat(SmileGateway, ClimateEntity):
"""Representation of an Plugwise thermostat."""
def __init__(self, api, name, min_temp, max_temp):
def __init__(
self, api, coordinator, name, dev_id, loc_id, model, min_temp, max_temp
):
"""Set up the Plugwise API."""
super().__init__(api, coordinator)
self._api = api
self._name = name
self._dev_id = dev_id
self._loc_id = loc_id
self._model = model
self._min_temp = min_temp
self._max_temp = max_temp
self._name = name
self._direct_objects = None
self._domain_objects = None
self._outdoor_temperature = None
self._selected_schema = None
self._last_active_schema = None
self._preset_mode = None
self._presets = None
self._presets_list = None
self._boiler_status = None
self._heating_status = None
self._cooling_status = None
self._dhw_status = None
self._boiler_state = None
self._heating_state = None
self._cooling_state = None
self._dhw_state = None
self._hvac_mode = None
self._schema_names = None
self._schema_status = None
self._current_temperature = None
self._thermostat_temperature = None
self._boiler_temperature = None
self._temperature = None
self._setpoint = None
self._water_pressure = None
self._schedule_temperature = None
self._schedule_temp = None
self._hvac_mode = None
self._single_thermostat = self._api.single_master_thermostat()
self._unique_id = f"{dev_id}-climate"
@property
def hvac_action(self):
"""Return the current hvac action."""
if self._heating_status or self._boiler_status or self._dhw_status:
return CURRENT_HVAC_HEAT
if self._cooling_status:
return CURRENT_HVAC_COOL
return CURRENT_HVAC_IDLE
"""Return the current action."""
if self._single_thermostat:
if self._heating_state or self._boiler_state:
return CURRENT_HVAC_HEAT
if self._cooling_state:
return CURRENT_HVAC_COOL
return CURRENT_HVAC_IDLE
if self._heating_state is not None or self._boiler_state is not None:
if self._setpoint > self._temperature:
return CURRENT_HVAC_HEAT
return CURRENT_HVAC_IDLE
@property
def name(self):
"""Return the name of the thermostat, if any."""
return self._name
@property
def device_info(self) -> Dict[str, any]:
"""Return the device information."""
device_information = {
"identifiers": {(DOMAIN, self._dev_id)},
"name": self._name,
"manufacturer": "Plugwise",
"model": self._model.replace("_", " ").title(),
}
if self._dev_id != self._api.gateway_id:
device_information["via_device"] = (DOMAIN, self._api.gateway_id)
del device_information["via_device"]
return device_information
@property
def icon(self):
"""Return the icon to use in the frontend."""
return DEFAULT_ICON
return THERMOSTAT_ICON
@property
def supported_features(self):
@ -146,82 +157,47 @@ class ThermostatDevice(ClimateEntity):
def device_state_attributes(self):
"""Return the device specific state attributes."""
attributes = {}
if self._outdoor_temperature:
attributes["outdoor_temperature"] = self._outdoor_temperature
if self._schema_names:
attributes["available_schemas"] = self._schema_names
if len(self._schema_names) > 1:
attributes["available_schemas"] = self._schema_names
if self._selected_schema:
attributes["selected_schema"] = self._selected_schema
if self._boiler_temperature:
attributes["boiler_temperature"] = self._boiler_temperature
if self._water_pressure:
attributes["water_pressure"] = self._water_pressure
return attributes
@property
def preset_modes(self):
"""Return the available preset modes list.
And make the presets with their temperatures available.
"""
"""Return the available preset modes list."""
return self._presets_list
@property
def hvac_modes(self):
"""Return the available hvac modes list."""
if self._heating_status is not None or self._boiler_status is not None:
if self._cooling_status is not None:
return HVAC_MODES_2
return HVAC_MODES_1
return None
if self._heating_state is not None or self._boiler_state is not None:
if self._cooling_state is not None:
return HVAC_MODES_HEAT_COOL
return HVAC_MODES_HEAT_ONLY
@property
def hvac_mode(self):
"""Return current active hvac state."""
if self._schema_status:
return HVAC_MODE_AUTO
if self._heating_status or self._boiler_status or self._dhw_status:
if self._cooling_status:
return HVAC_MODE_HEAT_COOL
return HVAC_MODE_HEAT
return HVAC_MODE_OFF
return self._hvac_mode
@property
def target_temperature(self):
"""Return the target_temperature.
From the XML the thermostat-value is used because it updates 'immediately'
compared to the target_temperature-value. This way the information on the card
is "immediately" updated after changing the preset, temperature, etc.
"""
return self._thermostat_temperature
"""Return the target_temperature."""
return self._setpoint
@property
def preset_mode(self):
"""Return the active selected schedule-name.
Or, return the active preset, or return Temporary in case of a manual change
in the set-temperature with a weekschedule active.
Or return Manual in case of a manual change and no weekschedule active.
"""
"""Return the active preset."""
if self._presets:
presets = self._presets
preset_temperature = presets.get(self._preset_mode, "none")
if self.hvac_mode == HVAC_MODE_AUTO:
if self._thermostat_temperature == self._schedule_temperature:
return f"{self._selected_schema}"
if self._thermostat_temperature == preset_temperature:
return self._preset_mode
return "Temporary"
if self._thermostat_temperature != preset_temperature:
return "Manual"
return self._preset_mode
return None
@property
def current_temperature(self):
"""Return the current room temperature."""
return self._current_temperature
return self._temperature
@property
def min_temp(self):
@ -238,62 +214,93 @@ class ThermostatDevice(ClimateEntity):
"""Return the unit of measured temperature."""
return TEMP_CELSIUS
def set_temperature(self, **kwargs):
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
_LOGGER.debug("Adjusting temperature")
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is not None and self._min_temp < temperature < self._max_temp:
_LOGGER.debug("Changing temporary temperature")
self._api.set_temperature(self._domain_objects, temperature)
if (temperature is not None) and (
self._min_temp < temperature < self._max_temp
):
try:
await self._api.set_temperature(self._loc_id, temperature)
self._setpoint = temperature
self.async_write_ha_state()
except Smile.PlugwiseError:
_LOGGER.error("Error while communicating to device")
else:
_LOGGER.error("Invalid temperature requested")
def set_hvac_mode(self, hvac_mode):
async def async_set_hvac_mode(self, hvac_mode):
"""Set the hvac mode."""
_LOGGER.debug("Adjusting hvac_mode (i.e. schedule/schema)")
schema_mode = "false"
state = SCHEDULE_OFF
if hvac_mode == HVAC_MODE_AUTO:
schema_mode = "true"
self._api.set_schema_state(
self._domain_objects, self._last_active_schema, schema_mode
)
state = SCHEDULE_ON
try:
await self._api.set_temperature(self._loc_id, self._schedule_temp)
self._setpoint = self._schedule_temp
except Smile.PlugwiseError:
_LOGGER.error("Error while communicating to device")
try:
await self._api.set_schedule_state(
self._loc_id, self._last_active_schema, state
)
self._hvac_mode = hvac_mode
self.async_write_ha_state()
except Smile.PlugwiseError:
_LOGGER.error("Error while communicating to device")
def set_preset_mode(self, preset_mode):
async def async_set_preset_mode(self, preset_mode):
"""Set the preset mode."""
_LOGGER.debug("Changing preset mode")
self._api.set_preset(self._domain_objects, preset_mode)
try:
await self._api.set_preset(self._loc_id, preset_mode)
self._preset_mode = preset_mode
self._setpoint = self._presets.get(self._preset_mode, "none")[0]
self.async_write_ha_state()
except Smile.PlugwiseError:
_LOGGER.error("Error while communicating to device")
def update(self):
"""Update the data from the thermostat."""
_LOGGER.debug("Update called")
self._direct_objects = self._api.get_direct_objects()
self._domain_objects = self._api.get_domain_objects()
self._outdoor_temperature = self._api.get_outdoor_temperature(
self._domain_objects
)
self._selected_schema = self._api.get_active_schema_name(self._domain_objects)
self._last_active_schema = self._api.get_last_active_schema_name(
self._domain_objects
)
self._preset_mode = self._api.get_current_preset(self._domain_objects)
self._presets = self._api.get_presets(self._domain_objects)
self._presets_list = list(self._api.get_presets(self._domain_objects))
self._boiler_status = self._api.get_boiler_status(self._direct_objects)
self._heating_status = self._api.get_heating_status(self._direct_objects)
self._cooling_status = self._api.get_cooling_status(self._direct_objects)
self._dhw_status = self._api.get_domestic_hot_water_status(self._direct_objects)
self._schema_names = self._api.get_schema_names(self._domain_objects)
self._schema_status = self._api.get_schema_state(self._domain_objects)
self._current_temperature = self._api.get_current_temperature(
self._domain_objects
)
self._thermostat_temperature = self._api.get_thermostat_temperature(
self._domain_objects
)
self._schedule_temperature = self._api.get_schedule_temperature(
self._domain_objects
)
self._boiler_temperature = self._api.get_boiler_temperature(
self._domain_objects
)
self._water_pressure = self._api.get_water_pressure(self._domain_objects)
def _process_data(self):
"""Update the data for this climate device."""
climate_data = self._api.get_device_data(self._dev_id)
heater_central_data = self._api.get_device_data(self._api.heater_id)
if "setpoint" in climate_data:
self._setpoint = climate_data["setpoint"]
if "temperature" in climate_data:
self._temperature = climate_data["temperature"]
if "schedule_temperature" in climate_data:
self._schedule_temp = climate_data["schedule_temperature"]
if "available_schedules" in climate_data:
self._schema_names = climate_data["available_schedules"]
if "selected_schedule" in climate_data:
self._selected_schema = climate_data["selected_schedule"]
if self._selected_schema is not None:
self._schema_status = True
else:
self._schema_status = False
if "last_used" in climate_data:
self._last_active_schema = climate_data["last_used"]
if "presets" in climate_data:
self._presets = climate_data["presets"]
if self._presets:
self._presets_list = list(self._presets)
if "active_preset" in climate_data:
self._preset_mode = climate_data["active_preset"]
if "boiler_state" in heater_central_data:
if heater_central_data["boiler_state"] is not None:
self._boiler_state = heater_central_data["boiler_state"]
if "heating_state" in heater_central_data:
if heater_central_data["heating_state"] is not None:
self._heating_state = heater_central_data["heating_state"]
if "cooling_state" in heater_central_data:
if heater_central_data["cooling_state"] is not None:
self._cooling_state = heater_central_data["cooling_state"]
if self._schema_status:
self._hvac_mode = HVAC_MODE_AUTO
elif self._heating_state is not None or self._boiler_state is not None:
self._hvac_mode = HVAC_MODE_HEAT
if self._cooling_state is not None:
self._hvac_mode = HVAC_MODE_HEAT_COOL
self.async_write_ha_state()