Skip to content

Linux chip-tool network recovery feature example #38421

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/chip-tool/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ static_library("chip-tool-utils") {
"commands/discover/DiscoverCommissionersCommand.cpp",
"commands/icd/ICDCommand.cpp",
"commands/icd/ICDCommand.h",
"commands/network-recovery/NetworkRecoveryCommand.cpp",
"commands/pairing/OpenCommissioningWindowCommand.cpp",
"commands/pairing/OpenCommissioningWindowCommand.h",
"commands/pairing/PairingCommand.cpp",
Expand Down
36 changes: 36 additions & 0 deletions examples/chip-tool/commands/network-recovery/Commands.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright (c) 2025 Project CHIP Authors
* 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.
*
*/

#pragma once

#include "NetworkRecoveryCommand.h"
#include <commands/common/Commands.h>

void registerCommandsNetworkRecovery(Commands & commands, CredentialIssuerCommands * credsIssuerConfig)
{
const char * clusterName = "networkrecovery";

commands_list clusterCommands = {
make_unique<NetworkRecoveryDiscoverCommand>(credsIssuerConfig),
make_unique<NetworkRecoveryRecoverCommand>("recover-wifi", RecoveryNetworkType::WiFi, credsIssuerConfig),
make_unique<NetworkRecoveryRecoverCommand>("recover-thread", RecoveryNetworkType::Thread, credsIssuerConfig),
};

commands.RegisterCommandSet(clusterName, clusterCommands,
"Commands for discovering and recovering recoverable devices by chip-tool.");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright (c) 2025 Project CHIP Authors
* 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.
*
*/

#include "NetworkRecoveryCommand.h"
#include <commands/common/DeviceScanner.h>
#include <commands/common/RemoteDataModelLogger.h>
#include <lib/support/BytesToHex.h>

using namespace ::chip;

void NetworkRecoveryCommandBase::OnNetworkRecoverDiscover(std::list<uint64_t> recoveryIds)
{
ChipLogProgress(chipTool, "Find recoverable devices:");
for (const auto & recoveryId : recoveryIds)
{
ChipLogProgress(chipTool, "0x" ChipLogFormatX64, ChipLogValueX64(recoveryId));
(void) recoveryId; // Avoid unused variable warning in case logging is disabled
}
SetCommandExitStatus(CHIP_NO_ERROR);
}

void NetworkRecoveryCommandBase::OnNetworkRecoverComplete(NodeId deviceId, CHIP_ERROR error)
{
if (error == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Recovery complete for devicice " ChipLogFormatX64, ChipLogValueX64(deviceId));
}
else
{
ChipLogError(chipTool, "Recovery failed for device " ChipLogFormatX64, ChipLogValueX64(deviceId));
}
SetCommandExitStatus(error);
}

CHIP_ERROR NetworkRecoveryDiscoverCommand::RunCommand()
{
uint16_t timeout = mTimeout.ValueOr(30);
ChipLogProgress(chipTool, "Start scanning recoverable nodes, timeout:%d", timeout);
mCommissioner = &CurrentCommissioner();
mCommissioner->RegisterNetworkRecoverDelegate(this);
return mCommissioner->DiscoverRecoverableNodes(timeout);
}

CHIP_ERROR NetworkRecoveryRecoverCommand::RunCommand()
{
CHIP_ERROR err;
mCommissioner = &CurrentCommissioner();
mCommissioner->RegisterNetworkRecoverDelegate(this);
if (mOperationalDataset.empty())
{
chip::Controller::WiFiCredentials wiFiCreds(mSSID, mPassword);
err = mCommissioner->RecoverNode(mNodeId, mRecoveryId, wiFiCreds, mBreadcrumb);
}
else
{
err = mCommissioner->RecoverNode(mNodeId, mRecoveryId, mOperationalDataset, mBreadcrumb);
}
return err;
}
106 changes: 106 additions & 0 deletions examples/chip-tool/commands/network-recovery/NetworkRecoveryCommand.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* Copyright (c) 2025 Project CHIP Authors
* 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.
*
*/

#pragma once

#include "../common/CHIPCommand.h"
#include <controller/NetworkRecover.h>
#include <lib/support/Span.h>
#include <lib/support/ThreadOperationalDataset.h>

enum class RecoveryNetworkType
{
None,
WiFi,
Thread,
};

class NetworkRecoveryCommandBase : public CHIPCommand, public chip::Controller::NetworkRecoverDelegate
{
public:
NetworkRecoveryCommandBase(const char * name, CredentialIssuerCommands * credsIssuerConfig) :
CHIPCommand(name, credsIssuerConfig)
{}
/////////// NetworkRecoverDelegate Interface /////////
void OnNetworkRecoverDiscover(std::list<uint64_t> recoveryIds) override;
void OnNetworkRecoverComplete(NodeId deviceId, CHIP_ERROR error) override;

/////////// CHIPCommand Interface /////////
chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(30); }

protected:
chip::Controller::DeviceCommissioner * mCommissioner;
};

class NetworkRecoveryDiscoverCommand : public NetworkRecoveryCommandBase
{
public:
NetworkRecoveryDiscoverCommand(CredentialIssuerCommands * credsIssuerConfig) :
NetworkRecoveryCommandBase("discover", credsIssuerConfig)
{
AddArgument("timeout", 0, UINT16_MAX, &mTimeout);
}
CHIP_ERROR RunCommand() override;
chip::System::Clock::Timeout GetWaitDuration() const override
{
return chip::System::Clock::Seconds16(mTimeout.ValueOr(30) + 10);
}

private:
chip::Optional<uint16_t> mTimeout;
};

class NetworkRecoveryRecoverCommand : public NetworkRecoveryCommandBase
{
public:
NetworkRecoveryRecoverCommand(const char * commandName, RecoveryNetworkType networkType,
CredentialIssuerCommands * credsIssuerConfig) :
NetworkRecoveryCommandBase(commandName, credsIssuerConfig),
mNetworkType(networkType)
{
AddArgument("node-id", 0, UINT64_MAX, &mNodeId);
AddArgument("recovery-identifier", 0, UINT64_MAX, &mRecoveryId);

switch (mNetworkType)
{
case RecoveryNetworkType::WiFi:
AddArgument("ssid", &mSSID);
AddArgument("password", &mPassword);
break;
case RecoveryNetworkType::Thread:
AddArgument("operational-dataset", &mOperationalDataset);
break;
default:
break;
}
AddArgument("breadcrumb", 0, UINT64_MAX, &mBreadcrumb);
}

CHIP_ERROR RunCommand() override;
chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(70); }

private:
chip::NodeId mNodeId;
uint64_t mRecoveryId;
RecoveryNetworkType mNetworkType;
chip::ByteSpan mSSID;
chip::ByteSpan mPassword;
chip::ByteSpan mOperationalDataset;
uint64_t mBreadcrumb;
chip::Optional<uint16_t> mTimeout;
};
2 changes: 2 additions & 0 deletions examples/chip-tool/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include "commands/group/Commands.h"
#include "commands/icd/ICDCommand.h"
#include "commands/interactive/Commands.h"
#include "commands/network-recovery/Commands.h"
#include "commands/pairing/Commands.h"
#include "commands/payload/Commands.h"
#include "commands/session-management/Commands.h"
Expand All @@ -52,6 +53,7 @@ int main(int argc, char * argv[])
registerCommandsSubscriptions(commands, &credIssuerCommands);
registerCommandsStorage(commands);
registerCommandsSessionManagement(commands, &credIssuerCommands);
registerCommandsNetworkRecovery(commands, &credIssuerCommands);

return commands.Run(argc, argv);
}
1 change: 1 addition & 0 deletions scripts/tools/check_includes_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@
# Not really for embedded consumers; uses std::deque to keep track
# of a list of discovered things.
'src/controller/SetUpCodePairer.h': {'deque'},
'src/controller/NetworkRecover.h': {'deque', 'list'},

'src/controller/ExamplePersistentStorage.cpp': {'fstream', 'string', 'map'},

Expand Down
71 changes: 71 additions & 0 deletions src/app/CASESessionManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,21 @@ void CASESessionManager::FindOrEstablishSession(const ScopedNodeId & peerId, Cal
transportPayloadCapability);
}

void CASESessionManager::FindOrEstablishSession(const ScopedNodeId & peerId, Callback::Callback<OnDeviceConnected> * onConnection,
Callback::Callback<OnDeviceConnectionFailure> * onFailure,
Transport::PeerAddress & addr,
#if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
uint8_t attemptCount, Callback::Callback<OnDeviceConnectionRetry> * onRetry,
#endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
TransportPayloadCapability transportPayloadCapability)
{
FindOrEstablishSessionHelper(peerId, onConnection, onFailure, nullptr, addr,
#if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
attemptCount, onRetry,
#endif
transportPayloadCapability);
}

void CASESessionManager::FindOrEstablishSession(const ScopedNodeId & peerId, Callback::Callback<OnDeviceConnected> * onConnection,
Callback::Callback<OperationalSessionSetup::OnSetupFailure> * onSetupFailure,
#if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
Expand Down Expand Up @@ -131,6 +146,62 @@ void CASESessionManager::FindOrEstablishSessionHelper(const ScopedNodeId & peerI
}
}

void CASESessionManager::FindOrEstablishSessionHelper(const ScopedNodeId & peerId,
Callback::Callback<OnDeviceConnected> * onConnection,
Callback::Callback<OnDeviceConnectionFailure> * onFailure,
Callback::Callback<OperationalSessionSetup::OnSetupFailure> * onSetupFailure,
Transport::PeerAddress & addr,
#if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
uint8_t attemptCount, Callback::Callback<OnDeviceConnectionRetry> * onRetry,
#endif
TransportPayloadCapability transportPayloadCapability)
{
ChipLogDetail(CASESessionManager, "FindOrEstablishSession: PeerId = [%d:" ChipLogFormatX64 "]", peerId.GetFabricIndex(),
ChipLogValueX64(peerId.GetNodeId()));

bool forAddressUpdate = false;
OperationalSessionSetup * session = FindExistingSessionSetup(peerId, forAddressUpdate);
if (session == nullptr)
{
ChipLogDetail(CASESessionManager, "FindOrEstablishSession: No existing OperationalSessionSetup instance found");
session = mConfig.sessionSetupPool->Allocate(mConfig.sessionInitParams, mConfig.clientPool, peerId, this);

if (session == nullptr)
{
if (onFailure != nullptr)
{
onFailure->mCall(onFailure->mContext, peerId, CHIP_ERROR_NO_MEMORY);
}

if (onSetupFailure != nullptr)
{
OperationalSessionSetup::ConnectionFailureInfo failureInfo(peerId, CHIP_ERROR_NO_MEMORY,
SessionEstablishmentStage::kUnknown);
onSetupFailure->mCall(onSetupFailure->mContext, failureInfo);
}
return;
}
}

#if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
session->UpdateAttemptCount(attemptCount);
if (onRetry)
{
session->AddRetryHandler(onRetry);
}
#endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES

if (onFailure != nullptr)
{
session->Connect(onConnection, onFailure, addr, transportPayloadCapability);
}

if (onSetupFailure != nullptr)
{
session->Connect(onConnection, onSetupFailure, transportPayloadCapability);
}
}

void CASESessionManager::ReleaseSessionsForFabric(FabricIndex fabricIndex)
{
mConfig.sessionSetupPool->ReleaseAllSessionSetupsForFabric(fabricIndex);
Expand Down
15 changes: 14 additions & 1 deletion src/app/CASESessionManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ class CASESessionManager : public OperationalSessionReleaseDelegate, public Sess
Callback::Callback<OnDeviceConnectionFailure> * onFailure,
#if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
uint8_t attemptCount = 1, Callback::Callback<OnDeviceConnectionRetry> * onRetry = nullptr,
#endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
TransportPayloadCapability transportPayloadCapability = TransportPayloadCapability::kMRPPayload);
void FindOrEstablishSession(const ScopedNodeId & peerId, Callback::Callback<OnDeviceConnected> * onConnection,
Callback::Callback<OnDeviceConnectionFailure> * onFailure, Transport::PeerAddress & addr,
#if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
uint8_t attemptCount = 1, Callback::Callback<OnDeviceConnectionRetry> * onRetry = nullptr,
#endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
TransportPayloadCapability transportPayloadCapability = TransportPayloadCapability::kMRPPayload);

Expand Down Expand Up @@ -178,7 +184,14 @@ class CASESessionManager : public OperationalSessionReleaseDelegate, public Sess
uint8_t attemptCount, Callback::Callback<OnDeviceConnectionRetry> * onRetry,
#endif
TransportPayloadCapability transportPayloadCapability);

void FindOrEstablishSessionHelper(const ScopedNodeId & peerId, Callback::Callback<OnDeviceConnected> * onConnection,
Callback::Callback<OnDeviceConnectionFailure> * onFailure,
Callback::Callback<OperationalSessionSetup::OnSetupFailure> * onSetupFailure,
Transport::PeerAddress & addr,
#if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
uint8_t attemptCount, Callback::Callback<OnDeviceConnectionRetry> * onRetry,
#endif
TransportPayloadCapability transportPayloadCapability);
CASESessionManagerConfig mConfig;
};

Expand Down
Loading
Loading