From 1380616fc3962e08d1760d7cb0ee62642e37ffba Mon Sep 17 00:00:00 2001 From: tianfeng-yang <130436698+tianfeng-yang@users.noreply.github.com> Date: Tue, 20 Jun 2023 11:19:53 +0800 Subject: [PATCH] [Python] export manual code when OpenCommissioningWindow (#27059) * [Python] export manual code when OpenCommissioningWindow * fix CI * fix CI * fix CI * return class replacement tuple && restyled by autopep8 * fix CI * Rename parameter name & restyled by autopep8 --- ...Controller-ScriptDevicePairingDelegate.cpp | 15 ++++--- ...ceController-ScriptDevicePairingDelegate.h | 4 +- src/controller/python/chip/ChipDeviceCtrl.py | 20 +++++++--- .../python/test/test_scripts/base.py | 39 +++++++++---------- src/python_testing/TC_CGEN_2_4.py | 15 +++---- src/python_testing/TC_DA_1_5.py | 4 +- 6 files changed, 55 insertions(+), 42 deletions(-) diff --git a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp index 66f461d0071b3c..b1e7fa98c9df1d 100644 --- a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp +++ b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp @@ -20,6 +20,7 @@ #include "ChipDeviceController-ScriptDevicePairingDelegate.h" #include "lib/support/TypeTraits.h" #include +#include #include namespace chip { @@ -133,11 +134,15 @@ void ScriptDevicePairingDelegate::OnOpenCommissioningWindow(NodeId deviceId, CHI { if (mOnWindowOpenCompleteCallback != nullptr) { - QRCodeSetupPayloadGenerator generator(payload); - std::string code; - generator.payloadBase38Representation(code); - ChipLogProgress(Zcl, "code = %s", code.c_str()); - mOnWindowOpenCompleteCallback(deviceId, payload.setUpPINCode, code.c_str(), ToPyChipError(status)); + std::string setupManualCode; + std::string setupQRCode; + + ManualSetupPayloadGenerator(payload).payloadDecimalStringRepresentation(setupManualCode); + QRCodeSetupPayloadGenerator(payload).payloadBase38Representation(setupQRCode); + ChipLogProgress(Zcl, "SetupManualCode = %s", setupManualCode.c_str()); + ChipLogProgress(Zcl, "SetupQRCode = %s", setupQRCode.c_str()); + mOnWindowOpenCompleteCallback(deviceId, payload.setUpPINCode, setupManualCode.c_str(), setupQRCode.c_str(), + ToPyChipError(status)); } if (mWindowOpener != nullptr) { diff --git a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h index 2bfd50b37436a8..b93ba94f532270 100644 --- a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h +++ b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h @@ -35,8 +35,8 @@ namespace Controller { extern "C" { typedef void (*DevicePairingDelegate_OnPairingCompleteFunct)(PyChipError err); typedef void (*DevicePairingDelegate_OnCommissioningCompleteFunct)(NodeId nodeId, PyChipError err); -typedef void (*DevicePairingDelegate_OnWindowOpenCompleteFunct)(NodeId nodeId, uint32_t setupPinCode, const char * setupCode, - PyChipError err); +typedef void (*DevicePairingDelegate_OnWindowOpenCompleteFunct)(NodeId nodeId, uint32_t setupPinCode, const char * manualCode, + const char * setupQRCode, PyChipError err); // Used for testing by OpCredsBinding typedef void (*DevicePairingDelegate_OnCommissioningSuccessFunct)(PeerId peerId); diff --git a/src/controller/python/chip/ChipDeviceCtrl.py b/src/controller/python/chip/ChipDeviceCtrl.py index 3cf99f6572b434..401a356d7556ca 100644 --- a/src/controller/python/chip/ChipDeviceCtrl.py +++ b/src/controller/python/chip/ChipDeviceCtrl.py @@ -57,7 +57,7 @@ from .interaction_model import delegate as im from .native import PyChipError -__all__ = ["ChipDeviceController"] +__all__ = ["ChipDeviceController", "CommissioningParameters"] # Defined in $CHIP_ROOT/src/lib/core/CHIPError.h CHIP_ERROR_TIMEOUT: int = 50 @@ -67,7 +67,7 @@ _DevicePairingDelegate_OnCommissioningCompleteFunct = CFUNCTYPE( None, c_uint64, PyChipError) _DevicePairingDelegate_OnOpenWindowCompleteFunct = CFUNCTYPE( - None, c_uint64, c_uint32, c_char_p, PyChipError) + None, c_uint64, c_uint32, c_char_p, c_char_p, PyChipError) _DevicePairingDelegate_OnCommissioningStatusUpdateFunct = CFUNCTYPE( None, c_uint64, c_uint8, PyChipError) # void (*)(Device *, CHIP_ERROR). @@ -82,6 +82,13 @@ _ChipDeviceController_IterateDiscoveredCommissionableNodesFunct = CFUNCTYPE(None, c_char_p, c_size_t) +@dataclass +class CommissioningParameters: + setupPinCode: int + setupManualCode: str + setupQRCode: str + + @dataclass class NOCChain: nocBytes: bytes @@ -260,10 +267,12 @@ def HandleCommissioningComplete(nodeid, err): self._ChipStack.commissioningCompleteEvent.set() self._ChipStack.completeEvent.set() - def HandleOpenWindowComplete(nodeid: int, setupPinCode: int, setupCode: str, err: PyChipError) -> None: + def HandleOpenWindowComplete(nodeid: int, setupPinCode: int, setupManualCode: str, + setupQRCode: str, err: PyChipError) -> None: if err.is_success: print("Open Commissioning Window complete setting nodeid {} pincode to {}".format(nodeid, setupPinCode)) - self._ChipStack.openCommissioningWindowPincode[nodeid] = (setupPinCode, setupCode) + self._ChipStack.openCommissioningWindowPincode[nodeid] = CommissioningParameters( + setupPinCode=setupPinCode, setupManualCode=setupManualCode.decode(), setupQRCode=setupQRCode.decode()) else: print("Failed to open commissioning window: {}".format(err)) @@ -658,7 +667,8 @@ def DiscoverAllCommissioning(self): self.devCtrl) ).raise_on_error() - def OpenCommissioningWindow(self, nodeid: int, timeout: int, iteration: int, discriminator: int, option: int) -> (int, str): + def OpenCommissioningWindow(self, nodeid: int, timeout: int, iteration: int, + discriminator: int, option: int) -> CommissioningParameters: self.CheckIsActive() self._ChipStack.CallAsync( lambda: self._dmLib.pychip_DeviceController_OpenCommissioningWindow( diff --git a/src/controller/python/test/test_scripts/base.py b/src/controller/python/test/test_scripts/base.py index 57a757401eeec5..8ab30f8f6f5686 100644 --- a/src/controller/python/test/test_scripts/base.py +++ b/src/controller/python/test/test_scripts/base.py @@ -130,14 +130,12 @@ def CheckEnableBeforeRun(*args, **kwargs): def configurable_tests(): - res = [v for v in _configurable_test_sets] - res.sort() + res = sorted([v for v in _configurable_test_sets]) return res def configurable_test_cases(): - res = [v for v in _configurable_tests] - res.sort() + res = sorted([v for v in _configurable_tests]) return res @@ -190,7 +188,8 @@ def assertValueEqual(self, expected): class BaseTestHelper: - def __init__(self, nodeid: int, paaTrustStorePath: str, testCommissioner: bool = False, keypair: p256keypair.P256Keypair = None): + def __init__(self, nodeid: int, paaTrustStorePath: str, testCommissioner: bool = False, + keypair: p256keypair.P256Keypair = None): chip.native.Init() self.chipStack = ChipStack('/tmp/repl_storage.json') @@ -250,16 +249,16 @@ async def TestRevokeCommissioningWindow(self, ip: str, setuppin: int, nodeid: in nodeid, 0, Clusters.GeneralCommissioning.Commands.ArmFailSafe(expiryLengthSeconds=180, breadcrumb=0)) await self.devCtrl.SendCommand( - nodeid, 0, Clusters.AdministratorCommissioning.Commands.RevokeCommissioning(), timedRequestTimeoutMs=10000) + nodeid, 0, Clusters.AdministratorCommissioning.Commands.RevokeCommissioning(), timedRequestTimeoutMs=10000) await self.devCtrl.SendCommand( nodeid, 0, Clusters.AdministratorCommissioning.Commands.OpenBasicCommissioningWindow(180), timedRequestTimeoutMs=10000) await self.devCtrl.SendCommand( - nodeid, 0, Clusters.AdministratorCommissioning.Commands.RevokeCommissioning(), timedRequestTimeoutMs=10000) + nodeid, 0, Clusters.AdministratorCommissioning.Commands.RevokeCommissioning(), timedRequestTimeoutMs=10000) return True def TestEnhancedCommissioningWindow(self, ip: str, nodeid: int): - pin, code = self.devCtrl.OpenCommissioningWindow(nodeid=nodeid, timeout=600, iteration=10000, discriminator=3840, option=1) - return self.TestPaseOnly(ip=ip, nodeid=nodeid, setuppin=pin, devCtrl=self.devCtrl2) + params = self.devCtrl.OpenCommissioningWindow(nodeid=nodeid, timeout=600, iteration=10000, discriminator=3840, option=1) + return self.TestPaseOnly(ip=ip, nodeid=nodeid, setuppin=params.setupPinCode, devCtrl=self.devCtrl2) def TestPaseOnly(self, ip: str, setuppin: int, nodeid: int, devCtrl=None): if devCtrl is None: @@ -461,9 +460,9 @@ async def TestControllerCATValues(self, nodeid: int): # Read out the attribute again - this time, it should succeed. res = await newControllers[0].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)]) - if (type(res[0][ + if (not isinstance(res[0][ Clusters.AccessControl][ - Clusters.AccessControl.Attributes.Acl][0]) != Clusters.AccessControl.Structs.AccessControlEntryStruct): + Clusters.AccessControl.Attributes.Acl][0], Clusters.AccessControl.Structs.AccessControlEntryStruct)): self.logger.error(f"2: Received something other than data:{res}") return False @@ -505,9 +504,9 @@ async def TestMultiControllerFabric(self, nodeid: int): # Doing this ensures that we're not somehow aliasing the CASE sessions. # res = await self.devCtrl.ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)]) - if (type(res[0][ + if (not isinstance(res[0][ Clusters.AccessControl][ - Clusters.AccessControl.Attributes.Acl][0]) != Clusters.AccessControl.Structs.AccessControlEntryStruct): + Clusters.AccessControl.Attributes.Acl][0], Clusters.AccessControl.Structs.AccessControlEntryStruct)): self.logger.error(f"2: Received something other than data:{res}") return False @@ -531,9 +530,9 @@ async def TestMultiControllerFabric(self, nodeid: int): targetNodeId=nodeid ) res = await newControllers[0].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)]) - if (type(res[0][ + if (not isinstance(res[0][ Clusters.AccessControl][ - Clusters.AccessControl.Attributes.Acl][0]) != Clusters.AccessControl.Structs.AccessControlEntryStruct): + Clusters.AccessControl.Attributes.Acl][0], Clusters.AccessControl.Structs.AccessControlEntryStruct)): self.logger.error(f"4: Received something other than data:{res}") return False @@ -547,9 +546,9 @@ async def TestMultiControllerFabric(self, nodeid: int): targetNodeId=nodeid ) res = await newControllers[1].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.AccessControl.Attributes.Acl)]) - if (type(res[0][ + if (not isinstance(res[0][ Clusters.AccessControl][ - Clusters.AccessControl.Attributes.Acl][0]) != Clusters.AccessControl.Structs.AccessControlEntryStruct): + Clusters.AccessControl.Attributes.Acl][0], Clusters.AccessControl.Structs.AccessControlEntryStruct)): self.logger.error(f"5: Received something other than data:{res}") return False @@ -571,11 +570,9 @@ async def TestMultiControllerFabric(self, nodeid: int): # res = await newControllers[1].ReadAttribute(nodeid=nodeid, attributes=[(0, Clusters.BasicInformation.Attributes.ClusterRevision)]) - if (type( - res[0][ + if (not isinstance(res[0][ Clusters.BasicInformation][ - Clusters.BasicInformation.Attributes.ClusterRevision] - ) != Clusters.BasicInformation.Attributes.ClusterRevision.attribute_type.Type): + Clusters.BasicInformation.Attributes.ClusterRevision], Clusters.BasicInformation.Attributes.ClusterRevision.attribute_type.Type)): self.logger.error(f"7: Received something other than data:{res}") return False diff --git a/src/python_testing/TC_CGEN_2_4.py b/src/python_testing/TC_CGEN_2_4.py index 56db66b3cbe508..1f0e86b5cd172d 100644 --- a/src/python_testing/TC_CGEN_2_4.py +++ b/src/python_testing/TC_CGEN_2_4.py @@ -23,18 +23,19 @@ import chip.clusters.enum import chip.FabricAdmin from chip import ChipDeviceCtrl +from chip.ChipDeviceCtrl import CommissioningParameters from matter_testing_support import MatterBaseTest, async_test_body, default_matter_test_main from mobly import asserts class TC_CGEN_2_4(MatterBaseTest): - def OpenCommissioningWindow(self) -> int: + def OpenCommissioningWindow(self) -> CommissioningParameters: try: - pin, code = self.th1.OpenCommissioningWindow( + params = self.th1.OpenCommissioningWindow( nodeid=self.dut_node_id, timeout=600, iteration=10000, discriminator=self.matter_test_config.discriminators[0], option=1) time.sleep(5) - return pin, code + return params except Exception as e: logging.exception('Error running OpenCommissioningWindow %s', e) @@ -44,13 +45,13 @@ async def CommissionToStageSendCompleteAndCleanup( self, stage: int, expectedErrorPart: chip.native.ErrorSDKPart, expectedErrCode: int): logging.info("-----------------Fail on step {}-------------------------".format(stage)) - pin, code = self.OpenCommissioningWindow() + params = self.OpenCommissioningWindow() self.th2.ResetTestCommissioner() # This will run the commissioning up to the point where stage x is run and the # response is sent before the test commissioner simulates a failure self.th2.SetTestCommissionerPrematureCompleteAfter(stage) errcode = self.th2.CommissionOnNetwork( - nodeId=self.dut_node_id, setupPinCode=pin, + nodeId=self.dut_node_id, setupPinCode=params.setupPinCode, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=self.matter_test_config.discriminators[0]) logging.info('Commissioning complete done. Successful? {}, errorcode = {}'.format(errcode.is_success, errcode)) asserts.assert_false(errcode.is_success, 'Commissioning complete did not error as expected') @@ -85,12 +86,12 @@ async def test_TC_CGEN_2_4(self): await self.CommissionToStageSendCompleteAndCleanup(13, chip.native.ErrorSDKPart.IM_CLUSTER_STATUS, 0x02) logging.info('Step 15 - TH1 opens a commissioning window') - pin, code = self.OpenCommissioningWindow() + params = self.OpenCommissioningWindow() logging.info('Step 16 - TH2 fully commissions the DUT') self.th2.ResetTestCommissioner() errcode = self.th2.CommissionOnNetwork( - nodeId=self.dut_node_id, setupPinCode=pin, + nodeId=self.dut_node_id, setupPinCode=params.setupPinCode, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=self.matter_test_config.discriminators[0]) logging.info('Commissioning complete done. Successful? {}, errorcode = {}'.format(errcode.is_success, errcode)) diff --git a/src/python_testing/TC_DA_1_5.py b/src/python_testing/TC_DA_1_5.py index 5634f53b3b93f3..567d7577604288 100644 --- a/src/python_testing/TC_DA_1_5.py +++ b/src/python_testing/TC_DA_1_5.py @@ -162,7 +162,7 @@ async def test_TC_DA_1_5(self): await self.send_single_cmd(cmd=gcomm.Commands.ArmFailSafe(expiryLengthSeconds=0, breadcrumb=1)) self.print_step(13, "Open commissioning window") - pin, _ = self.default_controller.OpenCommissioningWindow( + params = self.default_controller.OpenCommissioningWindow( nodeid=self.dut_node_id, timeout=600, iteration=10000, discriminator=1234, option=1) self.print_step(14, "Commission to TH2") @@ -171,7 +171,7 @@ async def test_TC_DA_1_5(self): TH2 = new_fabric_admin.NewController(nodeId=112233) errcode = TH2.CommissionOnNetwork( - nodeId=self.dut_node_id, setupPinCode=pin, + nodeId=self.dut_node_id, setupPinCode=params.setupPinCode, filterType=ChipDeviceCtrl.DiscoveryFilterType.LONG_DISCRIMINATOR, filter=1234) asserts.assert_true(errcode.is_success, 'Commissioning on TH2 did not complete successfully')