Skip to content

Commit

Permalink
[Python] export manual code when OpenCommissioningWindow (#27059)
Browse files Browse the repository at this point in the history
* [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
  • Loading branch information
tianfeng-yang authored and pull[bot] committed Nov 20, 2023
1 parent 5aa092f commit 5486609
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include "ChipDeviceController-ScriptDevicePairingDelegate.h"
#include "lib/support/TypeTraits.h"
#include <controller/python/chip/native/PyChipError.h>
#include <setup_payload/ManualSetupPayloadGenerator.h>
#include <setup_payload/QRCodeSetupPayloadGenerator.h>

namespace chip {
Expand Down Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
20 changes: 15 additions & 5 deletions src/controller/python/chip/ChipDeviceCtrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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).
Expand All @@ -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
Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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(
Expand Down
39 changes: 18 additions & 21 deletions src/controller/python/test/test_scripts/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand All @@ -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

Expand All @@ -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

Expand All @@ -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

Expand Down
15 changes: 8 additions & 7 deletions src/python_testing/TC_CGEN_2_4.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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')
Expand Down Expand Up @@ -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))

Expand Down
4 changes: 2 additions & 2 deletions src/python_testing/TC_DA_1_5.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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')

Expand Down

0 comments on commit 5486609

Please sign in to comment.