diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index effbef0ca439fd..3acc9e4cdf4fe2 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -196,21 +196,6 @@ jobs: build \ --copy-artifacts-to objdir-clone \ " - - name: Run Tests - run: | - ./scripts/run_in_build_env.sh \ - "./scripts/tests/run_test_suite.py \ - --chip-tool ./out/linux-x64-chip-tool${CHIP_TOOL_VARIANT}-${BUILD_VARIANT}/chip-tool \ - run \ - --iterations 1 \ - --test-timeout-seconds 120 \ - --all-clusters-app ./out/linux-x64-all-clusters-${BUILD_VARIANT}/chip-all-clusters-app \ - --lock-app ./out/linux-x64-lock-${BUILD_VARIANT}/chip-lock-app \ - --ota-provider-app ./out/linux-x64-ota-provider-${BUILD_VARIANT}/chip-ota-provider-app \ - --ota-requestor-app ./out/linux-x64-ota-requestor-${BUILD_VARIANT}/chip-ota-requestor-app \ - --tv-app ./out/linux-x64-tv-app-${BUILD_VARIANT}/chip-tv-app \ - --bridge-app ./out/linux-x64-bridge-${BUILD_VARIANT}/chip-bridge-app \ - " - name: Run Tests using the python parser sending commands to chip-tool # https://github.com/project-chip/connectedhomeip/issues/27673 @@ -335,23 +320,6 @@ jobs: build \ --copy-artifacts-to objdir-clone \ " - - name: Run Tests - if: matrix.build_variant != 'no-ble-tsan-clang' - run: | - ./scripts/run_in_build_env.sh \ - "./scripts/tests/run_test_suite.py \ - --chip-tool ./out/darwin-x64-chip-tool${CHIP_TOOL_VARIANT}-${BUILD_VARIANT}/chip-tool \ - --target-skip-glob '{Test_TC_DGTHREAD_2_1,Test_TC_DGTHREAD_2_2,Test_TC_DGTHREAD_2_3,Test_TC_DGTHREAD_2_4}' \ - run \ - --iterations 1 \ - --test-timeout-seconds 120 \ - --all-clusters-app ./out/darwin-x64-all-clusters-${BUILD_VARIANT}/chip-all-clusters-app \ - --lock-app ./out/darwin-x64-lock-${BUILD_VARIANT}/chip-lock-app \ - --ota-provider-app ./out/darwin-x64-ota-provider-${BUILD_VARIANT}/chip-ota-provider-app \ - --ota-requestor-app ./out/darwin-x64-ota-requestor-${BUILD_VARIANT}/chip-ota-requestor-app \ - --tv-app ./out/darwin-x64-tv-app-${BUILD_VARIANT}/chip-tv-app \ - --bridge-app ./out/darwin-x64-bridge-${BUILD_VARIANT}/chip-bridge-app \ - " - name: Run Tests using the python parser sending commands to chip-tool # https://github.com/project-chip/connectedhomeip/issues/27673 diff --git a/examples/chip-tool/BUILD.gn b/examples/chip-tool/BUILD.gn index f52f3a463196b7..829b21f3f0b5cb 100644 --- a/examples/chip-tool/BUILD.gn +++ b/examples/chip-tool/BUILD.gn @@ -38,7 +38,6 @@ config("config") { "CONFIG_USE_LOCAL_STORAGE=${config_use_local_storage}", "CONFIG_USE_SEPARATE_EVENTLOOP=${config_use_separate_eventloop}", "CONFIG_USE_INTERACTIVE_MODE=${config_use_interactive_mode}", - "CONFIG_ENABLE_YAML_TESTS=${config_enable_yaml_tests}", ] cflags = [ "-Wconversion" ] @@ -46,8 +45,6 @@ config("config") { static_library("chip-tool-utils") { sources = [ - "${chip_root}/src/app/tests/suites/include/ConstraintsChecker.h", - "${chip_root}/src/app/tests/suites/include/ValueChecker.h", "${chip_root}/src/controller/ExamplePersistentStorage.cpp", "${chip_root}/src/controller/ExamplePersistentStorage.h", "${chip_root}/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp", @@ -92,10 +89,6 @@ static_library("chip-tool-utils") { ] } - if (config_enable_yaml_tests) { - sources += [ "commands/tests/TestCommand.cpp" ] - } - if (chip_device_platform == "darwin") { sources += [ "commands/common/DeviceScanner.cpp" ] } @@ -103,13 +96,7 @@ static_library("chip-tool-utils") { public_deps = [ "${chip_root}/examples/common/tracing:commandline", "${chip_root}/src/app/server", - "${chip_root}/src/app/tests/suites/commands/commissioner", - "${chip_root}/src/app/tests/suites/commands/delay", - "${chip_root}/src/app/tests/suites/commands/discovery", "${chip_root}/src/app/tests/suites/commands/interaction_model", - "${chip_root}/src/app/tests/suites/commands/log", - "${chip_root}/src/app/tests/suites/commands/system", - "${chip_root}/src/app/tests/suites/pics", "${chip_root}/src/controller/data_model", "${chip_root}/src/credentials:file_attestation_trust_store", "${chip_root}/src/lib", diff --git a/examples/chip-tool/commands/tests/TestCommand.cpp b/examples/chip-tool/commands/tests/TestCommand.cpp deleted file mode 100644 index 6b1f081bd92536..00000000000000 --- a/examples/chip-tool/commands/tests/TestCommand.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2021 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 "TestCommand.h" - -CHIP_ERROR TestCommand::RunCommand() -{ - if (mPICSFilePath.HasValue()) - { - PICS.SetValue(PICSBooleanReader::Read(mPICSFilePath.Value())); - } - - NextTest(); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR TestCommand::WaitForCommissionee(const char * identity, - const chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type & value) -{ - chip::FabricIndex fabricIndex = GetCommissioner(identity).GetFabricIndex(); - ReturnErrorCodeIf(fabricIndex == chip::kUndefinedFabricIndex, CHIP_ERROR_INCORRECT_STATE); - - // - // There's a chance the commissionee may have rebooted before this call here as part of a test flow - // or is just starting out fresh outright. Let's make sure we're not re-using any cached CASE sessions - // that will now be stale and mismatched with the peer, causing subsequent interactions to fail. - // - if (value.expireExistingSession.ValueOr(true)) - { - GetCommissioner(identity).SessionMgr()->ExpireAllSessions(chip::ScopedNodeId(value.nodeId, fabricIndex)); - } - - SetIdentity(identity); - return GetCommissioner(identity).GetConnectedDevice(value.nodeId, &mOnDeviceConnectedCallback, - &mOnDeviceConnectionFailureCallback); -} - -void TestCommand::OnDeviceConnectedFn(void * context, chip::Messaging::ExchangeManager & exchangeMgr, - const chip::SessionHandle & sessionHandle) -{ - ChipLogProgress(chipTool, " **** Test Setup: Device Connected\n"); - auto * command = static_cast(context); - VerifyOrReturn(command != nullptr, ChipLogError(chipTool, "Device connected, but cannot run the test, as the context is null")); - command->mDevices[command->GetIdentity()] = std::make_unique(&exchangeMgr, sessionHandle); - - LogErrorOnFailure(command->ContinueOnChipMainThread(CHIP_NO_ERROR)); -} - -void TestCommand::OnDeviceConnectionFailureFn(void * context, const chip::ScopedNodeId & peerId, CHIP_ERROR error) -{ - ChipLogProgress(chipTool, " **** Test Setup: Device Connection Failure [deviceId=%" PRIu64 ". Error %" CHIP_ERROR_FORMAT "\n]", - peerId.GetNodeId(), error.Format()); - auto * command = static_cast(context); - VerifyOrReturn(command != nullptr, ChipLogError(chipTool, "Test command context is null")); - - LogErrorOnFailure(command->ContinueOnChipMainThread(error)); -} - -void TestCommand::ExitAsync(intptr_t context) -{ - auto testCommand = reinterpret_cast(context); - testCommand->InteractionModel::Shutdown(); - testCommand->SetCommandExitStatus(CHIP_ERROR_INTERNAL); -} - -void TestCommand::Exit(std::string message, CHIP_ERROR err) -{ - bool shouldContinueOnFailure = mContinueOnFailure.HasValue() && mContinueOnFailure.Value(); - if (shouldContinueOnFailure) - { - if (CHIP_NO_ERROR != err) - { - ChipLogError(chipTool, " ***** Step Failure: %s\n", message.c_str()); - mErrorMessages.push_back(message); - ContinueOnChipMainThread(CHIP_NO_ERROR); - return; - } - - // If the test runner has been configured to not stop after a test failure, exit can be called with a success but it could - // be pending errors from previous steps. - uint32_t errorsCount = static_cast(mErrorMessages.size()); - if (errorsCount) - { - ChipLogError(chipTool, "Error: %u error(s) has been encountered:", errorsCount); - - for (uint32_t i = 0; i < errorsCount; i++) - { - ChipLogError(chipTool, "\t%u. %s", (i + 1), mErrorMessages.at(i).c_str()); - } - err = CHIP_ERROR_INTERNAL; - } - } - - mContinueProcessing = false; - - LogEnd(message, err); - - if (CHIP_NO_ERROR == err) - { - InteractionModel::Shutdown(); - SetCommandExitStatus(err); - } - else - { - chip::DeviceLayer::PlatformMgr().ScheduleWork(ExitAsync, reinterpret_cast(this)); - } -} - -CHIP_ERROR TestCommand::ContinueOnChipMainThread(CHIP_ERROR err) -{ - if (mContinueProcessing == false) - { - return CHIP_NO_ERROR; - } - - if (CHIP_NO_ERROR == err) - { - chip::app::Clusters::DelayCommands::Commands::WaitForMs::Type value; - value.ms = 0; - return WaitForMs(GetIdentity().c_str(), value); - } - - Exit(chip::ErrorStr(err), err); - return CHIP_NO_ERROR; -} diff --git a/examples/chip-tool/commands/tests/TestCommand.h b/examples/chip-tool/commands/tests/TestCommand.h deleted file mode 100644 index b1de8a20517024..00000000000000 --- a/examples/chip-tool/commands/tests/TestCommand.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2021 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 -#include -#include -#include -#include -#include -#include -#include -#include -#include - -constexpr uint16_t kTimeoutInSeconds = 90; - -class TestCommand : public TestRunner, - public CHIPCommand, - public ValueChecker, - public ConstraintsChecker, - public PICSChecker, - public LogCommands, - public CommissionerCommands, - public DiscoveryCommands, - public SystemCommands, - public DelayCommands, - public InteractionModel -{ -public: - TestCommand(const char * commandName, uint16_t testsCount, CredentialIssuerCommands * credsIssuerConfig) : - TestRunner(commandName, testsCount), CHIPCommand(commandName, credsIssuerConfig), - mOnDeviceConnectedCallback(OnDeviceConnectedFn, this), mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureFn, this) - { - AddArgument("continueOnFailure", 0, 1, &mContinueOnFailure, - "Boolean indicating if the test runner should continue execution if a test fails. Default to false."); - AddArgument("delayInMs", 0, UINT64_MAX, &mDelayInMs); - AddArgument("PICS", &mPICSFilePath); - } - - ~TestCommand(){}; - - /////////// CHIPCommand Interface ///////// - CHIP_ERROR RunCommand() override; - -protected: - /////////// DelayCommands Interface ///////// - CHIP_ERROR WaitForCommissionee(const char * identity, - const chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type & value) override; - void OnWaitForMs() override { NextTest(); }; - - /////////// Interaction Model Interface ///////// - chip::DeviceProxy * GetDevice(const char * identity) override { return mDevices[identity].get(); } - void OnResponse(const chip::app::StatusIB & status, chip::TLV::TLVReader * data) override{}; - - static void OnDeviceConnectedFn(void * context, chip::Messaging::ExchangeManager & exchangeMgr, - const chip::SessionHandle & sessionHandle); - static void OnDeviceConnectionFailureFn(void * context, const chip::ScopedNodeId & peerId, CHIP_ERROR error); - - CHIP_ERROR ContinueOnChipMainThread(CHIP_ERROR err) override; - - chip::Controller::DeviceCommissioner & GetCommissioner(const char * identity) override - { - return CHIPCommand::GetCommissioner(identity); - }; - - static void ExitAsync(intptr_t context); - void Exit(std::string message, CHIP_ERROR err = CHIP_ERROR_INTERNAL) override; - - chip::Callback::Callback mOnDeviceConnectedCallback; - chip::Callback::Callback mOnDeviceConnectionFailureCallback; - - bool IsUnsupported(const chip::app::StatusIB & status) - { - return status.mStatus == chip::Protocols::InteractionModel::Status::UnsupportedAttribute || - status.mStatus == chip::Protocols::InteractionModel::Status::UnsupportedCommand; - } - - chip::Optional mPICSFilePath; - chip::Optional mTimeout; - std::map> mDevices; - - // When set to false, prevents interaction model events from affecting the current test status. - // This flag exists because if an error happens while processing a response the allocated - // command client/sender (ReadClient/WriteClient/CommandSender) can not be deallocated - // as it still used by the stack afterward. So a task is scheduled to run to close the - // test suite as soon as possible, and pending events are ignored in between. - bool mContinueProcessing = true; - - // When set to true, the test runner continue to run after a test failure. - chip::Optional mContinueOnFailure; - std::vector mErrorMessages; -}; diff --git a/examples/chip-tool/main.cpp b/examples/chip-tool/main.cpp index 17bb7f13a57e80..a1eb4646a9fd98 100644 --- a/examples/chip-tool/main.cpp +++ b/examples/chip-tool/main.cpp @@ -30,7 +30,6 @@ #include "commands/storage/Commands.h" #include -#include // ================================================================================ // Main Code @@ -44,7 +43,6 @@ int main(int argc, char * argv[]) registerCommandsInteractive(commands, &credIssuerCommands); registerCommandsPayload(commands); registerCommandsPairing(commands, &credIssuerCommands); - registerCommandsTests(commands, &credIssuerCommands); registerCommandsGroup(commands, &credIssuerCommands); registerClusters(commands, &credIssuerCommands); registerCommandsSubscriptions(commands, &credIssuerCommands); diff --git a/examples/chip-tool/templates/tests/commands.zapt b/examples/chip-tool/templates/tests/commands.zapt deleted file mode 100644 index acafcaa626f3dc..00000000000000 --- a/examples/chip-tool/templates/tests/commands.zapt +++ /dev/null @@ -1,75 +0,0 @@ -{{> header}} - -#pragma once - -#if CONFIG_ENABLE_YAML_TESTS - -#include -#include -#include -#include -#include - -#include // For INFINITY - -class TestList : public Command -{ -public: - TestList() : Command("list") {}; - CHIP_ERROR Run() override - { - {{#chip_tests "../../../../src/app/tests/suites/ciTests.json" includeAllClusters=true}}printf("{{filename}}\n");{{/chip_tests}} - - return CHIP_NO_ERROR; - } -}; - -class ManualTestList : public Command -{ -public: - ManualTestList() : Command("list-manual") {}; - CHIP_ERROR Run() override - { - {{#chip_tests "../../../../src/app/tests/suites/manualTests.json" includeAllClusters=true}}printf("{{filename}}\n");{{/chip_tests}} - - return CHIP_NO_ERROR; - } -}; - -class PythonRunnerOnlyTestList : public Command -{ -public: - PythonRunnerOnlyTestList() : Command("list-python-runner-only") {}; - CHIP_ERROR Run() override - { - {{#chip_tests "../../../../src/app/tests/suites/pythonRunnerOnlyTests.json" includeAllClusters=true}}printf("{{filename}}\n");{{/chip_tests}} - - return CHIP_NO_ERROR; - } -}; - -{{>test_cluster tests="../../../../src/app/tests/suites/ciTests.json" credsIssuerConfigArg=true needsWaitDuration=true}} -{{>test_cluster tests="../../../../src/app/tests/suites/manualTests.json" credsIssuerConfigArg=true needsWaitDuration=true}} - -#endif // CONFIG_ENABLE_YAML_TESTS - -void registerCommandsTests(Commands & commands, CredentialIssuerCommands * credsIssuerConfig) -{ - const char * clusterName = "Tests"; - - commands_list clusterCommands = { -#if CONFIG_ENABLE_YAML_TESTS - make_unique(), - make_unique(), - make_unique(), - {{#chip_tests "../../../../src/app/tests/suites/ciTests.json" includeAllClusters=true}} - make_unique<{{filename}}Suite>(credsIssuerConfig), - {{/chip_tests}} - {{#chip_tests "../../../../src/app/tests/suites/manualTests.json" includeAllClusters=true}} - make_unique<{{filename}}Suite>(credsIssuerConfig), - {{/chip_tests}} -#endif // CONFIG_ENABLE_YAML_TESTS - }; - - commands.RegisterCommandSet(clusterName, clusterCommands, "Commands for running YAML tests."); -} diff --git a/examples/chip-tool/templates/tests/templates.json b/examples/chip-tool/templates/tests/templates.json deleted file mode 100644 index 93505fe7a1fce4..00000000000000 --- a/examples/chip-tool/templates/tests/templates.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "name": "CHIP Tool Tests templates", - "version": "chip-v1", - "helpers": [ - "partials/helper.js", - "common/StringHelper.js", - "templates/app/helper.js", - "templates/chip/helper.js", - "common/ClusterTestGeneration.js", - "chip-tool/templates/helper.js", - "chip-tool/templates/tests/helper.js" - ], - "resources": { - "pics-metafile": "../../../../src/app/tests/suites/certification/PICS.yaml", - "certification-metadir": "../../../../src/app/tests/suites/certification", - "test-metadir": "../../../../src/app/tests/suites" - }, - "override": "../../../../src/app/zap-templates/common/override.js", - "partials": [ - { - "name": "header", - "path": "../../../../src/app/zap-templates/partials/header.zapt" - }, - { - "name": "test_cluster", - "path": "partials/test_cluster.zapt" - }, - { - "name": "test_step", - "path": "partials/test_step.zapt" - }, - { - "name": "test_step_response", - "path": "partials/test_step_response.zapt" - }, - { - "name": "maybeCheckExpectedValue", - "path": "partials/checks/maybeCheckExpectedValue.zapt" - }, - { - "name": "maybeCheckExpectedConstraints", - "path": "partials/checks/maybeCheckExpectedConstraints.zapt" - }, - { - "name": "setupSaveAs", - "path": "partials/saveAs/setupSaveAs.zapt" - }, - { - "name": "teardownSaveAs", - "path": "partials/saveAs/teardownSaveAs.zapt" - }, - { - "name": "maybeSaveAs", - "path": "partials/saveAs/maybeSaveAs.zapt" - }, - { - "name": "commandValue", - "path": "partials/command_value.zapt" - }, - { - "name": "valueEquals", - "path": "partials/value_equals.zapt" - }, - { - "name": "octetStringValue", - "path": "partials/octet_string_value.zapt" - } - ], - "templates": [ - { - "path": "commands.zapt", - "name": "Tests Commands header", - "output": "test/Commands.h" - } - ] -} diff --git a/scripts/tools/zap_regen_all.py b/scripts/tools/zap_regen_all.py index 03a1ee12b20753..a274ea84597a15 100755 --- a/scripts/tools/zap_regen_all.py +++ b/scripts/tools/zap_regen_all.py @@ -338,7 +338,7 @@ def setupArgumentsParser(): description='Generate content from ZAP files') parser.add_argument('--type', action='append', choices=__TARGET_TYPES__.keys(), help='Choose which content type to generate (default: all)') - parser.add_argument('--tests', default='all', choices=['all', 'chip-tool', 'darwin-framework-tool', 'app1', 'app2'], + parser.add_argument('--tests', default='all', choices=['all', 'darwin-framework-tool', 'app1', 'app2'], help='When generating tests only target, Choose which tests to generate (default: all)') parser.add_argument('--dry-run', default=False, action='store_true', help="Don't do any generation, just log what targets would be generated (default: False)") @@ -439,10 +439,6 @@ def getCodegenTemplates(): def getTestsTemplatesTargets(test_target): zap_input = ZapInput.FromPropertiesJson('src/app/zap-templates/zcl/zcl.json') templates = { - 'chip-tool': { - 'template': 'examples/chip-tool/templates/tests/templates.json', - 'output_dir': 'zzz_generated/chip-tool/zap-generated' - }, 'darwin-framework-tool': { 'template': 'examples/darwin-framework-tool/templates/tests/templates.json', 'output_dir': 'zzz_generated/darwin-framework-tool/zap-generated' diff --git a/src/app/tests/suites/commands/commissioner/BUILD.gn b/src/app/tests/suites/commands/commissioner/BUILD.gn deleted file mode 100644 index 3f4c174a70fef5..00000000000000 --- a/src/app/tests/suites/commands/commissioner/BUILD.gn +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright (c) 2022 Project CHIP Authors -# -# 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. - -import("//build_overrides/build.gni") -import("//build_overrides/chip.gni") - -static_library("commissioner") { - output_name = "libCommissionerCommands" - - sources = [ - "CommissionerCommands.cpp", - "CommissionerCommands.h", - ] - - cflags = [ "-Wconversion" ] - - public_deps = [ - "${chip_root}/src/controller", - "${chip_root}/src/lib/support", - ] -} diff --git a/src/app/tests/suites/commands/commissioner/CommissionerCommands.cpp b/src/app/tests/suites/commands/commissioner/CommissionerCommands.cpp deleted file mode 100644 index d60c46d42ce5b0..00000000000000 --- a/src/app/tests/suites/commands/commissioner/CommissionerCommands.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2022 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 "CommissionerCommands.h" - -constexpr uint16_t kPayloadMaxSize = 64; - -CHIP_ERROR -CommissionerCommands::PairWithCode(const char * identity, - const chip::app::Clusters::CommissionerCommands::Commands::PairWithCode::Type & value) -{ - VerifyOrReturnError(value.payload.size() > 0 && value.payload.size() < kPayloadMaxSize, CHIP_ERROR_INVALID_ARGUMENT); - - GetCommissioner(identity).RegisterPairingDelegate(this); - - char code[kPayloadMaxSize]; - memset(code, '\0', sizeof(code)); - memcpy(code, value.payload.data(), value.payload.size()); - ChipLogError(chipTool, "Pairing Code is %s", code); - - // To reduce the scanning latency in some setups, and since the primary use for PairWithCode is to commission a device to - // another commissioner, assume that the commissionable device is available on the network. - auto discoveryType = chip::Controller::DiscoveryType::kDiscoveryNetworkOnly; - if (value.discoverOnce.ValueOr(false)) - { - discoveryType = chip::Controller::DiscoveryType::kDiscoveryNetworkOnlyWithoutPASEAutoRetry; - } - return GetCommissioner(identity).PairDevice(value.nodeId, code, discoveryType); -} - -CHIP_ERROR CommissionerCommands::Unpair(const char * identity, - const chip::app::Clusters::CommissionerCommands::Commands::Unpair::Type & value) -{ - return GetCommissioner(identity).UnpairDevice(value.nodeId); -} - -CHIP_ERROR CommissionerCommands::GetCommissionerNodeId( - const char * identity, const chip::app::Clusters::CommissionerCommands::Commands::GetCommissionerNodeId::Type & value) -{ - chip::GetCommissionerNodeIdResponse data; - data.nodeId = GetCommissioner(identity).GetNodeId(); - - chip::app::StatusIB status; - status.mStatus = chip::Protocols::InteractionModel::Status::Success; - - constexpr uint32_t kMaxDataLen = 128; - uint8_t * buffer = static_cast(chip::Platform::MemoryCalloc(sizeof(uint8_t), kMaxDataLen)); - if (buffer == nullptr) - { - ChipLogError(chipTool, "Can not allocate commissioner node id data: %s", chip::ErrorStr(CHIP_ERROR_NO_MEMORY)); - return CHIP_ERROR_NO_MEMORY; - } - - chip::TLV::TLVWriter writer; - writer.Init(buffer, kMaxDataLen); - CHIP_ERROR err = data.Encode(writer, chip::TLV::AnonymousTag()); - if (CHIP_NO_ERROR != err) - { - ChipLogError(chipTool, "Can not encode commissioner node id data: %s", chip::ErrorStr(err)); - return err; - } - - uint32_t dataLen = writer.GetLengthWritten(); - writer.Finalize(); - - chip::TLV::TLVReader reader; - reader.Init(buffer, dataLen); - reader.Next(); - - OnResponse(status, &reader); - - chip::Platform::MemoryFree(buffer); - - return CHIP_NO_ERROR; -} - -chip::app::StatusIB ConvertToStatusIB(CHIP_ERROR err) -{ - using chip::app::StatusIB; - using namespace chip; - using namespace chip::Protocols::InteractionModel; - using namespace chip::app::Clusters::OperationalCredentials; - - if (CHIP_ERROR_INVALID_PUBLIC_KEY == err) - { - return StatusIB(Status::Failure, to_underlying(NodeOperationalCertStatusEnum::kInvalidPublicKey)); - } - if (CHIP_ERROR_WRONG_NODE_ID == err) - { - return StatusIB(Status::Failure, to_underlying(NodeOperationalCertStatusEnum::kInvalidNodeOpId)); - } - if (CHIP_ERROR_UNSUPPORTED_CERT_FORMAT == err) - { - return StatusIB(Status::Failure, to_underlying(NodeOperationalCertStatusEnum::kInvalidNOC)); - } - if (CHIP_ERROR_FABRIC_EXISTS == err) - { - return StatusIB(Status::Failure, to_underlying(NodeOperationalCertStatusEnum::kFabricConflict)); - } - if (CHIP_ERROR_INVALID_FABRIC_INDEX == err) - { - return StatusIB(Status::Failure, to_underlying(NodeOperationalCertStatusEnum::kInvalidFabricIndex)); - } - - return StatusIB(err); -} - -void CommissionerCommands::OnStatusUpdate(DevicePairingDelegate::Status status) -{ - switch (status) - { - case DevicePairingDelegate::Status::SecurePairingSuccess: - ChipLogProgress(chipTool, "Secure Pairing Success"); - break; - case DevicePairingDelegate::Status::SecurePairingFailed: - ChipLogError(chipTool, "Secure Pairing Failed"); - OnResponse(ConvertToStatusIB(CHIP_ERROR_INCORRECT_STATE), nullptr); - break; - } -} - -void CommissionerCommands::OnPairingComplete(CHIP_ERROR err) -{ - if (CHIP_NO_ERROR != err) - { - ChipLogError(chipTool, "Pairing Complete Failure: %s", ErrorStr(err)); - OnResponse(ConvertToStatusIB(err), nullptr); - } -} - -void CommissionerCommands::OnPairingDeleted(CHIP_ERROR err) -{ - if (err != CHIP_NO_ERROR) - { - ChipLogError(chipTool, "Pairing Delete Failure: %s", ErrorStr(err)); - } - - OnResponse(ConvertToStatusIB(err), nullptr); -} - -void CommissionerCommands::OnCommissioningComplete(chip::NodeId nodeId, CHIP_ERROR err) -{ - if (err != CHIP_NO_ERROR) - { - ChipLogError(chipTool, "Commissioning Complete Failure: %s", ErrorStr(err)); - } - - OnResponse(ConvertToStatusIB(err), nullptr); -} diff --git a/src/app/tests/suites/commands/commissioner/CommissionerCommands.h b/src/app/tests/suites/commands/commissioner/CommissionerCommands.h deleted file mode 100644 index 9056f3a53947e3..00000000000000 --- a/src/app/tests/suites/commands/commissioner/CommissionerCommands.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2022 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 -#include - -#include - -class CommissionerCommands : public chip::Controller::DevicePairingDelegate -{ -public: - CommissionerCommands(){}; - ~CommissionerCommands() override{}; - - virtual void OnResponse(const chip::app::StatusIB & status, chip::TLV::TLVReader * data) = 0; - virtual CHIP_ERROR ContinueOnChipMainThread(CHIP_ERROR err) = 0; - virtual chip::Controller::DeviceCommissioner & GetCommissioner(const char * identity) = 0; - - CHIP_ERROR PairWithCode(const char * identity, - const chip::app::Clusters::CommissionerCommands::Commands::PairWithCode::Type & value); - CHIP_ERROR Unpair(const char * identity, const chip::app::Clusters::CommissionerCommands::Commands::Unpair::Type & value); - CHIP_ERROR - GetCommissionerNodeId(const char * identity, - const chip::app::Clusters::CommissionerCommands::Commands::GetCommissionerNodeId::Type & value); - - /////////// DevicePairingDelegate Interface ///////// - void OnStatusUpdate(chip::Controller::DevicePairingDelegate::Status status) override; - void OnPairingComplete(CHIP_ERROR error) override; - void OnPairingDeleted(CHIP_ERROR error) override; - void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR error) override; -};