forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChipDeviceCtrl.py
2445 lines (1937 loc) · 114 KB
/
ChipDeviceCtrl.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
#
# Copyright (c) 2020-2025 Project CHIP Authors
# Copyright (c) 2019-2020 Google, LLC.
# Copyright (c) 2013-2018 Nest Labs, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# @file
# Python interface for Chip Device Manager
#
"""Chip Device Controller interface
"""
# Needed to use types in type hints before they are fully defined.
from __future__ import absolute_import, annotations, print_function
import asyncio
import builtins
import concurrent.futures
import copy
import ctypes
import enum
import json
import logging
import secrets
import threading
import typing
from ctypes import (CDLL, CFUNCTYPE, POINTER, Structure, byref, c_bool, c_char, c_char_p, c_int, c_int32, c_size_t, c_uint8,
c_uint16, c_uint32, c_uint64, c_void_p, cast, create_string_buffer, pointer, py_object, resize, string_at)
from dataclasses import dataclass
import dacite # type: ignore
from . import FabricAdmin
from . import clusters as Clusters
from . import discovery
from .bdx import Bdx
from .clusters import Attribute as ClusterAttribute
from .clusters import ClusterObjects as ClusterObjects
from .clusters import Command as ClusterCommand
from .clusters.CHIPClusters import ChipClusters
from .crypto import p256keypair
from .interaction_model import SessionParameters, SessionParametersStruct
from .native import PyChipError
__all__ = ["ChipDeviceController", "CommissioningParameters"]
# Defined in $CHIP_ROOT/src/lib/core/CHIPError.h
CHIP_ERROR_TIMEOUT: int = 50
_RCACCallbackType = CFUNCTYPE(None, POINTER(c_uint8), c_size_t)
LOGGER = logging.getLogger(__name__)
_DevicePairingDelegate_OnPairingCompleteFunct = CFUNCTYPE(None, PyChipError)
_DeviceUnpairingCompleteFunct = CFUNCTYPE(None, c_uint64, PyChipError)
_DevicePairingDelegate_OnCommissioningCompleteFunct = CFUNCTYPE(
None, c_uint64, PyChipError)
_DevicePairingDelegate_OnOpenWindowCompleteFunct = CFUNCTYPE(
None, c_uint64, c_uint32, c_char_p, c_char_p, PyChipError)
_DevicePairingDelegate_OnCommissioningStatusUpdateFunct = CFUNCTYPE(
None, c_uint64, c_uint8, PyChipError)
_DevicePairingDelegate_OnFabricCheckFunct = CFUNCTYPE(
None, c_uint64)
# void (*)(Device *, CHIP_ERROR).
#
# CHIP_ERROR is actually signed, so using c_uint32 is weird, but everything
# else seems to do it.
_DeviceAvailableCallbackFunct = CFUNCTYPE(None, py_object, c_void_p, PyChipError)
_IssueNOCChainCallbackPythonCallbackFunct = CFUNCTYPE(
None, py_object, PyChipError, c_void_p, c_size_t, c_void_p, c_size_t, c_void_p, c_size_t, c_void_p, c_size_t, c_uint64)
_ChipDeviceController_IterateDiscoveredCommissionableNodesFunct = CFUNCTYPE(None, c_char_p, c_size_t)
# Defines for the transport payload types to use to select the suitable
# underlying transport of the session.
# class TransportPayloadCapability(ctypes.c_int):
class TransportPayloadCapability(ctypes.c_int):
MRP_PAYLOAD = 0
LARGE_PAYLOAD = 1
MRP_OR_TCP_PAYLOAD = 2
@dataclass
class CommissioningParameters:
setupPinCode: int
setupManualCode: str
setupQRCode: str
@dataclass
class NOCChain:
nocBytes: typing.Optional[bytes]
icacBytes: typing.Optional[bytes]
rcacBytes: typing.Optional[bytes]
ipkBytes: typing.Optional[bytes]
adminSubject: int
@dataclass
class ICDRegistrationParameters:
symmetricKey: typing.Optional[bytes]
checkInNodeId: typing.Optional[int]
monitoredSubject: typing.Optional[int]
stayActiveMs: typing.Optional[int]
clientType: typing.Optional[Clusters.IcdManagement.Enums.ClientTypeEnum]
class CStruct(Structure):
_fields_ = [('symmetricKey', c_char_p), ('symmetricKeyLength', c_size_t), ('checkInNodeId',
c_uint64), ('monitoredSubject', c_uint64), ('stayActiveMsec', c_uint32), ('clientType', c_uint8)]
def to_c(self):
return ICDRegistrationParameters.CStruct(self.symmetricKey, len(self.symmetricKey), self.checkInNodeId, self.monitoredSubject, self.stayActiveMs, self.clientType.value)
@_DeviceAvailableCallbackFunct
def _DeviceAvailableCallback(closure, device, err):
closure.deviceAvailable(device, err)
@_IssueNOCChainCallbackPythonCallbackFunct
def _IssueNOCChainCallbackPythonCallback(devCtrl, status: PyChipError, noc: c_void_p, nocLen: int, icac: c_void_p,
icacLen: int, rcac: c_void_p, rcacLen: int, ipk: c_void_p, ipkLen: int, adminSubject: int):
nocChain = NOCChain(None, None, None, None, 0)
if status.is_success:
nocBytes = None
if nocLen > 0:
nocBytes = string_at(noc, nocLen)[:]
icacBytes = None
if icacLen > 0:
icacBytes = string_at(icac, icacLen)[:]
rcacBytes = None
if rcacLen > 0:
rcacBytes = string_at(rcac, rcacLen)[:]
ipkBytes = None
if ipkLen > 0:
ipkBytes = string_at(ipk, ipkLen)[:]
nocChain = NOCChain(nocBytes, icacBytes, rcacBytes, ipkBytes, adminSubject)
devCtrl.NOCChainCallback(nocChain)
# Methods for ICD
class ScopedNodeId(Structure):
_fields_ = [("nodeId", c_uint64), ("fabricIndex", c_uint8)]
def __hash__(self):
return self.nodeId << 8 | self.fabricIndex
def __str__(self):
return f"({self.fabricIndex}:{self.nodeId:16x})"
def __eq__(self, other):
return self.nodeId == other.nodeId and self.fabricIndex == other.fabricIndex
_OnCheckInCompleteFunct = CFUNCTYPE(None, ScopedNodeId)
_OnCheckInCompleteWaitListLock = threading.Lock()
_OnCheckInCompleteWaitList: typing.Dict[ScopedNodeId, set] = dict()
@_OnCheckInCompleteFunct
def _OnCheckInComplete(scopedNodeId: ScopedNodeId):
callbacks = []
with _OnCheckInCompleteWaitListLock:
callbacks = list(_OnCheckInCompleteWaitList.get(scopedNodeId, set()))
for callback in callbacks:
callback(scopedNodeId)
def RegisterOnActiveCallback(scopedNodeId: ScopedNodeId, callback: typing.Callable[[ScopedNodeId], None]):
''' Registers a callback when the device with given (fabric index, node id) becomes active.
Does nothing if the callback is already registered.
'''
with _OnCheckInCompleteWaitListLock:
waitList = _OnCheckInCompleteWaitList.get(scopedNodeId, set())
waitList.add(callback)
_OnCheckInCompleteWaitList[scopedNodeId] = waitList
def UnregisterOnActiveCallback(scopedNodeId: ScopedNodeId, callback: typing.Callable[[ScopedNodeId], None]):
''' Unregisters a callback when the device with given (fabric index, node id) becomes active.
Does nothing if the callback has not been registered.
'''
with _OnCheckInCompleteWaitListLock:
_OnCheckInCompleteWaitList.get(scopedNodeId, set()).remove(callback)
async def WaitForCheckIn(scopedNodeId: ScopedNodeId, timeoutSeconds: float):
''' Waits for a device becomes active.
Returns:
- A future, completes when the device becomes active.
'''
eventLoop = asyncio.get_running_loop()
future = eventLoop.create_future()
def OnCheckInCallback(nodeid):
eventLoop.call_soon_threadsafe(lambda: future.done() or future.set_result(None))
RegisterOnActiveCallback(scopedNodeId, OnCheckInCallback)
try:
await asyncio.wait_for(future, timeout=timeoutSeconds)
finally:
UnregisterOnActiveCallback(scopedNodeId, OnCheckInCallback)
# This is a fix for WEAV-429. Jay Logue recommends revisiting this at a later
# date to allow for truly multiple instances so this is temporary.
def _singleton(cls):
instance = [None]
def wrapper(*args, **kwargs):
if instance[0] is None:
instance[0] = cls(*args, **kwargs)
return instance[0]
return wrapper
class CallbackContext:
"""A context manager for handling callbacks that are expected to be called exactly once.
The context manager makes sure that no concurrent operations which use the same callback
handlers are executed.
"""
def __init__(self, lock: asyncio.Lock) -> None:
self._lock = lock
self._future = None
async def __aenter__(self):
await self._lock.acquire()
self._future = concurrent.futures.Future()
return self
@property
def future(self) -> typing.Optional[concurrent.futures.Future]:
return self._future
async def __aexit__(self, exc_type, exc_value, traceback):
if not self._future.done():
# In case the initial call (which sets up for the callback) fails,
# the future will never be used actually. So just cancel it here
# for completeness, in case somebody is expecting it to be completed.
self._future.cancel()
self._future = None
self._lock.release()
class CommissioningContext(CallbackContext):
"""A context manager for handling commissioning callbacks that are expected to be called exactly once.
This context also resets commissioning related device controller state.
"""
def __init__(self, devCtrl: ChipDeviceControllerBase, lock: asyncio.Lock) -> None:
super().__init__(lock)
self._devCtrl = devCtrl
async def __aenter__(self):
await super().__aenter__()
self._devCtrl._fabricCheckNodeId = -1
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await super().__aexit__(exc_type, exc_value, traceback)
class CommissionableNode(discovery.CommissionableNode):
def SetDeviceController(self, devCtrl: 'ChipDeviceController'):
self._devCtrl = devCtrl
def Commission(self, nodeId: int, setupPinCode: int) -> int:
''' Commission the device using the device controller discovered this device.
nodeId: The nodeId commissioned to the device
setupPinCode: The setup pin code of the device
Returns:
- Effective Node ID of the device (as defined by the assigned NOC)
'''
return self._devCtrl.CommissionOnNetwork(
nodeId, setupPinCode, filterType=discovery.FilterType.INSTANCE_NAME, filter=self.instanceName)
def __rich_repr__(self):
yield "(To Be Commissioned By)", self._devCtrl.name
for k in self.__dataclass_fields__.keys():
if k in self.__dict__:
yield k, self.__dict__[k]
class DeviceProxyWrapper():
''' Encapsulates a pointer to OperationalDeviceProxy on the c++ side that needs to be
freed when DeviceProxyWrapper goes out of scope. There is a potential issue where
if this is copied around that a double free will occur, but how this is used today
that is not an issue that needs to be accounted for and it will become very apparent
if that happens.
'''
class DeviceProxyType(enum.Enum):
OPERATIONAL = enum.auto(),
COMMISSIONEE = enum.auto(),
def __init__(self, deviceProxy: ctypes.c_void_p, proxyType, dmLib=None):
self._deviceProxy = deviceProxy
self._dmLib = dmLib
self._proxyType = proxyType
def __del__(self):
# Commissionee device proxies are owned by the DeviceCommissioner. See #33031
if (self._proxyType == self.DeviceProxyType.OPERATIONAL and self._dmLib is not None and hasattr(builtins, 'chipStack') and builtins.chipStack is not None):
# This destructor is called from any threading context, including on the Matter threading context.
# So, we cannot call chipStack.Call or chipStack.CallAsyncWithCompleteCallback which waits for the posted work to
# actually be executed. Instead, we just post/schedule the work and move on.
builtins.chipStack.PostTaskOnChipThread(lambda: self._dmLib.pychip_FreeOperationalDeviceProxy(self._deviceProxy))
@property
def deviceProxy(self) -> ctypes.c_void_p:
return self._deviceProxy
@property
def localSessionId(self) -> int:
self._dmLib.pychip_GetLocalSessionId.argtypes = [ctypes.c_void_p, POINTER(ctypes.c_uint16)]
self._dmLib.pychip_GetLocalSessionId.restype = PyChipError
localSessionId = ctypes.c_uint16(0)
builtins.chipStack.Call(
lambda: self._dmLib.pychip_GetLocalSessionId(self._deviceProxy, pointer(localSessionId))
).raise_on_error()
return localSessionId.value
@property
def numTotalSessions(self) -> int:
self._dmLib.pychip_GetNumSessionsToPeer.argtypes = [ctypes.c_void_p, POINTER(ctypes.c_uint32)]
self._dmLib.pychip_GetNumSessionsToPeer.restype = PyChipError
numSessions = ctypes.c_uint32(0)
builtins.chipStack.Call(
lambda: self._dmLib.pychip_GetNumSessionsToPeer(self._deviceProxy, pointer(numSessions))
).raise_on_error()
return numSessions.value
@property
def attestationChallenge(self) -> bytes:
self._dmLib.pychip_GetAttestationChallenge.argtypes = (c_void_p, POINTER(c_uint8), POINTER(c_size_t))
self._dmLib.pychip_GetAttestationChallenge.restype = PyChipError
# this buffer is overly large, but we shall resize
size = 64
buf = ctypes.c_uint8(size)
csize = ctypes.c_size_t(size)
builtins.chipStack.Call(
lambda: self._dmLib.pychip_GetAttestationChallenge(self._deviceProxy, buf, ctypes.byref(csize))
).raise_on_error()
resize(buf, csize.value)
return bytes(buf)
@property
def sessionAllowsLargePayload(self) -> bool:
self._dmLib.pychip_SessionAllowsLargePayload.argtypes = [ctypes.c_void_p, POINTER(ctypes.c_bool)]
self._dmLib.pychip_SessionAllowsLargePayload.restype = PyChipError
supportsLargePayload = ctypes.c_bool(False)
builtins.chipStack.Call(
lambda: self._dmLib.pychip_SessionAllowsLargePayload(self._deviceProxy, pointer(supportsLargePayload))
).raise_on_error()
return supportsLargePayload.value
@property
def isSessionOverTCPConnection(self) -> bool:
self._dmLib.pychip_IsSessionOverTCPConnection.argtypes = [ctypes.c_void_p, POINTER(ctypes.c_bool)]
self._dmLib.pychip_IsSessionOverTCPConnection.restype = PyChipError
isSessionOverTCP = ctypes.c_bool(False)
builtins.chipStack.Call(
lambda: self._dmLib.pychip_IsSessionOverTCPConnection(self._deviceProxy, pointer(isSessionOverTCP))
).raise_on_error()
return isSessionOverTCP.value
@property
def isActiveSession(self) -> bool:
self._dmLib.pychip_IsActiveSession.argtypes = [ctypes.c_void_p, POINTER(ctypes.c_bool)]
self._dmLib.pychip_IsActiveSession.restype = PyChipError
isActiveSession = ctypes.c_bool(False)
builtins.chipStack.Call(
lambda: self._dmLib.pychip_IsActiveSession(self._deviceProxy, pointer(isActiveSession))
).raise_on_error()
return isActiveSession.value
def closeTCPConnectionWithPeer(self):
self._dmLib.pychip_CloseTCPConnectionWithPeer.argtypes = [ctypes.c_void_p]
self._dmLib.pychip_CloseTCPConnectionWithPeer.restype = PyChipError
builtins.chipStack.Call(
lambda: self._dmLib.pychip_CloseTCPConnectionWithPeer(self._deviceProxy)
).raise_on_error()
DiscoveryFilterType = discovery.FilterType
DiscoveryType = discovery.DiscoveryType
class ChipDeviceControllerBase():
activeList: typing.Set = set()
def __init__(self, name: str = ''):
self.devCtrl = None
self._ChipStack = builtins.chipStack
self._dmLib: typing.Any = None
self._InitLib()
pairingDelegate = c_void_p(None)
devCtrl = c_void_p(None)
self.pairingDelegate = pairingDelegate
self.devCtrl = devCtrl
self.name = name
self._fabricCheckNodeId = -1
self._isActive = False
self._Cluster = ChipClusters(builtins.chipStack)
self._Cluster.InitLib(self._dmLib)
self._commissioning_lock: asyncio.Lock = asyncio.Lock()
self._commissioning_context: CommissioningContext = CommissioningContext(self, self._commissioning_lock)
self._open_window_context: CallbackContext = CallbackContext(asyncio.Lock())
self._unpair_device_context: CallbackContext = CallbackContext(asyncio.Lock())
self._pase_establishment_context: CallbackContext = CallbackContext(self._commissioning_lock)
def _set_dev_ctrl(self, devCtrl, pairingDelegate):
def HandleCommissioningComplete(nodeId: int, err: PyChipError):
if err.is_success:
LOGGER.info("Commissioning complete")
else:
LOGGER.warning("Failed to commission: {}".format(err))
self._dmLib.pychip_DeviceController_SetIcdRegistrationParameters(False, None)
if self._dmLib.pychip_TestCommissionerUsed():
err = self._dmLib.pychip_GetCompletionError()
if self._commissioning_context.future is None:
LOGGER.exception("HandleCommissioningComplete called unexpectedly")
return
if err.is_success:
self._commissioning_context.future.set_result(nodeId)
else:
self._commissioning_context.future.set_exception(err.to_exception())
def HandleFabricCheck(nodeId):
self._fabricCheckNodeId = nodeId
def HandleOpenWindowComplete(nodeid: int, setupPinCode: int, setupManualCode: bytes,
setupQRCode: bytes, err: PyChipError) -> None:
if err.is_success:
LOGGER.info("Open Commissioning Window complete setting nodeid {} pincode to {}".format(nodeid, setupPinCode))
commissioningParameters = CommissioningParameters(
setupPinCode=setupPinCode, setupManualCode=setupManualCode.decode(), setupQRCode=setupQRCode.decode())
else:
LOGGER.warning("Failed to open commissioning window: {}".format(err))
if self._open_window_context.future is None:
LOGGER.exception("HandleOpenWindowComplete called unexpectedly")
return
if err.is_success:
self._open_window_context.future.set_result(commissioningParameters)
else:
self._open_window_context.future.set_exception(err.to_exception())
def HandleUnpairDeviceComplete(nodeid: int, err: PyChipError):
if err.is_success:
LOGGER.info("Succesfully unpaired device with nodeid {}".format(nodeid))
else:
LOGGER.warning("Failed to unpair device: {}".format(err))
if self._unpair_device_context.future is None:
LOGGER.exception("HandleUnpairDeviceComplete called unexpectedly")
return
if err.is_success:
self._unpair_device_context.future.set_result(None)
else:
self._unpair_device_context.future.set_exception(err.to_exception())
def HandlePASEEstablishmentComplete(err: PyChipError):
if not err.is_success:
LOGGER.warning("Failed to establish secure session to device: {}".format(err))
else:
LOGGER.info("Established secure session with Device")
if self._commissioning_context.future is not None:
# During Commissioning, HandlePASEEstablishmentComplete will also be called.
# Only complete the future if PASE session establishment failed.
if not err.is_success:
self._commissioning_context.future.set_exception(err.to_exception())
return
if self._pase_establishment_context.future is None:
LOGGER.exception("HandlePASEEstablishmentComplete called unexpectedly")
return
if err.is_success:
self._pase_establishment_context.future.set_result(None)
else:
self._pase_establishment_context.future.set_exception(err.to_exception())
self.pairingDelegate = pairingDelegate
self.devCtrl = devCtrl
self.cbHandlePASEEstablishmentCompleteFunct = _DevicePairingDelegate_OnPairingCompleteFunct(
HandlePASEEstablishmentComplete)
self._dmLib.pychip_ScriptDevicePairingDelegate_SetKeyExchangeCallback(
self.pairingDelegate, self.cbHandlePASEEstablishmentCompleteFunct)
self.cbHandleCommissioningCompleteFunct = _DevicePairingDelegate_OnCommissioningCompleteFunct(
HandleCommissioningComplete)
self._dmLib.pychip_ScriptDevicePairingDelegate_SetCommissioningCompleteCallback(
self.pairingDelegate, self.cbHandleCommissioningCompleteFunct)
self.cbHandleFabricCheckFunct = _DevicePairingDelegate_OnFabricCheckFunct(HandleFabricCheck)
self._dmLib.pychip_ScriptDevicePairingDelegate_SetFabricCheckCallback(self.pairingDelegate, self.cbHandleFabricCheckFunct)
self.cbHandleOpenWindowCompleteFunct = _DevicePairingDelegate_OnOpenWindowCompleteFunct(
HandleOpenWindowComplete)
self._dmLib.pychip_ScriptDevicePairingDelegate_SetOpenWindowCompleteCallback(
self.pairingDelegate, self.cbHandleOpenWindowCompleteFunct)
self.cbHandleDeviceUnpairCompleteFunct = _DeviceUnpairingCompleteFunct(HandleUnpairDeviceComplete)
self._isActive = True
# Validate FabricID/NodeID followed from NOC Chain
self._fabricId = self.GetFabricIdInternal()
self._fabricIndex = self.GetFabricIndexInternal()
self._nodeId = self.GetNodeIdInternal()
def _finish_init(self):
self._isActive = True
ChipDeviceController.activeList.add(self)
def _enablePairingCompleteCallback(self, value: bool):
self._dmLib.pychip_ScriptDevicePairingDelegate_SetExpectingPairingComplete(self.pairingDelegate, value)
@property
def nodeId(self) -> int:
return self._nodeId
@property
def fabricId(self) -> int:
return self._fabricId
@property
def name(self) -> str:
return self._name
@name.setter
def name(self, new_name: str):
self._name = new_name
@property
def isActive(self) -> bool:
return self._isActive
def Shutdown(self):
''' Shuts down this controller and reclaims any used resources, including the bound
C++ constructor instance in the SDK.
'''
if not self._isActive:
return
if self.devCtrl is not None:
self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_DeleteDeviceController(
self.devCtrl, self.pairingDelegate)
).raise_on_error()
self.pairingDelegate = None
self.devCtrl = None
ChipDeviceController.activeList.remove(self)
self._isActive = False
def ShutdownAll(self):
''' Shut down all active controllers and reclaim any used resources.
'''
#
# We want a shallow copy here since it would other create new instances
# of the controllers in the list.
#
# We need a copy since we're going to walk through the list and shutdown
# each controller, which in turn, will remove themselves from the active list.
#
# We cannot do that while iterating through the original list.
#
activeList = copy.copy(ChipDeviceController.activeList)
for controller in activeList:
controller.Shutdown()
ChipDeviceController.activeList.clear()
def CheckIsActive(self):
if (not self._isActive):
raise RuntimeError(
"DeviceCtrl instance was already shutdown previously!")
def __del__(self):
self.Shutdown()
def IsConnected(self):
self.CheckIsActive()
return self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_IsConnected(
self.devCtrl)
)
async def ConnectBLE(self, discriminator: int, setupPinCode: int, nodeid: int, isShortDiscriminator: bool = False) -> int:
"""Connect to a BLE device using the given discriminator and setup pin code.
Returns:
- Effective Node ID of the device (as defined by the assigned NOC)
"""
self.CheckIsActive()
async with self._commissioning_context as ctx:
self._enablePairingCompleteCallback(True)
await self._ChipStack.CallAsync(
lambda: self._dmLib.pychip_DeviceController_ConnectBLE(
self.devCtrl, discriminator, isShortDiscriminator, setupPinCode, nodeid)
)
return await asyncio.futures.wrap_future(ctx.future)
async def UnpairDevice(self, nodeid: int) -> None:
self.CheckIsActive()
async with self._unpair_device_context as ctx:
await self._ChipStack.CallAsync(
lambda: self._dmLib.pychip_DeviceController_UnpairDevice(
self.devCtrl, nodeid, self.cbHandleDeviceUnpairCompleteFunct)
)
return await asyncio.futures.wrap_future(ctx.future)
def CloseBLEConnection(self):
self.CheckIsActive()
self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceCommissioner_CloseBleConnection(
self.devCtrl)
).raise_on_error()
def ExpireSessions(self, nodeid):
"""Close all sessions with `nodeid` (if any existed) so that sessions get re-established.
This is needed to properly handle operations that invalidate a node's state, such as
UpdateNOC.
WARNING: ONLY CALL THIS IF YOU UNDERSTAND THE SIDE-EFFECTS
"""
self.CheckIsActive()
self._ChipStack.Call(lambda: self._dmLib.pychip_ExpireSessions(self.devCtrl, nodeid)).raise_on_error()
def MarkSessionDefunct(self, nodeid):
'''
Marks a previously active session with the specified node as defunct to temporarily prevent it
from being used with new exchanges to send or receive messages. This should be called when there
is suspicion of a loss-of-sync with the session state on the associated peer, such as evidence
of transport failure.
If messages are received thereafter on this session, the session will be put back into the Active state.
This function should only be called on an active session.
This will NOT detach any existing SessionHolders.
Parameters:
nodeid (int): The node ID of the device whose session should be marked as defunct.
Raises:
RuntimeError: If the controller is not active.
PyChipError: If the operation fails.
'''
self.CheckIsActive()
self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_MarkSessionDefunct(
self.devCtrl, nodeid)
).raise_on_error()
def MarkSessionForEviction(self, nodeid):
'''
Marks the session with the specified node for eviction. It will first detach all SessionHolders
attached to this session by calling 'OnSessionReleased' on each of them. This will force them
to release their reference to the session. If there are no more references left, the session
will then be de-allocated.
Once marked for eviction, the session SHALL NOT ever become active again.
Parameters:
nodeid (int): The node ID of the device whose session should be marked for eviction.
Raises:
RuntimeError: If the controller is not active.
PyChipError: If the operation fails.
'''
self.CheckIsActive()
self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_MarkSessionForEviction(
self.devCtrl, nodeid)
).raise_on_error()
async def _establishPASESession(self, callFunct):
self.CheckIsActive()
async with self._pase_establishment_context as ctx:
self._enablePairingCompleteCallback(True)
await self._ChipStack.CallAsync(callFunct)
await asyncio.futures.wrap_future(ctx.future)
async def EstablishPASESessionBLE(self, setupPinCode: int, discriminator: int, nodeid: int) -> None:
await self._establishPASESession(
lambda: self._dmLib.pychip_DeviceController_EstablishPASESessionBLE(
self.devCtrl, setupPinCode, discriminator, nodeid)
)
async def EstablishPASESessionIP(self, ipaddr: str, setupPinCode: int, nodeid: int, port: int = 0) -> None:
await self._establishPASESession(
lambda: self._dmLib.pychip_DeviceController_EstablishPASESessionIP(
self.devCtrl, ipaddr.encode("utf-8"), setupPinCode, nodeid, port)
)
async def EstablishPASESession(self, setUpCode: str, nodeid: int) -> None:
await self._establishPASESession(
lambda: self._dmLib.pychip_DeviceController_EstablishPASESession(
self.devCtrl, setUpCode.encode("utf-8"), nodeid)
)
def GetTestCommissionerUsed(self):
return self._ChipStack.Call(
lambda: self._dmLib.pychip_TestCommissionerUsed()
)
def ResetTestCommissioner(self):
self._dmLib.pychip_ResetCommissioningTests()
def SetTestCommissionerSimulateFailureOnStage(self, stage: int):
return self._dmLib.pychip_SetTestCommissionerSimulateFailureOnStage(
stage)
def SetTestCommissionerSimulateFailureOnReport(self, stage: int):
return self._dmLib.pychip_SetTestCommissionerSimulateFailureOnReport(
stage)
def SetTestCommissionerPrematureCompleteAfter(self, stage: int):
return self._dmLib.pychip_SetTestCommissionerPrematureCompleteAfter(
stage)
def CheckTestCommissionerCallbacks(self):
return self._ChipStack.Call(
lambda: self._dmLib.pychip_TestCommissioningCallbacks()
)
def CheckStageSuccessful(self, stage: int):
return self._ChipStack.Call(
lambda: self._dmLib.pychip_TestCommissioningStageSuccessful(stage)
)
def CheckTestCommissionerPaseConnection(self, nodeid):
return self._dmLib.pychip_TestPaseConnection(nodeid)
def ResolveNode(self, nodeid):
self.CheckIsActive()
self.GetConnectedDeviceSync(nodeid, allowPASE=False)
def GetAddressAndPort(self, nodeid):
self.CheckIsActive()
address = create_string_buffer(64)
port = c_uint16(0)
# Intentially return None instead of raising exceptions on error
error = self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_GetAddressAndPort(
self.devCtrl, nodeid, address, 64, pointer(port))
)
return (address.value.decode(), port.value) if error == 0 else None
async def DiscoverCommissionableNodes(self, filterType: discovery.FilterType = discovery.FilterType.NONE, filter: typing.Any = None,
stopOnFirst: bool = False, timeoutSecond: int = 5) -> typing.Union[None, CommissionableNode, typing.List[CommissionableNode]]:
''' Discover commissionable nodes via DNS-SD with specified filters.
Supported filters are:
discovery.FilterType.NONE
discovery.FilterType.SHORT_DISCRIMINATOR
discovery.FilterType.LONG_DISCRIMINATOR
discovery.FilterType.VENDOR_ID
discovery.FilterType.DEVICE_TYPE
discovery.FilterType.COMMISSIONING_MODE
discovery.FilterType.INSTANCE_NAME
discovery.FilterType.COMMISSIONER
discovery.FilterType.COMPRESSED_FABRIC_ID
This function will always return a list of CommissionableDevice. When stopOnFirst is set,
this function will return when at least one device is discovered or on timeout.
'''
self.CheckIsActive()
if isinstance(filter, int):
filter = str(filter)
# Discovery is also used during commissioning. Make sure this manual discovery
# and commissioning attempts do not interfere with each other.
async with self._commissioning_lock:
await self._ChipStack.CallAsync(
lambda: self._dmLib.pychip_DeviceController_DiscoverCommissionableNodes(
self.devCtrl, int(filterType), str(filter).encode("utf-8")))
async def _wait_discovery():
while not await self._ChipStack.CallAsyncWithResult(
lambda: self._dmLib.pychip_DeviceController_HasDiscoveredCommissionableNode(self.devCtrl)):
await asyncio.sleep(0.1)
return
try:
if stopOnFirst:
await asyncio.wait_for(_wait_discovery(), timeoutSecond)
else:
await asyncio.sleep(timeoutSecond)
except TimeoutError:
# Expected timeout, do nothing
pass
finally:
await self._ChipStack.CallAsync(
lambda: self._dmLib.pychip_DeviceController_StopCommissionableDiscovery(self.devCtrl))
return await self.GetDiscoveredDevices()
async def GetDiscoveredDevices(self):
def GetDevices(devCtrl):
devices = []
@_ChipDeviceController_IterateDiscoveredCommissionableNodesFunct
def HandleDevice(deviceJson, deviceJsonLen):
jsonStr = ctypes.string_at(deviceJson, deviceJsonLen).decode("utf-8")
device = dacite.from_dict(data_class=CommissionableNode, data=json.loads(jsonStr))
device.SetDeviceController(devCtrl)
devices.append(device)
self._dmLib.pychip_DeviceController_IterateDiscoveredCommissionableNodes(devCtrl.devCtrl, HandleDevice)
return devices
return await self._ChipStack.CallAsyncWithResult(lambda: GetDevices(self))
def GetIPForDiscoveredDevice(self, idx, addrStr, length):
self.CheckIsActive()
return self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_GetIPForDiscoveredDevice(
self.devCtrl, idx, addrStr, length)
)
class CommissioningWindowPasscode(enum.IntEnum):
kOriginalSetupCode = 0,
kTokenWithRandomPin = 1,
async def OpenCommissioningWindow(self, nodeid: int, timeout: int, iteration: int,
discriminator: int, option: CommissioningWindowPasscode) -> CommissioningParameters:
''' Opens a commissioning window on the device with the given nodeid.
nodeid: Node id of the device
timeout: Command timeout
iteration: The PAKE iteration count associated with the PAKE Passcode ID and ephemeral
PAKE passcode verifier to be used for this commissioning. Valid range: 1000 - 100000
Ignored if option == 0
discriminator: The long discriminator for the DNS-SD advertisement. Valid range: 0-4095
Ignored if option == 0
option: 0 = kOriginalSetupCode
1 = kTokenWithRandomPIN
Returns CommissioningParameters
'''
self.CheckIsActive()
async with self._open_window_context as ctx:
await self._ChipStack.CallAsync(
lambda: self._dmLib.pychip_DeviceController_OpenCommissioningWindow(
self.devCtrl, self.pairingDelegate, nodeid, timeout, iteration, discriminator, option)
)
return await asyncio.futures.wrap_future(ctx.future)
def GetCompressedFabricId(self):
self.CheckIsActive()
fabricid = c_uint64(0)
self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_GetCompressedFabricId(
self.devCtrl, pointer(fabricid))
).raise_on_error()
return fabricid.value
def GetFabricIdInternal(self):
"""Get the fabric ID from the object. Only used to validate cached value from property."""
self.CheckIsActive()
fabricid = c_uint64(0)
self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_GetFabricId(
self.devCtrl, pointer(fabricid))
).raise_on_error()
return fabricid.value
def GetFabricIndexInternal(self):
"""Get the fabric index from the object. Only used to validate cached value from property."""
self.CheckIsActive()
fabricindex = c_uint8(0)
self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_GetFabricIndex(
self.devCtrl, pointer(fabricindex))
).raise_on_error()
return fabricindex.value
def GetNodeIdInternal(self) -> int:
"""Get the node ID from the object. Only used to validate cached value from property."""
self.CheckIsActive()
nodeid = c_uint64(0)
self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_GetNodeId(
self.devCtrl, pointer(nodeid))
).raise_on_error()
return nodeid.value
def GetClusterHandler(self):
self.CheckIsActive()
return self._Cluster
async def FindOrEstablishPASESession(self, setupCode: str, nodeid: int, timeoutMs: typing.Optional[int] = None) -> typing.Optional[DeviceProxyWrapper]:
''' Returns CommissioneeDeviceProxy if we can find or establish a PASE connection to the specified device'''
self.CheckIsActive()
returnDevice = c_void_p(None)
res = await self._ChipStack.CallAsyncWithResult(lambda: self._dmLib.pychip_GetDeviceBeingCommissioned(
self.devCtrl, nodeid, byref(returnDevice)), timeoutMs)
if res.is_success:
return DeviceProxyWrapper(returnDevice, DeviceProxyWrapper.DeviceProxyType.COMMISSIONEE, self._dmLib)
await self.EstablishPASESession(setupCode, nodeid)