-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnode.py
More file actions
798 lines (707 loc) · 28.6 KB
/
node.py
File metadata and controls
798 lines (707 loc) · 28.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
"""Base class of Plugwise node device."""
from __future__ import annotations
from abc import ABC
from asyncio import Task, create_task
from collections.abc import Awaitable, Callable
from datetime import UTC, datetime, timedelta
import logging
from typing import Any
from ..api import (
AvailableState,
BatteryConfig,
EnergyStatistics,
MotionConfig,
MotionSensitivity,
MotionState,
NetworkStatistics,
NodeEvent,
NodeFeature,
NodeInfo,
NodeType,
PowerStatistics,
RelayConfig,
RelayState,
)
from ..connection import StickController
from ..constants import SUPPRESS_INITIALIZATION_WARNINGS, UTF8
from ..exceptions import FeatureError, NodeError
from ..helpers.util import version_to_model
from ..messages.requests import NodeInfoRequest, NodePingRequest
from ..messages.responses import NodeInfoResponse, NodePingResponse
from .helpers import raise_not_loaded
from .helpers.cache import NodeCache
from .helpers.firmware import FEATURE_SUPPORTED_AT_FIRMWARE, SupportedVersions
from .helpers.subscription import FeaturePublisher
_LOGGER = logging.getLogger(__name__)
NODE_FEATURES = (
NodeFeature.AVAILABLE,
NodeFeature.INFO,
NodeFeature.PING,
)
CACHE_FIRMWARE = "firmware"
CACHE_NODE_TYPE = "node_type"
CACHE_HARDWARE = "hardware"
CACHE_NODE_INFO_TIMESTAMP = "node_info_timestamp"
class PlugwiseBaseNode(FeaturePublisher, ABC):
"""Abstract Base Class for a Plugwise node."""
def __init__(
self,
mac: str,
address: int,
controller: StickController,
loaded_callback: Callable[[NodeEvent, str], Awaitable[None]],
):
"""Initialize Plugwise base node class."""
super().__init__()
self._loaded_callback = loaded_callback
self._message_subscribe = controller.subscribe_to_messages
self._features: tuple[NodeFeature, ...] = NODE_FEATURES
self._last_seen = datetime.now(tz=UTC)
self._node_info = NodeInfo(mac, address)
self._ping = NetworkStatistics()
self._mac_in_bytes = bytes(mac, encoding=UTF8)
self._mac_in_str = mac
self._send = controller.send
self._cache_enabled: bool = False
self._cache_folder_create: bool = False
self._cache_save_task: Task[None] | None = None
self._node_cache = NodeCache(mac, "")
# Sensors
self._available: bool = False
self._connected: bool = False
self._initialized: bool = False
self._initialization_delay_expired: datetime | None = None
self._loaded: bool = False
self._node_protocols: SupportedVersions | None = None
# Node info
self._current_log_address: int | None = None
# region Properties
@property
def available(self) -> bool:
"""Return network availability state."""
return self._available
@property
def available_state(self) -> AvailableState:
"""Network availability state."""
return AvailableState(
self._available,
self._last_seen,
)
@property
@raise_not_loaded
def battery_config(self) -> BatteryConfig:
"""Battery related configuration settings."""
if NodeFeature.BATTERY not in self._features:
raise FeatureError(
f"Battery configuration property is not supported for node {self.mac}"
)
raise NotImplementedError()
@property
@raise_not_loaded
def clock_sync(self) -> bool:
"""Indicate if the internal clock must be synced."""
if NodeFeature.BATTERY not in self._features:
raise FeatureError(
f"Clock sync property is not supported for node {self.mac}"
)
raise NotImplementedError()
@property
def cache_folder(self) -> str:
"""Return path to cache folder."""
return self._node_cache.cache_root_directory
@cache_folder.setter
def cache_folder(self, cache_folder: str) -> None:
"""Set path to cache folder."""
self._node_cache.cache_root_directory = cache_folder
@property
def cache_folder_create(self) -> bool:
"""Return if cache folder must be create when it does not exists."""
return self._cache_folder_create
@cache_folder_create.setter
def cache_folder_create(self, enable: bool = True) -> None:
"""Enable or disable creation of cache folder."""
self._cache_folder_create = enable
@property
def cache_enabled(self) -> bool:
"""Return usage of cache."""
return self._cache_enabled
@cache_enabled.setter
def cache_enabled(self, enable: bool) -> None:
"""Enable or disable usage of cache."""
self._cache_enabled = enable
@property
@raise_not_loaded
def energy(self) -> EnergyStatistics:
"""Energy statistics."""
if NodeFeature.POWER not in self._features:
raise FeatureError(f"Energy state is not supported for node {self.mac}")
raise NotImplementedError()
@property
@raise_not_loaded
def energy_consumption_interval(self) -> int | None:
"""Interval (minutes) energy consumption counters are locally logged at Circle devices."""
if NodeFeature.ENERGY not in self._features:
raise FeatureError(
f"Energy log interval is not supported for node {self.mac}"
)
raise NotImplementedError()
@property
@raise_not_loaded
def energy_production_interval(self) -> int | None:
"""Interval (minutes) energy production counters are locally logged at Circle devices."""
if NodeFeature.ENERGY not in self._features:
raise FeatureError(
f"Energy log interval is not supported for node {self.mac}"
)
raise NotImplementedError()
@property
def features(self) -> tuple[NodeFeature, ...]:
"""Supported feature types of node."""
return self._features
@property
@raise_not_loaded
def humidity(self) -> float:
"""Humidity state."""
if NodeFeature.HUMIDITY not in self._features:
raise FeatureError(f"Humidity state is not supported for node {self.mac}")
raise NotImplementedError()
@property
def is_battery_powered(self) -> bool:
"""Return if node is battery powered."""
return self._node_info.is_battery_powered
@property
def is_loaded(self) -> bool:
"""Return load status."""
return self._loaded
@property
def last_seen(self) -> datetime:
"""Timestamp of last network activity."""
return self._last_seen
@property
def name(self) -> str:
"""Return name of node."""
if self._node_info.name is not None:
return self._node_info.name
return self._mac_in_str
@property
def network_address(self) -> int:
"""Zigbee network registration address."""
return self._node_info.zigbee_address
@property
def node_info(self) -> NodeInfo:
"""Node information."""
return self._node_info
@property
def mac(self) -> str:
"""Zigbee mac address of node."""
return self._mac_in_str
@property
@raise_not_loaded
def motion(self) -> bool:
"""Motion detection value."""
if NodeFeature.MOTION not in self._features:
raise FeatureError(f"Motion state is not supported for node {self.mac}")
raise NotImplementedError()
@property
@raise_not_loaded
def motion_config(self) -> MotionConfig:
"""Motion configuration settings."""
if NodeFeature.MOTION not in self._features:
raise FeatureError(
f"Motion configuration is not supported for node {self.mac}"
)
raise NotImplementedError()
@property
@raise_not_loaded
def motion_state(self) -> MotionState:
"""Motion detection state."""
if NodeFeature.MOTION not in self._features:
raise FeatureError(f"Motion state is not supported for node {self.mac}")
raise NotImplementedError()
@property
def ping_stats(self) -> NetworkStatistics:
"""Ping statistics."""
return self._ping
@property
@raise_not_loaded
def power(self) -> PowerStatistics:
"""Power statistics."""
if NodeFeature.POWER not in self._features:
raise FeatureError(f"Power state is not supported for node {self.mac}")
raise NotImplementedError()
@property
@raise_not_loaded
def relay_state(self) -> RelayState:
"""State of relay."""
if NodeFeature.RELAY not in self._features:
raise FeatureError(f"Relay state is not supported for node {self.mac}")
raise NotImplementedError()
@property
@raise_not_loaded
def relay(self) -> bool:
"""Relay value."""
if NodeFeature.RELAY not in self._features:
raise FeatureError(f"Relay value is not supported for node {self.mac}")
raise NotImplementedError()
@property
@raise_not_loaded
def relay_config(self) -> RelayConfig:
"""Relay configuration."""
if NodeFeature.RELAY_INIT not in self._features:
raise FeatureError(
f"Relay configuration is not supported for node {self.mac}"
)
raise NotImplementedError()
@property
@raise_not_loaded
def switch(self) -> bool:
"""Switch button value."""
if NodeFeature.SWITCH not in self._features:
raise FeatureError(f"Switch value is not supported for node {self.mac}")
raise NotImplementedError()
@property
@raise_not_loaded
def temperature(self) -> float:
"""Temperature value."""
if NodeFeature.TEMPERATURE not in self._features:
raise FeatureError(
f"Temperature state is not supported for node {self.mac}"
)
raise NotImplementedError()
# endregion
def _setup_protocol(
self,
firmware: dict[datetime, SupportedVersions],
node_features: tuple[NodeFeature, ...],
) -> None:
"""Determine protocol version based on firmware version and enable supported additional supported features."""
if self._node_info.firmware is None:
return
self._node_protocols = firmware.get(self._node_info.firmware, None)
if self._node_protocols is None:
_LOGGER.warning(
"Failed to determine the protocol version for node %s (%s) based on firmware version %s of list %s",
self._node_info.mac,
self.__class__.__name__,
self._node_info.firmware,
str(firmware.keys()),
)
return
for feature in node_features:
if (
required_version := FEATURE_SUPPORTED_AT_FIRMWARE.get(feature)
) is not None and (
self._node_protocols.min
<= required_version
<= self._node_protocols.max
and feature not in self._features
):
self._features += (feature,)
self._node_info.features = self._features
async def reconnect(self) -> None:
"""Reconnect node to Plugwise Zigbee network."""
if await self.ping_update() is not None:
self._connected = True
await self._available_update_state(True, None)
async def disconnect(self) -> None:
"""Disconnect node from Plugwise Zigbee network."""
self._connected = False
await self._available_update_state(False)
async def scan_calibrate_light(self) -> bool:
"""Request to calibration light sensitivity of Scan device. Returns True if successful."""
raise NotImplementedError()
async def load(self) -> bool:
"""Load configuration and activate node features."""
raise NotImplementedError()
async def _load_cache_file(self) -> bool:
"""Load states from previous cached information."""
if self._loaded:
return True
if not self._cache_enabled:
_LOGGER.warning(
"Unable to load node %s from cache because caching is disabled",
self.mac,
)
return False
if not self._node_cache.initialized:
await self._node_cache.initialize_cache(self._cache_folder_create)
return await self._node_cache.restore_cache()
async def clear_cache(self) -> None:
"""Clear current cache."""
if self._node_cache is not None:
await self._node_cache.clear_cache()
async def _load_from_cache(self) -> bool:
"""Load states from previous cached information. Return True if successful."""
if self._loaded:
return True
if not await self._load_cache_file():
_LOGGER.debug("Node %s failed to load cache file", self.mac)
return False
# Node Info
if not await self._node_info_load_from_cache():
_LOGGER.debug("Node %s failed to load node_info from cache", self.mac)
return False
return True
async def initialize(self) -> None:
"""Initialize node configuration."""
if self._initialized:
return
self._initialization_delay_expired = datetime.now(tz=UTC) + timedelta(
minutes=SUPPRESS_INITIALIZATION_WARNINGS
)
self._initialized = True
async def _available_update_state(
self, available: bool, timestamp: datetime | None = None
) -> None:
"""Update the node availability state."""
if self._available == available:
if (
self._last_seen is not None
and timestamp is not None
and int((timestamp - self._last_seen).total_seconds()) > 5
):
self._last_seen = timestamp
await self.publish_feature_update_to_subscribers(
NodeFeature.AVAILABLE, self.available_state
)
return
if timestamp is not None:
self._last_seen = timestamp
if available:
_LOGGER.info("Device %s detected to be available (on-line)", self.name)
self._available = True
await self.publish_feature_update_to_subscribers(
NodeFeature.AVAILABLE, self.available_state
)
return
_LOGGER.info("Device %s detected to be not available (off-line)", self.name)
self._available = False
await self.publish_feature_update_to_subscribers(
NodeFeature.AVAILABLE, self.available_state
)
async def node_info_update(
self, node_info: NodeInfoResponse | None = None
) -> NodeInfo | None:
"""Update Node hardware information."""
if node_info is None:
request = NodeInfoRequest(self._send, self._mac_in_bytes)
node_info = await request.send()
if node_info is None:
_LOGGER.debug("No response for node_info_update() for %s", self.mac)
await self._available_update_state(False)
return self._node_info
await self._available_update_state(True, node_info.timestamp)
await self.update_node_details(
firmware=node_info.firmware,
node_type=node_info.node_type,
hardware=node_info.hardware,
timestamp=node_info.timestamp,
relay_state=node_info.relay_state,
logaddress_pointer=node_info.current_logaddress_pointer,
)
return self._node_info
async def _node_info_load_from_cache(self) -> bool:
"""Load node info settings from cache."""
firmware = self._get_cache_as_datetime(CACHE_FIRMWARE)
hardware = self._get_cache(CACHE_HARDWARE)
timestamp = self._get_cache_as_datetime(CACHE_NODE_INFO_TIMESTAMP)
node_type: NodeType | None = None
if (node_type_str := self._get_cache(CACHE_NODE_TYPE)) is not None:
node_type = NodeType(int(node_type_str))
return await self.update_node_details(
firmware=firmware,
hardware=hardware,
node_type=node_type,
timestamp=timestamp,
relay_state=None,
logaddress_pointer=None,
)
# pylint: disable=too-many-arguments
async def update_node_details(
self,
firmware: datetime | None,
hardware: str | None,
node_type: NodeType | None,
timestamp: datetime | None,
relay_state: bool | None,
logaddress_pointer: int | None,
) -> bool:
"""Process new node info and return true if all fields are updated."""
complete = True
if node_type is None:
complete = False
else:
self._node_info.node_type = NodeType(node_type)
self._set_cache(CACHE_NODE_TYPE, self._node_info.node_type.value)
if firmware is None:
complete = False
else:
self._node_info.firmware = firmware
self._set_cache(CACHE_FIRMWARE, firmware)
if hardware is None:
complete = False
else:
if self._node_info.version != hardware:
# Generate modelname based on hardware version
hardware, model_info = version_to_model(hardware)
model_info = model_info.split(" ")
self._node_info.model = model_info[0]
# Correct model when node_type doesn't match
# Switch reports hardware version of paired Circle (pw_usb_beta #245)
if (
self._node_info.node_type is not None
and (
correct_model := self._node_info.node_type.name.lower().split("_")[0]
) not in self._node_info.model.lower()
):
self._node_info.model = correct_model.capitalize()
# Replace model_info list
model_info = [self._node_info.model]
# Handle + devices
if len(model_info) > 1 and "+" in model_info[1]:
self._node_info.model = model_info[0] + " " + model_info[1]
model_info[0] = self._node_info.model
model_info.pop(1)
self._node_info.version = hardware
if self._node_info.model == "Unknown":
_LOGGER.warning(
"Failed to detect hardware model for %s based on '%s'",
self.mac,
hardware,
)
self._node_info.model_type = None
if len(model_info) > 1:
self._node_info.model_type = " ".join(model_info[1:])
if self._node_info.model is not None:
self._node_info.name = f"{model_info[0]} {self._node_info.mac[-5:]}"
self._set_cache(CACHE_HARDWARE, hardware)
if timestamp is None:
complete = False
else:
self._node_info.timestamp = timestamp
self._set_cache(CACHE_NODE_INFO_TIMESTAMP, timestamp)
await self.save_cache()
if timestamp is not None and timestamp > datetime.now(tz=UTC) - timedelta(
minutes=5
):
await self._available_update_state(True, timestamp)
return complete
async def is_online(self) -> bool:
"""Check if node is currently online."""
if await self.ping_update() is None:
_LOGGER.debug("No response to ping for %s", self.mac)
return False
return True
async def ping_update(
self, ping_response: NodePingResponse | None = None, retries: int = 1
) -> NetworkStatistics | None:
"""Update ping statistics."""
if ping_response is None:
request = NodePingRequest(self._send, self._mac_in_bytes, retries)
ping_response = await request.send()
if ping_response is None:
await self._available_update_state(False)
return None
await self._available_update_state(True, ping_response.timestamp)
self.update_ping_stats(
ping_response.timestamp,
ping_response.rssi_in,
ping_response.rssi_out,
ping_response.rtt,
)
await self.publish_feature_update_to_subscribers(NodeFeature.PING, self._ping)
return self._ping
def update_ping_stats(
self, timestamp: datetime, rssi_in: int, rssi_out: int, rtt: int
) -> None:
"""Update ping statistics."""
self._ping.timestamp = timestamp
self._ping.rssi_in = rssi_in
self._ping.rssi_out = rssi_out
self._ping.rtt = rtt
self._available = True
@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:
if feature not in self._features:
raise NodeError(
f"Update of feature '{feature.name}' is "
+ f"not supported for {self.mac}"
)
if feature == NodeFeature.INFO:
states[NodeFeature.INFO] = await self.node_info_update()
elif feature == NodeFeature.AVAILABLE:
states[NodeFeature.AVAILABLE] = self.available_state
elif feature == NodeFeature.PING:
states[NodeFeature.PING] = await self.ping_update()
else:
raise NodeError(
f"Update of feature '{feature.name}' is "
+ f"not supported for {self.mac}"
)
return states
async def unload(self) -> None:
"""Deactivate and unload node features."""
if not self._cache_enabled:
return
if self._cache_save_task is not None and not self._cache_save_task.done():
await self._cache_save_task
await self.save_cache(trigger_only=False, full_write=True)
def _get_cache(self, setting: str) -> str | None:
"""Retrieve value of specified setting from cache memory."""
if not self._cache_enabled:
return None
return self._node_cache.get_state(setting)
def _get_cache_as_datetime(self, setting: str) -> datetime | None:
"""Retrieve value of specified setting from cache memory and return it as datetime object."""
if (timestamp_str := self._get_cache(setting)) is not None:
data = timestamp_str.split("-")
if len(data) == 6:
try:
return datetime(
year=int(data[0]),
month=int(data[1]),
day=int(data[2]),
hour=int(data[3]),
minute=int(data[4]),
second=int(data[5]),
tzinfo=UTC,
)
except ValueError:
_LOGGER.warning(
"Invalid datetime format in cache for setting %s: %s",
setting,
timestamp_str,
)
return None
def _set_cache(self, setting: str, value: Any) -> None:
"""Store setting with value in cache memory."""
if not self._cache_enabled:
return
if isinstance(value, datetime):
self._node_cache.update_state(
setting,
f"{value.year}-{value.month}-{value.day}-{value.hour}"
+ f"-{value.minute}-{value.second}",
)
elif isinstance(value, str):
self._node_cache.update_state(setting, value)
else:
self._node_cache.update_state(setting, str(value))
async def save_cache(
self, trigger_only: bool = True, full_write: bool = False
) -> None:
"""Save cached data to cache file when cache is enabled."""
if not self._cache_enabled or not self._loaded or not self._initialized:
return
_LOGGER.debug("Save cache file for node %s", self.mac)
if self._cache_save_task is not None and not self._cache_save_task.done():
await self._cache_save_task
if trigger_only:
self._cache_save_task = create_task(self._node_cache.save_cache())
else:
await self._node_cache.save_cache(rewrite=full_write)
@staticmethod
def skip_update(data_class: Any, seconds: int) -> bool:
"""Check if update can be skipped when timestamp of given dataclass is less than given seconds old."""
if data_class is None:
return False
if not hasattr(data_class, "timestamp"):
return False
if data_class.timestamp is None:
return False
if data_class.timestamp + timedelta(seconds=seconds) > datetime.now(tz=UTC):
return True
return False
# region Configuration of properties
@raise_not_loaded
async def set_awake_duration(self, seconds: int) -> bool:
"""Change the awake duration."""
if NodeFeature.BATTERY not in self._features:
raise FeatureError(
f"Changing awake duration is not supported for node {self.mac}"
)
raise NotImplementedError()
@raise_not_loaded
async def set_clock_interval(self, minutes: int) -> bool:
"""Change the clock interval."""
if NodeFeature.BATTERY not in self._features:
raise FeatureError(
f"Changing clock interval is not supported for node {self.mac}"
)
raise NotImplementedError()
@raise_not_loaded
async def set_clock_sync(self, sync: bool) -> bool:
"""Change the clock synchronization setting."""
if NodeFeature.BATTERY not in self._features:
raise FeatureError(
f"Configuration of clock sync is not supported for node {self.mac}"
)
raise NotImplementedError()
@raise_not_loaded
async def set_maintenance_interval(self, minutes: int) -> bool:
"""Change the maintenance interval."""
if NodeFeature.BATTERY not in self._features:
raise FeatureError(
f"Changing maintenance interval is not supported for node {self.mac}"
)
raise NotImplementedError()
@raise_not_loaded
async def set_motion_daylight_mode(self, state: bool) -> bool:
"""Configure if motion must be detected when light level is below threshold."""
if NodeFeature.MOTION not in self._features:
raise FeatureError(
f"Configuration of daylight mode is not supported for node {self.mac}"
)
raise NotImplementedError()
@raise_not_loaded
async def set_motion_reset_timer(self, minutes: int) -> bool:
"""Configure the motion reset timer in minutes."""
if NodeFeature.MOTION not in self._features:
raise FeatureError(
f"Changing motion reset timer is not supported for node {self.mac}"
)
raise NotImplementedError()
@raise_not_loaded
async def set_motion_sensitivity_level(self, level: MotionSensitivity) -> bool:
"""Configure motion sensitivity level."""
if NodeFeature.MOTION not in self._features:
raise FeatureError(
f"Configuration of motion sensitivity is not supported for node {self.mac}"
)
raise NotImplementedError()
@raise_not_loaded
async def set_relay(self, state: bool) -> bool:
"""Change the state of the relay."""
if NodeFeature.RELAY not in self._features:
raise FeatureError(
f"Changing state of relay is not supported for node {self.mac}"
)
raise NotImplementedError()
@raise_not_loaded
async def set_relay_init(self, state: bool) -> bool:
"""Change the initial power-on state of the relay."""
if NodeFeature.RELAY_INIT not in self._features:
raise FeatureError(
f"Configuration of initial power-up relay state is not supported for node {self.mac}"
)
raise NotImplementedError()
@raise_not_loaded
async def set_sleep_duration(self, minutes: int) -> bool:
"""Change the sleep duration."""
if NodeFeature.BATTERY not in self._features:
raise FeatureError(
f"Configuration of sleep duration is not supported for node {self.mac}"
)
raise NotImplementedError()
# endregion
async def message_for_node(self, message: Any) -> None:
"""Process message for node."""
if isinstance(message, NodePingResponse):
await self.ping_update(message)
elif isinstance(message, NodeInfoResponse):
await self.node_info_update(message)
else:
raise NotImplementedError()