-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathclimate.py
More file actions
1185 lines (1104 loc) · 54.8 KB
/
Copy pathclimate.py
File metadata and controls
1185 lines (1104 loc) · 54.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Adds support for smart (PID) thermostat units.
For more details about this platform, please refer to the documentation at
https://github.com/ScratMan/HASmartThermostat"""
import asyncio
import logging
import time
from abc import ABC
import voluptuous as vol
from homeassistant.core import HomeAssistant
from homeassistant.helpers import condition, entity_platform
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_TEMPERATURE,
CONF_NAME,
CONF_UNIQUE_ID,
EVENT_HOMEASSISTANT_START,
PRECISION_HALVES,
PRECISION_TENTHS,
PRECISION_WHOLE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
STATE_OFF,
STATE_UNKNOWN,
)
from homeassistant.components.number.const import (
ATTR_VALUE,
SERVICE_SET_VALUE,
DOMAIN as NUMBER_DOMAIN
)
from homeassistant.components.input_number import DOMAIN as INPUT_NUMBER_DOMAIN
from homeassistant.core import DOMAIN as HA_DOMAIN, CoreState, callback
from homeassistant.util import slugify
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import (
async_track_state_change,
async_track_time_interval,
)
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity, ClimateEntityFeature
from homeassistant.components.climate import (
ATTR_PRESET_MODE,
HVACMode,
HVACAction,
PRESET_AWAY,
PRESET_NONE,
PRESET_ECO,
PRESET_BOOST,
PRESET_COMFORT,
PRESET_HOME,
PRESET_SLEEP,
PRESET_ACTIVITY,
)
from . import DOMAIN, PLATFORMS
from . import const
from . import pid_controller
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(const.CONF_HEATER): cv.entity_id,
vol.Optional(const.CONF_COOLER): cv.entity_id,
vol.Required(const.CONF_INVERT_HEATER, default=False): cv.boolean,
vol.Required(const.CONF_SENSOR): cv.entity_id,
vol.Optional(const.CONF_OUTDOOR_SENSOR): cv.entity_id,
vol.Optional(const.CONF_AC_MODE): cv.boolean,
vol.Optional(const.CONF_FORCE_OFF_STATE, default=True): cv.boolean,
vol.Optional(const.CONF_MAX_TEMP): vol.Coerce(float),
vol.Optional(const.CONF_MIN_TEMP): vol.Coerce(float),
vol.Optional(CONF_NAME, default=const.DEFAULT_NAME): cv.string,
vol.Optional(CONF_UNIQUE_ID, default='none'): cv.string,
vol.Optional(const.CONF_TARGET_TEMP): vol.Coerce(float),
vol.Optional(const.CONF_HOT_TOLERANCE, default=const.DEFAULT_TOLERANCE): vol.Coerce(float),
vol.Optional(const.CONF_COLD_TOLERANCE, default=const.DEFAULT_TOLERANCE): vol.Coerce(
float),
vol.Optional(const.CONF_MIN_CYCLE_DURATION, default=const.DEFAULT_MIN_CYCLE_DURATION):
vol.All(cv.time_period, cv.positive_timedelta),
vol.Optional(const.CONF_MIN_OFF_CYCLE_DURATION): vol.All(
cv.time_period, cv.positive_timedelta),
vol.Optional(const.CONF_MIN_CYCLE_DURATION_PID_OFF): vol.All(
cv.time_period, cv.positive_timedelta),
vol.Optional(const.CONF_MIN_OFF_CYCLE_DURATION_PID_OFF): vol.All(
cv.time_period, cv.positive_timedelta),
vol.Required(const.CONF_KEEP_ALIVE): vol.All(cv.time_period, cv.positive_timedelta),
vol.Optional(const.CONF_SAMPLING_PERIOD, default=const.DEFAULT_SAMPLING_PERIOD): vol.All(
cv.time_period, cv.positive_timedelta),
vol.Optional(const.CONF_SENSOR_STALL, default=const.DEFAULT_SENSOR_STALL): vol.All(
cv.time_period, cv.positive_timedelta),
vol.Optional(const.CONF_OUTPUT_SAFETY, default=const.DEFAULT_OUTPUT_SAFETY): vol.Coerce(
float),
vol.Optional(const.CONF_INITIAL_HVAC_MODE): vol.In(
[HVACMode.COOL, HVACMode.HEAT, HVACMode.OFF]
),
vol.Optional(const.CONF_PRESET_SYNC_MODE, default=const.DEFAULT_PRESET_SYNC_MODE): vol.In(
['sync', 'none']
),
vol.Optional(const.CONF_AWAY_TEMP): vol.Coerce(float),
vol.Optional(const.CONF_ECO_TEMP): vol.Coerce(float),
vol.Optional(const.CONF_BOOST_TEMP): vol.Coerce(float),
vol.Optional(const.CONF_COMFORT_TEMP): vol.Coerce(float),
vol.Optional(const.CONF_HOME_TEMP): vol.Coerce(float),
vol.Optional(const.CONF_SLEEP_TEMP): vol.Coerce(float),
vol.Optional(const.CONF_ACTIVITY_TEMP): vol.Coerce(float),
vol.Optional(const.CONF_PRECISION): vol.In(
[PRECISION_TENTHS, PRECISION_HALVES, PRECISION_WHOLE]
),
vol.Optional(const.CONF_TARGET_TEMP_STEP): vol.In(
[PRECISION_TENTHS, PRECISION_HALVES, PRECISION_WHOLE]
),
vol.Optional(const.CONF_DIFFERENCE, default=const.DEFAULT_DIFFERENCE): vol.Coerce(float),
vol.Optional(const.CONF_KP, default=const.DEFAULT_KP): vol.Coerce(float),
vol.Optional(const.CONF_KI, default=const.DEFAULT_KI): vol.Coerce(float),
vol.Optional(const.CONF_KD, default=const.DEFAULT_KD): vol.Coerce(float),
vol.Optional(const.CONF_KE, default=const.DEFAULT_KE): vol.Coerce(float),
vol.Optional(const.CONF_PWM, default=const.DEFAULT_PWM): vol.All(
cv.time_period, cv.positive_timedelta
),
vol.Optional(const.CONF_BOOST_PID_OFF, default=False): cv.boolean,
vol.Optional(const.CONF_AUTOTUNE, default=const.DEFAULT_AUTOTUNE): cv.string,
vol.Optional(const.CONF_NOISEBAND, default=const.DEFAULT_NOISEBAND): vol.Coerce(float),
vol.Optional(const.CONF_LOOKBACK, default=const.DEFAULT_LOOKBACK): vol.All(
cv.time_period, cv.positive_timedelta),
vol.Optional(const.CONF_DEBUG, default=False): cv.boolean,
vol.Optional(const.CONF_PERIOD_FOR_DERIVATIVE_CALCULATION, default=const.DEFAULT_PERIOD_FOR_DERIVATIVE_CALCULATION): vol.All(
cv.time_period, cv.positive_timedelta),
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the generic thermostat platform."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
platform = entity_platform.current_platform.get()
assert platform
parameters = {
'name': config.get(CONF_NAME),
'unique_id': config.get(CONF_UNIQUE_ID),
'heater_entity_id': config.get(const.CONF_HEATER),
'cooler_entity_id': config.get(const.CONF_COOLER),
'invert_heater': config.get(const.CONF_INVERT_HEATER),
'sensor_entity_id': config.get(const.CONF_SENSOR),
'ext_sensor_entity_id': config.get(const.CONF_OUTDOOR_SENSOR),
'min_temp': config.get(const.CONF_MIN_TEMP),
'max_temp': config.get(const.CONF_MAX_TEMP),
'target_temp': config.get(const.CONF_TARGET_TEMP),
'hot_tolerance': config.get(const.CONF_HOT_TOLERANCE),
'cold_tolerance': config.get(const.CONF_COLD_TOLERANCE),
'ac_mode': config.get(const.CONF_AC_MODE),
'force_off_state': config.get(const.CONF_FORCE_OFF_STATE),
'min_cycle_duration': config.get(const.CONF_MIN_CYCLE_DURATION),
'min_off_cycle_duration': config.get(const.CONF_MIN_OFF_CYCLE_DURATION),
'min_cycle_duration_pid_off': config.get(const.CONF_MIN_CYCLE_DURATION_PID_OFF),
'min_off_cycle_duration_pid_off': config.get(const.CONF_MIN_OFF_CYCLE_DURATION_PID_OFF),
'keep_alive': config.get(const.CONF_KEEP_ALIVE),
'sampling_period': config.get(const.CONF_SAMPLING_PERIOD),
'sensor_stall': config.get(const.CONF_SENSOR_STALL),
'output_safety': config.get(const.CONF_OUTPUT_SAFETY),
'initial_hvac_mode': config.get(const.CONF_INITIAL_HVAC_MODE),
'preset_sync_mode': config.get(const.CONF_PRESET_SYNC_MODE),
'away_temp': config.get(const.CONF_AWAY_TEMP),
'eco_temp': config.get(const.CONF_ECO_TEMP),
'boost_temp': config.get(const.CONF_BOOST_TEMP),
'comfort_temp': config.get(const.CONF_COMFORT_TEMP),
'home_temp': config.get(const.CONF_HOME_TEMP),
'sleep_temp': config.get(const.CONF_SLEEP_TEMP),
'activity_temp': config.get(const.CONF_ACTIVITY_TEMP),
'precision': config.get(const.CONF_PRECISION),
'target_temp_step': config.get(const.CONF_TARGET_TEMP_STEP),
'unit': hass.config.units.temperature_unit,
'difference': config.get(const.CONF_DIFFERENCE),
'kp': config.get(const.CONF_KP),
'ki': config.get(const.CONF_KI),
'kd': config.get(const.CONF_KD),
'ke': config.get(const.CONF_KE),
'pwm': config.get(const.CONF_PWM),
'boost_pid_off': config.get(const.CONF_BOOST_PID_OFF),
'autotune': config.get(const.CONF_AUTOTUNE),
'noiseband': config.get(const.CONF_NOISEBAND),
'lookback': config.get(const.CONF_LOOKBACK),
'period_for_derivative_calculation': config.get(const.CONF_PERIOD_FOR_DERIVATIVE_CALCULATION),
const.CONF_DEBUG: config.get(const.CONF_DEBUG),
}
smart_thermostat = SmartThermostat(**parameters)
async_add_entities([smart_thermostat])
platform.async_register_entity_service( # type: ignore
"set_pid_gain",
{
vol.Optional("kp"): vol.Coerce(float),
vol.Optional("ki"): vol.Coerce(float),
vol.Optional("kd"): vol.Coerce(float),
vol.Optional("ke"): vol.Coerce(float),
},
"async_set_pid",
)
platform.async_register_entity_service( # type: ignore
"set_pid_mode",
{
vol.Required("mode"): vol.In(['auto', 'off']),
},
"async_set_pid_mode",
)
platform.async_register_entity_service( # type: ignore
"set_preset_temp",
{
vol.Optional("away_temp"): vol.Coerce(float),
vol.Optional("away_temp_disable"): vol.Coerce(bool),
vol.Optional("eco_temp"): vol.Coerce(float),
vol.Optional("eco_temp_disable"): vol.Coerce(bool),
vol.Optional("boost_temp"): vol.Coerce(float),
vol.Optional("boost_temp_disable"): vol.Coerce(bool),
vol.Optional("comfort_temp"): vol.Coerce(float),
vol.Optional("comfort_temp_disable"): vol.Coerce(bool),
vol.Optional("home_temp"): vol.Coerce(float),
vol.Optional("home_temp_disable"): vol.Coerce(bool),
vol.Optional("sleep_temp"): vol.Coerce(float),
vol.Optional("sleep_temp_disable"): vol.Coerce(bool),
vol.Optional("activity_temp"): vol.Coerce(float),
vol.Optional("activity_temp_disable"): vol.Coerce(bool),
},
"async_set_preset_temp",
)
platform.async_register_entity_service( # type: ignore
"clear_integral",
{},
"clear_integral",
)
class SmartThermostat(ClimateEntity, RestoreEntity, ABC):
"""Representation of a Smart Thermostat device."""
def __init__(self, **kwargs):
"""Initialize the thermostat."""
self._name = kwargs.get('name')
self._unique_id = kwargs.get('unique_id')
self._heater_entity_id = kwargs.get('heater_entity_id')
self._cooler_entity_id = kwargs.get('cooler_entity_id', None)
self._heater_polarity_invert = kwargs.get('invert_heater')
self._sensor_entity_id = kwargs.get('sensor_entity_id')
self._ext_sensor_entity_id = kwargs.get('ext_sensor_entity_id')
if self._unique_id == 'none':
self._unique_id = slugify(f"{DOMAIN}_{self._name}_{self._heater_entity_id}")
self._ac_mode = kwargs.get('ac_mode', False)
self._force_off_state = kwargs.get('force_off_state', True)
self._keep_alive = kwargs.get('keep_alive')
self._sampling_period = kwargs.get('sampling_period').seconds
self._sensor_stall = kwargs.get('sensor_stall').seconds
self._output_safety = kwargs.get('output_safety')
self._hvac_mode = kwargs.get('initial_hvac_mode', None)
self._saved_target_temp = kwargs.get('target_temp', None) or kwargs.get('away_temp', None)
self._temp_precision = kwargs.get('precision')
self._target_temperature_step = kwargs.get('target_temp_step')
self._debug = kwargs.get(const.CONF_DEBUG)
self._last_heat_cycle_time = time.time()
self._min_on_cycle_duration_pid_on = kwargs.get('min_cycle_duration')
self._min_off_cycle_duration_pid_on = kwargs.get('min_off_cycle_duration')
self._min_on_cycle_duration_pid_off = kwargs.get('min_cycle_duration_pid_off')
self._min_off_cycle_duration_pid_off = kwargs.get('min_off_cycle_duration_pid_off')
if self._min_off_cycle_duration_pid_on is None:
self._min_off_cycle_duration_pid_on = self._min_on_cycle_duration_pid_on
if self._min_on_cycle_duration_pid_off is None:
self._min_on_cycle_duration_pid_off = self._min_on_cycle_duration_pid_on
if self._min_off_cycle_duration_pid_off is None:
self._min_off_cycle_duration_pid_off = self._min_on_cycle_duration_pid_off
self._active = False
self._trigger_source = None
self._current_temp = None
self._cur_temp_time = None
self._previous_temp = None
self._previous_temp_time = None
self._ext_temp = None
self._temp_lock = asyncio.Lock()
self._min_temp = kwargs.get('min_temp')
self._max_temp = kwargs.get('max_temp')
self._target_temp = kwargs.get('target_temp')
self._unit = kwargs.get('unit')
self._support_flags = ClimateEntityFeature.TARGET_TEMPERATURE
self._support_flags |= ClimateEntityFeature.TURN_OFF
self._support_flags |= ClimateEntityFeature.TURN_ON
self._enable_turn_on_off_backwards_compatibility = False # To be removed after deprecation period
self._attr_preset_mode = 'none'
self._away_temp = kwargs.get('away_temp')
self._eco_temp = kwargs.get('eco_temp')
self._boost_temp = kwargs.get('boost_temp')
self._comfort_temp = kwargs.get('comfort_temp')
self._home_temp = kwargs.get('home_temp')
self._sleep_temp = kwargs.get('sleep_temp')
self._activity_temp = kwargs.get('activity_temp')
self._preset_sync_mode = kwargs.get('preset_sync_mode')
if True in [temp is not None for temp in [self._away_temp,
self._eco_temp,
self._boost_temp,
self._comfort_temp,
self._home_temp,
self._sleep_temp,
self._activity_temp]]:
self._support_flags |= ClimateEntityFeature.PRESET_MODE
self._difference = kwargs.get('difference')
if self._ac_mode:
self._attr_hvac_modes = [HVACMode.COOL, HVACMode.HEAT, HVACMode.OFF]
self._min_out = -self._difference
self._max_out = 0
else:
self._attr_hvac_modes = [HVACMode.HEAT, HVACMode.OFF]
self._min_out = 0
self._max_out = self._difference
self._kp = kwargs.get('kp')
self._ki = kwargs.get('ki')
self._kd = kwargs.get('kd')
self._ke = kwargs.get('ke')
self._pwm = kwargs.get('pwm').seconds
self._p = self._i = self._d = self._e = self._dt = 0
self._control_output = 0
self._force_on = False
self._force_off = False
self._boost_pid_off = kwargs.get('boost_pid_off')
self._autotune = kwargs.get('autotune').lower()
if self._autotune.lower() not in [
"ziegler-nichols",
"tyreus-luyben",
"ciancone-marlin",
"pessen-integral",
"some-overshoot",
"no-overshoot",
"brewing"
]:
self._autotune = "none"
self._lookback = kwargs.get('lookback').seconds + kwargs.get('lookback').days * 86400
self._noiseband = kwargs.get('noiseband')
self._cold_tolerance = abs(kwargs.get('cold_tolerance'))
self._hot_tolerance = abs(kwargs.get('hot_tolerance'))
self._time_changed = 0
self._last_sensor_update = time.time()
self._last_ext_sensor_update = time.time()
self._period_for_derivative_calculation = kwargs.get('period_for_derivative_calculation')
if self._autotune != "none":
self._pid_controller = None
self._pid_autotune = pid_controller.PIDAutotune(self._difference, self._lookback,
self._min_out, self._max_out,
self._noiseband, time.time)
_LOGGER.warning("%s: Autotune will run with the target temperature "
"set after 10 temperature samples from sensor. Changes submitted "
"after doesn't have any effect until autotuning is finished",
self.unique_id)
else:
_LOGGER.debug("%s: PID Gains kp = %s, ki = %s, kd = %s", self.unique_id, self._kp,
self._ki, self._kd)
self._pid_controller = pid_controller.PID(self._kp, self._ki, self._kd, self._ke,
self._min_out, self._max_out,
self._sampling_period, self._cold_tolerance,
self._hot_tolerance, self._period_for_derivative_calculation)
self._pid_controller.mode = "AUTO"
async def async_added_to_hass(self):
"""Run when entity about to be added."""
await super().async_added_to_hass()
# Add listener
self.async_on_remove(
async_track_state_change(
self.hass,
self._sensor_entity_id,
self._async_sensor_changed))
if self._ext_sensor_entity_id is not None:
self.async_on_remove(
async_track_state_change(
self.hass,
self._ext_sensor_entity_id,
self._async_ext_sensor_changed))
self.async_on_remove(
async_track_state_change(
self.hass,
self._heater_entity_id,
self._async_switch_changed))
if self._cooler_entity_id is not None:
self.async_on_remove(
async_track_state_change(
self.hass,
self._cooler_entity_id,
self._async_switch_changed))
if self._keep_alive:
self.async_on_remove(
async_track_time_interval(
self.hass,
self._async_control_heating,
self._keep_alive))
@callback
def _async_startup(*_):
"""Init on startup."""
sensor_state = self.hass.states.get(self._sensor_entity_id)
if sensor_state and sensor_state.state != STATE_UNKNOWN:
self._async_update_temp(sensor_state)
if self._ext_sensor_entity_id is not None:
ext_sensor_state = self.hass.states.get(self._ext_sensor_entity_id)
if ext_sensor_state and ext_sensor_state.state != STATE_UNKNOWN:
self._async_update_ext_temp(ext_sensor_state)
if self.hass.state == CoreState.running:
_async_startup()
else:
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _async_startup)
# Check If we have an old state
old_state = await self.async_get_last_state()
if old_state is not None:
# If we have a previously saved temperature
if old_state.attributes.get(ATTR_TEMPERATURE) is None:
if self._target_temp is None:
if self._ac_mode:
self._target_temp = self.max_temp
else:
self._target_temp = self.min_temp
_LOGGER.warning("%s: No setpoint available in old state, falling back to %s",
self.entity_id, self._target_temp)
else:
self._target_temp = float(old_state.attributes.get(ATTR_TEMPERATURE))
for preset_mode in ['away_temp', 'eco_temp', 'boost_temp', 'comfort_temp', 'home_temp',
'sleep_temp', 'activity_temp']:
if old_state.attributes.get(preset_mode) is not None:
setattr(self, f"_{preset_mode}", float(old_state.attributes.get(preset_mode)))
if old_state.attributes.get(ATTR_PRESET_MODE) is not None:
self._attr_preset_mode = old_state.attributes.get(ATTR_PRESET_MODE)
if isinstance(old_state.attributes.get('pid_i'), (float, int)) and \
self._pid_controller is not None:
self._i = float(old_state.attributes.get('pid_i'))
self._pid_controller.integral = self._i
if not self._hvac_mode and old_state.state:
self.set_hvac_mode(old_state.state)
if old_state.attributes.get('kp') is not None and self._pid_controller is not None:
self._kp = float(old_state.attributes.get('kp'))
self._pid_controller.set_pid_param(kp=self._kp)
elif old_state.attributes.get('Kp') is not None and self._pid_controller is not None:
self._kp = float(old_state.attributes.get('Kp'))
self._pid_controller.set_pid_param(kp=self._kp)
if old_state.attributes.get('ki') is not None and self._pid_controller is not None:
self._ki = float(old_state.attributes.get('ki'))
self._pid_controller.set_pid_param(ki=self._ki)
elif old_state.attributes.get('Ki') is not None and self._pid_controller is not None:
self._ki = float(old_state.attributes.get('Ki'))
self._pid_controller.set_pid_param(ki=self._ki)
if old_state.attributes.get('kd') is not None and self._pid_controller is not None:
self._kd = float(old_state.attributes.get('kd'))
self._pid_controller.set_pid_param(kd=self._kd)
elif old_state.attributes.get('Kd') is not None and self._pid_controller is not None:
self._kd = float(old_state.attributes.get('Kd'))
self._pid_controller.set_pid_param(kd=self._kd)
if old_state.attributes.get('ke') is not None and self._pid_controller is not None:
self._ke = float(old_state.attributes.get('ke'))
self._pid_controller.set_pid_param(ke=self._ke)
elif old_state.attributes.get('Ke') is not None and self._pid_controller is not None:
self._ke = float(old_state.attributes.get('Ke'))
self._pid_controller.set_pid_param(ke=self._ke)
if old_state.attributes.get('pid_mode') is not None and \
self._pid_controller is not None:
self._pid_controller.mode = old_state.attributes.get('pid_mode')
else:
# No previous state, try and restore defaults
if self._target_temp is None:
if self._ac_mode:
self._target_temp = self.max_temp
else:
self._target_temp = self.min_temp
_LOGGER.warning("%s: No setpoint to restore, setting to %s", self.entity_id,
self._target_temp)
# Set default state to off
if not self._hvac_mode:
self._hvac_mode = HVACMode.OFF
await self._async_control_heating(calc_pid=True)
@property
def should_poll(self):
"""Return the polling state."""
return False
@property
def name(self):
"""Return the name of the thermostat."""
return self._name
@property
def unique_id(self):
"""Return a unique ID."""
return self._unique_id
def _get_number_entity_domain(self, entity_id):
return INPUT_NUMBER_DOMAIN if "input_number" in entity_id else NUMBER_DOMAIN
@property
def precision(self):
"""Return the precision of the system."""
if self._temp_precision is not None:
return self._temp_precision
return super().precision
@property
def target_temperature_step(self):
"""Return the supported step of target temperature."""
return self._target_temperature_step
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return self._unit
@property
def current_temperature(self):
"""Return the sensor temperature."""
return self._current_temp
@property
def hvac_mode(self):
"""Return current operation."""
return self._hvac_mode
@property
def hvac_action(self):
"""Return the current running hvac operation if supported.
Need to be one of CURRENT_HVAC_*.
"""
if self._hvac_mode == HVACMode.OFF:
return HVACAction.OFF
if not self._is_device_active:
return HVACAction.IDLE
elif self._hvac_mode == HVACMode.COOL:
return HVACAction.COOLING
return HVACAction.HEATING
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._target_temp
@property
def preset_mode(self):
"""Return the current preset mode, e.g., home, away, temp."""
return self._attr_preset_mode
@property
def preset_modes(self):
"""Return a list of available preset modes."""
preset_modes = [PRESET_NONE]
for mode, preset_mode_temp in self._preset_modes_temp.items():
if preset_mode_temp is not None:
preset_modes.append(mode)
return preset_modes
@property
def _preset_modes_temp(self):
"""Return a list of preset modes and their temperatures"""
return {
PRESET_AWAY: self._away_temp,
PRESET_ECO: self._eco_temp,
PRESET_BOOST: self._boost_temp,
PRESET_COMFORT: self._comfort_temp,
PRESET_HOME: self._home_temp,
PRESET_SLEEP: self._sleep_temp,
PRESET_ACTIVITY: self._activity_temp,
}
@property
def _preset_temp_modes(self):
"""Return a list of preset temperature and their modes"""
return {
self._away_temp: PRESET_AWAY,
self._eco_temp: PRESET_ECO,
self._boost_temp: PRESET_BOOST,
self._comfort_temp: PRESET_COMFORT,
self._home_temp: PRESET_HOME,
self._sleep_temp: PRESET_SLEEP,
self._activity_temp: PRESET_ACTIVITY,
}
@property
def presets(self):
"""Return a dict of available preset and temperatures."""
presets = {}
for mode, preset_mode_temp in self._preset_modes_temp.items():
if preset_mode_temp is not None:
presets.update({mode: preset_mode_temp})
return presets
@property
def _min_on_cycle_duration(self):
if self.pid_mode == 'off':
return self._min_on_cycle_duration_pid_off
return self._min_on_cycle_duration_pid_on
@property
def _min_off_cycle_duration(self):
if self.pid_mode == 'off':
return self._min_off_cycle_duration_pid_off
return self._min_off_cycle_duration_pid_on
@property
def pid_parm(self):
"""Return the pid parameters of the thermostat."""
return self._kp, self._ki, self._kd
@property
def pid_control_p(self):
"""Return the proportional output of PID controller."""
return self._p
@property
def pid_control_i(self):
"""Return the integral output of PID controller."""
return self._i
@property
def pid_control_d(self):
"""Return the derivative output of PID controller."""
return self._d
@property
def pid_control_e(self):
"""Return the external output of external temperature compensation."""
return self._e
@property
def pid_mode(self):
"""Return the PID operating mode."""
if getattr(self, '_pid_controller', None) is not None:
return self._pid_controller.mode.lower()
return 'off'
@property
def pid_control_output(self):
"""Return the pid control output of the thermostat."""
return self._control_output
@property
def extra_state_attributes(self):
"""attributes to include in entity"""
device_state_attributes = {
'away_temp': self._away_temp,
'eco_temp': self._eco_temp,
'boost_temp': self._boost_temp,
'comfort_temp': self._comfort_temp,
'home_temp': self._home_temp,
'sleep_temp': self._sleep_temp,
'activity_temp': self._activity_temp,
"control_output": self._control_output,
"kp": self._kp,
"ki": self._ki,
"kd": self._kd,
"ke": self._ke,
"pid_mode": self.pid_mode,
"pid_i": 0 if self._autotune != "none" else self.pid_control_i,
}
if self._debug:
device_state_attributes.update({
"pid_p": 0 if self._autotune != "none" else self.pid_control_p,
"pid_d": 0 if self._autotune != "none" else self.pid_control_d,
"pid_e": 0 if self._autotune != "none" else self.pid_control_e,
"pid_dt": 0 if self._autotune != "none" else self._dt,
})
if self._autotune != "none":
device_state_attributes.update({
"autotune_status": self._pid_autotune.state,
"autotune_sample_time": self._pid_autotune.sample_time,
"autotune_tuning_rule": self._autotune,
"autotune_set_point": self._pid_autotune.set_point,
"autotune_peak_count": self._pid_autotune.peak_count,
"autotune_buffer_full": round(self._pid_autotune.buffer_full, 2),
"autotune_buffer_length": self._pid_autotune.buffer_length,
})
return device_state_attributes
def set_hvac_mode(self, hvac_mode: HVACMode) -> None:
"""Set new target hvac mode."""
if hvac_mode == HVACMode.HEAT:
self._min_out = 0
self._max_out = self._difference
self._hvac_mode = HVACMode.HEAT
elif hvac_mode == HVACMode.COOL:
self._min_out = -self._difference
self._max_out = 0
self._hvac_mode = HVACMode.COOL
elif hvac_mode == HVACMode.HEAT_COOL:
self._min_out = -self._difference
self._max_out = self._difference
self._hvac_mode = HVACMode.HEAT_COOL
elif hvac_mode == HVACMode.OFF:
self._hvac_mode = HVACMode.OFF
self._control_output = 0
self._previous_temp = None
self._previous_temp_time = None
if self._pid_controller is not None:
self._pid_controller.clear_samples()
if self._pid_controller:
self._pid_controller.out_max = self._max_out
self._pid_controller.out_min = self._min_out
async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
"""Set new target hvac mode."""
await self._async_heater_turn_off(force=True)
if hvac_mode == HVACMode.HEAT:
self._min_out = 0
self._max_out = self._difference
self._hvac_mode = HVACMode.HEAT
elif hvac_mode == HVACMode.COOL:
self._min_out = -self._difference
self._max_out = 0
self._hvac_mode = HVACMode.COOL
elif hvac_mode == HVACMode.HEAT_COOL:
self._min_out = -self._difference
self._max_out = self._difference
self._hvac_mode = HVACMode.HEAT_COOL
elif hvac_mode == HVACMode.OFF:
self._hvac_mode = HVACMode.OFF
self._control_output = 0
if self._pwm:
_LOGGER.debug("%s: Turn OFF heater from async_set_hvac_mode(%s)", self.entity_id,
hvac_mode)
await self._async_heater_turn_off(force=True)
else:
data = {ATTR_ENTITY_ID: self._heater_entity_id,
ATTR_VALUE: self._control_output}
_LOGGER.debug("%s: Set heater to %s from async_set_hvac_mode(%s)", self.entity_id,
self._control_output, hvac_mode)
await self.hass.services.async_call(
self._get_number_entity_domain(self._heater_entity_id),
SERVICE_SET_VALUE,
data)
if self._cooler_entity_id is not None:
data = {ATTR_ENTITY_ID: self._cooler_entity_id,
ATTR_VALUE: self._control_output}
_LOGGER.debug("%s: Set cooler to %s from async_set_hvac_mode(%s)", self.entity_id,
self._control_output, hvac_mode)
await self.hass.services.async_call(
self._get_number_entity_domain(self._cooler_entity_id),
SERVICE_SET_VALUE,
data)
# Clear the samples to avoid integrating the off period
self._previous_temp = None
self._previous_temp_time = None
if self._pid_controller is not None:
self._pid_controller.clear_samples()
else:
_LOGGER.error("%s: Unrecognized HVAC mode: %s", self.entity_id, hvac_mode)
return
if self._pid_controller:
self._pid_controller.out_max = self._max_out
self._pid_controller.out_min = self._min_out
if self._hvac_mode != HVACMode.OFF:
await self._async_control_heating(calc_pid=True)
# Ensure we update the current operation after changing the mode
self.async_write_ha_state()
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
return
if self._current_temp is not None and temperature > self._current_temp:
self._force_on = True
elif self._current_temp is not None and temperature < self._current_temp:
self._force_off = True
if temperature in self._preset_temp_modes and self._preset_sync_mode == 'sync':
await self.async_set_preset_mode(self._preset_temp_modes[temperature])
else:
await self.async_set_preset_mode(PRESET_NONE)
self._target_temp = temperature
await self._async_control_heating(calc_pid=True)
self.async_write_ha_state()
async def async_set_pid(self, **kwargs):
"""Set PID parameters."""
gain_kp = kwargs.get('kp', None)
gain_ki = kwargs.get('ki', None)
gain_kd = kwargs.get('kd', None)
gain_ke = kwargs.get('ke', None)
if gain_kp is not None:
self._kp = float(gain_kp)
if gain_ki is not None:
self._ki = float(gain_ki)
if gain_kd is not None:
self._kd = float(gain_kd)
if gain_ke is not None:
self._ke = float(gain_ke)
self._pid_controller.set_pid_param(self._kp, self._ki, self._kd, self._ke)
await self._async_control_heating(calc_pid=True)
async def async_set_pid_mode(self, **kwargs):
"""Set PID parameters."""
mode = kwargs.get('mode', None)
if str(mode).upper() in ['AUTO', 'OFF'] and self._pid_controller is not None:
self._pid_controller.mode = str(mode).upper()
await self._async_control_heating(calc_pid=True)
async def async_set_preset_temp(self, **kwargs):
"""Set the presets modes temperatures."""
away_temp = kwargs.get('away_temp', None)
eco_temp = kwargs.get('eco_temp', None)
boost_temp = kwargs.get('boost_temp', None)
comfort_temp = kwargs.get('comfort_temp', None)
home_temp = kwargs.get('home_temp', None)
sleep_temp = kwargs.get('sleep_temp', None)
activity_temp = kwargs.get('activity_temp', None)
away_temp_disable = kwargs.get('away_temp_disable', None)
eco_temp_disable = kwargs.get('eco_temp_disable', None)
boost_temp_disable = kwargs.get('boost_temp_disable', None)
comfort_temp_disable = kwargs.get('comfort_temp_disable', None)
home_temp_disable = kwargs.get('home_temp_disable', None)
sleep_temp_disable = kwargs.get('sleep_temp_disable', None)
activity_temp_disable = kwargs.get('activity_temp_disable', None)
if away_temp is not None:
self._away_temp = max(min(float(away_temp), self.max_temp), self.min_temp)
if eco_temp is not None:
self._eco_temp = max(min(float(eco_temp), self.max_temp), self.min_temp)
if boost_temp is not None:
self._boost_temp = max(min(float(boost_temp), self.max_temp), self.min_temp)
if comfort_temp is not None:
self._comfort_temp = max(min(float(comfort_temp), self.max_temp), self.min_temp)
if home_temp is not None:
self._home_temp = max(min(float(home_temp), self.max_temp), self.min_temp)
if sleep_temp is not None:
self._sleep_temp = max(min(float(sleep_temp), self.max_temp), self.min_temp)
if activity_temp is not None:
self._activity_temp = max(min(float(activity_temp), self.max_temp), self.min_temp)
if away_temp_disable is not None and away_temp_disable:
self._away_temp = None
if eco_temp_disable is not None and eco_temp_disable:
self._eco_temp = None
if boost_temp_disable is not None and boost_temp_disable:
self._boost_temp = None
if comfort_temp_disable is not None and comfort_temp_disable:
self._comfort_temp = None
if home_temp_disable is not None and home_temp_disable:
self._home_temp = None
if sleep_temp_disable is not None and sleep_temp_disable:
self._sleep_temp = None
if activity_temp_disable is not None and activity_temp_disable:
self._activity_temp = None
await self._async_control_heating(calc_pid=True)
async def clear_integral(self, **kwargs):
"""Clear the integral value."""
self._pid_controller.integral = 0.0
self._i = self._pid_controller.integral
self.async_write_ha_state()
@property
def min_temp(self):
"""Return the minimum temperature."""
if self._min_temp:
return self._min_temp
# get default temp from super class
return super().min_temp
@property
def max_temp(self):
"""Return the maximum temperature."""
if self._max_temp:
return self._max_temp
# Get default temp from super class
return super().max_temp
async def _async_sensor_changed(self, entity_id, old_state, new_state):
"""Handle temperature changes."""
if new_state is None:
return
self._previous_temp_time = self._cur_temp_time
self._cur_temp_time = time.time()
self._async_update_temp(new_state)
self._trigger_source = 'sensor'
_LOGGER.debug("%s: Received new temperature: %s", self.entity_id, self._current_temp)
await self._async_control_heating(calc_pid=True)
self.async_write_ha_state()
async def _async_ext_sensor_changed(self, entity_id, old_state, new_state):
"""Handle temperature changes."""
if new_state is None:
return
self._async_update_ext_temp(new_state)
self._trigger_source = 'ext_sensor'
_LOGGER.debug("%s: Received new external temperature: %s", self.entity_id, self._ext_temp)
await self._async_control_heating(calc_pid=False)
@callback
def _async_switch_changed(self, entity_id, old_state, new_state):
"""Handle heater switch state changes."""
if new_state is None:
return
self.async_write_ha_state()
@callback
def _async_update_temp(self, state):
"""Update thermostat with latest state from sensor."""
try:
self._previous_temp = self._current_temp
self._current_temp = float(state.state)
self._last_sensor_update = time.time()
except ValueError as ex:
_LOGGER.debug("%s: Unable to update from sensor %s: %s", self.entity_id,
self._sensor_entity_id, ex)
@callback
def _async_update_ext_temp(self, state):
"""Update thermostat with latest state from sensor."""
try:
self._ext_temp = float(state.state)
self._last_ext_sensor_update = time.time()
except ValueError as ex:
_LOGGER.debug("%s: Unable to update from sensor %s: %s", self.entity_id,
self._ext_sensor_entity_id, ex)
async def _async_control_heating(self, time_func=None, calc_pid=False):
"""Run PID controller, optional autotune for faster integration"""
async with self._temp_lock:
if not self._active and None not in (self._current_temp, self._target_temp):
self._active = True
_LOGGER.info("%s: Obtained temperature %s with set point %s. Activating Smart"
"Thermostat.", self.entity_id, self._current_temp, self._target_temp)
if not self._active or self._hvac_mode == HVACMode.OFF:
if self._force_off_state and self._hvac_mode == HVACMode.OFF and \
self._is_device_active:
_LOGGER.debug("%s: %s is active while HVAC mode is %s. Turning it OFF.",
self.entity_id, self.heater_or_cooler_entity, self._hvac_mode)
if self._pwm:
await self._async_heater_turn_off(force=True)
else:
self._control_output = 0
data = {ATTR_ENTITY_ID: self._heater_entity_id,
ATTR_VALUE: self._control_output}
await self.hass.services.async_call(
self._get_number_entity_domain(self._heater_entity_id),
SERVICE_SET_VALUE,
data)
if self._cooler_entity_id is not None:
data = {ATTR_ENTITY_ID: self._cooler_entity_id,
ATTR_VALUE: self._control_output}
await self.hass.services.async_call(
self._get_number_entity_domain(self._cooler_entity_id),
SERVICE_SET_VALUE,
data)
self.async_write_ha_state()
return
if self._sensor_stall != 0 and time.time() - self._last_sensor_update > \
self._sensor_stall:
# sensor not updated for too long, considered as stall, set to safety level
self._control_output = self._output_safety
elif calc_pid or self._sampling_period != 0:
await self.calc_output()
await self.set_control_value()
self.async_write_ha_state()
@property
def _is_device_active(self):
if self._pwm:
"""If the toggleable device is currently active."""
if self._heater_polarity_invert:
return self.hass.states.is_state(self.heater_or_cooler_entity, STATE_OFF)
return self.hass.states.is_state(self.heater_or_cooler_entity, STATE_ON)
else:
"""If the valve device is currently active."""
try: # do not throw an error if the state is not yet available on startup
return float(self.hass.states.get(self.heater_or_cooler_entity).state) > 0
except:
return False
@property
def supported_features(self):
"""Return the list of supported features."""
return self._support_flags
@property
def heater_or_cooler_entity(self):
"""Return the entity to be controlled based on HVAC MODE"""
if self.hvac_mode == HVACMode.COOL and self._cooler_entity_id is not None:
return self._cooler_entity_id
return self._heater_entity_id
async def _async_heater_turn_on(self):
"""Turn heater toggleable device on."""
if time.time() - self._last_heat_cycle_time >= self._min_off_cycle_duration.seconds:
data = {ATTR_ENTITY_ID: self.heater_or_cooler_entity}