-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathdevice_controller.py
1673 lines (1495 loc) · 68.6 KB
/
device_controller.py
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
"""Matter Device Controller implementation.
This module implements the Matter Device Controller WebSocket API. Compared to the
`ChipDeviceControllerWrapper` class it adds the WebSocket specific sauce and adds more
features which are not part of the Python Matter Device Controller per-se, e.g.
pinging a device.
"""
from __future__ import annotations
import asyncio
from collections import deque
from datetime import datetime
from functools import cached_property, lru_cache
import logging
import secrets
import time
from typing import TYPE_CHECKING, Any, cast
from chip.ChipDeviceCtrl import ChipDeviceController
from chip.clusters import Attribute, Objects as Clusters
from chip.clusters.Attribute import ValueDecodeFailure
from chip.clusters.ClusterObjects import ALL_ATTRIBUTES, ALL_CLUSTERS, Cluster
from chip.discovery import DiscoveryType
from chip.exceptions import ChipStackError
from zeroconf import BadTypeInNameException, IPVersion, ServiceStateChange, Zeroconf
from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconf
from matter_server.common.const import VERBOSE_LOG_LEVEL
from matter_server.common.custom_clusters import check_polled_attributes
from matter_server.common.models import (
CommissionableNodeData,
CommissioningParameters,
MatterSoftwareVersion,
)
from matter_server.server.helpers.attributes import parse_attributes_from_read_result
from matter_server.server.helpers.utils import ping_ip
from matter_server.server.ota import check_for_update
from matter_server.server.ota.provider import ExternalOtaProvider
from matter_server.server.sdk import ChipDeviceControllerWrapper
from ..common.errors import (
InvalidArguments,
NodeCommissionFailed,
NodeInterviewFailed,
NodeNotExists,
NodeNotReady,
NodeNotResolving,
UpdateCheckError,
UpdateError,
)
from ..common.helpers.api import api_command
from ..common.helpers.json import JSON_DECODE_EXCEPTIONS, json_loads
from ..common.helpers.util import (
create_attribute_path_from_attribute,
dataclass_from_dict,
parse_attribute_path,
parse_value,
)
from ..common.models import (
APICommand,
EventType,
MatterNodeData,
MatterNodeEvent,
NodePingResult,
)
from .const import DATA_MODEL_SCHEMA_VERSION
if TYPE_CHECKING:
from collections.abc import Callable, Iterable
from pathlib import Path
from .server import MatterServer
DATA_KEY_NODES = "nodes"
DATA_KEY_LAST_NODE_ID = "last_node_id"
LOGGER = logging.getLogger(__name__)
NODE_SUBSCRIPTION_CEILING_WIFI = 60
NODE_SUBSCRIPTION_CEILING_THREAD = 60
NODE_SUBSCRIPTION_CEILING_BATTERY_POWERED = 600
NODE_RESUBSCRIBE_ATTEMPTS_UNAVAILABLE = 3
NODE_RESUBSCRIBE_TIMEOUT_OFFLINE = 30 * 60 * 1000
NODE_RESUBSCRIBE_FORCE_TIMEOUT = 5
NODE_PING_TIMEOUT = 10
NODE_PING_TIMEOUT_BATTERY_POWERED = 60
NODE_MDNS_BACKOFF = 610 # must be higher than (highest) sub ceiling
FALLBACK_NODE_SCANNER_INTERVAL = 1800
CUSTOM_ATTRIBUTES_POLLER_INTERVAL = 30
MDNS_TYPE_OPERATIONAL_NODE = "_matter._tcp.local."
MDNS_TYPE_COMMISSIONABLE_NODE = "_matterc._udp.local."
TEST_NODE_START = 900000
ROUTING_ROLE_ATTRIBUTE_PATH = create_attribute_path_from_attribute(
0, Clusters.ThreadNetworkDiagnostics.Attributes.RoutingRole
)
DESCRIPTOR_PARTS_LIST_ATTRIBUTE_PATH = create_attribute_path_from_attribute(
0, Clusters.Descriptor.Attributes.PartsList
)
BASIC_INFORMATION_VENDOR_ID_ATTRIBUTE_PATH = create_attribute_path_from_attribute(
0, Clusters.BasicInformation.Attributes.VendorID
)
BASIC_INFORMATION_PRODUCT_ID_ATTRIBUTE_PATH = create_attribute_path_from_attribute(
0, Clusters.BasicInformation.Attributes.ProductID
)
BASIC_INFORMATION_SOFTWARE_VERSION_ATTRIBUTE_PATH = (
create_attribute_path_from_attribute(
0, Clusters.BasicInformation.Attributes.SoftwareVersion
)
)
BASIC_INFORMATION_SOFTWARE_VERSION_STRING_ATTRIBUTE_PATH = (
create_attribute_path_from_attribute(
0, Clusters.BasicInformation.Attributes.SoftwareVersionString
)
)
# pylint: disable=too-many-lines,too-many-instance-attributes,too-many-public-methods
class MatterDeviceController:
"""Class that manages the Matter devices."""
def __init__(
self,
server: MatterServer,
paa_root_cert_dir: Path,
ota_provider_dir: Path,
):
"""Initialize the device controller."""
self.server = server
self._ota_provider_dir = ota_provider_dir
self._chip_device_controller = ChipDeviceControllerWrapper(
server, paa_root_cert_dir
)
# we keep the last events in memory so we can include them in the diagnostics dump
self.event_history: deque[Attribute.EventReadResult] = deque(maxlen=25)
self._compressed_fabric_id: int | None = None
self._fabric_id_hex: str | None = None
self._wifi_credentials_set: bool = False
self._thread_credentials_set: bool = False
self._nodes_in_setup: set[int] = set()
self._nodes_in_ota: set[int] = set()
self._node_last_seen: dict[int, float] = {}
self._nodes: dict[int, MatterNodeData] = {}
self._last_known_ip_addresses: dict[int, list[str]] = {}
self._last_subscription_attempt: dict[int, int] = {}
self._known_commissioning_params: dict[int, CommissioningParameters] = {}
self._known_commissioning_params_timers: dict[int, asyncio.TimerHandle] = {}
self._aiobrowser: AsyncServiceBrowser | None = None
self._aiozc: AsyncZeroconf | None = None
self._fallback_node_scanner_timer: asyncio.TimerHandle | None = None
self._fallback_node_scanner_task: asyncio.Task | None = None
self._thread_node_setup_throttle = asyncio.Semaphore(5)
self._mdns_event_timer: dict[str, asyncio.TimerHandle] = {}
self._polled_attributes: dict[int, set[str]] = {}
self._custom_attribute_poller_timer: asyncio.TimerHandle | None = None
self._custom_attribute_poller_task: asyncio.Task | None = None
self._attribute_update_callbacks: dict[int, list[Callable]] = {}
async def initialize(self) -> None:
"""Initialize the device controller."""
self._compressed_fabric_id = (
await self._chip_device_controller.get_compressed_fabric_id()
)
self._fabric_id_hex = hex(self._compressed_fabric_id)[2:]
async def start(self) -> None:
"""Handle logic on controller start."""
# load nodes from persistent storage
nodes: dict[str, dict | None] = self.server.storage.get(DATA_KEY_NODES, {})
orphaned_nodes: set[str] = set()
for node_id_str, node_dict in nodes.items():
node_id = int(node_id_str)
if node_dict is None:
# Non-initialized (left-over) node from a failed commissioning attempt.
# NOTE: This code can be removed in a future version
# as this can no longer happen.
orphaned_nodes.add(node_id_str)
continue
try:
node = dataclass_from_dict(MatterNodeData, node_dict, strict=True)
except (KeyError, ValueError):
# constructing MatterNodeData from the cached dict is not possible,
# revert to a fallback object and the node will be re-interviewed
node = MatterNodeData(
node_id=node_id,
date_commissioned=node_dict.get(
"date_commissioned",
datetime(1970, 1, 1),
),
last_interview=node_dict.get(
"last_interview",
datetime(1970, 1, 1),
),
interview_version=0,
)
# always mark node as unavailable at startup until subscriptions are ready
node.available = False
self._nodes[node_id] = node
# cleanup orhpaned nodes from storage
for node_id_str in orphaned_nodes:
self.server.storage.remove(DATA_KEY_NODES, node_id_str)
LOGGER.info("Loaded %s nodes from stored configuration", len(self._nodes))
# set-up mdns browser
self._aiozc = AsyncZeroconf(ip_version=IPVersion.All)
services = [MDNS_TYPE_OPERATIONAL_NODE, MDNS_TYPE_COMMISSIONABLE_NODE]
self._aiobrowser = AsyncServiceBrowser(
self._aiozc.zeroconf,
services,
handlers=[self._on_mdns_service_state_change],
)
# set-up fallback node scanner
self._schedule_fallback_scanner()
async def stop(self) -> None:
"""Handle logic on server stop."""
# shutdown (and cleanup) mdns browser and fallback node scanner
if self._aiobrowser:
await self._aiobrowser.async_cancel()
if self._fallback_node_scanner_timer:
self._fallback_node_scanner_timer.cancel()
if (scan_task := self._fallback_node_scanner_task) and not scan_task.done():
scan_task.cancel()
if self._aiozc:
await self._aiozc.async_close()
# shutdown the sdk device controller
await self._chip_device_controller.shutdown()
LOGGER.debug("Stopped.")
@property
def compressed_fabric_id(self) -> int | None:
"""Return the compressed fabric id."""
return self._compressed_fabric_id
@property
def wifi_credentials_set(self) -> bool:
"""Return if WiFi credentials have been set."""
return self._wifi_credentials_set
@property
def thread_credentials_set(self) -> bool:
"""Return if Thread operational dataset as been set."""
return self._thread_credentials_set
@cached_property
def _loop(self) -> asyncio.AbstractEventLoop:
"""Return the event loop."""
assert self.server.loop
return self.server.loop
@lru_cache(maxsize=1024) # noqa: B019
def get_node_logger(
self, logger: logging.Logger, node_id: int
) -> logging.LoggerAdapter:
"""Return a logger for a specific node."""
return logging.LoggerAdapter(logger, {"node": node_id})
@api_command(APICommand.GET_NODES)
def get_nodes(self, only_available: bool = False) -> list[MatterNodeData]:
"""Return all Nodes known to the server."""
return [
x
for x in self._nodes.values()
if x is not None and (x.available or not only_available)
]
@api_command(APICommand.GET_NODE)
def get_node(self, node_id: int) -> MatterNodeData:
"""Return info of a single Node."""
if node := self._nodes.get(node_id):
return node
raise NodeNotExists(f"Node {node_id} does not exist or is not yet interviewed")
@api_command(APICommand.COMMISSION_WITH_CODE)
async def commission_with_code(
self, code: str, network_only: bool = False
) -> MatterNodeData:
"""
Commission a device using a QR Code or Manual Pairing Code.
:param code: The QR Code or Manual Pairing Code for device commissioning.
:param network_only: If True, restricts device discovery to network only.
:return: The NodeInfo of the commissioned device.
"""
if not network_only and not self.server.bluetooth_enabled:
raise NodeCommissionFailed("Bluetooth commissioning is not available.")
node_id = self._get_next_node_id()
LOGGER.info(
"Starting Matter commissioning with code using Node ID %s.",
node_id,
)
try:
commissioned_node_id: int = (
await self._chip_device_controller.commission_with_code(
node_id,
code,
DiscoveryType.DISCOVERY_NETWORK_ONLY
if network_only
else DiscoveryType.DISCOVERY_ALL,
)
)
# We use SDK default behavior which always uses the commissioning Node ID in the
# generated NOC. So this should be the same really.
LOGGER.info("Commissioned Node ID: %s vs %s", commissioned_node_id, node_id)
if commissioned_node_id != node_id:
raise RuntimeError("Returned Node ID must match requested Node ID")
except ChipStackError as err:
raise NodeCommissionFailed(
f"Commission with code failed for node {node_id}."
) from err
LOGGER.info("Matter commissioning of Node ID %s successful.", node_id)
# perform full (first) interview of the device
# we retry the interview max 3 times as it may fail in noisy
# RF environments (in case of thread), mdns trouble or just flaky devices.
# retrying both the mdns resolve and (first) interview, increases the chances
# of a successful device commission.
retries = 3
while retries:
try:
await self.interview_node(node_id)
except (NodeNotResolving, NodeInterviewFailed) as err:
if retries <= 0:
raise err
retries -= 1
LOGGER.warning("Unable to interview Node %s: %s", node_id, err)
await asyncio.sleep(5)
else:
break
# make sure we start a subscription for this newly added node
await self._setup_node(node_id)
LOGGER.info("Commissioning of Node ID %s completed.", node_id)
# return full node object once we're complete
return self.get_node(node_id)
@api_command(APICommand.COMMISSION_ON_NETWORK)
async def commission_on_network(
self,
setup_pin_code: int,
filter_type: int = 0,
filter: Any = None, # pylint: disable=redefined-builtin
ip_addr: str | None = None,
) -> MatterNodeData:
"""
Do the routine for OnNetworkCommissioning, with a filter for mDNS discovery.
The filter can be an integer,
a string or None depending on the actual type of selected filter.
NOTE: For advanced usecases only, use `commission_with_code`
for regular commissioning.
Returns full NodeInfo once complete.
"""
node_id = self._get_next_node_id()
if ip_addr is not None:
ip_addr = self.server.scope_ipv6_lla(ip_addr)
try:
if ip_addr is None:
# regular CommissionOnNetwork if no IP address provided
LOGGER.info(
"Starting Matter commissioning on network using Node ID %s.",
node_id,
)
commissioned_node_id = (
await self._chip_device_controller.commission_on_network(
node_id, setup_pin_code, filter_type, filter
)
)
else:
LOGGER.info(
"Starting Matter commissioning using Node ID %s and IP %s.",
node_id,
ip_addr,
)
commissioned_node_id = await self._chip_device_controller.commission_ip(
node_id, setup_pin_code, ip_addr
)
# We use SDK default behavior which always uses the commissioning Node ID in the
# generated NOC. So this should be the same really.
if commissioned_node_id != node_id:
raise RuntimeError("Returned Node ID must match requested Node ID")
except ChipStackError as err:
raise NodeCommissionFailed(
f"Commissioning failed for node {node_id}."
) from err
LOGGER.info("Matter commissioning of Node ID %s successful.", node_id)
# perform full (first) interview of the device
# we retry the interview max 3 times as it may fail in noisy
# RF environments (in case of thread), mdns trouble or just flaky devices.
# retrying both the mdns resolve and (first) interview, increases the chances
# of a successful device commission.
retries = 3
while retries:
try:
await self.interview_node(node_id)
except NodeInterviewFailed as err:
if retries <= 0:
raise err
retries -= 1
LOGGER.warning("Unable to interview Node %s: %s", node_id, err)
await asyncio.sleep(5)
else:
break
# make sure we start a subscription for this newly added node
await self._setup_node(node_id)
LOGGER.info("Commissioning of Node ID %s completed.", node_id)
# return full node object once we're complete
return self.get_node(node_id)
@api_command(APICommand.SET_WIFI_CREDENTIALS)
async def set_wifi_credentials(self, ssid: str, credentials: str) -> None:
"""Set WiFi credentials for commissioning to a (new) device."""
await self._chip_device_controller.set_wifi_credentials(ssid, credentials)
self._wifi_credentials_set = True
@api_command(APICommand.SET_THREAD_DATASET)
async def set_thread_operational_dataset(self, dataset: str) -> None:
"""Set Thread Operational dataset in the stack."""
await self._chip_device_controller.set_thread_operational_dataset(dataset)
self._thread_credentials_set = True
@api_command(APICommand.OPEN_COMMISSIONING_WINDOW)
async def open_commissioning_window(
self,
node_id: int,
timeout: int = 300,
iteration: int = 1000,
option: int = ChipDeviceController.CommissioningWindowPasscode.kTokenWithRandomPin,
discriminator: int | None = None,
) -> CommissioningParameters:
"""Open a commissioning window to commission a device present on this controller to another.
Returns code to use as discriminator.
"""
if (node := self._nodes.get(node_id)) is None or not node.available:
raise NodeNotReady(f"Node {node_id} is not (yet) available.")
read_response: Attribute.AsyncReadTransaction.ReadResponse = (
await self._chip_device_controller.read_attribute(
node_id,
[(0, Clusters.AdministratorCommissioning.Attributes.WindowStatus)],
)
)
window_status = cast(
Clusters.AdministratorCommissioning.Enums.CommissioningWindowStatusEnum,
read_response.attributes[0][Clusters.AdministratorCommissioning][
Clusters.AdministratorCommissioning.Attributes.WindowStatus
],
)
if (
window_status
== Clusters.AdministratorCommissioning.Enums.CommissioningWindowStatusEnum.kWindowNotOpen
):
# Commissioning window is no longer open (e.g. device got paired already)
# Remove our stored commissioning parameters.
if node_id in self._known_commissioning_params_timers:
self._known_commissioning_params_timers[node_id].cancel()
self._known_commissioning_params.pop(node_id, None)
else:
# Node is still in commissioning mode, return previous parameters
if node_id in self._known_commissioning_params:
return self._known_commissioning_params[node_id]
# We restarted or somebody else put node into commissioning mode
# Close commissioning window and put into commissioning mode again.
LOGGER.info(
"Commissioning window open but no parameters available. Closing and reopening commissioning window for node %s",
node_id,
)
await self._chip_device_controller.send_command(
node_id,
endpoint_id=0,
command=Clusters.AdministratorCommissioning.Commands.RevokeCommissioning(),
timed_request_timeout_ms=5000,
)
if discriminator is None:
discriminator = secrets.randbelow(2**12)
sdk_result = await self._chip_device_controller.open_commissioning_window(
node_id,
timeout,
iteration,
discriminator,
option,
)
self._known_commissioning_params[node_id] = params = CommissioningParameters(
setup_pin_code=sdk_result.setupPinCode,
setup_manual_code=sdk_result.setupManualCode,
setup_qr_code=sdk_result.setupQRCode,
)
# we store the commission parameters and clear them after the timeout
self._known_commissioning_params_timers[node_id] = self._loop.call_later(
timeout, self._known_commissioning_params.pop, node_id, None
)
return params
@api_command(APICommand.DISCOVER)
async def discover_commissionable_nodes(
self,
) -> list[CommissionableNodeData]:
"""Discover Commissionable Nodes (discovered on BLE or mDNS)."""
sdk_result = await self._chip_device_controller.discover_commissionable_nodes()
if sdk_result is None:
return []
# ensure list
if not isinstance(sdk_result, list):
sdk_result = [sdk_result]
return [
CommissionableNodeData(
instance_name=x.instanceName,
host_name=x.hostName,
port=x.port,
long_discriminator=x.longDiscriminator,
vendor_id=x.vendorId,
product_id=x.productId,
commissioning_mode=x.commissioningMode,
device_type=x.deviceType,
device_name=x.deviceName,
pairing_instruction=x.pairingInstruction,
pairing_hint=x.pairingHint,
mrp_retry_interval_idle=x.mrpRetryIntervalIdle,
mrp_retry_interval_active=x.mrpRetryIntervalActive,
supports_tcp=x.supportsTcp,
addresses=x.addresses,
rotating_id=x.rotatingId,
)
for x in sdk_result
]
@api_command(APICommand.INTERVIEW_NODE)
async def interview_node(self, node_id: int) -> None:
"""Interview a node."""
if node_id >= TEST_NODE_START:
LOGGER.debug(
"interview_node called for test node %s",
node_id,
)
self.server.signal_event(EventType.NODE_UPDATED, self._nodes[node_id])
return
try:
LOGGER.info("Interviewing node: %s", node_id)
read_response: Attribute.AsyncReadTransaction.ReadResponse = (
await self._chip_device_controller.read_attribute(
node_id,
[()],
fabric_filtered=False,
)
)
except ChipStackError as err:
raise NodeInterviewFailed(f"Failed to interview node {node_id}") from err
is_new_node = node_id not in self._nodes
existing_info = self._nodes.get(node_id)
node = MatterNodeData(
node_id=node_id,
date_commissioned=(
existing_info.date_commissioned if existing_info else datetime.utcnow()
),
last_interview=datetime.utcnow(),
interview_version=DATA_MODEL_SCHEMA_VERSION,
available=existing_info.available if existing_info else False,
attributes=parse_attributes_from_read_result(read_response.tlvAttributes),
)
if existing_info:
node.attribute_subscriptions = existing_info.attribute_subscriptions
# work out if the node is a bridge device by looking at the devicetype of endpoint 1
if attr_data := node.attributes.get("1/29/0"):
node.is_bridge = any(x[0] == 14 for x in attr_data)
# save updated node data
self._nodes[node_id] = node
self._write_node_state(node_id, True)
if is_new_node:
# new node - first interview
self.server.signal_event(EventType.NODE_ADDED, node)
else:
# existing node, signal node updated event
# TODO: maybe only signal this event if attributes actually changed ?
self.server.signal_event(EventType.NODE_UPDATED, node)
LOGGER.debug("Interview of node %s completed", node_id)
@api_command(APICommand.DEVICE_COMMAND)
async def send_device_command(
self,
node_id: int,
endpoint_id: int,
cluster_id: int,
command_name: str,
payload: dict,
response_type: Any | None = None,
timed_request_timeout_ms: int | None = None,
interaction_timeout_ms: int | None = None,
) -> Any:
"""Send a command to a Matter node/device."""
if (node := self._nodes.get(node_id)) is None or not node.available:
raise NodeNotReady(f"Node {node_id} is not (yet) available.")
cluster_cls: Cluster = ALL_CLUSTERS[cluster_id]
command_cls = getattr(cluster_cls.Commands, command_name)
command = dataclass_from_dict(command_cls, payload, allow_sdk_types=True)
if node_id >= TEST_NODE_START:
LOGGER.debug(
"send_device_command called for test node %s on endpoint_id: %s - "
"cluster_id: %s - command_name: %s - payload: %s\n%s",
node_id,
endpoint_id,
cluster_id,
command_name,
payload,
command,
)
return None
return await self._chip_device_controller.send_command(
node_id,
endpoint_id,
command,
response_type,
timed_request_timeout_ms,
interaction_timeout_ms,
)
@api_command(APICommand.READ_ATTRIBUTE)
async def read_attribute(
self,
node_id: int,
attribute_path: str | list[str],
fabric_filtered: bool = False,
) -> dict[str, Any]:
"""
Read one or more attribute(s) on a node by specifying an attributepath.
The attribute path can be a single string or a list of strings.
The attribute path may contain wildcards (*) for cluster and/or attribute id.
The return type is a dictionary with the attribute path as key and the value as value.
"""
if (node := self._nodes.get(node_id)) is None or not node.available:
raise NodeNotReady(f"Node {node_id} is not (yet) available.")
attribute_paths = (
attribute_path if isinstance(attribute_path, list) else [attribute_path]
)
# handle test node
if node_id >= TEST_NODE_START:
LOGGER.debug(
"read_attribute called for test node %s on path(s): %s - fabric_filtered: %s",
node_id,
str(attribute_paths),
fabric_filtered,
)
return {
attr_path: self._nodes[node_id].attributes.get(attr_path)
for attr_path in attribute_paths
}
# parse text based attribute paths into the SDK Attribute Path objects
attributes: list[Attribute.AttributePath] = []
for attr_path in attribute_paths:
endpoint_id, cluster_id, attribute_id = parse_attribute_path(attr_path)
attributes.append(
Attribute.AttributePath(
EndpointId=endpoint_id,
ClusterId=cluster_id,
AttributeId=attribute_id,
)
)
result = await self._chip_device_controller.read(
node_id,
attributes,
fabric_filtered,
)
read_atributes = parse_attributes_from_read_result(result.tlvAttributes)
# update cached info in node attributes and signal events for updated attributes
values_changed = False
for attr_path, value in read_atributes.items():
if node.attributes.get(attr_path) != value:
node.attributes[attr_path] = value
self.server.signal_event(
EventType.ATTRIBUTE_UPDATED,
# send data as tuple[node_id, attribute_path, new_value]
(node_id, attr_path, value),
)
values_changed = True
# schedule writing of the node state if any values changed
if values_changed:
self._write_node_state(node_id)
return read_atributes
@api_command(APICommand.WRITE_ATTRIBUTE)
async def write_attribute(
self,
node_id: int,
attribute_path: str,
value: Any,
) -> Any:
"""Write an attribute(value) on a target node."""
if (node := self._nodes.get(node_id)) is None or not node.available:
raise NodeNotReady(f"Node {node_id} is not (yet) available.")
endpoint_id, cluster_id, attribute_id = parse_attribute_path(attribute_path)
if endpoint_id is None:
raise InvalidArguments(f"Invalid attribute path: {attribute_path}")
attribute = cast(
Clusters.ClusterAttributeDescriptor,
ALL_ATTRIBUTES[cluster_id][attribute_id](),
)
attribute.value = parse_value(
name=attribute_path,
value=value,
value_type=attribute.attribute_type.Type,
allow_none=False,
allow_sdk_types=True,
)
if node_id >= TEST_NODE_START:
LOGGER.debug(
"write_attribute called for test node %s on path %s - value %s\n%s",
node_id,
attribute_path,
value,
attribute,
)
return None
return await self._chip_device_controller.write_attribute(
node_id, [(endpoint_id, attribute)]
)
@api_command(APICommand.REMOVE_NODE)
async def remove_node(self, node_id: int) -> None:
"""Remove a Matter node/device from the fabric."""
if node_id not in self._nodes:
raise NodeNotExists(
f"Node {node_id} does not exist or has not been interviewed."
)
LOGGER.info("Removing Node ID %s.", node_id)
# shutdown any existing subscriptions
await self._chip_device_controller.shutdown_subscription(node_id)
self._polled_attributes.pop(node_id, None)
node = self._nodes.pop(node_id)
self.server.storage.remove(
DATA_KEY_NODES,
subkey=str(node_id),
)
LOGGER.info("Node ID %s successfully removed from Matter server.", node_id)
self.server.signal_event(EventType.NODE_REMOVED, node_id)
if node is None or node_id >= TEST_NODE_START:
return
try:
await self._chip_device_controller.unpair_device(node_id)
except ChipStackError as err:
LOGGER.warning("Removing current fabric from device failed: %s", err)
@api_command(APICommand.PING_NODE)
async def ping_node(self, node_id: int, attempts: int = 1) -> NodePingResult:
"""Ping node on the currently known IP-address(es)."""
result: NodePingResult = {}
if node_id >= TEST_NODE_START:
return {"0.0.0.0": True, "0000:1111:2222:3333:4444": True}
node = self._nodes.get(node_id)
if node is None:
raise NodeNotExists(
f"Node {node_id} does not exist or is not yet interviewed"
)
node_logger = self.get_node_logger(LOGGER, node_id)
battery_powered = (
node.attributes.get(ROUTING_ROLE_ATTRIBUTE_PATH, 0)
== Clusters.ThreadNetworkDiagnostics.Enums.RoutingRoleEnum.kSleepyEndDevice
)
async def _do_ping(ip_address: str) -> None:
"""Ping IP and add to result."""
timeout = (
NODE_PING_TIMEOUT_BATTERY_POWERED
if battery_powered
else NODE_PING_TIMEOUT
)
if "%" in ip_address:
# ip address contains an interface index
clean_ip, interface_idx = ip_address.split("%", 1)
node_logger.debug(
"Pinging address %s (using interface %s)", clean_ip, interface_idx
)
else:
node_logger.debug("Pinging address %s", ip_address)
result[ip_address] = await ping_ip(ip_address, timeout, attempts=attempts)
ip_addresses = await self._get_node_ip_addresses(node_id, prefer_cache=False)
tasks = [_do_ping(x) for x in ip_addresses]
# TODO: replace this gather with a taskgroup once we bump our py version
await asyncio.gather(*tasks)
# retrieve the currently connected/used address which is used
# by the sdk for communicating with the device
if sdk_result := await self._chip_device_controller.get_address_and_port(
node_id
):
active_address = sdk_result[0]
node_logger.info(
"The SDK is communicating with the device using %s", active_address
)
if active_address not in result and node.available:
# if the sdk is connected to a node, treat the address as pingable
result[active_address] = True
return result
async def _get_node_ip_addresses(
self, node_id: int, prefer_cache: bool = False
) -> list[str]:
"""Get the IP addresses of a node."""
cached_info = self._last_known_ip_addresses.get(node_id, [])
if prefer_cache and cached_info:
return cached_info
node = self._nodes.get(node_id)
if node is None:
raise NodeNotExists(
f"Node {node_id} does not exist or is not yet interviewed"
)
node_logger = self.get_node_logger(LOGGER, node_id)
# query mdns for all IP's
# ensure both fabric id and node id have 16 characters (prefix with zero's)
mdns_name = f"{self.compressed_fabric_id:0{16}X}-{node_id:0{16}X}.{MDNS_TYPE_OPERATIONAL_NODE}"
info = AsyncServiceInfo(MDNS_TYPE_OPERATIONAL_NODE, mdns_name)
if TYPE_CHECKING:
assert self._aiozc is not None
if not await info.async_request(self._aiozc.zeroconf, 3000):
node_logger.info(
"Node could not be discovered on the network, returning cached IP's"
)
return cached_info
ip_addresses = info.parsed_scoped_addresses(IPVersion.All)
# cache this info for later use
self._last_known_ip_addresses[node_id] = ip_addresses
return ip_addresses
@api_command(APICommand.GET_NODE_IP_ADDRESSES)
async def get_node_ip_addresses(
self,
node_id: int,
prefer_cache: bool = False,
scoped: bool = False,
) -> list[str]:
"""Return the currently known (scoped) IP-address(es)."""
ip_addresses = await self._get_node_ip_addresses(node_id, prefer_cache)
return ip_addresses if scoped else [x.split("%")[0] for x in ip_addresses]
@api_command(APICommand.IMPORT_TEST_NODE)
async def import_test_node(self, dump: str) -> None:
"""Import test node(s) from a HA or Matter server diagnostics dump."""
try:
dump_data = cast(dict, json_loads(dump))
except JSON_DECODE_EXCEPTIONS as err:
raise InvalidArguments("Invalid json") from err
# the dump format we accept here is a Home Assistant diagnostics file
# dump can either be a single dump or a full dump with multiple nodes
dump_nodes: list[dict[str, Any]]
if "node" in dump_data["data"]:
dump_nodes = [dump_data["data"]["node"]]
else:
dump_nodes = dump_data["data"]["server"]["nodes"]
# node ids > 900000 are reserved for test nodes
if self._nodes:
next_test_node_id = max(*(x for x in self._nodes), TEST_NODE_START) + 1
else:
# an empty self._nodes dict evaluates to false so we set the first
# test node id to TEST_NODE_START
next_test_node_id = TEST_NODE_START
for node_dict in dump_nodes:
node = dataclass_from_dict(MatterNodeData, node_dict, strict=True)
node.node_id = next_test_node_id
next_test_node_id += 1
self._nodes[node.node_id] = node
self.server.signal_event(EventType.NODE_ADDED, node)
@api_command(APICommand.CHECK_NODE_UPDATE)
async def check_node_update(self, node_id: int) -> MatterSoftwareVersion | None:
"""
Check if there is an update for a particular node.
Reads the current software version and checks the DCL if there is an update
available. If there is an update available, the command returns the version
information of the latest update available.
"""
update = await self._check_node_update(node_id)
if update is None:
return None
if not all(
key in update
for key in [
"vid",
"pid",
"softwareVersion",
"softwareVersionString",
"minApplicableSoftwareVersion",
"maxApplicableSoftwareVersion",
]
):
raise UpdateCheckError("Invalid update data")
return MatterSoftwareVersion(
vid=update["vid"],
pid=update["pid"],
software_version=update["softwareVersion"],
software_version_string=update["softwareVersionString"],
firmware_information=update.get("firmwareInformation", None),
min_applicable_software_version=update["minApplicableSoftwareVersion"],
max_applicable_software_version=update["maxApplicableSoftwareVersion"],
release_notes_url=update.get("releaseNotesUrl", None),
)
@api_command(APICommand.UPDATE_NODE)
async def update_node(self, node_id: int, software_version: int | str) -> None:
"""
Update a node to a new software version.
This command checks if the requested software version is indeed still available
and if so, it will start the update process. The update process will be handled
by the built-in OTA provider. The OTA provider will download the update and
notify the node about the new update.
"""
node_logger = LOGGER.getChild(f"node_{node_id}")
node_logger.info("Update to software version %r", software_version)
update = await self._check_node_update(node_id, software_version)
if update is None:
raise UpdateCheckError(
f"Software version {software_version} is not available for node {node_id}."
)
# Add update to the OTA provider
ota_provider = ExternalOtaProvider(
self.server.vendor_id, self._ota_provider_dir / f"{node_id}"
)
await ota_provider.initialize()
node_logger.info("Downloading update from '%s'", update["otaUrl"])
await ota_provider.download_update(update)
self._attribute_update_callbacks.setdefault(node_id, []).append(
ota_provider.check_update_state
)
try:
if node_id in self._nodes_in_ota:
raise UpdateError(
f"Node {node_id} is already in the process of updating."
)
self._nodes_in_ota.add(node_id)
# Make sure any previous instances get stopped
node_logger.info("Starting update using OTA Provider.")
await ota_provider.start_update(
self._chip_device_controller,
node_id,
)
finally:
self._attribute_update_callbacks[node_id].remove(
ota_provider.check_update_state
)
self._nodes_in_ota.remove(node_id)
async def _check_node_update(
self,
node_id: int,
requested_software_version: int | str | None = None,
) -> dict | None:
node_logger = LOGGER.getChild(f"node_{node_id}")