Compare commits

...

8 Commits

Author SHA1 Message Date
Jean-Marc Collin
5b8fb81053 Documentation update for release 2.0.0 2023-02-03 23:17:09 +01:00
Jean-Marc Collin
8b77d9d75f Some switch are not visible in the list of radiators #40 2023-02-03 22:30:33 +01:00
Jean-Marc Collin
3d977c4981 Failure to initialize #39 2023-02-01 10:43:21 +01:00
Jean-Marc Collin
115df52f67 Issue#36 - Error at initialisation
Issue#32 - Error with Fan Modes on thermostat over climate type
2023-01-31 22:19:43 +01:00
Jean-Marc Collin
3371197594 Fix issue#32 Error with Fan Modes on thermostat over climate type 2023-01-31 09:35:27 +01:00
Jean-Marc Collin
7e63c9aa79 Heater can restart after HVAC_MODE_OFF 2023-01-30 07:09:43 +01:00
Jean-Marc Collin
100cfaeac9 Add binary sensors for window sensors 2023-01-30 06:49:39 +01:00
Jean-Marc Collin
77631e94d9 FIX feature selection 2023-01-29 23:21:51 +01:00
12 changed files with 522 additions and 223 deletions

View File

@@ -111,3 +111,30 @@ recorder:
- switch
- climate
- sensor
template:
- binary_sensor:
- name: maison_occupee
unique_id: maison_occupee
state: "{{is_state('person.jmc', 'home') }}"
device_class: occupancy
switch:
- platform: template
switches:
pilote_sdb_rdc:
friendly_name: "Pilote chauffage SDB RDC"
value_template: "{{ is_state_attr('switch_seche_serviettes_sdb_rdc', 'sensor_state', 'on') }}"
turn_on:
service: select.select_option
data:
option: comfort
target:
entity_id: select.seche_serviettes_sdb_rdc_cable_outlet_mode
turn_off:
service: select.select_option
data:
option: comfort-2
target:
entity_id: select.seche_serviettes_sdb_rdc_cable_outlet_mode

View File

@@ -13,12 +13,13 @@
- [HACS installation (recommendé)](#hacs-installation-recommendé)
- [Installation manuelle](#installation-manuelle)
- [Configuration](#configuration)
- [Configuration minimale](#configuration-minimale)
- [Choix des attributs de base](#choix-des-attributs-de-base)
- [Sélectionnez l'entité pilotée](#sélectionnez-lentité-pilotée)
- [Configurez les coefficients de l'algorithme TPI](#configurez-les-coefficients-de-lalgorithme-tpi)
- [Configurer la température préréglée](#configurer-la-température-préréglée)
- [Configurer les portes/fenêtres en allumant/éteignant les thermostats](#configurer-les-portesfenêtres-en-allumantéteignant-les-thermostats)
- [Configurer le mode d'activité ou la détection de mouvement](#configurer-le-mode-dactivité-ou-la-détection-de-mouvement)
- [Configurer la gestion de l'alimentation](#configurer-la-gestion-de-lalimentation)
- [Configurer la gestion de la puissance](#configurer-la-gestion-de-la-puissance)
- [Configurer la présence ou l'occupation](#configurer-la-présence-ou-loccupation)
- [Configuration avancée](#configuration-avancée)
- [Exemples de réglage](#exemples-de-réglage)
@@ -40,16 +41,22 @@
- [Toujours mieux avec Apex-chart pour régler votre thermostat](#toujours-mieux-avec-apex-chart-pour-régler-votre-thermostat)
- [Les contributions sont les bienvenues !](#les-contributions-sont-les-bienvenues)
_Composant développé à l'aide de l'incroyable modèle de développement [[blueprint](https://github.com/custom-components/integration_blueprint)]._
Ce composant personnalisé pour Home Assistant est une mise à niveau et est une réécriture complète du composant "Awesome thermostat" (voir [Github](https://github.com/dadge/awesome_thermostat)) avec l'ajout de fonctionnalités.
# Quand l'utiliser et ne pas l'utiliser
Ce thermostat a pour but de commander un radiateur qui ne fonctionne qu'en mode marche/arrêt. La configuration minimale nécessaire pour utiliser ce thermostat est :
1. un équipement comme un radiateur (un interrupteur),
2. une sonde de température pour la pièce (ou un input_number),
3. un capteur de température externe (pensez à l'intégration météo si vous n'en avez pas)
Ce thermostat peut piloter 2 types d'équipement:
1. un radiateur qui ne fonctionne qu'en mode marche/arrêt (nommé ```thermostat_over_switch```). La configuration minimale nécessaire pour utiliser ce type thermostat est :
a. un équipement comme un radiateur (un ```switch``` ou équivalent),
b. une sonde de température pour la pièce (ou un input_number),
c. un capteur de température externe (pensez à l'intégration météo si vous n'en avez pas)
2. un autre thermostat qui a ses propres modes de fonctionnement (nommé ```thermostat_over_climate```). Pour ce type de thermostat la configuration minimale nécessite :
a. un équipement comme une climatisation qui est pilotée par sa propre entity de type ```climate```,
b. une sonde de température pour la pièce (ou un input_number),
c. un capteur de température externe (pensez à l'intégration météo si vous n'en avez pas)
Le type ```thermostat_over_climate``` permet d'ajouter à votre équipement existant toutes les fonctionnalités fournies par VersatileThermostat. L'entité climate VersatileThermostat pilotera votre entité climate, en la coupant si les fenêtres sont ouvertes, la passant en mode Eco si personne n'est présent, etc. Cf. [ici](#pourquoi-une-nouvelle-implémentation-du-thermostat). Pour ce type de thermostat, les cycles éventuels de chauffe sont pilotés par l'entité climate sous-jacente et pas par le Versatile Thermostat lui-même.
Parce que cette intégration vise à commander le radiateur en tenant compte du préréglage configuré (preset) et de la température ambiante, ces informations sont obligatoires.
@@ -100,28 +107,44 @@ La configuration peut être modifiée via la même interface. Sélectionnez simp
Suivez ensuite les étapes de configuration comme suit :
## Configuration minimale
## Choix des attributs de base
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-main.png?raw=true)
Donnez les principaux attributs obligatoires :
1. un nom (sera le nom de l'intégration et aussi le nom de l'entité climate)
2. un identifiant d'entité d'équipement qui représente l'élément chauffant. Cet équipement doit pouvoir s'allumer ou s'éteindre,
3. un identifiant d'entité de capteur de température qui donne la température de la pièce dans laquelle le radiateur est installé,
4. une entité capteur de température donnant la température extérieure. Si vous n'avez pas de capteur externe, vous pouvez utiliser l'intégration météo locale
5. une durée de cycle en minutes. A chaque cycle, le radiateur s'allumera puis s'éteindra pendant une durée calculée afin d'atteindre la température ciblée (voir [preset](#configure-the-preset-temperature) ci-dessous),
6. Algorithme à utiliser. Aujourd'hui, seul l'algorithme TPI est disponible. Voir [algorithme](#algorithme)
2. le type de thermostat ```thermostat_over_switch``` pour piloter un radiateur commandé par un switch ou ```thermostat_over_climate``` pour piloter un autre thermostat. Cf. [ci-dessus](#pourquoi-une-nouvelle-implémentation-du-thermostat)
4. un identifiant d'entité de capteur de température qui donne la température de la pièce dans laquelle le radiateur est installé,
5. une entité capteur de température donnant la température extérieure. Si vous n'avez pas de capteur externe, vous pouvez utiliser l'intégration météo locale
6. une durée de cycle en minutes. A chaque cycle, le radiateur s'allumera puis s'éteindra pendant une durée calculée afin d'atteindre la température ciblée (voir [preset](#configure-the-preset-temperature) ci-dessous),
7. les températures minimales et maximales du thermostat,
8. la liste des fonctionnalités qui seront utilisées pour ce thermostat. En fonction de vos choix, les écrans de configuration suivants s'afficheront ou pas.
> ![Astuce](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/tips.png?raw=true) _*Notes*_
1. Les calculs sont effectués à chaque cycle. Donc en cas de changement de conditions, il faudra attendre le prochain cycle pour voir un changement. Pour cette raison, le cycle ne doit pas être trop long. **5 min est une bonne valeur**,
1. avec le type ```thermostat_over_swutch```, les calculs sont effectués à chaque cycle. Donc en cas de changement de conditions, il faudra attendre le prochain cycle pour voir un changement. Pour cette raison, le cycle ne doit pas être trop long. **5 min est une bonne valeur**,
2. si le cycle est trop court, le radiateur ne pourra jamais atteindre la température cible en effet pour le radiateur à accumulation et il sera sollicité inutilement
## Sélectionnez l'entité pilotée
En fonction de votre choix sur le type de thermostat, vous devrez choisir une entité de type switch ou une entité de type climate. Seules les entités compatibles sont présentées.
Pour un thermostat de type ```thermostat_over_switch```:
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-linked-entity.png?raw=true)
L'algorithme à utiliser est aujourd'hui limité à TPI est disponible. Voir [algorithme](#algorithme)
Pour un thermostat de type ```thermostat_over_climate```:
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-linked-entity2.png?raw=true)
## Configurez les coefficients de l'algorithme TPI
Cliquez sur 'Valider' sur la page précédente et vous y arriverez :
Si vous avez choisi un thermostat de type ```thermostat_over_switch``` vous arriverez sur cette page :
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-tpi.png?raw=true)
Vous devez donner :
1. le coefficient coef_int de l'algorithme TPI,
2. le coefficient coef_ext de l'algorithme TPI
Pour plus d'informations sur l'algorithme TPI et son réglage, veuillez vous référer à [algorithm](#algorithm).
## Configurer la température préréglée
@@ -144,7 +167,7 @@ Le mode préréglé (preset) vous permet de préconfigurer la température cibl
5. Si vous ne souhaitez pas utiliser le préréglage, indiquez 0 comme température. Le préréglage sera alors ignoré et ne s'affichera pas dans le composant front
## Configurer les portes/fenêtres en allumant/éteignant les thermostats
Cliquez sur 'Valider' sur la page précédente et vous y arriverez :
Si vous avez choisi la fonctionnalité ```Avec détection des ouvertures```, cliquez sur 'Valider' sur la page précédente et vous y arriverez :
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-window.png?raw=true)
@@ -159,7 +182,7 @@ Et c'est tout ! votre thermostat s'éteindra lorsque les fenêtres seront ouvert
2. Si vous n'avez pas de capteur de fenêtre/porte dans votre chambre, laissez simplement l'identifiant de l'entité du capteur vide
## Configurer le mode d'activité ou la détection de mouvement
Cliquez sur 'Valider' sur la page précédente et vous y arriverez :
Si vous avez choisi la fonctionnalité ```Avec détection de mouvement```, cliquez sur 'Valider' sur la page précédente et vous y arriverez :
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-motion.png?raw=true)
@@ -181,9 +204,9 @@ Pour que cela fonctionne, le thermostat climatique doit être en mode prérégl
> ![Astuce](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/tips.png?raw=true) _*Notes*_
1. Sachez que comme pour les autres modes prédéfinis, ``Activity`` ne sera proposé que s'il est correctement configuré. En d'autres termes, les 4 clés de configuration doivent être définies si vous souhaitez voir l'activité dans l'interface de l'assistant domestique
## Configurer la gestion de l'alimentation
## Configurer la gestion de la puissance
Cliquez sur 'Valider' sur la page précédente et vous arriverez ici :
Si vous avez choisi la fonctionnalité ```Avec détection de la puissance```, cliquez sur 'Valider' sur la page précédente et vous arriverez ici :
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-power.png?raw=true)
@@ -193,13 +216,13 @@ Notez que toutes les valeurs de puissance doivent avoir les mêmes unités (kW o
Cela vous permet de modifier la puissance maximale au fil du temps à l'aide d'un planificateur ou de ce que vous voulez.
> ![Astuce](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/tips.png?raw=true) _*Notes*_
1. En cas de délestage, le radiateur est réglé sur le préréglage nommé ``power``. Il s'agit d'un préréglage caché, vous ne pouvez pas le sélectionner manuellement.
1. En cas de délestage, le radiateur est réglé sur le préréglage nommé ```power```. Il s'agit d'un préréglage caché, vous ne pouvez pas le sélectionner manuellement.
2. Je l'utilise pour éviter de dépasser la limite de mon contrat d'électricité lorsqu'un véhicule électrique est en charge. Cela crée une sorte d'autorégulation.
3. Gardez toujours une marge, car la puissance max peut être brièvement dépassée en attendant le calcul du prochain cycle typiquement ou par des équipements non régulés.
4. Si vous ne souhaitez pas utiliser cette fonctionnalité, laissez simplement l'identifiant des entités vide
## Configurer la présence ou l'occupation
Cette fonction vous permet de modifier dynamiquement la température de tous les préréglages du thermostat configurés lorsque personne n'est à la maison ou lorsque quelqu'un rentre à la maison. Pour cela, vous devez configurer la température qui sera utilisée pour chaque préréglage lorsque la présence est désactivée. Lorsque le capteur de présence s'éteint, ces températures seront utilisées. Lorsqu'il se rallume, la température "normale" configurée pour le préréglage est utilisée. Voir [gestion des préréglages](#configure-the-preset-temperature).
Si sélectionnée en première page, cette fonction vous permet de modifier dynamiquement la température de tous les préréglages du thermostat configurés lorsque personne n'est à la maison ou lorsque quelqu'un rentre à la maison. Pour cela, vous devez configurer la température qui sera utilisée pour chaque préréglage lorsque la présence est désactivée. Lorsque le capteur de présence s'éteint, ces températures seront utilisées. Lorsqu'il se rallume, la température "normale" configurée pour le préréglage est utilisée. Voir [gestion des préréglages](#configure-the-preset-temperature).
Pour configurer la présence remplissez ce formulaire :
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-presence.png?raw=true)

View File

@@ -14,6 +14,7 @@
- [Manual installation](#manual-installation)
- [Configuration](#configuration)
- [Minimal configuration update](#minimal-configuration-update)
- [Select the driven entity](#select-the-driven-entity)
- [Configure the TPI algorithm coefficients](#configure-the-tpi-algorithm-coefficients)
- [Configure the preset temperature](#configure-the-preset-temperature)
- [Configure the doors/windows turning on/off the thermostats](#configure-the-doorswindows-turning-onoff-the-thermostats)
@@ -40,18 +41,22 @@
- [Even better with Apex-chart to tune your Thermostat](#even-better-with-apex-chart-to-tune-your-thermostat)
- [Contributions are welcome!](#contributions-are-welcome)
_Component developed by using the amazing development template [[blueprint](https://github.com/custom-components/integration_blueprint)]._
This custom component for Home Assistant is an upgrade and is a complete rewrite of the component "Awesome thermostat" (see [Github](https://github.com/dadge/awesome_thermostat)) with addition of features.
# When to use / not use
This thermostat aims to command a heater which works only in on/off mode. The minimal needed configuration to use this thermostat is:
1. an equipement like a heater (a switch),
2. a temperature sensor for the room (or an input_number),
3. an external temperature sensor (think of the meteo integration if you don't have one)
This thermostat can control 2 types of equipment:
1. a heater that only works in on/off mode (named ```thermostat_over_switch```). The minimum configuration required to use this type of thermostat is:
has. equipment such as a radiator (a ```switch``` or equivalent),
b. a temperature probe for the room (or an input_number),
vs. an external temperature sensor (think about weather integration if you don't have one)
2. another thermostat that has its own operating modes (named ```thermostat_over_climate```). For this type of thermostat, the minimum configuration requires:
has. equipment such as air conditioning which is controlled by its own ```climate``` type entity,
b. a temperature probe for the room (or an input_number),
vs. an external temperature sensor (think about weather integration if you don't have one)
Because this integration aims to command the heater considering the preset configured and the room temperature, those informations are mandatory.
The ```thermostat_over_climate``` type allows you to add all the functionality provided by VersatileThermostat to your existing equipment. The climate VersatileThermostat entity will control your climate entity, turning it off if the windows are open, switching it to Eco mode if no one is present, etc. See [here](#why-a-new-implementation-of-the-thermostat). For this type of thermostat, any heating cycles are controlled by the underlying climate entity and not by the Versatile Thermostat itself.
# Why another thermostat implementation ?
@@ -103,17 +108,28 @@ Then follow the configurations steps as follow:
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-main.png?raw=true)
Give the main mandatory attributes:
1. a name (will be the integration name and also the climate entity name)
2. an equipment entity id which represent the heater. This equipment should be able to switch on or off,
3. a temporature sensor entity id which gives the temperature of the room in which the heater is installed,
4. a temperature sensor entity giving the external temperature. If don't have any external sensor, you can use the local meteo integration
5. a cycle duration in minutes. At each cycle, the heater will be turned on then off for a calculated period in order to reach the targeted temperature (see [preset](#configure-the-preset-temperature) below),
6. Algorithm to use. Today only the TPI algorithm is available. See [algorithm](#algorithm)
1. a name (will be the name of the integration and also the name of the climate entity)
2. the type of thermostat ```thermostat_over_switch``` to control a radiator controlled by a switch or ```thermostat_over_climate``` to control another thermostat. Cf. [above](#why-a-new-thermostat-implementation)
4. a temperature sensor entity identifier which gives the temperature of the room in which the radiator is installed,
5. a temperature sensor entity giving the outside temperature. If you don't have an external sensor, you can use local weather integration
6. a cycle duration in minutes. On each cycle, the heater will cycle on and then off for a calculated time to reach the target temperature (see [preset](#configure-the-preset-temperature) below),
7. minimum and maximum thermostat temperatures,
8. the list of features that will be used for this thermostat. Depending on your choices, the following configuration screens will appear or not.
> ![Tip](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/tips.png?raw=true) _*Notes*_
1. Calculation are done at each cycle. So in case of conditions change, you will have to wait for the next cycle to see a change. For this reason, the cycle should not be too long. **5 min is a good value**,
1. With the ```thermostat_over_switch``` type, calculation are done at each cycle. So in case of conditions change, you will have to wait for the next cycle to see a change. For this reason, the cycle should not be too long. **5 min is a good value**,
2. if the cycle is too short, the heater could never reach the target temperature indeed for heater with accumulation features and it will be unnecessary solicited
## Select the driven entity
Depending on your choice on the type of thermostat, you will have to choose a switch type entity or a climate type entity. Only compatible entities are shown.
For a ```thermostat_over_switch``` thermostat:
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-linked-entity.png?raw=true)
The algorithm to be used today is limited to TPI is available. See [algorithm](#algorithm)
For a ```thermostat_over_climate``` thermostat:
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-linked-entity2.png?raw=true)
## Configure the TPI algorithm coefficients
Click on 'Validate' on the previous page and you will get there:
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-tpi.png?raw=true)
@@ -139,7 +155,7 @@ The preset mode allows you to pre-configurate targeted temperature. Used in conj
5. ff you don't want to use the preseet, give 0 as temperature. The preset will then been ignored and will not displayed in the front component
## Configure the doors/windows turning on/off the thermostats
Click on 'Validate' on the previous page and you will get there:
If you choose the ```Window management``` feature, click on 'Validate' on the previous page and you will get there:
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-window.png?raw=true)
Give the following attributes:
@@ -153,7 +169,7 @@ And that's it ! your thermostat will turn off when the windows is open and be tu
2. If you don't have any window/door sensor in your room, just leave the sensor entity id empty
## Configure the activity mode or motion detection
Click on 'Validate' on the previous page and you will get there:
If you choose the ```Motion management``` feature, lick on 'Validate' on the previous page and you will get there:
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-motion.png?raw=true)
We will now see how to configure the new Activity mode.
@@ -176,7 +192,7 @@ For this to work, the climate thermostat should be in ``Activity`` preset mode.
## Configure the power management
Click on 'Validate' on the previous page and you will get there:
If you choose the ```Power management``` feature, click on 'Validate' on the previous page and you will get there:
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-power.png?raw=true)
This feature allows you to regulate the power consumption of your radiators. Known as shedding, this feature allows you to limit the electrical power consumption of your heater if overpowering conditions are detected. Give a **sensor to the current power consumption of your house**, a **sensor to the max power** that should not be exceeded, the **power consumption of your heater** and the algorithm will not start a radiator if the max power will be exceeded after radiator starts.
@@ -192,7 +208,7 @@ This allows you to change the max power along time using a Scheduler or whatever
4. If you don't want to use this feature, just leave the entities id empty
## Configure the presence or occupancy
This feature allows you to dynamically changes the temperature of all configured Versatile thermostat's presets when nobody is at home or when someone comes back home. For this, you have to configure the temperature that will be used for each preset when presence is off. When the occupancy sensor turns to off, those tempoeratures will be used. When it turns on again the "normal" temperature configured for the preset is used. See [preset management](#configure-the-preset-temperature).
If you choose the ```Presence management``` feature, this feature allows you to dynamically changes the temperature of all configured Versatile thermostat's presets when nobody is at home or when someone comes back home. For this, you have to configure the temperature that will be used for each preset when presence is off. When the occupancy sensor turns to off, those tempoeratures will be used. When it turns on again the "normal" temperature configured for the preset is used. See [preset management](#configure-the-preset-temperature).
To configure presence fills this form:
![image](https://github.com/jmcollin78/versatile_thermostat/blob/main/images/config-presence.png?raw=true)

View File

@@ -34,17 +34,15 @@ from homeassistant.helpers import (
entity_platform,
) # , config_validation as cv
from homeassistant.components.climate.const import (
from homeassistant.components.climate import (
DOMAIN as CLIMATE_DOMAIN,
ATTR_PRESET_MODE,
# ATTR_FAN_MODE,
CURRENT_HVAC_COOL,
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
CURRENT_HVAC_OFF,
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
HVACMode,
HVACAction,
# HVAC_MODE_COOL,
# HVAC_MODE_HEAT,
# HVAC_MODE_OFF,
PRESET_ACTIVITY,
# PRESET_AWAY,
PRESET_BOOST,
@@ -53,7 +51,8 @@ from homeassistant.components.climate.const import (
# PRESET_HOME,
PRESET_NONE,
# PRESET_SLEEP,
SUPPORT_PRESET_MODE,
ClimateEntityFeature,
# ClimateEntityFeature.PRESET_MODE,
# SUPPORT_TARGET_TEMPERATURE,
SERVICE_SET_FAN_MODE,
SERVICE_SET_HUMIDITY,
@@ -63,6 +62,13 @@ from homeassistant.components.climate.const import (
SERVICE_SET_TEMPERATURE,
)
# from homeassistant.components.climate import (
# CURRENT_HVAC_HEAT,
# HVACAction.IDLE,
# HVACAction.OFF,
# HVACAction.COOLING,
# )
from homeassistant.const import (
# UnitOfTemperature,
ATTR_TEMPERATURE,
@@ -220,6 +226,8 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
self._is_over_climate = False
self._underlying_climate = None
self._attr_translation_key = "versatile_thermostat"
self.post_init(entry_infos)
def post_init(self, entry_infos):
@@ -297,7 +305,7 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
# TODO if self.ac_mode:
# self.hvac_list = [HVAC_MODE_COOL, HVAC_MODE_OFF]
# else:
self._hvac_list = [HVAC_MODE_HEAT, HVAC_MODE_OFF]
self._hvac_list = [HVACMode.HEAT, HVACMode.OFF]
self._unit = UnitOfTemperature.CELSIUS
# Will be restored if possible
self._hvac_mode = None # HVAC_MODE_OFF
@@ -383,7 +391,7 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
# Calculate all possible presets
self._attr_preset_modes = [PRESET_NONE]
if len(presets):
self._support_flags = SUPPORT_FLAGS | SUPPORT_PRESET_MODE
self._support_flags = SUPPORT_FLAGS | ClimateEntityFeature.PRESET_MODE
for key, val in presets.items():
if val != 0.0:
@@ -741,7 +749,7 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
# Set default state to off
if not self._hvac_mode:
self._hvac_mode = HVAC_MODE_OFF
self._hvac_mode = HVACMode.OFF
_LOGGER.info(
"%s - restored state is target_temp=%.1f, preset_mode=%s, hvac_mode=%s",
@@ -774,6 +782,50 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
return self._hvac_list
@property
def fan_mode(self) -> str | None:
"""Return the fan setting.
Requires ClimateEntityFeature.FAN_MODE.
"""
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.fan_mode
return None
@property
def fan_modes(self) -> list[str] | None:
"""Return the list of available fan modes.
Requires ClimateEntityFeature.FAN_MODE.
"""
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.fan_modes
return []
@property
def swing_mode(self) -> str | None:
"""Return the swing setting.
Requires ClimateEntityFeature.SWING_MODE.
"""
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.swing_mode
return None
@property
def swing_modes(self) -> list[str] | None:
"""Return the list of available swing modes.
Requires ClimateEntityFeature.SWING_MODE.
"""
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.swing_modes
return None
@property
def temperature_unit(self):
"""Return the unit of measurement."""
@@ -796,13 +848,13 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.hvac_action
if self._hvac_mode == HVAC_MODE_OFF:
return CURRENT_HVAC_OFF
if self._hvac_mode == HVACMode.OFF:
return HVACAction.OFF
if not self._is_device_active:
return CURRENT_HVAC_IDLE
return HVACAction.IDLE
if self._ac_mode:
return CURRENT_HVAC_COOL
return CURRENT_HVAC_HEAT
return HVACAction.COOLING
return HVACAction.HEATING
@property
def target_temperature(self):
@@ -820,20 +872,114 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
@property
def _is_device_active(self):
"""If the toggleable device is currently active."""
if self._is_over_climate or not self.hass.states.get(self._heater_entity_id):
return None
return self.hass.states.is_state(self._heater_entity_id, STATE_ON)
if self._is_over_climate:
if self._underlying_climate:
return self._underlying_climate.hvac_action not in [
HVACAction.IDLE,
HVACAction.OFF,
]
else:
return None
else:
return self.hass.states.is_state(self._heater_entity_id, STATE_ON)
@property
def current_temperature(self):
"""Return the sensor temperature."""
return self._cur_temp
@property
def target_temperature_step(self) -> float | None:
"""Return the supported step of target temperature."""
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.target_temperature_step
return None
@property
def target_temperature_high(self) -> float | None:
"""Return the highbound target temperature we try to reach.
Requires ClimateEntityFeature.TARGET_TEMPERATURE_RANGE.
"""
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.target_temperature_high
return None
@property
def target_temperature_low(self) -> float | None:
"""Return the lowbound target temperature we try to reach.
Requires ClimateEntityFeature.TARGET_TEMPERATURE_RANGE.
"""
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.target_temperature_low
return None
@property
def is_aux_heat(self) -> bool | None:
"""Return true if aux heater.
Requires ClimateEntityFeature.AUX_HEAT.
"""
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.is_aux_heat
return None
def turn_aux_heat_on(self) -> None:
"""Turn auxiliary heater on."""
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.turn_aux_heat_on()
raise NotImplementedError()
async def async_turn_aux_heat_on(self) -> None:
"""Turn auxiliary heater on."""
if self._is_over_climate and self._underlying_climate:
await self._underlying_climate.async_turn_aux_heat_on()
raise NotImplementedError()
def turn_aux_heat_off(self) -> None:
"""Turn auxiliary heater off."""
if self._is_over_climate and self._underlying_climate:
return self._underlying_climate.turn_aux_heat_off()
raise NotImplementedError()
async def async_turn_aux_heat_off(self) -> None:
"""Turn auxiliary heater off."""
if self._is_over_climate and self._underlying_climate:
await self._underlying_climate.async_turn_aux_heat_off()
raise NotImplementedError()
@property
def preset_mode(self) -> str | None:
"""Return the current preset mode, e.g., home, away, temp.
Requires ClimateEntityFeature.PRESET_MODE.
"""
return self._attr_preset_mode
@property
def preset_modes(self) -> list[str] | None:
"""Return a list of available preset modes.
Requires ClimateEntityFeature.PRESET_MODE.
"""
return self._attr_preset_modes
async def async_set_hvac_mode(self, hvac_mode):
"""Set new target hvac mode."""
_LOGGER.info("%s - Set hvac mode: %s", self, hvac_mode)
if hvac_mode is None:
return
if self._is_over_climate and self._underlying_climate:
data = {ATTR_ENTITY_ID: self._climate_entity_id, "hvac_mode": hvac_mode}
await self.hass.services.async_call(
@@ -842,14 +988,14 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
# await self._underlying_climate.async_set_hvac_mode(hvac_mode)
self._hvac_mode = hvac_mode # self._underlying_climate.hvac_mode
else:
if hvac_mode == HVAC_MODE_HEAT:
self._hvac_mode = HVAC_MODE_HEAT
if hvac_mode == HVACMode.HEAT:
self._hvac_mode = HVACMode.HEAT
await self._async_control_heating(force=True)
elif hvac_mode == HVAC_MODE_COOL:
self._hvac_mode = HVAC_MODE_COOL
elif hvac_mode == HVACMode.COOL:
self._hvac_mode = HVACMode.COOL
await self._async_control_heating(force=True)
elif hvac_mode == HVAC_MODE_OFF:
self._hvac_mode = HVAC_MODE_OFF
elif hvac_mode == HVACMode.OFF:
self._hvac_mode = HVACMode.OFF
if self._is_device_active:
await self._async_underlying_entity_turn_off()
await self._async_control_heating(force=True)
@@ -1080,10 +1226,10 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
await self.restore_hvac_mode()
elif self._window_state == STATE_ON:
_LOGGER.info(
"%s - Window is open. Set hvac_mode to '%s'", self, HVAC_MODE_OFF
"%s - Window is open. Set hvac_mode to '%s'", self, HVACMode.OFF
)
self.save_hvac_mode()
await self.async_set_hvac_mode(HVAC_MODE_OFF)
await self.async_set_hvac_mode(HVACMode.OFF)
self.update_custom_attributes()
if self._window_call_cancel:
@@ -1155,7 +1301,7 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
async def _check_switch_initial_state(self):
"""Prevent the device from keep running if HVAC_MODE_OFF."""
_LOGGER.debug("%s - Calling _check_switch_initial_state", self)
if self._hvac_mode == HVAC_MODE_OFF and self._is_device_active:
if self._hvac_mode == HVACMode.OFF and self._is_device_active:
_LOGGER.warning(
"The climate mode is OFF, but the switch device is ON. Turning off device %s",
self._heater_entity_id,
@@ -1185,9 +1331,13 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
)
# old_state = event.data.get("old_state")
if new_state is None or new_state.state not in [
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
HVACMode.OFF,
HVACMode.HEAT,
HVACMode.COOL,
HVACMode.HEAT_COOL,
HVACMode.DRY,
HVACMode.AUTO,
HVACMode.FAN_ONLY,
]:
return
self._hvac_mode = new_state.state
@@ -1377,11 +1527,17 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
async def _async_underlying_entity_turn_off(self):
"""Turn heater toggleable device off."""
if not self._is_over_climate:
_LOGGER.debug(
"%s - Stopping underlying switch %s", self, self._heater_entity_id
)
data = {ATTR_ENTITY_ID: self._heater_entity_id}
await self.hass.services.async_call(
HA_DOMAIN, SERVICE_TURN_OFF, data, context=self._context
)
else:
_LOGGER.debug(
"%s - Stopping underlying switch %s", self, self._climate_entity_id
)
data = {ATTR_ENTITY_ID: self._climate_entity_id}
await self.hass.services.async_call(
HA_DOMAIN, SERVICE_TURN_OFF, data, context=self._context
@@ -1443,11 +1599,7 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
self._device_power,
)
ret = self._current_power + self._device_power >= self._current_power_max
if (
not self._overpowering_state
and ret
and not self._hvac_mode == HVAC_MODE_OFF
):
if not self._overpowering_state and ret and not self._hvac_mode == HVACMode.OFF:
_LOGGER.warning(
"%s - overpowering is detected. Heater preset will be set to 'power'",
self,
@@ -1495,8 +1647,8 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
or delta_ext_temp > self._security_delay_min
)
climate_cond: bool = self._is_over_climate and self.hvac_action not in [
CURRENT_HVAC_COOL,
CURRENT_HVAC_IDLE,
HVACAction.COOLING,
HVACAction.IDLE,
]
switch_cond: bool = (
not self._is_over_climate
@@ -1534,7 +1686,7 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
self.save_hvac_mode()
self.save_preset_mode()
await self._async_set_preset_mode_internal(PRESET_SECURITY)
await self.async_set_hvac_mode(HVAC_MODE_OFF)
await self.async_set_hvac_mode(HVACMode.OFF)
if (
self._security_state
@@ -1567,16 +1719,19 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
# Check overpowering condition
overpowering: bool = await self.check_overpowering()
if overpowering:
_LOGGER.debug("%s - End of cycle (0)", self)
_LOGGER.debug("%s - End of cycle (overpowering)", self)
return
security: bool = await self.check_security()
if security:
_LOGGER.debug("%s - End of cycle (1)", self)
_LOGGER.debug("%s - End of cycle (security)", self)
return
# Stop here if we are off
if self._hvac_mode == HVAC_MODE_OFF:
if self._hvac_mode == HVACMode.OFF:
_LOGGER.debug("%s - End of cycle (HVAC_MODE_OFF)", self)
if self._is_device_active:
await self._async_underlying_entity_turn_off()
return
if not self._is_over_climate:
@@ -1606,7 +1761,7 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
_LOGGER.debug("%s - End of cycle (2)", self)
return
if self._hvac_mode == HVAC_MODE_HEAT and on_time_sec > 0:
if self._hvac_mode == HVACMode.HEAT and on_time_sec > 0:
async def _turn_on_off_later(
on: bool, time, heater_action, next_cycle_action
@@ -1616,6 +1771,12 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
self._async_cancel_cycle = None
_LOGGER.debug("%s - Stopping cycle during calculation", self)
if self._hvac_mode == HVACMode.OFF:
_LOGGER.debug("%s - End of cycle (HVAC_MODE_OFF - 2)", self)
if self._is_device_active:
await self._async_underlying_entity_turn_off()
return
if on:
security = (
await self.check_security()
@@ -1822,29 +1983,3 @@ class VersatileThermostat(ClimateEntity, RestoreEntity):
if self._attr_preset_mode == preset:
await self._async_set_preset_mode_internal(preset, force=True)
await self._async_control_heating(force=True)
# No more needed
# @classmethod
# def add_entity(cls, entry_id, entity):
# """Adds an entity into the VersatileRegistry entities"""
# _LOGGER.debug("Adding entity %s", entry_id)
# cls._registry[entry_id] = entity
# _LOGGER.debug("Entity registry is now %s", cls._registry)
#
# @classmethod
# async def update_entity(cls, entry_id, infos):
# """Updates an existing entity referenced by entry_id with the infos in arguments"""
# entity: VersatileThermostat = cls._registry.get(entry_id)
# if entity is None:
# _LOGGER.warning(
# "Tries to update VersatileThermostat entity %s but was not found in thermostat registry",
# entry_id,
# )
# return
#
# _LOGGER.debug("We have found the entity to update")
# entity.post_init(infos)
#
# await entity.async_added_to_hass()

View File

@@ -8,25 +8,20 @@ from collections.abc import Mapping
import voluptuous as vol
from homeassistant.exceptions import HomeAssistantError
from homeassistant.const import TEMPERATURE, UnitOfPower
from homeassistant.util.unit_system import TEMPERATURE_UNITS
from homeassistant.core import callback, async_get_hass
from homeassistant.core import callback
from homeassistant.config_entries import (
ConfigEntry,
ConfigFlow as HAConfigFlow,
OptionsFlow,
)
from homeassistant.data_entry_flow import FlowHandler
from homeassistant.data_entry_flow import FlowResult
from homeassistant.data_entry_flow import FlowHandler, FlowResult
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.entity_registry import (
RegistryEntry,
async_get,
)
from homeassistant.helpers import selector
from homeassistant.components.climate import ClimateEntity, DOMAIN as CLIMATE_DOMAIN
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.components.input_boolean import (
@@ -39,6 +34,7 @@ from homeassistant.components.input_number import (
)
from homeassistant.components.person import DOMAIN as PERSON_DOMAIN
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
from .const import (
@@ -125,35 +121,33 @@ def add_suggested_values_to_schema(
return vol.Schema(schema)
def is_temperature_sensor(sensor: RegistryEntry):
"""Check if a registryEntry is a temperature sensor or assimilable to a temperature sensor"""
if not sensor.entity_id.startswith(
INPUT_NUMBER_DOMAIN
) and not sensor.entity_id.startswith(SENSOR_DOMAIN):
return False
return (
sensor.device_class == TEMPERATURE
or sensor.original_device_class == TEMPERATURE
or sensor.unit_of_measurement in TEMPERATURE_UNITS
)
def is_power_sensor(sensor: RegistryEntry):
"""Check if a registryEntry is a power sensor or assimilable to a temperature sensor"""
if not sensor.entity_id.startswith(
INPUT_NUMBER_DOMAIN
) and not sensor.entity_id.startswith(SENSOR_DOMAIN):
return False
return (
# sensor.device_class == TEMPERATURE
# or sensor.original_device_class == TEMPERATURE
sensor.unit_of_measurement
in [
UnitOfPower.KILO_WATT,
UnitOfPower.WATT,
UnitOfPower.BTU_PER_HOUR,
]
)
# def is_temperature_sensor(sensor: RegistryEntry):
# """Check if a registryEntry is a temperature sensor or assimilable to a temperature sensor"""
# if not sensor.entity_id.startswith(
# INPUT_NUMBER_DOMAIN
# ) and not sensor.entity_id.startswith(SENSOR_DOMAIN):
# return False
# return (
# sensor.device_class == TEMPERATURE
# or sensor.original_device_class == TEMPERATURE
# or sensor.unit_of_measurement in TEMPERATURE_UNITS
# )
#
#
# def is_power_sensor(sensor: RegistryEntry):
# """Check if a registryEntry is a power sensor or assimilable to a temperature sensor"""
# if not sensor.entity_id.startswith(
# INPUT_NUMBER_DOMAIN
# ) and not sensor.entity_id.startswith(SENSOR_DOMAIN):
# return False
# return (
# sensor.unit_of_measurement
# in [
# UnitOfPower.KILO_WATT,
# UnitOfPower.WATT,
# UnitOfPower.BTU_PER_HOUR,
# ]
# )
class VersatileThermostatBaseConfigFlow(FlowHandler):
@@ -166,46 +160,62 @@ class VersatileThermostatBaseConfigFlow(FlowHandler):
super().__init__()
_LOGGER.debug("CTOR BaseConfigFlow infos: %s", infos)
self._infos = infos
self.hass = async_get_hass()
ent_reg = async_get(hass=self.hass)
is_empty: bool = not bool(infos)
# Fix features selection depending to infos
self._infos[CONF_USE_WINDOW_FEATURE] = (
is_empty or self._infos.get(CONF_WINDOW_SENSOR) is not None
)
self._infos[CONF_USE_MOTION_FEATURE] = (
is_empty or self._infos.get(CONF_MOTION_SENSOR) is not None
)
self._infos[CONF_USE_POWER_FEATURE] = is_empty or (
self._infos.get(CONF_POWER_SENSOR) is not None
and self._infos.get(CONF_MAX_POWER_SENSOR) is not None
)
self._infos[CONF_USE_PRESENCE_FEATURE] = (
is_empty or self._infos.get(CONF_PRESENCE_SENSOR) is not None
)
climates = []
switches = []
temp_sensors = []
power_sensors = []
window_sensors = []
presence_sensors = []
# self.hass = async_get_hass()
# ent_reg = async_get(hass=self.hass)
k: str
for k in ent_reg.entities:
v: RegistryEntry = ent_reg.entities[k]
_LOGGER.debug("Looking entity: %s", k)
# if k.startswith(CLIMATE_DOMAIN) and (
# infos is None or k != infos.get("entity_id")
# ):
# _LOGGER.debug("Climate !")
# climates.append(k)
if k.startswith(SWITCH_DOMAIN) or k.startswith(INPUT_BOOLEAN_DOMAIN):
_LOGGER.debug("Switch !")
switches.append(k)
elif is_temperature_sensor(v):
_LOGGER.debug("Temperature sensor !")
temp_sensors.append(k)
elif is_power_sensor(v):
_LOGGER.debug("Power sensor !")
power_sensors.append(k)
elif k.startswith(PERSON_DOMAIN):
_LOGGER.debug("Presence sensor !")
presence_sensors.append(k)
# window sensor
if k.startswith(INPUT_BOOLEAN_DOMAIN):
_LOGGER.debug("Window or presence sensor !")
window_sensors.append(k)
presence_sensors.append(k)
# Special case for climates which are not in EntityRegistry
climates = self.find_all_climates()
# climates = []
# switches = []
# temp_sensors = []
# power_sensors = []
# window_sensors = []
# presence_sensors = []
#
# k: str
# for k in ent_reg.entities:
# v: RegistryEntry = ent_reg.entities[k]
# _LOGGER.debug("Looking entity: %s", k)
# # if k.startswith(CLIMATE_DOMAIN) and (
# # infos is None or k != infos.get("entity_id")
# # ):
# # _LOGGER.debug("Climate !")
# # climates.append(k)
# if k.startswith(SWITCH_DOMAIN) or k.startswith(INPUT_BOOLEAN_DOMAIN):
# _LOGGER.debug("Switch !")
# switches.append(k)
# elif is_temperature_sensor(v):
# _LOGGER.debug("Temperature sensor !")
# temp_sensors.append(k)
# elif is_power_sensor(v):
# _LOGGER.debug("Power sensor !")
# power_sensors.append(k)
# elif k.startswith(PERSON_DOMAIN):
# _LOGGER.debug("Presence sensor !")
# presence_sensors.append(k)
#
# # window sensor and presence
# if k.startswith(INPUT_BOOLEAN_DOMAIN) or k.startswith(BINARY_SENSOR_DOMAIN):
# _LOGGER.debug("Window or presence sensor !")
# window_sensors.append(k)
# presence_sensors.append(k)
#
# # Special case for climates which are not in EntityRegistry
# climates = self.find_all_climates()
self.STEP_USER_DATA_SCHEMA = vol.Schema(
{
@@ -213,8 +223,17 @@ class VersatileThermostatBaseConfigFlow(FlowHandler):
vol.Required(
CONF_THERMOSTAT_TYPE, default=CONF_THERMOSTAT_SWITCH
): vol.In(CONF_THERMOSTAT_TYPES),
vol.Required(CONF_TEMP_SENSOR): vol.In(temp_sensors),
vol.Required(CONF_EXTERNAL_TEMP_SENSOR): vol.In(temp_sensors),
vol.Required(CONF_TEMP_SENSOR): selector.EntitySelector(
selector.EntitySelectorConfig(
domain=[SENSOR_DOMAIN, INPUT_NUMBER_DOMAIN]
),
),
# vol.In(temp_sensors),
vol.Required(CONF_EXTERNAL_TEMP_SENSOR): selector.EntitySelector(
selector.EntitySelectorConfig(
domain=[SENSOR_DOMAIN, INPUT_NUMBER_DOMAIN]
),
), # vol.In(temp_sensors),
vol.Required(CONF_CYCLE_MIN, default=5): cv.positive_int,
vol.Required(CONF_TEMP_MIN, default=7): vol.Coerce(float),
vol.Required(CONF_TEMP_MAX, default=35): vol.Coerce(float),
@@ -227,7 +246,11 @@ class VersatileThermostatBaseConfigFlow(FlowHandler):
self.STEP_THERMOSTAT_SWITCH = vol.Schema(
{
vol.Required(CONF_HEATER): vol.In(switches),
vol.Required(CONF_HEATER): selector.EntitySelector(
selector.EntitySelectorConfig(
domain=[SWITCH_DOMAIN, INPUT_BOOLEAN_DOMAIN]
),
), # vol.In(switches),
vol.Required(
CONF_PROP_FUNCTION, default=PROPORTIONAL_FUNCTION_TPI
): vol.In(
@@ -240,7 +263,9 @@ class VersatileThermostatBaseConfigFlow(FlowHandler):
self.STEP_THERMOSTAT_CLIMATE = vol.Schema(
{
vol.Required(CONF_CLIMATE): vol.In(climates),
vol.Required(CONF_CLIMATE): selector.EntitySelector(
selector.EntitySelectorConfig(domain=CLIMATE_DOMAIN),
), # vol.In(climates),
}
)
@@ -260,14 +285,22 @@ class VersatileThermostatBaseConfigFlow(FlowHandler):
self.STEP_WINDOW_DATA_SCHEMA = vol.Schema(
{
vol.Optional(CONF_WINDOW_SENSOR): vol.In(window_sensors),
vol.Optional(CONF_WINDOW_SENSOR): selector.EntitySelector(
selector.EntitySelectorConfig(
domain=[BINARY_SENSOR_DOMAIN, INPUT_BOOLEAN_DOMAIN]
),
), # vol.In(window_sensors),
vol.Optional(CONF_WINDOW_DELAY, default=30): cv.positive_int,
}
)
self.STEP_MOTION_DATA_SCHEMA = vol.Schema(
{
vol.Optional(CONF_MOTION_SENSOR): vol.In(window_sensors),
vol.Optional(CONF_MOTION_SENSOR): selector.EntitySelector(
selector.EntitySelectorConfig(
domain=[BINARY_SENSOR_DOMAIN, INPUT_BOOLEAN_DOMAIN]
),
), # vol.In(window_sensors),
vol.Optional(CONF_MOTION_DELAY, default=30): cv.positive_int,
vol.Optional(CONF_MOTION_PRESET, default="comfort"): vol.In(
CONF_PRESETS_SELECTIONABLE
@@ -280,8 +313,16 @@ class VersatileThermostatBaseConfigFlow(FlowHandler):
self.STEP_POWER_DATA_SCHEMA = vol.Schema(
{
vol.Optional(CONF_POWER_SENSOR): vol.In(power_sensors),
vol.Optional(CONF_MAX_POWER_SENSOR): vol.In(power_sensors),
vol.Optional(CONF_POWER_SENSOR): selector.EntitySelector(
selector.EntitySelectorConfig(
domain=[SENSOR_DOMAIN, INPUT_NUMBER_DOMAIN]
),
), # vol.In(power_sensors),
vol.Optional(CONF_MAX_POWER_SENSOR): selector.EntitySelector(
selector.EntitySelectorConfig(
domain=[SENSOR_DOMAIN, INPUT_NUMBER_DOMAIN]
),
), # vol.In(power_sensors),
vol.Optional(CONF_DEVICE_POWER, default="1"): vol.Coerce(float),
vol.Optional(CONF_PRESET_POWER, default="13"): vol.Coerce(float),
}
@@ -289,7 +330,15 @@ class VersatileThermostatBaseConfigFlow(FlowHandler):
self.STEP_PRESENCE_DATA_SCHEMA = vol.Schema(
{
vol.Optional(CONF_PRESENCE_SENSOR): vol.In(presence_sensors),
vol.Optional(CONF_PRESENCE_SENSOR): selector.EntitySelector(
selector.EntitySelectorConfig(
domain=[
PERSON_DOMAIN,
BINARY_SENSOR_DOMAIN,
INPUT_BOOLEAN_DOMAIN,
]
),
), # vol.In(presence_sensors),
}
).extend(
{
@@ -601,8 +650,18 @@ class VersatileThermostatOptionsFlowHandler(
"Into OptionsFlowHandler.async_step_presets user_input=%s", user_input
)
next_step = self.async_step_advanced
if self._infos[CONF_USE_WINDOW_FEATURE]:
next_step = self.async_step_window
elif self._infos[CONF_USE_MOTION_FEATURE]:
next_step = self.async_step_motion
elif self._infos[CONF_USE_POWER_FEATURE]:
next_step = self.async_step_power
elif self._infos[CONF_USE_PRESENCE_FEATURE]:
next_step = self.async_step_presence
return await self.generic_step(
"presets", self.STEP_PRESETS_DATA_SCHEMA, user_input, self.async_step_window
"presets", self.STEP_PRESETS_DATA_SCHEMA, user_input, next_step
)
async def async_step_window(self, user_input: dict | None = None) -> FlowResult:
@@ -611,8 +670,15 @@ class VersatileThermostatOptionsFlowHandler(
"Into OptionsFlowHandler.async_step_window user_input=%s", user_input
)
next_step = self.async_step_advanced
if self._infos[CONF_USE_MOTION_FEATURE]:
next_step = self.async_step_motion
elif self._infos[CONF_USE_POWER_FEATURE]:
next_step = self.async_step_power
elif self._infos[CONF_USE_PRESENCE_FEATURE]:
next_step = self.async_step_presence
return await self.generic_step(
"window", self.STEP_WINDOW_DATA_SCHEMA, user_input, self.async_step_motion
"window", self.STEP_WINDOW_DATA_SCHEMA, user_input, next_step
)
async def async_step_motion(self, user_input: dict | None = None) -> FlowResult:
@@ -621,8 +687,14 @@ class VersatileThermostatOptionsFlowHandler(
"Into OptionsFlowHandler.async_step_motion user_input=%s", user_input
)
next_step = self.async_step_advanced
if self._infos[CONF_USE_POWER_FEATURE]:
next_step = self.async_step_power
elif self._infos[CONF_USE_PRESENCE_FEATURE]:
next_step = self.async_step_presence
return await self.generic_step(
"motion", self.STEP_MOTION_DATA_SCHEMA, user_input, self.async_step_power
"motion", self.STEP_MOTION_DATA_SCHEMA, user_input, next_step
)
async def async_step_power(self, user_input: dict | None = None) -> FlowResult:
@@ -631,11 +703,15 @@ class VersatileThermostatOptionsFlowHandler(
"Into OptionsFlowHandler.async_step_power user_input=%s", user_input
)
next_step = self.async_step_advanced
if self._infos[CONF_USE_PRESENCE_FEATURE]:
next_step = self.async_step_presence
return await self.generic_step(
"power",
self.STEP_POWER_DATA_SCHEMA,
user_input,
self.async_step_presence,
next_step,
)
async def async_step_presence(self, user_input: dict | None = None) -> FlowResult:
@@ -666,34 +742,20 @@ class VersatileThermostatOptionsFlowHandler(
async def async_end(self):
"""Finalization of the ConfigEntry creation"""
_LOGGER.debug(
"ConfigFlow.async_finalize - updating entry with: %s", self._infos
)
# Find eventual existing entity to update it
# removing entities from registry (they will be recreated)
if not self._infos[CONF_USE_WINDOW_FEATURE]:
self._infos[CONF_WINDOW_SENSOR] = None
if not self._infos[CONF_USE_MOTION_FEATURE]:
self._infos[CONF_MOTION_SENSOR] = None
if not self._infos[CONF_USE_POWER_FEATURE]:
self._infos[CONF_POWER_SENSOR] = None
self._infos[CONF_MAX_POWER_SENSOR] = None
if not self._infos[CONF_USE_PRESENCE_FEATURE]:
self._infos[CONF_PRESENCE_SENSOR] = None
# No need to do that. Only the update_listener on __init__.py is necessary
# ent_reg = entity_registry.async_get(self.hass)
# for entry in entity_registry.async_entries_for_config_entry(
# ent_reg, self.config_entry.entry_id
# ):
# _LOGGER.info(
# "Removing entity %s due to configuration change", entry.entity_id
# )
# ent_reg.async_remove(entry.entity_id)
# _LOGGER.debug(
# "We have found entities to update: %s", self.config_entry.entry_id
# )
# await VersatileThermostat.update_entity(self.config_entry.entry_id, self._infos)
# for entity_id in reg_entities.values():
# ent_reg.async_remove(entity_id)
#
_LOGGER.info(
"Recreating entry %s due to configuration change",
"Recreating entry %s due to configuration change. New config is now: %s",
self.config_entry.entry_id,
self._infos,
)
self.hass.config_entries.async_update_entry(self.config_entry, data=self._infos)
return self.async_create_entry(title=None, data=None)

View File

@@ -209,5 +209,17 @@
"thermostat_over_climate": "Thermostat over another thermostat"
}
}
},
"entity": {
"climate": {
"versatile_thermostat": {
"states_attributes": {
"preset_mode": {
"power": "Shedding",
"security": "Security"
}
}
}
}
}
}

View File

@@ -209,5 +209,17 @@
"thermostat_over_climate": "Thermostat over another thermostat"
}
}
},
"entity": {
"climate": {
"versatile_thermostat": {
"states_attributes": {
"preset_mode": {
"power": "Shedding",
"security": "Security"
}
}
}
}
}
}

View File

@@ -209,5 +209,17 @@
"thermostat_over_climate": "Thermostat sur un autre thermostat"
}
}
},
"entity": {
"climate": {
"versatile_thermostat": {
"states_attributes": {
"preset_mode": {
"power": "Délestage",
"security": "Sécurité"
}
}
}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 14 KiB