Skip to content

Commit

Permalink
Add interactive command darwin framework tool (#19418)
Browse files Browse the repository at this point in the history
* Add Interactive command in darwin-framework-tool

* Generated code
  • Loading branch information
krypton36 authored Jun 13, 2022
1 parent 634519e commit e38e2a6
Show file tree
Hide file tree
Showing 12 changed files with 12,301 additions and 10,643 deletions.
13 changes: 12 additions & 1 deletion examples/darwin-framework-tool/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,19 @@ config("config") {
"${chip_root}/examples/chip-tool/commands/clusters/ComplexArgument.h",
]

defines = [ "CONFIG_ENABLE_YAML_TESTS=${config_enable_yaml_tests}" ]
defines = [
"CONFIG_ENABLE_YAML_TESTS=${config_enable_yaml_tests}",
"CONFIG_USE_INTERACTIVE_MODE=${config_use_interactive_mode}",
]

cflags = [
"-Wconversion",
"-fobjc-arc",
]

if (config_use_interactive_mode) {
libs = [ "readline" ]
}
}

executable("darwin-framework-tool") {
Expand All @@ -55,6 +62,10 @@ executable("darwin-framework-tool") {
"main.mm",
]

if (config_use_interactive_mode) {
sources += [ "commands/interactive/InteractiveCommands.mm" ]
}

if (config_enable_yaml_tests) {
sources += [ "${chip_root}/zzz_generated/darwin-framework-tool/zap-generated/cluster/CHIPTestClustersObjc.mm" ]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ class ModelCommand : public CHIPCommandBridge
AddArgument("endpoint-id", 0, UINT16_MAX, &mEndPointId);
}

void Shutdown() override;

void Cleanup() override { ModelCommand::Shutdown(); }

/////////// CHIPCommand Interface /////////
CHIP_ERROR RunCommand() override;
chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(10); }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,5 @@
}];
return CHIP_NO_ERROR;
}

void ModelCommand::Shutdown() { ResetArguments(); }
Original file line number Diff line number Diff line change
Expand Up @@ -132,24 +132,25 @@ class SubscribeAttribute : public ModelCommand {
params.keepPreviousSubscriptions
= mKeepSubscriptions.HasValue() ? [NSNumber numberWithBool:mKeepSubscriptions.Value()] : nil;
[device subscribeAttributeWithEndpointId:[NSNumber numberWithUnsignedShort:endpointId]
clusterId:[NSNumber numberWithUnsignedInteger:mClusterId]
attributeId:[NSNumber numberWithUnsignedInteger:mAttributeId]
minInterval:[NSNumber numberWithUnsignedInteger:mMinInterval]
maxInterval:[NSNumber numberWithUnsignedInteger:mMaxInterval]
params:params
clientQueue:callbackQueue
reportHandler:^(
NSArray<NSDictionary<NSString *, id> *> * _Nullable values, NSError * _Nullable error) {
if (values) {
for (id item in values) {
NSLog(@"Response Item: %@", [item description]);
}
}
if (error || !mWait) {
SetCommandExitStatus(error);
}
}
subscriptionEstablished:nil];
clusterId:[NSNumber numberWithUnsignedInteger:mClusterId]
attributeId:[NSNumber numberWithUnsignedInteger:mAttributeId]
minInterval:[NSNumber numberWithUnsignedInteger:mMinInterval]
maxInterval:[NSNumber numberWithUnsignedInteger:mMaxInterval]
params:params
clientQueue:callbackQueue
reportHandler:^(NSArray<NSDictionary<NSString *, id> *> * _Nullable values, NSError * _Nullable error) {
if (values) {
for (id item in values) {
NSLog(@"Response Item: %@", [item description]);
}
}
if (error || !mWait) {
SetCommandExitStatus(error);
}
}
subscriptionEstablished:^() {
mSubscriptionEstablished = YES;
}];

return CHIP_NO_ERROR;
}
Expand All @@ -162,10 +163,19 @@ class SubscribeAttribute : public ModelCommand {
protected:
chip::Optional<bool> mKeepSubscriptions;
chip::Optional<bool> mFabricFiltered;
bool mSubscriptionEstablished = NO;
uint16_t mMinInterval;
uint16_t mMaxInterval;
bool mWait;

void Shutdown() override
{
mSubscriptionEstablished = NO;
ModelCommand::Shutdown();
}

bool DeferInteractiveCleanup() override { return mSubscriptionEstablished; }

private:
chip::ClusterId mClusterId;
chip::AttributeId mAttributeId;
Expand Down Expand Up @@ -216,6 +226,7 @@ class SubscribeEvent : public ModelCommand {
}
}
subscriptionEstablished:^() {
mSubscriptionEstablished = YES;
}];

return CHIP_NO_ERROR;
Expand All @@ -229,6 +240,7 @@ class SubscribeEvent : public ModelCommand {
protected:
chip::Optional<bool> mKeepSubscriptions;
chip::Optional<chip::EventNumber> mEventNumber;
bool mSubscriptionEstablished = NO;
uint16_t mMinInterval;
uint16_t mMaxInterval;
bool mWait;
Expand Down
22 changes: 20 additions & 2 deletions examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ class CHIPCommandBridge : public Command
void SetCommandExitStatus(CHIP_ERROR status)
{
mCommandExitStatus = status;
ShutdownCommissioner();
StopWaiting();
}

Expand Down Expand Up @@ -76,6 +75,22 @@ class CHIPCommandBridge : public Command
// if failure).
void LogNSError(const char * logString, NSError * error);

// Clean up any resources allocated by the command. Some commands may hold
// on to resources after Shutdown(), but Cleanup() will guarantee those are
// cleaned up.
virtual void Cleanup() {}

// If true, skip calling Cleanup() when in interactive mode, so the command
// can keep doing work as needed. Cleanup() will be called when quitting
// interactive mode. This method will be called before Shutdown, so it can
// use member values that Shutdown will normally reset.
virtual bool DeferInteractiveCleanup() { return NO; }

// Execute any deferred cleanups. Used when exiting interactive mode.
void ExecuteDeferredCleanups();

static std::set<CHIPCommandBridge *> sDeferredCleanups;

private:
CHIP_ERROR InitializeCommissioner(std::string key, chip::FabricId fabricId,
const chip::Credentials::AttestationTrustStore * trustStore);
Expand All @@ -87,8 +102,11 @@ class CHIPCommandBridge : public Command
CHIP_ERROR StartWaiting(chip::System::Clock::Timeout seconds);
void StopWaiting();

CHIP_ERROR MaybeSetUpStack();
CHIP_ERROR MaybeTearDownStack();

// Our three controllers: alpha, beta, gamma.
std::map<std::string, CHIPDeviceController *> mControllers;
static std::map<std::string, CHIPDeviceController *> mControllers;

// The current controller; the one the current command should be using.
CHIPDeviceController * mCurrentController;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,36 @@

const uint16_t kListenPort = 5541;
static CHIPToolPersistentStorageDelegate * storage = nil;
std::set<CHIPCommandBridge *> CHIPCommandBridge::sDeferredCleanups;
std::map<std::string, CHIPDeviceController *> CHIPCommandBridge::mControllers;

CHIP_ERROR CHIPCommandBridge::Run()
{
ChipLogProgress(chipTool, "Running Command");
ReturnErrorOnFailure(MaybeSetUpStack());
SetIdentity(mCommissionerName.HasValue() ? mCommissionerName.Value() : kIdentityAlpha);
ReturnLogErrorOnFailure(RunCommand());
ReturnLogErrorOnFailure(StartWaiting(GetWaitDuration()));

bool deferCleanup = (IsInteractive() && DeferInteractiveCleanup());

Shutdown();

if (deferCleanup) {
sDeferredCleanups.insert(this);
} else {
Cleanup();
}
ReturnErrorOnFailure(MaybeTearDownStack());

return CHIP_NO_ERROR;
}

CHIP_ERROR CHIPCommandBridge::MaybeSetUpStack()
{
if (IsInteractive()) {
return CHIP_NO_ERROR;
}
NSData * ipk;
CHIPToolKeypair * nocSigner = [[CHIPToolKeypair alloc] init];
storage = [[CHIPToolPersistentStorageDelegate alloc] init];
Expand Down Expand Up @@ -76,15 +102,19 @@
mControllers[identities[i]] = controller;
}

// If no commissioner name passed in, default to alpha.
SetIdentity(mCommissionerName.HasValue() ? mCommissionerName.Value() : kIdentityAlpha);

ReturnLogErrorOnFailure(RunCommand());
ReturnLogErrorOnFailure(StartWaiting(GetWaitDuration()));

return CHIP_NO_ERROR;
}

CHIP_ERROR CHIPCommandBridge::MaybeTearDownStack()
{
CHIP_ERROR err;
if (IsInteractive()) {
return CHIP_NO_ERROR;
}
err = ShutdownCommissioner();
return err;
}

void CHIPCommandBridge::SetIdentity(const char * identity)
{
std::string name = std::string(identity);
Expand Down Expand Up @@ -116,15 +146,13 @@

CHIP_ERROR CHIPCommandBridge::StartWaiting(chip::System::Clock::Timeout duration)
{
chip::DeviceLayer::PlatformMgr().StartEventLoopTask();
auto waitingUntil = std::chrono::system_clock::now() + std::chrono::duration_cast<std::chrono::seconds>(duration);
{
std::unique_lock<std::mutex> lk(cvWaitingForResponseMutex);
if (!cvWaitingForResponse.wait_until(lk, waitingUntil, [this]() { return !this->mWaitingForResponse; })) {
mCommandExitStatus = CHIP_ERROR_TIMEOUT;
}
}
LogErrorOnFailure(chip::DeviceLayer::PlatformMgr().StopEventLoopTask());

return mCommandExitStatus;
}
Expand All @@ -133,7 +161,7 @@
{
{
std::lock_guard<std::mutex> lk(cvWaitingForResponseMutex);
mWaitingForResponse = false;
mWaitingForResponse = NO;
}
cvWaitingForResponse.notify_all();
}
Expand All @@ -156,3 +184,11 @@
ChipLogError(chipTool, "%s: %s", logString, chip::ErrorStr(err));
}
}

void CHIPCommandBridge::ExecuteDeferredCleanups()
{
for (auto * cmd : sDeferredCleanups) {
cmd->Cleanup();
}
sDeferredCleanups.clear();
}
37 changes: 37 additions & 0 deletions examples/darwin-framework-tool/commands/interactive/Commands.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* 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 "../common/CHIPCommandBridge.h"
#include <commands/common/Command.h>

#include "InteractiveCommands.h"

void registerCommandsInteractive(Commands & commands)
{
const char * clusterName = "interactive";

commands_list clusterCommands = {
#if CONFIG_USE_INTERACTIVE_MODE
make_unique<InteractiveStartCommand>(&commands),
#endif // CONFIG_USE_INTERACTIVE_MODE
};

commands.Register(clusterName, clusterCommands);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* 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 "../common/CHIPCommandBridge.h"
#include "commands/common/Commands.h"

#include "InteractiveCommands.h"

class Commands;

class InteractiveStartCommand : public CHIPCommandBridge
{
public:
InteractiveStartCommand(Commands * commandsHandler) : CHIPCommandBridge("start"), mHandler(commandsHandler) {}

CHIP_ERROR RunCommand() override;

chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(0); }

private:
bool ParseCommand(char * command);
Commands * mHandler = nullptr;
};
Loading

0 comments on commit e38e2a6

Please sign in to comment.