-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest_usb.py
More file actions
3080 lines (2768 loc) · 128 KB
/
test_usb.py
File metadata and controls
3080 lines (2768 loc) · 128 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
"""Test plugwise USB Stick."""
import asyncio
from collections.abc import Callable, Coroutine
from datetime import UTC, datetime as dt, timedelta as td
import importlib
import logging
import random
from typing import Any
from unittest.mock import MagicMock, Mock, patch
import pytest
import aiofiles # type: ignore[import-untyped]
import crcmod
from freezegun import freeze_time
crc_fun = crcmod.mkCrcFun(0x11021, rev=False, initCrc=0x0000, xorOut=0x0000)
pw_stick = importlib.import_module("plugwise_usb")
pw_api = importlib.import_module("plugwise_usb.api")
pw_exceptions = importlib.import_module("plugwise_usb.exceptions")
pw_connection = importlib.import_module("plugwise_usb.connection")
pw_connection_manager = importlib.import_module("plugwise_usb.connection.manager")
pw_constants = importlib.import_module("plugwise_usb.constants")
pw_helpers_cache = importlib.import_module("plugwise_usb.helpers.cache")
pw_network_cache = importlib.import_module("plugwise_usb.network.cache")
pw_node_cache = importlib.import_module("plugwise_usb.nodes.helpers.cache")
pw_receiver = importlib.import_module("plugwise_usb.connection.receiver")
pw_sender = importlib.import_module("plugwise_usb.connection.sender")
pw_requests = importlib.import_module("plugwise_usb.messages.requests")
pw_responses = importlib.import_module("plugwise_usb.messages.responses")
pw_msg_properties = importlib.import_module("plugwise_usb.messages.properties")
pw_userdata = importlib.import_module("stick_test_data")
pw_node = importlib.import_module("plugwise_usb.nodes.node")
pw_circle = importlib.import_module("plugwise_usb.nodes.circle")
pw_sed = importlib.import_module("plugwise_usb.nodes.sed")
pw_scan = importlib.import_module("plugwise_usb.nodes.scan")
pw_sense = importlib.import_module("plugwise_usb.nodes.sense")
pw_switch = importlib.import_module("plugwise_usb.nodes.switch")
pw_energy_counter = importlib.import_module("plugwise_usb.nodes.helpers.counter")
pw_energy_calibration = importlib.import_module("plugwise_usb.nodes.helpers")
pw_energy_pulses = importlib.import_module("plugwise_usb.nodes.helpers.pulses")
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.DEBUG)
def inc_seq_id(seq_id: bytes | None) -> bytes:
"""Increment sequence id."""
if seq_id is None:
return b"0000"
temp_int = int(seq_id, 16) + 1
if temp_int >= 65532:
temp_int = 0
temp_str = str(hex(temp_int)).lstrip("0x").upper()
while len(temp_str) < 4:
temp_str = "0" + temp_str
return temp_str.encode()
def construct_message(data: bytes, seq_id: bytes = b"0000") -> bytes:
"""Construct plugwise message."""
body = data[:4] + seq_id + data[4:]
return bytes(
pw_constants.MESSAGE_HEADER
+ body
+ bytes(f"{crc_fun(body):04X}", pw_constants.UTF8)
+ pw_constants.MESSAGE_FOOTER
)
class DummyTransport:
"""Dummy transport class."""
protocol_data_received: Callable[[bytes], None]
def __init__(
self,
loop: asyncio.AbstractEventLoop,
test_data: dict[bytes, tuple[str, bytes, bytes | None]] | None = None,
) -> None:
"""Initialize dummy transport class."""
self._loop = loop
self._msg = 0
self._seq_id = b"1233"
self._processed: list[bytes] = []
self._first_response = test_data
self._second_response = test_data
if test_data is None:
self._first_response = pw_userdata.RESPONSE_MESSAGES
self._second_response = pw_userdata.SECOND_RESPONSE_MESSAGES
self.random_extra_byte = 0
self._closing = False
def is_closing(self) -> bool:
"""Close connection."""
return self._closing
def write(self, data: bytes) -> None:
"""Write data back to system."""
log = None
ack = None
response = None
if data in self._processed and self._second_response is not None:
log, ack, response = self._second_response.get(data, (None, None, None))
if log is None and self._first_response is not None:
log, ack, response = self._first_response.get(data, (None, None, None))
if log is None:
resp = pw_userdata.PARTLY_RESPONSE_MESSAGES.get(
data[:24], (None, None, None)
)
if resp is None:
_LOGGER.debug("No msg response for %s", str(data))
return
log, ack, response = resp
if ack is None:
_LOGGER.debug("No ack response for %s", str(data))
return
self._seq_id = inc_seq_id(self._seq_id)
if response and self._msg == 0:
self.message_response_at_once(ack, response, self._seq_id)
self._processed.append(data)
else:
self.message_response(ack, self._seq_id)
self._processed.append(data)
if response is None or self._closing:
return
self._loop.create_task(self._delayed_response(response, self._seq_id))
self._msg += 1
async def _delayed_response(self, data: bytes, seq_id: bytes) -> None:
delay = random.uniform(0.005, 0.025)
await asyncio.sleep(delay)
self.message_response(data, seq_id)
def message_response(self, data: bytes, seq_id: bytes) -> None:
"""Handle message response."""
self.random_extra_byte += 1
if self.random_extra_byte > 25:
self.protocol_data_received(b"\x83")
self.random_extra_byte = 0
self.protocol_data_received(construct_message(data, seq_id) + b"\x83")
else:
self.protocol_data_received(construct_message(data, seq_id))
def message_response_at_once(self, ack: bytes, data: bytes, seq_id: bytes) -> None:
"""Full message."""
self.random_extra_byte += 1
if self.random_extra_byte > 25:
self.protocol_data_received(b"\x83")
self.random_extra_byte = 0
self.protocol_data_received(
construct_message(ack, seq_id)
+ construct_message(data, seq_id)
+ b"\x83"
)
else:
self.protocol_data_received(
construct_message(ack, seq_id) + construct_message(data, seq_id)
)
def close(self) -> None:
"""Close connection."""
self._closing = True
class MockSerial:
"""Mock serial connection."""
def __init__(
self, custom_response: dict[bytes, tuple[str, bytes, bytes | None]] | None
) -> None:
"""Init mocked serial connection."""
self.custom_response = custom_response
self._protocol: pw_receiver.StickReceiver | None = None # type: ignore[name-defined]
self._transport: DummyTransport | None = None
def inject_message(self, data: bytes, seq_id: bytes) -> None:
"""Inject message to be received from stick."""
if self._transport is None:
return
self._transport.message_response(data, seq_id)
def trigger_connection_lost(self) -> None:
"""Trigger connection lost."""
if self._protocol is None:
return
self._protocol.connection_lost()
async def mock_connection(
self,
loop: asyncio.AbstractEventLoop,
protocol_factory: Callable[[], pw_receiver.StickReceiver], # type: ignore[name-defined]
**kwargs: dict[str, Any],
) -> tuple[DummyTransport, pw_receiver.StickReceiver]: # type: ignore[name-defined]
"""Mock connection with dummy connection."""
self._protocol = protocol_factory()
self._transport = DummyTransport(loop, self.custom_response)
self._transport.protocol_data_received = self._protocol.data_received
loop.call_soon_threadsafe(self._protocol.connection_made, self._transport)
return self._transport, self._protocol
class MockOsPath:
"""Mock aiofiles.path class."""
async def exists(self, file_or_path: str) -> bool: # noqa: PLR0911
"""Exists folder."""
test_exists = [
"mock_folder_that_exists",
"mock_folder_that_exists/nodetype.cache",
"mock_folder_that_exists\\nodetype.cache",
"mock_folder_that_exists/0123456789ABCDEF.cache",
"mock_folder_that_exists\\0123456789ABCDEF.cache",
"mock_folder_that_exists\\file_that_exists.ext",
]
if file_or_path in test_exists:
return True
return file_or_path == "mock_folder_that_exists/file_that_exists.ext"
async def mkdir(self, path: str) -> None:
"""Make dir."""
return
class MockStickController:
"""Mock stick controller."""
def __init__(self) -> None:
"""Initialize MockStickController."""
self.send_response: list[pw_responses.PlugwiseResponse] = []
async def subscribe_to_messages(
self,
node_response_callback: Callable[ # type: ignore[name-defined]
[pw_responses.PlugwiseResponse], Coroutine[Any, Any, bool]
],
mac: bytes | None = None,
message_ids: tuple[bytes] | None = None,
) -> Callable[[], None]:
"""Subscribe a awaitable callback to be called when a specific message is received.
Returns function to unsubscribe.
"""
def dummy_method() -> None:
"""Fake method."""
return dummy_method
def append_response(self, response) -> None:
"""Add response to queue."""
self.send_response.append(response)
def clear_responses(self) -> None:
"""Clear response queue."""
self.send_response.clear()
async def send(
self,
request: pw_requests.PlugwiseRequest, # type: ignore[name-defined]
suppress_node_errors=True,
) -> pw_responses.PlugwiseResponse | None: # type: ignore[name-defined]
"""Submit request to queue and return response."""
if self.send_response:
return self.send_response.pop(0)
return None
aiofiles.threadpool.wrap.register(MagicMock)(
lambda *args, **kwargs: aiofiles.threadpool.AsyncBufferedIOBase(*args, **kwargs) # pylint: disable=unnecessary-lambda
)
class TestStick:
"""Test USB Stick."""
test_node_awake: asyncio.Future[str]
test_node_loaded: asyncio.Future[str]
test_node_join: asyncio.Future[str]
test_connected: asyncio.Future[bool]
test_disconnected: asyncio.Future[bool]
test_relay_state_on: asyncio.Future[bool]
test_relay_state_off: asyncio.Future[bool]
test_motion_on: asyncio.Future[bool]
test_motion_off: asyncio.Future[bool]
test_init_relay_state_off: asyncio.Future[bool]
test_init_relay_state_on: asyncio.Future[bool]
async def dummy_fn(self, request: pw_requests.PlugwiseRequest, test: bool) -> None: # type: ignore[name-defined]
"""Callable dummy routine."""
return
@pytest.mark.asyncio
async def test_sorting_request_messages(self) -> None:
"""Test request message priority sorting."""
node_add_request = pw_requests.NodeAddRequest(
self.dummy_fn, b"1111222233334444", True
)
await asyncio.sleep(0.001) # Ensure timestamp is different
relay_switch_request = pw_requests.CircleRelaySwitchRequest(
self.dummy_fn, b"1234ABCD12341234", True
)
await asyncio.sleep(0.001) # Ensure timestamp is different
circle_plus_allow_joining_request = pw_requests.CirclePlusAllowJoiningRequest(
self.dummy_fn, True
)
# validate sorting based on timestamp with same priority level
assert node_add_request < circle_plus_allow_joining_request
assert circle_plus_allow_joining_request > node_add_request
assert circle_plus_allow_joining_request >= node_add_request
assert node_add_request <= circle_plus_allow_joining_request
# validate sorting based on priority
assert relay_switch_request > node_add_request
assert relay_switch_request >= node_add_request
assert node_add_request < relay_switch_request
assert node_add_request <= relay_switch_request
assert relay_switch_request > circle_plus_allow_joining_request
assert relay_switch_request >= circle_plus_allow_joining_request
assert circle_plus_allow_joining_request < relay_switch_request
assert circle_plus_allow_joining_request <= relay_switch_request
# Change priority
node_add_request.priority = pw_requests.Priority.LOW
# Validate node_add_request is less than other requests
assert node_add_request < relay_switch_request
assert node_add_request <= relay_switch_request
assert node_add_request < circle_plus_allow_joining_request
assert node_add_request <= circle_plus_allow_joining_request
assert relay_switch_request > node_add_request
assert relay_switch_request >= node_add_request
assert circle_plus_allow_joining_request > node_add_request
assert circle_plus_allow_joining_request >= node_add_request
@pytest.mark.asyncio
async def test_msg_properties(self) -> None:
"""Test message properties."""
# UnixTimestamp
unix_timestamp = pw_msg_properties.UnixTimestamp(
dt(2011, 6, 27, 9, 4, 10, tzinfo=UTC), 8
)
assert unix_timestamp.serialize() == b"4E08478A"
with pytest.raises(pw_exceptions.MessageError):
unix_timestamp.value
unix_timestamp.deserialize(b"4E08478A")
assert unix_timestamp.value == dt(2011, 6, 27, 9, 4, 10, tzinfo=UTC)
@pytest.mark.asyncio
async def test_stick_connect_without_port(self) -> None:
"""Test connecting to stick without port config."""
stick = pw_stick.Stick()
assert stick.nodes == {}
assert stick.joined_nodes is None
with pytest.raises(pw_exceptions.StickError):
stick.mac_stick
with pytest.raises(pw_exceptions.StickError):
stick.mac_coordinator
with pytest.raises(pw_exceptions.StickError):
stick.network_id
assert not stick.network_discovered
assert not stick.network_state
with pytest.raises(pw_exceptions.StickError):
await stick.connect()
stick.port = "null"
with pytest.raises(pw_exceptions.StickError):
await stick.connect()
await stick.disconnect()
@pytest.mark.asyncio
async def test_stick_reconnect(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test connecting to stick while already connected."""
monkeypatch.setattr(
pw_connection_manager,
"create_serial_connection",
MockSerial(None).mock_connection,
)
stick = pw_stick.Stick()
stick.port = "test_port"
assert stick.port == "test_port"
await stick.connect()
# second time should raise
with pytest.raises(pw_exceptions.StickError):
await stick.connect()
await stick.disconnect()
@pytest.mark.asyncio
async def test_stick_connect_without_response(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Test connecting to stick without response."""
monkeypatch.setattr(
pw_connection_manager,
"create_serial_connection",
MockSerial(
{
b"FFFF": (
"no response",
b"0000",
b"",
),
}
).mock_connection,
)
monkeypatch.setattr(pw_sender, "STICK_TIME_OUT", 0.2)
stick = pw_stick.Stick()
stick.port = "test_port"
with pytest.raises(pw_exceptions.StickError):
await stick.initialize()
# Connect
await stick.connect()
# Still raise StickError connected but without response
with pytest.raises(pw_exceptions.StickError):
await stick.initialize()
await stick.disconnect()
@pytest.mark.asyncio
async def test_stick_connect_timeout(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test connecting to stick."""
monkeypatch.setattr(
pw_connection_manager,
"create_serial_connection",
MockSerial(
{
b"\x05\x05\x03\x03000AB43C\r\n": (
"STICK INIT timeout",
b"000000E1", # Timeout ack
None,
),
}
).mock_connection,
)
monkeypatch.setattr(pw_sender, "STICK_TIME_OUT", 0.5)
stick = pw_stick.Stick()
await stick.connect("test_port")
with pytest.raises(pw_exceptions.StickError):
await stick.initialize()
await stick.disconnect()
async def connected(self, event: pw_api.StickEvent) -> None: # type: ignore[name-defined]
"""Set connected state helper."""
if event is pw_api.StickEvent.CONNECTED:
self.test_connected.set_result(True)
else:
self.test_connected.set_exception(BaseException("Incorrect event"))
@pytest.mark.asyncio
async def test_stick_connect(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test connecting to stick."""
monkeypatch.setattr(
pw_connection_manager,
"create_serial_connection",
MockSerial(None).mock_connection,
)
stick = pw_stick.Stick(port="test_port", cache_enabled=False)
unsub_connect = stick.subscribe_to_stick_events(
stick_event_callback=self.connected,
events=(pw_api.StickEvent.CONNECTED,),
)
self.test_connected = asyncio.Future()
await stick.connect("test_port")
assert await self.test_connected
await stick.initialize()
assert stick.mac_stick == "0123456789012345"
assert stick.name == "Stick 12345"
assert stick.mac_coordinator == "0098765432101234"
assert stick.firmware == dt(2011, 6, 27, 8, 47, 37, tzinfo=UTC)
assert stick.hardware == "070085"
assert not stick.network_discovered
assert stick.network_state
assert stick.network_id == 17185
unsub_connect()
await stick.disconnect()
assert not stick.network_state
with pytest.raises(pw_exceptions.StickError):
stick.mac_stick
async def disconnected(self, event: pw_api.StickEvent) -> None: # type: ignore[name-defined]
"""Handle disconnect event callback."""
if event is pw_api.StickEvent.DISCONNECTED:
self.test_disconnected.set_result(True)
else:
self.test_disconnected.set_exception(BaseException("Incorrect event"))
@pytest.mark.asyncio
async def test_stick_connection_lost(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test connecting to stick."""
mock_serial = MockSerial(None)
monkeypatch.setattr(
pw_connection_manager,
"create_serial_connection",
mock_serial.mock_connection,
)
stick = pw_stick.Stick()
await stick.connect("test_port")
await stick.initialize()
assert stick.network_state
self.test_disconnected = asyncio.Future()
unsub_disconnect = stick.subscribe_to_stick_events(
stick_event_callback=self.disconnected,
events=(pw_api.StickEvent.DISCONNECTED,),
)
# Trigger disconnect
mock_serial.trigger_connection_lost()
assert await self.test_disconnected
assert not stick.network_state
unsub_disconnect()
await stick.disconnect()
async def node_awake(self, event: pw_api.NodeEvent, mac: str) -> None: # type: ignore[name-defined]
"""Handle awake event callback."""
_LOGGER.debug("Node %s has event %s", mac, str(event))
if event == pw_api.NodeEvent.AWAKE:
self.test_node_awake.set_result(mac)
else:
self.test_node_awake.set_exception(
BaseException(
f"Invalid {event} event, expected " + f"{pw_api.NodeEvent.AWAKE}"
)
)
async def node_loaded(self, event: pw_api.NodeEvent, mac: str) -> None: # type: ignore[name-defined]
"""Handle awake event callback."""
if event == pw_api.NodeEvent.LOADED:
self.test_node_loaded.set_result(mac)
else:
self.test_node_loaded.set_exception(
BaseException(
f"Invalid {event} event, expected " + f"{pw_api.NodeEvent.LOADED}"
)
)
async def node_motion_state(
self,
feature: pw_api.NodeFeature, # type: ignore[name-defined]
motion: pw_api.MotionState, # type: ignore[name-defined]
) -> None:
"""Handle motion event callback."""
if feature == pw_api.NodeFeature.MOTION:
if motion.state:
self.test_motion_on.set_result(motion.state)
else:
self.test_motion_off.set_result(motion.state)
else:
self.test_motion_on.set_exception(
BaseException(
f"Invalid {feature} feature, expected "
+ f"{pw_api.NodeFeature.MOTION}"
)
)
self.test_motion_off.set_exception(
BaseException(
f"Invalid {feature} feature, expected "
+ f"{pw_api.NodeFeature.MOTION}"
)
)
async def _wait_for_scan(self, stick) -> None:
"""Wait for scan completion with timeout."""
async def wait_scan_completed():
while not stick._network._register.scan_completed:
await asyncio.sleep(0.1)
try:
await asyncio.wait_for(wait_scan_completed(), timeout=10)
except TimeoutError:
pytest.fail("Scan did not complete within 10 seconds")
@pytest.mark.asyncio
async def test_stick_node_discovered_subscription( # noqa: PLR0915
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Testing "new_node" subscription for Scan."""
mock_serial = MockSerial(None)
monkeypatch.setattr(
pw_connection_manager,
"create_serial_connection",
mock_serial.mock_connection,
)
monkeypatch.setattr(pw_sender, "STICK_TIME_OUT", 0.1)
monkeypatch.setattr(pw_requests, "NODE_TIME_OUT", 0.5)
stick = pw_stick.Stick("test_port", cache_enabled=False)
await stick.connect()
await stick.initialize()
await stick.discover_nodes(load=False)
await self._wait_for_scan(stick)
self.test_node_awake = asyncio.Future()
unsub_awake = stick.subscribe_to_node_events(
node_event_callback=self.node_awake,
events=(pw_api.NodeEvent.AWAKE,),
)
# Inject NodeAwakeResponse message to trigger a 'node discovered' event
mock_serial.inject_message(b"004F555555555555555500", b"FFFE")
mac_awake_node = await self.test_node_awake
assert mac_awake_node == "5555555555555555"
unsub_awake()
await stick.nodes["5555555555555555"].load()
assert stick.nodes["5555555555555555"].node_info.firmware == dt(
2011, 6, 27, 8, 55, 44, tzinfo=UTC
)
assert stick.nodes["5555555555555555"].node_info.version == "080007"
assert stick.nodes["5555555555555555"].node_info.model == "Scan"
assert stick.nodes["5555555555555555"].node_info.model_type is None
assert stick.nodes["5555555555555555"].available
assert stick.nodes["5555555555555555"].node_info.is_battery_powered
assert sorted(stick.nodes["5555555555555555"].features) == sorted(
(
pw_api.NodeFeature.AVAILABLE,
pw_api.NodeFeature.BATTERY,
pw_api.NodeFeature.INFO,
pw_api.NodeFeature.PING,
pw_api.NodeFeature.MOTION,
pw_api.NodeFeature.MOTION_CONFIG,
)
)
# Check Scan is raising NodeError for unsupported features
with pytest.raises(pw_exceptions.FeatureError):
stick.nodes["5555555555555555"].relay
with pytest.raises(pw_exceptions.FeatureError):
stick.nodes["5555555555555555"].relay_state
with pytest.raises(pw_exceptions.FeatureError):
stick.nodes["5555555555555555"].switch
with pytest.raises(pw_exceptions.FeatureError):
stick.nodes["5555555555555555"].power
with pytest.raises(pw_exceptions.FeatureError):
stick.nodes["5555555555555555"].sense
with pytest.raises(pw_exceptions.FeatureError):
stick.nodes["5555555555555555"].energy
# Motion
self.test_motion_on = asyncio.Future()
self.test_motion_off = asyncio.Future()
unsub_motion = stick.nodes["5555555555555555"].subscribe_to_feature_update(
node_feature_callback=self.node_motion_state,
features=(pw_api.NodeFeature.MOTION,),
)
# Inject motion message to trigger a 'motion on' event
mock_serial.inject_message(b"005655555555555555550001", b"FFFF")
motion_on = await self.test_motion_on
assert motion_on
assert stick.nodes["5555555555555555"].motion
# Inject motion message to trigger a 'motion off' event
mock_serial.inject_message(b"005655555555555555550000", b"FFFF")
motion_off = await self.test_motion_off
assert not motion_off
assert not stick.nodes["5555555555555555"].motion
unsub_motion()
await stick.disconnect()
async def node_join(self, event: pw_api.NodeEvent, mac: str) -> None: # type: ignore[name-defined]
"""Handle join event callback."""
if event == pw_api.NodeEvent.JOIN:
self.test_node_join.set_result(mac)
else:
self.test_node_join.set_exception(
BaseException(
f"Invalid {event} event, expected " + f"{pw_api.NodeEvent.JOIN}"
)
)
# @pytest.mark.asyncio
# async def test_stick_node_join_subscription(
# self, monkeypatch: pytest.MonkeyPatch
# ) -> None:
# """Testing "new_node" subscription."""
# mock_serial = MockSerial(None)
# monkeypatch.setattr(
# pw_connection_manager,
# "create_serial_connection",
# mock_serial.mock_connection,
# )
# monkeypatch.setattr(pw_sender, "STICK_TIME_OUT", 0.1)
# monkeypatch.setattr(pw_requests, "NODE_TIME_OUT", 0.5)
# stick = pw_stick.Stick("test_port", cache_enabled=False)
# await stick.connect()
# await stick.initialize()
# await stick.discover_nodes(load=False)
# self.test_node_join = asyncio.Future()
# unusb_join = stick.subscribe_to_node_events(
# node_event_callback=self.node_join,
# events=(pw_api.NodeEvent.JOIN,),
# )
## Inject NodeJoinAvailableResponse
# mock_serial.inject_message(b"00069999999999999999", b"1253") # @bouwew: seq_id is not FFFC!
# mac_join_node = await self.test_node_join
# assert mac_join_node == "9999999999999999"
# unusb_join()
# await stick.disconnect()
@pytest.mark.asyncio
async def test_node_discovery(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Testing discovery of nodes."""
mock_serial = MockSerial(None)
monkeypatch.setattr(
pw_connection_manager,
"create_serial_connection",
mock_serial.mock_connection,
)
monkeypatch.setattr(pw_sender, "STICK_TIME_OUT", 0.2)
monkeypatch.setattr(pw_requests, "NODE_TIME_OUT", 2.0)
stick = pw_stick.Stick("test_port", cache_enabled=False)
await stick.connect()
await stick.initialize()
await stick.discover_nodes(load=False)
await self._wait_for_scan(stick)
assert stick.joined_nodes == 9
assert stick.nodes.get("0098765432101234") is not None
assert len(stick.nodes) == 7 # Discovered nodes
# Test unregistering of node
await stick.unregister_node("3333333333333333")
assert stick.nodes.get("3333333333333333") is None
assert len(stick.nodes) == 6
await stick.disconnect()
async def node_relay_state(
self,
feature: pw_api.NodeFeature, # type: ignore[name-defined]
state: pw_api.RelayState, # type: ignore[name-defined]
) -> None:
"""Handle relay event callback."""
if feature in (pw_api.NodeFeature.RELAY, pw_api.NodeFeature.RELAY_LOCK):
if feature == pw_api.NodeFeature.RELAY:
if state.state:
self.test_relay_state_on.set_result(state.state)
else:
self.test_relay_state_off.set_result(state.state)
if feature == pw_api.NodeFeature.RELAY_LOCK:
# Handle RELAY_LOCK callbacks if needed
pass
else:
self.test_relay_state_on.set_exception(
BaseException(
f"Invalid {feature} feature, expected "
+ f"{pw_api.NodeFeature.RELAY}"
)
)
self.test_relay_state_off.set_exception(
BaseException(
f"Invalid {feature} feature, expected "
+ f"{pw_api.NodeFeature.RELAY}"
)
)
async def node_init_relay_state(
self,
feature: pw_api.NodeFeature, # type: ignore[name-defined]
config: pw_api.RelayConfig, # type: ignore[name-defined]
) -> None:
"""Relay Callback for event."""
if feature == pw_api.NodeFeature.RELAY_INIT:
if config.init_state:
self.test_init_relay_state_on.set_result(config.init_state)
else:
self.test_init_relay_state_off.set_result(config.init_state)
else:
self.test_init_relay_state_on.set_exception(
BaseException(
f"Invalid {feature} feature, expected "
+ f"{pw_api.NodeFeature.RELAY_INIT}"
)
)
self.test_init_relay_state_off.set_exception(
BaseException(
f"Invalid {feature} feature, expected "
+ f"{pw_api.NodeFeature.RELAY_INIT}"
)
)
@freeze_time("2025-04-03 22:00:00", real_asyncio=True)
@pytest.mark.asyncio
async def test_node_relay_and_power(self, monkeypatch: pytest.MonkeyPatch) -> None: # noqa: PLR0915
"""Testing discovery of nodes."""
mock_serial = MockSerial(None)
monkeypatch.setattr(
pw_connection_manager,
"create_serial_connection",
mock_serial.mock_connection,
)
monkeypatch.setattr(pw_sender, "STICK_TIME_OUT", 0.2)
monkeypatch.setattr(pw_requests, "NODE_TIME_OUT", 2.0)
stick = pw_stick.Stick("test_port", cache_enabled=False)
await stick.connect()
await stick.initialize()
await stick.discover_nodes(load=False)
await self._wait_for_scan(stick)
# Validate if NodeError is raised when device is not loaded
with pytest.raises(pw_exceptions.NodeError):
await stick.nodes["0098765432101234"].set_relay(True)
with pytest.raises(pw_exceptions.NodeError):
await stick.nodes["0098765432101234"].set_relay_lock(True)
# Manually load node
await stick.nodes["0098765432101234"].load()
# Check relay_lock is set to False when not in cache
assert stick.nodes["0098765432101234"].relay_lock
assert not stick.nodes["0098765432101234"].relay_lock.state
unsub_relay = stick.nodes["0098765432101234"].subscribe_to_feature_update(
node_feature_callback=self.node_relay_state,
features=(
pw_api.NodeFeature.RELAY,
pw_api.NodeFeature.RELAY_LOCK,
),
)
# Test async switching back from on to off
self.test_relay_state_off = asyncio.Future()
assert not await stick.nodes["0098765432101234"].set_relay(False)
assert not await self.test_relay_state_off
assert not stick.nodes["0098765432101234"].relay
# Test blocked async switching due to relay-lock active
await stick.nodes["0098765432101234"].set_relay_lock(True)
assert stick.nodes["0098765432101234"].relay_lock.state
assert not await stick.nodes["0098765432101234"].set_relay(True)
assert not stick.nodes["0098765432101234"].relay
# Make sure to turn lock off for further testing
await stick.nodes["0098765432101234"].set_relay_lock(False)
assert not stick.nodes["0098765432101234"].relay_lock.state
# Test async switching back from off to on
self.test_relay_state_on = asyncio.Future()
assert await stick.nodes["0098765432101234"].set_relay(True)
assert await self.test_relay_state_on
assert stick.nodes["0098765432101234"].relay
# Test async switching back from on to off
self.test_relay_state_off = asyncio.Future()
await stick.nodes["0098765432101234"].relay_off()
assert not await self.test_relay_state_off
assert not stick.nodes["0098765432101234"].relay
assert not stick.nodes["0098765432101234"].relay_state.state
# Test async switching back from off to on
self.test_relay_state_on = asyncio.Future()
await stick.nodes["0098765432101234"].relay_on()
assert await self.test_relay_state_on
assert stick.nodes["0098765432101234"].relay
assert stick.nodes["0098765432101234"].relay_state.state
unsub_relay()
# Check if node is online
assert await stick.nodes["0098765432101234"].is_online()
# Test non-support relay configuration
with pytest.raises(pw_exceptions.FeatureError):
stick.nodes["0098765432101234"].relay_config
with pytest.raises(pw_exceptions.FeatureError):
await stick.nodes["0098765432101234"].set_relay_init(True)
with pytest.raises(pw_exceptions.FeatureError):
await stick.nodes["0098765432101234"].set_relay_init(False)
# Check Circle is raising NodeError for unsupported features
with pytest.raises(pw_exceptions.FeatureError):
stick.nodes["0098765432101234"].motion
with pytest.raises(pw_exceptions.FeatureError):
stick.nodes["0098765432101234"].switch
with pytest.raises(pw_exceptions.FeatureError):
stick.nodes["0098765432101234"].sense
# Test relay init
# load node 2222222222222222 which has
# the firmware with init relay feature
# Validate if NodeError is raised when device is not loaded
with pytest.raises(pw_exceptions.NodeError):
await stick.nodes["2222222222222222"].set_relay_init(True)
await stick.nodes["2222222222222222"].load()
self.test_init_relay_state_on = asyncio.Future()
self.test_init_relay_state_off = asyncio.Future()
unsub_inti_relay = stick.nodes["2222222222222222"].subscribe_to_feature_update(
node_feature_callback=self.node_init_relay_state,
features=(pw_api.NodeFeature.RELAY_INIT,),
)
# Test async switching back init_state from on to off
assert stick.nodes["2222222222222222"].relay_config.init_state
self.test_init_relay_state_off = asyncio.Future()
assert not await stick.nodes["2222222222222222"].set_relay_init(False)
assert not await self.test_init_relay_state_off
assert not stick.nodes["2222222222222222"].relay_config.init_state
# Test async switching back from off to on
self.test_init_relay_state_on = asyncio.Future()
assert await stick.nodes["2222222222222222"].set_relay_init(True)
assert await self.test_init_relay_state_on
assert stick.nodes["2222222222222222"].relay_config.init_state
unsub_inti_relay()
await stick.disconnect()
@freeze_time("2025-04-03 22:00:00", real_asyncio=True)
@pytest.mark.asyncio
async def test_energy_circle(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Testing energy retrieval."""
mock_serial = MockSerial(None)
monkeypatch.setattr(
pw_connection_manager,
"create_serial_connection",
mock_serial.mock_connection,
)
monkeypatch.setattr(pw_energy_pulses, "MAX_LOG_HOURS", 25)
monkeypatch.setattr(pw_sender, "STICK_TIME_OUT", 0.2)
monkeypatch.setattr(pw_requests, "NODE_TIME_OUT", 2.0)
async def fake_get_missing_energy_logs(address: int) -> None:
"""Mock missing energy logs."""
monkeypatch.setattr(
pw_circle.PlugwiseCircle,
"get_missing_energy_logs",
fake_get_missing_energy_logs,
)
stick = pw_stick.Stick("test_port", cache_enabled=False)
await stick.connect()
await stick.initialize()
await stick.discover_nodes(load=False)
await self._wait_for_scan(stick)
# Check calibration in unloaded state
assert not stick.nodes["0098765432101234"].calibrated
# Manually load node
await stick.nodes["0098765432101234"].load()
# Check calibration in loaded state
assert stick.nodes["0098765432101234"].calibrated
# Test power state without request
assert stick.nodes["0098765432101234"].power == pw_api.PowerStatistics(
last_second=None, last_8_seconds=None, timestamp=None
)
pu = await stick.nodes["0098765432101234"].power_update()
assert pu.last_second == pytest.approx(21.2780505980402, rel=1e-09, abs=1e-09)
assert pu.last_8_seconds == -27.150578775440106
# Test energy state without request
assert stick.nodes["0098765432101234"].energy == pw_api.EnergyStatistics(
log_interval_consumption=None,
log_interval_production=None,
hour_consumption=None,
hour_consumption_reset=None,
day_consumption=None,
day_consumption_reset=None,
hour_production=None,
hour_production_reset=None,
day_production=None,
day_production_reset=None,
)
# energy_update is not complete and should return none
utc_now = dt.now(UTC)
assert await stick.nodes["0098765432101234"].energy_update() is None
# Allow for background task to finish
assert stick.nodes["0098765432101234"].energy == pw_api.EnergyStatistics(
log_interval_consumption=60,
log_interval_production=None,
hour_consumption=0.0026868922443345974,
hour_consumption_reset=utc_now.replace(minute=0, second=0, microsecond=0),
day_consumption=None,
day_consumption_reset=None,
hour_production=None,
hour_production_reset=None,
day_production=None,
day_production_reset=None,
)
await stick.disconnect()
@freeze_time("2025-04-03 22:00:00")
def test_pulse_collection_consumption( # noqa: PLR0915
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Testing pulse collection class."""
monkeypatch.setattr(pw_energy_pulses, "MAX_LOG_HOURS", 24)
fixed_this_hour = dt.now(UTC)
# Test consumption logs
tst_consumption = pw_energy_pulses.PulseCollection(mac="0098765432101234")
assert tst_consumption.log_addresses_missing is None
assert tst_consumption.production_logging is None