-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsense.py
More file actions
908 lines (817 loc) · 35.6 KB
/
sense.py
File metadata and controls
908 lines (817 loc) · 35.6 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
"""Plugwise Sense node object."""
from __future__ import annotations
from asyncio import gather
from collections.abc import Awaitable, Callable
from dataclasses import replace
from datetime import UTC, datetime
import logging
from typing import Any, Final
from ..api import (
NodeEvent,
NodeFeature,
NodeType,
SenseHysteresisConfig,
SenseStatistics,
)
from ..connection import StickController
from ..exceptions import MessageError, NodeError
from ..messages.requests import (
SenseConfigureHysteresisRequest,
SenseReportIntervalRequest,
)
from ..messages.responses import (
NODE_SWITCH_GROUP_ID,
SENSE_REPORT_ID,
NodeAckResponseType,
NodeSwitchGroupResponse,
PlugwiseResponse,
SenseReportResponse,
)
from ..nodes.sed import NodeSED
from .helpers import raise_not_loaded
from .helpers.firmware import SENSE_FIRMWARE_SUPPORT
_LOGGER = logging.getLogger(__name__)
# Sense calculations
SENSE_HUMIDITY_MULTIPLIER: Final = 125
SENSE_HUMIDITY_OFFSET: Final = 6
SENSE_HUMIDITY_LIMIT: Final = 65535
SENSE_TEMPERATURE_MULTIPLIER: Final = 175.72
SENSE_TEMPERATURE_OFFSET: Final = 46.85
SENSE_TEMPERATURE_LIMIT: Final = 65535
SENSE_FEATURES: Final = (
NodeFeature.INFO,
NodeFeature.SENSE,
NodeFeature.SENSE_HYSTERESIS,
)
# Default firmware if not known
DEFAULT_FIRMWARE: Final = datetime(2010, 12, 3, 10, 17, 7, tzinfo=UTC)
CACHE_SENSE_HYSTERESIS_HUMIDITY_ENABLED = "humidity_enabled"
CACHE_SENSE_HYSTERESIS_HUMIDITY_UPPER_BOUND = "humidity_upper_bound"
CACHE_SENSE_HYSTERESIS_HUMIDITY_LOWER_BOUND = "humidity_lower_bound"
CACHE_SENSE_HYSTERESIS_HUMIDITY_DIRECTION = "humidity_direction"
CACHE_SENSE_HYSTERESIS_TEMPERATURE_ENABLED = "temperature_enabled"
CACHE_SENSE_HYSTERESIS_TEMPERATURE_UPPER_BOUND = "temperature_upper_bound"
CACHE_SENSE_HYSTERESIS_TEMPERATURE_LOWER_BOUND = "temperature_lower_bound"
CACHE_SENSE_HYSTERESIS_TEMPERATURE_DIRECTION = "temperature_direction"
CACHE_SENSE_HYSTERESIS_REPORT_INTERVAL = "report_interval"
CACHE_SENSE_HYSTERESIS_CONFIG_DIRTY = "sense_hysteresis_config_dirty"
DEFAULT_SENSE_HYSTERESIS_HUMIDITY_ENABLED: Final = False
DEFAULT_SENSE_HYSTERESIS_HUMIDITY_UPPER_BOUND: Final[float] = 24.0
DEFAULT_SENSE_HYSTERESIS_HUMIDITY_LOWER_BOUND: Final[float] = 24.0
DEFAULT_SENSE_HYSTERESIS_HUMIDITY_DIRECTION: Final[bool] = True
DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_ENABLED: Final[bool] = False
DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_UPPER_BOUND: Final[float] = 50.0
DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_LOWER_BOUND: Final[float] = 50.0
DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_DIRECTION: Final[bool] = True
DEFAULT_SENSE_HYSTERESIS_REPORT_INTERVAL: Final[int] = 15
class PlugwiseSense(NodeSED):
"""Plugwise Sense node."""
def __init__(
self,
mac: str,
node_type: NodeType,
controller: StickController,
loaded_callback: Callable[[NodeEvent, str], Awaitable[None]],
):
"""Initialize Scan Device."""
super().__init__(mac, node_type, controller, loaded_callback)
self._sense_statistics = SenseStatistics()
self._hysteresis_config = SenseHysteresisConfig()
self._sense_subscription: Callable[[], None] | None = None
self._unsubscribe_switch_group: Callable[[], None] | None = None
async def load(self) -> None:
"""Load and activate Sense node features."""
if self._loaded:
return
_LOGGER.debug("Loading Sense node %s", self._node_info.mac)
await super().load()
self._setup_protocol(SENSE_FIRMWARE_SUPPORT, SENSE_FEATURES)
await self.initialize()
await self._loaded_callback(NodeEvent.LOADED, self.mac)
@raise_not_loaded
async def initialize(self) -> None:
"""Initialize Sense node."""
if self._initialized:
return
self._sense_subscription = await self._message_subscribe(
self._sense_report,
self._mac_in_bytes,
(SENSE_REPORT_ID,),
)
self._unsubscribe_switch_group = await self._message_subscribe(
self._switch_group,
self._mac_in_bytes,
(NODE_SWITCH_GROUP_ID,),
)
await super().initialize()
async def unload(self) -> None:
"""Unload node."""
self._loaded = False
if self._sense_subscription is not None:
self._sense_subscription()
if self._unsubscribe_switch_group is not None:
self._unsubscribe_switch_group()
await super().unload()
# region Caching
async def _load_defaults(self) -> None:
"""Load default configuration settings."""
await super()._load_defaults()
self._sense_statistics = SenseStatistics()
if self._node_info.model is None:
self._node_info.model = "Sense"
self._sed_node_info_update_task_scheduled = True
if self._node_info.name is None:
self._node_info.name = f"Sense {self._node_info.mac[-5:]}"
self._sed_node_info_update_task_scheduled = True
if self._node_info.firmware is None:
self._node_info.firmware = DEFAULT_FIRMWARE
self._sed_node_info_update_task_scheduled = True
async def _load_from_cache(self) -> bool:
"""Load states from previous cached information. Returns True if successful."""
super_load_success = await super()._load_from_cache()
dirty = False
if (humidity_enabled := self._humidity_enabled_from_cache()) is None:
dirty = True
humidity_enabled = DEFAULT_SENSE_HYSTERESIS_HUMIDITY_ENABLED
if (humidity_upper_bound := self._humidity_upper_bound_from_cache()) is None:
dirty = True
humidity_upper_bound = DEFAULT_SENSE_HYSTERESIS_HUMIDITY_UPPER_BOUND
if (humidity_lower_bound := self._humidity_lower_bound_from_cache()) is None:
dirty = True
humidity_lower_bound = DEFAULT_SENSE_HYSTERESIS_HUMIDITY_LOWER_BOUND
if (humidity_direction := self._humidity_direction_from_cache()) is None:
dirty = True
humidity_direction = DEFAULT_SENSE_HYSTERESIS_HUMIDITY_DIRECTION
if (temperature_enabled := self._temperature_enabled_from_cache()) is None:
dirty = True
temperature_enabled = DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_ENABLED
if (
temperature_upper_bound := self._temperature_upper_bound_from_cache()
) is None:
dirty = True
temperature_upper_bound = DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_UPPER_BOUND
if (
temperature_lower_bound := self._temperature_lower_bound_from_cache()
) is None:
dirty = True
temperature_lower_bound = DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_LOWER_BOUND
if (temperature_direction := self._temperature_direction_from_cache()) is None:
dirty = True
temperature_direction = DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_DIRECTION
if (report_interval := self._report_interval_from_cache()) is None:
dirty = True
report_interval = DEFAULT_SENSE_HYSTERESIS_REPORT_INTERVAL
dirty |= self._sense_hysteresis_config_dirty_from_cache()
self._hysteresis_config = SenseHysteresisConfig(
humidity_enabled=humidity_enabled,
humidity_upper_bound=humidity_upper_bound,
humidity_lower_bound=humidity_lower_bound,
humidity_direction=humidity_direction,
temperature_enabled=temperature_enabled,
temperature_upper_bound=temperature_upper_bound,
temperature_lower_bound=temperature_lower_bound,
temperature_direction=temperature_direction,
report_interval=report_interval,
dirty=dirty,
)
if dirty:
await self._sense_configure_update()
return super_load_success
def _humidity_enabled_from_cache(self) -> bool | None:
"""Load humidity hysteresis enabled from cache."""
return self._get_cache_as_bool(CACHE_SENSE_HYSTERESIS_HUMIDITY_ENABLED)
def _humidity_upper_bound_from_cache(self) -> float | None:
"""Load humidity upper bound from cache."""
if (
humidity_upper_bound := self._get_cache(
CACHE_SENSE_HYSTERESIS_HUMIDITY_UPPER_BOUND
)
) is not None:
return float(humidity_upper_bound)
return None
def _humidity_lower_bound_from_cache(self) -> float | None:
"""Load humidity lower bound from cache."""
if (
humidity_lower_bound := self._get_cache(
CACHE_SENSE_HYSTERESIS_HUMIDITY_LOWER_BOUND
)
) is not None:
return float(humidity_lower_bound)
return None
def _humidity_direction_from_cache(self) -> bool | None:
"""Load humidity hysteresis switch direction from cache."""
return self._get_cache_as_bool(CACHE_SENSE_HYSTERESIS_HUMIDITY_DIRECTION)
def _temperature_enabled_from_cache(self) -> bool | None:
"""Load temperature hysteresis enabled from cache."""
return self._get_cache_as_bool(CACHE_SENSE_HYSTERESIS_TEMPERATURE_ENABLED)
def _temperature_upper_bound_from_cache(self) -> float | None:
"""Load temperature upper bound from cache."""
if (
temperature_upper_bound := self._get_cache(
CACHE_SENSE_HYSTERESIS_TEMPERATURE_UPPER_BOUND
)
) is not None:
return float(temperature_upper_bound)
return None
def _temperature_lower_bound_from_cache(self) -> float | None:
"""Load temperature lower bound from cache."""
if (
temperature_lower_bound := self._get_cache(
CACHE_SENSE_HYSTERESIS_TEMPERATURE_LOWER_BOUND
)
) is not None:
return float(temperature_lower_bound)
return None
def _temperature_direction_from_cache(self) -> bool | None:
"""Load Temperature hysteresis switch direction from cache."""
return self._get_cache_as_bool(CACHE_SENSE_HYSTERESIS_TEMPERATURE_DIRECTION)
def _report_interval_from_cache(self) -> int | None:
"""Load report interval from cache."""
if (
report_interval := self._get_cache(CACHE_SENSE_HYSTERESIS_REPORT_INTERVAL)
) is not None:
return int(report_interval)
return None
def _sense_hysteresis_config_dirty_from_cache(self) -> bool:
"""Load sense hysteresis dirty from cache."""
if (
dirty := self._get_cache_as_bool(CACHE_SENSE_HYSTERESIS_CONFIG_DIRTY)
) is not None:
return dirty
return True
# endregion
# region properties
@property
@raise_not_loaded
def sense_statistics(self) -> SenseStatistics:
"""Sense Statistics."""
return self._sense_statistics
@property
def hysteresis_config(self) -> SenseHysteresisConfig:
"""Sense Hysteresis Configuration."""
return SenseHysteresisConfig(
humidity_enabled=self.humidity_enabled,
humidity_upper_bound=self.humidity_upper_bound,
humidity_lower_bound=self.humidity_lower_bound,
humidity_direction=self.humidity_direction,
temperature_enabled=self.temperature_enabled,
temperature_upper_bound=self.temperature_upper_bound,
temperature_lower_bound=self.temperature_lower_bound,
temperature_direction=self.temperature_direction,
report_interval=self.report_interval,
dirty=self.hysteresis_config_dirty,
)
@property
def humidity_enabled(self) -> bool:
"""Humidity hysteresis enabled flag."""
if self._hysteresis_config.humidity_enabled is not None:
return self._hysteresis_config.humidity_enabled
return DEFAULT_SENSE_HYSTERESIS_HUMIDITY_ENABLED
@property
def humidity_upper_bound(self) -> float:
"""Humidity upper bound value."""
if self._hysteresis_config.humidity_upper_bound is not None:
return self._hysteresis_config.humidity_upper_bound
return DEFAULT_SENSE_HYSTERESIS_HUMIDITY_UPPER_BOUND
@property
def humidity_lower_bound(self) -> float:
"""Humidity lower bound value."""
if self._hysteresis_config.humidity_lower_bound is not None:
return self._hysteresis_config.humidity_lower_bound
return DEFAULT_SENSE_HYSTERESIS_HUMIDITY_LOWER_BOUND
@property
def humidity_direction(self) -> bool:
"""Humidity hysteresis switch direction."""
if self._hysteresis_config.humidity_direction is not None:
return self._hysteresis_config.humidity_direction
return DEFAULT_SENSE_HYSTERESIS_HUMIDITY_DIRECTION
@property
def temperature_enabled(self) -> bool:
"""Temperature hysteresis enabled flag."""
if self._hysteresis_config.temperature_enabled is not None:
return self._hysteresis_config.temperature_enabled
return DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_ENABLED
@property
def temperature_upper_bound(self) -> float:
"""Temperature upper bound value."""
if self._hysteresis_config.temperature_upper_bound is not None:
return self._hysteresis_config.temperature_upper_bound
return DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_UPPER_BOUND
@property
def temperature_lower_bound(self) -> float:
"""Temperature lower bound value."""
if self._hysteresis_config.temperature_lower_bound is not None:
return self._hysteresis_config.temperature_lower_bound
return DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_LOWER_BOUND
@property
def temperature_direction(self) -> bool:
"""Temperature hysteresis switch direction."""
if self._hysteresis_config.temperature_direction is not None:
return self._hysteresis_config.temperature_direction
return DEFAULT_SENSE_HYSTERESIS_TEMPERATURE_DIRECTION
@property
def report_interval(self) -> int:
"""Sense report interval in minutes."""
if self._hysteresis_config.report_interval is not None:
return self._hysteresis_config.report_interval
return DEFAULT_SENSE_HYSTERESIS_REPORT_INTERVAL
@property
def hysteresis_config_dirty(self) -> bool:
"""Sense hysteresis configuration dirty flag."""
return self._hysteresis_config.dirty
# end region
# region Configuration actions
async def set_hysteresis_humidity_enabled(self, state: bool) -> bool:
"""Configure if humidity hysteresis should be enabled or not.
Configuration request will be queued and will be applied the next time when node is awake for maintenance.
"""
_LOGGER.debug(
"set_hysteresis_humidity_enabled | Device %s | %s -> %s",
self.name,
self._hysteresis_config.humidity_enabled,
state,
)
if self._hysteresis_config.humidity_enabled == state:
return False
self._hysteresis_config = replace(
self._hysteresis_config,
humidity_enabled=state,
dirty=True,
)
await self._sense_configure_update()
return True
async def set_hysteresis_humidity_upper_bound(self, upper_bound: float) -> bool:
"""Configure humidity hysteresis upper bound.
Configuration request will be queued and will be applied the next time when node is awake for maintenance.
"""
_LOGGER.debug(
"set_hysteresis_humidity_upper_bound | Device %s | %s -> %s",
self.name,
self._hysteresis_config.humidity_upper_bound,
upper_bound,
)
if upper_bound < 1 or upper_bound > 99:
raise ValueError(
f"Invalid humidity upper bound {upper_bound}. It must be between 1 and 99 %."
)
if (
self._hysteresis_config.humidity_lower_bound is not None
and upper_bound < self._hysteresis_config.humidity_lower_bound
):
raise ValueError(
f"Invalid humidity upper bound {upper_bound}. It must be ≥ the lower bound {self._hysteresis_config.humidity_lower_bound}."
)
if self._hysteresis_config.humidity_upper_bound == upper_bound:
return False
self._hysteresis_config = replace(
self._hysteresis_config,
humidity_upper_bound=upper_bound,
dirty=True,
)
await self._sense_configure_update()
return True
async def set_hysteresis_humidity_lower_bound(self, lower_bound: float) -> bool:
"""Configure humidity hysteresis lower bound.
Configuration request will be queued and will be applied the next time when node is awake for maintenance.
"""
_LOGGER.debug(
"set_hysteresis_humidity_lower_bound | Device %s | %s -> %s",
self.name,
self._hysteresis_config.humidity_lower_bound,
lower_bound,
)
if lower_bound < 1 or lower_bound > 99:
raise ValueError(
f"Invalid humidity lower bound {lower_bound}. It must be between 1 and 99 %."
)
if (
self._hysteresis_config.humidity_upper_bound is not None
and lower_bound > self._hysteresis_config.humidity_upper_bound
):
raise ValueError(
f"Invalid humidity lower bound {lower_bound}. It must be ≤ the upper bound {self._hysteresis_config.humidity_upper_bound}."
)
if self._hysteresis_config.humidity_lower_bound == lower_bound:
return False
self._hysteresis_config = replace(
self._hysteresis_config,
humidity_lower_bound=lower_bound,
dirty=True,
)
await self._sense_configure_update()
return True
async def set_hysteresis_humidity_direction(self, state: bool) -> bool:
"""Configure humidity hysteresis to switch on or off on increasing or decreasing direction.
Configuration request will be queued and will be applied the next time when node is awake for maintenance.
"""
_LOGGER.debug(
"set_hysteresis_humidity_direction | Device %s | %s -> %s",
self.name,
self._hysteresis_config.humidity_direction,
state,
)
if self._hysteresis_config.humidity_direction == state:
return False
self._hysteresis_config = replace(
self._hysteresis_config,
humidity_direction=state,
dirty=True,
)
await self._sense_configure_update()
return True
async def set_hysteresis_temperature_enabled(self, state: bool) -> bool:
"""Configure if temperature hysteresis should be enabled or not.
Configuration request will be queued and will be applied the next time when node is awake for maintenance.
"""
_LOGGER.debug(
"set_hysteresis_temperature_enabled | Device %s | %s -> %s",
self.name,
self._hysteresis_config.temperature_enabled,
state,
)
if self._hysteresis_config.temperature_enabled == state:
return False
self._hysteresis_config = replace(
self._hysteresis_config,
temperature_enabled=state,
dirty=True,
)
await self._sense_configure_update()
return True
async def set_hysteresis_temperature_upper_bound(self, upper_bound: float) -> bool:
"""Configure temperature hysteresis upper bound.
Configuration request will be queued and will be applied the next time when node is awake for maintenance.
"""
_LOGGER.debug(
"set_hysteresis_temperature_upper_bound | Device %s | %s -> %s",
self.name,
self._hysteresis_config.temperature_upper_bound,
upper_bound,
)
if upper_bound < 1 or upper_bound > 60:
raise ValueError(
f"Invalid temperature upper bound {upper_bound}. It must be between 1 and 60 °C."
)
if (
self._hysteresis_config.temperature_lower_bound is not None
and upper_bound < self._hysteresis_config.temperature_lower_bound
):
raise ValueError(
f"Invalid temperature upper bound {upper_bound}. It must be ≥ the lower bound {self._hysteresis_config.temperature_lower_bound}."
)
if self._hysteresis_config.temperature_upper_bound == upper_bound:
return False
self._hysteresis_config = replace(
self._hysteresis_config,
temperature_upper_bound=upper_bound,
dirty=True,
)
await self._sense_configure_update()
return True
async def set_hysteresis_temperature_lower_bound(self, lower_bound: float) -> bool:
"""Configure temperature hysteresis lower bound.
Configuration request will be queued and will be applied the next time when node is awake for maintenance.
"""
_LOGGER.debug(
"set_hysteresis_temperature_lower_bound | Device %s | %s -> %s",
self.name,
self._hysteresis_config.temperature_lower_bound,
lower_bound,
)
if lower_bound < 1 or lower_bound > 60:
raise ValueError(
f"Invalid temperature lower bound {lower_bound}. It must be between 1 and 60 °C."
)
if (
self._hysteresis_config.temperature_upper_bound is not None
and lower_bound > self._hysteresis_config.temperature_upper_bound
):
raise ValueError(
f"Invalid temperature lower bound {lower_bound}. It must be ≤ the upper bound {self._hysteresis_config.temperature_upper_bound}."
)
if self._hysteresis_config.temperature_lower_bound == lower_bound:
return False
self._hysteresis_config = replace(
self._hysteresis_config,
temperature_lower_bound=lower_bound,
dirty=True,
)
await self._sense_configure_update()
return True
async def set_report_interval(self, report_interval: int) -> bool:
"""Configure Sense measurement interval.
Configuration request will be queued and will be applied the next time when node is awake for maintenance.
"""
_LOGGER.debug(
"set_report_interval | Device %s | %s -> %s",
self.name,
self._hysteresis_config.report_interval,
report_interval,
)
if report_interval < 1 or report_interval > 60:
raise ValueError(
f"Invalid measurement interval {report_interval}. It must be between 1 and 60 minutes"
)
if self._hysteresis_config.report_interval == report_interval:
return False
self._hysteresis_config = replace(
self._hysteresis_config,
report_interval=report_interval,
dirty=True,
)
await self._sense_configure_update()
return True
async def set_hysteresis_temperature_direction(self, state: bool) -> bool:
"""Configure temperature hysteresis to switch on or off on increasing or decreasing direction.
Configuration request will be queued and will be applied the next time when node is awake for maintenance.
"""
_LOGGER.debug(
"set_hysteresis_temperature_direction | Device %s | %s -> %s",
self.name,
self._hysteresis_config.temperature_direction,
state,
)
if self._hysteresis_config.temperature_direction == state:
return False
self._hysteresis_config = replace(
self._hysteresis_config,
temperature_direction=state,
dirty=True,
)
await self._sense_configure_update()
return True
# end region
async def _switch_group(self, response: PlugwiseResponse) -> bool:
"""Switch group request from Sense.
turn on/off based on hysteresis and direction.
"""
if not isinstance(response, NodeSwitchGroupResponse):
raise MessageError(
f"Invalid response message type ({response.__class__.__name__}) received, expected NodeSwitchGroupResponse"
)
_LOGGER.warning("%s received %s", self.name, response)
await gather(
self._available_update_state(True, response.timestamp),
self._hysteresis_state_update(
response.switch_state,
response.switch_group,
),
)
return True
async def _hysteresis_state_update(
self, switch_state: bool, switch_group: int
) -> None:
"""Process hysteresis state update."""
_LOGGER.debug(
"_hysteresis_state_update for %s: %s",
self.name,
switch_state,
)
if switch_group == 1:
self._sense_statistics.humidity_hysteresis_state = switch_state
elif switch_group == 2:
self._sense_statistics.temperature_hysteresis_state = switch_state
else:
_LOGGER.debug(
"Ignoring unknown switch_group %s for %s", switch_group, self.name
)
await self.publish_feature_update_to_subscribers(
NodeFeature.SENSE, self._sense_statistics
)
async def _sense_report(self, response: PlugwiseResponse) -> bool:
"""Process sense report message to extract current temperature and humidity values."""
if not isinstance(response, SenseReportResponse):
raise MessageError(
f"Invalid response message type ({response.__class__.__name__}) received, expected SenseReportResponse"
)
report_received = False
await self._available_update_state(True, response.timestamp)
if response.temperature.value != SENSE_TEMPERATURE_LIMIT:
self._sense_statistics.temperature = float(
SENSE_TEMPERATURE_MULTIPLIER * (response.temperature.value / 65536)
- SENSE_TEMPERATURE_OFFSET
)
report_received = True
if response.humidity.value != SENSE_HUMIDITY_LIMIT:
self._sense_statistics.humidity = float(
SENSE_HUMIDITY_MULTIPLIER * (response.humidity.value / 65536)
- SENSE_HUMIDITY_OFFSET
)
report_received = True
if report_received:
await self.publish_feature_update_to_subscribers(
NodeFeature.SENSE, self._sense_statistics
)
return report_received
async def _run_awake_tasks(self) -> None:
"""Execute all awake tasks."""
await super()._run_awake_tasks()
if self._hysteresis_config.dirty:
configure_result = await gather(
self._configure_sense_humidity_task(),
self._configure_sense_temperature_task(),
self._configure_sense_report_interval_task(),
)
if all(configure_result):
self._hysteresis_config = replace(self._hysteresis_config, dirty=False)
await self._sense_configure_update()
return
else:
_LOGGER.warning(
"Sense hysteresis configuration partially failed for %s "
"(humidity=%s, temperature=%s, report_interval=%s); will retry on next wake.",
self.name,
configure_result[0],
configure_result[1],
configure_result[2],
)
await self.publish_feature_update_to_subscribers(
NodeFeature.SENSE_HYSTERESIS,
self.hysteresis_config,
)
async def _configure_sense_humidity_task(self) -> bool:
"""Configure Sense humidity hysteresis device settings. Returns True if successful."""
if not self._hysteresis_config.dirty:
return True
# Set value to -1% for 'disabled' (humidity):2621
humidity_lower_bound = 2621
humidity_upper_bound = 2621
if self.humidity_enabled:
if self.humidity_lower_bound > self.humidity_upper_bound:
raise ValueError(
f"Invalid humidity lower bound {self.humidity_lower_bound}. It must be ≤ the upper bound {self.humidity_upper_bound}."
)
humidity_lower_bound = int(
(self.humidity_lower_bound + SENSE_HUMIDITY_OFFSET)
* 65536
/ SENSE_HUMIDITY_MULTIPLIER
)
humidity_upper_bound = int(
(self.humidity_upper_bound + SENSE_HUMIDITY_OFFSET)
* 65536
/ SENSE_HUMIDITY_MULTIPLIER
)
request = SenseConfigureHysteresisRequest(
self._send,
self._mac_in_bytes,
False,
humidity_lower_bound,
humidity_upper_bound,
self.humidity_direction,
)
if (response := await request.send()) is None:
self._log_configure_failed("humidity hysteresis")
return False
if response.node_ack_type == NodeAckResponseType.SENSE_BOUNDARIES_FAILED:
_LOGGER.warning(
"Failed to configure humidity hysteresis settings for %s", self.name
)
return False
if response.node_ack_type == NodeAckResponseType.SENSE_BOUNDARIES_ACCEPTED:
self._log_configure_success("humidity hysteresis")
return True
self._log_unexpected_response_ack(response.node_ack_type)
return False
async def _configure_sense_temperature_task(self) -> bool:
"""Configure Sense temperature hysteresis device settings. Returns True if successful."""
if not self._hysteresis_config.dirty:
return True
# Set value to -1 °C for disabled (temperature): 17099
temperature_lower_bound = 17099
temperature_upper_bound = 17099
if self.temperature_enabled:
if self.temperature_lower_bound > self.temperature_upper_bound:
raise ValueError(
f"Invalid temperature lower bound {self.temperature_lower_bound}. It must be ≤ the upper bound {self.temperature_upper_bound}."
)
temperature_lower_bound = int(
(self.temperature_lower_bound + SENSE_TEMPERATURE_OFFSET)
* 65536
/ SENSE_TEMPERATURE_MULTIPLIER
)
temperature_upper_bound = int(
(self.temperature_upper_bound + SENSE_TEMPERATURE_OFFSET)
* 65536
/ SENSE_TEMPERATURE_MULTIPLIER
)
request = SenseConfigureHysteresisRequest(
self._send,
self._mac_in_bytes,
True,
temperature_lower_bound,
temperature_upper_bound,
self.temperature_direction,
)
if (response := await request.send()) is None:
_LOGGER.warning(
"No response from %s to configure temperature hysteresis settings request",
self.name,
)
return False
if response.node_ack_type == NodeAckResponseType.SENSE_BOUNDARIES_FAILED:
self._log_configure_failed("temperature hysteresis")
return False
if response.node_ack_type == NodeAckResponseType.SENSE_BOUNDARIES_ACCEPTED:
self._log_configure_success("temperature hysteresis")
return True
self._log_unexpected_response_ack(response.node_ack_type)
return False
async def _configure_sense_report_interval_task(self) -> bool:
"""Configure Sense report interval setting. Returns True if successful."""
if not self._hysteresis_config.dirty:
return True
request = SenseReportIntervalRequest(
self._send,
self._mac_in_bytes,
self.report_interval,
)
if (response := await request.send()) is None:
_LOGGER.warning(
"No response from %s to configure report interval.",
self.name,
)
return False
if response.node_ack_type == NodeAckResponseType.SENSE_INTERVAL_FAILED:
self._log_configure_failed("report interval")
return False
if response.node_ack_type == NodeAckResponseType.SENSE_INTERVAL_ACCEPTED:
self._log_configure_success("report interval")
return True
self._log_unexpected_response_ack(response.node_ack_type)
return False
def _log_unexpected_response_ack(self, response: NodeAckResponseType) -> None:
"""Log unexpected response."""
_LOGGER.warning(
"Unexpected response ack type %s for %s",
response.name,
self.name,
)
def _log_configure_failed(self, parameter: str) -> None:
"""Log configuration failed."""
_LOGGER.warning("Failed to configure %s for %s", parameter, self.name)
def _log_configure_success(self, parameter: str) -> None:
"""Log configuration success."""
_LOGGER.debug("Successful configure %s for %s", parameter, self.name)
async def _sense_configure_update(self) -> None:
"""Push sense configuration update to cache."""
self._set_cache(CACHE_SENSE_HYSTERESIS_HUMIDITY_ENABLED, self.humidity_enabled)
self._set_cache(
CACHE_SENSE_HYSTERESIS_HUMIDITY_UPPER_BOUND, self.humidity_upper_bound
)
self._set_cache(
CACHE_SENSE_HYSTERESIS_HUMIDITY_LOWER_BOUND, self.humidity_lower_bound
)
self._set_cache(
CACHE_SENSE_HYSTERESIS_HUMIDITY_DIRECTION, self.humidity_direction
)
self._set_cache(
CACHE_SENSE_HYSTERESIS_TEMPERATURE_ENABLED, self.temperature_enabled
)
self._set_cache(
CACHE_SENSE_HYSTERESIS_TEMPERATURE_UPPER_BOUND, self.temperature_upper_bound
)
self._set_cache(
CACHE_SENSE_HYSTERESIS_TEMPERATURE_LOWER_BOUND, self.temperature_lower_bound
)
self._set_cache(
CACHE_SENSE_HYSTERESIS_TEMPERATURE_DIRECTION, self.temperature_direction
)
self._set_cache(CACHE_SENSE_HYSTERESIS_REPORT_INTERVAL, self.report_interval)
self._set_cache(
CACHE_SENSE_HYSTERESIS_CONFIG_DIRTY, self.hysteresis_config_dirty
)
await gather(
self.publish_feature_update_to_subscribers(
NodeFeature.SENSE_HYSTERESIS,
self.hysteresis_config,
),
self.save_cache(),
)
@raise_not_loaded
async def get_state(self, features: tuple[NodeFeature]) -> dict[NodeFeature, Any]:
"""Update latest state for given feature."""
states: dict[NodeFeature, Any] = {}
for feature in features:
_LOGGER.debug(
"Updating node %s - feature '%s'",
self._node_info.mac,
feature,
)
if feature not in self._features:
raise NodeError(
f"Update of feature '{feature.name}' is not supported for {self.mac}"
)
match feature:
case NodeFeature.PING:
states[NodeFeature.PING] = await self.ping_update()
case NodeFeature.SENSE:
states[NodeFeature.SENSE] = self._sense_statistics
case NodeFeature.SENSE_HYSTERESIS:
states[NodeFeature.SENSE_HYSTERESIS] = self.hysteresis_config
case _:
state_result = await super().get_state((feature,))
if feature in state_result:
states[feature] = state_result[feature]
if NodeFeature.AVAILABLE not in states:
states[NodeFeature.AVAILABLE] = self.available_state
return states