# Smart Thermostat - le chauffage contrôlé par PID

**URL:** <https://forum.hacf.fr/t/smart-thermostat-le-chauffage-controle-par-pid/7633>\
**Category:** Intégration\
**Tags:** climatisation-climate, hacs, chauffage-heating, chauffage, integration\
**Created:** [Novembre 30, 2021, 11:35 UTC](https://forum.hacf.fr/t/smart-thermostat-le-chauffage-controle-par-pid/7633 "2021-11-30T23:35:42Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![ScratMan](https://forum.hacf.fr/letter_avatar_proxy/v4/letter/s/d2c977/32.png) [@ScratMan](https://forum.hacf.fr/u/ScratMan)\
**Post date:** [Novembre 30, 2021, 11:36 UTC](https://forum.hacf.fr/t/smart-thermostat-le-chauffage-controle-par-pid/7633/2 "2021-11-30T23:36:12Z")

</div>

[![hacs_badge](https://img.shields.io/badge/HACS-Custom-orange.svg?style=for-the-badge)](https://github.com/custom-components/hacs)

# HASmartThermostat

## Smart Thermostat avec contrôleur PID pour Home Assistant

Crée un thermostat virtuel avec une régulation de température précise et réactive par contrôleur PID.  
[Principe d’un contrôleur PID](https://fr.wikipedia.org/wiki/R%C3%A9gulateur_PID).  
Ce thermostat peut contrôler n’importe quel système de chauffage ou de climatisation via fil pilote ou relais (déconseillé pour les fortes puissances) par modulation PWM en fonction de la température et de sa variation dans le temps.

![](https://github.com/ScratMan/HASmartThermostat/blob/master/climate_chart.png?raw=true)

## Installation:

L’installation via Home Assistant Community Store est recommandée.

### Installation avec HACS:

Se rendre dans HACS, cliquer sur Intégrations, puis sur le bouton "Ajouter " en bas à droite. Dans le champ de rechercher, entrer «&nbsp;Smart thermostat (PID)&nbsp;» et cliquer sur l’intégration dans la liste en dessous. Cliquer sur «&nbsp;Télécharger avec HACS&nbsp;» pour installer l’intégration.

### Installation manuelle:

1. Télécharger et extraire le code source : [https://github.com/ScratMan/HASmartThermostat/archive/refs/heads/master.zip](https://github.com/ScratMan/HASmartThermostat/archive/refs/heads/master.zip)
2. Se rendre dans le dossier de configuration de Home Assistant (par défaut `homeassistant/.homeassistant/` ; où se trouve le fichier `configuration.yaml`)
3. Créer un dossier `custom_components` s’il n’existe pas
4. Copier le contenu du dossier `custom_components/smart_thermostat` du code source dans un dossier `<conf-dir>/custom_components/smart_thermostat`

## Configuration:

Le Smart Thermostat peut être ajouté à Home Assistant une fois installé en ajoutant une section `climate` au fichier `configuration.yaml`.

### Configuration example:

#### configuration.yaml

```auto
climate:
  - platform: smart_thermostat
    name: Smart Thermostat Example
    unique_id: smart_thermostat_example
    heater: switch.on_off_heater
    target_sensor: sensor.ambient_temperature
    min_temp: 7
    max_temp: 28
    ac_mode: False
    target_temp: 19
    keep_alive:
      seconds: 60
    away_temp: 14
    kp : 5
    ki : 0.01
    kd : 500
    pwm : 00:15:00

```

## Utilisation:

**Traduction en cours**  
The target sensor measures the ambient temperature while the heater switch controls an ON/OFF heating system.  
The PID controller computes the amount of time the heater should remain ON over the PWM period to reach the temperature  
set point, in example with PWM set to 15 minutes, if output is 100% the heater will be kept on for the next 15 minutes  
PWM period. If PID output is 33%, the heater will be switched ON for 5 minutes only.

By default, the PID controller will be called each time the target sensor is updated. When using main powered sensor  
with high sampling rate, the _sampling\_period_ parameter should be used to slow down the PID controller refresh rate.

By adjusting the Kp, Ki and Kd gains, you can tune the system response to your liking. You can find many tutorials for  
guidance on the web. Here are a few useful links:

- [PID Control made easy](https://www.eurotherm.com/temperature-control/pid-control-made-easy/)
- [Practical PID Process Dynamics with Proportional Pressure Controllers](https://clippard.com/cms/wiki/practical-pid-process-dynamics-proportional-pressure-controllers)
- [PID Tuner](https://pidtuner.com/)
- [PID development blog from Brett Beauregard](http://brettbeauregard.com/blog/category/pid/)
- [PID controller explained](https://controlguru.com/table-of-contents/)

To make it quick and simple:

- Kp gain adjusts the proportional part of the error compensation. Higher values means  
stronger reaction to error. Increase the value for faster rise time.
- Ki gain adjusts the integral part. Integral compensates the residual error when temperature settles in a cumulative  
way. The longer the temperature remains below the set point, the higher the integral compensation will be. If your  
system settles below the set point, increase the Ki value. If it overshoots the set point, decrease the Ki value.
- Kd gain adjusts the derivative part of the compensation. Derivative compensates the inertia of the system. If the  
sensor temperature increases quickly between two samples, the PID will decrease the PWM level accordingly to limit the  
overshoot.

![](https://upload.wikimedia.org/wikipedia/commons/4/43/PID_en.svg)

PID output value is the weighted sum of the control terms:  
`error = set_point - current_temperature`  
`di = ` temperature change between last two samples  
`dt = ` time elapsed between last two samples  
`P = Kp * error`  
`I = last_I + (Ki * error * dt)`  
`D = -(Kd * di) / dt`  
`output = P + I + D`  
Output is then limited to 0% to 100% range to control the PWM.

### Autotune (not always working, not recommended to use):

You can use the autotune feature to find some working PID parameters.  
Add the _autotune:_ parameter with the desired tuning rule, and optionally set the noiseband and lookback duration if the  
default 2 hours doesn’t match your HVAC system bandwidth.  
Restart Home Assistant to start the thermostat in autotune mode and set the desired temperature on the thermostat.  
The autotuner will then start analyzing your heating system, measure the sampling rate of the sensor, control the heater  
switch and monitor the temperature changes.

Wait for the autotune to finish by checking the _autotune\_status_ attribute for success. The Kp, Ki and Kd gains will  
then be computed and set according to the selected rule and the thermostat switches to PID.  
The Kp, Ki and Kd gains are also computed using the other rules, and all values are shown in the Home Assistant log  
like this: **«&nbsp;Smart thermostat PID Autotuner output with ziegler-nichols rule: Kp=######, Ki=######, Kd=######&nbsp;»**.  
You should then save for reference the gains computed by the autotuner for future testing.

**Warning** : The thermostat set point can’t be changed once the autotuner has started monitoring the temperature.  
The temperature regulation will work as a basic hysteresis thermostat based on set point and noise band. If your  
heating system and temperature monitoring is slow, reducing the noise band will reduce the temperature oscillations  
around the set point. If the sampling rate of your temperature sensor is too fast (few seconds) or noisy (frequent  
temperature changes) increase the noise band for system stability.

**Warning** : The autotuner result is saved in the entity attributes and restored after Home Assistant is restarted.  
However, it is recommended to save the new gains in the YAML configuration file to keep it in case of Home Assistant  
database’s is corrupted.

### Services

Services can be used in Home Assistant to configure the thermostat.  
The following services are available:\

**Set PID gains:** `smart_thermostat.set_pid_gain`  
Use this service to adjust the PID gains without requiring a restart of Home  
Assistant. Values are saved to Home Assistant database and restored after a restart. Please consider saving  
the final gain parameters in YAML configuration file when satisfied to keep it safe in case of database corruption.  
Optional parameters : kp, ki and kd, as float.  
Example:

```auto
service: smart_thermostat.set_pid_gain
data:
  kp: 11.8
  ki: 0.00878
target:
  entity_id: climate.salle_de_bain

```

**Set preset modes temperatures:** `smart_thermostat.set_preset_temp`  
Use this service to set the temperatures for the preset modes. It can be adjusted  
for all preset modes, if a preset mode is not enabled through YAML, it will be enabled. You can use any preset temp  
parameter available in smart thermostat settings.  
Example:

```auto
service: smart_thermostat.set_preset_temp
data:
  away_temp: 14.6
  boost_temp: 22.5
target:
  entity_id: climate.salle_de_bain

```

**Clear the integral part:** `smart_thermostat.clear_integral`  
Use this service to reset the integral part of the PID controller to 0. Useful  
when tuning the PID gains to quickly test the behavior without waiting the integral to stabilize by itself.

**Reload integration:** `smart_thermostat.reload`  
Use this service to reload the thermostat from scratch without requiring a restart of Home Assistant.

## Parameters:

- **name** (Optional): Name of the thermostat.
- **unique\_id** (Optional): unique entity\_id for the smart thermostat.
- **heater** (Required): entity\_id for heater switch, must be a toggle device. Becomes air conditioning switch when  
ac\_mode is set to True.
- **target\_sensor** (Required): entity\_id for a temperature sensor, target\_sensor.state must be temperature.
- **keep\_alive** (Required): sets update interval for the PWM pulse width. If interval is too big, the PWM granularity  
will be reduced, leading to lower accuracy of temperature control, can be float in seconds, or time hh:mm:ss.
- **kp** (Recommended): Set PID parameter, proportional (p) control value (default 100).
- **ki** (Recommended): Set PID parameter, integral (i) control value (default 0).
- **kd** (Recommended): Set PID parameter, derivative (d) control value (default 0).
- **pwm** (Optional): Set period of the pulse width modulation. If too long, the response time of the thermostat will  
be too slow, leading to lower accuracy of temperature control. Can be float in seconds or time hh:mm:ss (default 15mn).
- **min\_cycle\_duration** (Optional): Set a minimum amount of time that the switch specified in the heater option must  
be in its current state prior to being switched either off or on (useful to protect boilers). Can be float in seconds  
or time hh:mm:ss (default 0s).
- **min\_off\_cycle\_duration** (Optional): When _min\_cycle\_duration_ is specified, Set a minimum amount of time that the  
switch specified in the heater option must remain in OFF state prior to being switched ON. The _min\_cycle\_duration_  
setting is then used for ON cycle only, allowing different minimum cycle time for ON and OFF. Can be float in seconds  
or time hh:mm:ss (default 0s).
- **sampling\_period** (Optional): interval between two computation of the PID. If set to 0, PID computation is called  
each time the temperature sensor sends an update. Can be float in seconds or time hh:mm:ss (default 0)
- **target\_temp\_step** (Optional): the adjustment step of target temperature (valid are 0.1, 0.5 and 1.0, default 0.5 for Celsius  
and 1.0 for Fahrenheit)
- **precision** (Optional): the displayed temperature precision (valid are 0.1, 0.5 and 1.0, default 0.1 for Celsius  
and 1.0 for Fahrenheit)
- **min\_temp** (Optional): Set minimum set point available (default: 7).
- **max\_temp** (Optional): Set maximum set point available (default: 35).
- **target\_temp** (Optional): Set initial target temperature. If not set target temperature will be set to null on  
startup.
- **ac\_mode** (Optional): Set the switch specified in the heater option to be treated as a cooling device instead of a  
heating device. Should be a boolean (default: false).
- **away\_temp** (Optional): Set the temperature used by the «&nbsp;Away&nbsp;» preset. If this is not specified, away\_mode feature will not be available.
- **eco\_temp** (Optional): Set the temperature used by the «&nbsp;Eco&nbsp;» preset. If this is not specified, eco feature will not be available.
- **boost\_temp** (Optional): Set the temperature used by the «&nbsp;Boost&nbsp;» preset. If this is not specified, boost feature will not be available.
- **comfort\_temp** (Optional): Set the temperature used by the «&nbsp;Comfort&nbsp;» preset. If this is not specified, comfort feature will not be available.
- **home\_temp** (Optional): Set the temperature used by the «&nbsp;Home&nbsp;» preset. If this is not specified, home feature will not be available.
- **sleep\_temp** (Optional): Set the temperature used by the «&nbsp;Sleep&nbsp;» preset. If this is not specified, sleep feature will not be available.
- **activity\_temp** (Optional): Set the temperature used by the «&nbsp;Activity&nbsp;» preset. If this is not specified, activity feature will not be available.
- **noiseband** (Optional): set noiseband for autotune (float): Determines by how much the input value  
must overshoot/undershoot the set point before the state changes (default : 0.5).
- **lookback** (Optional): length of the autotune buffer for the signal analysis to detect peaks, can  
be float in seconds, or time hh:mm:ss (default 2 hours).
- **autotune** (Optional): Set the name of the selected rule for autotune settings (ie «&nbsp;ziegler-nichols&nbsp;»). If it’s not set, autotune is disabled. The following  
tuning\_rules are available:

| ruler | Kp\_divisor, Ki\_divisor, Kd\_divisor |
| --- | --- |
| «&nbsp;ziegler-nichols&nbsp;» | 34, 40, 160 |
| «&nbsp;tyreus-luyben&nbsp;» | 44, 9, 126 |
| «&nbsp;ciancone-marlin&nbsp;» | 66, 88, 162 |
| «&nbsp;pessen-integral&nbsp;» | 28, 50, 133 |
| «&nbsp;some-overshoot&nbsp;» | 60, 40, 60 |
| «&nbsp;no-overshoot&nbsp;» | 100, 40, 60 |
| «&nbsp;brewing&nbsp;» | 2.5, 6, 380 |

### Sources

Ce code est issue du projet Smart Thermostat PID:  
[https://github.com/aendle/custom\_components](https://github.com/aendle/custom_components)   
Le module Python PID avec Autotune est basé sur pid-autotune:  
[https://github.com/hirschmann/pid-autotune](https://github.com/hirschmann/pid-autotune)

---

_[View the full topic](https://forum.hacf.fr/t/smart-thermostat-le-chauffage-controle-par-pid/7633)._
