Skip to content

Commit

Permalink
[python] Add command for closing an open connection (#8430)
Browse files Browse the repository at this point in the history
* [python] Add command for closing an open connection

Currently, the CHIP stack is not able to recover an open
CASE session in certain circumstances such as a device
reboot. Add a command for closing an open session on the
controller side so that the connection can be started from
scratch when necessary.

* Update README
  • Loading branch information
Damian-Nordic authored and pull[bot] committed Aug 26, 2021
1 parent da8f6c2 commit 1177888
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/controller/CHIPDevice.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,14 @@ CHIP_ERROR Device::OpenPairingWindow(uint32_t timeout, PairingWindowOption optio
return CHIP_NO_ERROR;
}

CHIP_ERROR Device::CloseSession()
{
ReturnErrorCodeIf(mState != ConnectionState::SecureConnected, CHIP_ERROR_INCORRECT_STATE);
mSessionManager->ExpirePairing(mSecureSession);
mState = ConnectionState::NotConnected;
return CHIP_NO_ERROR;
}

CHIP_ERROR Device::UpdateAddress(const Transport::PeerAddress & addr)
{
bool didLoad;
Expand Down Expand Up @@ -505,12 +513,7 @@ void Device::OperationalCertProvisioned()
mDeviceOperationalCertProvisioned = true;

Persist();

if (mState == ConnectionState::SecureConnected)
{
mSessionManager->ExpirePairing(mSecureSession);
mState = ConnectionState::NotConnected;
}
CloseSession();
}

CHIP_ERROR Device::WarmupCASESession()
Expand Down
5 changes: 5 additions & 0 deletions src/controller/CHIPDevice.h
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,11 @@ class DLL_EXPORT Device : public Messaging::ExchangeDelegate, public SessionEsta
*/
CHIP_ERROR OpenPairingWindow(uint32_t timeout, PairingWindowOption option, SetupPayload & setupPayload);

/**
* In case there exists an open session to the device, mark it as expired.
*/
CHIP_ERROR CloseSession();

/**
* @brief
* Update address of the device.
Expand Down
9 changes: 9 additions & 0 deletions src/controller/python/ChipDeviceController-ScriptBinding.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ CHIP_ERROR pychip_DeviceController_ConnectBLE(chip::Controller::DeviceCommission
uint32_t setupPINCode, chip::NodeId nodeid);
CHIP_ERROR pychip_DeviceController_ConnectIP(chip::Controller::DeviceCommissioner * devCtrl, const char * peerAddrStr,
uint32_t setupPINCode, chip::NodeId nodeid);
CHIP_ERROR pychip_DeviceController_CloseSession(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid);

CHIP_ERROR pychip_DeviceController_DiscoverCommissionableNodesLongDiscriminator(chip::Controller::DeviceCommissioner * devCtrl,
uint16_t long_discriminator);
Expand Down Expand Up @@ -257,6 +258,14 @@ CHIP_ERROR pychip_DeviceController_ConnectIP(chip::Controller::DeviceCommissione
return devCtrl->PairDevice(nodeid, params);
}

CHIP_ERROR pychip_DeviceController_CloseSession(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid)
{
Device * device;
ReturnErrorOnFailure(devCtrl->GetDevice(nodeid, &device));

return device->CloseSession();
}

CHIP_ERROR pychip_DeviceController_DiscoverAllCommissionableNodes(chip::Controller::DeviceCommissioner * devCtrl)
{
Mdns::DiscoveryFilter filter(Mdns::DiscoveryFilterType::kNone, (uint16_t) 0);
Expand Down
5 changes: 5 additions & 0 deletions src/controller/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,11 @@ persisted by controller / device.

If no nodeid given, a random Node ID will be used.

### `close-session <nodeid>`

If case there eixsts an open session (PASE or CASE) to the device with a given
Node ID, mark it as expired.

### `discover`

Discover available Matter accessory devices:
Expand Down
18 changes: 18 additions & 0 deletions src/controller/python/chip-device-ctrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ def __init__(self, rendezvousAddr=None, controllerNodeId=0, bluetoothAdapter=Non

"connect",
"close-ble",
"close-session",
"resolve",
"zcl",
"zclread",
Expand Down Expand Up @@ -527,6 +528,23 @@ def do_connect(self, line):
print(str(ex))
return

def do_closesession(self, line):
"""
close-session <nodeid>
Close any session associated with a given node ID.
"""
try:
parser = argparse.ArgumentParser()
parser.add_argument('nodeid', type=int, help='Peer node ID')
args = parser.parse_args(shlex.split(line))

self.devCtrl.CloseSession(args.nodeid)
except exceptions.ChipStackException as ex:
print(str(ex))
except:
self.do_help("close-session")

def do_resolve(self, line):
"""
resolve <fabricid> <nodeid>
Expand Down
8 changes: 8 additions & 0 deletions src/controller/python/chip/ChipDeviceCtrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,11 @@ def CloseBLEConnection(self):
lambda: self._dmLib.pychip_DeviceCommissioner_CloseBleConnection(self.devCtrl)
)

def CloseSession(self, nodeid):
return self._ChipStack.Call(
lambda: self._dmLib.pychip_DeviceController_CloseSession(self.devCtrl, nodeid)
)

def ConnectIP(self, ipaddr, setupPinCode, nodeid):
self.state = DCState.RENDEZVOUS_ONGOING
return self._ChipStack.CallAsync(
Expand Down Expand Up @@ -398,6 +403,9 @@ def _InitLib(self):
self._dmLib.pychip_DeviceController_ConnectIP.argtypes = [c_void_p, c_char_p, c_uint32, c_uint64]
self._dmLib.pychip_DeviceController_ConnectIP.restype = c_uint32

self._dmLib.pychip_DeviceController_CloseSession.argtypes = [c_void_p, c_uint64]
self._dmLib.pychip_DeviceController_CloseSession.restype = c_uint32

self._dmLib.pychip_DeviceController_GetAddressAndPort.argtypes = [
c_void_p, c_uint64, c_char_p, c_uint64, POINTER(c_uint16)]
self._dmLib.pychip_DeviceController_GetAddressAndPort.restype = c_uint32
Expand Down
9 changes: 9 additions & 0 deletions src/controller/python/test/test_scripts/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ def TestKeyExchange(self, ip: str, setuppin: int, nodeid: int):
self.logger.info("Device finished key exchange.")
return True

def TestCloseSession(self, nodeid: int):
self.logger.info(f"Closing sessions with device {nodeid}")
try:
self.devCtrl.CloseSession(nodeid)
return True
except Exception as ex:
self.logger.exception(f"Failed to close sessions with device {nodeid}: {ex}")
return False

def TestNetworkCommissioning(self, nodeid: int, endpoint: int, group: int, dataset: str, network_id: str):
self.logger.info("Commissioning network to device {}".format(nodeid))
try:
Expand Down
3 changes: 3 additions & 0 deletions src/controller/python/test/test_scripts/mobile-device-test.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ def main():
group=GROUP_ID),
"Failed to test Write Basic Attributes")

logger.info("Testing closing sessions")
FailIfNot(test.TestCloseSession(nodeid=1), "Failed to close sessions")

timeoutTicker.stop()

logger.info("Test finished")
Expand Down

0 comments on commit 1177888

Please sign in to comment.