From e0c64e44145654620c3a3489cd4be248cfe5915d Mon Sep 17 00:00:00 2001 From: Yufeng Wang <44623591+yufengwangca@users.noreply.github.com> Date: Tue, 13 Oct 2020 06:20:30 -0700 Subject: [PATCH 01/40] Rename SecureSessionMgrCallback to SecureSessionMgrDelegate to align the delegate naming (#3204) --- examples/common/chip-app-server/Server.cpp | 2 +- examples/wifi-echo/server/esp32/main/EchoServer.cpp | 2 +- src/controller/CHIPDeviceController.h | 2 +- src/transport/SecureSessionMgr.h | 8 ++++---- src/transport/tests/TestSecureSessionMgr.cpp | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/common/chip-app-server/Server.cpp b/examples/common/chip-app-server/Server.cpp index 104091aef2cde2..014f39a0cd2513 100644 --- a/examples/common/chip-app-server/Server.cpp +++ b/examples/common/chip-app-server/Server.cpp @@ -59,7 +59,7 @@ SecureSessionMgrBase & SessionManager() namespace { -class ServerCallback : public SecureSessionMgrCallback +class ServerCallback : public SecureSessionMgrDelegate { public: void OnMessageReceived(const PacketHeader & header, Transport::PeerConnectionState * state, System::PacketBuffer * buffer, diff --git a/examples/wifi-echo/server/esp32/main/EchoServer.cpp b/examples/wifi-echo/server/esp32/main/EchoServer.cpp index 4a6dad511b138e..b470a569234caa 100644 --- a/examples/wifi-echo/server/esp32/main/EchoServer.cpp +++ b/examples/wifi-echo/server/esp32/main/EchoServer.cpp @@ -120,7 +120,7 @@ static size_t odc(const uint8_t * bytes, size_t bytes_len, char * out, size_t ou return required; } -class EchoServerCallback : public SecureSessionMgrCallback +class EchoServerCallback : public SecureSessionMgrDelegate { public: void OnMessageReceived(const PacketHeader & header, Transport::PeerConnectionState * state, System::PacketBuffer * buffer, diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index 0b09e3aa7f709f..e2510a5ede7055 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -95,7 +95,7 @@ class DLL_EXPORT DevicePairingDelegate virtual void OnPairingDeleted(CHIP_ERROR error) {} }; -class DLL_EXPORT ChipDeviceController : public SecureSessionMgrCallback, public RendezvousSessionDelegate +class DLL_EXPORT ChipDeviceController : public SecureSessionMgrDelegate, public RendezvousSessionDelegate { friend class ChipDeviceControllerCallback; diff --git a/src/transport/SecureSessionMgr.h b/src/transport/SecureSessionMgr.h index 173b70cb6f51b1..2cc94a84aa21dd 100644 --- a/src/transport/SecureSessionMgr.h +++ b/src/transport/SecureSessionMgr.h @@ -50,7 +50,7 @@ class SecureSessionMgrBase; * is interested in receiving these callbacks, they can specialize this class and handle * each trigger in their implementation of this class. */ -class DLL_EXPORT SecureSessionMgrCallback : public ReferenceCounted +class DLL_EXPORT SecureSessionMgrDelegate : public ReferenceCounted { public: /** @@ -86,7 +86,7 @@ class DLL_EXPORT SecureSessionMgrCallback : public ReferenceCounted @@ -112,7 +112,7 @@ class DLL_EXPORT SecureSessionMgrBase : public ReferenceCounted mPeerConnections; // < Active connections to other peers State mState; // < Initialization state of the object - SecureSessionMgrCallback * mCB = nullptr; + SecureSessionMgrDelegate * mCB = nullptr; /** Schedules a new oneshot timer for checking connection expiry. */ void ScheduleExpiryTimer(); diff --git a/src/transport/tests/TestSecureSessionMgr.cpp b/src/transport/tests/TestSecureSessionMgr.cpp index 4a0f60cd927e0f..d5ccd3838c8c13 100644 --- a/src/transport/tests/TestSecureSessionMgr.cpp +++ b/src/transport/tests/TestSecureSessionMgr.cpp @@ -63,7 +63,7 @@ class LoopbackTransport : public Transport::Base bool CanSendToPeer(const PeerAddress & address) override { return true; } }; -class TestSessMgrCallback : public SecureSessionMgrCallback +class TestSessMgrCallback : public SecureSessionMgrDelegate { public: void OnMessageReceived(const PacketHeader & header, PeerConnectionState * state, System::PacketBuffer * msgBuf, From 6b140c41efeebc86df66baff98e8d9f480f28cd0 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Tue, 13 Oct 2020 16:22:28 +0200 Subject: [PATCH 02/40] ChipTool: Add cluster name to the command line parameters (#3198) --- examples/chip-tool/README.md | 41 ++- .../chip-tool/commands/common/Command.cpp | 8 +- .../chip-tool/commands/common/Commands.cpp | 276 +++++++++--------- examples/chip-tool/commands/common/Commands.h | 16 +- .../commands/common/NetworkCommand.h | 4 +- examples/chip-tool/commands/echo/Commands.h | 6 +- examples/lighting-app/efr32/README.md | 2 +- examples/lock-app/efr32/README.md | 2 +- .../linux-cirque/test-on-off-cluster.py | 4 +- 9 files changed, 194 insertions(+), 165 deletions(-) diff --git a/examples/chip-tool/README.md b/examples/chip-tool/README.md index b8db605388f86a..bb4da89f60c289 100644 --- a/examples/chip-tool/README.md +++ b/examples/chip-tool/README.md @@ -36,14 +36,14 @@ pass it the discriminator and pairing code of the remote device. The command below uses the default values hard-coded into the debug versions of the ESP32 wifi-echo app: - $ chip-tool echo-ble 3840 12345678 + $ chip-tool echo ble 3840 12345678 ### Ping a device over IP To start the Client in echo mode, run the built executable and pass it the IP address and port of the server to talk to, as well as the command "echo". - $ chip-tool 192.168.0.30 8000 echo + $ chip-tool echo ip 192.168.0.30 8000 If valid values are supplied, it will begin to periodically send messages to the server address provided. @@ -55,12 +55,39 @@ Stop the Client at any time with `Ctrl + C`. ## Using the Client to Send CHIP Commands -To use the Client to send a CHIP comands, run the built executable and pass it -the IP address and port of the server to talk to, the name of the command to -send, as well as an enpoint id. Right now the "off", "on", and "toggle" commands -are supported, from the On/Off cluster. The endpoint id must be between 1 +To use the Client to send a CHIP commands, run the built executable and pass it +the target cluster name, the target command name, an endpoint id as well as the +IP address and port of the server to talk to. The endpoint id must be between 1 and 240. - $ chip-tool 192.168.0.30 8000 on 1 + $ chip-tool onoff on 1 192.168.0.30 11095 The client will send a single command packet and then exit. + +### How to get the list of supported clusters + +To get the list of supported clusters, run the built executable without any +arguments. + + $ chip-tool + +### How to get the list of supported commands for a specific cluster + +To get the list of commands for a specific cluster, run the built executable +with the target cluster name. + + $ chip-tool onoff + +### How to get the list of supported attributes for a specific cluster + +To the the list of attributes for a specific cluster, run the built executable +with the target cluster name and the `read` command name. + + $ chip-tool onoff read + +### How to get the list of parameters for a command + +To get the list of parameters for a specific command, run the built executable +with the target cluster name and the target command name + + $ chip-tool onoff on diff --git a/examples/chip-tool/commands/common/Command.cpp b/examples/chip-tool/commands/common/Command.cpp index 9837652eff1e87..98c44c21d581da 100644 --- a/examples/chip-tool/commands/common/Command.cpp +++ b/examples/chip-tool/commands/common/Command.cpp @@ -128,7 +128,7 @@ size_t Command::AddArgument(const char * name, const char * value) arg.name = name; arg.value = const_cast(reinterpret_cast(value)); - mArgs.push_back(arg); + mArgs.emplace(mArgs.begin(), arg); return mArgs.size(); } @@ -139,7 +139,7 @@ size_t Command::AddArgument(const char * name, char ** value) arg.name = name; arg.value = reinterpret_cast(value); - mArgs.push_back(arg); + mArgs.emplace(mArgs.begin(), arg); return mArgs.size(); } @@ -150,7 +150,7 @@ size_t Command::AddArgument(const char * name, AddressWithInterface * out) arg.name = name; arg.value = reinterpret_cast(out); - mArgs.push_back(arg); + mArgs.emplace(mArgs.begin(), arg); return mArgs.size(); } @@ -163,7 +163,7 @@ size_t Command::AddArgument(const char * name, int64_t min, int64_t max, void * arg.min = min; arg.max = max; - mArgs.push_back(arg); + mArgs.emplace(mArgs.begin(), arg); return mArgs.size(); } diff --git a/examples/chip-tool/commands/common/Commands.cpp b/examples/chip-tool/commands/common/Commands.cpp index b5aff8b0733ed6..82b13b56636120 100644 --- a/examples/chip-tool/commands/common/Commands.cpp +++ b/examples/chip-tool/commands/common/Commands.cpp @@ -19,13 +19,15 @@ #include "Commands.h" #include "Command.h" + +#include #include void Commands::Register(const char * clusterName, commands_list commandsList) { for (auto & command : commandsList) { - clusters[clusterName].push_back(std::move(command)); + mClusters[clusterName].push_back(std::move(command)); } } @@ -49,196 +51,192 @@ int Commands::Run(NodeId localId, NodeId remoteId, int argc, char ** argv) return (err == CHIP_NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE; } -CHIP_ERROR Commands::RunCommand(ChipDeviceController & dc, NodeId remoteId, int argc, char * argv[]) +CHIP_ERROR Commands::RunCommand(ChipDeviceController & dc, NodeId remoteId, int argc, char ** argv) { CHIP_ERROR err = CHIP_NO_ERROR; + std::map::iterator cluster; + Command * command = nullptr; - VerifyOrExit(argc > 1, err = CHIP_ERROR_INVALID_ARGUMENT); + if (argc <= 1) + { + ChipLogError(chipTool, "Missing cluster name"); + ShowClusters(argv[0]); + ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT); + } - for (auto & cluster : clusters) + cluster = GetCluster(argv[1]); + if (cluster == mClusters.end()) { - for (auto & command : cluster.second) - { - if (strcmp(command->GetName(), argv[1]) == 0) - { - // If the command is a read command, ensure the target attribute value matches with the last argument - if (strcmp(command->GetName(), "read") == 0 && strcmp(command->GetAttribute(), argv[argc - 1]) != 0) - { - continue; - } + ChipLogError(chipTool, "Unknown cluster: %s", argv[1]); + ShowClusters(argv[0]); + ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT); + } - VerifyOrExit(command->InitArguments(argc - 2, &argv[2]), err = CHIP_ERROR_INVALID_ARGUMENT); + if (argc <= 2) + { + ChipLogError(chipTool, "Missing command name"); + ShowCluster(argv[0], argv[1], cluster->second); + ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT); + } - err = command->Run(&dc, remoteId); - SuccessOrExit(err); + if (strcmp(argv[2], "read") != 0) + { + command = GetCommand(cluster->second, argv[2]); + if (command == nullptr) + { + ChipLogError(chipTool, "Unknown command: %s", argv[2]); + ShowCluster(argv[0], argv[1], cluster->second); + ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT); + } + } + else + { + if (argc <= 3) + { + ChipLogError(chipTool, "Missing attribute name"); + ShowClusterAttributes(argv[0], argv[1], cluster->second); + ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT); + } - return err; - } + command = GetReadCommand(cluster->second, argv[2], argv[3]); + if (command == nullptr) + { + ChipLogError(chipTool, "Unknown attribute: %s", argv[3]); + ShowClusterAttributes(argv[0], argv[1], cluster->second); + ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT); } } - // No command found. - ChipLogError(chipTool, "Unknown command: %s", argv[1]); - Commands::ShowUsage(argv[0]); - return CHIP_ERROR_NOT_IMPLEMENTED; + if (!command->InitArguments(argc - 3, &argv[3])) + { + ShowCommand(argv[0], argv[1], command); + ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT); + } -exit: + err = command->Run(&dc, remoteId); if (err != CHIP_NO_ERROR) { ChipLogError(chipTool, "Run command failure: %s", chip::ErrorStr(err)); - Commands::ShowUsage(argv[0]); + ExitNow(); } +exit: return err; } -void Commands::ShowUsage(const char * executable) +std::map::iterator Commands::GetCluster(std::string clusterName) { - fprintf(stderr, "Usage:\n"); - fprintf(stderr, " %s command [params]\n\n", executable); - fprintf(stderr, " Supported commands and their parameters:\n"); - fprintf(stderr, "\n"); - fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); - fprintf(stderr, " | Misc. Commands: |\n"); - fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); - PrintMiscCommands(); - fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); - fprintf(stderr, "\n"); - fprintf(stderr, "\n"); - fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); - fprintf(stderr, " | Clusters: |\n"); - fprintf(stderr, " | |\n"); - fprintf(stderr, " | Usage: |\n"); - fprintf(stderr, " | command_name remote-ip remote-port endpoint-id [param1 param2 ...] |\n"); - fprintf(stderr, " | |\n"); - fprintf(stderr, " | Available command names and command specific parameters: |\n"); - fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); - PrintClustersCommands(); - fprintf(stderr, "\n"); - fprintf(stderr, "\n"); - fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); - fprintf(stderr, " | Read Attributes: |\n"); - fprintf(stderr, " | |\n"); - fprintf(stderr, " | Usage: |\n"); - fprintf(stderr, " | read remote-ip remote-port endpoint-id attribute-name |\n"); - fprintf(stderr, " | |\n"); - fprintf(stderr, " | Available attribute names: |\n"); - fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); - PrintClustersAttributes(); + for (auto & cluster : mClusters) + { + std::string key(cluster.first); + std::transform(key.begin(), key.end(), key.begin(), ::tolower); + if (key.compare(clusterName) == 0) + { + return mClusters.find(cluster.first); + } + } + + return mClusters.end(); } -void Commands::PrintMiscCommands() +Command * Commands::GetCommand(CommandsVector & commands, std::string commandName) { - for (auto & cluster : clusters) + for (auto & command : commands) { - if (cluster.first[0] == '\0') + if (commandName.compare(command->GetName()) == 0) { - for (auto & command : cluster.second) - { - std::string arguments = ""; - arguments += command->GetName(); - - size_t argumentsCount = command->GetArgumentsCount(); - for (size_t j = 0; j < argumentsCount; j++) - { - arguments += " "; - arguments += command->GetArgumentName(j); - } - - fprintf(stderr, " | %-84s|\n", arguments.c_str()); - } + return command.get(); } } + + return nullptr; } -void PrintClusterHeader(const char * name) +Command * Commands::GetReadCommand(CommandsVector & commands, std::string commandName, std::string attributeName) { - fprintf(stderr, " | * Cluster: %-73s|\n", name); - fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); + for (auto & command : commands) + { + if (commandName.compare(command->GetName()) == 0 && attributeName.compare(command->GetAttribute()) == 0) + { + return command.get(); + } + } + + return nullptr; } -void PrintClusterFooter() +void Commands::ShowClusters(std::string executable) { - fprintf(stderr, " | %-84s|\n", ""); + fprintf(stderr, "Usage:\n"); + fprintf(stderr, " %s cluster_name command_name [param1 param2 ...]\n", executable.c_str()); + fprintf(stderr, "\n"); + fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); + fprintf(stderr, " | Clusters: |\n"); + fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); + for (auto & cluster : mClusters) + { + fprintf(stderr, " | * %-82s|\n", cluster.first.c_str()); + } fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); } -void Commands::PrintClustersCommands() +void Commands::ShowCluster(std::string executable, std::string clusterName, CommandsVector & commands) { - for (auto & cluster : clusters) + fprintf(stderr, "Usage:\n"); + fprintf(stderr, " %s %s command_name [param1 param2 ...]\n", executable.c_str(), clusterName.c_str()); + fprintf(stderr, "\n"); + fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); + fprintf(stderr, " | Commands: |\n"); + fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); + bool readCommand = false; + for (auto & command : commands) { - bool hasCommands = false; - - if (cluster.first[0] != '\0') + if (strcmp(command->GetName(), "read") == 0) { - for (auto & command : cluster.second) + if (readCommand == false) { - if (strcmp("read", command->GetName()) != 0) - { - if (!hasCommands) - { - PrintClusterHeader(cluster.first); - hasCommands = true; - } - - std::string arguments = ""; - arguments += command->GetName(); - - size_t argumentsCount = command->GetArgumentsCount(); - - // Skip the first 3 arguments since those are the common arguments for ModelCommands. - if (argumentsCount > 3) - { - arguments += " ["; - for (size_t i = 3; i < argumentsCount; i++) - { - if (i != 3) - { - arguments += " "; - } - arguments += command->GetArgumentName(i); - } - arguments += "]"; - } - - fprintf(stderr, " | %-84s|\n", arguments.c_str()); - } + fprintf(stderr, " | * %-82s|\n", command->GetName()); + readCommand = true; } } - - if (hasCommands) + else { - PrintClusterFooter(); + fprintf(stderr, " | * %-82s|\n", command->GetName()); } } + fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); } -void Commands::PrintClustersAttributes() +void Commands::ShowClusterAttributes(std::string executable, std::string clusterName, CommandsVector & commands) { - for (auto & cluster : clusters) + fprintf(stderr, "Usage:\n"); + fprintf(stderr, " %s %s read attribute-name [param1 param2 ...]\n", executable.c_str(), clusterName.c_str()); + fprintf(stderr, "\n"); + fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); + fprintf(stderr, " | Attributes: |\n"); + fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); + for (auto & command : commands) { - bool hasAttributes = false; - - if (cluster.first[0] != '\0') + if (strcmp(command->GetName(), "read") == 0) { - for (auto & command : cluster.second) - { - if (strcmp("read", command->GetName()) == 0) - { - if (!hasAttributes) - { - PrintClusterHeader(cluster.first); - hasAttributes = true; - } - - fprintf(stderr, " | %-84s|\n", command->GetAttribute()); - } - } + fprintf(stderr, " | * %-82s|\n", command->GetAttribute()); } + } + fprintf(stderr, " +-------------------------------------------------------------------------------------+\n"); +} - if (hasAttributes) - { - PrintClusterFooter(); - } +void Commands::ShowCommand(std::string executable, std::string clusterName, Command * command) +{ + fprintf(stderr, "Usage:\n"); + + std::string arguments = ""; + arguments += command->GetName(); + + size_t argumentsCount = command->GetArgumentsCount(); + for (size_t i = 0; i < argumentsCount; i++) + { + arguments += " "; + arguments += command->GetArgumentName(i); } + fprintf(stderr, " %s %s %s\n", executable.c_str(), clusterName.c_str(), arguments.c_str()); } diff --git a/examples/chip-tool/commands/common/Commands.h b/examples/chip-tool/commands/common/Commands.h index 94a03296249b9a..c47c7ddcdf036c 100644 --- a/examples/chip-tool/commands/common/Commands.h +++ b/examples/chip-tool/commands/common/Commands.h @@ -28,17 +28,21 @@ class Commands public: using ChipDeviceController = ::chip::DeviceController::ChipDeviceController; using NodeId = ::chip::NodeId; + using CommandsVector = ::std::vector>; void Register(const char * clusterName, commands_list commandsList); int Run(NodeId localId, NodeId remoteId, int argc, char ** argv); private: - CHIP_ERROR RunCommand(ChipDeviceController & dc, NodeId remoteId, int argc, char * argv[]); + CHIP_ERROR RunCommand(ChipDeviceController & dc, NodeId remoteId, int argc, char ** argv); + std::map::iterator GetCluster(std::string clusterName); + Command * GetCommand(CommandsVector & commands, std::string commandName); + Command * GetReadCommand(CommandsVector & commands, std::string commandName, std::string attributeName); - void ShowUsage(const char * executable); - void PrintMiscCommands(); - void PrintClustersCommands(); - void PrintClustersAttributes(); + void ShowClusters(std::string executable); + void ShowCluster(std::string executable, std::string clusterName, CommandsVector & commands); + void ShowClusterAttributes(std::string executable, std::string clusterName, CommandsVector & commands); + void ShowCommand(std::string executable, std::string clusterName, Command * command); - std::map>> clusters; + std::map mClusters; }; diff --git a/examples/chip-tool/commands/common/NetworkCommand.h b/examples/chip-tool/commands/common/NetworkCommand.h index b6f1119b0226d3..79f21f847b2523 100644 --- a/examples/chip-tool/commands/common/NetworkCommand.h +++ b/examples/chip-tool/commands/common/NetworkCommand.h @@ -34,14 +34,14 @@ class NetworkCommand : public Command { if (type == NetworkType::UDP || type == NetworkType::ALL) { + AddArgument("device-remote-port", 0, UINT16_MAX, &mRemotePort); AddArgument("device-remote-ip", &mRemoteAddr); - AddArgument("device-remote-port", 0, 65536, &mRemotePort); } if (type == NetworkType::BLE || type == NetworkType::ALL) { - AddArgument("discriminator", 0, 4096, &mDiscriminator); AddArgument("setup-pin-code", 0, 134217727, &mSetupPINCode); + AddArgument("discriminator", 0, 4096, &mDiscriminator); } } diff --git a/examples/chip-tool/commands/echo/Commands.h b/examples/chip-tool/commands/echo/Commands.h index ce1647e5b71783..20d65f8961cbfb 100644 --- a/examples/chip-tool/commands/echo/Commands.h +++ b/examples/chip-tool/commands/echo/Commands.h @@ -23,18 +23,18 @@ class Echo : public EchoCommand { public: - Echo() : EchoCommand("echo", NetworkType::UDP) {} + Echo() : EchoCommand("ip", NetworkType::UDP) {} }; class EchoBle : public EchoCommand { public: - EchoBle() : EchoCommand("echo-ble", NetworkType::BLE) {} + EchoBle() : EchoCommand("ble", NetworkType::BLE) {} }; void registerCommandsEcho(Commands & commands) { - const char * clusterName = ""; + const char * clusterName = "Echo"; commands_list clusterCommands = { make_unique(), diff --git a/examples/lighting-app/efr32/README.md b/examples/lighting-app/efr32/README.md index bd4db163ef4a52..227d8a46cf9773 100644 --- a/examples/lighting-app/efr32/README.md +++ b/examples/lighting-app/efr32/README.md @@ -156,7 +156,7 @@ combination with JLinkRTTClient as follows: `router table` using a serial terminal (screen / minicom etc.) on the board running the lighting-app example) - Using chip-tool you can now control the light status with on/off command - such as `chip-tool on 11095 1` + such as `chip-tool onoff on 1 11095` ### Notes diff --git a/examples/lock-app/efr32/README.md b/examples/lock-app/efr32/README.md index 805771eb8cb944..9a11a44b680df3 100644 --- a/examples/lock-app/efr32/README.md +++ b/examples/lock-app/efr32/README.md @@ -156,7 +156,7 @@ combination with JLinkRTTClient as follows: `router table` using a serial terminal (screen / minicom etc.) on the board running the lock-app example) - Using chip-tool you can now control the lock status with on/off command such - as `chip-tool on 11095 1` + as `chip-tool onoff on 1 11095` ### Notes diff --git a/src/test_driver/linux-cirque/test-on-off-cluster.py b/src/test_driver/linux-cirque/test-on-off-cluster.py index da7293e0af6800..663cd837360019 100644 --- a/src/test_driver/linux-cirque/test-on-off-cluster.py +++ b/src/test_driver/linux-cirque/test-on-off-cluster.py @@ -79,7 +79,7 @@ def run_data_model_test(self): for ip in server_ip_address: output = self.execute_device_cmd( - tool_device_id, "chip-tool on {} {} 1".format(ip, CHIP_PORT)) + tool_device_id, "chip-tool onoff on 1 {} {}".format(ip, CHIP_PORT)) self.logger.info( 'checking output does not contain "No response from device"') self.assertFalse(self.sequenceMatch( @@ -87,7 +87,7 @@ def run_data_model_test(self): time.sleep(1) for ip in server_ip_address: output = self.execute_device_cmd( - tool_device_id, "chip-tool off {} {} 1".format(ip, CHIP_PORT)) + tool_device_id, "chip-tool onoff off 1 {} {}".format(ip, CHIP_PORT)) self.logger.info( 'checking output does not contain "No response from device"') self.assertFalse(self.sequenceMatch( From 60a280713c21abd4cc455a7829c9151c97f09e23 Mon Sep 17 00:00:00 2001 From: Michael Spang Date: Tue, 13 Oct 2020 11:03:21 -0400 Subject: [PATCH 03/40] Disable happy testing locally by default (#3217) These make the "all" build fail except in happy's special userns environment, and the build stays persistently dirty because happy doesn't track inputs & outputs. Disable it by default until these issues are fixed. See #3214. --- .github/workflows/unit_integration_test.yaml | 2 +- BUILD.gn | 8 +++--- build/chip/happy_test.gni | 1 + build/chip/tests.gni | 3 +++ src/BUILD.gn | 2 +- src/inet/tests/BUILD.gn | 27 +++++++++++--------- 6 files changed, 26 insertions(+), 17 deletions(-) diff --git a/.github/workflows/unit_integration_test.yaml b/.github/workflows/unit_integration_test.yaml index 26e653100a4fc0..85cee7e5f8e4cc 100644 --- a/.github/workflows/unit_integration_test.yaml +++ b/.github/workflows/unit_integration_test.yaml @@ -68,7 +68,7 @@ jobs: *) ;; esac - scripts/build/gn_gen.sh --args="$GN_ARGS" + scripts/build/gn_gen.sh --args="$GN_ARGS chip_enable_happy_tests=true" - name: Run Build run: scripts/build/gn_build.sh - name: Run Tests diff --git a/BUILD.gn b/BUILD.gn index 9dc084b45089bd..d3ced42cc4e4ce 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -92,9 +92,11 @@ if (current_toolchain != "${dir_pw_toolchain}/dummy:dummy") { } # We don't always want to run happy tests, make them a seperate group. - group("happy_tests") { - if (chip_link_tests) { - deps = [ "//src:happy_tests" ] + if (chip_enable_happy_tests) { + group("happy_tests") { + if (chip_link_tests) { + deps = [ "//src:happy_tests" ] + } } } } else { diff --git a/build/chip/happy_test.gni b/build/chip/happy_test.gni index 8db45dbc078c44..bc325d2da9ea8a 100644 --- a/build/chip/happy_test.gni +++ b/build/chip/happy_test.gni @@ -17,6 +17,7 @@ import("//build_overrides/chip.gni") import("${chip_root}/build/chip/tests.gni") assert(chip_build_tests) +assert(chip_enable_happy_tests) template("happy_test") { _suite_name = target_name diff --git a/build/chip/tests.gni b/build/chip/tests.gni index bf718a2a529708..169b55c33c3685 100644 --- a/build/chip/tests.gni +++ b/build/chip/tests.gni @@ -19,6 +19,9 @@ import("${chip_root}/src/platform/device.gni") declare_args() { # Enable building tests. chip_build_tests = current_os != "freertos" + + # Enable happy tests. + chip_enable_happy_tests = false } declare_args() { diff --git a/src/BUILD.gn b/src/BUILD.gn index b8de3a77f291d6..1aab88afc19e1c 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -64,7 +64,7 @@ if (chip_build_tests) { } } - if (current_os == "linux") { + if (chip_enable_happy_tests) { group("happy_tests") { deps = [ "${chip_root}/src/test_driver/happy/tests/standalone/inet:inet_tests", diff --git a/src/inet/tests/BUILD.gn b/src/inet/tests/BUILD.gn index bc68b29733637b..69a127c140b4cf 100644 --- a/src/inet/tests/BUILD.gn +++ b/src/inet/tests/BUILD.gn @@ -16,6 +16,7 @@ import("//build_overrides/chip.gni") import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") +import("${chip_root}/build/chip/tests.gni") import("${chip_root}/src/lwip/lwip.gni") import("${chip_root}/src/platform/device.gni") @@ -69,20 +70,22 @@ chip_test_suite("tests") { } } -# The following binaries should be executed by happy. -chip_test_suite("happy_tests") { - output_name = "libHappyTestInetCommon" +if (chip_enable_happy_tests) { + # The following binaries should be executed by happy. + chip_test_suite("happy_tests") { + output_name = "libHappyTestInetCommon" - sources = [ "TestInetLayerMulticast.cpp" ] + sources = [ "TestInetLayerMulticast.cpp" ] - public_configs = [ ":tests_config" ] + public_configs = [ ":tests_config" ] - public_deps = [ - ":tests_common", - "${chip_root}/src/inet", - "${chip_root}/src/lib/core", - "${nlunit_test_root}:nlunit-test", - ] + public_deps = [ + ":tests_common", + "${chip_root}/src/inet", + "${chip_root}/src/lib/core", + "${nlunit_test_root}:nlunit-test", + ] - tests = [ "TestInetLayerMulticast" ] + tests = [ "TestInetLayerMulticast" ] + } } From ba6fdbc7fcf0f90ed8d684893185dd97457bda42 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Tue, 13 Oct 2020 17:04:45 +0200 Subject: [PATCH 04/40] Replace ChipLogProgress by ChipLogError in VerifyOrExit calls (#3212) --- src/platform/Linux/BLEManagerImpl.cpp | 4 +- src/platform/Linux/CHIPBluezHelper.cpp | 250 ++++++++++++------------- src/transport/SecureSessionMgr.cpp | 22 +-- 3 files changed, 136 insertions(+), 140 deletions(-) diff --git a/src/platform/Linux/BLEManagerImpl.cpp b/src/platform/Linux/BLEManagerImpl.cpp index 2662db83164a16..a81ca7a366c413 100644 --- a/src/platform/Linux/BLEManagerImpl.cpp +++ b/src/platform/Linux/BLEManagerImpl.cpp @@ -428,8 +428,8 @@ void BLEManagerImpl::HandleTXCharCCCDWrite(BLE_CONNECTION_OBJECT conId) BluezConnection * connection = static_cast(conId); - VerifyOrExit(connection != nullptr, ChipLogProgress(DeviceLayer, "Connection is NULL in HandleTXCharCCCDWrite")); - VerifyOrExit(connection->mpC2 != nullptr, ChipLogProgress(DeviceLayer, "C2 is NULL in HandleTXCharCCCDWrite")); + VerifyOrExit(connection != nullptr, ChipLogError(DeviceLayer, "Connection is NULL in HandleTXCharCCCDWrite")); + VerifyOrExit(connection->mpC2 != nullptr, ChipLogError(DeviceLayer, "C2 is NULL in HandleTXCharCCCDWrite")); // Post an event to the Chip queue to process either a CHIPoBLE Subscribe or Unsubscribe based on // whether the client is enabling or disabling indications. diff --git a/src/platform/Linux/CHIPBluezHelper.cpp b/src/platform/Linux/CHIPBluezHelper.cpp index 1e881dc8f08332..b7a2136a6cf953 100644 --- a/src/platform/Linux/CHIPBluezHelper.cpp +++ b/src/platform/Linux/CHIPBluezHelper.cpp @@ -79,9 +79,9 @@ static gboolean BluezAdvertisingRelease(BluezLEAdvertisement1 * aAdv, GDBusMetho { bool isSuccess = false; BluezEndpoint * endpoint = static_cast(apClosure); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); - VerifyOrExit(aAdv != nullptr, ChipLogProgress(DeviceLayer, "BluezLEAdvertisement1 is NULL in %s", __func__)); - ChipLogProgress(DeviceLayer, "Release adv object in %s", __func__); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(aAdv != nullptr, ChipLogError(DeviceLayer, "BluezLEAdvertisement1 is NULL in %s", __func__)); + ChipLogDetail(DeviceLayer, "Release adv object in %s", __func__); g_dbus_object_manager_server_unexport(endpoint->mpRoot, endpoint->mpAdvPath); endpoint->mIsAdvertising = false; @@ -102,11 +102,11 @@ static BluezLEAdvertisement1 * BluezAdvertisingCreate(BluezEndpoint * apEndpoint GVariantBuilder serviceUUIDsBuilder; char * debugStr; - VerifyOrExit(apEndpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(apEndpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); if (apEndpoint->mpAdvPath == nullptr) apEndpoint->mpAdvPath = g_strdup_printf("%s/advertising", apEndpoint->mpRootPath); - ChipLogProgress(DeviceLayer, "Create adv object at %s", apEndpoint->mpAdvPath); + ChipLogDetail(DeviceLayer, "Create adv object at %s", apEndpoint->mpAdvPath); object = bluez_object_skeleton_new(apEndpoint->mpAdvPath); adv = bluez_leadvertisement1_skeleton_new(); @@ -128,7 +128,7 @@ static BluezLEAdvertisement1 * BluezAdvertisingCreate(BluezEndpoint * apEndpoint serviceUUID = g_variant_builder_end(&serviceUUIDsBuilder); debugStr = g_variant_print(serviceData, TRUE); - ChipLogProgress(DeviceLayer, "SET service data to %s", debugStr); + ChipLogDetail(DeviceLayer, "SET service data to %s", debugStr); g_free(debugStr); bluez_leadvertisement1_set_type_(adv, (apEndpoint->mType & BLUEZ_ADV_TYPE_CONNECTABLE) ? "peripheral" : "broadcast"); @@ -170,18 +170,18 @@ static void BluezAdvStartDone(GObject * aObject, GAsyncResult * aResult, gpointe BluezEndpoint * endpoint = static_cast(apClosure); gboolean success = FALSE; - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); success = bluez_leadvertising_manager1_call_register_advertisement_finish(advMgr, aResult, &error); if (success == FALSE) { g_dbus_object_manager_server_unexport(endpoint->mpRoot, endpoint->mpAdvPath); } - VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, "FAIL: RegisterAdvertisement : %s", error->message)); + VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: RegisterAdvertisement : %s", error->message)); endpoint->mIsAdvertising = true; - ChipLogProgress(DeviceLayer, "RegisterAdvertisement complete"); + ChipLogDetail(DeviceLayer, "RegisterAdvertisement complete"); exit: BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(success == TRUE, nullptr); @@ -196,7 +196,7 @@ static void BluezAdvStopDone(GObject * aObject, GAsyncResult * aResult, gpointer GError * error = nullptr; gboolean success = FALSE; - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); success = bluez_leadvertising_manager1_call_unregister_advertisement_finish(advMgr, aResult, &error); @@ -209,9 +209,9 @@ static void BluezAdvStopDone(GObject * aObject, GAsyncResult * aResult, gpointer endpoint->mIsAdvertising = false; } - VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, "FAIL: UnregisterAdvertisement : %s", error->message)); + VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: UnregisterAdvertisement : %s", error->message)); - ChipLogProgress(DeviceLayer, "UnregisterAdvertisement complete"); + ChipLogDetail(DeviceLayer, "UnregisterAdvertisement complete"); exit: BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(success == TRUE, nullptr); @@ -224,13 +224,12 @@ static gboolean BluezAdvSetup(void * apClosure) BluezEndpoint * endpoint = static_cast(apClosure); BluezLEAdvertisement1 * adv; - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); - VerifyOrExit(endpoint->mIsAdvertising == FALSE, - ChipLogProgress(DeviceLayer, "FAIL: Advertising already enabled in %s", __func__)); - VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL endpoint->mpAdapter in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint->mIsAdvertising == FALSE, ChipLogError(DeviceLayer, "FAIL: Advertising already enabled in %s", __func__)); + VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL endpoint->mpAdapter in %s", __func__)); adv = BluezAdvertisingCreate(endpoint); - VerifyOrExit(adv != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL adv in %s", __func__)); + VerifyOrExit(adv != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL adv in %s", __func__)); exit: return G_SOURCE_REMOVE; @@ -244,16 +243,16 @@ static gboolean BluezAdvStart(void * apEndpoint) GVariant * options; BluezEndpoint * endpoint = static_cast(apEndpoint); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); VerifyOrExit(!endpoint->mIsAdvertising, - ChipLogProgress(DeviceLayer, "FAIL: Advertising has already been enabled in %s", __func__)); - VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL endpoint->mpAdapter in %s", __func__)); + ChipLogError(DeviceLayer, "FAIL: Advertising has already been enabled in %s", __func__)); + VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL endpoint->mpAdapter in %s", __func__)); adapter = g_dbus_interface_get_object(G_DBUS_INTERFACE(endpoint->mpAdapter)); - VerifyOrExit(adapter != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL adapter in %s", __func__)); + VerifyOrExit(adapter != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL adapter in %s", __func__)); advMgr = bluez_object_get_leadvertising_manager1(BLUEZ_OBJECT(adapter)); - VerifyOrExit(advMgr != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL advMgr in %s", __func__)); + VerifyOrExit(advMgr != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL advMgr in %s", __func__)); g_variant_builder_init(&optionsBuilder, G_VARIANT_TYPE("a{sv}")); options = g_variant_builder_end(&optionsBuilder); @@ -271,16 +270,16 @@ static gboolean BluezAdvStop(void * apEndpoint) BluezEndpoint * endpoint = static_cast(apEndpoint); BluezLEAdvertisingManager1 * advMgr = nullptr; - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); VerifyOrExit(endpoint->mIsAdvertising, - ChipLogProgress(DeviceLayer, "FAIL: Advertising has already been disabled in %s", __func__)); - VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL endpoint->mpAdapter in %s", __func__)); + ChipLogError(DeviceLayer, "FAIL: Advertising has already been disabled in %s", __func__)); + VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL endpoint->mpAdapter in %s", __func__)); adapter = g_dbus_interface_get_object(G_DBUS_INTERFACE(endpoint->mpAdapter)); - VerifyOrExit(adapter != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL adapter in %s", __func__)); + VerifyOrExit(adapter != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL adapter in %s", __func__)); advMgr = bluez_object_get_leadvertising_manager1(BLUEZ_OBJECT(adapter)); - VerifyOrExit(advMgr != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL advMgr in %s", __func__)); + VerifyOrExit(advMgr != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL advMgr in %s", __func__)); bluez_leadvertising_manager1_call_unregister_advertisement(advMgr, endpoint->mpAdvPath, nullptr, BluezAdvStopDone, apEndpoint); @@ -292,7 +291,7 @@ static gboolean BluezCharacteristicReadValue(BluezGattCharacteristic1 * aChar, G GVariant * aOptions) { GVariant * val; - ChipLogProgress(DeviceLayer, "Received BluezCharacteristicReadValue"); + ChipLogDetail(DeviceLayer, "Received BluezCharacteristicReadValue"); val = bluez_gatt_characteristic1_get_value(aChar); bluez_gatt_characteristic1_complete_read_value(aChar, aInvocation, val); return TRUE; @@ -309,9 +308,9 @@ static gboolean BluezCharacteristicWriteValue(BluezGattCharacteristic1 * aChar, BluezConnection * conn = NULL; BluezEndpoint * endpoint = static_cast(apEndpoint); - VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != NULL, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); - VerifyOrExit(aValue != NULL, ChipLogProgress(DeviceLayer, "aValue is NULL in %s", __func__)); + VerifyOrExit(aValue != NULL, ChipLogError(DeviceLayer, "aValue is NULL in %s", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != NULL, @@ -334,7 +333,7 @@ static gboolean BluezCharacteristicWriteValue(BluezGattCharacteristic1 * aChar, static gboolean BluezCharacteristicWriteValueError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aValue, GVariant * aOptions, gpointer apClosure) { - ChipLogProgress(DeviceLayer, "BluezCharacteristicWriteValueError"); + ChipLogDetail(DeviceLayer, "BluezCharacteristicWriteValueError"); g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.NotSupported", "Write for characteristic is unsupported"); return TRUE; @@ -350,20 +349,20 @@ static gboolean BluezCharacteristicWriteFD(GIOChannel * aChannel, GIOCondition a BluezConnection * conn = static_cast(apEndpoint); - VerifyOrExit(conn != nullptr, ChipLogProgress(DeviceLayer, "No CHIP Bluez connection in %s", __func__)); + VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "No CHIP Bluez connection in %s", __func__)); - VerifyOrExit(!(aCond & G_IO_HUP), ChipLogProgress(DeviceLayer, "INFO: socket disconnected in %s", __func__)); - VerifyOrExit(!(aCond & (G_IO_ERR | G_IO_NVAL)), ChipLogProgress(DeviceLayer, "INFO: socket error in %s", __func__)); - VerifyOrExit(aCond == G_IO_IN, ChipLogProgress(DeviceLayer, "FAIL: error in %s", __func__)); + VerifyOrExit(!(aCond & G_IO_HUP), ChipLogError(DeviceLayer, "INFO: socket disconnected in %s", __func__)); + VerifyOrExit(!(aCond & (G_IO_ERR | G_IO_NVAL)), ChipLogError(DeviceLayer, "INFO: socket error in %s", __func__)); + VerifyOrExit(aCond == G_IO_IN, ChipLogError(DeviceLayer, "FAIL: error in %s", __func__)); - ChipLogProgress(DeviceLayer, "c1 %s mtu, %d", __func__, conn->mMtu); + ChipLogDetail(DeviceLayer, "c1 %s mtu, %d", __func__, conn->mMtu); buf = static_cast(g_malloc(conn->mMtu)); fd = g_io_channel_unix_get_fd(aChannel); len = read(fd, buf, conn->mMtu); - VerifyOrExit(len > 0, ChipLogProgress(DeviceLayer, "FAIL: short read in %s (%d)", __func__, len)); + VerifyOrExit(len > 0, ChipLogError(DeviceLayer, "FAIL: short read in %s (%d)", __func__, len)); // Casting len to size_t is safe, since we ensured that it's not negative. newVal = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, buf, static_cast(len), sizeof(uint8_t)); @@ -403,18 +402,18 @@ static gboolean BluezCharacteristicAcquireWrite(BluezGattCharacteristic1 * aChar BluezConnection * conn = nullptr; BluezEndpoint * endpoint = static_cast(apEndpoint); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != nullptr, g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.Failed", "No Chipoble connection")); - ChipLogProgress(DeviceLayer, "BluezCharacteristicAcquireWrite is called, conn: %p", conn); + ChipLogDetail(DeviceLayer, "BluezCharacteristicAcquireWrite is called, conn: %p", conn); if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, fds) < 0) { errStr = strerror(errno); - ChipLogProgress(DeviceLayer, "FAIL: socketpair: %s in %s", errStr, __func__); + ChipLogError(DeviceLayer, "FAIL: socketpair: %s in %s", errStr, __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.Failed", "FD creation failed"); SuccessOrExit(false); } @@ -427,7 +426,7 @@ static gboolean BluezCharacteristicAcquireWrite(BluezGattCharacteristic1 * aChar } else { - ChipLogProgress(DeviceLayer, "FAIL: no MTU in options in %s", __func__); + ChipLogError(DeviceLayer, "FAIL: no MTU in options in %s", __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.InvalidArguments", "MTU negotiation failed"); SuccessOrExit(false); } @@ -454,7 +453,7 @@ static gboolean BluezCharacteristicAcquireWrite(BluezGattCharacteristic1 * aChar static gboolean BluezCharacteristicAcquireWriteError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions) { - ChipLogProgress(DeviceLayer, "BluezCharacteristicAcquireWriteError is called"); + ChipLogDetail(DeviceLayer, "BluezCharacteristicAcquireWriteError is called"); g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.NotSupported", "AcquireWrite for characteristic is unsupported"); return TRUE; @@ -471,7 +470,7 @@ static gboolean BluezCharacteristicAcquireNotify(BluezGattCharacteristic1 * aCha bool isSuccess = false; BluezEndpoint * endpoint = static_cast(apEndpoint); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != nullptr, @@ -491,7 +490,7 @@ static gboolean BluezCharacteristicAcquireNotify(BluezGattCharacteristic1 * aCha if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, fds) < 0) { errStr = strerror(errno); - ChipLogProgress(DeviceLayer, "FAIL: socketpair: %s in %s", errStr, __func__); + ChipLogError(DeviceLayer, "FAIL: socketpair: %s in %s", errStr, __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.Failed", "FD creation failed"); SuccessOrExit(false); } @@ -521,7 +520,7 @@ static gboolean BluezCharacteristicAcquireNotify(BluezGattCharacteristic1 * aCha static gboolean BluezCharacteristicAcquireNotifyError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions) { - ChipLogProgress(DeviceLayer, "TRACE: AcquireNotify is called"); + ChipLogDetail(DeviceLayer, "TRACE: AcquireNotify is called"); g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.NotSupported", "AcquireNotify for characteristic is unsupported"); return TRUE; @@ -534,7 +533,7 @@ static gboolean BluezCharacteristicStartNotify(BluezGattCharacteristic1 * aChar, BluezConnection * conn = nullptr; BluezEndpoint * endpoint = static_cast(apEndpoint); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != nullptr, @@ -571,7 +570,7 @@ static gboolean BluezCharacteristicStopNotify(BluezGattCharacteristic1 * aChar, BluezConnection * conn = nullptr; BluezEndpoint * endpoint = static_cast(apEndpoint); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != nullptr, @@ -632,8 +631,8 @@ static gboolean BluezIsServiceOnDevice(BluezGattService1 * aService, BluezDevice static gboolean BluezIsCharOnService(BluezGattCharacteristic1 * aChar, BluezGattService1 * aService) { - ChipLogProgress(DeviceLayer, "Char1 %s", bluez_gatt_characteristic1_get_service(aChar)); - ChipLogProgress(DeviceLayer, "Char1 %s", g_dbus_proxy_get_object_path(G_DBUS_PROXY(aService))); + ChipLogDetail(DeviceLayer, "Char1 %s", bluez_gatt_characteristic1_get_service(aChar)); + ChipLogDetail(DeviceLayer, "Char1 %s", g_dbus_proxy_get_object_path(G_DBUS_PROXY(aService))); return strcmp(bluez_gatt_characteristic1_get_service(aChar), g_dbus_proxy_get_object_path(G_DBUS_PROXY(aService))) == 0 ? TRUE : FALSE; } @@ -645,10 +644,10 @@ static void BluezConnectionInit(BluezConnection * apConn) GList * l; BluezEndpoint * endpoint = nullptr; - VerifyOrExit(apConn != nullptr, ChipLogProgress(DeviceLayer, "Bluez connection is NULL in %s", __func__)); + VerifyOrExit(apConn != nullptr, ChipLogError(DeviceLayer, "Bluez connection is NULL in %s", __func__)); endpoint = apConn->mpEndpoint; - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); if (!endpoint->mIsCentral) { @@ -677,7 +676,7 @@ static void BluezConnectionInit(BluezConnection * apConn) } } - VerifyOrExit(apConn->mpService != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL service in %s", __func__)); + VerifyOrExit(apConn->mpService != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL service in %s", __func__)); for (l = objects; l != nullptr; l = l->next) { @@ -707,8 +706,8 @@ static void BluezConnectionInit(BluezConnection * apConn) } } - VerifyOrExit(apConn->mpC1 != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL C1 in %s", __func__)); - VerifyOrExit(apConn->mpC2 != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL C2 in %s", __func__)); + VerifyOrExit(apConn->mpC1 != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL C1 in %s", __func__)); + VerifyOrExit(apConn->mpC2 != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL C2 in %s", __func__)); } exit: @@ -720,7 +719,7 @@ static gboolean BluezConnectionInitIdle(gpointer user_data) { BluezConnection * conn = static_cast(user_data); - ChipLogProgress(DeviceLayer, "%s", __func__); + ChipLogDetail(DeviceLayer, "%s", __func__); BluezConnectionInit(conn); @@ -762,7 +761,7 @@ static BluezGattCharacteristic1 * BluezCharacteristicCreate(BluezGattService1 * BluezObjectSkeleton * object; BluezGattCharacteristic1 * characteristic; - ChipLogProgress(DeviceLayer, "Create characteristic object at %s", charPath); + ChipLogDetail(DeviceLayer, "Create characteristic object at %s", charPath); object = bluez_object_skeleton_new(charPath); characteristic = bluez_gatt_characteristic1_skeleton_new(); @@ -783,10 +782,10 @@ static void BluezPeripheralRegisterAppDone(GObject * aObject, GAsyncResult * aRe gboolean success = bluez_gatt_manager1_call_register_application_finish(gattMgr, aResult, &error); - VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, "FAIL: RegisterApplication : %s", error->message)); + VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: RegisterApplication : %s", error->message)); BLEManagerImpl::NotifyBLEPeripheralRegisterAppComplete(true, nullptr); - ChipLogProgress(DeviceLayer, "BluezPeripheralRegisterAppDone done"); + ChipLogDetail(DeviceLayer, "BluezPeripheralRegisterAppDone done"); exit: if (error != nullptr) @@ -805,13 +804,13 @@ gboolean BluezPeripheralRegisterApp(void * apClosure) GVariant * options; BluezEndpoint * endpoint = static_cast(apClosure); - VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL endpoint->mpAdapter in %s", __func__)); + VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL endpoint->mpAdapter in %s", __func__)); adapter = g_dbus_interface_get_object(G_DBUS_INTERFACE(endpoint->mpAdapter)); - VerifyOrExit(adapter != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL adapter in %s", __func__)); + VerifyOrExit(adapter != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL adapter in %s", __func__)); gattMgr = bluez_object_get_gatt_manager1(BLUEZ_OBJECT(adapter)); - VerifyOrExit(gattMgr != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL gattMgr in %s", __func__)); + VerifyOrExit(gattMgr != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL gattMgr in %s", __func__)); g_variant_builder_init(&optionsBuilder, G_VARIANT_TYPE("a{sv}")); options = g_variant_builder_end(&optionsBuilder); @@ -843,9 +842,9 @@ static void BluezHandleAdvertisementFromDevice(BluezDevice1 * aDevice, BluezEndp // service data is optional and may not be present VerifyOrExit(serviceData != nullptr, ); - ChipLogProgress(DeviceLayer, "TRACE: Device %s Advertising flags: %s", address, flags); + ChipLogDetail(DeviceLayer, "TRACE: Device %s Advertising flags: %s", address, flags); debugStr = g_variant_print(serviceData, TRUE); - ChipLogProgress(DeviceLayer, "TRACE: Device %s Service data: %s", address, debugStr); + ChipLogDetail(DeviceLayer, "TRACE: Device %s Service data: %s", address, debugStr); g_variant_iter_init(&serviceIterator, serviceData); @@ -856,16 +855,16 @@ static void BluezHandleAdvertisementFromDevice(BluezDevice1 * aDevice, BluezEndp const auto uuidStr = g_variant_get_string(key, &dataLen); const void * rawData; - VerifyOrExit(chip::Ble::StringToUUID(uuidStr, uuid), ChipLogProgress(DeviceLayer, "TRACE: Invalid BLE UUID format")); + VerifyOrExit(chip::Ble::StringToUUID(uuidStr, uuid), ChipLogError(DeviceLayer, "TRACE: Invalid BLE UUID format")); if (!UUIDsMatch(&uuid, &Ble::CHIP_BLE_SVC_ID)) continue; rawData = g_variant_get_fixed_array(g_variant_get_variant(val), &dataLen, sizeof(uint8_t)); - VerifyOrExit(dataLen == sizeof(deviceInfo), ChipLogProgress(DeviceLayer, "TRACE: Invalid BLE Device info")); + VerifyOrExit(dataLen == sizeof(deviceInfo), ChipLogError(DeviceLayer, "TRACE: Invalid BLE Device info")); memcpy(&deviceInfo, rawData, dataLen); - ChipLogProgress(DeviceLayer, "TRACE: Found CHIP BLE Device: %" PRIu16, deviceInfo.GetDeviceDiscriminator()); + ChipLogDetail(DeviceLayer, "TRACE: Found CHIP BLE Device: %" PRIu16, deviceInfo.GetDeviceDiscriminator()); if (endpoint->mDiscoveryRequest.mDiscriminator == deviceInfo.GetDeviceDiscriminator() && endpoint->mDiscoveryRequest.mAutoConnect) @@ -882,8 +881,8 @@ static void BluezSignalInterfacePropertiesChanged(GDBusObjectManagerClient * aMa { BluezEndpoint * endpoint = static_cast(apClosure); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); - VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, "FAIL: NULL endpoint->mpAdapter in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL endpoint->mpAdapter in %s", __func__)); if (strcmp(g_dbus_proxy_get_interface_name(aInterface), DEVICE_INTERFACE) == 0) { @@ -906,7 +905,7 @@ static void BluezSignalInterfacePropertiesChanged(GDBusObjectManagerClient * aMa if (connected) { - ChipLogProgress(DeviceLayer, "Bluez coonnected"); + ChipLogDetail(DeviceLayer, "Bluez coonnected"); // for a central, the connection has been already allocated. For a peripheral, it has not. // todo do we need this ? we could handle all connection the same wa... if (endpoint->mIsCentral) @@ -915,16 +914,16 @@ static void BluezSignalInterfacePropertiesChanged(GDBusObjectManagerClient * aMa if (!endpoint->mIsCentral) { VerifyOrExit(conn == nullptr, - ChipLogProgress(DeviceLayer, "FAIL: connection already tracked: conn: %x device: %s", conn, - g_dbus_proxy_get_object_path(aInterface))); + ChipLogError(DeviceLayer, "FAIL: connection already tracked: conn: %x device: %s", conn, + g_dbus_proxy_get_object_path(aInterface))); conn = g_new0(BluezConnection, 1); conn->mpPeerAddress = g_strdup(bluez_device1_get_address(device)); conn->mpDevice = static_cast(g_object_ref(device)); conn->mpEndpoint = endpoint; BluezConnectionInit(conn); endpoint->mpPeerDevicePath = g_strdup(g_dbus_proxy_get_object_path(aInterface)); - ChipLogProgress(DeviceLayer, "coonnected, insert, conn:%p, c1:%p, c2:%p and %s", conn, conn->mpC1, - conn->mpC2, endpoint->mpPeerDevicePath); + ChipLogError(DeviceLayer, "coonnected, insert, conn:%p, c1:%p, c2:%p and %s", conn, conn->mpC1, + conn->mpC2, endpoint->mpPeerDevicePath); g_hash_table_insert(endpoint->mpConnMap, endpoint->mpPeerDevicePath, conn); } // for central, we do not call BluezConnectionInit until the services have been resolved @@ -933,7 +932,7 @@ static void BluezSignalInterfacePropertiesChanged(GDBusObjectManagerClient * aMa } else { - ChipLogProgress(DeviceLayer, "Bluez disconnected"); + ChipLogDetail(DeviceLayer, "Bluez disconnected"); BLEManagerImpl::CHIPoBluez_ConnectionClosed(conn); BluezOTConnectionDestroy(conn); g_hash_table_remove(endpoint->mpConnMap, g_dbus_proxy_get_object_path(aInterface)); @@ -978,7 +977,7 @@ static void BluezSignalInterfacePropertiesChanged(GDBusObjectManagerClient * aMa static void BluezHandleNewDevice(BluezDevice1 * device, BluezEndpoint * apEndpoint) { - VerifyOrExit(apEndpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(apEndpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); if (apEndpoint->mIsCentral) { BluezHandleAdvertisementFromDevice(device, apEndpoint); @@ -991,8 +990,8 @@ static void BluezHandleNewDevice(BluezDevice1 * device, BluezEndpoint * apEndpoi conn = static_cast( g_hash_table_lookup(apEndpoint->mpConnMap, g_dbus_proxy_get_object_path(G_DBUS_PROXY(device)))); VerifyOrExit(conn == nullptr, - ChipLogProgress(DeviceLayer, "FAIL: connection already tracked: conn: %x new device: %s", conn, - g_dbus_proxy_get_object_path(G_DBUS_PROXY(device)))); + ChipLogError(DeviceLayer, "FAIL: connection already tracked: conn: %x new device: %s", conn, + g_dbus_proxy_get_object_path(G_DBUS_PROXY(device)))); conn = g_new0(BluezConnection, 1); conn->mpPeerAddress = g_strdup(bluez_device1_get_address(device)); @@ -1040,7 +1039,7 @@ static BluezGattService1 * BluezServiceCreate(gpointer apClosure) BluezEndpoint * endpoint = static_cast(apClosure); endpoint->mpServicePath = g_strdup_printf("%s/service", endpoint->mpRootPath); - ChipLogProgress(DeviceLayer, "CREATE service object at %s", endpoint->mpServicePath); + ChipLogDetail(DeviceLayer, "CREATE service object at %s", endpoint->mpServicePath); object = bluez_object_skeleton_new(endpoint->mpServicePath); service = bluez_gatt_service1_skeleton_new(); @@ -1062,7 +1061,7 @@ static void bluezObjectsSetup(BluezEndpoint * apEndpoint) GList * l; char * expectedPath = nullptr; - VerifyOrExit(apEndpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(apEndpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); expectedPath = g_strdup_printf("%s/hci%d", BLUEZ_PATH, apEndpoint->mNodeId); objects = g_dbus_object_manager_get_objects(apEndpoint->mpObjMgr); @@ -1098,8 +1097,7 @@ static void bluezObjectsSetup(BluezEndpoint * apEndpoint) } g_list_free_full(interfaces, g_object_unref); } - VerifyOrExit(apEndpoint->mpAdapter != nullptr, - ChipLogProgress(DeviceLayer, "FAIL: NULL apEndpoint->mpAdapter in %s", __func__)); + VerifyOrExit(apEndpoint->mpAdapter != nullptr, ChipLogError(DeviceLayer, "FAIL: NULL apEndpoint->mpAdapter in %s", __func__)); bluez_adapter1_set_powered(apEndpoint->mpAdapter, TRUE); // with BLE we are discoverable only when advertising so this can be @@ -1116,7 +1114,7 @@ static BluezConnection * GetBluezConnectionViaDevice(BluezEndpoint * apEndpoint) { BluezConnection * retval = static_cast(g_hash_table_lookup(apEndpoint->mpConnMap, apEndpoint->mpPeerDevicePath)); - // ChipLogProgress(DeviceLayer, "acquire connection object %p in (%s)", retval, __func__); + // ChipLogError(DeviceLayer, "acquire connection object %p in (%s)", retval, __func__); return retval; } @@ -1129,7 +1127,7 @@ static BluezConnection * BluezCharacteristicGetBluezConnection(BluezGattCharacte GVariantDict options; GVariant * v; - VerifyOrExit(apEndpoint != NULL, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(apEndpoint != NULL, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); VerifyOrExit(apEndpoint->mIsCentral, ); /* TODO Unfortunately StartNotify/StopNotify doesn't provide info about @@ -1182,7 +1180,7 @@ static BluezConnection * BluezCharacteristicGetBluezConnection(BluezGattCharacte v = g_variant_dict_lookup_value(&options, "device", G_VARIANT_TYPE_OBJECT_PATH); - VerifyOrExit(v != NULL, ChipLogProgress(DeviceLayer, "FAIL: No device option in dictionary (%s)", __func__)); + VerifyOrExit(v != NULL, ChipLogError(DeviceLayer, "FAIL: No device option in dictionary (%s)", __func__)); path = g_variant_get_string(v, NULL); @@ -1266,7 +1264,7 @@ static void BluezPeripheralObjectsSetup(gpointer apClosure) static const char * const c2_flags[] = { "read", "indicate", nullptr }; BluezEndpoint * endpoint = static_cast(apClosure); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); endpoint->mpService = BluezServiceCreate(apClosure); // C1 characteristic @@ -1293,8 +1291,8 @@ static void BluezPeripheralObjectsSetup(gpointer apClosure) g_signal_connect(endpoint->mpC2, "handle-stop-notify", G_CALLBACK(BluezCharacteristicStopNotify), apClosure); g_signal_connect(endpoint->mpC2, "handle-confirm", G_CALLBACK(BluezCharacteristicConfirm), apClosure); - ChipLogProgress(DeviceLayer, "CHIP BTP C1 %s", bluez_gatt_characteristic1_get_service(endpoint->mpC1)); - ChipLogProgress(DeviceLayer, "CHIP BTP C2 %s", bluez_gatt_characteristic1_get_service(endpoint->mpC2)); + ChipLogDetail(DeviceLayer, "CHIP BTP C1 %s", bluez_gatt_characteristic1_get_service(endpoint->mpC1)); + ChipLogDetail(DeviceLayer, "CHIP BTP C2 %s", bluez_gatt_characteristic1_get_service(endpoint->mpC2)); exit: return; @@ -1303,9 +1301,9 @@ static void BluezPeripheralObjectsSetup(gpointer apClosure) static void BluezOnBusAcquired(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) { BluezEndpoint * endpoint = static_cast(apClosure); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); - ChipLogProgress(DeviceLayer, "TRACE: Bus acquired for name %s", aName); + ChipLogDetail(DeviceLayer, "TRACE: Bus acquired for name %s", aName); endpoint->mpRootPath = g_strdup_printf("/chipoble/%04x", getpid() & 0xffff); endpoint->mpRoot = g_dbus_object_manager_server_new(endpoint->mpRootPath); @@ -1319,12 +1317,12 @@ static void BluezOnBusAcquired(GDBusConnection * aConn, const gchar * aName, gpo #if CHIP_BLUEZ_NAME_MONITOR static void BluezOnNameAcquired(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) { - ChipLogProgress(DeviceLayer, "TRACE: Owning name: Acquired %s", aName); + ChipLogDetail(DeviceLayer, "TRACE: Owning name: Acquired %s", aName); } static void BluezOnNameLost(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) { - ChipLogProgress(DeviceLayer, "TRACE: Owning name: lost %s", aName); + ChipLogDetail(DeviceLayer, "TRACE: Owning name: lost %s", aName); } #endif @@ -1334,10 +1332,10 @@ static void * BluezMainLoop(void * apClosure) GError * error = nullptr; GDBusConnection * conn = nullptr; BluezEndpoint * endpoint = static_cast(apClosure); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error); - VerifyOrExit(conn != nullptr, ChipLogProgress(DeviceLayer, "FAIL: get bus sync in %s, error: %s", __func__, error->message)); + VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "FAIL: get bus sync in %s, error: %s", __func__, error->message)); if (endpoint->mpAdapterName != nullptr) endpoint->mpOwningName = g_strdup_printf("%s", endpoint->mpAdapterName); @@ -1350,7 +1348,7 @@ static void * BluezMainLoop(void * apClosure) conn, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE, "/", bluez_object_manager_client_get_proxy_type, nullptr /* unused user data in the Proxy Type Func */, nullptr /*destroy notify */, nullptr /* cancellable */, &error); - VerifyOrExit(manager != nullptr, ChipLogProgress(DeviceLayer, "FAIL: Error getting object manager client: %s", error->message)); + VerifyOrExit(manager != nullptr, ChipLogError(DeviceLayer, "FAIL: Error getting object manager client: %s", error->message)); endpoint->mpObjMgr = manager; @@ -1367,9 +1365,9 @@ static void * BluezMainLoop(void * apClosure) g_signal_connect(manager, "object-removed", G_CALLBACK(BluezSignalOnObjectRemoved), apClosure); g_signal_connect(manager, "interface-proxy-properties-changed", G_CALLBACK(BluezSignalInterfacePropertiesChanged), apClosure); - ChipLogProgress(DeviceLayer, "TRACE: Bluez mainloop starting %s", __func__); + ChipLogDetail(DeviceLayer, "TRACE: Bluez mainloop starting %s", __func__); g_main_loop_run(sBluezMainLoop); - ChipLogProgress(DeviceLayer, "TRACE: Bluez mainloop stopping %s", __func__); + ChipLogDetail(DeviceLayer, "TRACE: Bluez mainloop stopping %s", __func__); BluezObjectsCleanup(endpoint); @@ -1394,7 +1392,7 @@ bool BluezRunOnBluezThread(int (*aCallback)(void *), void * apClosure) exit: if (msg != nullptr) { - ChipLogProgress(DeviceLayer, "%s in %s", msg, __func__); + ChipLogDetail(DeviceLayer, "%s in %s", msg, __func__); } return msg == nullptr; @@ -1410,22 +1408,22 @@ static gboolean BluezC2Indicate(void * apClosure) size_t len, written; closure = static_cast(apClosure); - VerifyOrExit(closure != nullptr, ChipLogProgress(DeviceLayer, "ConnectionDataBundle is NULL in %s", __func__)); + VerifyOrExit(closure != nullptr, ChipLogError(DeviceLayer, "ConnectionDataBundle is NULL in %s", __func__)); conn = closure->mpConn; - VerifyOrExit(conn != nullptr, ChipLogProgress(DeviceLayer, "BluezConnection is NULL in %s", __func__)); - VerifyOrExit(conn->mpC2 != nullptr, ChipLogProgress(DeviceLayer, "FAIL: C2 Indicate: %s", "NULL C2")); + VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "BluezConnection is NULL in %s", __func__)); + VerifyOrExit(conn->mpC2 != nullptr, ChipLogError(DeviceLayer, "FAIL: C2 Indicate: %s", "NULL C2")); if (bluez_gatt_characteristic1_get_notify_acquired(conn->mpC2) == TRUE) { buf = (char *) g_variant_get_fixed_array(closure->mpVal, &len, sizeof(uint8_t)); VerifyOrExit(len <= static_cast(std::numeric_limits::max()), - ChipLogProgress(DeviceLayer, "FAIL: buffer too large in %s", __func__)); + ChipLogError(DeviceLayer, "FAIL: buffer too large in %s", __func__)); status = g_io_channel_write_chars(conn->mC2Channel.mpChannel, buf, static_cast(len), &written, &error); g_variant_unref(closure->mpVal); closure->mpVal = nullptr; - VerifyOrExit(status == G_IO_STATUS_NORMAL, ChipLogProgress(DeviceLayer, "FAIL: C2 Indicate: %s", error->message)); + VerifyOrExit(status == G_IO_STATUS_NORMAL, ChipLogError(DeviceLayer, "FAIL: C2 Indicate: %s", error->message)); } else { @@ -1456,7 +1454,7 @@ bool SendBluezIndication(BLE_CONNECTION_OBJECT apConn, chip::System::PacketBuffe uint8_t * buffer = nullptr; size_t len = 0; - VerifyOrExit(apBuf != nullptr, ChipLogProgress(DeviceLayer, "apBuf is NULL in %s", __func__)); + VerifyOrExit(apBuf != nullptr, ChipLogError(DeviceLayer, "apBuf is NULL in %s", __func__)); buffer = apBuf->Start(); len = apBuf->DataLength(); @@ -1487,13 +1485,13 @@ static gboolean BluezDisconnect(void * apClosure) GError * error = nullptr; gboolean success; - VerifyOrExit(conn != nullptr, ChipLogProgress(DeviceLayer, "conn is NULL in %s", __func__)); - VerifyOrExit(conn->mpDevice != nullptr, ChipLogProgress(DeviceLayer, "FAIL: Disconnect: %s", "NULL Device")); + VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "conn is NULL in %s", __func__)); + VerifyOrExit(conn->mpDevice != nullptr, ChipLogError(DeviceLayer, "FAIL: Disconnect: %s", "NULL Device")); - ChipLogProgress(DeviceLayer, "%s peer=%s", __func__, bluez_device1_get_address(conn->mpDevice)); + ChipLogDetail(DeviceLayer, "%s peer=%s", __func__, bluez_device1_get_address(conn->mpDevice)); success = bluez_device1_call_disconnect_sync(conn->mpDevice, nullptr, &error); - VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, "FAIL: Disconnect: %s", error->message)); + VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: Disconnect: %s", error->message)); exit: if (error != nullptr) @@ -1582,7 +1580,7 @@ CHIP_ERROR ConfigureBluezAdv(BLEAdvConfig & aBleAdvConfig, BluezEndpoint * apEnd exit: if (nullptr != msg) { - ChipLogProgress(DeviceLayer, "%s in %s", msg, __func__); + ChipLogDetail(DeviceLayer, "%s in %s", msg, __func__); err = CHIP_ERROR_INCORRECT_STATE; if (apEndpoint->mpChipServiceData != nullptr) { @@ -1601,11 +1599,11 @@ CHIP_ERROR InitBluezBleLayer(bool aIsCentral, char * apBleAddr, BLEAdvConfig & a int tmpErrno; BluezEndpoint * endpoint = nullptr; - VerifyOrExit(pipe2(sBluezFD, O_DIRECT) == 0, ChipLogProgress(DeviceLayer, "FAIL: open pipe in %s", __func__)); + VerifyOrExit(pipe2(sBluezFD, O_DIRECT) == 0, ChipLogError(DeviceLayer, "FAIL: open pipe in %s", __func__)); // initialize server endpoint endpoint = g_new0(BluezEndpoint, 1); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "FAIL: memory allocation in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "FAIL: memory allocation in %s", __func__)); if (apBleAddr != nullptr) endpoint->mpAdapterAddr = g_strdup(apBleAddr); @@ -1622,11 +1620,11 @@ CHIP_ERROR InitBluezBleLayer(bool aIsCentral, char * apBleAddr, BLEAdvConfig & a } sBluezMainLoop = g_main_loop_new(nullptr, FALSE); - VerifyOrExit(sBluezMainLoop != nullptr, ChipLogProgress(DeviceLayer, "FAIL: memory alloc in %s", __func__)); + VerifyOrExit(sBluezMainLoop != nullptr, ChipLogError(DeviceLayer, "FAIL: memory alloc in %s", __func__)); pthreadErr = pthread_create(&sBluezThread, nullptr, BluezMainLoop, endpoint); tmpErrno = errno; - VerifyOrExit(pthreadErr == 0, ChipLogProgress(DeviceLayer, "FAIL: pthread_create (%s) in %s", strerror(tmpErrno), __func__)); + VerifyOrExit(pthreadErr == 0, ChipLogError(DeviceLayer, "FAIL: pthread_create (%s) in %s", strerror(tmpErrno), __func__)); sleep(1); retval = TRUE; @@ -1635,7 +1633,7 @@ CHIP_ERROR InitBluezBleLayer(bool aIsCentral, char * apBleAddr, BLEAdvConfig & a if (retval) { apEndpoint = endpoint; - ChipLogProgress(DeviceLayer, "PlatformBlueZInit init success"); + ChipLogDetail(DeviceLayer, "PlatformBlueZInit init success"); } else { @@ -1655,8 +1653,8 @@ void StartDiscoveryDone(GObject * aObject, GAsyncResult * aResult, gpointer apEn GError * error = nullptr; gboolean success = bluez_adapter1_call_start_discovery_finish(adapter, aResult, &error); - VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, "FAIL: StartDiscovery : %s", error->message)); - ChipLogProgress(DeviceLayer, "StartDiscovery complete"); + VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: StartDiscovery : %s", error->message)); + ChipLogDetail(DeviceLayer, "StartDiscovery complete"); exit: if (error != nullptr) @@ -1668,11 +1666,11 @@ static gboolean StartDiscoveryImpl(void * apDiscoveryTaskArg) DiscoveryTaskArg * taskArg = static_cast(apDiscoveryTaskArg); BluezEndpoint * endpoint; - VerifyOrExit(taskArg != nullptr, ChipLogProgress(DeviceLayer, "taskArg is NULL in %s", __func__)); + VerifyOrExit(taskArg != nullptr, ChipLogError(DeviceLayer, "taskArg is NULL in %s", __func__)); endpoint = taskArg->first; - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); - VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, "mpAdapter is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogError(DeviceLayer, "mpAdapter is NULL in %s", __func__)); endpoint->mDiscoveryRequest = taskArg->second; bluez_adapter1_call_start_discovery(endpoint->mpAdapter, nullptr, StartDiscoveryDone, endpoint); @@ -1707,11 +1705,11 @@ static void StopDiscoveryDone(GObject * aObject, GAsyncResult * aResult, gpointe GError * error = nullptr; gboolean success = bluez_adapter1_call_stop_discovery_finish(adapter, aResult, &error); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); endpoint->mDiscoveryRequest = {}; - VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, "FAIL: StopDiscovery : %s", error->message)); - ChipLogProgress(DeviceLayer, "StopDiscovery complete"); + VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: StopDiscovery : %s", error->message)); + ChipLogDetail(DeviceLayer, "StopDiscovery complete"); exit: if (error != nullptr) @@ -1722,8 +1720,8 @@ static gboolean StopDiscoveryImpl(void * apEndpoint) { BluezEndpoint * endpoint = static_cast(apEndpoint); - VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, "endpoint is NULL in %s", __func__)); - VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, "mpAdapter is NULL in %s", __func__)); + VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogError(DeviceLayer, "mpAdapter is NULL in %s", __func__)); bluez_adapter1_call_stop_discovery(endpoint->mpAdapter, nullptr, StopDiscoveryDone, apEndpoint); @@ -1752,8 +1750,8 @@ static void ConnectDeviceDone(GObject * aObject, GAsyncResult * aResult, gpointe GError * error = nullptr; gboolean success = bluez_device1_call_connect_finish(device, aResult, &error); - VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, "FAIL: ConnectDevice : %s", error->message)); - ChipLogProgress(DeviceLayer, "ConnectDevice complete"); + VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: ConnectDevice : %s", error->message)); + ChipLogDetail(DeviceLayer, "ConnectDevice complete"); exit: if (error != nullptr) @@ -1764,7 +1762,7 @@ static gboolean ConnectDeviceImpl(void * apDevice) { BluezDevice1 * device = static_cast(apDevice); - VerifyOrExit(device != nullptr, ChipLogProgress(DeviceLayer, "device is NULL in %s", __func__)); + VerifyOrExit(device != nullptr, ChipLogError(DeviceLayer, "device is NULL in %s", __func__)); bluez_device1_call_connect(device, nullptr, ConnectDeviceDone, nullptr); diff --git a/src/transport/SecureSessionMgr.cpp b/src/transport/SecureSessionMgr.cpp index b5162a1390bc6a..e3e5d8a17cbee2 100644 --- a/src/transport/SecureSessionMgr.cpp +++ b/src/transport/SecureSessionMgr.cpp @@ -147,7 +147,7 @@ CHIP_ERROR SecureSessionMgrBase::SendMessage(NodeId peerNodeId, System::PacketBu VerifyOrExit(CanCastTo(totalLen + taglen), err = CHIP_ERROR_INTERNAL); msgBuf->SetDataLength(static_cast(totalLen + taglen), nullptr); - ChipLogProgress(Inet, "Secure transport transmitting msg %u after encryption", state->GetSendMessageIndex()); + ChipLogDetail(Inet, "Secure transport transmitting msg %u after encryption", state->GetSendMessageIndex()); err = mTransport->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), state->GetPeerAddress(), msgBuf); msgBuf = nullptr; @@ -161,11 +161,11 @@ CHIP_ERROR SecureSessionMgrBase::SendMessage(NodeId peerNodeId, System::PacketBu const char * errStr = ErrorStr(err); if (state == nullptr) { - ChipLogProgress(Inet, "Secure transport could not find a valid PeerConnection: %s", errStr); + ChipLogError(Inet, "Secure transport could not find a valid PeerConnection: %s", errStr); } else { - ChipLogProgress(Inet, "Secure transport failed to encrypt msg %u: %s", state->GetSendMessageIndex(), errStr); + ChipLogError(Inet, "Secure transport failed to encrypt msg %u: %s", state->GetSendMessageIndex(), errStr); } PacketBuffer::Free(msgBuf); msgBuf = nullptr; @@ -189,7 +189,7 @@ CHIP_ERROR SecureSessionMgrBase::NewPairing(const OptionalmPeerConnections.FindPeerConnectionState(packetHeader.GetSourceNodeId(), packetHeader.GetEncryptionKeyID(), &state)) { - ChipLogProgress(Inet, "Data received on an unknown connection (%d). Dropping it!!", packetHeader.GetEncryptionKeyID()); + ChipLogError(Inet, "Data received on an unknown connection (%d). Dropping it!!", packetHeader.GetEncryptionKeyID()); ExitNow(err = CHIP_ERROR_KEY_NOT_FOUND_FROM_PEER); } @@ -273,18 +273,16 @@ void SecureSessionMgrBase::HandleDataReceived(const PacketHeader & packetHeader, // TODO: We need length checks here! https://github.com/project-chip/connectedhomeip/issues/2928 err = mac.Decode(packetHeader, &data[packetHeader.GetPayloadLength()], kMaxTagLen, &taglen); - VerifyOrExit(err == CHIP_NO_ERROR, ChipLogProgress(Inet, "Secure transport failed to decode MAC Tag: err %d", err)); + VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Inet, "Secure transport failed to decode MAC Tag: err %d", err)); len = static_cast(len - taglen); msg->SetDataLength(len, nullptr); err = state->GetSecureSession().Decrypt(data, len, plainText, packetHeader, payloadHeader.GetEncodePacketFlags(), mac); - VerifyOrExit(err == CHIP_NO_ERROR, ChipLogProgress(Inet, "Secure transport failed to decrypt msg: err %d", err)); + VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Inet, "Secure transport failed to decrypt msg: err %d", err)); err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, headerSize, &decodedSize); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogProgress(Inet, "Secure transport failed to decode encrypted header: err %d", err)); - VerifyOrExit(headerSize == decodedSize, - ChipLogProgress(Inet, "Secure transport decode encrypted header length mismatched")); + VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Inet, "Secure transport failed to decode encrypted header: err %d", err)); + VerifyOrExit(headerSize == decodedSize, ChipLogError(Inet, "Secure transport decode encrypted header length mismatched")); msg->ConsumeHead(headerSize); @@ -322,7 +320,7 @@ void SecureSessionMgrBase::HandleConnectionExpired(const Transport::PeerConnecti char addr[Transport::PeerAddress::kMaxToStringSize]; state.GetPeerAddress().ToString(addr, sizeof(addr)); - ChipLogProgress(Inet, "Connection from '%s' expired", addr); + ChipLogDetail(Inet, "Connection from '%s' expired", addr); mgr->mTransport->Disconnect(state.GetPeerAddress()); } From 0e466b7715dceb455f92ef406aafa14a28ff97e8 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Tue, 13 Oct 2020 17:05:06 +0200 Subject: [PATCH 05/40] Activate log filtering by default on Darwin platforms (#3211) --- src/platform/Darwin/CHIPPlatformConfig.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/platform/Darwin/CHIPPlatformConfig.h b/src/platform/Darwin/CHIPPlatformConfig.h index 1efde6c4d92aed..1f60ec9b9ef6fb 100644 --- a/src/platform/Darwin/CHIPPlatformConfig.h +++ b/src/platform/Darwin/CHIPPlatformConfig.h @@ -85,7 +85,7 @@ #endif // CHIP_CONFIG_RMP_TIMER_DEFAULT_PERIOD #ifndef CHIP_LOG_FILTERING -#define CHIP_LOG_FILTERING 0 +#define CHIP_LOG_FILTERING 1 #endif // CHIP_LOG_FILTERING #ifndef CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS From c436fc64fc4b373e86adf9b129ed7c80182aee60 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Tue, 13 Oct 2020 17:05:28 +0200 Subject: [PATCH 06/40] [Darwin] Replace ChipLogProgress -> ChipLogDetail in BLEManagerImpl.cpp (#3213) --- src/platform/Darwin/BLEManagerImpl.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/platform/Darwin/BLEManagerImpl.cpp b/src/platform/Darwin/BLEManagerImpl.cpp index a705508ef61a91..61b70cb75da2d8 100644 --- a/src/platform/Darwin/BLEManagerImpl.cpp +++ b/src/platform/Darwin/BLEManagerImpl.cpp @@ -46,7 +46,7 @@ CHIP_ERROR BLEManagerImpl::_Init() { CHIP_ERROR err; - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); // Initialize the Chip BleLayer. BleApplicationDelegateImpl * appDelegate = new BleApplicationDelegateImpl(); @@ -58,55 +58,55 @@ CHIP_ERROR BLEManagerImpl::_Init() ConnectivityManager::CHIPoBLEServiceMode BLEManagerImpl::_GetCHIPoBLEServiceMode(void) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); return ConnectivityManager::kCHIPoBLEServiceMode_NotSupported; } CHIP_ERROR BLEManagerImpl::_SetCHIPoBLEServiceMode(ConnectivityManager::CHIPoBLEServiceMode val) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } bool BLEManagerImpl::_IsAdvertisingEnabled(void) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); return false; } CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } bool BLEManagerImpl::_IsFastAdvertisingEnabled(void) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); return false; } CHIP_ERROR BLEManagerImpl::_SetFastAdvertisingEnabled(bool val) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } bool BLEManagerImpl::_IsAdvertising(void) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); return false; } CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } @@ -117,13 +117,13 @@ BleLayer * BLEManagerImpl::_GetBleLayer() uint16_t BLEManagerImpl::_NumConnections(void) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); return 0; } void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) { - ChipLogProgress(DeviceLayer, "%s", __FUNCTION__); + ChipLogDetail(DeviceLayer, "%s", __FUNCTION__); } } // namespace Internal From bd23276548c9beb1f47ebea359d684c467ea4772 Mon Sep 17 00:00:00 2001 From: Pankaj Garg Date: Tue, 13 Oct 2020 08:08:10 -0700 Subject: [PATCH 07/40] Implement DevicePairingDelegate in CHIPTool iOS framework (#3156) * Implement DevicePairingDelegate in CHIPTool iOS framework * Address review comments * Address review comment * Fix restyle error --- .../DeviceNetworkProvisioningDelegate.cpp | 8 +- .../esp32/main/RendezvousMessageHandler.cpp | 4 +- .../server/esp32/main/ServiceProvisioning.cpp | 4 +- .../esp32/main/include/ServiceProvisioning.h | 25 ++++ src/controller/CHIPDeviceController.cpp | 14 -- src/controller/CHIPDeviceController.h | 9 -- .../QRCode/QRCodeViewController.h | 3 +- .../QRCode/QRCodeViewController.m | 7 + .../Framework/CHIP.xcodeproj/project.pbxproj | 12 ++ src/darwin/Framework/CHIP/CHIP.h | 1 + .../Framework/CHIP/CHIPDeviceController.h | 11 +- .../Framework/CHIP/CHIPDeviceController.mm | 44 +++--- .../CHIP/CHIPDevicePairingDelegate.h | 66 +++++++++ .../CHIP/CHIPDevicePairingDelegateBridge.h | 54 ++++++++ .../CHIP/CHIPDevicePairingDelegateBridge.mm | 125 ++++++++++++++++++ src/transport/NetworkProvisioning.cpp | 2 +- 16 files changed, 333 insertions(+), 56 deletions(-) create mode 100644 examples/wifi-echo/server/esp32/main/include/ServiceProvisioning.h create mode 100644 src/darwin/Framework/CHIP/CHIPDevicePairingDelegate.h create mode 100644 src/darwin/Framework/CHIP/CHIPDevicePairingDelegateBridge.h create mode 100644 src/darwin/Framework/CHIP/CHIPDevicePairingDelegateBridge.mm diff --git a/examples/wifi-echo/server/esp32/main/DeviceNetworkProvisioningDelegate.cpp b/examples/wifi-echo/server/esp32/main/DeviceNetworkProvisioningDelegate.cpp index 8821907e5727d0..38178b0d68f379 100644 --- a/examples/wifi-echo/server/esp32/main/DeviceNetworkProvisioningDelegate.cpp +++ b/examples/wifi-echo/server/esp32/main/DeviceNetworkProvisioningDelegate.cpp @@ -15,12 +15,14 @@ * limitations under the License. */ -#include "DeviceNetworkProvisioningDelegate.h" #include +#include "DeviceNetworkProvisioningDelegate.h" +#include "ServiceProvisioning.h" + using namespace ::chip; -void ESP32NetworkProvisioningDelegate::ProvisionNetwork(const char * ssid, const char * passwd) +void ESP32NetworkProvisioningDelegate::ProvisionNetwork(const char * ssid, const char * key) { - ChipLogProgress(NetworkProvisioning, "ESP32NetworkProvisioningDelegate: Received SSID and passwd\n"); + ChipLogProgress(NetworkProvisioning, "ESP32NetworkProvisioningDelegate: SSID: %s, key: %s", ssid, key); } diff --git a/examples/wifi-echo/server/esp32/main/RendezvousMessageHandler.cpp b/examples/wifi-echo/server/esp32/main/RendezvousMessageHandler.cpp index 32935d470ade61..35ca5e95f45997 100644 --- a/examples/wifi-echo/server/esp32/main/RendezvousMessageHandler.cpp +++ b/examples/wifi-echo/server/esp32/main/RendezvousMessageHandler.cpp @@ -21,9 +21,9 @@ #include #include -using namespace ::chip; +#include "ServiceProvisioning.h" -extern CHIP_ERROR SetWiFiStationProvisioning(char * ssid, char * key); +using namespace ::chip; CHIP_ERROR RendezvousMessageHandler::HandleMessageReceived(System::PacketBuffer * buffer) { diff --git a/examples/wifi-echo/server/esp32/main/ServiceProvisioning.cpp b/examples/wifi-echo/server/esp32/main/ServiceProvisioning.cpp index fc01e9bb21b015..56ef140c14797e 100644 --- a/examples/wifi-echo/server/esp32/main/ServiceProvisioning.cpp +++ b/examples/wifi-echo/server/esp32/main/ServiceProvisioning.cpp @@ -21,9 +21,11 @@ #include "esp_wifi.h" +#include "ServiceProvisioning.h" + using namespace ::chip::DeviceLayer; -CHIP_ERROR SetWiFiStationProvisioning(char * ssid, char * key) +CHIP_ERROR SetWiFiStationProvisioning(const char * ssid, const char * key) { ConnectivityMgr().SetWiFiStationMode(ConnectivityManager::kWiFiStationMode_Disabled); diff --git a/examples/wifi-echo/server/esp32/main/include/ServiceProvisioning.h b/examples/wifi-echo/server/esp32/main/include/ServiceProvisioning.h new file mode 100644 index 00000000000000..7ab80a09b0dad7 --- /dev/null +++ b/examples/wifi-echo/server/esp32/main/include/ServiceProvisioning.h @@ -0,0 +1,25 @@ +/* + * + * Copyright (c) 2020 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. + */ + +#ifndef _SERVICE_PROVISIONING_H +#define _SERVICE_PROVISIONING_H + +#include + +CHIP_ERROR SetWiFiStationProvisioning(const char * ssid, const char * key); + +#endif // _SERVICE_PROVISIONING_H diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 4bcec1a6136215..27247931680e6b 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -319,20 +319,6 @@ CHIP_ERROR ChipDeviceController::ResumeSecureSession() return err; } -CHIP_ERROR ChipDeviceController::PopulatePeerAddress(Transport::PeerAddress & peerAddress) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit(IsSecurelyConnected(), err = CHIP_ERROR_INCORRECT_STATE); - - peerAddress.SetIPAddress(mDeviceAddr); - peerAddress.SetPort(mDevicePort); - peerAddress.SetTransportType(Transport::Type::kUdp); - -exit: - return err; -} - bool ChipDeviceController::IsConnected() { return mState == kState_Initialized && diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index e2510a5ede7055..ef6b129da19c97 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -158,15 +158,6 @@ class DLL_EXPORT ChipDeviceController : public SecureSessionMgrDelegate, public ErrorHandler onError, uint16_t devicePort = CHIP_PORT, Inet::InterfaceId interfaceId = INET_NULL_INTERFACEID); - /** - * @brief - * Get the PeerAddress of a connected peer - * - * @param[in,out] peerAddress The PeerAddress object which will be populated with the details of the connected peer - * @return CHIP_ERROR An error if there's no active connection - */ - CHIP_ERROR PopulatePeerAddress(Transport::PeerAddress & peerAddress); - /** * @brief * Disconnect from a connected device diff --git a/src/darwin/CHIPTool/CHIPTool/View Controllers/QRCode/QRCodeViewController.h b/src/darwin/CHIPTool/CHIPTool/View Controllers/QRCode/QRCodeViewController.h index 2d95369ea19053..127098305c7810 100644 --- a/src/darwin/CHIPTool/CHIPTool/View Controllers/QRCode/QRCodeViewController.h +++ b/src/darwin/CHIPTool/CHIPTool/View Controllers/QRCode/QRCodeViewController.h @@ -19,6 +19,7 @@ #import #import -@interface QRCodeViewController : UIViewController +@interface QRCodeViewController + : UIViewController @end diff --git a/src/darwin/CHIPTool/CHIPTool/View Controllers/QRCode/QRCodeViewController.m b/src/darwin/CHIPTool/CHIPTool/View Controllers/QRCode/QRCodeViewController.m index 2607493576bfb6..52a8f692c74f5f 100644 --- a/src/darwin/CHIPTool/CHIPTool/View Controllers/QRCode/QRCodeViewController.m +++ b/src/darwin/CHIPTool/CHIPTool/View Controllers/QRCode/QRCodeViewController.m @@ -257,6 +257,7 @@ - (void)viewDidLoad dispatch_queue_t callbackQueue = dispatch_queue_create("com.zigbee.chip.qrcodevc.callback", DISPATCH_QUEUE_SERIAL); self.chipController = [CHIPDeviceController sharedController]; [self.chipController setDelegate:self queue:callbackQueue]; + [self.chipController setPairingDelegate:self queue:callbackQueue]; UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)]; [self.view addGestureRecognizer:tap]; @@ -283,6 +284,12 @@ - (void)deviceControllerOnMessage:(nonnull NSData *)message { } +// MARK: CHIPDevicePairingDelegate +- (void)onNetworkCredentialsRequested:(SendNetworkCredentials)handler +{ + NSLog(@"Network credential requested for pairing"); +} + // MARK: UI Helper methods - (void)manualCodeInitialState diff --git a/src/darwin/Framework/CHIP.xcodeproj/project.pbxproj b/src/darwin/Framework/CHIP.xcodeproj/project.pbxproj index fbd5abc83f4b08..8d8a347d8ca514 100644 --- a/src/darwin/Framework/CHIP.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/CHIP.xcodeproj/project.pbxproj @@ -8,6 +8,9 @@ /* Begin PBXBuildFile section */ 2C4DF09E248B2C60009307CB /* libmbedtls.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 2C4DF09D248B2C60009307CB /* libmbedtls.a */; settings = {ATTRIBUTES = (Required, ); }; }; + 2CB7163B252E8A7B0026E2BB /* CHIPDevicePairingDelegateBridge.h in Headers */ = {isa = PBXBuildFile; fileRef = 2CB71638252E8A7B0026E2BB /* CHIPDevicePairingDelegateBridge.h */; }; + 2CB7163C252E8A7C0026E2BB /* CHIPDevicePairingDelegateBridge.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2CB71639252E8A7B0026E2BB /* CHIPDevicePairingDelegateBridge.mm */; }; + 2CB7163F252F731E0026E2BB /* CHIPDevicePairingDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 2CB7163E252F731E0026E2BB /* CHIPDevicePairingDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; 515C401C2486BF43004C4DB3 /* CHIPOnOff.mm in Sources */ = {isa = PBXBuildFile; fileRef = 515C401A2486BF43004C4DB3 /* CHIPOnOff.mm */; }; 515C401D2486BF43004C4DB3 /* CHIPOnOff.h in Headers */ = {isa = PBXBuildFile; fileRef = 515C401B2486BF43004C4DB3 /* CHIPOnOff.h */; settings = {ATTRIBUTES = (Public, ); }; }; 991DC0842475F45400C13860 /* CHIPDeviceController.h in Headers */ = {isa = PBXBuildFile; fileRef = 991DC0822475F45400C13860 /* CHIPDeviceController.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -41,6 +44,9 @@ /* Begin PBXFileReference section */ 2C4DF09D248B2C60009307CB /* libmbedtls.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libmbedtls.a; path = lib/libmbedtls.a; sourceTree = BUILT_PRODUCTS_DIR; }; + 2CB71638252E8A7B0026E2BB /* CHIPDevicePairingDelegateBridge.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CHIPDevicePairingDelegateBridge.h; sourceTree = ""; }; + 2CB71639252E8A7B0026E2BB /* CHIPDevicePairingDelegateBridge.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = CHIPDevicePairingDelegateBridge.mm; sourceTree = ""; }; + 2CB7163E252F731E0026E2BB /* CHIPDevicePairingDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CHIPDevicePairingDelegate.h; sourceTree = ""; }; 515C401A2486BF43004C4DB3 /* CHIPOnOff.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = CHIPOnOff.mm; sourceTree = ""; }; 515C401B2486BF43004C4DB3 /* CHIPOnOff.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CHIPOnOff.h; sourceTree = ""; }; 991DC0822475F45400C13860 /* CHIPDeviceController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CHIPDeviceController.h; sourceTree = ""; }; @@ -109,6 +115,9 @@ B202528F2459E34F00F97062 /* CHIP */ = { isa = PBXGroup; children = ( + 2CB7163E252F731E0026E2BB /* CHIPDevicePairingDelegate.h */, + 2CB71638252E8A7B0026E2BB /* CHIPDevicePairingDelegateBridge.h */, + 2CB71639252E8A7B0026E2BB /* CHIPDevicePairingDelegateBridge.mm */, B2E0D7A8245B0B5C003C5B48 /* CHIP.h */, B2E0D7AB245B0B5C003C5B48 /* CHIPError.h */, B2E0D7AA245B0B5C003C5B48 /* CHIPError.mm */, @@ -154,6 +163,8 @@ isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( + 2CB7163B252E8A7B0026E2BB /* CHIPDevicePairingDelegateBridge.h in Headers */, + 2CB7163F252F731E0026E2BB /* CHIPDevicePairingDelegate.h in Headers */, 991DC0842475F45400C13860 /* CHIPDeviceController.h in Headers */, B2E0D7B2245B0B5C003C5B48 /* CHIPManualSetupPayloadParser.h in Headers */, B2E0D7B1245B0B5C003C5B48 /* CHIP.h in Headers */, @@ -286,6 +297,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 2CB7163C252E8A7C0026E2BB /* CHIPDevicePairingDelegateBridge.mm in Sources */, 515C401C2486BF43004C4DB3 /* CHIPOnOff.mm in Sources */, 991DC0892475F47D00C13860 /* CHIPDeviceController.mm in Sources */, B2E0D7B7245B0B5C003C5B48 /* CHIPQRCodeSetupPayloadParser.mm in Sources */, diff --git a/src/darwin/Framework/CHIP/CHIP.h b/src/darwin/Framework/CHIP/CHIP.h index 9ef531bf52d39a..78b9ad3de82c00 100644 --- a/src/darwin/Framework/CHIP/CHIP.h +++ b/src/darwin/Framework/CHIP/CHIP.h @@ -17,6 +17,7 @@ // pull together CHIP headers #import +#import #import #import #import diff --git a/src/darwin/Framework/CHIP/CHIPDeviceController.h b/src/darwin/Framework/CHIP/CHIPDeviceController.h index cf2f4f15e5c579..7270746ebab76f 100644 --- a/src/darwin/Framework/CHIP/CHIPDeviceController.h +++ b/src/darwin/Framework/CHIP/CHIPDeviceController.h @@ -28,6 +28,7 @@ typedef void (^ControllerOnMessageBlock)(NSData * message); typedef void (^ControllerOnErrorBlock)(NSError * error); @protocol CHIPDeviceControllerDelegate; +@protocol CHIPDevicePairingDelegate; @interface AddressInfo : NSObject @@ -43,7 +44,6 @@ typedef void (^ControllerOnErrorBlock)(NSError * error); - (BOOL)connectWithoutSecurePairing:(NSString *)ipAddress error:(NSError * __autoreleasing *)error __attribute__((deprecated("Available until Rendezvous is fully integrated"))); -- (nullable AddressInfo *)getAddressInfo; - (BOOL)sendMessage:(NSData *)message error:(NSError * __autoreleasing *)error; - (BOOL)sendOnCommand; - (BOOL)sendOffCommand; @@ -80,6 +80,15 @@ typedef void (^ControllerOnErrorBlock)(NSError * error); */ - (void)setDelegate:(id)delegate queue:(dispatch_queue_t)queue; +/** + * Set the Delegate for the Device Pairing as well as the Queue on which the Delegate callbacks will be triggered + * + * @param[in] delegate The delegate the pairing process should use + * + * @param[in] queue The queue on which the callbacks will be delivered + */ +- (void)setPairingDelegate:(id)delegate queue:(dispatch_queue_t)queue; + @end /** diff --git a/src/darwin/Framework/CHIP/CHIPDeviceController.mm b/src/darwin/Framework/CHIP/CHIPDeviceController.mm index f73a177183f9dc..110199a9628dfd 100644 --- a/src/darwin/Framework/CHIP/CHIPDeviceController.mm +++ b/src/darwin/Framework/CHIP/CHIPDeviceController.mm @@ -20,6 +20,7 @@ #include #import "CHIPDeviceController.h" +#import "CHIPDevicePairingDelegateBridge.h" #import "CHIPError.h" #import "CHIPLogging.h" @@ -63,6 +64,7 @@ @interface CHIPDeviceController () */ @property (readonly, nonatomic) dispatch_queue_t delegateQueue; @property (readonly) chip::DeviceController::ChipDeviceController * cppController; +@property (readonly) CHIPDevicePairingDelegateBridge * pairingDelegateBridge; @end @@ -96,10 +98,20 @@ - (instancetype)init return nil; } - if (CHIP_NO_ERROR != _cppController->Init(kLocalDeviceId)) { + _pairingDelegateBridge = new CHIPDevicePairingDelegateBridge(); + if (!_pairingDelegateBridge) { + CHIP_LOG_ERROR("Error: couldn't create pairing delegate"); + delete _cppController; + _cppController = NULL; + return nil; + } + + if (CHIP_NO_ERROR != _cppController->Init(kLocalDeviceId, _pairingDelegateBridge)) { CHIP_LOG_ERROR("Error: couldn't initialize c++ controller"); delete _cppController; _cppController = NULL; + delete _pairingDelegateBridge; + _pairingDelegateBridge = NULL; return nil; } } @@ -240,29 +252,6 @@ - (BOOL)connectWithoutSecurePairing:(NSString *)ipAddress error:(NSError * __aut return YES; } -- (AddressInfo *)getAddressInfo -{ - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Transport::PeerAddress peerAddr = chip::Transport::PeerAddress::Uninitialized(); - [self.lock lock]; - err = self.cppController->PopulatePeerAddress(peerAddr); - [self.lock unlock]; - chip::Inet::IPAddress ipAddr = peerAddr.GetIPAddress(); - uint16_t port = peerAddr.GetPort(); - - if (err != CHIP_NO_ERROR) { - return nil; - } - - // ignore the unused port - (void) port; - // A buffer big enough to hold ipv4 and ipv6 addresses - char ipAddrStr[64]; - ipAddr.ToString(ipAddrStr, sizeof(ipAddrStr)); - NSString * ipAddress = [NSString stringWithUTF8String:ipAddrStr]; - return [[AddressInfo alloc] initWithIP:ipAddress]; -} - - (BOOL)sendMessage:(NSData *)message error:(NSError * __autoreleasing *)error { CHIP_ERROR err = CHIP_NO_ERROR; @@ -462,4 +451,11 @@ - (void)setDelegate:(id)delegate queue:(dispatch_q [self.lock unlock]; } +- (void)setPairingDelegate:(id)delegate queue:(dispatch_queue_t)queue +{ + [self.lock lock]; + _pairingDelegateBridge->setDelegate(delegate, queue); + [self.lock unlock]; +} + @end diff --git a/src/darwin/Framework/CHIP/CHIPDevicePairingDelegate.h b/src/darwin/Framework/CHIP/CHIPDevicePairingDelegate.h new file mode 100644 index 00000000000000..0bf9e90dcac493 --- /dev/null +++ b/src/darwin/Framework/CHIP/CHIPDevicePairingDelegate.h @@ -0,0 +1,66 @@ +/** + * + * Copyright (c) 2020 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 "CHIPError.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^SendNetworkCredentials)(NSString * ssid, NSString * password); + +typedef NS_ENUM(NSUInteger, PairingStatus) { + kSecurePairingSuccess = 0, + kSecurePairingFailed, + kNetworkProvisioningSuccess, + kNetworkProvisioningFailed, + kUnknownStatus, +}; + +/** + * The protocol definition for the CHIPDevicePairingDelegate + * + * All delegate methods will be called on the supplied Delegate Queue. + */ +@protocol CHIPDevicePairingDelegate +@required +/** + * Notify the delegate when pairing requires network credentials + * + */ +- (void)onNetworkCredentialsRequested:(SendNetworkCredentials)handler; + +@optional +/** + * Notify the delegate when pairing status gets updated + * + */ +- (void)onStatusUpdate:(PairingStatus)status; + +/** + * Notify the delegate when pairing is completed + * + */ +- (void)onPairingComplete:(NSError *)error; + +/** + * Notify the delegate when pairing is deleted + * + */ +- (void)onPairingDeleted:(NSError *)error; +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/CHIPDevicePairingDelegateBridge.h b/src/darwin/Framework/CHIP/CHIPDevicePairingDelegateBridge.h new file mode 100644 index 00000000000000..b448c06b5e94dc --- /dev/null +++ b/src/darwin/Framework/CHIP/CHIPDevicePairingDelegateBridge.h @@ -0,0 +1,54 @@ +/** + * + * Copyright (c) 2020 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 "CHIPDevicePairingDelegate.h" +#import + +#include + +NS_ASSUME_NONNULL_BEGIN + +class CHIPDevicePairingDelegateBridge : public chip::DeviceController::DevicePairingDelegate +{ +public: + CHIPDevicePairingDelegateBridge(); + ~CHIPDevicePairingDelegateBridge(); + + void setDelegate(id delegate, dispatch_queue_t queue); + + void OnStatusUpdate(chip::RendezvousSessionDelegate::Status status) override; + + void OnNetworkCredentialsRequested(chip::RendezvousDeviceCredentialsDelegate * callback) override; + + void OnOperationalCredentialsRequested(const char * csr, size_t csr_length, + chip::RendezvousDeviceCredentialsDelegate * callback) override; + + void OnPairingComplete(CHIP_ERROR error) override; + + void OnPairingDeleted(CHIP_ERROR error) override; + +private: + id mDelegate; + dispatch_queue_t mQueue; + + SendNetworkCredentials mHandler; + chip::RendezvousDeviceCredentialsDelegate * mCallback; + + PairingStatus MapStatus(chip::RendezvousSessionDelegate::Status status); +}; + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/CHIPDevicePairingDelegateBridge.mm b/src/darwin/Framework/CHIP/CHIPDevicePairingDelegateBridge.mm new file mode 100644 index 00000000000000..fccf571ba52b98 --- /dev/null +++ b/src/darwin/Framework/CHIP/CHIPDevicePairingDelegateBridge.mm @@ -0,0 +1,125 @@ +/** + * + * Copyright (c) 2020 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 "CHIPDevicePairingDelegateBridge.h" +#import + +CHIPDevicePairingDelegateBridge::CHIPDevicePairingDelegateBridge(void) + : mDelegate(nil) +{ +} + +CHIPDevicePairingDelegateBridge::~CHIPDevicePairingDelegateBridge(void) {} + +void CHIPDevicePairingDelegateBridge::setDelegate(id delegate, dispatch_queue_t queue) +{ + if (delegate && queue) { + mDelegate = delegate; + mQueue = queue; + } else { + mDelegate = nil; + mQueue = nil; + } +} + +PairingStatus CHIPDevicePairingDelegateBridge::MapStatus(chip::RendezvousSessionDelegate::Status status) +{ + PairingStatus rv = kUnknownStatus; + switch (status) { + case chip::RendezvousSessionDelegate::Status::SecurePairingSuccess: + rv = kSecurePairingSuccess; + break; + case chip::RendezvousSessionDelegate::Status::SecurePairingFailed: + rv = kSecurePairingFailed; + break; + case chip::RendezvousSessionDelegate::Status::NetworkProvisioningSuccess: + rv = kNetworkProvisioningSuccess; + break; + case chip::RendezvousSessionDelegate::Status::NetworkProvisioningFailed: + rv = kNetworkProvisioningFailed; + break; + } + return rv; +} + +void CHIPDevicePairingDelegateBridge::OnStatusUpdate(chip::RendezvousSessionDelegate::Status status) +{ + NSLog(@"DevicePairingDelegate status updated: %d", status); + + id strongDelegate = mDelegate; + if ([strongDelegate respondsToSelector:@selector(onStatusUpdate:)]) { + if (strongDelegate && mQueue) { + PairingStatus pairingStatus = MapStatus(status); + dispatch_async(mQueue, ^{ + [strongDelegate onStatusUpdate:pairingStatus]; + }); + } + } +} + +void CHIPDevicePairingDelegateBridge::OnNetworkCredentialsRequested(chip::RendezvousDeviceCredentialsDelegate * callback) +{ + NSLog(@"DevicePairingDelegate Requesting network credentials"); + + mCallback = callback; + mHandler = ^(NSString * ssid, NSString * passwd) { + mCallback->SendNetworkCredentials([ssid UTF8String], [passwd UTF8String]); + }; + + id strongDelegate = mDelegate; + if (strongDelegate && mQueue) { + dispatch_async(mQueue, ^{ + [strongDelegate onNetworkCredentialsRequested:mHandler]; + }); + } +} + +void CHIPDevicePairingDelegateBridge::OnOperationalCredentialsRequested( + const char * csr, size_t csr_length, chip::RendezvousDeviceCredentialsDelegate * callback) +{ + NSLog(@"DevicePairingDelegate Requesting operational credentials"); +} + +void CHIPDevicePairingDelegateBridge::OnPairingComplete(CHIP_ERROR error) +{ + NSLog(@"DevicePairingDelegate Pairing complete. Status %d", error); + + id strongDelegate = mDelegate; + if ([strongDelegate respondsToSelector:@selector(onPairingComplete:)]) { + if (strongDelegate && mQueue) { + dispatch_async(mQueue, ^{ + NSError * nsError = [CHIPError errorForCHIPErrorCode:error]; + [strongDelegate onPairingComplete:nsError]; + }); + } + } +} + +void CHIPDevicePairingDelegateBridge::OnPairingDeleted(CHIP_ERROR error) +{ + NSLog(@"DevicePairingDelegate Pairing deleted. Status %d", error); + + id strongDelegate = mDelegate; + if ([strongDelegate respondsToSelector:@selector(onPairingDeleted:)]) { + if (strongDelegate && mQueue) { + dispatch_async(mQueue, ^{ + NSError * nsError = [CHIPError errorForCHIPErrorCode:error]; + [strongDelegate onPairingDeleted:nsError]; + }); + } + } +} diff --git a/src/transport/NetworkProvisioning.cpp b/src/transport/NetworkProvisioning.cpp index b7f19a77eb56ba..3f92caf5a8c6f0 100644 --- a/src/transport/NetworkProvisioning.cpp +++ b/src/transport/NetworkProvisioning.cpp @@ -205,7 +205,7 @@ CHIP_ERROR NetworkProvisioning::SendNetworkCredentials(const char * ssid, const { CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBuffer * buffer = System::PacketBuffer::New(); - BufBound bbuf(buffer->Start(), buffer->TotalLength()); + BufBound bbuf(buffer->Start(), buffer->AvailableDataLength()); ChipLogProgress(NetworkProvisioning, "Sending Network Creds. Delegate %p\n", mDelegate); VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE); From cafa77f97a4fb483a26312d003aee0043220f67a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Duda?= Date: Tue, 13 Oct 2020 17:08:46 +0200 Subject: [PATCH 08/40] [nrfconnect] Remove section about RTT logging in the documentation (#3203) --- examples/lighting-app/nrfconnect/README.md | 48 ---------------------- examples/lock-app/nrfconnect/README.md | 45 -------------------- 2 files changed, 93 deletions(-) diff --git a/examples/lighting-app/nrfconnect/README.md b/examples/lighting-app/nrfconnect/README.md index 7fc4f010d3ea5b..190cebc74a0054 100644 --- a/examples/lighting-app/nrfconnect/README.md +++ b/examples/lighting-app/nrfconnect/README.md @@ -15,7 +15,6 @@ An example application showing the use - [Configuring the example](#configuring-the-example) - [Flashing and debugging](#flashing-and-debugging) - [Accessing the command line](#accessing-the-command-line) - - [Viewing Logging Output](#viewing-logging-output)
@@ -259,50 +258,3 @@ The UART interface is configured for `115200` baud rate. All OpenThread commands must be prefixed with `ot`, for example `ot thread start`. - - - -## Viewing Logging Output - -The example application is built to use the SEGGER Real Time Transfer (RTT) -facility for log output. RTT is a feature built-in to the J-Link Interface MCU -on the development kit board. It allows bi-directional communication with an -embedded application without the need for a dedicated UART. - -Using the RTT facility requires downloading and installing the _SEGGER J-Link -Software and Documentation Pack_ -([web site](https://www.segger.com/downloads/jlink#J-LinkSoftwareAndDocumentationPack)). - -- Download the J-Link installer by navigating to the appropriate URL and - agreeing to the license agreement. - -

Linux: JLink_Linux_x86_64.deb

-

MacOS: JLink_MacOSX.pkg

- -- Install the J-Link software - - $ cd ~/Downloads - $ sudo dpkg -i JLink_Linux_V*_x86_64.deb - -* In Linux, grant the logged in user the ability to talk to the development - hardware via the linux tty device (/dev/ttyACMx) by adding them to the - dialout group. - - $ sudo usermod -a -G dialout ${USER} - -Once the above is complete, log output can be viewed using the JLinkExe tool in -combination with JLinkRTTClient as follows: - -- Run the JLinkExe tool with arguments to autoconnect to the nRF82480 DK - board: - - $ JLinkExe -device NRF52840_XXAA -if SWD -speed 4000 -autoconnect 1 - -- In a second terminal, run the JLinkRTTClient: - - $ JLinkRTTClient - -Logging output will appear in the second terminal. - -An alternate method for viewing log output is to use the J-Link GDB server -described in the following section. diff --git a/examples/lock-app/nrfconnect/README.md b/examples/lock-app/nrfconnect/README.md index b5e09783bfd20b..c6f7fd30eac654 100644 --- a/examples/lock-app/nrfconnect/README.md +++ b/examples/lock-app/nrfconnect/README.md @@ -15,7 +15,6 @@ An example application showing the use - [Configuring the example](#configuring-the-example) - [Flashing and debugging](#flashing-and-debugging) - [Accessing the command line](#accessing-the-command-line) - - [Viewing Logging Output](#viewing-logging-output)
@@ -263,47 +262,3 @@ The UART interface is configured for `115200` baud rate. All OpenThread commands must be prefixed with `ot`, for example `ot thread start`. - - - -## Viewing Logging Output - -The example application is built to use the SEGGER Real Time Transfer (RTT) -facility for log output. RTT is a feature built-in to the J-Link Interface MCU -on the development kit board. It allows bi-directional communication with an -embedded application without the need for a dedicated UART. - -Using the RTT facility requires downloading and installing the _SEGGER J-Link -Software and Documentation Pack_ -([web site](https://www.segger.com/downloads/jlink#J-LinkSoftwareAndDocumentationPack)). - -- Download the J-Link installer by navigating to the appropriate URL and - agreeing to the license agreement. - -

Linux: JLink_Linux_x86_64.deb

-

MacOS: JLink_MacOSX.pkg

- -- Install the J-Link software - - $ cd ~/Downloads - $ sudo dpkg -i JLink_Linux_V*_x86_64.deb - -* In Linux, grant the logged in user the ability to talk to the development - hardware via the linux tty device (/dev/ttyACMx) by adding them to the - dialout group. - - $ sudo usermod -a -G dialout ${USER} - -Once the above is complete, log output can be viewed using the JLinkExe tool in -combination with JLinkRTTClient as follows: - -- Run the JLinkExe tool with arguments to autoconnect to the nRF82480 DK - board: - - $ JLinkExe -device NRF52840_XXAA -if SWD -speed 4000 -autoconnect 1 - -- In a second terminal, run the JLinkRTTClient: - - $ JLinkRTTClient - -Logging output will appear in the second terminal. From 8c0e93b1aef343c649257f6eed32be13237b0e98 Mon Sep 17 00:00:00 2001 From: Michael Spang Date: Tue, 13 Oct 2020 11:23:13 -0400 Subject: [PATCH 09/40] Rename ipp files to cpp (#3199) Using the non-standard extension ".ipp" breaks tools. Rename these files to .cpp as they are in fact the definitions corresponding to the header file of the same name. It should be possible to compile them separately, however that's not done here. --- ...pp => GenericConfigurationManagerImpl.cpp} | 6 +- ...=> GenericConnectivityManagerImpl_BLE.cpp} | 10 +- ...GenericConnectivityManagerImpl_Thread.cpp} | 8 +- ...> GenericConnectivityManagerImpl_WiFi.cpp} | 9 +- ... GenericNetworkProvisioningServerImpl.cpp} | 6 +- ...mpl.ipp => GenericPlatformManagerImpl.cpp} | 6 +- ...> GenericPlatformManagerImpl_FreeRTOS.cpp} | 8 +- ...p => GenericPlatformManagerImpl_POSIX.cpp} | 8 +- ... => GenericPlatformManagerImpl_Zephyr.cpp} | 8 +- ...p => GenericSoftwareUpdateManagerImpl.cpp} | 340 +++++++++--------- ... GenericSoftwareUpdateManagerImpl_BDX.cpp} | 119 +++--- .../Darwin/ConfigurationManagerImpl.cpp | 2 +- .../Darwin/ConnectivityManagerImpl.cpp | 4 +- src/platform/Darwin/PlatformManagerImpl.cpp | 2 +- .../EFR32/ConfigurationManagerImpl.cpp | 2 +- .../EFR32/ConnectivityManagerImpl.cpp | 4 +- .../EFR32/NetworkProvisioningServerImpl.cpp | 2 +- src/platform/EFR32/PlatformManagerImpl.cpp | 2 +- .../EFR32/SoftwareUpdateManagerImpl.cpp | 4 +- src/platform/EFR32/ThreadStackManagerImpl.cpp | 4 +- .../ESP32/ConfigurationManagerImpl.cpp | 2 +- .../ESP32/ConnectivityManagerImpl.cpp | 2 +- .../ESP32/NetworkProvisioningServerImpl.cpp | 2 +- src/platform/ESP32/PlatformManagerImpl.cpp | 2 +- .../ESP32/SoftwareUpdateManagerImpl.cpp | 4 +- ...enericThreadStackManagerImpl_FreeRTOS.cpp} | 0 .../K32W/ConfigurationManagerImpl.cpp | 2 +- src/platform/K32W/ConnectivityManagerImpl.cpp | 4 +- .../K32W/NetworkProvisioningServerImpl.cpp | 2 +- src/platform/K32W/PlatformManagerImpl.cpp | 2 +- .../K32W/SoftwareUpdateManagerImpl.cpp | 4 +- src/platform/K32W/ThreadStackManagerImpl.cpp | 4 +- .../Linux/ConfigurationManagerImpl.cpp | 2 +- .../Linux/ConnectivityManagerImpl.cpp | 6 +- src/platform/Linux/PlatformManagerImpl.cpp | 2 +- ...ericThreadStackManagerImpl_OpenThread.cpp} | 0 ...hreadStackManagerImpl_OpenThread_LwIP.cpp} | 2 +- src/platform/README.md | 12 +- ...r.ipp => GenericBLEManagerImpl_Zephyr.cpp} | 0 ... GenericThreadStackManagerImpl_Zephyr.cpp} | 2 +- .../nRF5/ConfigurationManagerImpl.cpp | 4 +- src/platform/nRF5/ConnectivityManagerImpl.cpp | 4 +- src/platform/nRF5/PlatformManagerImpl.cpp | 2 +- .../nRF5/SoftwareUpdateManagerImpl.cpp | 2 +- src/platform/nRF5/ThreadStackManagerImpl.cpp | 4 +- src/platform/nrfconnect/BLEManagerImpl.cpp | 2 +- .../nrfconnect/ConfigurationManagerImpl.cpp | 4 +- .../nrfconnect/ConnectivityManagerImpl.cpp | 4 +- .../nrfconnect/PlatformManagerImpl.cpp | 2 +- .../nrfconnect/ThreadStackManagerImpl.cpp | 2 +- .../qpg6100/ConfigurationManagerImpl.cpp | 4 +- .../qpg6100/ConnectivityManagerImpl.cpp | 4 +- src/platform/qpg6100/PlatformManagerImpl.cpp | 2 +- .../qpg6100/SoftwareUpdateManagerImpl.cpp | 2 +- .../qpg6100/ThreadStackManagerImpl.cpp | 4 +- 55 files changed, 325 insertions(+), 331 deletions(-) rename src/include/platform/internal/{GenericConfigurationManagerImpl.ipp => GenericConfigurationManagerImpl.cpp} (99%) rename src/include/platform/internal/{GenericConnectivityManagerImpl_BLE.ipp => GenericConnectivityManagerImpl_BLE.cpp} (90%) rename src/include/platform/internal/{GenericConnectivityManagerImpl_Thread.ipp => GenericConnectivityManagerImpl_Thread.cpp} (94%) rename src/include/platform/internal/{GenericConnectivityManagerImpl_WiFi.ipp => GenericConnectivityManagerImpl_WiFi.cpp} (87%) rename src/include/platform/internal/{GenericNetworkProvisioningServerImpl.ipp => GenericNetworkProvisioningServerImpl.cpp} (99%) rename src/include/platform/internal/{GenericPlatformManagerImpl.ipp => GenericPlatformManagerImpl.cpp} (98%) rename src/include/platform/internal/{GenericPlatformManagerImpl_FreeRTOS.ipp => GenericPlatformManagerImpl_FreeRTOS.cpp} (97%) rename src/include/platform/internal/{GenericPlatformManagerImpl_POSIX.ipp => GenericPlatformManagerImpl_POSIX.cpp} (97%) rename src/include/platform/internal/{GenericPlatformManagerImpl_Zephyr.ipp => GenericPlatformManagerImpl_Zephyr.cpp} (96%) rename src/include/platform/internal/{GenericSoftwareUpdateManagerImpl.ipp => GenericSoftwareUpdateManagerImpl.cpp} (83%) rename src/include/platform/internal/{GenericSoftwareUpdateManagerImpl_BDX.ipp => GenericSoftwareUpdateManagerImpl_BDX.cpp} (71%) rename src/platform/FreeRTOS/{GenericThreadStackManagerImpl_FreeRTOS.ipp => GenericThreadStackManagerImpl_FreeRTOS.cpp} (100%) rename src/platform/OpenThread/{GenericThreadStackManagerImpl_OpenThread.ipp => GenericThreadStackManagerImpl_OpenThread.cpp} (100%) rename src/platform/OpenThread/{GenericThreadStackManagerImpl_OpenThread_LwIP.ipp => GenericThreadStackManagerImpl_OpenThread_LwIP.cpp} (99%) rename src/platform/Zephyr/{GenericBLEManagerImpl_Zephyr.ipp => GenericBLEManagerImpl_Zephyr.cpp} (100%) rename src/platform/Zephyr/{GenericThreadStackManagerImpl_Zephyr.ipp => GenericThreadStackManagerImpl_Zephyr.cpp} (99%) diff --git a/src/include/platform/internal/GenericConfigurationManagerImpl.ipp b/src/include/platform/internal/GenericConfigurationManagerImpl.cpp similarity index 99% rename from src/include/platform/internal/GenericConfigurationManagerImpl.ipp rename to src/include/platform/internal/GenericConfigurationManagerImpl.cpp index 55fdf44ae3afda..3f907faff2ee13 100644 --- a/src/include/platform/internal/GenericConfigurationManagerImpl.ipp +++ b/src/include/platform/internal/GenericConfigurationManagerImpl.cpp @@ -23,8 +23,8 @@ * GenericConfigurationManagerImpl<> template. */ -#ifndef GENERIC_CONFIGURATION_MANAGER_IMPL_IPP -#define GENERIC_CONFIGURATION_MANAGER_IMPL_IPP +#ifndef GENERIC_CONFIGURATION_MANAGER_IMPL_CPP +#define GENERIC_CONFIGURATION_MANAGER_IMPL_CPP #include #include @@ -1092,4 +1092,4 @@ template class GenericConfigurationManagerImpl; } // namespace DeviceLayer } // namespace chip -#endif // GENERIC_CONFIGURATION_MANAGER_IMPL_IPP +#endif // GENERIC_CONFIGURATION_MANAGER_IMPL_CPP diff --git a/src/include/platform/internal/GenericConnectivityManagerImpl_BLE.ipp b/src/include/platform/internal/GenericConnectivityManagerImpl_BLE.cpp similarity index 90% rename from src/include/platform/internal/GenericConnectivityManagerImpl_BLE.ipp rename to src/include/platform/internal/GenericConnectivityManagerImpl_BLE.cpp index 35e3d697d12ecb..1dc9c5a692e797 100644 --- a/src/include/platform/internal/GenericConnectivityManagerImpl_BLE.ipp +++ b/src/include/platform/internal/GenericConnectivityManagerImpl_BLE.cpp @@ -22,12 +22,11 @@ * for use on platforms that support BLE. */ -#ifndef GENERIC_CONNECTIVITY_MANAGER_IMPL_BLE_IPP -#define GENERIC_CONNECTIVITY_MANAGER_IMPL_BLE_IPP +#ifndef GENERIC_CONNECTIVITY_MANAGER_IMPL_BLE_CPP +#define GENERIC_CONNECTIVITY_MANAGER_IMPL_BLE_CPP #include - namespace chip { namespace DeviceLayer { namespace Internal { @@ -35,7 +34,7 @@ namespace Internal { // Fully instantiate the template class in whatever compilation unit includes this file. template class GenericConnectivityManagerImpl_BLE; -template +template const char * GenericConnectivityManagerImpl_BLE::_CHIPoBLEServiceModeToStr(ConnectivityManager::CHIPoBLEServiceMode mode) { switch (mode) @@ -55,5 +54,4 @@ const char * GenericConnectivityManagerImpl_BLE::_CHIPoBLEServiceMode } // namespace DeviceLayer } // namespace chip - -#endif // GENERIC_CONNECTIVITY_MANAGER_IMPL_BLE_IPP +#endif // GENERIC_CONNECTIVITY_MANAGER_IMPL_BLE_CPP diff --git a/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.ipp b/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.cpp similarity index 94% rename from src/include/platform/internal/GenericConnectivityManagerImpl_Thread.ipp rename to src/include/platform/internal/GenericConnectivityManagerImpl_Thread.cpp index c01ebc24c66e48..62c83513d78280 100644 --- a/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.ipp +++ b/src/include/platform/internal/GenericConnectivityManagerImpl_Thread.cpp @@ -22,8 +22,8 @@ * for use on platforms that support Thread. */ -#ifndef GENERIC_CONNECTIVITY_MANAGER_IMPL_THREAD_IPP -#define GENERIC_CONNECTIVITY_MANAGER_IMPL_THREAD_IPP +#ifndef GENERIC_CONNECTIVITY_MANAGER_IMPL_THREAD_CPP +#define GENERIC_CONNECTIVITY_MANAGER_IMPL_THREAD_CPP #include #include @@ -108,7 +108,7 @@ void GenericConnectivityManagerImpl_Thread::UpdateServiceConnectivity event.Type = DeviceEventType::kServiceConnectivityChange; event.ServiceConnectivityChange.ViaThread.Result = (haveServiceConnectivity) ? kConnectivity_Established : kConnectivity_Lost; - event.ServiceConnectivityChange.Overall.Result = event.ServiceConnectivityChange.ViaThread.Result; + event.ServiceConnectivityChange.Overall.Result = event.ServiceConnectivityChange.ViaThread.Result; PlatformMgr().PostEvent(&event); } } @@ -118,4 +118,4 @@ void GenericConnectivityManagerImpl_Thread::UpdateServiceConnectivity } // namespace DeviceLayer } // namespace chip -#endif // GENERIC_CONNECTIVITY_MANAGER_IMPL_THREAD_IPP +#endif // GENERIC_CONNECTIVITY_MANAGER_IMPL_THREAD_CPP diff --git a/src/include/platform/internal/GenericConnectivityManagerImpl_WiFi.ipp b/src/include/platform/internal/GenericConnectivityManagerImpl_WiFi.cpp similarity index 87% rename from src/include/platform/internal/GenericConnectivityManagerImpl_WiFi.ipp rename to src/include/platform/internal/GenericConnectivityManagerImpl_WiFi.cpp index 0c92c1328fcaff..6d7973d3fbbe87 100644 --- a/src/include/platform/internal/GenericConnectivityManagerImpl_WiFi.ipp +++ b/src/include/platform/internal/GenericConnectivityManagerImpl_WiFi.cpp @@ -21,8 +21,8 @@ * for use on platforms that support WiFi. */ -#ifndef GENERIC_CONNECTIVITY_MANAGER_IMPL_WIFI_IPP -#define GENERIC_CONNECTIVITY_MANAGER_IMPL_WIFI_IPP +#ifndef GENERIC_CONNECTIVITY_MANAGER_IMPL_WIFI_CPP +#define GENERIC_CONNECTIVITY_MANAGER_IMPL_WIFI_CPP #include #include @@ -36,8 +36,7 @@ namespace Internal { template class GenericConnectivityManagerImpl_WiFi; template -const char * -GenericConnectivityManagerImpl_WiFi::_WiFiStationModeToStr(ConnectivityManager::WiFiStationMode mode) +const char * GenericConnectivityManagerImpl_WiFi::_WiFiStationModeToStr(ConnectivityManager::WiFiStationMode mode) { switch (mode) { @@ -64,4 +63,4 @@ bool GenericConnectivityManagerImpl_WiFi::_IsWiFiStationEnabled() } // namespace DeviceLayer } // namespace chip -#endif // GENERIC_CONNECTIVITY_MANAGER_IMPL_WIFI_IPP +#endif // GENERIC_CONNECTIVITY_MANAGER_IMPL_WIFI_CPP diff --git a/src/include/platform/internal/GenericNetworkProvisioningServerImpl.ipp b/src/include/platform/internal/GenericNetworkProvisioningServerImpl.cpp similarity index 99% rename from src/include/platform/internal/GenericNetworkProvisioningServerImpl.ipp rename to src/include/platform/internal/GenericNetworkProvisioningServerImpl.cpp index 3a201575176aa0..ad2ccc435fcccd 100644 --- a/src/include/platform/internal/GenericNetworkProvisioningServerImpl.ipp +++ b/src/include/platform/internal/GenericNetworkProvisioningServerImpl.cpp @@ -23,8 +23,8 @@ * GenericNetworkProvisioningServerImpl<> template. */ -#ifndef GENERIC_NETWORK_PROVISIONING_SERVER_IMPL_IPP -#define GENERIC_NETWORK_PROVISIONING_SERVER_IMPL_IPP +#ifndef GENERIC_NETWORK_PROVISIONING_SERVER_IMPL_CPP +#define GENERIC_NETWORK_PROVISIONING_SERVER_IMPL_CPP #include #include @@ -1100,4 +1100,4 @@ void GenericNetworkProvisioningServerImpl::HandleConnectivityTestTime } // namespace DeviceLayer } // namespace chip -#endif // GENERIC_NETWORK_PROVISIONING_SERVER_IMPL_IPP +#endif // GENERIC_NETWORK_PROVISIONING_SERVER_IMPL_CPP diff --git a/src/include/platform/internal/GenericPlatformManagerImpl.ipp b/src/include/platform/internal/GenericPlatformManagerImpl.cpp similarity index 98% rename from src/include/platform/internal/GenericPlatformManagerImpl.ipp rename to src/include/platform/internal/GenericPlatformManagerImpl.cpp index 1851c864fd56bd..5f766a749e6ad8 100644 --- a/src/include/platform/internal/GenericPlatformManagerImpl.ipp +++ b/src/include/platform/internal/GenericPlatformManagerImpl.cpp @@ -22,8 +22,8 @@ * GenericPlatformManagerImpl<> template. */ -#ifndef GENERIC_PLATFORM_MANAGER_IMPL_IPP -#define GENERIC_PLATFORM_MANAGER_IMPL_IPP +#ifndef GENERIC_PLATFORM_MANAGER_IMPL_CPP +#define GENERIC_PLATFORM_MANAGER_IMPL_CPP #include #include @@ -280,4 +280,4 @@ template class GenericPlatformManagerImpl; } // namespace DeviceLayer } // namespace chip -#endif // GENERIC_PLATFORM_MANAGER_IMPL_IPP +#endif // GENERIC_PLATFORM_MANAGER_IMPL_CPP diff --git a/src/include/platform/internal/GenericPlatformManagerImpl_FreeRTOS.ipp b/src/include/platform/internal/GenericPlatformManagerImpl_FreeRTOS.cpp similarity index 97% rename from src/include/platform/internal/GenericPlatformManagerImpl_FreeRTOS.ipp rename to src/include/platform/internal/GenericPlatformManagerImpl_FreeRTOS.cpp index 8534b981ada2d7..3afa06cf1764d6 100644 --- a/src/include/platform/internal/GenericPlatformManagerImpl_FreeRTOS.ipp +++ b/src/include/platform/internal/GenericPlatformManagerImpl_FreeRTOS.cpp @@ -22,8 +22,8 @@ * GenericPlatformManagerImpl_FreeRTOS<> template. */ -#ifndef GENERIC_PLATFORM_MANAGER_IMPL_FREERTOS_IPP -#define GENERIC_PLATFORM_MANAGER_IMPL_FREERTOS_IPP +#ifndef GENERIC_PLATFORM_MANAGER_IMPL_FREERTOS_CPP +#define GENERIC_PLATFORM_MANAGER_IMPL_FREERTOS_CPP #include #include @@ -31,7 +31,7 @@ // Include the non-inline definitions for the GenericPlatformManagerImpl<> template, // from which the GenericPlatformManagerImpl_FreeRTOS<> template inherits. -#include +#include namespace chip { namespace DeviceLayer { @@ -242,4 +242,4 @@ CHIP_ERROR GenericPlatformManagerImpl_FreeRTOS::_Shutdown(void) } // namespace DeviceLayer } // namespace chip -#endif // GENERIC_PLATFORM_MANAGER_IMPL_FREERTOS_IPP +#endif // GENERIC_PLATFORM_MANAGER_IMPL_FREERTOS_CPP diff --git a/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.ipp b/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.cpp similarity index 97% rename from src/include/platform/internal/GenericPlatformManagerImpl_POSIX.ipp rename to src/include/platform/internal/GenericPlatformManagerImpl_POSIX.cpp index 05f3fdc0a4d965..6ce8e34f272a26 100644 --- a/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.ipp +++ b/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.cpp @@ -21,8 +21,8 @@ * GenericPlatformManagerImpl_POSIX<> template. */ -#ifndef GENERIC_PLATFORM_MANAGER_IMPL_POSIX_IPP -#define GENERIC_PLATFORM_MANAGER_IMPL_POSIX_IPP +#ifndef GENERIC_PLATFORM_MANAGER_IMPL_POSIX_CPP +#define GENERIC_PLATFORM_MANAGER_IMPL_POSIX_CPP #include #include @@ -30,7 +30,7 @@ // Include the non-inline definitions for the GenericPlatformManagerImpl<> template, // from which the GenericPlatformManagerImpl_POSIX<> template inherits. -#include +#include #include @@ -235,4 +235,4 @@ template class GenericPlatformManagerImpl_POSIX; } // namespace DeviceLayer } // namespace chip -#endif // GENERIC_PLATFORM_MANAGER_IMPL_POSIX_IPP +#endif // GENERIC_PLATFORM_MANAGER_IMPL_POSIX_CPP diff --git a/src/include/platform/internal/GenericPlatformManagerImpl_Zephyr.ipp b/src/include/platform/internal/GenericPlatformManagerImpl_Zephyr.cpp similarity index 96% rename from src/include/platform/internal/GenericPlatformManagerImpl_Zephyr.ipp rename to src/include/platform/internal/GenericPlatformManagerImpl_Zephyr.cpp index 0c4b06a3eb5e1d..cbe0ef284e7056 100644 --- a/src/include/platform/internal/GenericPlatformManagerImpl_Zephyr.ipp +++ b/src/include/platform/internal/GenericPlatformManagerImpl_Zephyr.cpp @@ -21,8 +21,8 @@ * GenericPlatformManagerImpl_Zephyr<> template. */ -#ifndef GENERIC_PLATFORM_MANAGER_IMPL_ZEPHYR_IPP -#define GENERIC_PLATFORM_MANAGER_IMPL_ZEPHYR_IPP +#ifndef GENERIC_PLATFORM_MANAGER_IMPL_ZEPHYR_CPP +#define GENERIC_PLATFORM_MANAGER_IMPL_ZEPHYR_CPP #include #include @@ -30,7 +30,7 @@ // Include the non-inline definitions for the GenericPlatformManagerImpl<> template, // from which the GenericPlatformManagerImpl_Zephyr<> template inherits. -#include +#include #include @@ -202,4 +202,4 @@ CHIP_ERROR GenericPlatformManagerImpl_Zephyr::_StartEventLoopTask(voi } // namespace DeviceLayer } // namespace chip -#endif // GENERIC_PLATFORM_MANAGER_IMPL_ZEPHYR_IPP +#endif // GENERIC_PLATFORM_MANAGER_IMPL_ZEPHYR_CPP diff --git a/src/include/platform/internal/GenericSoftwareUpdateManagerImpl.ipp b/src/include/platform/internal/GenericSoftwareUpdateManagerImpl.cpp similarity index 83% rename from src/include/platform/internal/GenericSoftwareUpdateManagerImpl.ipp rename to src/include/platform/internal/GenericSoftwareUpdateManagerImpl.cpp index 4eba5ba9cf0fef..da814f4189b221 100644 --- a/src/include/platform/internal/GenericSoftwareUpdateManagerImpl.ipp +++ b/src/include/platform/internal/GenericSoftwareUpdateManagerImpl.cpp @@ -22,14 +22,14 @@ * GenericSoftwareUpdateManagerImpl<> template. */ -#ifndef GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_IPP -#define GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_IPP +#ifndef GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_CPP +#define GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_CPP #if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER #include -#include #include +#include #include #include #include @@ -37,8 +37,8 @@ #include #include -#include #include +#include namespace chip { namespace DeviceLayer { @@ -53,30 +53,30 @@ using namespace ::chip::TLV; // Fully instantiate the generic implementation class in whatever compilation unit includes this file. template class GenericSoftwareUpdateManagerImpl; -template +template void GenericSoftwareUpdateManagerImpl::DoInit() { - mShouldRetry = false; + mShouldRetry = false; mScheduledCheckEnabled = false; - mIgnorePartialImage = false; + mIgnorePartialImage = false; mEventHandlerCallback = NULL; - mRetryPolicyCallback = DefaultRetryPolicyCallback; + mRetryPolicyCallback = DefaultRetryPolicyCallback; - mRetryCounter = 0; + mRetryCounter = 0; mMinWaitTimeMs = 0; mMaxWaitTimeMs = 0; mState = SoftwareUpdateManager::kState_Idle; } -template +template CHIP_ERROR GenericSoftwareUpdateManagerImpl::_SetEventCallback(void * const aAppState, - const SoftwareUpdateManager::EventCallback aEventCallback) + const SoftwareUpdateManager::EventCallback aEventCallback) { CHIP_ERROR err = CHIP_NO_ERROR; - mAppState = aAppState; + mAppState = aAppState; mEventHandlerCallback = aEventCallback; #if DEBUG @@ -100,16 +100,16 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::_SetEventCallback(void * #endif return err; - } -template -void GenericSoftwareUpdateManagerImpl::_SetRetryPolicyCallback(const SoftwareUpdateManager::RetryPolicyCallback aRetryPolicyCallback) +template +void GenericSoftwareUpdateManagerImpl::_SetRetryPolicyCallback( + const SoftwareUpdateManager::RetryPolicyCallback aRetryPolicyCallback) { mRetryPolicyCallback = (aRetryPolicyCallback != NULL) ? aRetryPolicyCallback : DefaultRetryPolicyCallback; } -template +template void GenericSoftwareUpdateManagerImpl::PrepareBinding(intptr_t arg) { CHIP_ERROR err; @@ -130,7 +130,7 @@ void GenericSoftwareUpdateManagerImpl::PrepareBinding(intptr_t arg) } } -template +template CHIP_ERROR GenericSoftwareUpdateManagerImpl::PrepareQuery(void) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -142,7 +142,7 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::PrepareQuery(void) QueryBeginEvent ev; EventOptions evOptions(true); - char firmwareRev[ConfigurationManager::kMaxFirmwareRevisionLength+1]; + char firmwareRev[ConfigurationManager::kMaxFirmwareRevisionLength + 1]; size_t firmwareRevLen; @@ -166,10 +166,10 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::PrepareQuery(void) NullifyAllEventFields(&ev); evOptions.relatedEventID = mEventId; - ev.currentSwVersion = firmwareRev; - ev.vendorId = imageQuery.productSpec.vendorId; - ev.vendorProductId = imageQuery.productSpec.productId; - ev.productRevision = imageQuery.productSpec.productRev; + ev.currentSwVersion = firmwareRev; + ev.vendorId = imageQuery.productSpec.vendorId; + ev.vendorProductId = imageQuery.productSpec.productId; + ev.productRevision = imageQuery.productSpec.productRev; ev.SetCurrentSwVersionPresent(); ev.SetVendorIdPresent(); ev.SetVendorProductIdPresent(); @@ -182,8 +182,8 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::PrepareQuery(void) SuccessOrExit(err); outParam.PrepareQuery.PackageSpecification = NULL; - outParam.PrepareQuery.DesiredLocale = NULL; - outParam.PrepareQuery.Error = CHIP_NO_ERROR; + outParam.PrepareQuery.DesiredLocale = NULL; + outParam.PrepareQuery.Error = CHIP_NO_ERROR; mEventHandlerCallback(mAppState, SoftwareUpdateManager::kEvent_PrepareQuery, inParam, outParam); VerifyOrExit(mState == SoftwareUpdateManager::kState_PrepareQuery, err = CHIP_DEVICE_ERROR_SOFTWARE_UPDATE_ABORTED); @@ -199,7 +199,8 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::PrepareQuery(void) // then skip over and move to the next field. if (outParam.PrepareQuery.DesiredLocale != NULL) { - err = imageQuery.localeSpec.init((uint8_t) strlen(outParam.PrepareQuery.DesiredLocale), (char *)outParam.PrepareQuery.DesiredLocale); + err = imageQuery.localeSpec.init((uint8_t) strlen(outParam.PrepareQuery.DesiredLocale), + (char *) outParam.PrepareQuery.DesiredLocale); SuccessOrExit(err); ev.locale = outParam.PrepareQuery.DesiredLocale; @@ -210,7 +211,8 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::PrepareQuery(void) // provided by the application, skip and move to the next field. if (outParam.PrepareQuery.PackageSpecification != NULL) { - err = imageQuery.packageSpec.init((uint8_t) strlen(outParam.PrepareQuery.PackageSpecification), (char *)outParam.PrepareQuery.PackageSpecification); + err = imageQuery.packageSpec.init((uint8_t) strlen(outParam.PrepareQuery.PackageSpecification), + (char *) outParam.PrepareQuery.PackageSpecification); SuccessOrExit(err); } @@ -230,7 +232,7 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::PrepareQuery(void) outParam.Clear(); inParam.PrepareQuery_Metadata.MetaDataWriter = &writer; - outParam.PrepareQuery_Metadata.Error = CHIP_NO_ERROR; + outParam.PrepareQuery_Metadata.Error = CHIP_NO_ERROR; // Call EventHandler Callback to allow application to write meta-data. mEventHandlerCallback(mAppState, SoftwareUpdateManager::kEvent_PrepareQuery_Metadata, inParam, outParam); @@ -251,7 +253,7 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::PrepareQuery(void) return err; } -template +template CHIP_ERROR GenericSoftwareUpdateManagerImpl::_CheckNow(void) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -270,7 +272,7 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::_CheckNow(void) SoftwareUpdateStartEvent ev; EventOptions evOptions(true); ev.trigger = START_TRIGGER_USER_INITIATED; - mEventId = LogEvent(&ev, evOptions); + mEventId = LogEvent(&ev, evOptions); } DriveState(SoftwareUpdateManager::kState_PrepareQuery); @@ -280,36 +282,36 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::_CheckNow(void) return err; } -template -void GenericSoftwareUpdateManagerImpl::GetEventState(int32_t& aEventState) +template +void GenericSoftwareUpdateManagerImpl::GetEventState(int32_t & aEventState) { int32_t event_state = 0; - switch(mState) + switch (mState) { - case SoftwareUpdateManager::kState_Idle: - case SoftwareUpdateManager::kState_ScheduledHoldoff: - event_state = STATE_IDLE; - break; - case SoftwareUpdateManager::kState_PrepareQuery: - case SoftwareUpdateManager::kState_Query: - event_state = STATE_QUERYING; - break; - case SoftwareUpdateManager::kState_Download: - event_state = STATE_DOWNLOADING; - break; - case SoftwareUpdateManager::kState_Install: - event_state = STATE_INSTALLING; - break; - default: - event_state = 0; - break; + case SoftwareUpdateManager::kState_Idle: + case SoftwareUpdateManager::kState_ScheduledHoldoff: + event_state = STATE_IDLE; + break; + case SoftwareUpdateManager::kState_PrepareQuery: + case SoftwareUpdateManager::kState_Query: + event_state = STATE_QUERYING; + break; + case SoftwareUpdateManager::kState_Download: + event_state = STATE_DOWNLOADING; + break; + case SoftwareUpdateManager::kState_Install: + event_state = STATE_INSTALLING; + break; + default: + event_state = 0; + break; } aEventState = event_state; } -template +template void GenericSoftwareUpdateManagerImpl::SoftwareUpdateFailed(CHIP_ERROR aError) { SoftwareUpdateManager::InEventParam inParam; @@ -360,10 +362,10 @@ void GenericSoftwareUpdateManagerImpl::SoftwareUpdateFailed(CHIP_ERRO DriveState(SoftwareUpdateManager::kState_Idle); exit: - return ; + return; } -template +template void GenericSoftwareUpdateManagerImpl::SoftwareUpdateFinished(CHIP_ERROR aError) { SoftwareUpdateManager::InEventParam inParam; @@ -372,7 +374,7 @@ void GenericSoftwareUpdateManagerImpl::SoftwareUpdateFinished(CHIP_ER inParam.Clear(); outParam.Clear(); - mShouldRetry = false; + mShouldRetry = false; mRetryCounter = 0; if (aError == CHIP_ERROR_NO_SW_UPDATE_AVAILABLE) @@ -396,11 +398,11 @@ void GenericSoftwareUpdateManagerImpl::SoftwareUpdateFinished(CHIP_ER NullifyAllEventFields(&ev); GetEventState(ev.state); evOptions.relatedEventID = mEventId; - ev.platformReturnCode = aError; + ev.platformReturnCode = aError; LogEvent(&ev, evOptions); } - inParam.Finished.Error = aError; + inParam.Finished.Error = aError; inParam.Finished.StatusReport = NULL; mEventHandlerCallback(mAppState, SoftwareUpdateManager::kEvent_Finished, inParam, outParam); @@ -408,19 +410,19 @@ void GenericSoftwareUpdateManagerImpl::SoftwareUpdateFinished(CHIP_ER DriveState(SoftwareUpdateManager::kState_Idle); } -template +template bool GenericSoftwareUpdateManagerImpl::_IsInProgress(void) { - return ((mState == SoftwareUpdateManager::kState_Idle || mState == SoftwareUpdateManager::kState_ScheduledHoldoff) ? - false : true ); + return ((mState == SoftwareUpdateManager::kState_Idle || mState == SoftwareUpdateManager::kState_ScheduledHoldoff) ? false + : true); } -template +template void GenericSoftwareUpdateManagerImpl::SendQuery(void) { CHIP_ERROR err; - SoftwareUpdateManager::InEventParam inParam; + SoftwareUpdateManager::InEventParam inParam; SoftwareUpdateManager::OutEventParam outParam; inParam.Clear(); @@ -436,7 +438,7 @@ void GenericSoftwareUpdateManagerImpl::SendQuery(void) } } -template +template void GenericSoftwareUpdateManagerImpl::HandleStatusReport(PacketBuffer * payload) { CHIP_ERROR err; @@ -463,13 +465,13 @@ void GenericSoftwareUpdateManagerImpl::HandleStatusReport(PacketBuffe } } -template +template void GenericSoftwareUpdateManagerImpl::HandleImageQueryResponse(PacketBuffer * payload) { CHIP_ERROR err = CHIP_NO_ERROR; SoftwareUpdateManager::InEventParam inParam; SoftwareUpdateManager::OutEventParam outParam; - char versionString[ConfigurationManager::kMaxFirmwareRevisionLength+1]; + char versionString[ConfigurationManager::kMaxFirmwareRevisionLength + 1]; { ImageQueryResponse imageQueryResponse; @@ -479,7 +481,8 @@ void GenericSoftwareUpdateManagerImpl::HandleImageQueryResponse(Packe SuccessOrExit(err); // Copy URI and version string since the original payload will be freed after this. - VerifyOrExit(imageQueryResponse.uri.theLength < CHIP_DEVICE_CONFIG_SOFTWARE_UPDATE_URI_LEN, err = CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrExit(imageQueryResponse.uri.theLength < CHIP_DEVICE_CONFIG_SOFTWARE_UPDATE_URI_LEN, + err = CHIP_ERROR_BUFFER_TOO_SMALL); strncpy(mURI, imageQueryResponse.uri.theString, imageQueryResponse.uri.theLength); mURI[imageQueryResponse.uri.theLength] = 0; VerifyOrExit(imageQueryResponse.versionSpec.theLength < ArraySize(versionString), err = CHIP_ERROR_BUFFER_TOO_SMALL); @@ -490,11 +493,11 @@ void GenericSoftwareUpdateManagerImpl::HandleImageQueryResponse(Packe mIntegritySpec = imageQueryResponse.integritySpec; // Arrange to pass query response information to the application. - inParam.SoftwareUpdateAvailable.Priority = imageQueryResponse.updatePriority; - inParam.SoftwareUpdateAvailable.Condition = imageQueryResponse.updateCondition; - inParam.SoftwareUpdateAvailable.IntegrityType = imageQueryResponse.integritySpec.type; - inParam.SoftwareUpdateAvailable.Version = versionString; - inParam.SoftwareUpdateAvailable.URI = mURI; + inParam.SoftwareUpdateAvailable.Priority = imageQueryResponse.updatePriority; + inParam.SoftwareUpdateAvailable.Condition = imageQueryResponse.updateCondition; + inParam.SoftwareUpdateAvailable.IntegrityType = imageQueryResponse.integritySpec.type; + inParam.SoftwareUpdateAvailable.Version = versionString; + inParam.SoftwareUpdateAvailable.URI = mURI; } // Release the packet buffer. @@ -507,8 +510,8 @@ void GenericSoftwareUpdateManagerImpl::HandleImageQueryResponse(Packe EventOptions evOptions(true); NullifyAllEventFields(&ev); evOptions.relatedEventID = mEventId; - ev.imageUrl = mURI; - ev.imageVersion = versionString; + ev.imageUrl = mURI; + ev.imageVersion = versionString; ev.SetImageUrlPresent(); ev.SetImageVersionPresent(); LogEvent(&ev, evOptions); @@ -547,7 +550,7 @@ void GenericSoftwareUpdateManagerImpl::HandleImageQueryResponse(Packe // Call the application to determine if a partially downloaded copy of the desired firmware image // already exists in local storage. Pass the URI of the desired image, which must match the metadata // stored with the image. - inParam.FetchPartialImageInfo.URI = mURI; + inParam.FetchPartialImageInfo.URI = mURI; outParam.FetchPartialImageInfo.PartialImageLen = 0; mEventHandlerCallback(mAppState, SoftwareUpdateManager::kEvent_FetchPartialImageInfo, inParam, outParam); VerifyOrExit(mState == SoftwareUpdateManager::kState_Query, err = CHIP_DEVICE_ERROR_SOFTWARE_UPDATE_ABORTED); @@ -586,9 +589,8 @@ void GenericSoftwareUpdateManagerImpl::HandleImageQueryResponse(Packe } } -template -void GenericSoftwareUpdateManagerImpl::HandleHoldOffTimerExpired(::chip::System::Layer * aLayer, - void * aAppState, +template +void GenericSoftwareUpdateManagerImpl::HandleHoldOffTimerExpired(::chip::System::Layer * aLayer, void * aAppState, ::chip::System::Error aError) { GenericSoftwareUpdateManagerImpl * self = &SoftwareUpdateMgrImpl(); @@ -596,14 +598,14 @@ void GenericSoftwareUpdateManagerImpl::HandleHoldOffTimerExpired(::ch { SoftwareUpdateStartEvent ev; EventOptions evOptions(true); - ev.trigger = START_TRIGGER_SCHEDULED; + ev.trigger = START_TRIGGER_SCHEDULED; self->mEventId = LogEvent(&ev, evOptions); } self->DriveState(SoftwareUpdateManager::kState_PrepareQuery); } -template +template void GenericSoftwareUpdateManagerImpl::DriveState(SoftwareUpdateManager::State aNextState) { if (mState != SoftwareUpdateManager::kState_Idle && @@ -614,59 +616,53 @@ void GenericSoftwareUpdateManagerImpl::DriveState(SoftwareUpdateManag mState = aNextState; - switch(mState) + switch (mState) { - case SoftwareUpdateManager::kState_Idle: + case SoftwareUpdateManager::kState_Idle: { + /* Compute the next wait time interval only if scheduled software update checks are + * enabled or when the previous attempt failed provided service connectivity is + * present. Start the timer once we have a valid interval. A Software Update Check + * will trigger on expiration of the timer unless service connectivity was lost or + * the application requested a manual software update check. + */ + if (mScheduledCheckEnabled || mShouldRetry) { - /* Compute the next wait time interval only if scheduled software update checks are - * enabled or when the previous attempt failed provided service connectivity is - * present. Start the timer once we have a valid interval. A Software Update Check - * will trigger on expiration of the timer unless service connectivity was lost or - * the application requested a manual software update check. - */ - if (mScheduledCheckEnabled || mShouldRetry) + uint32_t timeToNextQueryMS = GetNextWaitTimeInterval(); + + // If timeToNextQueryMs is 0, then do nothing. + if (timeToNextQueryMS) { - uint32_t timeToNextQueryMS = GetNextWaitTimeInterval(); - - // If timeToNextQueryMs is 0, then do nothing. - if (timeToNextQueryMS) - { - mState = SoftwareUpdateManager::kState_ScheduledHoldoff; - SystemLayer.StartTimer(timeToNextQueryMS, HandleHoldOffTimerExpired, NULL); - } + mState = SoftwareUpdateManager::kState_ScheduledHoldoff; + SystemLayer.StartTimer(timeToNextQueryMS, HandleHoldOffTimerExpired, NULL); } } - break; + } + break; - case SoftwareUpdateManager::kState_PrepareQuery: - { - PlatformMgr().ScheduleWork(PrepareBinding); - } - break; + case SoftwareUpdateManager::kState_PrepareQuery: { + PlatformMgr().ScheduleWork(PrepareBinding); + } + break; - case SoftwareUpdateManager::kState_Query: - { - SendQuery(); - } - break; + case SoftwareUpdateManager::kState_Query: { + SendQuery(); + } + break; - case SoftwareUpdateManager::kState_PrepareImageStorage: - { - PrepareImageStorage(); - } - break; + case SoftwareUpdateManager::kState_PrepareImageStorage: { + PrepareImageStorage(); + } + break; - case SoftwareUpdateManager::kState_Download: - { - PlatformMgr().ScheduleWork(StartDownload); - } - break; + case SoftwareUpdateManager::kState_Download: { + PlatformMgr().ScheduleWork(StartDownload); + } + break; - case SoftwareUpdateManager::kState_Install: - { - StartImageInstall(); - } - break; + case SoftwareUpdateManager::kState_Install: { + StartImageInstall(); + } + break; default: break; @@ -676,7 +672,7 @@ void GenericSoftwareUpdateManagerImpl::DriveState(SoftwareUpdateManag return; } -template +template CHIP_ERROR GenericSoftwareUpdateManagerImpl::_SetQueryIntervalWindow(uint32_t aMinWaitTimeMs, uint32_t aMaxWaitTimeMs) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -702,7 +698,7 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::_SetQueryIntervalWindow( return err; } -template +template uint32_t GenericSoftwareUpdateManagerImpl::GetNextWaitTimeInterval() { uint32_t timeOutMsecs; @@ -738,7 +734,7 @@ uint32_t GenericSoftwareUpdateManagerImpl::GetNextWaitTimeInterval() return timeOutMsecs; } -template +template uint32_t GenericSoftwareUpdateManagerImpl::ComputeNextScheduledWaitTimeInterval(void) { uint32_t timeOutMsecs = (mMinWaitTimeMs + (GetRandU32() % (mMaxWaitTimeMs - mMinWaitTimeMs))); @@ -748,18 +744,17 @@ uint32_t GenericSoftwareUpdateManagerImpl::ComputeNextScheduledWaitTi return timeOutMsecs; } -template -void GenericSoftwareUpdateManagerImpl::_DefaultEventHandler(void *apAppState, - SoftwareUpdateManager::EventType aEvent, - const SoftwareUpdateManager::InEventParam& aInParam, - SoftwareUpdateManager::OutEventParam& aOutParam) +template +void GenericSoftwareUpdateManagerImpl::_DefaultEventHandler(void * apAppState, SoftwareUpdateManager::EventType aEvent, + const SoftwareUpdateManager::InEventParam & aInParam, + SoftwareUpdateManager::OutEventParam & aOutParam) { // No actions required for current implementation aOutParam.DefaultHandlerCalled = true; } -template -CHIP_ERROR GenericSoftwareUpdateManagerImpl::StoreImageBlock(uint32_t aLength, uint8_t *aData) +template +CHIP_ERROR GenericSoftwareUpdateManagerImpl::StoreImageBlock(uint32_t aLength, uint8_t * aData) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -770,8 +765,8 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::StoreImageBlock(uint32_t outParam.Clear(); inParam.StoreImageBlock.DataBlockLen = aLength; - inParam.StoreImageBlock.DataBlock = aData; - outParam.StoreImageBlock.Error = CHIP_NO_ERROR; + inParam.StoreImageBlock.DataBlock = aData; + outParam.StoreImageBlock.Error = CHIP_NO_ERROR; mEventHandlerCallback(mAppState, SoftwareUpdateManager::kEvent_StoreImageBlock, inParam, outParam); VerifyOrExit(mState == SoftwareUpdateManager::kState_Download, err = CHIP_DEVICE_ERROR_SOFTWARE_UPDATE_ABORTED); @@ -787,7 +782,7 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::StoreImageBlock(uint32_t return err; } -template +template void GenericSoftwareUpdateManagerImpl::PrepareImageStorage(void) { SoftwareUpdateManager::InEventParam inParam; @@ -797,7 +792,7 @@ void GenericSoftwareUpdateManagerImpl::PrepareImageStorage(void) // image to be downloaded. inParam.Clear(); outParam.Clear(); - inParam.PrepareImageStorage.URI = mURI; + inParam.PrepareImageStorage.URI = mURI; inParam.PrepareImageStorage.IntegrityType = mIntegritySpec.type; mEventHandlerCallback(mAppState, SoftwareUpdateManager::kEvent_PrepareImageStorage, inParam, outParam); @@ -809,10 +804,10 @@ void GenericSoftwareUpdateManagerImpl::PrepareImageStorage(void) } } -template +template void GenericSoftwareUpdateManagerImpl::StartDownload(intptr_t arg) { - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; GenericSoftwareUpdateManagerImpl * self = &SoftwareUpdateMgrImpl(); SoftwareUpdateManager::InEventParam inParam; @@ -832,8 +827,8 @@ void GenericSoftwareUpdateManagerImpl::StartDownload(intptr_t arg) EventOptions evOptions(true); NullifyAllEventFields(&ev); evOptions.relatedEventID = self->mEventId; - ev.imageUrl = self->mURI; - ev.offset = self->mStartOffset; + ev.imageUrl = self->mURI; + ev.offset = self->mStartOffset; ev.SetImageUrlPresent(); ev.SetOffsetPresent(); LogEvent(&ev, evOptions); @@ -846,7 +841,7 @@ void GenericSoftwareUpdateManagerImpl::StartDownload(intptr_t arg) } } -template +template void GenericSoftwareUpdateManagerImpl::DownloadComplete() { DownloadFinishEvent ev; @@ -859,11 +854,11 @@ void GenericSoftwareUpdateManagerImpl::DownloadComplete() CheckImageIntegrity(); } -template +template void GenericSoftwareUpdateManagerImpl::CheckImageIntegrity(void) { - CHIP_ERROR err = CHIP_NO_ERROR; - int result = 0; + CHIP_ERROR err = CHIP_NO_ERROR; + int result = 0; uint8_t typeLength = 0; SoftwareUpdateManager::InEventParam inParam; @@ -872,28 +867,28 @@ void GenericSoftwareUpdateManagerImpl::CheckImageIntegrity(void) inParam.Clear(); outParam.Clear(); - switch(mIntegritySpec.type) + switch (mIntegritySpec.type) { - case kIntegrityType_SHA160: - typeLength = kLength_SHA160; - break; - case kIntegrityType_SHA256: - typeLength = kLength_SHA256; - break; - case kIntegrityType_SHA512: - typeLength = kLength_SHA512; - break; - default: - typeLength = 0; - break; + case kIntegrityType_SHA160: + typeLength = kLength_SHA160; + break; + case kIntegrityType_SHA256: + typeLength = kLength_SHA256; + break; + case kIntegrityType_SHA512: + typeLength = kLength_SHA512; + break; + default: + typeLength = 0; + break; } uint8_t computedIntegrityValue[typeLength]; - inParam.ComputeImageIntegrity.IntegrityType = mIntegritySpec.type; - inParam.ComputeImageIntegrity.IntegrityValueBuf = computedIntegrityValue; + inParam.ComputeImageIntegrity.IntegrityType = mIntegritySpec.type; + inParam.ComputeImageIntegrity.IntegrityValueBuf = computedIntegrityValue; inParam.ComputeImageIntegrity.IntegrityValueBufLen = typeLength; - outParam.ComputeImageIntegrity.Error = CHIP_NO_ERROR; + outParam.ComputeImageIntegrity.Error = CHIP_NO_ERROR; // Request the application to compute an integrity check value for the stored image. // Fail if the application returns an error. @@ -943,7 +938,7 @@ void GenericSoftwareUpdateManagerImpl::CheckImageIntegrity(void) } } -template +template void GenericSoftwareUpdateManagerImpl::StartImageInstall(void) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -991,12 +986,11 @@ void GenericSoftwareUpdateManagerImpl::StartImageInstall(void) } } -template +template void GenericSoftwareUpdateManagerImpl::Cleanup(void) -{ -} +{} -template +template CHIP_ERROR GenericSoftwareUpdateManagerImpl::_Abort(void) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -1023,7 +1017,7 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::_Abort(void) /** * Default Policy: */ -template +template void GenericSoftwareUpdateManagerImpl::DefaultRetryPolicyCallback(void * const aAppState, SoftwareUpdateManager::RetryParam & aRetryParam, uint32_t & aOutIntervalMsec) @@ -1044,7 +1038,7 @@ void GenericSoftwareUpdateManagerImpl::DefaultRetryPolicyCallback(voi if (self->mScheduledCheckEnabled && CHIP_DEVICE_CONFIG_SOFTWARE_UPDATE_MAX_WAIT_TIME_INTERVAL_MS > self->mMinWaitTimeMs) { - waitTimeInMsec = 0; + waitTimeInMsec = 0; maxWaitTimeInMsec = 0; } else @@ -1057,7 +1051,7 @@ void GenericSoftwareUpdateManagerImpl::DefaultRetryPolicyCallback(voi } else { - maxWaitTimeInMsec = 0; + maxWaitTimeInMsec = 0; } if (maxWaitTimeInMsec != 0) @@ -1066,9 +1060,9 @@ void GenericSoftwareUpdateManagerImpl::DefaultRetryPolicyCallback(voi waitTimeInMsec = minWaitTimeInMsec + (GetRandU32() % (maxWaitTimeInMsec - minWaitTimeInMsec)); ChipLogDetail(DeviceLayer, - "Computing swu retry policy: attempts %" PRIu32 ", max wait time %" PRIu32 " ms, selected wait time %" PRIu32 - " ms", - aRetryParam.NumRetries, maxWaitTimeInMsec, waitTimeInMsec); + "Computing swu retry policy: attempts %" PRIu32 ", max wait time %" PRIu32 " ms, selected wait time %" PRIu32 + " ms", + aRetryParam.NumRetries, maxWaitTimeInMsec, waitTimeInMsec); } aOutIntervalMsec = waitTimeInMsec; @@ -1076,7 +1070,7 @@ void GenericSoftwareUpdateManagerImpl::DefaultRetryPolicyCallback(voi return; } -template +template CHIP_ERROR GenericSoftwareUpdateManagerImpl::_PrepareImageStorageComplete(CHIP_ERROR aError) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -1099,7 +1093,7 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::_PrepareImageStorageComp return err; } -template +template CHIP_ERROR GenericSoftwareUpdateManagerImpl::_ImageInstallComplete(CHIP_ERROR aError) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -1116,7 +1110,7 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::_ImageInstallComplete(CH return err; } -template +template CHIP_ERROR GenericSoftwareUpdateManagerImpl::InstallImage(void) { return CHIP_ERROR_NOT_IMPLEMENTED; @@ -1127,4 +1121,4 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl::InstallImage(void) } // namespace chip #endif // CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER -#endif // GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_IPP +#endif // GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_CPP diff --git a/src/include/platform/internal/GenericSoftwareUpdateManagerImpl_BDX.ipp b/src/include/platform/internal/GenericSoftwareUpdateManagerImpl_BDX.cpp similarity index 71% rename from src/include/platform/internal/GenericSoftwareUpdateManagerImpl_BDX.ipp rename to src/include/platform/internal/GenericSoftwareUpdateManagerImpl_BDX.cpp index a500f74ca07cf3..f6a8301a52a4d4 100644 --- a/src/include/platform/internal/GenericSoftwareUpdateManagerImpl_BDX.ipp +++ b/src/include/platform/internal/GenericSoftwareUpdateManagerImpl_BDX.cpp @@ -22,8 +22,8 @@ * GenericSoftwareUpdateManagerImpl<> template. */ -#ifndef GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_BDX_IPP -#define GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_BDX_IPP +#ifndef GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_BDX_CPP +#define GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_BDX_CPP #if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER @@ -45,13 +45,13 @@ using namespace ::chip::Profiles::BulkDataTransfer; // Fully instantiate the generic implementation class in whatever compilation unit includes this file. template class GenericSoftwareUpdateManagerImpl_BDX; -template +template CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::DoInit(void) { CHIP_ERROR err; - mBinding = NULL; - mURI = NULL; + mBinding = NULL; + mURI = NULL; mBDXTransfer = NULL; mStartOffset = 0; @@ -60,43 +60,43 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::DoInit(void) return err; } -template -CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::StartImageDownload(char *aURI, uint64_t aStartOffset) +template +CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::StartImageDownload(char * aURI, uint64_t aStartOffset) { CHIP_ERROR err; VerifyOrExit(aURI != NULL, err = CHIP_ERROR_INVALID_ARGUMENT); - mURI = aURI; + mURI = aURI; mStartOffset = aStartOffset; mBinding = ExchangeMgr.NewBinding(HandleBindingEvent, NULL); VerifyOrExit(mBinding != NULL, err = CHIP_ERROR_NO_MEMORY); err = mBinding->BeginConfiguration() - .Target_ServiceEndpoint(CHIP_DEVICE_CONFIG_FILE_DOWNLOAD_ENDPOINT_ID) - .Transport_UDP_WRM() - .Exchange_ResponseTimeoutMsec(CHIP_DEVICE_CONFIG_FILE_DOWNLOAD_RESPOSNE_TIMEOUT) - .Security_SharedCASESession() - .PrepareBinding(); + .Target_ServiceEndpoint(CHIP_DEVICE_CONFIG_FILE_DOWNLOAD_ENDPOINT_ID) + .Transport_UDP_WRM() + .Exchange_ResponseTimeoutMsec(CHIP_DEVICE_CONFIG_FILE_DOWNLOAD_RESPOSNE_TIMEOUT) + .Security_SharedCASESession() + .PrepareBinding(); exit: return err; } -template +template CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::StartDownload(void) { CHIP_ERROR err; ReferencedString uri; - uri.init((uint16_t)strlen(mURI), mURI); + uri.init((uint16_t) strlen(mURI), mURI); BDXHandlers handlers = { - NULL, // SendAcceptHandler + NULL, // SendAcceptHandler ReceiveAcceptHandler, ReceiveRejectHandler, - NULL, // GetBlockHandler + NULL, // GetBlockHandler BlockReceiveHandler, XferErrorHandler, XferDoneHandler, @@ -134,13 +134,14 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::StartDownload(void) return err; } -template -CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::ReceiveAcceptHandler(BDXTransfer * aXfer, ReceiveAccept * aReceiveAcceptMsg) +template +CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::ReceiveAcceptHandler(BDXTransfer * aXfer, + ReceiveAccept * aReceiveAcceptMsg) { return CHIP_NO_ERROR; } -template +template void GenericSoftwareUpdateManagerImpl_BDX::ReceiveRejectHandler(BDXTransfer * aXfer, StatusReport * aReport) { GenericSoftwareUpdateManagerImpl_BDX * self = &SoftwareUpdateMgrImpl(); @@ -164,8 +165,9 @@ void GenericSoftwareUpdateManagerImpl_BDX::ReceiveRejectHandler(BDXTr } } -template -void GenericSoftwareUpdateManagerImpl_BDX::BlockReceiveHandler(BDXTransfer * xfr, uint64_t aLength, uint8_t * aDataBlock, bool aIsLastBlock) +template +void GenericSoftwareUpdateManagerImpl_BDX::BlockReceiveHandler(BDXTransfer * xfr, uint64_t aLength, uint8_t * aDataBlock, + bool aIsLastBlock) { CHIP_ERROR err; GenericSoftwareUpdateManagerImpl_BDX * self = &SoftwareUpdateMgrImpl(); @@ -173,7 +175,7 @@ void GenericSoftwareUpdateManagerImpl_BDX::BlockReceiveHandler(BDXTra err = self->Impl()->StoreImageBlock(aLength, aDataBlock); if (err == CHIP_DEVICE_ERROR_SOFTWARE_UPDATE_ABORTED) { - return ; + return; } else if (err != CHIP_NO_ERROR) { @@ -182,7 +184,7 @@ void GenericSoftwareUpdateManagerImpl_BDX::BlockReceiveHandler(BDXTra } } -template +template void GenericSoftwareUpdateManagerImpl_BDX::XferErrorHandler(BDXTransfer * aXfer, StatusReport * aReport) { GenericSoftwareUpdateManagerImpl_BDX * self = &SoftwareUpdateMgrImpl(); @@ -191,7 +193,7 @@ void GenericSoftwareUpdateManagerImpl_BDX::XferErrorHandler(BDXTransf self->Impl()->SoftwareUpdateFailed(CHIP_ERROR_STATUS_REPORT_RECEIVED, aReport); } -template +template void GenericSoftwareUpdateManagerImpl_BDX::XferDoneHandler(BDXTransfer * aXfer) { GenericSoftwareUpdateManagerImpl_BDX * self = &SoftwareUpdateMgrImpl(); @@ -200,7 +202,7 @@ void GenericSoftwareUpdateManagerImpl_BDX::XferDoneHandler(BDXTransfe self->Impl()->DownloadComplete(); } -template +template void GenericSoftwareUpdateManagerImpl_BDX::ErrorHandler(BDXTransfer * aXfer, CHIP_ERROR aErrorCode) { GenericSoftwareUpdateManagerImpl_BDX * self = &SoftwareUpdateMgrImpl(); @@ -209,39 +211,39 @@ void GenericSoftwareUpdateManagerImpl_BDX::ErrorHandler(BDXTransfer * self->Impl()->SoftwareUpdateFailed(aErrorCode, NULL); } -template +template void GenericSoftwareUpdateManagerImpl_BDX::HandleBindingEvent(void * appState, ::chip::Binding::EventType aEvent, - const ::chip::Binding::InEventParam & aInParam, ::chip::Binding::OutEventParam & aOutParam) + const ::chip::Binding::InEventParam & aInParam, + ::chip::Binding::OutEventParam & aOutParam) { - CHIP_ERROR err = CHIP_NO_ERROR; - StatusReport *statusReport = NULL; + CHIP_ERROR err = CHIP_NO_ERROR; + StatusReport * statusReport = NULL; GenericSoftwareUpdateManagerImpl_BDX * self = &SoftwareUpdateMgrImpl(); switch (aEvent) { - case chip::Binding::kEvent_PrepareFailed: - ChipLogProgress(DeviceLayer, "Failed to prepare Software Update BDX binding: %s", - (aInParam.PrepareFailed.Reason == CHIP_ERROR_STATUS_REPORT_RECEIVED) - ? StatusReportStr(aInParam.PrepareFailed.StatusReport->mProfileId, - aInParam.PrepareFailed.StatusReport->mStatusCode) - : ErrorStr(aInParam.PrepareFailed.Reason)); - statusReport = aInParam.PrepareFailed.StatusReport; - err = aInParam.PrepareFailed.Reason; - break; - - case chip::Binding::kEvent_BindingFailed: - ChipLogProgress(DeviceLayer, "Software Update BDX binding failed: %s", - ErrorStr(aInParam.BindingFailed.Reason)); - err = aInParam.PrepareFailed.Reason; - break; - - case chip::Binding::kEvent_BindingReady: - ChipLogProgress(DeviceLayer, "Software Update BDX binding ready"); - err = self->StartDownload(); - break; - - default: - chip::Binding::DefaultEventHandler(appState, aEvent, aInParam, aOutParam); + case chip::Binding::kEvent_PrepareFailed: + ChipLogProgress( + DeviceLayer, "Failed to prepare Software Update BDX binding: %s", + (aInParam.PrepareFailed.Reason == CHIP_ERROR_STATUS_REPORT_RECEIVED) + ? StatusReportStr(aInParam.PrepareFailed.StatusReport->mProfileId, aInParam.PrepareFailed.StatusReport->mStatusCode) + : ErrorStr(aInParam.PrepareFailed.Reason)); + statusReport = aInParam.PrepareFailed.StatusReport; + err = aInParam.PrepareFailed.Reason; + break; + + case chip::Binding::kEvent_BindingFailed: + ChipLogProgress(DeviceLayer, "Software Update BDX binding failed: %s", ErrorStr(aInParam.BindingFailed.Reason)); + err = aInParam.PrepareFailed.Reason; + break; + + case chip::Binding::kEvent_BindingReady: + ChipLogProgress(DeviceLayer, "Software Update BDX binding ready"); + err = self->StartDownload(); + break; + + default: + chip::Binding::DefaultEventHandler(appState, aEvent, aInParam, aOutParam); } if (err != CHIP_NO_ERROR) @@ -251,13 +253,13 @@ void GenericSoftwareUpdateManagerImpl_BDX::HandleBindingEvent(void * } } -template +template void GenericSoftwareUpdateManagerImpl_BDX::AbortDownload(void) { ResetState(); } -template +template void GenericSoftwareUpdateManagerImpl_BDX::ResetState(void) { if (mBinding != NULL) @@ -274,8 +276,9 @@ void GenericSoftwareUpdateManagerImpl_BDX::ResetState(void) mStartOffset = 0; } -template -CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::GetUpdateSchemeList(::chip::Profiles::SoftwareUpdate::UpdateSchemeList * aUpdateSchemeList) +template +CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::GetUpdateSchemeList( + ::chip::Profiles::SoftwareUpdate::UpdateSchemeList * aUpdateSchemeList) { uint8_t supportedSchemes[] = { Profiles::SoftwareUpdate::kUpdateScheme_BDX }; aUpdateSchemeList->init(ArraySize(supportedSchemes), supportedSchemes); @@ -288,4 +291,4 @@ CHIP_ERROR GenericSoftwareUpdateManagerImpl_BDX::GetUpdateSchemeList( } // namespace chip #endif // CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER -#endif // GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_BDX_IPP +#endif // GENERIC_SOFTWARE_UPDATE_MANAGER_IMPL_BDX_CPP diff --git a/src/platform/Darwin/ConfigurationManagerImpl.cpp b/src/platform/Darwin/ConfigurationManagerImpl.cpp index a6488ef763caa2..310a9e5a92e747 100644 --- a/src/platform/Darwin/ConfigurationManagerImpl.cpp +++ b/src/platform/Darwin/ConfigurationManagerImpl.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/platform/Darwin/ConnectivityManagerImpl.cpp b/src/platform/Darwin/ConnectivityManagerImpl.cpp index a6ad59725bda88..b5d073ce43177a 100644 --- a/src/platform/Darwin/ConnectivityManagerImpl.cpp +++ b/src/platform/Darwin/ConnectivityManagerImpl.cpp @@ -27,11 +27,11 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include +#include #endif using namespace ::chip; diff --git a/src/platform/Darwin/PlatformManagerImpl.cpp b/src/platform/Darwin/PlatformManagerImpl.cpp index 3f01ae0da441d8..ae147cdab2de93 100644 --- a/src/platform/Darwin/PlatformManagerImpl.cpp +++ b/src/platform/Darwin/PlatformManagerImpl.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/EFR32/ConfigurationManagerImpl.cpp b/src/platform/EFR32/ConfigurationManagerImpl.cpp index cac80267b6d16b..8b26e715877273 100644 --- a/src/platform/EFR32/ConfigurationManagerImpl.cpp +++ b/src/platform/EFR32/ConfigurationManagerImpl.cpp @@ -24,7 +24,7 @@ /* this file behaves like a config.h, comes first */ #include -#include +#include #include #include diff --git a/src/platform/EFR32/ConnectivityManagerImpl.cpp b/src/platform/EFR32/ConnectivityManagerImpl.cpp index 13762d1a34bf3e..ffb0ba67c8cc2e 100644 --- a/src/platform/EFR32/ConnectivityManagerImpl.cpp +++ b/src/platform/EFR32/ConnectivityManagerImpl.cpp @@ -29,11 +29,11 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include +#include #endif using namespace ::chip; diff --git a/src/platform/EFR32/NetworkProvisioningServerImpl.cpp b/src/platform/EFR32/NetworkProvisioningServerImpl.cpp index a204fb8235708e..4809eb0372856e 100644 --- a/src/platform/EFR32/NetworkProvisioningServerImpl.cpp +++ b/src/platform/EFR32/NetworkProvisioningServerImpl.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #include diff --git a/src/platform/EFR32/PlatformManagerImpl.cpp b/src/platform/EFR32/PlatformManagerImpl.cpp index ead8c3069d9fc8..dc5d0f3947b3b2 100644 --- a/src/platform/EFR32/PlatformManagerImpl.cpp +++ b/src/platform/EFR32/PlatformManagerImpl.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include diff --git a/src/platform/EFR32/SoftwareUpdateManagerImpl.cpp b/src/platform/EFR32/SoftwareUpdateManagerImpl.cpp index 871f9d86e018d3..993a009ea7b890 100644 --- a/src/platform/EFR32/SoftwareUpdateManagerImpl.cpp +++ b/src/platform/EFR32/SoftwareUpdateManagerImpl.cpp @@ -20,8 +20,8 @@ #if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER -#include -#include +#include +#include #include #include diff --git a/src/platform/EFR32/ThreadStackManagerImpl.cpp b/src/platform/EFR32/ThreadStackManagerImpl.cpp index 75d741c75b578f..14cb14df18bf26 100644 --- a/src/platform/EFR32/ThreadStackManagerImpl.cpp +++ b/src/platform/EFR32/ThreadStackManagerImpl.cpp @@ -26,8 +26,8 @@ /* this file behaves like a config.h, comes first */ #include -#include -#include +#include +#include #include #include diff --git a/src/platform/ESP32/ConfigurationManagerImpl.cpp b/src/platform/ESP32/ConfigurationManagerImpl.cpp index 83d61bde0af125..b6d25b34af2294 100644 --- a/src/platform/ESP32/ConfigurationManagerImpl.cpp +++ b/src/platform/ESP32/ConfigurationManagerImpl.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include "esp_wifi.h" diff --git a/src/platform/ESP32/ConnectivityManagerImpl.cpp b/src/platform/ESP32/ConnectivityManagerImpl.cpp index 17ec582c0be34a..a0537ed62175a0 100644 --- a/src/platform/ESP32/ConnectivityManagerImpl.cpp +++ b/src/platform/ESP32/ConnectivityManagerImpl.cpp @@ -20,7 +20,7 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #endif #include diff --git a/src/platform/ESP32/NetworkProvisioningServerImpl.cpp b/src/platform/ESP32/NetworkProvisioningServerImpl.cpp index 172a6aa8a8acdf..6de68937732a2b 100644 --- a/src/platform/ESP32/NetworkProvisioningServerImpl.cpp +++ b/src/platform/ESP32/NetworkProvisioningServerImpl.cpp @@ -19,7 +19,7 @@ /* this file behaves like a config.h, comes first */ #include -#include +#include #include #include diff --git a/src/platform/ESP32/PlatformManagerImpl.cpp b/src/platform/ESP32/PlatformManagerImpl.cpp index 9a66b5bb0bfd98..871b063c0e88b9 100644 --- a/src/platform/ESP32/PlatformManagerImpl.cpp +++ b/src/platform/ESP32/PlatformManagerImpl.cpp @@ -27,7 +27,7 @@ #include #include -#include +#include #include "esp_event.h" #include "esp_heap_caps_init.h" diff --git a/src/platform/ESP32/SoftwareUpdateManagerImpl.cpp b/src/platform/ESP32/SoftwareUpdateManagerImpl.cpp index c8cc51d0aefd4d..054cf66f0a877e 100644 --- a/src/platform/ESP32/SoftwareUpdateManagerImpl.cpp +++ b/src/platform/ESP32/SoftwareUpdateManagerImpl.cpp @@ -24,8 +24,8 @@ #include #include -#include -#include +#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.ipp b/src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.cpp similarity index 100% rename from src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.ipp rename to src/platform/FreeRTOS/GenericThreadStackManagerImpl_FreeRTOS.cpp diff --git a/src/platform/K32W/ConfigurationManagerImpl.cpp b/src/platform/K32W/ConfigurationManagerImpl.cpp index a931ef1eb9a0b1..c50a40759d5645 100644 --- a/src/platform/K32W/ConfigurationManagerImpl.cpp +++ b/src/platform/K32W/ConfigurationManagerImpl.cpp @@ -28,7 +28,7 @@ #include #include -#include +#include #include "fsl_reset.h" diff --git a/src/platform/K32W/ConnectivityManagerImpl.cpp b/src/platform/K32W/ConnectivityManagerImpl.cpp index 2c0d81e177bec8..025d87bb887e68 100644 --- a/src/platform/K32W/ConnectivityManagerImpl.cpp +++ b/src/platform/K32W/ConnectivityManagerImpl.cpp @@ -30,11 +30,11 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include +#include #endif using namespace ::chip; diff --git a/src/platform/K32W/NetworkProvisioningServerImpl.cpp b/src/platform/K32W/NetworkProvisioningServerImpl.cpp index 48fba9f3c3e244..936dad31fe8de5 100644 --- a/src/platform/K32W/NetworkProvisioningServerImpl.cpp +++ b/src/platform/K32W/NetworkProvisioningServerImpl.cpp @@ -19,7 +19,7 @@ /* this file behaves like a config.h, comes first */ #include -#include +#include #include #include diff --git a/src/platform/K32W/PlatformManagerImpl.cpp b/src/platform/K32W/PlatformManagerImpl.cpp index 1917fea80f9a53..9e7727ad5ab94c 100644 --- a/src/platform/K32W/PlatformManagerImpl.cpp +++ b/src/platform/K32W/PlatformManagerImpl.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include diff --git a/src/platform/K32W/SoftwareUpdateManagerImpl.cpp b/src/platform/K32W/SoftwareUpdateManagerImpl.cpp index 07e1b1e3c5c72e..c464bb327c24a6 100644 --- a/src/platform/K32W/SoftwareUpdateManagerImpl.cpp +++ b/src/platform/K32W/SoftwareUpdateManagerImpl.cpp @@ -24,8 +24,8 @@ #include #include -#include -#include +#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/K32W/ThreadStackManagerImpl.cpp b/src/platform/K32W/ThreadStackManagerImpl.cpp index bba306009ac0ca..fc317af3eeb059 100644 --- a/src/platform/K32W/ThreadStackManagerImpl.cpp +++ b/src/platform/K32W/ThreadStackManagerImpl.cpp @@ -31,8 +31,8 @@ #include #include -#include -#include +#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/Linux/ConfigurationManagerImpl.cpp b/src/platform/Linux/ConfigurationManagerImpl.cpp index bf6e658ab73dbf..6d12c43e7ea8f8 100644 --- a/src/platform/Linux/ConfigurationManagerImpl.cpp +++ b/src/platform/Linux/ConfigurationManagerImpl.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/platform/Linux/ConnectivityManagerImpl.cpp b/src/platform/Linux/ConnectivityManagerImpl.cpp index 7e4f23dafa308e..e9435ca880c972 100644 --- a/src/platform/Linux/ConnectivityManagerImpl.cpp +++ b/src/platform/Linux/ConnectivityManagerImpl.cpp @@ -27,15 +27,15 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include +#include #endif #if CHIP_DEVICE_CONFIG_ENABLE_WPA -#include +#include #endif using namespace ::chip; diff --git a/src/platform/Linux/PlatformManagerImpl.cpp b/src/platform/Linux/PlatformManagerImpl.cpp index 15c0fa4df6323f..8cba6a74b4e1df 100644 --- a/src/platform/Linux/PlatformManagerImpl.cpp +++ b/src/platform/Linux/PlatformManagerImpl.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.ipp b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.cpp similarity index 100% rename from src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.ipp rename to src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.cpp diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread_LwIP.ipp b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread_LwIP.cpp similarity index 99% rename from src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread_LwIP.ipp rename to src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread_LwIP.cpp index 829bb8d8140749..646fb39038dbe1 100644 --- a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread_LwIP.ipp +++ b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread_LwIP.cpp @@ -34,7 +34,7 @@ #include #include -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/README.md b/src/platform/README.md index d29cea62fb9903..cc68a9c32e5cfd 100644 --- a/src/platform/README.md +++ b/src/platform/README.md @@ -55,7 +55,7 @@ goals. 5. [Overriding Generic Behaviors](#Overriding-Generic-Behaviors)
6. [Multiple Inheritance and Subclassing of Generic Implementations](#Multiple-Inheritance-and-Subclassing-of-Generic-Implementations)
7. [Static Virtualization of Generic Implementation Behavior](#Static-Virtualization-of-Generic-Implementation-Behavior)
-8. [.ipp Files and Explicit Template Instantiation](#-ipp-files-and-explicit-template-instantiation)
+8. [.cpp Files and Explicit Template Instantiation](#-ipp-files-and-explicit-template-instantiation)
--- @@ -506,7 +506,7 @@ void GenericPlatformManagerImpl::DispatchEventToApplication(const CHI } ``` -### .ipp Files and Explicit Template Instantiation +### .cpp Files and Explicit Template Instantiation The rules for C++ templates require that the compiler 'see' the full definition of a class template at the moment of its instantiation. (Instantiation in this @@ -518,7 +518,7 @@ header file, which must then be included before the moment of instantiation. To provide a separation between the definition of a class template and the definitions of its members, the CHIP Device Layer places all non-inlined template member definitions into a separate file. This file has the same base -name as the template header file, but with a `.ipp` suffix. This pattern reduces +name as the template header file, but with a `.cpp` suffix. This pattern reduces clutter in the header file and makes it possible to include the non-inlined member definitions only when they are needed (more on this below). @@ -535,7 +535,7 @@ protected: ``` ```cpp -/* contents of GenericConfigurationManagerImpl.ipp */ +/* contents of GenericConfigurationManagerImpl.cpp */ template CHIP_ERROR GenericConfigurationManagerImpl::_GetDeviceId(uint64_t & deviceId) @@ -567,14 +567,14 @@ extern template class GenericConfigurationManagerImpl; ... ``` -Then, within a corresponding .cpp file, the template's .ipp file is included and +Then, within a corresponding .cpp file, the template's .cpp file is included and a `template class` definition is used to force an explicit instantiation of the template. ```cpp /* contents of ConfigurationManagerImpl.cpp */ -#include +#include // Fully instantiate the GenericConfigurationManagerImpl class. template class GenericConfigurationManagerImpl; diff --git a/src/platform/Zephyr/GenericBLEManagerImpl_Zephyr.ipp b/src/platform/Zephyr/GenericBLEManagerImpl_Zephyr.cpp similarity index 100% rename from src/platform/Zephyr/GenericBLEManagerImpl_Zephyr.ipp rename to src/platform/Zephyr/GenericBLEManagerImpl_Zephyr.cpp diff --git a/src/platform/Zephyr/GenericThreadStackManagerImpl_Zephyr.ipp b/src/platform/Zephyr/GenericThreadStackManagerImpl_Zephyr.cpp similarity index 99% rename from src/platform/Zephyr/GenericThreadStackManagerImpl_Zephyr.ipp rename to src/platform/Zephyr/GenericThreadStackManagerImpl_Zephyr.cpp index e9b9f13a186c8a..d660c38463565d 100644 --- a/src/platform/Zephyr/GenericThreadStackManagerImpl_Zephyr.ipp +++ b/src/platform/Zephyr/GenericThreadStackManagerImpl_Zephyr.cpp @@ -25,7 +25,7 @@ #ifndef GENERIC_THREAD_STACK_MANAGER_IMPL_ZEPHYR_IPP #define GENERIC_THREAD_STACK_MANAGER_IMPL_ZEPHYR_IPP -#include +#include #include #include diff --git a/src/platform/nRF5/ConfigurationManagerImpl.cpp b/src/platform/nRF5/ConfigurationManagerImpl.cpp index 84d18117106a13..29a1b378353e63 100644 --- a/src/platform/nRF5/ConfigurationManagerImpl.cpp +++ b/src/platform/nRF5/ConfigurationManagerImpl.cpp @@ -25,13 +25,13 @@ #include #include -#include +#include #include #include #if CHIP_DEVICE_CONFIG_ENABLE_FACTORY_PROVISIONING -#include +#include #endif // CHIP_DEVICE_CONFIG_ENABLE_FACTORY_PROVISIONING #include diff --git a/src/platform/nRF5/ConnectivityManagerImpl.cpp b/src/platform/nRF5/ConnectivityManagerImpl.cpp index a8014cb1a72dfe..668eff80900aca 100644 --- a/src/platform/nRF5/ConnectivityManagerImpl.cpp +++ b/src/platform/nRF5/ConnectivityManagerImpl.cpp @@ -19,11 +19,11 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include +#include #endif #include diff --git a/src/platform/nRF5/PlatformManagerImpl.cpp b/src/platform/nRF5/PlatformManagerImpl.cpp index 679d7c90862d5e..c3cb9e3489cfa2 100644 --- a/src/platform/nRF5/PlatformManagerImpl.cpp +++ b/src/platform/nRF5/PlatformManagerImpl.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include diff --git a/src/platform/nRF5/SoftwareUpdateManagerImpl.cpp b/src/platform/nRF5/SoftwareUpdateManagerImpl.cpp index 7622520a83a4ca..0ac11dca8cb497 100644 --- a/src/platform/nRF5/SoftwareUpdateManagerImpl.cpp +++ b/src/platform/nRF5/SoftwareUpdateManagerImpl.cpp @@ -20,7 +20,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/nRF5/ThreadStackManagerImpl.cpp b/src/platform/nRF5/ThreadStackManagerImpl.cpp index b90df6f0f7a73a..3c0472da0cca40 100644 --- a/src/platform/nRF5/ThreadStackManagerImpl.cpp +++ b/src/platform/nRF5/ThreadStackManagerImpl.cpp @@ -26,8 +26,8 @@ /* this file behaves like a config.h, comes first */ #include -#include -#include +#include +#include #include #include diff --git a/src/platform/nrfconnect/BLEManagerImpl.cpp b/src/platform/nrfconnect/BLEManagerImpl.cpp index ef4910409fd748..9d89e49cced948 100644 --- a/src/platform/nrfconnect/BLEManagerImpl.cpp +++ b/src/platform/nrfconnect/BLEManagerImpl.cpp @@ -25,7 +25,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/nrfconnect/ConfigurationManagerImpl.cpp b/src/platform/nrfconnect/ConfigurationManagerImpl.cpp index 0cc0294af78488..bde9059bf89321 100644 --- a/src/platform/nrfconnect/ConfigurationManagerImpl.cpp +++ b/src/platform/nrfconnect/ConfigurationManagerImpl.cpp @@ -24,13 +24,13 @@ #include #include -#include +#include #include #include #if CHIP_DEVICE_CONFIG_ENABLE_FACTORY_PROVISIONING -#include +#include #endif // CHIP_DEVICE_CONFIG_ENABLE_FACTORY_PROVISIONING #include diff --git a/src/platform/nrfconnect/ConnectivityManagerImpl.cpp b/src/platform/nrfconnect/ConnectivityManagerImpl.cpp index 6837f06bb2b7c8..10a398eed5778c 100644 --- a/src/platform/nrfconnect/ConnectivityManagerImpl.cpp +++ b/src/platform/nrfconnect/ConnectivityManagerImpl.cpp @@ -26,11 +26,11 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include +#include #endif using namespace ::chip; diff --git a/src/platform/nrfconnect/PlatformManagerImpl.cpp b/src/platform/nrfconnect/PlatformManagerImpl.cpp index 638fe367d99871..488af60737cc37 100644 --- a/src/platform/nrfconnect/PlatformManagerImpl.cpp +++ b/src/platform/nrfconnect/PlatformManagerImpl.cpp @@ -24,7 +24,7 @@ #include #include -#include +#include #include diff --git a/src/platform/nrfconnect/ThreadStackManagerImpl.cpp b/src/platform/nrfconnect/ThreadStackManagerImpl.cpp index 399dc4af8b6972..120da81df78e29 100644 --- a/src/platform/nrfconnect/ThreadStackManagerImpl.cpp +++ b/src/platform/nrfconnect/ThreadStackManagerImpl.cpp @@ -24,7 +24,7 @@ /* this file behaves like a config.h, comes first */ #include -#include +#include #include #include diff --git a/src/platform/qpg6100/ConfigurationManagerImpl.cpp b/src/platform/qpg6100/ConfigurationManagerImpl.cpp index 3858eb3eeb8ab3..a4e48e648dbfd4 100644 --- a/src/platform/qpg6100/ConfigurationManagerImpl.cpp +++ b/src/platform/qpg6100/ConfigurationManagerImpl.cpp @@ -24,13 +24,13 @@ #include #include -#include +#include #include #include #if CHIP_DEVICE_CONFIG_ENABLE_FACTORY_PROVISIONING -#include +#include #endif // CHIP_DEVICE_CONFIG_ENABLE_FACTORY_PROVISIONING #include diff --git a/src/platform/qpg6100/ConnectivityManagerImpl.cpp b/src/platform/qpg6100/ConnectivityManagerImpl.cpp index 4cfc39af5b723e..f1e6edfa26e45d 100644 --- a/src/platform/qpg6100/ConnectivityManagerImpl.cpp +++ b/src/platform/qpg6100/ConnectivityManagerImpl.cpp @@ -18,11 +18,11 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include +#include #endif #include diff --git a/src/platform/qpg6100/PlatformManagerImpl.cpp b/src/platform/qpg6100/PlatformManagerImpl.cpp index 0122ac35b36c54..dba3664d243c9c 100644 --- a/src/platform/qpg6100/PlatformManagerImpl.cpp +++ b/src/platform/qpg6100/PlatformManagerImpl.cpp @@ -24,7 +24,7 @@ #include #include -#include +#include #include diff --git a/src/platform/qpg6100/SoftwareUpdateManagerImpl.cpp b/src/platform/qpg6100/SoftwareUpdateManagerImpl.cpp index 13f3fa811dbe60..ce64b8139c7c29 100644 --- a/src/platform/qpg6100/SoftwareUpdateManagerImpl.cpp +++ b/src/platform/qpg6100/SoftwareUpdateManagerImpl.cpp @@ -19,7 +19,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/qpg6100/ThreadStackManagerImpl.cpp b/src/platform/qpg6100/ThreadStackManagerImpl.cpp index 4f418fc44b19bc..15cc5d75444081 100644 --- a/src/platform/qpg6100/ThreadStackManagerImpl.cpp +++ b/src/platform/qpg6100/ThreadStackManagerImpl.cpp @@ -25,8 +25,8 @@ /* this file behaves like a config.h, comes first */ #include -#include -#include +#include +#include #include #include From 04ac26bc349c415699efbd431fa3fa11e0febcf1 Mon Sep 17 00:00:00 2001 From: doru91 Date: Tue, 13 Oct 2020 18:23:28 +0300 Subject: [PATCH 10/40] [K32W] Add Gn/Ninja for the ELock Demo App (#3192) * [K32W] Refactor E-Lock Demo App Move platform code to examples/platform/k32w. Signed-off-by: Doru Gucea * [K32W] Add GN/Ninja build WIP Signed-off-by: Doru Gucea * [K32W] Hack for building external mbedtls both for OT and CHIP Signed-off-by: Doru Gucea * [K32W] Fix Usage Fault Interrupt handlers for Radio were not installed. Signed-off-by: Doru Gucea * [K32W] Coding style fixes Signed-off-by: Doru Gucea * [K32W] Remove hack around external mbedtls build Signed-off-by: Doru Gucea * [K32W] Fixes for GN Build * README update * fix linker error due to missing mbedtls define Signed-off-by: Doru Gucea * Restyled by gn * Restyled by prettier-markdown Signed-off-by: Doru Gucea * [K32W] Add missing mbedtls.gni file Signed-off-by: Doru Gucea * Restyled by gn Co-authored-by: Restyled.io --- BUILD.gn | 15 ++ config/k32w/toolchain/BUILD.gn | 24 ++ examples/build_overrides/k32w_sdk.gni | 18 ++ examples/lock-app/k32w/.gn | 29 +++ examples/lock-app/k32w/BUILD.gn | 94 ++++++++ examples/lock-app/k32w/Makefile | 11 +- examples/lock-app/k32w/README.md | 34 +-- examples/lock-app/k32w/args.gni | 19 ++ examples/lock-app/k32w/build | 1 + examples/lock-app/k32w/build_overrides | 1 + examples/platform/k32w/BUILD.gn | 28 +++ examples/platform/k32w/app/BUILD.gn | 25 +++ examples/platform/k32w/app/args.gni | 32 +++ .../ldscripts/chip-k32w061-lock-example.ld | 0 .../app/project_include}/CHIPProjectConfig.h | 0 .../app/project_include}/FreeRTOSConfig.h | 0 .../app/project_include}/OpenThreadConfig.h | 4 +- examples/platform/k32w/app/support/BUILD.gn | 32 +++ .../k32w/app}/support/FreeRtosMbedtlsMutex.c | 0 .../k32w/app/support}/FreeRtosMbedtlsMutex.h | 0 examples/platform/k32w/args.gni | 34 +++ .../k32w/doc/images/debg-conf.JPG | Bin .../k32w/doc/images/k32w-dk6.jpg | Bin .../k32w/doc/images/mcux-sdk-download.JPG | Bin .../k32w/doc/images/select-sdk.JPG | Bin .../main => platform/k32w/util}/LEDWidget.cpp | 0 .../k32w/util}/include/LEDWidget.h | 0 gn/build_overrides/k32w_sdk.gni | 18 ++ gn_build.sh | 17 ++ scripts/flashing/k32w_firmware_utils.py | 152 +++++++++++++ src/lwip/BUILD.gn | 6 +- src/platform/BUILD.gn | 34 +++ src/platform/K32W/args.gni | 40 ++++ src/platform/device.gni | 8 +- third_party/k32w_sdk/BUILD.gn | 67 ++++++ third_party/k32w_sdk/k32w_executable.gni | 46 ++++ third_party/k32w_sdk/k32w_sdk.gni | 209 ++++++++++++++++++ third_party/mbedtls/BUILD.gn | 83 +------ third_party/mbedtls/mbedtls.gni | 118 ++++++++++ .../openthread/platforms/k32w/BUILD.gn | 62 ++++++ 40 files changed, 1148 insertions(+), 113 deletions(-) create mode 100644 config/k32w/toolchain/BUILD.gn create mode 100644 examples/build_overrides/k32w_sdk.gni create mode 100644 examples/lock-app/k32w/.gn create mode 100644 examples/lock-app/k32w/BUILD.gn create mode 100644 examples/lock-app/k32w/args.gni create mode 120000 examples/lock-app/k32w/build create mode 120000 examples/lock-app/k32w/build_overrides create mode 100644 examples/platform/k32w/BUILD.gn create mode 100644 examples/platform/k32w/app/BUILD.gn create mode 100644 examples/platform/k32w/app/args.gni rename examples/{lock-app/k32w/main => platform/k32w/app}/ldscripts/chip-k32w061-lock-example.ld (100%) rename examples/{lock-app/k32w/main/include => platform/k32w/app/project_include}/CHIPProjectConfig.h (100%) rename examples/{lock-app/k32w/main/include => platform/k32w/app/project_include}/FreeRTOSConfig.h (100%) rename examples/{lock-app/k32w/main/include => platform/k32w/app/project_include}/OpenThreadConfig.h (94%) create mode 100644 examples/platform/k32w/app/support/BUILD.gn rename examples/{lock-app/k32w/main => platform/k32w/app}/support/FreeRtosMbedtlsMutex.c (100%) rename examples/{lock-app/k32w/main/include => platform/k32w/app/support}/FreeRtosMbedtlsMutex.h (100%) create mode 100644 examples/platform/k32w/args.gni rename examples/{lock-app => platform}/k32w/doc/images/debg-conf.JPG (100%) rename examples/{lock-app => platform}/k32w/doc/images/k32w-dk6.jpg (100%) rename examples/{lock-app => platform}/k32w/doc/images/mcux-sdk-download.JPG (100%) rename examples/{lock-app => platform}/k32w/doc/images/select-sdk.JPG (100%) rename examples/{lock-app/k32w/main => platform/k32w/util}/LEDWidget.cpp (100%) rename examples/{lock-app/k32w/main => platform/k32w/util}/include/LEDWidget.h (100%) create mode 100644 gn/build_overrides/k32w_sdk.gni create mode 100755 scripts/flashing/k32w_firmware_utils.py create mode 100644 src/platform/K32W/args.gni create mode 100644 third_party/k32w_sdk/BUILD.gn create mode 100644 third_party/k32w_sdk/k32w_executable.gni create mode 100644 third_party/k32w_sdk/k32w_sdk.gni create mode 100644 third_party/mbedtls/mbedtls.gni create mode 100644 third_party/openthread/platforms/k32w/BUILD.gn diff --git a/BUILD.gn b/BUILD.gn index d3ced42cc4e4ce..6810a2a5da524c 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -117,6 +117,9 @@ if (current_toolchain != "${dir_pw_toolchain}/dummy:dummy") { # Set this to true to enable qpg6100 builds by default. enable_qpg6100_builds = false + + # Set this to true to enable k32w builds by default. + enable_k32w_builds = false } declare_args() { @@ -152,6 +155,9 @@ if (current_toolchain != "${dir_pw_toolchain}/dummy:dummy") { # Build the efr32 lighting app example. enable_efr32_lighting_app_build = enable_efr32_builds + + # Build the k32w lock app example. + enable_k32w_lock_app_build = enable_k32w_builds } chip_build("host_clang") { @@ -230,6 +236,12 @@ if (current_toolchain != "${dir_pw_toolchain}/dummy:dummy") { } } + if (enable_k32w_lock_app_build) { + group("k32w_lock_app") { + deps = [ "${chip_root}/examples/lock-app/k32w(${chip_root}/config/k32w/toolchain:k32w_lock_app)" ] + } + } + group("default") { deps = [] if (enable_host_clang_build) { @@ -267,6 +279,9 @@ if (current_toolchain != "${dir_pw_toolchain}/dummy:dummy") { if (enable_efr32_lock_app_build) { deps += [ ":efr32_lock_app" ] } + if (enable_k32w_lock_app_build) { + deps += [ ":k32w_lock_app" ] + } } group("check") { diff --git a/config/k32w/toolchain/BUILD.gn b/config/k32w/toolchain/BUILD.gn new file mode 100644 index 00000000000000..1bcb0bb9cc5019 --- /dev/null +++ b/config/k32w/toolchain/BUILD.gn @@ -0,0 +1,24 @@ +# Copyright (c) 2020 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/chip.gni") + +import("//build/toolchain/arm_gcc/arm_toolchain.gni") + +arm_toolchain("k32w_lock_app") { + toolchain_args = { + current_os = "freertos" + import("${chip_root}/examples/lock-app/k32w/args.gni") + } +} diff --git a/examples/build_overrides/k32w_sdk.gni b/examples/build_overrides/k32w_sdk.gni new file mode 100644 index 00000000000000..a8ae04f65467d4 --- /dev/null +++ b/examples/build_overrides/k32w_sdk.gni @@ -0,0 +1,18 @@ +# Copyright (c) 2020 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. + +declare_args() { + # Root directory for k32w SDK. + k32w_sdk_build_root = "//third_party/connectedhomeip/third_party/k32w_sdk" +} diff --git a/examples/lock-app/k32w/.gn b/examples/lock-app/k32w/.gn new file mode 100644 index 00000000000000..94532917636fd3 --- /dev/null +++ b/examples/lock-app/k32w/.gn @@ -0,0 +1,29 @@ +# Copyright (c) 2020 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. + +# The location of the build configuration file. +buildconfig = "//build/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +# Allow loading paths relative to //gn. +secondary_source = "//third_party/connectedhomeip/gn/" + +default_args = { + target_cpu = "arm" + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/lock-app/k32w/BUILD.gn b/examples/lock-app/k32w/BUILD.gn new file mode 100644 index 00000000000000..5a023e38fc5bda --- /dev/null +++ b/examples/lock-app/k32w/BUILD.gn @@ -0,0 +1,94 @@ +# Copyright (c) 2020 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/chip.gni") +import("//build_overrides/k32w_sdk.gni") +import("//build_overrides/openthread.gni") + +import("${k32w_sdk_build_root}/k32w_executable.gni") +import("${k32w_sdk_build_root}/k32w_sdk.gni") + +assert(current_os == "freertos") + +k32w_platform_dir = "${chip_root}/examples/platform/k32w" + +k32w_sdk("sdk") { + include_dirs = [ + "main/include", + "main", + "${k32w_platform_dir}/app/project_include", + "${k32w_platform_dir}/app/support", + "${chip_root}/examples/lock-app/lock-common", + "${chip_root}/src/app/util", + "${k32w_platform_dir}/util/include", + ] + + sources = [ + "${k32w_platform_dir}/app/project_include/CHIPProjectConfig.h", + "${k32w_platform_dir}/app/project_include/FreeRTOSConfig.h", + "${k32w_platform_dir}/app/project_include/OpenThreadConfig.h", + "main/include/app_config.h", + ] + + public_deps = + [ "${chip_root}/third_party/openthread/platforms:libopenthread-platform" ] + + defines = [] + if (is_debug) { + defines += [ "BUILD_RELEASE=0" ] + } else { + defines += [ "BUILD_RELEASE=1" ] + } +} + +k32w_executable("lock_app") { + output_name = "chip-k32w061-lock-example" + + sources = [ + "${k32w_platform_dir}/util/LEDWidget.cpp", + "${k32w_platform_dir}/util/include/LEDWidget.h", + "main/AppTask.cpp", + "main/BoltLockManager.cpp", + "main/ZclCallbacks.cpp", + "main/include/AppEvent.h", + "main/include/AppTask.h", + "main/include/BoltLockManager.h", + "main/main.cpp", + ] + + deps = [ + ":sdk", + "${chip_root}/examples/common/chip-app-server:chip-app-server", + "${chip_root}/examples/lock-app/lock-common", + "${chip_root}/src/lib", + "${chip_root}/third_party/mbedtls:mbedtls", + "${k32w_platform_dir}/app/support:freertos_mbedtls_lock_support", + "${openthread_root}:libopenthread-cli-ftd", + "${openthread_root}:libopenthread-ftd", + ] + + output_dir = root_out_dir + + ldscript = "${k32w_platform_dir}/app/ldscripts/chip-k32w061-lock-example.ld" + + ldflags = [ "-T" + rebase_path(ldscript, root_build_dir) ] +} + +group("k32w") { + deps = [ ":lock_app" ] +} + +group("default") { + deps = [ ":k32w" ] +} diff --git a/examples/lock-app/k32w/Makefile b/examples/lock-app/k32w/Makefile index b2808e3ea3ad30..2589dd714655f7 100644 --- a/examples/lock-app/k32w/Makefile +++ b/examples/lock-app/k32w/Makefile @@ -36,9 +36,9 @@ SRCS = \ $(PROJECT_ROOT)/main/main.cpp \ $(PROJECT_ROOT)/main/AppTask.cpp \ $(PROJECT_ROOT)/main/BoltLockManager.cpp \ - $(PROJECT_ROOT)/main/LEDWidget.cpp \ $(PROJECT_ROOT)/main/ZclCallbacks.cpp \ - $(PROJECT_ROOT)/main/support/FreeRtosMbedtlsMutex.c \ + $(CHIP_ROOT)/examples/platform/k32w/util/LEDWidget.cpp \ + $(CHIP_ROOT)/examples/platform/k32w/app/support/FreeRtosMbedtlsMutex.c \ ${CHIP_ROOT}/src/app/util/af-event.cpp \ $(CHIP_ROOT)/src/app/util/attribute-size.c \ $(CHIP_ROOT)/src/app/util/attribute-storage.c \ @@ -105,6 +105,9 @@ INC_DIRS = \ $(PROJECT_ROOT)/src \ $(PROJECT_ROOT)/main \ $(PROJECT_ROOT)/main/include \ + $(CHIP_ROOT)/examples/platform/k32w/util/include \ + $(CHIP_ROOT)/examples/platform/k32w/app/support \ + $(CHIP_ROOT)/examples/platform/k32w/app/project_include \ $(CHIP_ROOT)/examples/lock-app/lock-common/ \ $(CHIP_ROOT)/examples/common/chip-app-server/include/ \ $(CHIP_ROOT)/src/include/ \ @@ -189,12 +192,12 @@ else CHIP_DEFINES += CHIP_CONFIG_LOG_LEVEL=OT_LOG_LEVEL_DEBG endif -CHIP_PROJECT_CONFIG = $(PROJECT_ROOT)/main/include/CHIPProjectConfig.h +CHIP_PROJECT_CONFIG = ${CHIP_ROOT}/examples/platform/k32w/app/project_include/CHIPProjectConfig.h OPENTHREAD_CONFIGURE_OPTIONS += \ --enable-child-supervision \ --enable-jam-detection -LINKER_SCRIPT = $(PROJECT_ROOT)/main/ldscripts/chip-k32w061-lock-example.ld +LINKER_SCRIPT = ${CHIP_ROOT}/examples/platform/k32w/app/ldscripts/chip-k32w061-lock-example.ld $(call GenerateBuildRules) diff --git a/examples/lock-app/k32w/README.md b/examples/lock-app/k32w/README.md index c4b5a22e2e8076..14e79d131e4e59 100644 --- a/examples/lock-app/k32w/README.md +++ b/examples/lock-app/k32w/README.md @@ -18,7 +18,7 @@ board. ## Introduction -![K32W061 DK6](doc/images/k32w-dk6.jpg) +![K32W061 DK6](../../platform/k32w/doc/images/k32w-dk6.jpg) The K32W lock example application provides a working demonstration of a connected door lock device, built using CHIP, and the NXP K32W061 SDK. The @@ -99,30 +99,21 @@ demo-application was compiled on Ubuntu 20.04). account is created, login and follow the steps for downloading SDK_2.6.1_K32W061DK6. The UI is very intuitive and the correct selection should be similiar with the one from the image below. - ![MCUXpresso SDK Download](doc/images/mcux-sdk-download.JPG) - -- Download the suitable - [ARM GCC toolchain](https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads/7-2018-q2-update) - for your Linux distribution - -- Set two Linux environmental variables based on the above downloaded - packages: - -``` -user@ubuntu:~/Desktop/git/connectedhomeip$ export K32W061_SDK_ROOT=/home/user/Desktop/git/SDK_2.6.1_K32W061DK6 -user@ubuntu:~/Desktop/git/connectedhomeip$ export GNU_INSTALL_ROOT=/home/user/Desktop/git/gcc-arm-none-eabi-7-2018-q2-update/bin/ -``` + ![MCUXpresso SDK Download](../../platform/k32w/doc/images/mcux-sdk-download.JPG) - You may start building the application ``` user@ubuntu:~/Desktop/git/connectedhomeip$ cd examples/lock-app/k32w/ -user@ubuntu:~/Desktop/git/connectedhomeip/examples/lock-app/k32w$ make +user@ubuntu:~/Desktop/git/connectedhomeip/examples/lock-app/k32w$ source third_party/connectedhomeip/scripts/activate.sh +user@ubuntu:~/Desktop/git/connectedhomeip/examples/lock-app/k32w$ gn gen out/debug --args="k32w_sdk_root=\"${K32W061_SDK_ROOT}\" is_debug=true" +user@ubuntu:~/Desktop/git/connectedhomeip/examples/lock-app/k32w$ ninja -C out/debug +user@ubuntu: $K32W061_SDK_ROOT/tools/imagetool/sign_images.sh out/debug/ ``` -In case OpenThread fails to compile due to some signing errors just follow the -compilation logs and install the recommanded packages (python version > 3, pip3, -pycrypto, pycryptodome): +In case signing errors are encountered just follow the compilation logs and +install the recommanded packages (python version > 3, pip3, pycrypto, +pycryptodome): ``` user@ubuntu:~$ python3 --version @@ -134,8 +125,7 @@ pycrypto 2.6.1 pycryptodome 3.9.8 ``` -The resulting elf file can be found in the build directory and it's named -chip-k32w061-lock-example.elf. +The resulting elf file can be found in out/debug/chip-k32w061-lock-example.elf. @@ -146,7 +136,7 @@ In order to flash the application we recommend using - Import the previously downloaded NXP SDK into MCUXpresso IDE. This can be done by drag-and-dropping the SDK archive into MCUXpresso IDE's "Installed - SDKs" tab; ![Select SDK](doc/images/select-sdk.JPG) + SDKs" tab; ![Select SDK](../../platform/k32w/doc/images/select-sdk.JPG) - Import Project CHIP in MCUXpresso IDE as Makefile Project: File->Import->C/C++->Existing Code as Makefile Project-> Next . Select Project CHIP folder as the Existing Code Location. In the @@ -175,4 +165,4 @@ In order to flash the application we recommend using select "bin" as the Format to use for programming. Make sure the Base address is 0x0. Click Debug. A pop-up window entitled Errors in Workspace will appear. Click Proceed. - ![Debug_configuration](doc/images/debg-conf.JPG) + ![Debug_configuration](../../platform/k32w/doc/images/debg-conf.JPG) diff --git a/examples/lock-app/k32w/args.gni b/examples/lock-app/k32w/args.gni new file mode 100644 index 00000000000000..0644c7a12cc68d --- /dev/null +++ b/examples/lock-app/k32w/args.gni @@ -0,0 +1,19 @@ +# Copyright (c) 2020 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/chip.gni") +import("${chip_root}/examples/platform/k32w/args.gni") + +# SDK target. This is overriden to add our SDK app_config.h & defines. +k32w_sdk_target = get_label_info(":sdk", "label_no_toolchain") diff --git a/examples/lock-app/k32w/build b/examples/lock-app/k32w/build new file mode 120000 index 00000000000000..d56ed62ae4d1ff --- /dev/null +++ b/examples/lock-app/k32w/build @@ -0,0 +1 @@ +third_party/connectedhomeip/build \ No newline at end of file diff --git a/examples/lock-app/k32w/build_overrides b/examples/lock-app/k32w/build_overrides new file mode 120000 index 00000000000000..194ee0b812dc3d --- /dev/null +++ b/examples/lock-app/k32w/build_overrides @@ -0,0 +1 @@ +../../build_overrides/ \ No newline at end of file diff --git a/examples/platform/k32w/BUILD.gn b/examples/platform/k32w/BUILD.gn new file mode 100644 index 00000000000000..1950755cd6d030 --- /dev/null +++ b/examples/platform/k32w/BUILD.gn @@ -0,0 +1,28 @@ +# Copyright (c) 2020 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/chip.gni") +import("//build_overrides/k32w_sdk.gni") + +import("${k32w_sdk_build_root}/k32w_sdk.gni") + +config("chip_examples_project_config") { + include_dirs = [ "app/project_include" ] +} + +source_set("openthread_core_config_k32w_chip_examples") { + sources = [ "app/project_include/OpenThreadConfig.h" ] + public_deps = [ "${chip_root}/third_party/openthread/platforms/k32w:openthread_core_config_k32w" ] + public_configs = [ ":chip_examples_project_config" ] +} diff --git a/examples/platform/k32w/app/BUILD.gn b/examples/platform/k32w/app/BUILD.gn new file mode 100644 index 00000000000000..92e058d128156d --- /dev/null +++ b/examples/platform/k32w/app/BUILD.gn @@ -0,0 +1,25 @@ +# Copyright (c) 2020 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/chip.gni") + +config("chip_examples_project_config") { + include_dirs = [ "app/project_include" ] +} + +source_set("openthread_core_config_k32w_chip_examples") { + sources = [ "app/project_include/OpenThreadConfig.h" ] + public_deps = [ "${chip_root}/third_party/openthread/platforms/k32w:openthread_core_config_k32w" ] + public_configs = [ ":chip_examples_project_config" ] +} diff --git a/examples/platform/k32w/app/args.gni b/examples/platform/k32w/app/args.gni new file mode 100644 index 00000000000000..19b7d20a1cf122 --- /dev/null +++ b/examples/platform/k32w/app/args.gni @@ -0,0 +1,32 @@ +# Copyright (c) 2020 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/chip.gni") + +import("${chip_root}/src/platform/K32W/args.gni") + +arm_float_abi = "soft" +arm_cpu = "cortex-m4" + +openthread_project_core_config_file = "OpenThreadConfig.h" + +chip_ble_project_config_include = "" +chip_device_project_config_include = "" +chip_project_config_include = "" +chip_inet_project_config_include = "" +chip_system_project_config_include = "" + +chip_system_config_provide_statistics = false +chip_inet_config_enable_raw_endpoint = false +chip_with_nlfaultinjection = true diff --git a/examples/lock-app/k32w/main/ldscripts/chip-k32w061-lock-example.ld b/examples/platform/k32w/app/ldscripts/chip-k32w061-lock-example.ld similarity index 100% rename from examples/lock-app/k32w/main/ldscripts/chip-k32w061-lock-example.ld rename to examples/platform/k32w/app/ldscripts/chip-k32w061-lock-example.ld diff --git a/examples/lock-app/k32w/main/include/CHIPProjectConfig.h b/examples/platform/k32w/app/project_include/CHIPProjectConfig.h similarity index 100% rename from examples/lock-app/k32w/main/include/CHIPProjectConfig.h rename to examples/platform/k32w/app/project_include/CHIPProjectConfig.h diff --git a/examples/lock-app/k32w/main/include/FreeRTOSConfig.h b/examples/platform/k32w/app/project_include/FreeRTOSConfig.h similarity index 100% rename from examples/lock-app/k32w/main/include/FreeRTOSConfig.h rename to examples/platform/k32w/app/project_include/FreeRTOSConfig.h diff --git a/examples/lock-app/k32w/main/include/OpenThreadConfig.h b/examples/platform/k32w/app/project_include/OpenThreadConfig.h similarity index 94% rename from examples/lock-app/k32w/main/include/OpenThreadConfig.h rename to examples/platform/k32w/app/project_include/OpenThreadConfig.h index f3c3fa5566f523..954c013d1aa837 100644 --- a/examples/lock-app/k32w/main/include/OpenThreadConfig.h +++ b/examples/platform/k32w/app/project_include/OpenThreadConfig.h @@ -25,8 +25,8 @@ #pragma once // Disable the Nxp-supplied OpenThread logging facilities and use -// the facilities provided by the OpenWeave Device Layer (see -// openweave/src/adaptations/device-layer/K32W/Logging.cpp). +// the facilities provided by the Device Layer (see +// src/platform/K32W/Logging.cpp). #define OPENTHREAD_CONFIG_LOG_OUTPUT OPENTHREAD_CONFIG_LOG_OUTPUT_APP // When operating in a less than ideal RF environment, having a more forgiving configuration diff --git a/examples/platform/k32w/app/support/BUILD.gn b/examples/platform/k32w/app/support/BUILD.gn new file mode 100644 index 00000000000000..93f69668b30442 --- /dev/null +++ b/examples/platform/k32w/app/support/BUILD.gn @@ -0,0 +1,32 @@ +# Copyright (c) 2020 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/chip.gni") +import("//build_overrides/k32w_sdk.gni") + +config("support_config") { + include_dirs = [ "../../.." ] +} + +source_set("freertos_mbedtls_lock_support") { + sources = [ + "FreeRtosMbedtlsMutex.c", + "FreeRtosMbedtlsMutex.h", + ] + + #TODO: not sure this is required, maybe we should make this dependant on mbedtls + public_deps = [ "${k32w_sdk_build_root}:k32w_sdk" ] + + public_configs = [ ":support_config" ] +} diff --git a/examples/lock-app/k32w/main/support/FreeRtosMbedtlsMutex.c b/examples/platform/k32w/app/support/FreeRtosMbedtlsMutex.c similarity index 100% rename from examples/lock-app/k32w/main/support/FreeRtosMbedtlsMutex.c rename to examples/platform/k32w/app/support/FreeRtosMbedtlsMutex.c diff --git a/examples/lock-app/k32w/main/include/FreeRtosMbedtlsMutex.h b/examples/platform/k32w/app/support/FreeRtosMbedtlsMutex.h similarity index 100% rename from examples/lock-app/k32w/main/include/FreeRtosMbedtlsMutex.h rename to examples/platform/k32w/app/support/FreeRtosMbedtlsMutex.h diff --git a/examples/platform/k32w/args.gni b/examples/platform/k32w/args.gni new file mode 100644 index 00000000000000..9f5900a8cb1f5b --- /dev/null +++ b/examples/platform/k32w/args.gni @@ -0,0 +1,34 @@ +# Copyright (c) 2020 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/chip.gni") + +import("${chip_root}/src/platform/K32W/args.gni") + +arm_float_abi = "soft" +arm_cpu = "cortex-m4" + +openthread_project_core_config_file = "OpenThreadConfig.h" +openthread_core_config_deps = [] +openthread_core_config_deps = [ "${chip_root}/examples/platform/k32w:openthread_core_config_k32w_chip_examples" ] + +chip_ble_project_config_include = "" +chip_device_project_config_include = "" +chip_project_config_include = "" +chip_inet_project_config_include = "" +chip_system_project_config_include = "" + +chip_system_config_provide_statistics = false +chip_inet_config_enable_raw_endpoint = false +chip_with_nlfaultinjection = true diff --git a/examples/lock-app/k32w/doc/images/debg-conf.JPG b/examples/platform/k32w/doc/images/debg-conf.JPG similarity index 100% rename from examples/lock-app/k32w/doc/images/debg-conf.JPG rename to examples/platform/k32w/doc/images/debg-conf.JPG diff --git a/examples/lock-app/k32w/doc/images/k32w-dk6.jpg b/examples/platform/k32w/doc/images/k32w-dk6.jpg similarity index 100% rename from examples/lock-app/k32w/doc/images/k32w-dk6.jpg rename to examples/platform/k32w/doc/images/k32w-dk6.jpg diff --git a/examples/lock-app/k32w/doc/images/mcux-sdk-download.JPG b/examples/platform/k32w/doc/images/mcux-sdk-download.JPG similarity index 100% rename from examples/lock-app/k32w/doc/images/mcux-sdk-download.JPG rename to examples/platform/k32w/doc/images/mcux-sdk-download.JPG diff --git a/examples/lock-app/k32w/doc/images/select-sdk.JPG b/examples/platform/k32w/doc/images/select-sdk.JPG similarity index 100% rename from examples/lock-app/k32w/doc/images/select-sdk.JPG rename to examples/platform/k32w/doc/images/select-sdk.JPG diff --git a/examples/lock-app/k32w/main/LEDWidget.cpp b/examples/platform/k32w/util/LEDWidget.cpp similarity index 100% rename from examples/lock-app/k32w/main/LEDWidget.cpp rename to examples/platform/k32w/util/LEDWidget.cpp diff --git a/examples/lock-app/k32w/main/include/LEDWidget.h b/examples/platform/k32w/util/include/LEDWidget.h similarity index 100% rename from examples/lock-app/k32w/main/include/LEDWidget.h rename to examples/platform/k32w/util/include/LEDWidget.h diff --git a/gn/build_overrides/k32w_sdk.gni b/gn/build_overrides/k32w_sdk.gni new file mode 100644 index 00000000000000..9f3d6dd8a1bb3d --- /dev/null +++ b/gn/build_overrides/k32w_sdk.gni @@ -0,0 +1,18 @@ +# Copyright (c) 2020 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. + +declare_args() { + # Root directory for K32W SDK build files. + k32w_sdk_build_root = "//third_party/k32w_sdk" +} diff --git a/gn_build.sh b/gn_build.sh index 4551532b12c53c..0566fe53a8b68a 100755 --- a/gn_build.sh +++ b/gn_build.sh @@ -114,6 +114,23 @@ else echo "Hint: Set \$EFR32_SDK_ROOT to enable building for EFR32" fi +# K32W SDK setup +k32w_sdk_args="" + +if [[ -d "$K32W061_SDK_ROOT" ]]; then + k32w_sdk_args+="k32w_sdk_root=\"$K32W061_SDK_ROOT\"" + extra_args+=" $k32w_sdk_args enable_k32w_builds=true" +fi + +echo +if [[ ! -d "$K32W061_SDK_ROOT" ]]; then + echo "Hint: Set \$K32W061_SDK_ROOT to enable building for K32W061" +else + echo 'To build the K32W lock sample as a standalone project': + echo "(cd $CHIP_ROOT/examples/lock-app/k32w; gn gen out/debug --args='$k32w_sdk_args'; ninja -C out/debug)" +fi +echo + echo _chip_banner "Build: GN configure" diff --git a/scripts/flashing/k32w_firmware_utils.py b/scripts/flashing/k32w_firmware_utils.py new file mode 100755 index 00000000000000..7a1c5fd9afdc98 --- /dev/null +++ b/scripts/flashing/k32w_firmware_utils.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +# Copyright (c) 2020 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. +"""Flash an K32W device. + +This is layered so that a caller can perform individual operations +through an `Flasher` instance, or operations according to a command line. +For `Flasher`, see the class documentation. For the parse_command() +interface or standalone execution: + +usage: k32w_firmware_utils.py [-h] [--verbose] [--erase] [--application FILE] + [--verify_application] [--reset] [--skip_reset] + [--commander FILE] [--serialno SERIAL] + +Flash K32W device + +optional arguments: + -h, --help show this help message and exit + +configuration: + --verbose, -v Report more verbosely + --commander FILE File name of the commander executable + --serialno SERIAL, -s SERIAL + Serial number of device to flash + +operations: + --erase Erase device + --application FILE Flash an image + --verify_application, --verify-application + Verify the image after flashing + --reset Reset device after flashing + --skip_reset, --skip-reset + Do not reset device after flashing +""" + +import sys + +import firmware_utils + +# Additional options that can be use to configure an `Flasher` +# object (as dictionary keys) and/or passed as command line options. +K32W_OPTIONS = { + # Configuration options define properties used in flashing operations. + 'configuration': { + # Tool configuration options. + 'commander': { + 'help': 'File name of the commander executable', + 'default': 'commander', + 'argparse': { + 'metavar': 'FILE' + }, + 'verify': ['{commander}', '--version'], + 'error': + """\ + Unable to execute {commander}. + + Please ensure that this tool is installed and + available. See the K32W example README for + installation instructions. + + """, + }, + 'serialno': { + 'help': 'Serial number of device to flash', + 'default': None, + 'alias': ['-s'], + 'argparse': { + 'metavar': 'SERIAL' + }, + }, + }, +} + + +class Flasher(firmware_utils.Flasher): + """Manage k32w flashing.""" + + def __init__(self, **options): + super().__init__(platform='K32W', module=__name__, **options) + self.define_options(K32W_OPTIONS) + + # Common command line arguments for commander device subcommands. + DEVICE_ARGUMENTS = [{'optional': 'serialno'}] + + def erase(self): + """Perform `commander device masserase`.""" + return self.run_tool( + 'commander', ['device', 'masserase', self.DEVICE_ARGUMENTS], + name='Erase device') + + def verify(self, image): + """Verify image.""" + return self.run_tool( + 'commander', + ['verify', self.DEVICE_ARGUMENTS, image], + name='Verify', + pass_message='Verified', + fail_message='Not verified', + fail_level=2) + + def flash(self, image): + """Flash image.""" + return self.run_tool( + 'commander', + ['flash', self.DEVICE_ARGUMENTS, image], + name='Flash') + + def reset(self): + """Reset the device.""" + return self.run_tool( + 'commander', + ['device', 'reset', self.DEVICE_ARGUMENTS], + name='Reset') + + def actions(self): + """Perform actions on the device according to self.option.""" + self.log(3, 'Options:', self.option) + + if self.option.erase: + if self.erase().err: + return self + + application = self.optional_file(self.option.application) + if application: + if self.flash(application).err: + return self + if self.option.verify_application: + if self.verify(application).err: + return self + if self.option.reset is None: + self.option.reset = True + + if self.option.reset: + if self.reset().err: + return self + + return self + + +if __name__ == '__main__': + sys.exit(Flasher().flash_command(sys.argv)) diff --git a/src/lwip/BUILD.gn b/src/lwip/BUILD.gn index 86d7a7acacc5d2..e67069faa8eaa1 100644 --- a/src/lwip/BUILD.gn +++ b/src/lwip/BUILD.gn @@ -29,7 +29,7 @@ if (lwip_platform == "") { assert(lwip_platform == "external" || lwip_platform == "standalone" || lwip_platform == "nrf5" || lwip_platform == "efr32" || - lwip_platform == "qpg6100", + lwip_platform == "k32w" || lwip_platform == "qpg6100", "Unsupported lwIP platform: ${lwip_platform}") if (lwip_platform != "external") { @@ -45,6 +45,8 @@ if (lwip_platform == "nrf5") { import("//build_overrides/efr32_sdk.gni") } else if (lwip_platform == "qpg6100") { import("//build_overrides/qpg6100_sdk.gni") +} else if (lwip_platform == "k32w") { + import("//build_overrides/k32w_sdk.gni") } buildconfig_header("lwip_buildconfig") { @@ -113,6 +115,8 @@ if (current_os == "zephyr") { public_deps += [ "${qpg6100_sdk_build_root}:qpg6100_sdk" ] } else if (lwip_platform == "standalone") { public_deps += [ "${chip_root}/src/lib/support" ] + } else if (lwip_platform == "k32w") { + public_deps += [ "${k32w_sdk_build_root}:k32w_sdk" ] } public_configs = [ diff --git a/src/platform/BUILD.gn b/src/platform/BUILD.gn index d05fa68d07e713..ff188bdf46362a 100644 --- a/src/platform/BUILD.gn +++ b/src/platform/BUILD.gn @@ -104,6 +104,11 @@ if (chip_device_platform != "none") { "CHIP_DEVICE_LAYER_TARGET_QPG6100=1", "CHIP_DEVICE_LAYER_TARGET=qpg6100", ] + } else if (chip_device_platform == "k32w") { + defines += [ + "CHIP_DEVICE_LAYER_TARGET_K32W=1", + "CHIP_DEVICE_LAYER_TARGET=K32W", + ] } } } @@ -264,6 +269,35 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { "ESP32/nimble/BLEManagerImpl.cpp", "FreeRTOS/SystemTimeSupport.cpp", ] + } else if (chip_device_platform == "k32w") { + sources += [ + "FreeRTOS/SystemTimeSupport.cpp", + "K32W/BLEManagerImpl.cpp", + "K32W/BLEManagerImpl.h", + "K32W/CHIPDevicePlatformConfig.h", + "K32W/CHIPDevicePlatformEvent.h", + "K32W/ConfigurationManagerImpl.cpp", + "K32W/ConfigurationManagerImpl.h", + "K32W/ConnectivityManagerImpl.cpp", + "K32W/ConnectivityManagerImpl.h", + "K32W/K32WConfig.cpp", + "K32W/K32WConfig.h", + "K32W/Logging.cpp", + "K32W/NetworkProvisioningServerImpl.h", + "K32W/PlatformManagerImpl.cpp", + "K32W/PlatformManagerImpl.h", + "K32W/SoftwareUpdateManagerImpl.h", + ] + + if (chip_enable_openthread) { + public_deps += [ "${openthread_root}:libopenthread-ftd" ] + + sources += [ + "K32W/ThreadStackManagerImpl.cpp", + "K32W/ThreadStackManagerImpl.h", + "OpenThread/OpenThreadUtils.cpp", + ] + } } else if (chip_device_platform == "linux") { sources += [ "Linux/BLEManagerImpl.cpp", diff --git a/src/platform/K32W/args.gni b/src/platform/K32W/args.gni new file mode 100644 index 00000000000000..996410c604d0ff --- /dev/null +++ b/src/platform/K32W/args.gni @@ -0,0 +1,40 @@ +# Copyright (c) 2020 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/chip.gni") +import("//build_overrides/k32w_sdk.gni") +import("//build_overrides/openthread.gni") + +chip_device_platform = "k32w" + +lwip_platform = "k32w" +lwip_ipv6 = true +lwip_ipv4 = false +lwip_api = true + +chip_inet_config_enable_ipv4 = false +chip_inet_config_enable_dns_resolver = false + +chip_build_tests = false + +mbedtls_target = "${chip_root}/third_party/k32w_sdk:mbedtls" +openthread_external_mbedtls = mbedtls_target + +openthread_project_core_config_file = "openthread-core-k32w061-config.h" +openthread_core_config_platform_check_file = + "openthread-core-k32w061-config-check.h" +openthread_core_config_deps = [ "${chip_root}/third_party/openthread/platforms/k32w:libopenthread-k32w-config" ] + +openthread_external_platform = + "${chip_root}/third_party/openthread/platforms/k32w:libopenthread-k32w" diff --git a/src/platform/device.gni b/src/platform/device.gni index 9af4125c942065..16cf04561067ff 100644 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -15,7 +15,7 @@ import("//build_overrides/chip.gni") declare_args() { - # Device platform layer: darwin, efr32, esp32, external, freertos, linux, nrf5, nrfconnect, qpg6100, none. + # Device platform layer: darwin, efr32, esp32, external, freertos, linux, nrf5, nrfconnect, k32w, qpg6100, none. chip_device_platform = "auto" chip_platform_target = "" } @@ -34,7 +34,7 @@ declare_args() { # Enable openthread support. chip_enable_openthread = chip_device_platform == "linux" || chip_device_platform == "nrf5" || - chip_device_platform == "efr32" + chip_device_platform == "efr32" || chip_device_platform == "k32w" # Enable wifi support. chip_enable_wifi = chip_device_platform == "linux" @@ -58,6 +58,8 @@ if (chip_device_platform == "darwin") { _chip_device_layer = "nrfconnect" } else if (chip_device_platform == "qpg6100") { _chip_device_layer = "qpg6100" +} else if (chip_device_platform == "k32w") { + _chip_device_layer = "K32W" } if (chip_device_platform != "external") { @@ -95,5 +97,5 @@ assert( chip_device_platform == "esp32" || chip_device_platform == "external" || chip_device_platform == "linux" || chip_device_platform == "nrf5" || chip_device_platform == "nrfconnect" || - chip_device_platform == "qpg6100", + chip_device_platform == "k32w" || chip_device_platform == "qpg6100", "Please select a valid value for chip_device_platform") diff --git a/third_party/k32w_sdk/BUILD.gn b/third_party/k32w_sdk/BUILD.gn new file mode 100644 index 00000000000000..7cba0c3a9122f4 --- /dev/null +++ b/third_party/k32w_sdk/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2020 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/k32w_sdk.gni") +import("//build_overrides/mbedtls.gni") + +import("${k32w_sdk_build_root}/k32w_sdk.gni") +import("${mbedtls_root}/mbedtls.gni") + +declare_args() { + # Build target to use for k32w SDK. Use this to set global SDK defines. + k32w_sdk_target = "" +} + +assert(k32w_sdk_target != "", "k32w_sdk_target must be specified") + +group("k32w_sdk") { + public_deps = [ k32w_sdk_target ] +} + +config("mbedtls_k32w_config") { + defines = [ + "MBEDTLS_CONFIG_FILE=", + "MBEDTLS_USER_CONFIG_FILE=", + + # These options should really be in the config.h... + "MBEDTLS_FREESCALE_FREERTOS_CALLOC_ALT=1", + "MBEDTLS_THREADING_C=1", + "MBEDTLS_THREADING_ALT=1", + "MBEDTLS_X509_CSR_WRITE_C", + "MBEDTLS_X509_CREATE_C", + "MBEDTLS_PK_WRITE_C", + "MBEDTLS_OID_C", + "MBEDTLS_PEM_WRITE_C", + "MBEDTLS_BASE64_C", + "MBEDTLS_HKDF_C", + "MBEDTLS_ERROR_C", + "MBEDTLS_PKCS5_C", + ] + + include_dirs = [ chip_root ] +} + +mbedtls_target("mbedtls") { + sources = [ + "${k32w_sdk_root}/middleware/mbedtls/port/ksdk/aes_alt.c", + "${k32w_sdk_root}/middleware/mbedtls/port/ksdk/ksdk_mbedtls.c", + ] + + public_configs = [ ":mbedtls_k32w_config" ] + + public_deps = [ + ":k32w_sdk", + "${chip_root}/third_party/openthread/platforms/k32w:openthread_mbedtls_config_k32w", + ] +} diff --git a/third_party/k32w_sdk/k32w_executable.gni b/third_party/k32w_sdk/k32w_executable.gni new file mode 100644 index 00000000000000..205176e2329d20 --- /dev/null +++ b/third_party/k32w_sdk/k32w_executable.gni @@ -0,0 +1,46 @@ +# Copyright (c) 2020 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/toolchain/flashable_executable.gni") + +template("k32w_executable") { + output_base_name = get_path_info(invoker.output_name, "name") + objcopy_image_name = output_base_name + ".hex" + objcopy_image_format = "srec" + objcopy = "arm-none-eabi-objcopy" + + # Copy flashing dependencies to the output directory so that the output + # is collectively self-contained; this allows flashing to work reliably + # even if the build and flashing steps take place on different machines + # or in different containers. + + flashing_runtime_target = target_name + ".flashing_runtime" + copy(flashing_runtime_target) { + sources = [ + "${chip_root}/scripts/flashing/firmware_utils.py", + "${chip_root}/scripts/flashing/k32w_firmware_utils.py", + ] + outputs = [ "${root_out_dir}/{{source_file_part}}" ] + } + + flashing_script_generator = + "${chip_root}/scripts/flashing/gen_flashing_script.py" + flashing_script_name = output_base_name + ".flash.py" + flashing_options = [ "k32w" ] + + flashable_executable(target_name) { + forward_variables_from(invoker, "*") + data_deps = [ ":${flashing_runtime_target}" ] + } +} diff --git a/third_party/k32w_sdk/k32w_sdk.gni b/third_party/k32w_sdk/k32w_sdk.gni new file mode 100644 index 00000000000000..bec9b7cbd4a08e --- /dev/null +++ b/third_party/k32w_sdk/k32w_sdk.gni @@ -0,0 +1,209 @@ +# Copyright (c) 2020 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/chip.gni") +import("//build_overrides/k32w_sdk.gni") +import("//build_overrides/mbedtls.gni") +import("//build_overrides/openthread.gni") + +declare_args() { + # Location of the k32w SDK. + k32w_sdk_root = getenv("K32W_SDK_ROOT") +} + +assert(k32w_sdk_root != "", "k32w_sdk_root must be specified") + +# Defines an k32w SDK build target. +# +# Parameters: +# k32w_sdk_root - The location of the k32w SDK. +# sources - Extra source files to build. +template("k32w_sdk") { + if (defined(invoker.k32w_sdk_root)) { + k32w_sdk_root = invoker.k32w_sdk_root + } + + assert(k32w_sdk_root != "", "k32w_sdk_root must be specified") + + sdk_target_name = target_name + + config("${sdk_target_name}_config") { + include_dirs = [] + if (defined(invoker.include_dirs)) { + include_dirs += invoker.include_dirs + } + + # We want to treat SDK headers as system headers, so that warnings in those + # headers are not fatal. Therefore don't add them directly to include_dirs; + # we will add them to cflags below instead. + _sdk_include_dirs = [ + "${k32w_sdk_root}/boards/k32w061dk6/wireless_examples/openthread/reed/bm", + "${k32w_sdk_root}boards/k32w061dk6/wireless_examples/openthread/enablement", + "${k32w_sdk_root}/CMSIS/Include", + "${k32w_sdk_root}/components/serial_manager", + "${k32w_sdk_root}/components/uart", + "${k32w_sdk_root}/devices/K32W061", + "${k32w_sdk_root}/devices/K32W061/drivers", + "${k32w_sdk_root}/devices/K32W061/utilities", + "${k32w_sdk_root}/devices/K32W061/utilities/debug_console", + "${k32w_sdk_root}/devices/K32W061/utilities/str", + "${k32w_sdk_root}/middleware/mbedtls/port/ksdk", + "${k32w_sdk_root}/middleware/wireless/framework/Common", + "${k32w_sdk_root}/middleware/wireless/framework/Flash/Internal", + "${k32w_sdk_root}/middleware/wireless/framework/FunctionLib", + "${k32w_sdk_root}/middleware/wireless/framework/GPIO", + "${k32w_sdk_root}/middleware/wireless/framework/Keyboard/Interface", + "${k32w_sdk_root}/middleware/wireless/framework/LED/Interface", + "${k32w_sdk_root}/middleware/wireless/framework/Lists", + "${k32w_sdk_root}/middleware/wireless/framework/MemManager/Interface", + "${k32w_sdk_root}/middleware/wireless/framework/OSAbstraction/Interface", + "${k32w_sdk_root}/middleware/wireless/framework/Panic/Interface", + "${k32w_sdk_root}/middleware/wireless/framework/PDM/Include", + "${k32w_sdk_root}/middleware/wireless/framework/RNG/Interface", + "${k32w_sdk_root}/middleware/wireless/framework/SerialManager/Source", + "${k32w_sdk_root}/middleware/wireless/framework/TimersManager/Interface", + "${k32w_sdk_root}/middleware/wireless/framework/TimersManager/Source", + "${k32w_sdk_root}/middleware/wireless/framework/XCVR/DK6", + "${k32w_sdk_root}/middleware/wireless/framework/XCVR/DK6/Build/Include", + "${k32w_sdk_root}/middleware/wireless/ieee-802.15.4/uMac/Include", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/portable/GCC/ARM_CM3", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/include", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/include/private", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/third_party/unity/src", + ] + + libs = [ + "${k32w_sdk_root}/middleware/wireless/ieee-802.15.4/lib/libMiniMac.a", + "${k32w_sdk_root}/middleware/wireless/framework/PDM/Library/libPDM.a", + "${k32w_sdk_root}/middleware/wireless/framework/XCVR/lib/libRadio.a", + ] + + defines = [ + "CPU_K32W061HN", + "CPU_JN518X", + "CPU_JN518X_REV=2", + "JENNIC_CHIP_FAMILY_NAME=_JN518x", + "gPWR_LDOMEM_0_9V_PD=0", + "SDK_DEBUGCONSOLE=0", + "NO_SYSCORECLK_UPD=0", + "USE_RTOS=1", + "FSL_RTOS_FREE_RTOS=1", + "MBEDTLS_FREESCALE_FREERTOS_CALLOC_ALT=1", + "gUartDebugConsole_d=0", + "gUsePdm_d=1", + "gLEDSupported_d", + "gKeyBoardSupported_d", + "gPdmNbSegments=63", + "osCustomStartup=1", + "OM15082=1", + "gKBD_KeysCount_c=3", + "gLEDsOnTargetBoardCnt_c=2", + "gLED_InvertedMode_d=1", + "ENABLE_RAM_VECTOR_TABLE=1", + "gTMR_Enabled_d=1", + "gTimestamp_Enabled_d=0", + "gMainThreadStackSize_c=2048", + "K32W_LOG_ENABLED=1", + "CHIP_ENABLE_OPENTHREAD=1", + "PoolsDetails_c=_block_size_ 512 _number_of_blocks_ 2 _pool_id_(0) _eol_ _block_size_ 768 _number_of_blocks_ 1 _pool_id_(0) _eol_", + "OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE=1", + "SUPPORT_FOR_15_4=1", + ] + + if (defined(invoker.defines)) { + defines += invoker.defines + } + + cflags = [ + "-Wno-unused-function", + "-Wno-conversion", + ] + + # Now add our "system-header" include dirs + foreach(include_dir, _sdk_include_dirs) { + cflags += [ "-isystem" + rebase_path(include_dir, root_build_dir) ] + } + } + + # TODO - Break up this monolith and make it configurable. + source_set(sdk_target_name) { + forward_variables_from(invoker, "*") + + if (!defined(sources)) { + sources = [] + } + + sources += [ + "${k32w_sdk_root}/boards/k32w061dk6/wireless_examples/openthread/enablement/clock_config.c", + "${k32w_sdk_root}/boards/k32w061dk6/wireless_examples/openthread/enablement/pin_mux.c", + "${k32w_sdk_root}/boards/k32w061dk6/wireless_examples/openthread/reed/bm/board.c", + "${k32w_sdk_root}/boards/k32w061dk6/wireless_examples/openthread/reed/bm/board_utility.c", + "${k32w_sdk_root}/boards/k32w061dk6/wireless_examples/openthread/reed/bm/hardware_init.c", + "${k32w_sdk_root}/components/serial_manager/serial_manager.c", + "${k32w_sdk_root}/components/serial_manager/serial_port_uart.c", + "${k32w_sdk_root}/components/uart/usart_adapter.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_aes.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_clock.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_common.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_ctimer.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_flash.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_flexcomm.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_gpio.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_inputmux.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_pint.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_power.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_reset.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_rng.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_sha.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_usart.c", + "${k32w_sdk_root}/devices/K32W061/drivers/fsl_wtimer.c", + "${k32w_sdk_root}/devices/K32W061/mcuxpresso/startup_k32w061.c", + "${k32w_sdk_root}/devices/K32W061/system_K32W061.c", + "${k32w_sdk_root}/devices/K32W061/utilities/debug_console/fsl_debug_console.c", + "${k32w_sdk_root}/devices/K32W061/utilities/str/fsl_str.c", + "${k32w_sdk_root}/middleware/wireless/framework/Common/MicroInt_arm_sdk2.c", + "${k32w_sdk_root}/middleware/wireless/framework/Flash/Internal/Flash_Adapter.c", + "${k32w_sdk_root}/middleware/wireless/framework/FunctionLib/FunctionLib.c", + "${k32w_sdk_root}/middleware/wireless/framework/GPIO/GPIO_Adapter.c", + "${k32w_sdk_root}/middleware/wireless/framework/Keyboard/Source/Keyboard.c", + "${k32w_sdk_root}/middleware/wireless/framework/LED/Source/LED.c", + "${k32w_sdk_root}/middleware/wireless/framework/Lists/GenericList.c", + "${k32w_sdk_root}/middleware/wireless/framework/MemManager/Source/MemManager.c", + "${k32w_sdk_root}/middleware/wireless/framework/OSAbstraction/Source/fsl_os_abstraction_free_rtos.c", + "${k32w_sdk_root}/middleware/wireless/framework/PDM/pdm_port.c", + "${k32w_sdk_root}/middleware/wireless/framework/Panic/Source/Panic.c", + "${k32w_sdk_root}/middleware/wireless/framework/Reset/Reset.c", + "${k32w_sdk_root}/middleware/wireless/framework/TimersManager/Source/TMR_Adapter.c", + "${k32w_sdk_root}/middleware/wireless/framework/TimersManager/Source/TimersManager.c", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/event_groups.c", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/list.c", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/portable/GCC/ARM_CM3/port.c", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/portable/MemMang/heap_3.c", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/queue.c", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/tasks.c", + "${k32w_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/timers.c", + ] + + if (!defined(public_deps)) { + public_deps = [] + } + + public_deps += [ "${openthread_root}/src/core:libopenthread_core_headers" ] + + if (!defined(public_configs)) { + public_configs = [] + } + + public_configs += [ ":${sdk_target_name}_config" ] + } +} diff --git a/third_party/mbedtls/BUILD.gn b/third_party/mbedtls/BUILD.gn index b03c4638ff5dbc..eba5b9a85cc79f 100644 --- a/third_party/mbedtls/BUILD.gn +++ b/third_party/mbedtls/BUILD.gn @@ -22,87 +22,8 @@ if (mbedtls_target != "") { public_deps = [ mbedtls_target ] } } else { - config("mbedtls_config") { - include_dirs = [ "repo/include" ] - } - - static_library("mbedtls") { - sources = [ - "repo/library/aes.c", - "repo/library/aesni.c", - "repo/library/arc4.c", - "repo/library/asn1parse.c", - "repo/library/asn1write.c", - "repo/library/base64.c", - "repo/library/bignum.c", - "repo/library/blowfish.c", - "repo/library/camellia.c", - "repo/library/ccm.c", - "repo/library/certs.c", - "repo/library/chacha20.c", - "repo/library/chachapoly.c", - "repo/library/cipher.c", - "repo/library/cipher_wrap.c", - "repo/library/ctr_drbg.c", - "repo/library/debug.c", - "repo/library/des.c", - "repo/library/dhm.c", - "repo/library/ecdh.c", - "repo/library/ecdsa.c", - "repo/library/ecp.c", - "repo/library/ecp_curves.c", - "repo/library/entropy.c", - "repo/library/entropy_poll.c", - "repo/library/error.c", - "repo/library/gcm.c", - "repo/library/hkdf.c", - "repo/library/hmac_drbg.c", - "repo/library/md.c", - "repo/library/md5.c", - "repo/library/md_wrap.c", - "repo/library/oid.c", - "repo/library/padlock.c", - "repo/library/pem.c", - "repo/library/pk.c", - "repo/library/pk_wrap.c", - "repo/library/pkcs12.c", - "repo/library/pkcs5.c", - "repo/library/pkparse.c", - "repo/library/pkwrite.c", - "repo/library/platform.c", - "repo/library/platform_util.c", - "repo/library/poly1305.c", - "repo/library/ripemd160.c", - "repo/library/rsa.c", - "repo/library/rsa_internal.c", - "repo/library/sha1.c", - "repo/library/sha256.c", - "repo/library/sha512.c", - "repo/library/ssl_cache.c", - "repo/library/ssl_ciphersuites.c", - "repo/library/ssl_cli.c", - "repo/library/ssl_cookie.c", - "repo/library/ssl_srv.c", - "repo/library/ssl_ticket.c", - "repo/library/ssl_tls.c", - "repo/library/version.c", - "repo/library/version_features.c", - "repo/library/x509.c", - "repo/library/x509_create.c", - "repo/library/x509_crl.c", - "repo/library/x509_csr.c", - "repo/library/x509write_crt.c", - "repo/library/x509write_csr.c", - "repo/library/xtea.c", - ] - - if (current_os != "freertos") { - sources += [ "repo/library/timing.c" ] - } - - public_configs = [ ":mbedtls_config" ] + import("mbedtls.gni") - output_name = "libmbedtls" - output_dir = "${root_out_dir}/lib" + mbedtls_target("mbedtls") { } } diff --git a/third_party/mbedtls/mbedtls.gni b/third_party/mbedtls/mbedtls.gni new file mode 100644 index 00000000000000..2a2cd0c98d03e5 --- /dev/null +++ b/third_party/mbedtls/mbedtls.gni @@ -0,0 +1,118 @@ +# Copyright (c) 2020 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/mbedtls.gni") + +template("mbedtls_target") { + mbedtls_target_name = target_name + + _mbedtls_root = "${mbedtls_root}/repo" + + config("${mbedtls_target_name}_config") { + include_dirs = [ "${_mbedtls_root}/include" ] + } + + static_library(mbedtls_target_name) { + forward_variables_from(invoker, "*") + + if (!defined(sources)) { + sources = [] + } + + sources += [ + "${_mbedtls_root}/library/aes.c", + "${_mbedtls_root}/library/aesni.c", + "${_mbedtls_root}/library/arc4.c", + "${_mbedtls_root}/library/asn1parse.c", + "${_mbedtls_root}/library/asn1write.c", + "${_mbedtls_root}/library/base64.c", + "${_mbedtls_root}/library/bignum.c", + "${_mbedtls_root}/library/blowfish.c", + "${_mbedtls_root}/library/camellia.c", + "${_mbedtls_root}/library/ccm.c", + "${_mbedtls_root}/library/certs.c", + "${_mbedtls_root}/library/chacha20.c", + "${_mbedtls_root}/library/chachapoly.c", + "${_mbedtls_root}/library/cipher.c", + "${_mbedtls_root}/library/cipher_wrap.c", + "${_mbedtls_root}/library/cmac.c", + "${_mbedtls_root}/library/ctr_drbg.c", + "${_mbedtls_root}/library/debug.c", + "${_mbedtls_root}/library/des.c", + "${_mbedtls_root}/library/dhm.c", + "${_mbedtls_root}/library/ecdh.c", + "${_mbedtls_root}/library/ecdsa.c", + "${_mbedtls_root}/library/ecjpake.c", + "${_mbedtls_root}/library/ecp.c", + "${_mbedtls_root}/library/ecp_curves.c", + "${_mbedtls_root}/library/entropy.c", + "${_mbedtls_root}/library/entropy_poll.c", + "${_mbedtls_root}/library/error.c", + "${_mbedtls_root}/library/gcm.c", + "${_mbedtls_root}/library/hkdf.c", + "${_mbedtls_root}/library/hmac_drbg.c", + "${_mbedtls_root}/library/md.c", + "${_mbedtls_root}/library/md5.c", + "${_mbedtls_root}/library/md_wrap.c", + "${_mbedtls_root}/library/oid.c", + "${_mbedtls_root}/library/padlock.c", + "${_mbedtls_root}/library/pem.c", + "${_mbedtls_root}/library/pk.c", + "${_mbedtls_root}/library/pk_wrap.c", + "${_mbedtls_root}/library/pkcs12.c", + "${_mbedtls_root}/library/pkcs5.c", + "${_mbedtls_root}/library/pkparse.c", + "${_mbedtls_root}/library/pkwrite.c", + "${_mbedtls_root}/library/platform.c", + "${_mbedtls_root}/library/platform_util.c", + "${_mbedtls_root}/library/poly1305.c", + "${_mbedtls_root}/library/ripemd160.c", + "${_mbedtls_root}/library/rsa.c", + "${_mbedtls_root}/library/rsa_internal.c", + "${_mbedtls_root}/library/sha1.c", + "${_mbedtls_root}/library/sha256.c", + "${_mbedtls_root}/library/sha512.c", + "${_mbedtls_root}/library/ssl_cache.c", + "${_mbedtls_root}/library/ssl_ciphersuites.c", + "${_mbedtls_root}/library/ssl_cli.c", + "${_mbedtls_root}/library/ssl_cookie.c", + "${_mbedtls_root}/library/ssl_srv.c", + "${_mbedtls_root}/library/ssl_ticket.c", + "${_mbedtls_root}/library/ssl_tls.c", + "${_mbedtls_root}/library/threading.c", + "${_mbedtls_root}/library/version.c", + "${_mbedtls_root}/library/version_features.c", + "${_mbedtls_root}/library/x509.c", + "${_mbedtls_root}/library/x509_create.c", + "${_mbedtls_root}/library/x509_crl.c", + "${_mbedtls_root}/library/x509_csr.c", + "${_mbedtls_root}/library/x509write_crt.c", + "${_mbedtls_root}/library/x509write_csr.c", + "${_mbedtls_root}/library/xtea.c", + ] + + if (current_os != "freertos") { + sources += [ "${_mbedtls_root}/library/timing.c" ] + } + + if (!defined(public_configs)) { + public_configs = [] + } + + public_configs += [ ":mbedtls_config" ] + + output_name = "libmbedtls" + output_dir = "${root_out_dir}/lib" + } +} diff --git a/third_party/openthread/platforms/k32w/BUILD.gn b/third_party/openthread/platforms/k32w/BUILD.gn new file mode 100644 index 00000000000000..d0795f5d3a58d3 --- /dev/null +++ b/third_party/openthread/platforms/k32w/BUILD.gn @@ -0,0 +1,62 @@ +# Copyright (c) 2020 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/chip.gni") +import("//build_overrides/k32w_sdk.gni") +import("//build_overrides/openthread.gni") + +config("openthread_k32w_config") { + include_dirs = [ + "${openthread_root}/examples/platforms/k32w/", + "${openthread_root}/examples/platforms/k32w/k32w061", + ] + + include_dirs += [ "${chip_root}/examples/platform/k32w" ] +} + +source_set("openthread_core_config_k32w") { + sources = [ + "${openthread_root}/examples/platforms/k32w/k32w061/openthread-core-k32w061-config-check.h", + "${openthread_root}/examples/platforms/k32w/k32w061/openthread-core-k32w061-config.h", + ] + + public_configs = [ ":openthread_k32w_config" ] +} + +source_set("openthread_mbedtls_config_k32w") { + sources = [ "${openthread_root}/examples/platforms/k32w/k32w061/k32w061-mbedtls-config.h" ] +} + +source_set("libopenthread-k32w") { + sources = [ + "${openthread_root}/examples/platforms/k32w/src/alarm.c", + "${openthread_root}/examples/platforms/k32w/src/diag.c", + "${openthread_root}/examples/platforms/k32w/src/entropy.c", + "${openthread_root}/examples/platforms/k32w/src/flash.c", + "${openthread_root}/examples/platforms/k32w/src/logging.c", + "${openthread_root}/examples/platforms/k32w/src/misc.c", + "${openthread_root}/examples/platforms/k32w/src/radio.c", + "${openthread_root}/examples/platforms/k32w/src/settings_k32w.c", + "${openthread_root}/examples/platforms/k32w/src/system.c", + "${openthread_root}/examples/platforms/k32w/src/uart.c", + ] + + public_deps = [ + ":openthread_core_config_k32w", + "${k32w_sdk_build_root}:k32w_sdk", + "${openthread_root}/src/core:libopenthread_core_headers", + "..:libopenthread-platform", + "..:libopenthread-platform-utils", + ] +} From dab94b8558784b8f21c76b5e585dac6045e92fe0 Mon Sep 17 00:00:00 2001 From: Michael Spang Date: Tue, 13 Oct 2020 12:12:45 -0400 Subject: [PATCH 11/40] clang-tidy: Apply fixes "readability-redundant-control-flow" (#3039) --- src/ble/BLEEndPoint.cpp | 2 -- src/inet/AsyncDNSResolverSockets.cpp | 2 -- src/inet/IPEndPointBasis.cpp | 2 -- src/inet/InetLayer.cpp | 4 ---- src/inet/tests/TestInetLayer.cpp | 7 +------ src/inet/tests/TestInetLayerMulticast.cpp | 2 -- src/lib/message/CHIPExchangeMgr.cpp | 7 +------ src/lib/message/CHIPFabricState.cpp | 6 ------ src/lib/message/CHIPMessageLayer.cpp | 3 --- src/lib/message/CHIPSecurityMgr.cpp | 4 ---- src/lib/message/ExchangeContext.cpp | 2 -- src/lib/support/CHIPArgParser.cpp | 4 +--- src/lib/support/PersistedCounter.cpp | 5 +---- src/platform/Linux/CHIPBluezHelper.cpp | 1 - 14 files changed, 4 insertions(+), 47 deletions(-) diff --git a/src/ble/BLEEndPoint.cpp b/src/ble/BLEEndPoint.cpp index a003ca493db7af..5fa1eae8dcdaae 100644 --- a/src/ble/BLEEndPoint.cpp +++ b/src/ble/BLEEndPoint.cpp @@ -269,8 +269,6 @@ void BLEEndPoint::HandleSubscribeReceived() { DoClose(kBleCloseFlag_SuppressCallback | kBleCloseFlag_AbortTransmission, err); } - - return; } void BLEEndPoint::HandleSubscribeComplete() diff --git a/src/inet/AsyncDNSResolverSockets.cpp b/src/inet/AsyncDNSResolverSockets.cpp index a9fb8cefbb654a..6dcb1572aaf637 100644 --- a/src/inet/AsyncDNSResolverSockets.cpp +++ b/src/inet/AsyncDNSResolverSockets.cpp @@ -294,8 +294,6 @@ void AsyncDNSResolverSockets::Resolve(DNSResolver & resolver) // Release lock. AsyncMutexUnlock(); - - return; } /* Event handler function for asynchronous DNS notification */ diff --git a/src/inet/IPEndPointBasis.cpp b/src/inet/IPEndPointBasis.cpp index be5b16c5bdb4ad..a95dcf3d60e637 100644 --- a/src/inet/IPEndPointBasis.cpp +++ b/src/inet/IPEndPointBasis.cpp @@ -1167,8 +1167,6 @@ void IPEndPointBasis::HandlePendingIO(uint16_t aPort) if (OnReceiveError != nullptr && lStatus != chip::System::MapErrorPOSIX(EAGAIN)) OnReceiveError(this, lStatus, nullptr); } - - return; } #endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS diff --git a/src/inet/InetLayer.cpp b/src/inet/InetLayer.cpp index 631d89faa24929..d16ba43ff4dad2 100644 --- a/src/inet/InetLayer.cpp +++ b/src/inet/InetLayer.cpp @@ -1338,8 +1338,6 @@ DLL_EXPORT void DidInit(Inet::InetLayer * aLayer, void * aContext, INET_ERROR an (void) aLayer; (void) aContext; (void) anError; - - return; } /** @@ -1386,8 +1384,6 @@ DLL_EXPORT void DidShutdown(Inet::InetLayer * aLayer, void * aContext, INET_ERRO (void) aLayer; (void) aContext; (void) anError; - - return; } } // namespace InetLayer diff --git a/src/inet/tests/TestInetLayer.cpp b/src/inet/tests/TestInetLayer.cpp index 9c48f7481c05b9..81f6c653e52a7d 100644 --- a/src/inet/tests/TestInetLayer.cpp +++ b/src/inet/tests/TestInetLayer.cpp @@ -589,10 +589,7 @@ static void HandleTCPConnectionClosed(TCPEndPoint * aEndPoint, INET_ERROR aError } } -static void HandleTCPDataSent(TCPEndPoint * aEndPoint, uint16_t len) -{ - return; -} +static void HandleTCPDataSent(TCPEndPoint * aEndPoint, uint16_t len) {} static void HandleTCPDataReceived(TCPEndPoint * aEndPoint, PacketBuffer * aBuffer) { @@ -928,8 +925,6 @@ void DriveSend() { SetStatusFailed(sTestState.mStatus); } - - return; } static void StartTest() diff --git a/src/inet/tests/TestInetLayerMulticast.cpp b/src/inet/tests/TestInetLayerMulticast.cpp index ed2fb873b6907d..24eff1af75fe81 100644 --- a/src/inet/tests/TestInetLayerMulticast.cpp +++ b/src/inet/tests/TestInetLayerMulticast.cpp @@ -866,8 +866,6 @@ void DriveSend() { SetStatusFailed(sTestState.mStatus); } - - return; } static void StartTest() diff --git a/src/lib/message/CHIPExchangeMgr.cpp b/src/lib/message/CHIPExchangeMgr.cpp index 5e6d4addab1440..8070c4524d230d 100644 --- a/src/lib/message/CHIPExchangeMgr.cpp +++ b/src/lib/message/CHIPExchangeMgr.cpp @@ -888,8 +888,6 @@ void ChipExchangeManager::DispatchMessage(ChipMessageInfo * msgInfo, PacketBuffe { PacketBuffer::Free(msgBuf); } - - return; } CHIP_ERROR ChipExchangeManager::RegisterUMH(uint32_t profileId, int16_t msgType, ChipConnection * con, bool allowDups, @@ -1216,10 +1214,7 @@ void ChipExchangeManager::TicklessDebugDumpRetransTable(const char * log) } } #else -void ChipExchangeManager::TicklessDebugDumpRetransTable(const char * log) -{ - return; -} +void ChipExchangeManager::TicklessDebugDumpRetransTable(const char * log) {} #endif // RMP_TICKLESS_DEBUG /** diff --git a/src/lib/message/CHIPFabricState.cpp b/src/lib/message/CHIPFabricState.cpp index 00255338abdd59..51a2fbdbf6ee2b 100644 --- a/src/lib/message/CHIPFabricState.cpp +++ b/src/lib/message/CHIPFabricState.cpp @@ -1071,8 +1071,6 @@ void ChipFabricState::OnMsgCounterSyncRespRcvd(uint64_t peerNodeId, uint32_t pee MessageLayer->ExchangeMgr->ClearMsgCounterSyncReq(peerNodeId); } } - - return; } // Start message counter synchronization timer. @@ -1111,8 +1109,6 @@ void ChipFabricState::OnMsgCounterSyncReqSent(uint32_t messageId) // Enable fast-poll mode for SEDs if not already enabled. MessageLayer->SignalMessageLayerActivityChanged(); } - - return; } // Handle MsgCounterSyncRespTimeout. @@ -1158,8 +1154,6 @@ void ChipFabricState::OnMsgCounterSyncRespTimeout(System::Layer * aSystemLayer, // Disable fast-poll mode for SEDs if needed. fabricState->MessageLayer->SignalMessageLayerActivityChanged(); } - - return; } /** diff --git a/src/lib/message/CHIPMessageLayer.cpp b/src/lib/message/CHIPMessageLayer.cpp index c09d6b356facd9..891b48439cfcff 100644 --- a/src/lib/message/CHIPMessageLayer.cpp +++ b/src/lib/message/CHIPMessageLayer.cpp @@ -1563,8 +1563,6 @@ void ChipMessageLayer::HandleUDPMessage(UDPEndPoint * endPoint, PacketBuffer * m if (msgLayer->OnReceiveError != nullptr) msgLayer->OnReceiveError(msgLayer, err, pktInfo); } - - return; } void ChipMessageLayer::HandleUDPReceiveError(UDPEndPoint * endPoint, INET_ERROR err, const IPPacketInfo * pktInfo) @@ -2380,7 +2378,6 @@ void ChipMessageLayer::GetPeerDescription(char * buf, size_t bufSize, uint64_t n { buf[bufSize - 1] = 0; } - return; } /** diff --git a/src/lib/message/CHIPSecurityMgr.cpp b/src/lib/message/CHIPSecurityMgr.cpp index 4b7018e60325a9..91e5a7fe958dc8 100644 --- a/src/lib/message/CHIPSecurityMgr.cpp +++ b/src/lib/message/CHIPSecurityMgr.cpp @@ -411,8 +411,6 @@ void ChipSecurityManager::HandleKeyErrorMsg(ExchangeContext * ec, PacketBuffer * if (ec != nullptr) ec->Close(); - - return; } CHIP_ERROR ChipSecurityManager::NewSessionExchange(uint64_t peerNodeId, const IPAddress & peerAddr, uint16_t peerPort) @@ -583,8 +581,6 @@ void ChipSecurityManager::HandleMsgCounterSyncRespMsg(ChipMessageInfo * msgInfo, exit: PacketBuffer::Free(msgBuf); - - return; } #endif // CHIP_CONFIG_USE_APP_GROUP_KEYS_FOR_MSG_ENC diff --git a/src/lib/message/ExchangeContext.cpp b/src/lib/message/ExchangeContext.cpp index b4b13d019e5eda..6c62a6ad2f394c 100644 --- a/src/lib/message/ExchangeContext.cpp +++ b/src/lib/message/ExchangeContext.cpp @@ -1036,8 +1036,6 @@ bool ExchangeContext::RMPCheckAndRemRetransTable(uint32_t ackMsgId, void ** rCtx res = true; break; } - - continue; } return res; diff --git a/src/lib/support/CHIPArgParser.cpp b/src/lib/support/CHIPArgParser.cpp index f49388b8416a5a..8fd3e04d5ff879 100644 --- a/src/lib/support/CHIPArgParser.cpp +++ b/src/lib/support/CHIPArgParser.cpp @@ -1078,9 +1078,7 @@ bool ParseHexString(const char * hexStr, uint32_t strLen, uint8_t * outBuf, uint HelpOptions::HelpOptions(const char * appName, const char * appUsage, const char * appVersion) : HelpOptions(appName, appUsage, appVersion, nullptr) -{ - return; -} +{} HelpOptions::HelpOptions(const char * appName, const char * appUsage, const char * appVersion, const char * appDesc) { diff --git a/src/lib/support/PersistedCounter.cpp b/src/lib/support/PersistedCounter.cpp index 243a02ef02509e..1f8ba575d99b1d 100644 --- a/src/lib/support/PersistedCounter.cpp +++ b/src/lib/support/PersistedCounter.cpp @@ -29,10 +29,7 @@ namespace chip { PersistedCounter::PersistedCounter() : mId(chip::Platform::PersistedStorage::kEmptyKey), mEpoch(0), mNextEpoch(0) {} -PersistedCounter::~PersistedCounter() -{ - return; -} +PersistedCounter::~PersistedCounter() {} CHIP_ERROR PersistedCounter::Init(const chip::Platform::PersistedStorage::Key aId, uint32_t aEpoch) diff --git a/src/platform/Linux/CHIPBluezHelper.cpp b/src/platform/Linux/CHIPBluezHelper.cpp index b7a2136a6cf953..30d0f5059b8287 100644 --- a/src/platform/Linux/CHIPBluezHelper.cpp +++ b/src/platform/Linux/CHIPBluezHelper.cpp @@ -793,7 +793,6 @@ static void BluezPeripheralRegisterAppDone(GObject * aObject, GAsyncResult * aRe BLEManagerImpl::NotifyBLEPeripheralRegisterAppComplete(false, nullptr); g_error_free(error); } - return; } gboolean BluezPeripheralRegisterApp(void * apClosure) From d73a1ba4f1efc2883c1ed1d6f2b119cedbdc40b4 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Tue, 13 Oct 2020 18:28:47 +0200 Subject: [PATCH 12/40] Add -Wconversion to chip-tool (#3208) --- examples/chip-tool/BUILD.gn | 2 + .../chip-tool/commands/clusters/Commands.h | 280 +++++++++--------- examples/chip-tool/commands/common/Command.h | 4 +- .../chip-tool/commands/common/EchoCommand.cpp | 13 +- .../commands/common/ModelCommand.cpp | 16 +- .../chip-tool/commands/common/ModelCommand.h | 4 +- .../commands/common/NetworkCommand.h | 4 +- src/lib/support/SafeInt.h | 2 +- 8 files changed, 166 insertions(+), 159 deletions(-) diff --git a/examples/chip-tool/BUILD.gn b/examples/chip-tool/BUILD.gn index 6e0df1219ff4af..410126356ca74d 100644 --- a/examples/chip-tool/BUILD.gn +++ b/examples/chip-tool/BUILD.gn @@ -34,6 +34,8 @@ executable("chip-tool") { defines = [ "BUILD_RELEASE=1" ] } + cflags = [ "-Wconversion" ] + public_deps = [ "${chip_root}/src/lib" ] output_dir = root_out_dir diff --git a/examples/chip-tool/commands/clusters/Commands.h b/examples/chip-tool/commands/clusters/Commands.h index e887cc21ffee5f..8d6cbdea628ff3 100644 --- a/examples/chip-tool/commands/clusters/Commands.h +++ b/examples/chip-tool/commands/clusters/Commands.h @@ -73,7 +73,7 @@ class BarrierControlGoToPercent : public ModelCommand AddArgument("percentOpen", 0, UINT8_MAX, &mPercentOpen); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBarrierControlClusterGoToPercentCommand(buffer->Start(), bufferSize, endPointId, mPercentOpen); } @@ -90,7 +90,7 @@ class ReadBarrierControlMovingState : public ModelCommand public: ReadBarrierControlMovingState() : ModelCommand("read", BARRIER_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "moving-state"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBarrierControlClusterReadMovingStateAttribute(buffer->Start(), bufferSize, endPointId); } @@ -107,7 +107,7 @@ class ReadBarrierControlSafetyStatus : public ModelCommand AddArgument("attr-name", "safety-status"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBarrierControlClusterReadSafetyStatusAttribute(buffer->Start(), bufferSize, endPointId); } @@ -124,7 +124,7 @@ class ReadBarrierControlCapabilities : public ModelCommand AddArgument("attr-name", "capabilities"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBarrierControlClusterReadCapabilitiesAttribute(buffer->Start(), bufferSize, endPointId); } @@ -141,7 +141,7 @@ class ReadBarrierControlBarrierPosition : public ModelCommand AddArgument("attr-name", "barrier-position"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBarrierControlClusterReadBarrierPositionAttribute(buffer->Start(), bufferSize, endPointId); } @@ -178,7 +178,7 @@ class BasicResetToFactoryDefaults : public ModelCommand public: BasicResetToFactoryDefaults() : ModelCommand("reset-to-factory-defaults", BASIC_CLUSTER_ID) {} - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterResetToFactoryDefaultsCommand(buffer->Start(), bufferSize, endPointId); } @@ -192,7 +192,7 @@ class ReadBasicZCLVersion : public ModelCommand public: ReadBasicZCLVersion() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "zclversion"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadZCLVersionAttribute(buffer->Start(), bufferSize, endPointId); } @@ -206,7 +206,7 @@ class ReadBasicApplicationVersion : public ModelCommand public: ReadBasicApplicationVersion() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "application-version"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadApplicationVersionAttribute(buffer->Start(), bufferSize, endPointId); } @@ -220,7 +220,7 @@ class ReadBasicStackVersion : public ModelCommand public: ReadBasicStackVersion() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "stack-version"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadStackVersionAttribute(buffer->Start(), bufferSize, endPointId); } @@ -234,7 +234,7 @@ class ReadBasicHWVersion : public ModelCommand public: ReadBasicHWVersion() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "hwversion"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadHWVersionAttribute(buffer->Start(), bufferSize, endPointId); } @@ -248,7 +248,7 @@ class ReadBasicManufacturerName : public ModelCommand public: ReadBasicManufacturerName() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "manufacturer-name"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadManufacturerNameAttribute(buffer->Start(), bufferSize, endPointId); } @@ -262,7 +262,7 @@ class ReadBasicModelIdentifier : public ModelCommand public: ReadBasicModelIdentifier() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "model-identifier"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadModelIdentifierAttribute(buffer->Start(), bufferSize, endPointId); } @@ -276,7 +276,7 @@ class ReadBasicDateCode : public ModelCommand public: ReadBasicDateCode() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "date-code"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadDateCodeAttribute(buffer->Start(), bufferSize, endPointId); } @@ -290,7 +290,7 @@ class ReadBasicPowerSource : public ModelCommand public: ReadBasicPowerSource() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "power-source"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadPowerSourceAttribute(buffer->Start(), bufferSize, endPointId); } @@ -304,7 +304,7 @@ class ReadBasicGenericDeviceClass : public ModelCommand public: ReadBasicGenericDeviceClass() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "generic-device-class"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadGenericDeviceClassAttribute(buffer->Start(), bufferSize, endPointId); } @@ -318,7 +318,7 @@ class ReadBasicGenericDeviceType : public ModelCommand public: ReadBasicGenericDeviceType() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "generic-device-type"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadGenericDeviceTypeAttribute(buffer->Start(), bufferSize, endPointId); } @@ -332,7 +332,7 @@ class ReadBasicProductCode : public ModelCommand public: ReadBasicProductCode() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "product-code"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadProductCodeAttribute(buffer->Start(), bufferSize, endPointId); } @@ -346,7 +346,7 @@ class ReadBasicProductURL : public ModelCommand public: ReadBasicProductURL() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "product-url"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadProductURLAttribute(buffer->Start(), bufferSize, endPointId); } @@ -360,7 +360,7 @@ class ReadBasicSWBuildID : public ModelCommand public: ReadBasicSWBuildID() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "swbuild-id"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadSWBuildIDAttribute(buffer->Start(), bufferSize, endPointId); } @@ -441,7 +441,7 @@ class ColorControlMoveColor : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterMoveColorCommand(buffer->Start(), bufferSize, endPointId, mRateX, mRateY, mOptionsMask, mOptionsOverride); @@ -470,7 +470,7 @@ class ColorControlMoveColorTemperature : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterMoveColorTemperatureCommand(buffer->Start(), bufferSize, endPointId, mMoveMode, mRate, mColorTemperatureMinimumMireds, mColorTemperatureMaximumMireds, @@ -500,7 +500,7 @@ class ColorControlMoveHue : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterMoveHueCommand(buffer->Start(), bufferSize, endPointId, mMoveMode, mRate, mOptionsMask, mOptionsOverride); @@ -527,7 +527,7 @@ class ColorControlMoveSaturation : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterMoveSaturationCommand(buffer->Start(), bufferSize, endPointId, mMoveMode, mRate, mOptionsMask, mOptionsOverride); @@ -555,7 +555,7 @@ class ColorControlMoveToColor : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterMoveToColorCommand(buffer->Start(), bufferSize, endPointId, mColorX, mColorY, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -583,7 +583,7 @@ class ColorControlMoveToColorTemperature : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterMoveToColorTemperatureCommand( buffer->Start(), bufferSize, endPointId, mColorTemperatureMireds, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -611,7 +611,7 @@ class ColorControlMoveToHue : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterMoveToHueCommand(buffer->Start(), bufferSize, endPointId, mHue, mDirection, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -640,7 +640,7 @@ class ColorControlMoveToHueAndSaturation : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterMoveToHueAndSaturationCommand(buffer->Start(), bufferSize, endPointId, mHue, mSaturation, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -668,7 +668,7 @@ class ColorControlMoveToSaturation : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterMoveToSaturationCommand(buffer->Start(), bufferSize, endPointId, mSaturation, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -696,7 +696,7 @@ class ColorControlStepColor : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterStepColorCommand(buffer->Start(), bufferSize, endPointId, mStepX, mStepY, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -727,7 +727,7 @@ class ColorControlStepColorTemperature : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterStepColorTemperatureCommand(buffer->Start(), bufferSize, endPointId, mStepMode, mStepSize, mTransitionTime, mColorTemperatureMinimumMireds, @@ -759,7 +759,7 @@ class ColorControlStepHue : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterStepHueCommand(buffer->Start(), bufferSize, endPointId, mStepMode, mStepSize, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -788,7 +788,7 @@ class ColorControlStepSaturation : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterStepSaturationCommand(buffer->Start(), bufferSize, endPointId, mStepMode, mStepSize, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -814,7 +814,7 @@ class ColorControlStopMoveStep : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterStopMoveStepCommand(buffer->Start(), bufferSize, endPointId, mOptionsMask, mOptionsOverride); @@ -833,7 +833,7 @@ class ReadColorControlCurrentHue : public ModelCommand public: ReadColorControlCurrentHue() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "current-hue"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadCurrentHueAttribute(buffer->Start(), bufferSize, endPointId); } @@ -850,7 +850,7 @@ class ReadColorControlCurrentSaturation : public ModelCommand AddArgument("attr-name", "current-saturation"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadCurrentSaturationAttribute(buffer->Start(), bufferSize, endPointId); } @@ -864,7 +864,7 @@ class ReadColorControlCurrentX : public ModelCommand public: ReadColorControlCurrentX() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "current-x"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadCurrentXAttribute(buffer->Start(), bufferSize, endPointId); } @@ -878,7 +878,7 @@ class ReadColorControlCurrentY : public ModelCommand public: ReadColorControlCurrentY() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "current-y"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadCurrentYAttribute(buffer->Start(), bufferSize, endPointId); } @@ -895,7 +895,7 @@ class ReadColorControlColorTemperatureMireds : public ModelCommand AddArgument("attr-name", "color-temperature-mireds"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorTemperatureMiredsAttribute(buffer->Start(), bufferSize, endPointId); } @@ -909,7 +909,7 @@ class ReadColorControlColorMode : public ModelCommand public: ReadColorControlColorMode() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "color-mode"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorModeAttribute(buffer->Start(), bufferSize, endPointId); } @@ -923,7 +923,7 @@ class ReadColorControlOptions : public ModelCommand public: ReadColorControlOptions() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "options"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadOptionsAttribute(buffer->Start(), bufferSize, endPointId); } @@ -940,7 +940,7 @@ class ReadColorControlNumberOfPrimaries : public ModelCommand AddArgument("attr-name", "number-of-primaries"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadNumberOfPrimariesAttribute(buffer->Start(), bufferSize, endPointId); } @@ -954,7 +954,7 @@ class ReadColorControlPrimary1X : public ModelCommand public: ReadColorControlPrimary1X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary1-x"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary1XAttribute(buffer->Start(), bufferSize, endPointId); } @@ -968,7 +968,7 @@ class ReadColorControlPrimary1Y : public ModelCommand public: ReadColorControlPrimary1Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary1-y"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary1YAttribute(buffer->Start(), bufferSize, endPointId); } @@ -985,7 +985,7 @@ class ReadColorControlPrimary1Intensity : public ModelCommand AddArgument("attr-name", "primary1-intensity"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary1IntensityAttribute(buffer->Start(), bufferSize, endPointId); } @@ -999,7 +999,7 @@ class ReadColorControlPrimary2X : public ModelCommand public: ReadColorControlPrimary2X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary2-x"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary2XAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1013,7 +1013,7 @@ class ReadColorControlPrimary2Y : public ModelCommand public: ReadColorControlPrimary2Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary2-y"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary2YAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1030,7 +1030,7 @@ class ReadColorControlPrimary2Intensity : public ModelCommand AddArgument("attr-name", "primary2-intensity"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary2IntensityAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1044,7 +1044,7 @@ class ReadColorControlPrimary3X : public ModelCommand public: ReadColorControlPrimary3X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary3-x"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary3XAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1058,7 +1058,7 @@ class ReadColorControlPrimary3Y : public ModelCommand public: ReadColorControlPrimary3Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary3-y"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary3YAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1075,7 +1075,7 @@ class ReadColorControlPrimary3Intensity : public ModelCommand AddArgument("attr-name", "primary3-intensity"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary3IntensityAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1089,7 +1089,7 @@ class ReadColorControlPrimary4X : public ModelCommand public: ReadColorControlPrimary4X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary4-x"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary4XAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1103,7 +1103,7 @@ class ReadColorControlPrimary4Y : public ModelCommand public: ReadColorControlPrimary4Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary4-y"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary4YAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1120,7 +1120,7 @@ class ReadColorControlPrimary4Intensity : public ModelCommand AddArgument("attr-name", "primary4-intensity"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary4IntensityAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1134,7 +1134,7 @@ class ReadColorControlPrimary5X : public ModelCommand public: ReadColorControlPrimary5X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary5-x"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary5XAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1148,7 +1148,7 @@ class ReadColorControlPrimary5Y : public ModelCommand public: ReadColorControlPrimary5Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary5-y"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary5YAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1165,7 +1165,7 @@ class ReadColorControlPrimary5Intensity : public ModelCommand AddArgument("attr-name", "primary5-intensity"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary5IntensityAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1179,7 +1179,7 @@ class ReadColorControlPrimary6X : public ModelCommand public: ReadColorControlPrimary6X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary6-x"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary6XAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1193,7 +1193,7 @@ class ReadColorControlPrimary6Y : public ModelCommand public: ReadColorControlPrimary6Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary6-y"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary6YAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1210,7 +1210,7 @@ class ReadColorControlPrimary6Intensity : public ModelCommand AddArgument("attr-name", "primary6-intensity"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary6IntensityAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1227,7 +1227,7 @@ class ReadColorControlEnhancedCurrentHue : public ModelCommand AddArgument("attr-name", "enhanced-current-hue"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadEnhancedCurrentHueAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1244,7 +1244,7 @@ class ReadColorControlEnhancedColorMode : public ModelCommand AddArgument("attr-name", "enhanced-color-mode"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadEnhancedColorModeAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1261,7 +1261,7 @@ class ReadColorControlColorLoopActive : public ModelCommand AddArgument("attr-name", "color-loop-active"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorLoopActiveAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1278,7 +1278,7 @@ class ReadColorControlColorLoopDirection : public ModelCommand AddArgument("attr-name", "color-loop-direction"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorLoopDirectionAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1295,7 +1295,7 @@ class ReadColorControlColorLoopTime : public ModelCommand AddArgument("attr-name", "color-loop-time"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorLoopTimeAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1312,7 +1312,7 @@ class ReadColorControlColorLoopStartEnhancedHue : public ModelCommand AddArgument("attr-name", "color-loop-start-enhanced-hue"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorLoopStartEnhancedHueAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1329,7 +1329,7 @@ class ReadColorControlColorLoopStoredEnhancedHue : public ModelCommand AddArgument("attr-name", "color-loop-stored-enhanced-hue"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorLoopStoredEnhancedHueAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1346,7 +1346,7 @@ class ReadColorControlColorCapabilities : public ModelCommand AddArgument("attr-name", "color-capabilities"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorCapabilitiesAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1363,7 +1363,7 @@ class ReadColorControlColorTempPhysicalMinMireds : public ModelCommand AddArgument("attr-name", "color-temp-physical-min-mireds"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorTempPhysicalMinMiredsAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1380,7 +1380,7 @@ class ReadColorControlColorTempPhysicalMaxMireds : public ModelCommand AddArgument("attr-name", "color-temp-physical-max-mireds"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorTempPhysicalMaxMiredsAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1397,7 +1397,7 @@ class ReadColorControlCoupleColorTempToLevelMinMireds : public ModelCommand AddArgument("attr-name", "couple-color-temp-to-level-min-mireds"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadCoupleColorTempToLevelMinMiredsAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1414,7 +1414,7 @@ class ReadColorControlStartUpColorTemperatureMireds : public ModelCommand AddArgument("attr-name", "start-up-color-temperature-mireds"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadStartUpColorTemperatureMiredsAttribute(buffer->Start(), bufferSize, endPointId); } @@ -1463,7 +1463,7 @@ class DoorLockClearAllPINCodes : public ModelCommand public: DoorLockClearAllPINCodes() : ModelCommand("clear-all-pincodes", DOOR_LOCK_CLUSTER_ID) {} - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterClearAllPINCodesCommand(buffer->Start(), bufferSize, endPointId); } @@ -1488,7 +1488,7 @@ class DoorLockClearAllRFIDCodes : public ModelCommand public: DoorLockClearAllRFIDCodes() : ModelCommand("clear-all-rfidcodes", DOOR_LOCK_CLUSTER_ID) {} - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterClearAllRFIDCodesCommand(buffer->Start(), bufferSize, endPointId); } @@ -1516,7 +1516,7 @@ class DoorLockClearHolidaySchedule : public ModelCommand AddArgument("holidayScheduleID", 0, UINT8_MAX, &mHolidayScheduleID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterClearHolidayScheduleCommand(buffer->Start(), bufferSize, endPointId, mHolidayScheduleID); } @@ -1544,7 +1544,7 @@ class DoorLockClearPINCode : public ModelCommand public: DoorLockClearPINCode() : ModelCommand("clear-pincode", DOOR_LOCK_CLUSTER_ID) { AddArgument("userID", 0, UINT16_MAX, &mUserID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterClearPINCodeCommand(buffer->Start(), bufferSize, endPointId, mUserID); } @@ -1575,7 +1575,7 @@ class DoorLockClearRFIDCode : public ModelCommand AddArgument("userID", 0, UINT16_MAX, &mUserID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterClearRFIDCodeCommand(buffer->Start(), bufferSize, endPointId, mUserID); } @@ -1607,7 +1607,7 @@ class DoorLockClearWeekdaySchedule : public ModelCommand AddArgument("userID", 0, UINT16_MAX, &mUserID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterClearWeekdayScheduleCommand(buffer->Start(), bufferSize, endPointId, mScheduleID, mUserID); } @@ -1640,7 +1640,7 @@ class DoorLockClearYearDaySchedule : public ModelCommand AddArgument("userID", 0, UINT16_MAX, &mUserID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterClearYearDayScheduleCommand(buffer->Start(), bufferSize, endPointId, mScheduleID, mUserID); } @@ -1672,7 +1672,7 @@ class DoorLockGetHolidaySchedule : public ModelCommand AddArgument("holidayScheduleID", 0, UINT8_MAX, &mHolidayScheduleID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterGetHolidayScheduleCommand(buffer->Start(), bufferSize, endPointId, mHolidayScheduleID); } @@ -1711,7 +1711,7 @@ class DoorLockGetLogRecord : public ModelCommand AddArgument("logIndex", 0, UINT16_MAX, &mLogIndex); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterGetLogRecordCommand(buffer->Start(), bufferSize, endPointId, mLogIndex); } @@ -1751,7 +1751,7 @@ class DoorLockGetPINCode : public ModelCommand public: DoorLockGetPINCode() : ModelCommand("get-pincode", DOOR_LOCK_CLUSTER_ID) { AddArgument("userID", 0, UINT16_MAX, &mUserID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterGetPINCodeCommand(buffer->Start(), bufferSize, endPointId, mUserID); } @@ -1785,7 +1785,7 @@ class DoorLockGetRFIDCode : public ModelCommand public: DoorLockGetRFIDCode() : ModelCommand("get-rfidcode", DOOR_LOCK_CLUSTER_ID) { AddArgument("userID", 0, UINT16_MAX, &mUserID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterGetRFIDCodeCommand(buffer->Start(), bufferSize, endPointId, mUserID); } @@ -1819,7 +1819,7 @@ class DoorLockGetUserType : public ModelCommand public: DoorLockGetUserType() : ModelCommand("get-user-type", DOOR_LOCK_CLUSTER_ID) { AddArgument("userID", 0, UINT16_MAX, &mUserID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterGetUserTypeCommand(buffer->Start(), bufferSize, endPointId, mUserID); } @@ -1853,7 +1853,7 @@ class DoorLockGetWeekdaySchedule : public ModelCommand AddArgument("userID", 0, UINT16_MAX, &mUserID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterGetWeekdayScheduleCommand(buffer->Start(), bufferSize, endPointId, mScheduleID, mUserID); } @@ -1900,7 +1900,7 @@ class DoorLockGetYearDaySchedule : public ModelCommand AddArgument("userID", 0, UINT16_MAX, &mUserID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterGetYearDayScheduleCommand(buffer->Start(), bufferSize, endPointId, mScheduleID, mUserID); } @@ -1937,7 +1937,7 @@ class DoorLockLockDoor : public ModelCommand public: DoorLockLockDoor() : ModelCommand("lock-door", DOOR_LOCK_CLUSTER_ID) { AddArgument("pINOrRFIDCode", &mPINOrRFIDCode); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterLockDoorCommand(buffer->Start(), bufferSize, endPointId, mPINOrRFIDCode); } @@ -1971,7 +1971,7 @@ class DoorLockSetHolidaySchedule : public ModelCommand AddArgument("operatingModeDuringHoliday", 0, UINT8_MAX, &mOperatingModeDuringHoliday); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterSetHolidayScheduleCommand(buffer->Start(), bufferSize, endPointId, mHolidayScheduleID, mLocalStartTime, mLocalEndTime, mOperatingModeDuringHoliday); @@ -2009,7 +2009,7 @@ class DoorLockSetPINCode : public ModelCommand AddArgument("pIN", &mPIN); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterSetPINCodeCommand(buffer->Start(), bufferSize, endPointId, mUserID, mUserStatus, mUserType, mPIN); @@ -2047,7 +2047,7 @@ class DoorLockSetRFIDCode : public ModelCommand AddArgument("rFIDCode", &mRFIDCode); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterSetRFIDCodeCommand(buffer->Start(), bufferSize, endPointId, mUserID, mUserStatus, mUserType, mRFIDCode); @@ -2083,7 +2083,7 @@ class DoorLockSetUserType : public ModelCommand AddArgument("userType", 0, UINT8_MAX, &mUserType); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterSetUserTypeCommand(buffer->Start(), bufferSize, endPointId, mUserID, mUserType); } @@ -2121,7 +2121,7 @@ class DoorLockSetWeekdaySchedule : public ModelCommand AddArgument("endMinute", 0, UINT8_MAX, &mEndMinute); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterSetWeekdayScheduleCommand(buffer->Start(), bufferSize, endPointId, mScheduleID, mUserID, mDaysMask, mStartHour, mStartMinute, mEndHour, mEndMinute); @@ -2162,7 +2162,7 @@ class DoorLockSetYearDaySchedule : public ModelCommand AddArgument("localEndTime", 0, UINT32_MAX, &mLocalEndTime); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterSetYearDayScheduleCommand(buffer->Start(), bufferSize, endPointId, mScheduleID, mUserID, mLocalStartTime, mLocalEndTime); @@ -2194,7 +2194,7 @@ class DoorLockUnlockDoor : public ModelCommand public: DoorLockUnlockDoor() : ModelCommand("unlock-door", DOOR_LOCK_CLUSTER_ID) { AddArgument("pINOrRFIDCode", &mPINOrRFIDCode); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterUnlockDoorCommand(buffer->Start(), bufferSize, endPointId, mPINOrRFIDCode); } @@ -2226,7 +2226,7 @@ class DoorLockUnlockWithTimeout : public ModelCommand AddArgument("pINOrRFIDCode", &mPINOrRFIDCode); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterUnlockWithTimeoutCommand(buffer->Start(), bufferSize, endPointId, mTimeoutInSeconds, mPINOrRFIDCode); @@ -2256,7 +2256,7 @@ class ReadDoorLockLockState : public ModelCommand public: ReadDoorLockLockState() : ModelCommand("read", DOOR_LOCK_CLUSTER_ID) { AddArgument("attr-name", "lock-state"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterReadLockStateAttribute(buffer->Start(), bufferSize, endPointId); } @@ -2270,7 +2270,7 @@ class ReadDoorLockLockType : public ModelCommand public: ReadDoorLockLockType() : ModelCommand("read", DOOR_LOCK_CLUSTER_ID) { AddArgument("attr-name", "lock-type"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterReadLockTypeAttribute(buffer->Start(), bufferSize, endPointId); } @@ -2284,7 +2284,7 @@ class ReadDoorLockActuatorEnabled : public ModelCommand public: ReadDoorLockActuatorEnabled() : ModelCommand("read", DOOR_LOCK_CLUSTER_ID) { AddArgument("attr-name", "actuator-enabled"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterReadActuatorEnabledAttribute(buffer->Start(), bufferSize, endPointId); } @@ -2318,7 +2318,7 @@ class GroupsAddGroup : public ModelCommand AddArgument("groupName", &mGroupName); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterAddGroupCommand(buffer->Start(), bufferSize, endPointId, mGroupId, mGroupName); } @@ -2353,7 +2353,7 @@ class GroupsAddGroupIfIdentifying : public ModelCommand AddArgument("groupName", &mGroupName); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterAddGroupIfIdentifyingCommand(buffer->Start(), bufferSize, endPointId, mGroupId, mGroupName); } @@ -2374,7 +2374,7 @@ class GroupsGetGroupMembership : public ModelCommand AddArgument("groupList", 0, UINT16_MAX, &mGroupList); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterGetGroupMembershipCommand(buffer->Start(), bufferSize, endPointId, mGroupList); } @@ -2404,7 +2404,7 @@ class GroupsRemoveAllGroups : public ModelCommand public: GroupsRemoveAllGroups() : ModelCommand("remove-all-groups", GROUPS_CLUSTER_ID) {} - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterRemoveAllGroupsCommand(buffer->Start(), bufferSize, endPointId); } @@ -2418,7 +2418,7 @@ class GroupsRemoveGroup : public ModelCommand public: GroupsRemoveGroup() : ModelCommand("remove-group", GROUPS_CLUSTER_ID) { AddArgument("groupId", 0, UINT16_MAX, &mGroupId); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterRemoveGroupCommand(buffer->Start(), bufferSize, endPointId, mGroupId); } @@ -2448,7 +2448,7 @@ class GroupsViewGroup : public ModelCommand public: GroupsViewGroup() : ModelCommand("view-group", GROUPS_CLUSTER_ID) { AddArgument("groupId", 0, UINT16_MAX, &mGroupId); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterViewGroupCommand(buffer->Start(), bufferSize, endPointId, mGroupId); } @@ -2480,7 +2480,7 @@ class ReadGroupsNameSupport : public ModelCommand public: ReadGroupsNameSupport() : ModelCommand("read", GROUPS_CLUSTER_ID) { AddArgument("attr-name", "name-support"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterReadNameSupportAttribute(buffer->Start(), bufferSize, endPointId); } @@ -2509,7 +2509,7 @@ class IdentifyIdentify : public ModelCommand AddArgument("identifyTime", 0, UINT16_MAX, &mIdentifyTime); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeIdentifyClusterIdentifyCommand(buffer->Start(), bufferSize, endPointId, mIdentifyTime); } @@ -2526,7 +2526,7 @@ class IdentifyIdentifyQuery : public ModelCommand public: IdentifyIdentifyQuery() : ModelCommand("identify-query", IDENTIFY_CLUSTER_ID) {} - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeIdentifyClusterIdentifyQueryCommand(buffer->Start(), bufferSize, endPointId); } @@ -2551,7 +2551,7 @@ class ReadIdentifyIdentifyTime : public ModelCommand public: ReadIdentifyIdentifyTime() : ModelCommand("read", IDENTIFY_CLUSTER_ID) { AddArgument("attr-name", "identify-time"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeIdentifyClusterReadIdentifyTimeAttribute(buffer->Start(), bufferSize, endPointId); } @@ -2591,7 +2591,7 @@ class LevelMove : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterMoveCommand(buffer->Start(), bufferSize, endPointId, mMoveMode, mRate, mOptionsMask, mOptionsOverride); @@ -2618,7 +2618,7 @@ class LevelMoveToLevel : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterMoveToLevelCommand(buffer->Start(), bufferSize, endPointId, mLevel, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -2645,7 +2645,7 @@ class LevelMoveToLevelWithOnOff : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterMoveToLevelWithOnOffCommand(buffer->Start(), bufferSize, endPointId, mLevel, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -2672,7 +2672,7 @@ class LevelMoveWithOnOff : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterMoveWithOnOffCommand(buffer->Start(), bufferSize, endPointId, mMoveMode, mRate, mOptionsMask, mOptionsOverride); @@ -2700,7 +2700,7 @@ class LevelStep : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterStepCommand(buffer->Start(), bufferSize, endPointId, mStepMode, mStepSize, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -2729,7 +2729,7 @@ class LevelStepWithOnOff : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterStepWithOnOffCommand(buffer->Start(), bufferSize, endPointId, mStepMode, mStepSize, mTransitionTime, mOptionsMask, mOptionsOverride); @@ -2755,7 +2755,7 @@ class LevelStop : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterStopCommand(buffer->Start(), bufferSize, endPointId, mOptionsMask, mOptionsOverride); } @@ -2777,7 +2777,7 @@ class LevelStopWithOnOff : public ModelCommand AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterStopWithOnOffCommand(buffer->Start(), bufferSize, endPointId, mOptionsMask, mOptionsOverride); } @@ -2795,7 +2795,7 @@ class ReadLevelCurrentLevel : public ModelCommand public: ReadLevelCurrentLevel() : ModelCommand("read", LEVEL_CLUSTER_ID) { AddArgument("attr-name", "current-level"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterReadCurrentLevelAttribute(buffer->Start(), bufferSize, endPointId); } @@ -2809,7 +2809,7 @@ class ReadLevelRemainingTime : public ModelCommand public: ReadLevelRemainingTime() : ModelCommand("read", LEVEL_CLUSTER_ID) { AddArgument("attr-name", "remaining-time"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterReadRemainingTimeAttribute(buffer->Start(), bufferSize, endPointId); } @@ -2823,7 +2823,7 @@ class ReadLevelOptions : public ModelCommand public: ReadLevelOptions() : ModelCommand("read", LEVEL_CLUSTER_ID) { AddArgument("attr-name", "options"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterReadOptionsAttribute(buffer->Start(), bufferSize, endPointId); } @@ -2850,7 +2850,7 @@ class OnOffOff : public ModelCommand public: OnOffOff() : ModelCommand("off", ON_OFF_CLUSTER_ID) {} - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeOnOffClusterOffCommand(buffer->Start(), bufferSize, endPointId); } @@ -2864,7 +2864,7 @@ class OnOffOn : public ModelCommand public: OnOffOn() : ModelCommand("on", ON_OFF_CLUSTER_ID) {} - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeOnOffClusterOnCommand(buffer->Start(), bufferSize, endPointId); } @@ -2878,7 +2878,7 @@ class OnOffToggle : public ModelCommand public: OnOffToggle() : ModelCommand("toggle", ON_OFF_CLUSTER_ID) {} - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeOnOffClusterToggleCommand(buffer->Start(), bufferSize, endPointId); } @@ -2892,7 +2892,7 @@ class ReadOnOffOnOff : public ModelCommand public: ReadOnOffOnOff() : ModelCommand("read", ON_OFF_CLUSTER_ID) { AddArgument("attr-name", "on-off"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeOnOffClusterReadOnOffAttribute(buffer->Start(), bufferSize, endPointId); } @@ -2938,7 +2938,7 @@ class ScenesAddScene : public ModelCommand AddArgument("extensionFieldSets", &mExtensionFieldSets); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterAddSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID, mTransitionTime, mSceneName, mExtensionFieldSets); @@ -2982,7 +2982,7 @@ class ScenesCopyScene : public ModelCommand AddArgument("sceneIdentifierTo", 0, UINT8_MAX, &mSceneIdentifierTo); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterCopySceneCommand(buffer->Start(), bufferSize, endPointId, mMode, mGroupIdentifierFrom, mSceneIdentifierFrom, mGroupIdentifierTo, mSceneIdentifierTo); @@ -3027,7 +3027,7 @@ class ScenesEnhancedAddScene : public ModelCommand AddArgument("extensionFieldSets", &mExtensionFieldSets); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterEnhancedAddSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID, mTransitionTime, mSceneName, mExtensionFieldSets); @@ -3068,7 +3068,7 @@ class ScenesEnhancedViewScene : public ModelCommand AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterEnhancedViewSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID); } @@ -3110,7 +3110,7 @@ class ScenesGetSceneMembership : public ModelCommand AddArgument("groupID", 0, UINT16_MAX, &mGroupID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterGetSceneMembershipCommand(buffer->Start(), bufferSize, endPointId, mGroupID); } @@ -3149,7 +3149,7 @@ class ScenesRecallScene : public ModelCommand AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterRecallSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID, mTransitionTime); } @@ -3171,7 +3171,7 @@ class ScenesRemoveAllScenes : public ModelCommand AddArgument("groupID", 0, UINT16_MAX, &mGroupID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterRemoveAllScenesCommand(buffer->Start(), bufferSize, endPointId, mGroupID); } @@ -3205,7 +3205,7 @@ class ScenesRemoveScene : public ModelCommand AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterRemoveSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID); } @@ -3242,7 +3242,7 @@ class ScenesStoreScene : public ModelCommand AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterStoreSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID); } @@ -3279,7 +3279,7 @@ class ScenesViewScene : public ModelCommand AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterViewSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID); } @@ -3318,7 +3318,7 @@ class ReadScenesSceneCount : public ModelCommand public: ReadScenesSceneCount() : ModelCommand("read", SCENES_CLUSTER_ID) { AddArgument("attr-name", "scene-count"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterReadSceneCountAttribute(buffer->Start(), bufferSize, endPointId); } @@ -3332,7 +3332,7 @@ class ReadScenesCurrentScene : public ModelCommand public: ReadScenesCurrentScene() : ModelCommand("read", SCENES_CLUSTER_ID) { AddArgument("attr-name", "current-scene"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterReadCurrentSceneAttribute(buffer->Start(), bufferSize, endPointId); } @@ -3346,7 +3346,7 @@ class ReadScenesCurrentGroup : public ModelCommand public: ReadScenesCurrentGroup() : ModelCommand("read", SCENES_CLUSTER_ID) { AddArgument("attr-name", "current-group"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterReadCurrentGroupAttribute(buffer->Start(), bufferSize, endPointId); } @@ -3360,7 +3360,7 @@ class ReadScenesSceneValid : public ModelCommand public: ReadScenesSceneValid() : ModelCommand("read", SCENES_CLUSTER_ID) { AddArgument("attr-name", "scene-valid"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterReadSceneValidAttribute(buffer->Start(), bufferSize, endPointId); } @@ -3374,7 +3374,7 @@ class ReadScenesNameSupport : public ModelCommand public: ReadScenesNameSupport() : ModelCommand("read", SCENES_CLUSTER_ID) { AddArgument("attr-name", "name-support"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterReadNameSupportAttribute(buffer->Start(), bufferSize, endPointId); } @@ -3403,7 +3403,7 @@ class ReadTemperatureMeasurementMeasuredValue : public ModelCommand AddArgument("attr-name", "measured-value"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeTemperatureMeasurementClusterReadMeasuredValueAttribute(buffer->Start(), bufferSize, endPointId); } @@ -3420,7 +3420,7 @@ class ReadTemperatureMeasurementMinMeasuredValue : public ModelCommand AddArgument("attr-name", "min-measured-value"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeTemperatureMeasurementClusterReadMinMeasuredValueAttribute(buffer->Start(), bufferSize, endPointId); } @@ -3437,7 +3437,7 @@ class ReadTemperatureMeasurementMaxMeasuredValue : public ModelCommand AddArgument("attr-name", "max-measured-value"); } - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override + uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeTemperatureMeasurementClusterReadMaxMeasuredValueAttribute(buffer->Start(), bufferSize, endPointId); } diff --git a/examples/chip-tool/commands/common/Command.h b/examples/chip-tool/commands/common/Command.h index ca9448f1fbf058..448ad1e3de019a 100644 --- a/examples/chip-tool/commands/common/Command.h +++ b/examples/chip-tool/commands/common/Command.h @@ -54,8 +54,8 @@ struct Argument { const char * name; ArgumentType type; - uint32_t min; - uint32_t max; + int64_t min; + int64_t max; void * value; }; diff --git a/examples/chip-tool/commands/common/EchoCommand.cpp b/examples/chip-tool/commands/common/EchoCommand.cpp index e9d57e41426e65..cf3fbe9715bd7c 100644 --- a/examples/chip-tool/commands/common/EchoCommand.cpp +++ b/examples/chip-tool/commands/common/EchoCommand.cpp @@ -26,19 +26,24 @@ static const char * PAYLOAD = "Message from Standalone CHIP echo client!"; void EchoCommand::SendEcho() const { - size_t payload_len = strlen(PAYLOAD); + size_t payloadLen = strlen(PAYLOAD); + if (payloadLen > UINT16_MAX) + { + ChipLogError(chipTool, "PAYLOAD length too big for PacketBuffer (> UINT16_MAX)"); + return; + } // Reallocate buffer on each run, as the secure transport encrypts and // overwrites the buffer from previous iteration. - auto * buffer = PacketBuffer::NewWithAvailableSize(payload_len); + auto * buffer = PacketBuffer::NewWithAvailableSize(static_cast(payloadLen)); if (buffer == nullptr) { ChipLogError(chipTool, "Failed to allocate memory for packet data."); return; } - memcpy(buffer->Start(), PAYLOAD, payload_len); - buffer->SetDataLength(payload_len); + memcpy(buffer->Start(), PAYLOAD, payloadLen); + buffer->SetDataLength(static_cast(payloadLen)); CHIP_ERROR err = mController->SendMessage(NULL, buffer); if (err == CHIP_NO_ERROR) diff --git a/examples/chip-tool/commands/common/ModelCommand.cpp b/examples/chip-tool/commands/common/ModelCommand.cpp index 5029d0731da732..0a37ab5048fef2 100644 --- a/examples/chip-tool/commands/common/ModelCommand.cpp +++ b/examples/chip-tool/commands/common/ModelCommand.cpp @@ -85,8 +85,8 @@ CHIP_ERROR ModelCommand::Run(ChipDeviceController * dc, NodeId remoteId) bool ModelCommand::SendCommand(ChipDeviceController * dc) { // Make sure our buffer is big enough, but this will need a better setup! - static const size_t bufferSize = 1024; - auto * buffer = PacketBuffer::NewWithAvailableSize(bufferSize); + static const uint16_t bufferSize = 1024; + auto * buffer = PacketBuffer::NewWithAvailableSize(bufferSize); if (buffer == nullptr) { @@ -137,7 +137,7 @@ void ModelCommand::ReceiveCommandResponse(ChipDeviceController * dc, PacketBuffe frameControl = chip::Encoding::Read8(message); sequenceNumber = chip::Encoding::Read8(message); commandId = chip::Encoding::Read8(message); - messageLen -= 3; + messageLen = static_cast(messageLen - 3); VerifyOrExit(isValidFrame(frameControl), ChipLogError(chipTool, "Unexpected frame control byte: 0x%02x", frameControl)); VerifyOrExit(sequenceNumber == 1, ChipLogError(chipTool, "Unexpected sequence number: %d", sequenceNumber)); @@ -145,7 +145,7 @@ void ModelCommand::ReceiveCommandResponse(ChipDeviceController * dc, PacketBuffe mEndPointId == frame.sourceEndpoint, ChipLogError(chipTool, "Invalid endpoint '0x%02x'. Expected endpoint '0x%02x'", frame.sourceEndpoint, mEndPointId)); VerifyOrExit(mClusterId == frame.clusterId, - ChipLogError(chipTool, "Invalid cluster '0x%02x'. Expected cluster '0x%02x'", frame.clusterId, mClusterId)); + ChipLogError(chipTool, "Invalid cluster '0x%04x'. Expected cluster '0x%04x'", frame.clusterId, mClusterId)); isGlobalCommand = (frameControl == kZCLGlobalCmdFrameControlHeader); isGlobalCommand ? ParseGlobalResponseCommand(commandId, message, messageLen) @@ -199,9 +199,9 @@ void ModelCommand::ParseReadAttributeResponseCommand(uint8_t * message, uint16_t // But for now we only support one attribute value, and that value is a boolean. CHECK_MESSAGE_LENGTH(messageLen >= 3); - attrId = chip::Encoding::LittleEndian::Read16(message); - status = chip::Encoding::Read8(message); - messageLen -= 3; + attrId = chip::Encoding::LittleEndian::Read16(message); + status = chip::Encoding::Read8(message); + messageLen = static_cast(messageLen - 3); if (status == 0) { @@ -261,7 +261,7 @@ void ModelCommand::ParseReadAttributeResponseCommandFailure(uint16_t attrId, uin void ModelCommand::ParseSpecificClusterResponseCommand(uint8_t commandId, uint8_t * message, uint16_t messageLen) const { - ChipLogProgress(chipTool, "Parsing cluster id '0x%02x' response command '0x%02x'", mClusterId, commandId); + ChipLogProgress(chipTool, "Parsing cluster id '0x%04x' response command '0x%02x'", mClusterId, commandId); if (!HandleClusterResponse(message, messageLen)) { ChipLogProgress(chipTool, "Not handling command '0x%02x'", commandId); diff --git a/examples/chip-tool/commands/common/ModelCommand.h b/examples/chip-tool/commands/common/ModelCommand.h index efc4f782eb4c13..e7a4fa1fb0ab46 100644 --- a/examples/chip-tool/commands/common/ModelCommand.h +++ b/examples/chip-tool/commands/common/ModelCommand.h @@ -51,7 +51,7 @@ class ModelCommand : public NetworkCommand void OnError(ChipDeviceController * dc, CHIP_ERROR err) override; void OnMessage(ChipDeviceController * dc, chip::System::PacketBuffer * buffer) override; - virtual size_t EncodeCommand(chip::System::PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) = 0; + virtual uint16_t EncodeCommand(chip::System::PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) = 0; virtual bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const { return false; } private: @@ -72,6 +72,6 @@ class ModelCommand : public NetworkCommand std::condition_variable cvWaitingForResponse; std::mutex cvWaitingForResponseMutex; bool mWaitingForResponse{ false }; - uint32_t mEndPointId; uint16_t mClusterId; + uint8_t mEndPointId; }; diff --git a/examples/chip-tool/commands/common/NetworkCommand.h b/examples/chip-tool/commands/common/NetworkCommand.h index 79f21f847b2523..dcc9fc0caa06d8 100644 --- a/examples/chip-tool/commands/common/NetworkCommand.h +++ b/examples/chip-tool/commands/common/NetworkCommand.h @@ -60,7 +60,7 @@ class NetworkCommand : public Command char mName[46]; Command::AddressWithInterface mRemoteAddr; - uint32_t mRemotePort; - uint32_t mDiscriminator; + uint16_t mRemotePort; + uint16_t mDiscriminator; uint32_t mSetupPINCode; }; diff --git a/src/lib/support/SafeInt.h b/src/lib/support/SafeInt.h index f513b76f7aaf9d..efbaa23b376bea 100644 --- a/src/lib/support/SafeInt.h +++ b/src/lib/support/SafeInt.h @@ -138,7 +138,7 @@ typename std::enable_if::value, typename std::make_signed // then noting that both (numeric_limits::max() - arg) and its negation // are guaranteed to fit in signed_type. signed_type diff = static_cast(numeric_limits::max() - arg); - return -diff - 1; + return static_cast(-diff - 1); } } // namespace chip From e90a5e3ffee67b3338f0a46354aa9d547dd8904e Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Tue, 13 Oct 2020 20:23:47 +0200 Subject: [PATCH 13/40] Add src/platform/Darwin/Logging.cpp and use it for chip-tool and ios (#3215) * Add src/platform/Darwin/Logging.cpp and use it for chip-tool and ios * Move src/platform/Darwin/Logging.cpp under src/lib/support/CHIPLoggingLogV.cpp --- .../Framework/CHIP.xcodeproj/project.pbxproj | 4 - src/darwin/Framework/CHIP/CHIPLogging.mm | 92 ------------------- .../Framework/chip_xcode_build_connector.sh | 4 - src/lib/core/BUILD.gn | 2 + src/lib/core/core.gni | 5 +- src/lib/support/logging/CHIPLoggingLogV.cpp | 51 ++++++++++ 6 files changed, 57 insertions(+), 101 deletions(-) delete mode 100644 src/darwin/Framework/CHIP/CHIPLogging.mm diff --git a/src/darwin/Framework/CHIP.xcodeproj/project.pbxproj b/src/darwin/Framework/CHIP.xcodeproj/project.pbxproj index 8d8a347d8ca514..6aa72494cca002 100644 --- a/src/darwin/Framework/CHIP.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/CHIP.xcodeproj/project.pbxproj @@ -29,7 +29,6 @@ B2F53AF2245B0DCF0010745E /* CHIPSetupPayloadParserTests.m in Sources */ = {isa = PBXBuildFile; fileRef = B2F53AF1245B0DCF0010745E /* CHIPSetupPayloadParserTests.m */; }; BA09EB43247477BA00605257 /* libCHIP.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BA09EB3F2474762900605257 /* libCHIP.a */; }; BA107AEF2470CFBB004287EB /* chip_xcode_build_connector.sh in Resources */ = {isa = PBXBuildFile; fileRef = BA107AEE2470CFBB004287EB /* chip_xcode_build_connector.sh */; }; - C4C222C02475A38700984173 /* CHIPLogging.mm in Sources */ = {isa = PBXBuildFile; fileRef = C4C222BF2475A38700984173 /* CHIPLogging.mm */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -68,7 +67,6 @@ B2F53AF1245B0DCF0010745E /* CHIPSetupPayloadParserTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CHIPSetupPayloadParserTests.m; sourceTree = ""; }; BA09EB3F2474762900605257 /* libCHIP.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libCHIP.a; path = lib/libCHIP.a; sourceTree = BUILT_PRODUCTS_DIR; }; BA107AEE2470CFBB004287EB /* chip_xcode_build_connector.sh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.sh; path = chip_xcode_build_connector.sh; sourceTree = ""; }; - C4C222BF2475A38700984173 /* CHIPLogging.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = CHIPLogging.mm; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -121,7 +119,6 @@ B2E0D7A8245B0B5C003C5B48 /* CHIP.h */, B2E0D7AB245B0B5C003C5B48 /* CHIPError.h */, B2E0D7AA245B0B5C003C5B48 /* CHIPError.mm */, - C4C222BF2475A38700984173 /* CHIPLogging.mm */, 991DC08A247704DC00C13860 /* CHIPLogging.h */, B2E0D7A9245B0B5C003C5B48 /* CHIPManualSetupPayloadParser.h */, B2E0D7AD245B0B5C003C5B48 /* CHIPManualSetupPayloadParser.mm */, @@ -301,7 +298,6 @@ 515C401C2486BF43004C4DB3 /* CHIPOnOff.mm in Sources */, 991DC0892475F47D00C13860 /* CHIPDeviceController.mm in Sources */, B2E0D7B7245B0B5C003C5B48 /* CHIPQRCodeSetupPayloadParser.mm in Sources */, - C4C222C02475A38700984173 /* CHIPLogging.mm in Sources */, B2E0D7B3245B0B5C003C5B48 /* CHIPError.mm in Sources */, B2E0D7B9245B0B5C003C5B48 /* CHIPSetupPayload.mm in Sources */, B2E0D7B6245B0B5C003C5B48 /* CHIPManualSetupPayloadParser.mm in Sources */, diff --git a/src/darwin/Framework/CHIP/CHIPLogging.mm b/src/darwin/Framework/CHIP/CHIPLogging.mm deleted file mode 100644 index b130deeaa44a6c..00000000000000 --- a/src/darwin/Framework/CHIP/CHIPLogging.mm +++ /dev/null @@ -1,92 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2013-2017 Nest Labs, Inc. - * 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. - */ - -/** - * @file - * This file implements a platform-specific CHIP log interface. - * - */ - -#include -#include - -#import -#import - -#include - -#if CHIP_ERROR_LOGGING || CHIP_PROGRESS_LOGGING || CHIP_DETAIL_LOGGING - -namespace chip { - -namespace Logging { - - /* - * void LogV() - * - * Description: - * This routine writes to the Foundation log stream, the - * specified CHIP-related variable argument message for the - * specified CHIP module and category. - * - * Input(s): - * aModule - An enumeration indicating the CHIP module or - * subsystem the message is associated with. - * aCategory - An enumeration indicating the CHIP category - * the message is associated with. - * aMsg - A NULL-terminated C string containing the message, - * with C Standard I/O-style format specifiers, to log. - * aV - A variable argument list, corresponding to format - * specifiers in the message. - * - * Output(s): - * N/A - * - * Returns: - * N/A - * - * @note There is a function called Log(), which takes a varargs intead of a - * va_list and will call this function as needed. It's declared and - * implemented in the core CHIP library. - */ - void LogV(uint8_t aModule, uint8_t aCategory, const char * aMsg, va_list aV) - { - if (IsCategoryEnabled(aCategory)) { - char formattedMsg[512]; - size_t prefixLen; - - char moduleName[ChipLoggingModuleNameLen + 1]; - GetModuleName(moduleName, aModule); - - prefixLen = snprintf( - formattedMsg, sizeof(formattedMsg), "CHIP:%s: %s", moduleName, (aCategory == kLogCategory_Error) ? "ERROR: " : ""); - if (prefixLen >= sizeof(formattedMsg)) - prefixLen = sizeof(formattedMsg) - 1; - - vsnprintf(formattedMsg + prefixLen, sizeof(formattedMsg) - prefixLen, aMsg, aV); - - os_log(OS_LOG_DEFAULT, "%s", formattedMsg); - } - } - -} // namespace Logging - -} // namespace chip - -#endif // CHIP_ERROR_LOGGING || CHIP_PROGRESS_LOGGING || CHIP_DETAIL_LOGGING diff --git a/src/darwin/Framework/chip_xcode_build_connector.sh b/src/darwin/Framework/chip_xcode_build_connector.sh index 4993e279d7b9b2..8eeef3e2ec821d 100755 --- a/src/darwin/Framework/chip_xcode_build_connector.sh +++ b/src/darwin/Framework/chip_xcode_build_connector.sh @@ -47,9 +47,6 @@ for define in "${DEFINES[@]}"; do # skip over those that GN does for us case "$define" in - CHIP_LOGGING_STYLE*) - continue - ;; CHIP_DEVICE_LAYER*) continue ;; @@ -74,7 +71,6 @@ declare -a args=( 'chip_crypto="mbedtls"' 'chip_build_tools=false' 'chip_build_tests=false' - 'chip_logging_style="external"' 'chip_ble_project_config_include=""' 'chip_device_project_config_include=""' 'chip_inet_project_config_include=""' diff --git a/src/lib/core/BUILD.gn b/src/lib/core/BUILD.gn index 783c6e4765095c..cd1995d92b9ec9 100644 --- a/src/lib/core/BUILD.gn +++ b/src/lib/core/BUILD.gn @@ -27,6 +27,7 @@ buildconfig_header("chip_buildconfig") { chip_target_style_unix = chip_target_style == "unix" chip_target_style_embedded = chip_target_style == "embedded" chip_logging_style_android = chip_logging_style == "android" + chip_logging_style_darwin = chip_logging_style == "darwin" chip_logging_style_external = chip_logging_style == "external" chip_logging_style_stdio = chip_logging_style == "stdio" chip_logging_style_stdio_weak = chip_logging_style == "stdio_weak" @@ -53,6 +54,7 @@ buildconfig_header("chip_buildconfig") { "CHIP_TARGET_STYLE_UNIX=${chip_target_style_unix}", "CHIP_TARGET_STYLE_EMBEDDED=${chip_target_style_embedded}", "CHIP_LOGGING_STYLE_ANDROID=${chip_logging_style_android}", + "CHIP_LOGGING_STYLE_DARWIN=${chip_logging_style_darwin}", "CHIP_LOGGING_STYLE_EXTERNAL=${chip_logging_style_external}", "CHIP_LOGGING_STYLE_STDIO=${chip_logging_style_stdio}", "CHIP_LOGGING_STYLE_STDIO_WEAK=${chip_logging_style_stdio_weak}", diff --git a/src/lib/core/core.gni b/src/lib/core/core.gni index 123629caa967ac..937941ce2d06c6 100644 --- a/src/lib/core/core.gni +++ b/src/lib/core/core.gni @@ -54,6 +54,8 @@ if (chip_target_style == "") { if (chip_logging_style == "") { if (current_os == "android") { chip_logging_style = "android" + } else if (current_os == "mac" || current_os == "ios") { + chip_logging_style = "darwin" } else if (current_os != "freertos") { chip_logging_style = "stdio" } else { @@ -66,7 +68,8 @@ assert(chip_target_style == "unix" || chip_target_style == "embedded", assert( chip_logging_style == "android" || chip_logging_style == "external" || - chip_logging_style == "stdio" || chip_logging_style == "stdio_weak", + chip_logging_style == "stdio" || chip_logging_style == "stdio_weak" || + chip_logging_style == "darwin", "Please select a valid logging style: android, external, stdio, stdio_weak") assert( diff --git a/src/lib/support/logging/CHIPLoggingLogV.cpp b/src/lib/support/logging/CHIPLoggingLogV.cpp index dd8b869a9219b3..5178d398e26881 100644 --- a/src/lib/support/logging/CHIPLoggingLogV.cpp +++ b/src/lib/support/logging/CHIPLoggingLogV.cpp @@ -33,6 +33,10 @@ #include #endif +#if CHIP_LOGGING_STYLE_DARWIN +#include +#endif + #if HAVE_SYS_TIME_H && CHIP_LOGGING_STYLE_STDIO_WITH_TIMESTAMPS #include #endif // HAVE_SYS_TIME_H && CHIP_LOGGING_STYLE_STDIO_WITH_TIMESTAMPS @@ -106,6 +110,53 @@ DLL_EXPORT __CHIP_LOGGING_LINK_ATTRIBUTE void LogV(uint8_t module, uint8_t categ vprintf(msg, v); printf("\n"); +#elif CHIP_LOGGING_STYLE_DARWIN + + char moduleName[ChipLoggingModuleNameLen + 1]; + GetModuleName(moduleName, module); + + char formattedMsg[512]; + int32_t prefixLen = snprintf(formattedMsg, sizeof(formattedMsg), "CHIP: [%s] ", moduleName); + if (prefixLen < 0) + { + // This should never happens. + return; + } + + if (prefixLen >= sizeof(formattedMsg)) + { + prefixLen = sizeof(formattedMsg) - 1; + } + + vsnprintf(formattedMsg + prefixLen, sizeof(formattedMsg) - static_cast(prefixLen), msg, v); + + switch (category) + { + case kLogCategory_Error: + os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_ERROR, "🔴 %{public}s", formattedMsg); +#if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 + fprintf(stdout, "\033[1;31m"); +#endif + break; + + case kLogCategory_Progress: + os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_INFO, "🔵 %{public}s", formattedMsg); +#if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 + fprintf(stdout, "\033[0;32m"); +#endif + break; + + case kLogCategory_Detail: + os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_DEBUG, "🟢 %{public}s", formattedMsg); +#if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 + fprintf(stdout, "\033[0;34m"); +#endif + break; + } +#if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 + fprintf(stdout, "%s\033[0m\n", formattedMsg); +#endif + #else #error "Undefined platform-specific implementation for non-externnal chip logging style!" From 382008c7cf8af44fc59fcb5f078757db62baa800 Mon Sep 17 00:00:00 2001 From: Michael Spang Date: Tue, 13 Oct 2020 16:10:25 -0400 Subject: [PATCH 14/40] Reduce kSpake2p_Iteration_Count to fix timeouts (#3205) * Reduce kSpake2p_Iteration_Count to fix timeouts Initializing this takes 15 seconds on ESP32, which is longer than most timers we specify (e.g. BLE disconnect timer is 5 seconds). Reduce this to a value that doesn't interfere with other work. fixes #3089 * Update RendezvousSession.cpp * Update RendezvousSession.cpp --- src/transport/RendezvousSession.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transport/RendezvousSession.cpp b/src/transport/RendezvousSession.cpp index 3f872072f749c9..d818063233dc3f 100644 --- a/src/transport/RendezvousSession.cpp +++ b/src/transport/RendezvousSession.cpp @@ -28,7 +28,7 @@ #endif // CONFIG_NETWORK_LAYER_BLE static const size_t kMax_SecureSDU_Length = 1024; -static constexpr uint32_t kSpake2p_Iteration_Count = 50000; +static constexpr uint32_t kSpake2p_Iteration_Count = 100; static const char * kSpake2pKeyExchangeSalt = "SPAKE2P Key Exchange Salt"; using namespace chip::Inet; From 716269815c867196488815e5a61e77ec76233c13 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Wed, 14 Oct 2020 02:39:19 +0200 Subject: [PATCH 15/40] ChipTool: Use an env variable to filters ChipLog* messages if needed (#3226) --- examples/chip-tool/BUILD.gn | 1 + .../chip-tool/commands/common/Commands.cpp | 3 + .../chip-tool/commands/common/Logging.cpp | 59 +++++++++++++++++++ examples/chip-tool/commands/common/Logging.h | 21 +++++++ 4 files changed, 84 insertions(+) create mode 100644 examples/chip-tool/commands/common/Logging.cpp create mode 100644 examples/chip-tool/commands/common/Logging.h diff --git a/examples/chip-tool/BUILD.gn b/examples/chip-tool/BUILD.gn index 410126356ca74d..9f5a4107c0767e 100644 --- a/examples/chip-tool/BUILD.gn +++ b/examples/chip-tool/BUILD.gn @@ -23,6 +23,7 @@ executable("chip-tool") { "commands/common/Command.cpp", "commands/common/Commands.cpp", "commands/common/EchoCommand.cpp", + "commands/common/Logging.cpp", "commands/common/ModelCommand.cpp", "commands/common/NetworkCommand.cpp", "main.cpp", diff --git a/examples/chip-tool/commands/common/Commands.cpp b/examples/chip-tool/commands/common/Commands.cpp index 82b13b56636120..0eab0309edbbac 100644 --- a/examples/chip-tool/commands/common/Commands.cpp +++ b/examples/chip-tool/commands/common/Commands.cpp @@ -19,6 +19,7 @@ #include "Commands.h" #include "Command.h" +#include "Logging.h" #include #include @@ -33,6 +34,8 @@ void Commands::Register(const char * clusterName, commands_list commandsList) int Commands::Run(NodeId localId, NodeId remoteId, int argc, char ** argv) { + ConfigureChipLogging(); + CHIP_ERROR err = CHIP_NO_ERROR; ChipDeviceController dc; diff --git a/examples/chip-tool/commands/common/Logging.cpp b/examples/chip-tool/commands/common/Logging.cpp new file mode 100644 index 00000000000000..908349dd7125f6 --- /dev/null +++ b/examples/chip-tool/commands/common/Logging.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2020 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 +#include + +#include +#include + +using namespace ::chip::Logging; + +constexpr LogCategory kDefaultLoggingLevel = kLogCategory_Detail; + +void ConfigureChipLogging() +{ + LogCategory chipLogLevel = kDefaultLoggingLevel; + + const char * level = getenv("CHIP_LOG_LEVEL"); + VerifyOrExit(level != NULL, /**/); + + if (strcasecmp(level, "none") == 0) + { + chipLogLevel = kLogCategory_None; + } + else if (strcasecmp(level, "error") == 0) + { + chipLogLevel = kLogCategory_Error; + } + else if (strcasecmp(level, "progress") == 0) + { + chipLogLevel = kLogCategory_Progress; + } + else if (strcasecmp(level, "detail") == 0) + { + chipLogLevel = kLogCategory_Detail; + } + else if (strcasecmp(level, "retain") == 0) + { + chipLogLevel = kLogCategory_Retain; + } + +exit: + SetLogFilter(chipLogLevel); +} diff --git a/examples/chip-tool/commands/common/Logging.h b/examples/chip-tool/commands/common/Logging.h new file mode 100644 index 00000000000000..c2893208a70969 --- /dev/null +++ b/examples/chip-tool/commands/common/Logging.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2020 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 + +void ConfigureChipLogging(); From 8c2f388427fcefb5cef5707fe1bcf7d07ac55eff Mon Sep 17 00:00:00 2001 From: jmartinez-silabs <67972863+jmartinez-silabs@users.noreply.github.com> Date: Tue, 13 Oct 2020 20:39:38 -0400 Subject: [PATCH 16/40] [EFR32] Stack overflow on MG21 boards (#3224) * Reduce Chip task and Thread task Stack size for EFR platforms (fix stack overflow for mg21) Fix CPU and Architecture flags for MG21 family Add ldflags to lock_app and lighting_app to show memory usage after build * Fix rebase conflict * Fix build for lock app/Undo removed includes * Restyled by whitespace * Restyled by gn * Fix removed #ifdef with previous merge * Restyled by whitespace * add opt-in for binary size console output Fix typo in comment * Restyled by gn * Set chip_print_memory_usage as build argurment variable for examples apps Co-authored-by: Restyled.io --- examples/lighting-app/efr32/BUILD.gn | 12 +++++ examples/lighting-app/efr32/include/AppTask.h | 4 +- examples/lighting-app/efr32/src/AppTask.cpp | 29 +++++++---- examples/lock-app/efr32/BUILD.gn | 12 +++++ examples/lock-app/efr32/include/AppTask.h | 3 +- examples/lock-app/efr32/src/AppTask.cpp | 52 ++++++------------- examples/platform/efr32/Service.cpp | 29 +++++++++++ examples/platform/efr32/Service.h | 1 + src/platform/EFR32/CHIPDevicePlatformConfig.h | 4 +- third_party/efr32_sdk/efr32_arm.gni | 10 ++-- 10 files changed, 100 insertions(+), 56 deletions(-) diff --git a/examples/lighting-app/efr32/BUILD.gn b/examples/lighting-app/efr32/BUILD.gn index 4f3e5d597b705b..8157588dad113a 100644 --- a/examples/lighting-app/efr32/BUILD.gn +++ b/examples/lighting-app/efr32/BUILD.gn @@ -23,6 +23,11 @@ assert(current_os == "freertos") efr32_project_dir = "${chip_root}/examples/lighting-app/efr32" examples_plat_dir = "${chip_root}/examples/platform/efr32" +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + show_qr_code = true # BRD4166A --> ThunderBoard Sense 2 (No LCD) @@ -124,6 +129,13 @@ efr32_executable("lighting_app") { } ldflags = [ "-T" + rebase_path(ldscript, root_build_dir) ] + + if (chip_print_memory_usage) { + ldflags += [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } } group("efr32") { diff --git a/examples/lighting-app/efr32/include/AppTask.h b/examples/lighting-app/efr32/include/AppTask.h index 64405818e6ec2c..e286abf5fc686a 100644 --- a/examples/lighting-app/efr32/include/AppTask.h +++ b/examples/lighting-app/efr32/include/AppTask.h @@ -67,7 +67,8 @@ class AppTask { kFunction_NoneSelected = 0, kFunction_SoftwareUpdate = 0, - kFunction_FactoryReset, + kFunction_StartThread = 1, + kFunction_FactoryReset = 2, kFunction_Invalid } Function; @@ -75,7 +76,6 @@ class AppTask Function_t mFunction; bool mFunctionTimerActive; bool mSyncClusterToButtonAction; - chip::Ble::BLEEndPoint * mBLEEndPoint; static AppTask sAppTask; }; diff --git a/examples/lighting-app/efr32/src/AppTask.cpp b/examples/lighting-app/efr32/src/AppTask.cpp index aeacbef2eba838..a3ed269afcfffc 100644 --- a/examples/lighting-app/efr32/src/AppTask.cpp +++ b/examples/lighting-app/efr32/src/AppTask.cpp @@ -35,9 +35,6 @@ #include #include -using namespace chip::TLV; -using namespace chip::DeviceLayer; - #include #if CHIP_ENABLE_OPENTHREAD #include @@ -67,6 +64,7 @@ static bool sIsThreadAttached = false; static bool sHaveBLEConnections = false; static bool sHaveServiceConnectivity = false; +using namespace chip::TLV; using namespace ::chip::DeviceLayer; AppTask AppTask::sAppTask; @@ -355,7 +353,7 @@ void AppTask::FunctionTimerEventHandler(AppEvent * aEvent) // If we reached here, the button was held past FACTORY_RESET_TRIGGER_TIMEOUT, // initiate factory reset - if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_SoftwareUpdate) + if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_StartThread) { EFR32_LOG("Factory Reset Triggered. Release button within %ums to cancel.", FACTORY_RESET_CANCEL_WINDOW_TIMEOUT); @@ -400,20 +398,29 @@ void AppTask::FunctionHandler(AppEvent * aEvent) if (!sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_NoneSelected) { sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT); - sAppTask.mFunction = kFunction_SoftwareUpdate; + sAppTask.mFunction = kFunction_StartThread; } } else { - // If the button was released before factory reset got initiated, trigger a - // software update. - if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_SoftwareUpdate) + // If the button was released before factory reset got initiated, start Thread Network + if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_StartThread) { sAppTask.CancelTimer(); - sAppTask.mFunction = kFunction_NoneSelected; - - EFR32_LOG("Software Update currently not supported."); +#if CHIP_ENABLE_OPENTHREAD + if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) + { + StartDefaultThreadNetwork(); + EFR32_LOG("Device is not commissioned to a Thread network. Starting with the default configuration."); + } + else + { + EFR32_LOG("Device is commissioned to a Thread network."); + } +#elif + EFR32_LOG("Thread is not defined."); +#endif } else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_FactoryReset) { diff --git a/examples/lock-app/efr32/BUILD.gn b/examples/lock-app/efr32/BUILD.gn index d38c94a3d756c8..a520d48c695c16 100644 --- a/examples/lock-app/efr32/BUILD.gn +++ b/examples/lock-app/efr32/BUILD.gn @@ -23,6 +23,11 @@ assert(current_os == "freertos") efr32_project_dir = "${chip_root}/examples/lock-app/efr32" examples_plat_dir = "${chip_root}/examples/platform/efr32" +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + show_qr_code = true # BRD4166A --> ThunderBoard Sense 2 (No LCD) @@ -124,6 +129,13 @@ efr32_executable("lock_app") { } ldflags = [ "-T" + rebase_path(ldscript, root_build_dir) ] + + if (chip_print_memory_usage) { + ldflags += [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } } group("efr32") { diff --git a/examples/lock-app/efr32/include/AppTask.h b/examples/lock-app/efr32/include/AppTask.h index 020203287d28c7..ae7659b64c54d7 100644 --- a/examples/lock-app/efr32/include/AppTask.h +++ b/examples/lock-app/efr32/include/AppTask.h @@ -67,7 +67,7 @@ class AppTask { kFunction_NoneSelected = 0, kFunction_SoftwareUpdate = 0, - kFunction_Joiner = 1, + kFunction_StartThread = 1, kFunction_FactoryReset = 2, kFunction_Invalid @@ -76,7 +76,6 @@ class AppTask Function_t mFunction; bool mFunctionTimerActive; bool mSyncClusterToButtonAction; - chip::Ble::BLEEndPoint * mBLEEndPoint; static AppTask sAppTask; }; diff --git a/examples/lock-app/efr32/src/AppTask.cpp b/examples/lock-app/efr32/src/AppTask.cpp index 048407d18e75f5..adf109b5540645 100644 --- a/examples/lock-app/efr32/src/AppTask.cpp +++ b/examples/lock-app/efr32/src/AppTask.cpp @@ -35,16 +35,12 @@ #include #include -using namespace chip::TLV; -using namespace chip::DeviceLayer; - #include #if CHIP_ENABLE_OPENTHREAD #include #include #include #include -#define JOINER_START_TRIGGER_TIMEOUT 1500 #endif #define FACTORY_RESET_TRIGGER_TIMEOUT 3000 @@ -68,6 +64,7 @@ static bool sIsPairedToAccount = false; static bool sHaveBLEConnections = false; static bool sHaveServiceConnectivity = false; +using namespace chip::TLV; using namespace ::chip::DeviceLayer; AppTask AppTask::sAppTask; @@ -358,17 +355,8 @@ void AppTask::FunctionTimerEventHandler(AppEvent * aEvent) // If we reached here, the button was held past FACTORY_RESET_TRIGGER_TIMEOUT, // initiate factory reset - if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_SoftwareUpdate) - { -#if CHIP_ENABLE_OPENTHREAD - EFR32_LOG("Release button now to Start Thread Joiner"); - EFR32_LOG("Hold to trigger Factory Reset"); - sAppTask.mFunction = kFunction_Joiner; - sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT); - } - else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_Joiner) + if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_StartThread) { -#endif EFR32_LOG("Factory Reset Triggered. Release button within %ums to cancel.", FACTORY_RESET_CANCEL_WINDOW_TIMEOUT); // Start timer for FACTORY_RESET_CANCEL_WINDOW_TIMEOUT to allow user to @@ -411,37 +399,31 @@ void AppTask::FunctionHandler(AppEvent * aEvent) { if (!sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_NoneSelected) { -#if CHIP_ENABLE_OPENTHREAD - sAppTask.StartTimer(JOINER_START_TRIGGER_TIMEOUT); -#else sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT); -#endif - - sAppTask.mFunction = kFunction_SoftwareUpdate; + sAppTask.mFunction = kFunction_StartThread; } } else { - // If the button was released before factory reset got initiated, trigger a - // software update. - if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_SoftwareUpdate) + // If the button was released before factory reset got initiated, start Thread Network + if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_StartThread) { sAppTask.CancelTimer(); - sAppTask.mFunction = kFunction_NoneSelected; - - EFR32_LOG("Software Update currently not supported."); - } #if CHIP_ENABLE_OPENTHREAD - else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_Joiner) - { - sAppTask.CancelTimer(); - sAppTask.mFunction = kFunction_NoneSelected; - - CHIP_ERROR error = ThreadStackMgr().JoinerStart(); - EFR32_LOG("Thread joiner triggered: %s", chip::ErrorStr(error)); - } + if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) + { + StartDefaultThreadNetwork(); + EFR32_LOG("Device is not commissioned to a Thread network. Starting with the default configuration."); + } + else + { + EFR32_LOG("Device is commissioned to a Thread network."); + } +#elif + EFR32_LOG("Thread is not defined."); #endif + } else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_FactoryReset) { // Set lock status LED back to show state of lock. diff --git a/examples/platform/efr32/Service.cpp b/examples/platform/efr32/Service.cpp index 27884b1cb86859..715d12ab2bf9bf 100644 --- a/examples/platform/efr32/Service.cpp +++ b/examples/platform/efr32/Service.cpp @@ -106,3 +106,32 @@ void PublishService() } ThreadStackMgrImpl().UnlockThreadStack(); } + +void StartDefaultThreadNetwork(void) +{ + // Set default thread network Info and enable/start thread + + chip::DeviceLayer::Internal::DeviceNetworkInfo deviceNetworkInfo; + memset(&deviceNetworkInfo, 0, sizeof(deviceNetworkInfo)); + const char * networkName = "OpenThread"; + const uint8_t masterKey[chip::DeviceLayer::Internal::kThreadNetworkKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, + 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, + 0xcc, 0xdd, 0xee, 0xff }; + const uint8_t threadMeshPrefix[chip::DeviceLayer::Internal::kThreadMeshPrefixLength] = { 0xfd, 0xde, 0xad, 0x00, + 0xbe, 0xef, 0x00, 0x00 }; + + const uint8_t extendedPanId[chip::DeviceLayer::Internal::kThreadExtendedPANIdLength] = { 0xDE, 0xAD, 0x00, 0xBE, + 0xEF, 0x00, 0xCA, 0xFE }; + memcpy(deviceNetworkInfo.ThreadNetworkName, networkName, strlen(networkName)); + memcpy(deviceNetworkInfo.ThreadExtendedPANId, extendedPanId, sizeof(extendedPanId)); + deviceNetworkInfo.FieldPresent.ThreadExtendedPANId = true; + memcpy(deviceNetworkInfo.ThreadNetworkKey, masterKey, sizeof(masterKey)); + deviceNetworkInfo.FieldPresent.ThreadMeshPrefix = true; + memcpy(deviceNetworkInfo.ThreadMeshPrefix, threadMeshPrefix, sizeof(threadMeshPrefix)); + deviceNetworkInfo.ThreadPANId = 0x1234; + deviceNetworkInfo.ThreadChannel = 11; + + chip::DeviceLayer::ThreadStackMgr().SetThreadEnabled(false); + chip::DeviceLayer::ThreadStackMgr().SetThreadProvision(deviceNetworkInfo); + chip::DeviceLayer::ThreadStackMgr().SetThreadEnabled(true); +} diff --git a/examples/platform/efr32/Service.h b/examples/platform/efr32/Service.h index 1426ec65adec71..14abfb0e1d2189 100644 --- a/examples/platform/efr32/Service.h +++ b/examples/platform/efr32/Service.h @@ -19,3 +19,4 @@ void SetDeviceName(const char * newDeviceName); void PublishService(); +void StartDefaultThreadNetwork(void); diff --git a/src/platform/EFR32/CHIPDevicePlatformConfig.h b/src/platform/EFR32/CHIPDevicePlatformConfig.h index 809e6d2e456678..e387f044a60503 100644 --- a/src/platform/EFR32/CHIPDevicePlatformConfig.h +++ b/src/platform/EFR32/CHIPDevicePlatformConfig.h @@ -116,11 +116,11 @@ #endif // CHIP_DEVICE_CONFIG_BLE_APP_TASK_STACK_SIZE #ifndef CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE -#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE 8192 +#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE 4096 #endif // CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE #ifndef CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE -#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE 8192 +#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE 4096 #endif // CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_TELEMETRY 0 diff --git a/third_party/efr32_sdk/efr32_arm.gni b/third_party/efr32_sdk/efr32_arm.gni index 2e871b39139b37..38e0a3849e3c40 100644 --- a/third_party/efr32_sdk/efr32_arm.gni +++ b/third_party/efr32_sdk/efr32_arm.gni @@ -14,14 +14,16 @@ import("efr32_board.gni") -arm_arch = "armv7e-m" -arm_abi = "aapcs" -arm_cpu = "cortex-m4" - if (efr32_family == "efr32mg12") { + arm_arch = "armv7e-m" + arm_abi = "aapcs" + arm_cpu = "cortex-m4" arm_float_abi = "softfp" arm_fpu = "fpv4-sp-d16" } else if (efr32_family == "efr32mg21") { + arm_arch = "armv8-m.main+dsp" + arm_abi = "aapcs" + arm_cpu = "cortex-m33" arm_float_abi = "hard" arm_fpu = "fpv5-sp-d16" } From 4780fd371875069bf356c2d856e90bbace15b2b9 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Wed, 14 Oct 2020 02:39:55 +0200 Subject: [PATCH 17/40] Update ChipLog* from examples/chip-tool, src/app/encoder.cpp and src/controller/CHIPDeviceController.cpp to better represent what they log (#3228) --- examples/chip-tool/commands/common/Command.cpp | 2 +- examples/chip-tool/commands/common/EchoCommand.cpp | 2 +- examples/chip-tool/commands/common/ModelCommand.cpp | 6 +++--- examples/chip-tool/commands/common/NetworkCommand.cpp | 4 ++-- src/app/encoder.cpp | 6 +++--- src/controller/CHIPDeviceController.cpp | 10 +++++----- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/examples/chip-tool/commands/common/Command.cpp b/examples/chip-tool/commands/common/Command.cpp index 98c44c21d581da..6a2826e88bcfa0 100644 --- a/examples/chip-tool/commands/common/Command.cpp +++ b/examples/chip-tool/commands/common/Command.cpp @@ -31,7 +31,7 @@ bool Command::InitArguments(int argc, char ** argv) size_t argsCount = mArgs.size(); VerifyOrExit(argsCount == (size_t)(argc), - ChipLogProgress(chipTool, "InitArgs: Wrong arguments number: %zu instead of %zu", argc, argsCount)); + ChipLogError(chipTool, "InitArgs: Wrong arguments number: %zu instead of %zu", argc, argsCount)); for (size_t i = 0; i < argsCount; i++) { diff --git a/examples/chip-tool/commands/common/EchoCommand.cpp b/examples/chip-tool/commands/common/EchoCommand.cpp index cf3fbe9715bd7c..10de3016edb082 100644 --- a/examples/chip-tool/commands/common/EchoCommand.cpp +++ b/examples/chip-tool/commands/common/EchoCommand.cpp @@ -71,7 +71,7 @@ void EchoCommand::ReceiveEcho(PacketBuffer * buffer) const } else { - ChipLogProgress(chipTool, "Echo: (%s): Error \nSend: %s \nRecv: %s", GetNetworkName(), PAYLOAD, msg_buffer); + ChipLogError(chipTool, "Echo: (%s): Error \nSend: %s \nRecv: %s", GetNetworkName(), PAYLOAD, msg_buffer); } } diff --git a/examples/chip-tool/commands/common/ModelCommand.cpp b/examples/chip-tool/commands/common/ModelCommand.cpp index 0a37ab5048fef2..76405de88b03b5 100644 --- a/examples/chip-tool/commands/common/ModelCommand.cpp +++ b/examples/chip-tool/commands/common/ModelCommand.cpp @@ -103,7 +103,7 @@ bool ModelCommand::SendCommand(ChipDeviceController * dc) } buffer->SetDataLength(dataLength); - ChipLogProgress(chipTool, "Encoded data of length %d", dataLength); + ChipLogDetail(chipTool, "Encoded data of length %d", dataLength); #ifdef DEBUG PrintBuffer(buffer); @@ -129,7 +129,7 @@ void ModelCommand::ReceiveCommandResponse(ChipDeviceController * dc, PacketBuffe PacketBuffer::Free(buffer); ExitNow(); } - ChipLogProgress(chipTool, "APS frame processing success!"); + ChipLogDetail(chipTool, "APS frame processing success!"); messageLen = extractMessage(buffer->Start(), buffer->DataLength(), &message); CHECK_MESSAGE_LENGTH(messageLen >= 3); @@ -264,7 +264,7 @@ void ModelCommand::ParseSpecificClusterResponseCommand(uint8_t commandId, uint8_ ChipLogProgress(chipTool, "Parsing cluster id '0x%04x' response command '0x%02x'", mClusterId, commandId); if (!HandleClusterResponse(message, messageLen)) { - ChipLogProgress(chipTool, "Not handling command '0x%02x'", commandId); + ChipLogError(chipTool, "Not handling command '0x%02x'", commandId); } } diff --git a/examples/chip-tool/commands/common/NetworkCommand.cpp b/examples/chip-tool/commands/common/NetworkCommand.cpp index f06b2ae8e15fd8..a49be61ceb9a9b 100644 --- a/examples/chip-tool/commands/common/NetworkCommand.cpp +++ b/examples/chip-tool/commands/common/NetworkCommand.cpp @@ -24,7 +24,7 @@ using namespace ::chip::System; static void onConnect(ChipDeviceController * dc, Transport::PeerConnectionState * state, void * appReqState) { - ChipLogProgress(chipTool, "OnConnect"); + ChipLogDetail(chipTool, "OnConnect"); NetworkCommand * command = reinterpret_cast(dc->AppState); command->OnConnect(dc); @@ -40,7 +40,7 @@ static void onError(ChipDeviceController * dc, void * appReqState, CHIP_ERROR er static void onMessage(ChipDeviceController * dc, void * appReqState, PacketBuffer * buffer) { - ChipLogProgress(chipTool, "OnMessage: Received %zu bytes", buffer->DataLength()); + ChipLogDetail(chipTool, "OnMessage: Received %zu bytes", buffer->DataLength()); NetworkCommand * command = reinterpret_cast(dc->AppState); command->OnMessage(dc, buffer); diff --git a/src/app/encoder.cpp b/src/app/encoder.cpp index af1145cbcbe1db..220f20eadf1bbb 100644 --- a/src/app/encoder.cpp +++ b/src/app/encoder.cpp @@ -122,17 +122,17 @@ static uint16_t doEncodeApsFrame(BufBound & buf, uint16_t profileID, uint16_t cl if (isMeasuring) { result = buf.Written(); - ChipLogProgress(Zcl, "Measured APS frame size %d", result); + ChipLogDetail(Zcl, "Measured APS frame size %d", result); } else { result = buf.Fit() ? buf.Written() : 0; CHECK_FRAME_LENGTH(result, "Buffer too small"); - ChipLogProgress(Zcl, "Successfully encoded %d bytes", result); + ChipLogDetail(Zcl, "Successfully encoded %d bytes", result); } if (!CanCastTo(result)) { - ChipLogProgress(Zcl, "Can't fit our measured size in uint16_t"); + ChipLogError(Zcl, "Can't fit our measured size in uint16_t"); result = 0; } diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 27247931680e6b..e27e3707347809 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -131,7 +131,7 @@ CHIP_ERROR ChipDeviceController::Shutdown() { CHIP_ERROR err = CHIP_NO_ERROR; - ChipLogProgress(Controller, "Shutting down the controller\n"); + ChipLogDetail(Controller, "Shutting down the controller"); VerifyOrExit(mState == kState_Initialized, err = CHIP_ERROR_INCORRECT_STATE); @@ -387,7 +387,7 @@ CHIP_ERROR ChipDeviceController::SendMessage(void * appReqState, PacketBuffer * buffer->AddRef(); err = mSessionManager->SendMessage(mRemoteDeviceId.Value(), buffer); - ChipLogProgress(Controller, "SendMessage returned %d\n", err); + ChipLogDetail(Controller, "SendMessage returned %d", err); // The send could fail due to network timeouts (e.g. broken pipe) // Try sesion resumption if needed @@ -461,7 +461,7 @@ void ChipDeviceController::OnMessageReceived(const PacketHeader & header, Transp { if (!mRemoteDeviceId.HasValue()) { - ChipLogProgress(Controller, "Learned remote device id"); + ChipLogDetail(Controller, "Learned remote device id"); mRemoteDeviceId = header.GetSourceNodeId(); } else if (mRemoteDeviceId != header.GetSourceNodeId()) @@ -507,7 +507,7 @@ void ChipDeviceController::OnRendezvousStatusUpdate(RendezvousSessionDelegate::S switch (status) { case RendezvousSessionDelegate::SecurePairingSuccess: - ChipLogProgress(Controller, "Remote device completed SPAKE2+ handshake\n"); + ChipLogDetail(Controller, "Remote device completed SPAKE2+ handshake\n"); mPairingSession = mRendezvousSession->GetPairingSession(); mSecurePairingSession = &mPairingSession; @@ -524,7 +524,7 @@ void ChipDeviceController::OnRendezvousStatusUpdate(RendezvousSessionDelegate::S case RendezvousSessionDelegate::NetworkProvisioningSuccess: - ChipLogProgress(Controller, "Remote device was assigned an ip address\n"); + ChipLogDetail(Controller, "Remote device was assigned an ip address\n"); mDeviceAddr = mRendezvousSession->GetIPAddress(); break; From 90090c6f177ac899d88d78a4d43ed9315ed8681d Mon Sep 17 00:00:00 2001 From: Michael Sandstedt Date: Wed, 14 Oct 2020 09:22:33 -0500 Subject: [PATCH 18/40] [build] fix Linux and Darwin builds when chip_enable_ble=false (#3179) (#3238) --- src/BUILD.gn | 4 ++-- src/platform/Darwin/CHIPDevicePlatformConfig.h | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/BUILD.gn b/src/BUILD.gn index 1aab88afc19e1c..58836845c8a9b3 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -27,8 +27,8 @@ config("includes") { defines = [ "CHIP_SEPARATE_CONFIG_H=1" ] - if (current_os == "linux") { - defines += [ "CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE=1" ] + if (chip_device_platform == "linux" || chip_device_platform == "darwin") { + defines += [ "CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE=${chip_enable_ble}" ] } } diff --git a/src/platform/Darwin/CHIPDevicePlatformConfig.h b/src/platform/Darwin/CHIPDevicePlatformConfig.h index ee2f929dcc5b3d..142bc09cfa6550 100644 --- a/src/platform/Darwin/CHIPDevicePlatformConfig.h +++ b/src/platform/Darwin/CHIPDevicePlatformConfig.h @@ -30,7 +30,9 @@ #define CHIP_DEVICE_CONFIG_ENABLE_THREAD 0 +#ifndef CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 +#endif #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 0 From 5b0142e2b8fa20ac41635ec993ab70998cc3e5b6 Mon Sep 17 00:00:00 2001 From: Kevin Schoedel <67607049+kpschoedel@users.noreply.github.com> Date: Wed, 14 Oct 2020 10:40:11 -0400 Subject: [PATCH 19/40] Safety changes after malloc to CHIPMem conversions (#3230) #### Problem As part of heap memory management, a recent change (#3143) replaced malloc()-family calls one-for-one with their "CHIPMem.h" equivalents. Reviewers proposed some related small safety changes. #### Summary of Changes - added an assert() - null out two dead pointers --- src/inet/tests/TestInetCommon.cpp | 2 +- src/lib/core/CHIPTLVReader.cpp | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/inet/tests/TestInetCommon.cpp b/src/inet/tests/TestInetCommon.cpp index e61db451a84988..7aa131917383e1 100644 --- a/src/inet/tests/TestInetCommon.cpp +++ b/src/inet/tests/TestInetCommon.cpp @@ -290,8 +290,8 @@ void InitNetwork() { uint64_t iid = gNetworkOptions.LocalIPv6Addr[j].InterfaceId(); char * tap_name = (char *) chip::Platform::MemoryAlloc(sizeof(gDefaultTapDeviceName)); + assert(tap_name); snprintf(tap_name, sizeof(gDefaultTapDeviceName), "chip-dev-%" PRIx64, iid & 0xFFFF); - tap_name[sizeof(gDefaultTapDeviceName) - 1] = 0; gNetworkOptions.TapDeviceName.push_back(tap_name); } } diff --git a/src/lib/core/CHIPTLVReader.cpp b/src/lib/core/CHIPTLVReader.cpp index 81193dfd577e99..167323a25438b2 100644 --- a/src/lib/core/CHIPTLVReader.cpp +++ b/src/lib/core/CHIPTLVReader.cpp @@ -695,6 +695,7 @@ CHIP_ERROR TLVReader::DupBytes(uint8_t *& buf, uint32_t & dataLen) if (err != CHIP_NO_ERROR) { chip::Platform::MemoryFree(buf); + buf = nullptr; return err; } @@ -739,6 +740,7 @@ CHIP_ERROR TLVReader::DupString(char *& buf) if (err != CHIP_NO_ERROR) { chip::Platform::MemoryFree(buf); + buf = nullptr; return err; } From b8d7be4d24dfd6162096fbec4bc2da7992fc0370 Mon Sep 17 00:00:00 2001 From: Michael Spang Date: Wed, 14 Oct 2020 12:31:23 -0400 Subject: [PATCH 20/40] Fix warnings -Wunused-variable (#3220) Remove unused variable extensionFieldSets --- examples/chip-tool/commands/clusters/Commands.h | 2 -- src/controller/CHIPDeviceController.cpp | 3 +-- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/examples/chip-tool/commands/clusters/Commands.h b/examples/chip-tool/commands/clusters/Commands.h index 8d6cbdea628ff3..321847ec879c21 100644 --- a/examples/chip-tool/commands/clusters/Commands.h +++ b/examples/chip-tool/commands/clusters/Commands.h @@ -3082,7 +3082,6 @@ class ScenesEnhancedViewScene : public ModelCommand uint16_t transitionTime = chip::Encoding::LittleEndian::Read16(message); uint8_t msgLen = chip::Encoding::Read8(message); // FIXME - SExtensionFieldSetList is not supported. - void * extensionFieldSets; ChipLogProgress(chipTool, "EnhancedViewSceneResponse:"); ChipLogProgress(chipTool, " status: 0x%02x", status); @@ -3293,7 +3292,6 @@ class ScenesViewScene : public ModelCommand uint16_t transitionTime = chip::Encoding::LittleEndian::Read16(message); uint8_t msgLen = chip::Encoding::Read8(message); // FIXME - SExtensionFieldSetList is not supported. - void * extensionFieldSets; ChipLogProgress(chipTool, "ViewSceneResponse:"); ChipLogProgress(chipTool, " status: 0x%02x", status); diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index e27e3707347809..d310c1635cb7bb 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -177,8 +177,7 @@ CHIP_ERROR ChipDeviceController::ConnectDevice(NodeId remoteDeviceId, Rendezvous NewConnectionHandler onConnected, MessageReceiveHandler onMessageReceived, ErrorHandler onError, uint16_t devicePort, Inet::InterfaceId interfaceId) { - CHIP_ERROR err = CHIP_NO_ERROR; - RendezvousSession * rendezvousSession = nullptr; + CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(mState == kState_Initialized, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mConState == kConnectionState_NotConnected, err = CHIP_ERROR_INCORRECT_STATE); From 18179b39c22d10758065ea1751d7db6d53c1465a Mon Sep 17 00:00:00 2001 From: Pankaj Garg Date: Wed, 14 Oct 2020 10:36:32 -0700 Subject: [PATCH 21/40] Use 4 bits from discriminator in manual setup code (#3235) * Use 4 bits from discriminator in manual setup code * Restyled by clang-format * Updates to test * Restyled by clang-format Co-authored-by: Restyled.io --- .../ManualSetupPayloadGenerator.cpp | 2 +- src/setup_payload/SetupPayload.cpp | 7 +++- src/setup_payload/SetupPayload.h | 1 + src/setup_payload/tests/TestManualCode.cpp | 39 ++++++++++++++++++- 4 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/setup_payload/ManualSetupPayloadGenerator.cpp b/src/setup_payload/ManualSetupPayloadGenerator.cpp index 3583230a810c7a..a7e5912903069b 100644 --- a/src/setup_payload/ManualSetupPayloadGenerator.cpp +++ b/src/setup_payload/ManualSetupPayloadGenerator.cpp @@ -34,7 +34,7 @@ static uint32_t shortPayloadRepresentation(const SetupPayload & payload) { int offset = 1; uint32_t result = payload.requiresCustomFlow ? 1 : 0; - result |= payload.discriminator << offset; + result |= (payload.discriminator & kManualSetupDiscriminatorFieldBitMask) << offset; offset += kManualSetupDiscriminatorFieldLengthInBits; result |= payload.setUpPINCode << offset; return result; diff --git a/src/setup_payload/SetupPayload.cpp b/src/setup_payload/SetupPayload.cpp index e48cd786981e90..188182749733d4 100644 --- a/src/setup_payload/SetupPayload.cpp +++ b/src/setup_payload/SetupPayload.cpp @@ -83,7 +83,12 @@ bool SetupPayload::isValidQRCodePayload() bool SetupPayload::isValidManualCode() { - if (discriminator >= 1 << kManualSetupDiscriminatorFieldLengthInBits) + // The discriminator for manual setup code is 4 least significant bits + // in a regular 12 bit discriminator. Let's make sure that the provided + // discriminator fits within 12 bits (kPayloadDiscriminatorFieldLengthInBits). + // The manual setup code generator will only use 4 least significant bits from + // it. + if (discriminator >= 1 << kPayloadDiscriminatorFieldLengthInBits) { return false; } diff --git a/src/setup_payload/SetupPayload.h b/src/setup_payload/SetupPayload.h index 479a7a56130820..51dc667a9f8aed 100644 --- a/src/setup_payload/SetupPayload.h +++ b/src/setup_payload/SetupPayload.h @@ -40,6 +40,7 @@ const int kCustomFlowRequiredFieldLengthInBits = 1; const int kRendezvousInfoFieldLengthInBits = 8; const int kPayloadDiscriminatorFieldLengthInBits = 12; const int kManualSetupDiscriminatorFieldLengthInBits = 4; +const int kManualSetupDiscriminatorFieldBitMask = (1 << kManualSetupDiscriminatorFieldLengthInBits) - 1; const int kSetupPINCodeFieldLengthInBits = 27; const int kPaddingFieldLengthInBits = 5; diff --git a/src/setup_payload/tests/TestManualCode.cpp b/src/setup_payload/tests/TestManualCode.cpp index 8944ce6e947112..acdc5ca971f595 100644 --- a/src/setup_payload/tests/TestManualCode.cpp +++ b/src/setup_payload/tests/TestManualCode.cpp @@ -136,7 +136,7 @@ void TestDecimalRepresentation_AllZeros(nlTestSuite * inSuite, void * inContext) void TestDecimalRepresentation_InvalidPayload(nlTestSuite * inSuite, void * inContext) { SetupPayload payload = GetDefaultPayload(); - payload.discriminator = 16; + payload.discriminator = 0x1f00; ManualSetupPayloadGenerator generator(payload); string result; @@ -153,6 +153,42 @@ void assertPayloadValues(nlTestSuite * inSuite, CHIP_ERROR actualError, CHIP_ERR NL_TEST_ASSERT(inSuite, payload.productID == productID); } +void TestGenerateAndParser_ManualSetupCodeWithLongDiscriminator(nlTestSuite * inSuite, void * inContext) +{ + SetupPayload payload = GetDefaultPayload(); + payload.requiresCustomFlow = false; + payload.discriminator = 0xf1a; + + { + // Test short 11 digit code + ManualSetupPayloadGenerator generator(payload); + string result; + NL_TEST_ASSERT(inSuite, generator.payloadDecimalStringRepresentation(result) == CHIP_NO_ERROR); + + SetupPayload outPayload; + CHIP_ERROR err = ManualSetupPayloadParser(result).populatePayload(outPayload); + assertPayloadValues(inSuite, err, CHIP_NO_ERROR, outPayload, payload.setUpPINCode, 0xa, payload.vendorID, + payload.productID); + } + + payload.vendorID = 1; + payload.productID = 1; + payload.requiresCustomFlow = true; + payload.discriminator = 0xf1b; + + { + // Test long 21 digit code + ManualSetupPayloadGenerator generator(payload); + string result; + NL_TEST_ASSERT(inSuite, generator.payloadDecimalStringRepresentation(result) == CHIP_NO_ERROR); + + SetupPayload outPayload; + CHIP_ERROR err = ManualSetupPayloadParser(result).populatePayload(outPayload); + assertPayloadValues(inSuite, err, CHIP_NO_ERROR, outPayload, payload.setUpPINCode, 0xb, payload.vendorID, + payload.productID); + } +} + void assertEmptyPayloadWithError(nlTestSuite * inSuite, CHIP_ERROR actualError, CHIP_ERROR expectedError, const SetupPayload & payload) { @@ -507,6 +543,7 @@ const nlTest sTests[] = NL_TEST_DEF("Decimal Representation from Full Payload without Zeros", TestDecimalRepresentation_FullPayloadWithoutZeros_DoesNotRequireCustomFlow), NL_TEST_DEF("Decimal Representation from Full Payload without Zeros (Custom Flow)", TestDecimalRepresentation_FullPayloadWithoutZeros), NL_TEST_DEF("Test Decimal Representation - Invalid Payload", TestDecimalRepresentation_InvalidPayload), + NL_TEST_DEF("Test 12 bit discriminator for manual setup code", TestGenerateAndParser_ManualSetupCodeWithLongDiscriminator), NL_TEST_DEF("Test Decimal Representation - All Zeros", TestDecimalRepresentation_AllZeros), NL_TEST_DEF("Parse from Partial Payload", TestPayloadParser_PartialPayload), NL_TEST_DEF("Parse from Full Payload", TestPayloadParser_FullPayload), From 50eb18a16a54e9e58ae47958e78b26a4a600d63c Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Wed, 14 Oct 2020 21:07:06 +0200 Subject: [PATCH 22/40] Remove unused folders from chip-tool (#3243) --- .../clusters/BarrierControl/Commands.h | 62 ------------------- .../commands/clusters/DoorLock/Commands.h | 62 ------------------- 2 files changed, 124 deletions(-) delete mode 100644 examples/chip-tool/commands/clusters/BarrierControl/Commands.h delete mode 100644 examples/chip-tool/commands/clusters/DoorLock/Commands.h diff --git a/examples/chip-tool/commands/clusters/BarrierControl/Commands.h b/examples/chip-tool/commands/clusters/BarrierControl/Commands.h deleted file mode 100644 index 34a400fb2b5ba9..00000000000000 --- a/examples/chip-tool/commands/clusters/BarrierControl/Commands.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2020 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/ModelCommand.h" - -class MoveToPercent : public ModelCommand -{ -public: - MoveToPercent(const uint16_t clusterId) : ModelCommand("move-to-percent", clusterId) - { - AddArgument("percent", 0, UINT8_MAX, &mPercent); - } - - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override - { - return encodeMoveToPercentCommand(buffer->Start(), bufferSize, endPointId, mPercent); - } - -private: - uint8_t mPercent; -}; - -class StopMoveToPercent : public ModelCommand -{ -public: - StopMoveToPercent(const uint16_t clusterId) : ModelCommand("stop-move-to-percent", clusterId) {} - - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override - { - return encodeStopMoveToPercentCommand(buffer->Start(), bufferSize, endPointId); - } -}; - -void registerClusterBarrierControl(Commands & commands) -{ - const char * clusterName = "BarrierControl"; - const uint16_t clusterId = 0x0103; - - commands_list clusterCommands = { - make_unique(clusterId), - make_unique(clusterId), - }; - - commands.Register(clusterName, clusterCommands); -} diff --git a/examples/chip-tool/commands/clusters/DoorLock/Commands.h b/examples/chip-tool/commands/clusters/DoorLock/Commands.h deleted file mode 100644 index 8b582fb6c4f0e1..00000000000000 --- a/examples/chip-tool/commands/clusters/DoorLock/Commands.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2020 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/ModelCommand.h" - -class LockDoor : public ModelCommand -{ -public: - LockDoor(const uint16_t clusterId) : ModelCommand("lock-door", clusterId) { AddArgument("PIN", &mPIN); } - - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override - { - return encodeLockDoorCommand(buffer->Start(), bufferSize, endPointId, mPIN); - } - -private: - char * mPIN; -}; - -class UnlockDoor : public ModelCommand -{ -public: - UnlockDoor(const uint16_t clusterId) : ModelCommand("unlock-door", clusterId) { AddArgument("PIN", &mPIN); } - - size_t EncodeCommand(PacketBuffer * buffer, size_t bufferSize, uint16_t endPointId) override - { - return encodeUnlockDoorCommand(buffer->Start(), bufferSize, endPointId, mPIN); - } - -private: - char * mPIN; -}; - -void registerClusterDoorLock(Commands & commands) -{ - const char * clusterName = "DoorLock"; - const uint16_t clusterId = 0x0101; - - commands_list clusterCommands = { - make_unique(clusterId), - make_unique(clusterId), - }; - - commands.Register(clusterName, clusterCommands); -} From 56ea6a5822ace4e6610a2a74dc08229dc3d936d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20Kr=C3=B3lik?= <66667989+Damian-Nordic@users.noreply.github.com> Date: Wed, 14 Oct 2020 21:10:08 +0200 Subject: [PATCH 23/40] Fix build with chip_config_network_layer_ble=false (#3247) * Fix build with chip_config_network_layer_ble=false --- examples/shell/shell_common/cmd_btp.cpp | 4 ++-- src/BUILD.gn | 6 +++++- src/controller/CHIPDeviceController.cpp | 4 ++-- src/lib/message/CHIPConnection.cpp | 2 ++ src/lib/message/CHIPMessageLayer.cpp | 2 ++ 5 files changed, 13 insertions(+), 5 deletions(-) diff --git a/examples/shell/shell_common/cmd_btp.cpp b/examples/shell/shell_common/cmd_btp.cpp index e5b8aae66d9089..99952b1e3ed696 100644 --- a/examples/shell/shell_common/cmd_btp.cpp +++ b/examples/shell/shell_common/cmd_btp.cpp @@ -15,6 +15,8 @@ * limitations under the License. */ +#include "ChipShellCollection.h" + #include #if CONFIG_NETWORK_LAYER_BLE @@ -28,8 +30,6 @@ #include #include -#include - using namespace chip; using namespace chip::Shell; using namespace chip::Platform; diff --git a/src/BUILD.gn b/src/BUILD.gn index 58836845c8a9b3..6ff5b79d1ae7b3 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -15,6 +15,7 @@ import("//build_overrides/chip.gni") import("${chip_root}/build/chip/tests.gni") +import("${chip_root}/src/ble/ble.gni") import("${chip_root}/src/lwip/lwip.gni") import("${chip_root}/src/platform/device.gni") @@ -47,7 +48,6 @@ if (chip_build_tests) { if (chip_device_platform != "esp32") { deps += [ - "${chip_root}/src/ble/tests", "${chip_root}/src/lib/core/tests", "${chip_root}/src/lib/support/tests", "${chip_root}/src/platform/tests", @@ -55,6 +55,10 @@ if (chip_build_tests) { ] } + if (chip_config_network_layer_ble && chip_device_platform != "esp32") { + deps += [ "${chip_root}/src/ble/tests" ] + } + if (chip_with_lwip && chip_device_platform != "esp32") { deps += [ "${chip_root}/src/lwip/tests" ] } diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index d310c1635cb7bb..f40f770bb72a9c 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -182,12 +182,12 @@ CHIP_ERROR ChipDeviceController::ConnectDevice(NodeId remoteDeviceId, Rendezvous VerifyOrExit(mState == kState_Initialized, err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(mConState == kConnectionState_NotConnected, err = CHIP_ERROR_INCORRECT_STATE); -#if CONFIG_DEVICE_LAYER +#if CONFIG_DEVICE_LAYER && CONFIG_NETWORK_LAYER_BLE if (!params.HasBleLayer()) { params.SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()); } -#endif // CONFIG_DEVICE_LAYER +#endif // CONFIG_DEVICE_LAYER && CONFIG_NETWORK_LAYER_BLE mRendezvousSession = new RendezvousSession(this); err = mRendezvousSession->Init(params.SetLocalNodeId(mLocalDeviceId)); diff --git a/src/lib/message/CHIPConnection.cpp b/src/lib/message/CHIPConnection.cpp index a235392db8b94b..d86ae1e713a026 100644 --- a/src/lib/message/CHIPConnection.cpp +++ b/src/lib/message/CHIPConnection.cpp @@ -44,7 +44,9 @@ #include #include +#if CONFIG_NETWORK_LAYER_BLE using namespace chip::Ble; +#endif // CONFIG_NETWORK_LAYER_BLE using namespace chip::Inet; using namespace chip::System; diff --git a/src/lib/message/CHIPMessageLayer.cpp b/src/lib/message/CHIPMessageLayer.cpp index 891b48439cfcff..cbf9f2004745a2 100644 --- a/src/lib/message/CHIPMessageLayer.cpp +++ b/src/lib/message/CHIPMessageLayer.cpp @@ -54,7 +54,9 @@ #include #include +#if CONFIG_NETWORK_LAYER_BLE using namespace chip::Ble; +#endif // CONFIG_NETWORK_LAYER_BLE using namespace chip::Crypto; using namespace chip::Encoding; using namespace chip::Inet; From 094aa322f504a6bf3827e13fc5e232537d13e15b Mon Sep 17 00:00:00 2001 From: Rob Walker Date: Wed, 14 Oct 2020 12:56:50 -0700 Subject: [PATCH 24/40] Cleanup cirque_tests.sh (#3206) * Cleanup cirque_tests.sh * really remove sudo --- scripts/tests/cirque_tests.sh | 65 ++++++++++++++--------------------- 1 file changed, 26 insertions(+), 39 deletions(-) diff --git a/scripts/tests/cirque_tests.sh b/scripts/tests/cirque_tests.sh index 043c47c49369be..2b5bbe03fcf27f 100755 --- a/scripts/tests/cirque_tests.sh +++ b/scripts/tests/cirque_tests.sh @@ -16,10 +16,10 @@ # limitations under the License. # -SOURCE="${BASH_SOURCE[0]}" -SOURCE_DIR="$(cd "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)" -REPO_DIR="$SOURCE_DIR/../../" -TEST_DIR="$REPO_DIR"/src/test_driver/linux-cirque +SOURCE=${BASH_SOURCE[0]} +SOURCE_DIR=$(cd "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd) +REPO_DIR=$SOURCE_DIR/../../ +TEST_DIR=$REPO_DIR/src/test_driver/linux-cirque LOG_DIR=${LOG_DIR:-$(mktemp -d)} @@ -33,43 +33,35 @@ BOLD_YELLOW_TEXT="\033[1;33m" BOLD_RED_TEXT="\033[1;31m" RESET_COLOR="\033[0m" -function __flask_clean() { - flask_pid=$(ps aux | grep "[f]lask run" | grep -v "sudo" | awk '{print $2}' | sort -k2 -rn) - if [ ! -z "$flask_pid" ]; then - for pid in "$flask_pid"; do +function __kill_grep() { + ps aux | grep "$1" | awk '{print $2}' | sort -k2 -rn | + while read -r pid; do kill -2 "$pid" done - fi +} + +function __flask_clean() { + __kill_grep 'flask run' } function __socat_clean() { - socat_pid=$(ps aux | grep "[s]ocat" | awk '{print $2}') - if [ ! -z "$socat_pid" ]; then - for pid in "$socat_pid"; do - kill -2 "$pid" - done - fi + __kill_grep 'socat' } function __virtual_thread_clean() { - vthread_pid=$(ps aux | grep "[o]t-ncp-ftd" | awk '{print $2}') - if [ ! -z "$vthread_pid" ]; then - for pid in "$vthread_pid"; do - kill -2 "$pid" - done - fi + __kill_grep 'ot-ncp-ftd' } function __cirquetest_start_flask() { - echo "Start Flask" + echo 'Start Flask' cd "$REPO_DIR"/third_party/cirque/repo - sudo FLASK_APP='cirque/restservice/service.py' \ + FLASK_APP='cirque/restservice/service.py' \ PATH="$PATH":"$REPO_DIR"/third_party/cirque/repo/openthread/output/x86_64-unknown-linux-gnu/bin/ \ python3 -m flask run >"$LOG_DIR/$CURRENT_TEST/flask.log" 2>&1 } function __cirquetest_clean_flask() { - echo "Cleanup Flask" + echo 'Cleanup Flask' __flask_clean __socat_clean __virtual_thread_clean @@ -92,7 +84,7 @@ function cirquetest_bootstrap() { function cirquetest_run_test() { # Start Cirque flash server export CURRENT_TEST="$1" - export DEVICE_LOG_DIR="$LOG_DIR/$CURRENT_TEST/device_logs" + export DEVICE_LOG_DIR="$LOG_DIR/$CURRENT_TEST"/device_logs mkdir -p "$DEVICE_LOG_DIR" __cirquetest_start_flask & sleep 5 @@ -105,11 +97,9 @@ function cirquetest_run_test() { # After test finished, the container is perserved and networks will not be deleted # This is useful when running tests on local workstation, but not for CI. - if [ "x$CLEANUP_DOCKER_FOR_CI" = "x1" ]; then + if [[ "x$CLEANUP_DOCKER_FOR_CI" = "x1" ]]; then echo "Do docker container and network prune" - # TODO: Filter cirque containers - cat /proc/1/cgroup >&2 - cat /proc/1/mountinfo >&2 + # TODO: Filter cirque containers ? if ! grep docker.sock /proc/1/mountinfo; then docker ps -aq | xargs docker stop >/dev/null 2>&1 fi @@ -123,22 +113,19 @@ function cirquetest_run_all_tests() { # shellharden requires quotes around variables, which will break for-each loops # This is the workaround echo "Logs will be stored at $LOG_DIR" - test_pass="1" + test_pass=1 mkdir -p "$LOG_DIR" - for i in "${!CIRQUE_TESTS[@]}"; do - test_name="${CIRQUE_TESTS[$i]}" + for test_name in "${CIRQUE_TESTS[@]}"; do echo "[ RUN] $test_name" - cirquetest_run_test "$test_name" >"$LOG_DIR/$test_name.log" 2>&1 - exitcode=$? - if [ "$exitcode" = 0 ]; then + if cirquetest_run_test "$test_name" >"$LOG_DIR/$test_name.log" 2>&1; then echo -e "[$BOLD_GREEN_TEXT""PASS""$RESET_COLOR] $test_name" else echo -e "[$BOLD_RED_TEXT""FAIL""$RESET_COLOR] $test_name (Exitcode: $exitcode)" - test_pass="0" + test_pass=0 fi done - if [ "$test_pass" -eq "1" ]; then + if ((test_pass)); then echo -e "[$BOLD_GREEN_TEXT""PASS""$RESET_COLOR] Test finished, test log can be found at artifacts" return 0 else @@ -147,14 +134,14 @@ function cirquetest_run_all_tests() { fi } -subcommand="$1" +subcommand=$1 shift case $subcommand in *) cirquetest_"$subcommand" "$@" exitcode=$? - if [ "$exitcode" = 127 ]; then + if ((exitcode == 127)); then echo "Unknown command: $subcommand" >&2 fi exit "$exitcode" From 00c01607a832b4179d66bc9fe84fe496202c2a49 Mon Sep 17 00:00:00 2001 From: Rob Walker Date: Wed, 14 Oct 2020 18:55:02 -0700 Subject: [PATCH 25/40] MacOS to macOS (#3259) --- docs/BUILDING.md | 2 +- docs/README.md | 2 +- docs/VSCODE_DEVELOPMENT.md | 2 +- src/README.md | 2 +- src/inet/RawEndPoint.cpp | 2 +- src/inet/TCPEndPoint.cpp | 6 +++--- src/inet/UDPEndPoint.cpp | 2 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 6634efca268ea1..b747640005f93e 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -47,7 +47,7 @@ sudo apt-get install git gcc g++ python pkg-config libssl-dev libdbus-1-dev libg #### How to install prerequisites on macOS -On MacOS, first install Xcode from the Mac App Store. The remaining dependencies +On macOS, first install Xcode from the Mac App Store. The remaining dependencies can be installed and satisfied using [Brew](https://brew.sh/): ``` diff --git a/docs/README.md b/docs/README.md index 531df56015dd5f..922369481ab7bf 100644 --- a/docs/README.md +++ b/docs/README.md @@ -28,5 +28,5 @@ Some tools and utilities are dependent on third party tools, such as Docker. environments that don't pollute the host OS. It is also much easier to maintain stability across multiple host environments. Install stable version of [Docker Desktop](https://www.docker.com/products/docker-desktop) relevant to -your native OS (MacOS or Windows). Once installed, you can run docker commands +your native OS (macOS or Windows). Once installed, you can run docker commands from the shell/terminal. diff --git a/docs/VSCODE_DEVELOPMENT.md b/docs/VSCODE_DEVELOPMENT.md index df523993fbaacf..305373058d9272 100644 --- a/docs/VSCODE_DEVELOPMENT.md +++ b/docs/VSCODE_DEVELOPMENT.md @@ -9,7 +9,7 @@ workflow [here](https://code.visualstudio.com/docs/remote/containers). Tested on: -- MacOS 10.5 +- macOS 10.5 - Windows 10 Pro + WSL + Ubuntu 18 LTS ## Setup Steps diff --git a/src/README.md b/src/README.md index a2cad09165887b..ff9157b798b2f9 100644 --- a/src/README.md +++ b/src/README.md @@ -10,7 +10,7 @@ The CHIP src directory is structured as follows: | ble | BLE Layer -- Bluetooth Transport Protocol (BTP) | | controller | Controller API | | crypto | Cryptography libraries | -| darwin | Darwin Framework (iOS and MacOS) | +| darwin | Darwin Framework (iOS and macOS) | | include | Public headers | | inet | Network Layer -- TCP and UDP endpoints | | lib | Core and Support libraries | diff --git a/src/inet/RawEndPoint.cpp b/src/inet/RawEndPoint.cpp index 73ffb76ee11aa3..dad825334f6da6 100644 --- a/src/inet/RawEndPoint.cpp +++ b/src/inet/RawEndPoint.cpp @@ -61,7 +61,7 @@ #endif // HAVE_NETINET_ICMP6_H #endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS -// SOCK_CLOEXEC not defined on all platforms, e.g. iOS/MacOS: +// SOCK_CLOEXEC not defined on all platforms, e.g. iOS/macOS: #ifdef SOCK_CLOEXEC #define SOCK_FLAGS SOCK_CLOEXEC #else diff --git a/src/inet/TCPEndPoint.cpp b/src/inet/TCPEndPoint.cpp index 126825f31cc63f..0e68692367c394 100644 --- a/src/inet/TCPEndPoint.cpp +++ b/src/inet/TCPEndPoint.cpp @@ -63,7 +63,7 @@ #include #include -// SOCK_CLOEXEC not defined on all platforms, e.g. iOS/MacOS: +// SOCK_CLOEXEC not defined on all platforms, e.g. iOS/macOS: #ifdef SOCK_CLOEXEC #define SOCK_FLAGS SOCK_CLOEXEC #else @@ -74,7 +74,7 @@ // socket option level for Linux and BSD systems. #define TCP_SOCKOPT_LEVEL SOL_TCP #else -// socket option level for MacOS & iOS systems. +// socket option level for macOS & iOS systems. #define TCP_SOCKOPT_LEVEL IPPROTO_TCP #endif @@ -82,7 +82,7 @@ // socket option for Linux and BSD systems. #define TCP_IDLE_INTERVAL_OPT_NAME TCP_KEEPIDLE #else -// socket option for MacOS & iOS systems. +// socket option for macOS & iOS systems. #define TCP_IDLE_INTERVAL_OPT_NAME TCP_KEEPALIVE #endif diff --git a/src/inet/UDPEndPoint.cpp b/src/inet/UDPEndPoint.cpp index 6984af169d9fec..b75d49bdc4b637 100644 --- a/src/inet/UDPEndPoint.cpp +++ b/src/inet/UDPEndPoint.cpp @@ -65,7 +65,7 @@ #include -// SOCK_CLOEXEC not defined on all platforms, e.g. iOS/MacOS: +// SOCK_CLOEXEC not defined on all platforms, e.g. iOS/macOS: #ifdef SOCK_CLOEXEC #define SOCK_FLAGS SOCK_CLOEXEC #else From 40f26bfbb826de1d92aa8ed7b60900b22db48dab Mon Sep 17 00:00:00 2001 From: yunhanw-google Date: Thu, 15 Oct 2020 14:49:45 -0700 Subject: [PATCH 26/40] Fix missing glib package for cirque presubmit (#3274) Problem Cirque uses ot-br-posix as generic docker node basefile, recent upstream otbr make dockerfile refactor, which seems to make glib package missing. Summary of changes: -- Add missing glib pckage to unblock the presubmit. --- examples/chip-tool/Dockerfile | 2 +- examples/lighting-app/linux/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/chip-tool/Dockerfile b/examples/chip-tool/Dockerfile index 5a15b50dad77e4..96a3f15552d221 100644 --- a/examples/chip-tool/Dockerfile +++ b/examples/chip-tool/Dockerfile @@ -16,7 +16,7 @@ # from generic_node_image - +RUN apt-get install -y libglib2.0 COPY out/debug/chip-tool /usr/bin/ COPY entrypoint.sh / diff --git a/examples/lighting-app/linux/Dockerfile b/examples/lighting-app/linux/Dockerfile index 710ff88f1669a3..c2e3a20d5612e8 100644 --- a/examples/lighting-app/linux/Dockerfile +++ b/examples/lighting-app/linux/Dockerfile @@ -16,7 +16,7 @@ # from generic_node_image - +RUN apt-get install -y libglib2.0 COPY out/debug/chip-tool-server /usr/bin/ COPY entrypoint.sh / From e31b2c585e4d3d25166487538febc77bcabb6f53 Mon Sep 17 00:00:00 2001 From: Kamil Kasperczyk <66371704+kkasperczyk-no@users.noreply.github.com> Date: Fri, 16 Oct 2020 03:24:14 +0200 Subject: [PATCH 27/40] [nrfconnect] Fixed building issues that appeared after last NCS update. (#3244) There are few building issues in the nrfconnect samples, which appeared after last NCS upmerge: * No such file or directory when including "nrf_cc3xx_platform_mutex.h". * 'isascii' was not declared in this scope in CHIPArgParses.cpp file. * 'strcasecmp' was not declared in this scope in CHIPArgeParses.cpp file. * Invalid conversion from 'const device*' to 'device*' in LightingManagerImpl.cpp file, when calling device_get_binding() method. * Temporarly added include path to the missing file in the nrfconnect-app.cmake file, what will be removed after fixing and merging PR with fix in the nrfxlib. * Removed deprecated isascii method, as isgraph check is enough for this use case. * Added -std=gnu++11 option to the compiler flags, as strcasecmp is not present in c++11 sources. * Performed const_cast to fit into the new device_get_binding() method API. --- config/nrfconnect/chip-lib.cmake | 3 ++- config/nrfconnect/nrfconnect-app.cmake | 3 +++ examples/lighting-app/nrfconnect/main/LightingManager.cpp | 2 +- src/lib/support/CHIPArgParser.cpp | 2 +- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/config/nrfconnect/chip-lib.cmake b/config/nrfconnect/chip-lib.cmake index 81d5421517dc4b..7445fdce073cbd 100644 --- a/config/nrfconnect/chip-lib.cmake +++ b/config/nrfconnect/chip-lib.cmake @@ -81,7 +81,8 @@ function(chip_configure TARGET_NAME) convert_list_of_flags_to_string_of_flags(CHIP_CFLAGS CHIP_CFLAGS) zephyr_get_compile_flags(CHIP_CXXFLAGS CXX) - list(FILTER CHIP_CXXFLAGS EXCLUDE REGEX -std.*) # CHIP adds gnu++11 anyway... + list(FILTER CHIP_CXXFLAGS EXCLUDE REGEX -std.*) + list(APPEND CHIP_CXXFLAGS "-std=gnu++11") convert_list_of_flags_to_string_of_flags(CHIP_CXXFLAGS CHIP_CXXFLAGS) set(GN_ARGS "") diff --git a/config/nrfconnect/nrfconnect-app.cmake b/config/nrfconnect/nrfconnect-app.cmake index 097eb7aa566e01..36742f4ad275a3 100644 --- a/config/nrfconnect/nrfconnect-app.cmake +++ b/config/nrfconnect/nrfconnect-app.cmake @@ -53,6 +53,9 @@ endif() # ================================================== find_package(Zephyr HINTS $ENV{ZEPHYR_BASE}) +# This is temporary solution and should be removed after merging including fix in Zephyr +zephyr_include_directories("${ZEPHYR_BASE}/../nrfxlib/crypto/nrf_cc310_platform/include") + # ================================================== # General settings # ================================================== diff --git a/examples/lighting-app/nrfconnect/main/LightingManager.cpp b/examples/lighting-app/nrfconnect/main/LightingManager.cpp index a1903349ac99ca..3247ae2311ef31 100644 --- a/examples/lighting-app/nrfconnect/main/LightingManager.cpp +++ b/examples/lighting-app/nrfconnect/main/LightingManager.cpp @@ -34,7 +34,7 @@ int LightingManager::Init(const char * gpioDeviceName, gpio_pin_t gpioPin) mState = kState_On; mGPIOPin = gpioPin; - mGPIODevice = device_get_binding(gpioDeviceName); + mGPIODevice = const_cast(device_get_binding(gpioDeviceName)); if (!mGPIODevice) { diff --git a/src/lib/support/CHIPArgParser.cpp b/src/lib/support/CHIPArgParser.cpp index 8fd3e04d5ff879..a64e8b551f740c 100644 --- a/src/lib/support/CHIPArgParser.cpp +++ b/src/lib/support/CHIPArgParser.cpp @@ -83,7 +83,7 @@ static bool HelpTextContainsShortOption(char optChar, const char * helpText); static inline bool IsShortOptionChar(int ch) { - return isascii(ch) && isgraph(ch); + return isgraph(ch); } /** From 61215e59a01535452076de53fd69fe5299ac86bb Mon Sep 17 00:00:00 2001 From: Kevin Schoedel <67607049+kpschoedel@users.noreply.github.com> Date: Thu, 15 Oct 2020 21:26:16 -0400 Subject: [PATCH 28/40] Clean up ex-malloc() use of CHIPMem.h (#3222) * Clean up ex-malloc() use of CHIPMem.h #### Problem As part of heap memory management, a recent change (#3143) replaced malloc()-family calls one-for-one with their "CHIPMem.h" equivalents, but a one-to-one replacement is not always ideal. #### Summary of Changes - Use ScopedMemoryBuffer instead where possible. - Added ScopedMemoryString, since this is a common case. - Some addition safety checks. * Split off safety changes. * Simplified string operations. * Move strlen to callers * Review --- src/controller/CHIPDeviceController.cpp | 1 + src/inet/tests/TestInetCommonOptions.cpp | 7 ++- src/lib/core/tests/TestCHIPTLV.cpp | 16 +++-- src/lib/support/BUILD.gn | 1 - src/lib/support/CHIPArgParser.cpp | 11 ++-- src/lib/support/CHIPMemString.cpp | 48 --------------- src/lib/support/CHIPMemString.h | 66 ++++++++++++++++++--- src/lib/support/tests/TestCHIPArgParser.cpp | 10 ++-- src/platform/ESP32/ESP32Config.cpp | 14 ++--- 9 files changed, 83 insertions(+), 91 deletions(-) delete mode 100644 src/lib/support/CHIPMemString.cpp diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index f40f770bb72a9c..4fc4b785e5eb9c 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include diff --git a/src/inet/tests/TestInetCommonOptions.cpp b/src/inet/tests/TestInetCommonOptions.cpp index 97b7b36cf04b17..a0c96dc7f32490 100644 --- a/src/inet/tests/TestInetCommonOptions.cpp +++ b/src/inet/tests/TestInetCommonOptions.cpp @@ -30,6 +30,7 @@ #include "TestInetCommonOptions.h" +#include #include #include #include @@ -258,9 +259,9 @@ bool FaultInjectionOptions::HandleOption(const char * progName, OptionSet * optS { #if CHIP_CONFIG_TEST || CHIP_SYSTEM_CONFIG_TEST || INET_CONFIG_TEST case kToolCommonOpt_FaultInjection: { - char * mutableArg = chip::Platform::MemoryAllocString(arg); - bool parseRes = ParseFaultInjectionStr(mutableArg, faultMgrFnTable, faultMgrFnTableLen); - chip::Platform::MemoryFree(mutableArg); + chip::Platform::ScopedMemoryString mutableArg(arg, strlen(arg)); + assert(mutableArg); + bool parseRes = ParseFaultInjectionStr(mutableArg.Get(), faultMgrFnTable, faultMgrFnTableLen); if (!parseRes) { PrintArgError("%s: Invalid string specified for fault injection option: %s\n", progName, arg); diff --git a/src/lib/core/tests/TestCHIPTLV.cpp b/src/lib/core/tests/TestCHIPTLV.cpp index 2bc50798ea8e24..59b01d25e2c7b8 100644 --- a/src/lib/core/tests/TestCHIPTLV.cpp +++ b/src/lib/core/tests/TestCHIPTLV.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include @@ -212,14 +213,13 @@ void TestString(nlTestSuite * inSuite, TLVReader & reader, uint64_t tag, const c uint32_t expectedLen = strlen(expectedVal); NL_TEST_ASSERT(inSuite, reader.GetLength() == expectedLen); - char * val = static_cast(chip::Platform::MemoryAlloc(expectedLen + 1)); + chip::Platform::ScopedMemoryBuffer valBuffer; + char * val = static_cast(valBuffer.Alloc(expectedLen + 1).Get()); CHIP_ERROR err = reader.GetString(val, expectedLen + 1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, memcmp(val, expectedVal, expectedLen + 1) == 0); - - chip::Platform::MemoryFree(val); } void TestDupString(nlTestSuite * inSuite, TLVReader & reader, uint64_t tag, const char * expectedVal) @@ -230,14 +230,13 @@ void TestDupString(nlTestSuite * inSuite, TLVReader & reader, uint64_t tag, cons uint32_t expectedLen = strlen(expectedVal); NL_TEST_ASSERT(inSuite, reader.GetLength() == expectedLen); - char * val = static_cast(chip::Platform::MemoryAlloc(expectedLen + 1)); + chip::Platform::ScopedMemoryBuffer valBuffer; + char * val = valBuffer.Alloc(expectedLen + 1).Get(); CHIP_ERROR err = reader.DupString(val); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, memcmp(val, expectedVal, expectedLen + 1) == 0); - - chip::Platform::MemoryFree(val); } void TestDupBytes(nlTestSuite * inSuite, TLVReader & reader, uint64_t tag, const uint8_t * expectedVal, uint32_t expectedLen) @@ -247,13 +246,12 @@ void TestDupBytes(nlTestSuite * inSuite, TLVReader & reader, uint64_t tag, const NL_TEST_ASSERT(inSuite, reader.GetLength() == expectedLen); - uint8_t * val = static_cast(chip::Platform::MemoryAlloc(expectedLen)); + chip::Platform::ScopedMemoryBuffer valBuffer; + uint8_t * val = valBuffer.Alloc(expectedLen).Get(); CHIP_ERROR err = reader.DupBytes(val, expectedLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, memcmp(val, expectedVal, expectedLen) == 0); - - chip::Platform::MemoryFree(val); } void TestBufferContents(nlTestSuite * inSuite, PacketBuffer * buf, const uint8_t * expectedVal, uint32_t expectedLen) diff --git a/src/lib/support/BUILD.gn b/src/lib/support/BUILD.gn index f443d8ac773831..ff947d4d7df9f3 100644 --- a/src/lib/support/BUILD.gn +++ b/src/lib/support/BUILD.gn @@ -69,7 +69,6 @@ static_library("support") { "Base64.cpp", "CHIPArgParser.cpp", "CHIPCounter.cpp", - "CHIPMemString.cpp", "CHIPPlatformMemory.cpp", "ErrorStr.cpp", "FibonacciUtils.cpp", diff --git a/src/lib/support/CHIPArgParser.cpp b/src/lib/support/CHIPArgParser.cpp index a64e8b551f740c..ad9a8318718a03 100644 --- a/src/lib/support/CHIPArgParser.cpp +++ b/src/lib/support/CHIPArgParser.cpp @@ -491,29 +491,26 @@ bool ParseArgs(const char * progName, int argc, char * argv[], OptionSet * optSe bool ParseArgsFromString(const char * progName, const char * argStr, OptionSet * optSets[], NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown) { - char * argStrCopy = nullptr; - char ** argv = nullptr; + char ** argv = nullptr; int argc; bool res; - argStrCopy = chip::Platform::MemoryAllocString(argStr); - if (argStrCopy == nullptr) + chip::Platform::ScopedMemoryString argStrCopy(argStr, strlen(argStr)); + if (!argStrCopy) { PrintArgError("%s: Memory allocation failure\n", progName); return false; } - argc = SplitArgs(argStrCopy, argv, const_cast(progName)); + argc = SplitArgs(argStrCopy.Get(), argv, const_cast(progName)); if (argc < 0) { PrintArgError("%s: Memory allocation failure\n", progName); - chip::Platform::MemoryFree(argStrCopy); return false; } res = ParseArgs(progName, argc, argv, optSets, nonOptArgHandler, ignoreUnknown); - chip::Platform::MemoryFree(argStrCopy); chip::Platform::MemoryFree(argv); return res; diff --git a/src/lib/support/CHIPMemString.cpp b/src/lib/support/CHIPMemString.cpp deleted file mode 100644 index 6573aada85ab9c..00000000000000 --- a/src/lib/support/CHIPMemString.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Copyright (c) 2020 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. - */ - -/** - * @file - * This file implements string operations that allocate heap memory. - */ - -#include - -#include -#include - -namespace chip { -namespace Platform { - -char * MemoryAllocString(const char * string, size_t length) -{ - if (length == 0) - { - length = strlen(string); - } - char * copy = static_cast(MemoryAlloc(length + 1)); - if (copy) - { - strncpy(copy, string, length); - copy[length] = 0; - } - return copy; -} - -} // namespace Platform -} // namespace chip diff --git a/src/lib/support/CHIPMemString.h b/src/lib/support/CHIPMemString.h index b41b2d53470b26..d1dad8c91cb948 100644 --- a/src/lib/support/CHIPMemString.h +++ b/src/lib/support/CHIPMemString.h @@ -21,31 +21,79 @@ * This file defines string operations that allocate heap memory. */ -#ifndef CHIP_MEM_STRING_H -#define CHIP_MEM_STRING_H +#pragma once #include +#include + +#include namespace chip { namespace Platform { +/** + * Copies a C-style string. + * + * This differs from `strncpy()` in some important ways: + * - `dest` can be nullptr, in which case no copy is attempted, and the function returns nullptr. + * - A non-nullptr result is always null-terminated. + * + * @param[in] dest Destination string buffer (which must be at least `length`+1 bytes) + * or nullptr. + * + * @param[in] source String to be copied. + * + * @param[in] length Length to be copied. + * + * @retval Same as `dest`. + */ +inline char * CopyString(char * dest, const char * source, size_t length) +{ + if (dest) + { + strncpy(dest, source, length); + dest[length] = 0; + } + return dest; +} + /** * This function copies a C-style string to memory newly allocated by Platform::MemoryAlloc(). * * @param[in] string String to be copied. * - * @param[in] length Length of the string to be copied. If zero, `strlen(string)` - * will be used. Like `strncpy()`, if the `string` is shorter - * then the remaining space up to `length` will be filled with - * null bytes. + * @param[in] length Length to be copied. Like `strncpy()`, if the `string` is shorter + * than `length`, then the remaining space will be filled with null + * bytes. Like `strndup()` but unlike `strncpy()`, the result is always + * null-terminated. * * @retval Pointer to a null-terminated string in case of success. * @retval `nullptr` if memory allocation fails. * */ -extern char * MemoryAllocString(const char * string, size_t length = 0); +inline char * MemoryAllocString(const char * string, size_t length) +{ + return CopyString(static_cast(MemoryAlloc(length + 1)), string, length); +} + +/** + * Represents a C string in a ScopedMemoryBuffer. + */ + +class ScopedMemoryString : public ScopedMemoryBuffer +{ +public: + /** + * Create a ScopedMemoryString. + * + * @param[in] string String to be copied. + * + * @param[in] length Length to be copied. Like `strncpy()`, if the `string` is shorter than + * `length`, then the remaining space will be filled with null bytes. Like + * `strndup()` but unlike `strncpy()`, the result is always null-terminated. + */ + ScopedMemoryString(const char * string, size_t length) { CopyString(Alloc(length + 1).Get(), string, length); } +}; } // namespace Platform } // namespace chip - -#endif // CHIP_MEM_STRING_H diff --git a/src/lib/support/tests/TestCHIPArgParser.cpp b/src/lib/support/tests/TestCHIPArgParser.cpp index c24ed7751df29a..8dd3124e3ac234 100644 --- a/src/lib/support/tests/TestCHIPArgParser.cpp +++ b/src/lib/support/tests/TestCHIPArgParser.cpp @@ -691,11 +691,11 @@ static bool HandleOption(const char * progName, OptionSet * optSet, int id, cons VerifyOrQuit(sCallbackRecordCount < kMaxCallbackRecords, "Out of callback records"); sCallbackRecords[sCallbackRecordCount].Type = CallbackRecord::kHandleOption; - sCallbackRecords[sCallbackRecordCount].ProgName = chip::Platform::MemoryAllocString(progName); + sCallbackRecords[sCallbackRecordCount].ProgName = chip::Platform::MemoryAllocString(progName, strlen(progName)); sCallbackRecords[sCallbackRecordCount].OptSet = optSet; sCallbackRecords[sCallbackRecordCount].Id = id; - sCallbackRecords[sCallbackRecordCount].Name = chip::Platform::MemoryAllocString(name); - sCallbackRecords[sCallbackRecordCount].Arg = (arg != nullptr) ? chip::Platform::MemoryAllocString(arg) : nullptr; + sCallbackRecords[sCallbackRecordCount].Name = chip::Platform::MemoryAllocString(name, strlen(name)); + sCallbackRecords[sCallbackRecordCount].Arg = (arg != nullptr) ? chip::Platform::MemoryAllocString(arg, strlen(arg)) : nullptr; sCallbackRecordCount++; return true; } @@ -716,7 +716,7 @@ static bool HandleNonOptionArgs(const char * progName, int argc, char * argv[]) VerifyOrQuit(sCallbackRecordCount < kMaxCallbackRecords, "Out of callback records"); sCallbackRecords[sCallbackRecordCount].Type = CallbackRecord::kHandleNonOptionArgs; - sCallbackRecords[sCallbackRecordCount].ProgName = chip::Platform::MemoryAllocString(progName); + sCallbackRecords[sCallbackRecordCount].ProgName = chip::Platform::MemoryAllocString(progName, strlen(progName)); sCallbackRecords[sCallbackRecordCount].Argc = argc; sCallbackRecordCount++; @@ -724,7 +724,7 @@ static bool HandleNonOptionArgs(const char * progName, int argc, char * argv[]) { VerifyOrQuit(sCallbackRecordCount < kMaxCallbackRecords, "Out of callback records"); sCallbackRecords[sCallbackRecordCount].Type = CallbackRecord::kNonOptionArg; - sCallbackRecords[sCallbackRecordCount].Arg = chip::Platform::MemoryAllocString(argv[i]); + sCallbackRecords[sCallbackRecordCount].Arg = chip::Platform::MemoryAllocString(argv[i], strlen(argv[i])); sCallbackRecordCount++; } diff --git a/src/platform/ESP32/ESP32Config.cpp b/src/platform/ESP32/ESP32Config.cpp index ecda06f3a33349..1063d56fd9edce 100644 --- a/src/platform/ESP32/ESP32Config.cpp +++ b/src/platform/ESP32/ESP32Config.cpp @@ -365,21 +365,17 @@ CHIP_ERROR ESP32Config::WriteConfigValueStr(Key key, const char * str) CHIP_ERROR ESP32Config::WriteConfigValueStr(Key key, const char * str, size_t strLen) { CHIP_ERROR err; - char * strCopy = NULL; + chip::Platform::ScopedMemoryBuffer strCopy; if (str != NULL) { - strCopy = chip::Platform::MemoryAllocString(str, strLen); - VerifyOrExit(strCopy != NULL, err = CHIP_ERROR_NO_MEMORY); + strCopy.Calloc(strLen + 1); + VerifyOrExit(strCopy, err = CHIP_ERROR_NO_MEMORY); + strncpy(strCopy.Get(), str, strLen); } - - err = ESP32Config::WriteConfigValueStr(key, strCopy); + err = ESP32Config::WriteConfigValueStr(key, strCopy.Get()); exit: - if (strCopy != NULL) - { - chip::Platform::MemoryFree(strCopy); - } return err; } From 5e60371b5aa1fcb8583f5a9a0df43943a98bada6 Mon Sep 17 00:00:00 2001 From: Song Guo Date: Fri, 16 Oct 2020 21:30:42 +0800 Subject: [PATCH 29/40] [Happy] Follow ups of #2688 (#3239) * Follow ups of happy tests * Add redirect option * Capture test output * Add check * Fix document * Restyled by prettier-markdown * Remove unused import Co-authored-by: Restyled.io --- build/chip/happy_test.gni | 1 + scripts/tests/gn_tests.sh | 2 +- scripts/tests/happy_test_wrapper.py | 27 ++++++++++++++--- scripts/tests/happy_tests.sh | 12 -------- src/test_driver/happy/README.md | 46 +++++++++++++++++++++++++++++ 5 files changed, 71 insertions(+), 17 deletions(-) create mode 100644 src/test_driver/happy/README.md diff --git a/build/chip/happy_test.gni b/build/chip/happy_test.gni index bc325d2da9ea8a..dbc5ef03057aa9 100644 --- a/build/chip/happy_test.gni +++ b/build/chip/happy_test.gni @@ -36,6 +36,7 @@ template("happy_test") { # GN will run python under virtual env, which will cause test failed to run args = [ "--ci=True", + "--silent=True", "--test-bin-dir", rebase_path("${_test_output_dir}"), rebase_path("${_test}.py"), diff --git a/scripts/tests/gn_tests.sh b/scripts/tests/gn_tests.sh index 454fbc43d8fde8..964a66cc922290 100755 --- a/scripts/tests/gn_tests.sh +++ b/scripts/tests/gn_tests.sh @@ -31,5 +31,5 @@ set -x ninja -v -C "$CHIP_ROOT/out/$BUILD_TYPE" -k 0 check if [ "x$RUN_HAPPY_TESTS" == "x1" ]; then - unshare --map-root-user -n -m "$CHIP_ROOT/scripts/tests/happy_tests.sh" ninjarun + ninja -v -C "$CHIP_ROOT/out/$BUILD_TYPE" -k 0 happy_tests fi diff --git a/scripts/tests/happy_test_wrapper.py b/scripts/tests/happy_test_wrapper.py index c469e6bbd9399f..36a988e50652dc 100755 --- a/scripts/tests/happy_test_wrapper.py +++ b/scripts/tests/happy_test_wrapper.py @@ -16,9 +16,11 @@ # This is a wrapper for running happy tests. +import argparse import os +import subprocess import sys -import argparse +import tempfile CHIP_PATH = os.path.realpath(os.path.join( os.path.dirname(__file__), "../..")) @@ -33,11 +35,19 @@ help='The path of test binaries') parser.add_argument('--ci', dest='ci', type=bool, nargs='?', default=False, help='Set this if running script under venv but happy is installed globally') +parser.add_argument('--silent', dest='silent', type=bool, nargs='?', default=False, + help='Set this will mute output when the test finished successfully') if __name__ == '__main__': + if os.getuid() != 0: + os.execvpe("unshare", ["unshare", "--map-root-user", + "-n", "-m", "python3"] + sys.argv, test_environ) + print("Failed to run script in new user namespace", file=sys.stderr) + exit(1) + if os.system("mount --make-private /") != 0 or os.system("mount -t tmpfs tmpfs /run") != 0: + print("Failed to setup private mount points", file=sys.stderr) + exit(1) args = parser.parse_args() - print(args, file=sys.stderr) - print(test_environ, file=sys.stderr) # GN will run Python in venv, which will break happy test if args.ci: if test_environ.get("VIRTUAL_ENV", None) != None: @@ -48,4 +58,13 @@ test_environ["TEST_BIN_DIR"] = args.bin_dir test_environ["HAPPY_MAIN_CONFIG_FILE"] = os.path.realpath( os.path.join(CHIP_PATH, "src/test_driver/happy/conf/main_conf.json")) - os.execvpe("python3", ["python3", args.test_script], test_environ) + if args.silent: + fp, fname = tempfile.mkstemp() + run_res = subprocess.run(["python3", args.test_script], + stdout=fp, stderr=fp, env=test_environ) + if run_res.returncode != 0: + with open(fname, 'rb') as test_output: + os.write(sys.stderr.fileno(), test_output.read()) + exit(run_res.returncode) + else: + os.execvpe("python3", ["python3", args.test_script], test_environ) diff --git a/scripts/tests/happy_tests.sh b/scripts/tests/happy_tests.sh index 7fe83586948e6f..41034b538868fe 100755 --- a/scripts/tests/happy_tests.sh +++ b/scripts/tests/happy_tests.sh @@ -57,18 +57,6 @@ function happytest_run() { "$REPO_DIR/scripts/tests/happy_test_wrapper.py" --test-bin-dir "$REPO_DIR/out/$BUILD_TYPE/tests" "$1" } -function happytest_ninjarun() { - # This function is used for run happy tests under GN / Ninja - if [ "$(whoami)" != "root" ]; then - echo "ninjarun should be invoked under root / user namespace" - echo 'Try `unshare --map-root-user -n -m scripts/tests/happy_tests.sh ninjarun`' - return 1 - fi - mount --make-private / - mount -t tmpfs tmpfs /run - ninja -v -C "$REPO_DIR/out/$BUILD_TYPE" -k 0 happy_tests -} - subcommand="$1" shift diff --git a/src/test_driver/happy/README.md b/src/test_driver/happy/README.md new file mode 100644 index 00000000000000..2b784fd4853ac3 --- /dev/null +++ b/src/test_driver/happy/README.md @@ -0,0 +1,46 @@ +## Happy Tests + +> Happy simulates complex network topologies. On a single Linux machine, Happy +> can create multiple nodes with network stacks that are independent from each +> other. Some nodes may be connected to simulated Thread networks, others may +> connect to simulated Wi-Fi, WAN (Internet), or cellular networks. + +**You need to run happy tests on Linux platforms.** + +### Usage + +- We suggest using + [rootless Docker](https://docs.docker.com/engine/security/rootless/) if you + have concerns about `--privileged` option on docker run. In your + project-chip checkout path, run: + + $ docker run --rm --privileged \ + --entrypoint /bin/bash \ + --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" \ + -it --mount type=bind,source=`pwd`,target=`pwd` \ + connectedhomeip/chip-build:0.4.8 + + Mount your checkout to the same path as your local path avoids errors during + bootstrap. + +- Install packages + + $ sudo scripts/tests/happy_tests.sh install_packages + +- Install happy framework + + $ scripts/tests/happy_tests.sh bootstrap + +- Build CHIP + + $ scripts/build/gn_bootstrap.sh + $ scripts/build/gn_gen.sh --args="chip_enable_happy_tests=true" + $ scripts/build/gn_build.sh + +- Run Tests + + $ RUN_HAPPY_TESTS=1 scripts/tests/gn_tests.sh + +- Run a single test + + $ scripts/tests/happy_test_wrapper.py" --test-bin-dir "out/tests" {test script path} From 4b82c2bcb768f1e5e4315beaa1af6f3046a457b2 Mon Sep 17 00:00:00 2001 From: szatmz <39386237+szatmz@users.noreply.github.com> Date: Fri, 16 Oct 2020 12:32:43 -0400 Subject: [PATCH 30/40] Integrate Mobly (#2967) Problem Described as Pillar 1 in https://github.com/project-chip/connectedhomeip/blob/master/docs/api/device_runner.md Solution Mobly (https://github.com/google/mobly) is a host side on-device test orchestration framework. This change integrates Mobly through a ChipDevice controller class and provides an example test that requires an EchoService Pigweed RPC server be present on the DUT. This change adds integrations/mobly with a python module called 'chip_mobly'. It has a mobly-conformant pigweed device implementation. Adds a mobly test to pigweed-app which can be executed in the output directory as follows: ``` python pigweed_mobly_test.py -c pigweed_mobly_config.yml ``` The test will use nrf5_firmware_utils to flash the pigweed-app on an nRF52840 device and run a simple Echo RPC. --- examples/pigweed-app/nrf5/BUILD.gn | 13 ++- .../nrf5/mobly_tests/pigweed_mobly_config.yml | 25 ++++++ .../nrf5/mobly_tests/pigweed_mobly_test.py | 43 +++++++++ .../docker/images/chip-build/Dockerfile | 3 +- integrations/mobly/chip_mobly/__init__.py | 13 +++ .../mobly/chip_mobly/pigweed_device.py | 89 +++++++++++++++++++ integrations/mobly/hello_world_config.yml | 21 +++++ integrations/mobly/hello_world_test.py | 42 +++++++++ integrations/mobly/setup.py | 30 +++++++ scripts/activate.sh | 7 ++ scripts/bootstrap.sh | 7 ++ scripts/build/gn_bootstrap.sh | 4 +- scripts/examples/gn_build_example.sh | 4 +- scripts/examples/gn_efr32_example.sh | 4 +- scripts/flashing/nrf5_firmware_utils.py | 20 +++++ 15 files changed, 314 insertions(+), 11 deletions(-) create mode 100644 examples/pigweed-app/nrf5/mobly_tests/pigweed_mobly_config.yml create mode 100755 examples/pigweed-app/nrf5/mobly_tests/pigweed_mobly_test.py create mode 100644 integrations/mobly/chip_mobly/__init__.py create mode 100644 integrations/mobly/chip_mobly/pigweed_device.py create mode 100644 integrations/mobly/hello_world_config.yml create mode 100755 integrations/mobly/hello_world_test.py create mode 100644 integrations/mobly/setup.py diff --git a/examples/pigweed-app/nrf5/BUILD.gn b/examples/pigweed-app/nrf5/BUILD.gn index 865f66ddf44bde..7d4213e743c13c 100644 --- a/examples/pigweed-app/nrf5/BUILD.gn +++ b/examples/pigweed-app/nrf5/BUILD.gn @@ -57,8 +57,19 @@ nrf5_executable("pigweed_app") { ldflags = [ "-T" + rebase_path(ldscript, root_build_dir) ] } +copy("mobly_tests") { + sources = [ + "mobly_tests/pigweed_mobly_config.yml", + "mobly_tests/pigweed_mobly_test.py", + ] + outputs = [ "$root_out_dir/{{source_file_part}}" ] +} + group("nrf5") { - deps = [ ":pigweed_app" ] + deps = [ + ":mobly_tests", + ":pigweed_app", + ] } group("default") { diff --git a/examples/pigweed-app/nrf5/mobly_tests/pigweed_mobly_config.yml b/examples/pigweed-app/nrf5/mobly_tests/pigweed_mobly_config.yml new file mode 100644 index 00000000000000..7c53d1eeeefa01 --- /dev/null +++ b/examples/pigweed-app/nrf5/mobly_tests/pigweed_mobly_config.yml @@ -0,0 +1,25 @@ +# Copyright (c) 2020 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. + +TestBeds: + # A test bed where pw_rpc will find a CHIP device + - Name: SampleTestBed + Controllers: + PigweedDevice: + - device_tty: /dev/ttyACM0 + baud: 115200 + platform_module: nrf5_firmware_utils + platform_args: + - application: chip-nrf52840-pigweed-example.hex + softdevice: s140_nrf52_7.0.1_softdevice.hex diff --git a/examples/pigweed-app/nrf5/mobly_tests/pigweed_mobly_test.py b/examples/pigweed-app/nrf5/mobly_tests/pigweed_mobly_test.py new file mode 100755 index 00000000000000..d2e182ee89ebfe --- /dev/null +++ b/examples/pigweed-app/nrf5/mobly_tests/pigweed_mobly_test.py @@ -0,0 +1,43 @@ +# Copyright (c) 2020 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. + +from chip_mobly import pigweed_device +from mobly import asserts +from mobly import base_test +from mobly import test_runner + + +class PigweedMoblyTest(base_test.BaseTestClass): + def setup_class(self): + # Registering pigweed_device controller module declares the test's + # dependency on CHIP/Pigweed device hardware. By default, we expect at least one + # object is created from this. + # Flashes the image passed in the configuration yml. + self.ads = self.register_controller(pigweed_device) + self.dut = self.ads[0] + self.dut.platform.flash() + + def test_hello(self): + expected = "hello!" + status, payload = self.dut.rpcs().EchoService.Echo(msg=expected) + asserts.assert_true(status.ok(), "Status is %s" % status) + asserts.assert_equal( + payload.msg, + expected, + 'Returned payload is "%s" expected "%s"' % (payload.msg, expected), + ) + + +if __name__ == "__main__": + test_runner.main() diff --git a/integrations/docker/images/chip-build/Dockerfile b/integrations/docker/images/chip-build/Dockerfile index dbd263cc9a0028..be29eb708e2fec 100644 --- a/integrations/docker/images/chip-build/Dockerfile +++ b/integrations/docker/images/chip-build/Dockerfile @@ -68,7 +68,8 @@ RUN set -x \ && : # last line RUN set -x \ - && pip3 install circleci attrs coloredlogs PyGithub pygit \ + && pip3 install circleci attrs coloredlogs PyGithub pygit future \ + portpicker mobly \ && : # last line # build and install gn diff --git a/integrations/mobly/chip_mobly/__init__.py b/integrations/mobly/chip_mobly/__init__.py new file mode 100644 index 00000000000000..3a2252cb67477c --- /dev/null +++ b/integrations/mobly/chip_mobly/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2020 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. diff --git a/integrations/mobly/chip_mobly/pigweed_device.py b/integrations/mobly/chip_mobly/pigweed_device.py new file mode 100644 index 00000000000000..94cae18c2409b6 --- /dev/null +++ b/integrations/mobly/chip_mobly/pigweed_device.py @@ -0,0 +1,89 @@ +# Copyright (c) 2020 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 os +from pathlib import Path +import serial +import importlib + +from pw_hdlc_lite.rpc import HdlcRpcClient + +# Point the script to the .proto file with our RPC services. +PROTO = Path(os.environ["PW_ROOT"], "pw_rpc/pw_rpc_protos/echo.proto") + +MOBLY_CONTROLLER_CONFIG_NAME = "PigweedDevice" + + +class Error(Exception): + """This is the Exception class defined for all errors.""" + + +class PigweedDevice: + def __init__(self, device_tty, baud, platform_module=None, platform_args=None): + self.pw_rpc_client = HdlcRpcClient(serial.Serial(device_tty, baud), [PROTO]) + self._platform = None + print("Platform args: %s" % platform_args) + print("Platform module: %s" % platform_module) + if platform_module: + m = importlib.import_module(platform_module) + create_platform_method = getattr(m, "create_platform") + self._platform = create_platform_method(platform_args) + + def rpcs(self): + return self.pw_rpc_client.rpcs().pw.rpc + + @property + def platform(self): + return self._platform + + +def create(configs): + """Initializes the CHIP devices based on the testbed configuration. + + Args: + configs: a list of testbed configs. + + Returns: + a list of device objects + """ + objs = [] + for config in configs: + _validate_config(config) + device = PigweedDevice(**config) + objs.append(device) + return objs + + +def destroy(unused_objs): + """Destroys the wearable objects. + + Args: + unused_objs: a list of device objects. + """ + pass + + +def _validate_config(config): + """Verifies that a config dict for a CHIP device is valid. + + Args: + config: A dict that is the configuration for a CHIP device. + + Raises: + chip_device.Error: Config file is not valid. + """ + required_keys = ["device_tty", "baud"] # A placeholder. + for key in required_keys: + if key not in config: + raise Error("Required key %s missing from config %s" % (key, config)) diff --git a/integrations/mobly/hello_world_config.yml b/integrations/mobly/hello_world_config.yml new file mode 100644 index 00000000000000..bd47505fcba5c9 --- /dev/null +++ b/integrations/mobly/hello_world_config.yml @@ -0,0 +1,21 @@ +# Copyright (c) 2020 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. + +TestBeds: + # A test bed where pw_rpc will find a CHIP device + - Name: SampleTestBed + Controllers: + PigweedDevice: + - device_tty: /dev/ttyACM0 + baud: 115200 diff --git a/integrations/mobly/hello_world_test.py b/integrations/mobly/hello_world_test.py new file mode 100755 index 00000000000000..e6e18bcc56bac2 --- /dev/null +++ b/integrations/mobly/hello_world_test.py @@ -0,0 +1,42 @@ +# Copyright (c) 2020 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. + +from chip_mobly import pigweed_device +from mobly import asserts +from mobly import base_test +from mobly import test_runner + + +class HelloWorldTest(base_test.BaseTestClass): + def setup_class(self): + # Registering pigweed_device controller module declares the test's + # dependency on CHIP/Pigweed device hardware. By default, we expect at least one + # object is created from this. + # Assumes correct image is already flashed. + self.ads = self.register_controller(pigweed_device) + self.dut = self.ads[0] + + def test_hello(self): + expected = "hello!" + status, payload = self.dut.rpcs().EchoService.Echo(msg=expected) + asserts.assert_true(status.ok(), "Status is %s" % status) + asserts.assert_equal( + payload.msg, + expected, + 'Returned payload is "%s" expected "%s"' % (payload.msg, expected), + ) + + +if __name__ == "__main__": + test_runner.main() diff --git a/integrations/mobly/setup.py b/integrations/mobly/setup.py new file mode 100644 index 00000000000000..cca4d23af0d0d4 --- /dev/null +++ b/integrations/mobly/setup.py @@ -0,0 +1,30 @@ +# Copyright (c) 2020 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. + +"""chip_mobly""" + +import setuptools + +setuptools.setup( + name='chip_mobly', + version='0.0.1', + author='CHIP Authors', +# author_email='?', + description='Integration of Mobly with CHIP devices', + packages=setuptools.find_packages(), +#TODO - uncomment this once native python building is solved for +# psutil (one of mobly's dependencies which CHIP does +# not actually need) +# install_requires=['mobly'], +) diff --git a/scripts/activate.sh b/scripts/activate.sh index 30c817771ce1f2..9cb80cac6f6545 100644 --- a/scripts/activate.sh +++ b/scripts/activate.sh @@ -25,5 +25,12 @@ export PW_BRANDING_BANNER="$CHIP_ROOT/.chip-banner.txt" export PW_BRANDING_BANNER_COLOR="bold_white" export PW_VIRTUALENV_REQUIREMENTS="$CHIP_ROOT/scripts/requirements.txt" +export PW_VIRTUALENV_SETUP_PY_ROOTS="$CHIP_ROOT/integrations/mobly" + # shellcheck source=/dev/null source "$CHIP_ROOT/third_party/pigweed/repo/activate.sh" + +#TODO - remove this once native python building is solved for +# psutil (one of mobly's dependencies which CHIP does +# not actually need, so --no-deps is OK) +pip install --no-deps portpicker mobly diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index e6f9162689c558..71cace8a0d99c5 100644 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -32,5 +32,12 @@ fi git submodule update --init +export PW_VIRTUALENV_SETUP_PY_ROOTS="$CHIP_ROOT/integrations/mobly" + # shellcheck source=/dev/null source "$CHIP_ROOT/third_party/pigweed/repo/bootstrap.sh" + +#TODO - remove this once native python building is solved for +# psutil (one of mobly's dependencies which CHIP does +# not actually need, so --no-deps is OK) +pip install --no-deps portpicker mobly diff --git a/scripts/build/gn_bootstrap.sh b/scripts/build/gn_bootstrap.sh index 3d5cfa5b6f2842..d2390771b78870 100755 --- a/scripts/build/gn_bootstrap.sh +++ b/scripts/build/gn_bootstrap.sh @@ -23,6 +23,4 @@ set -e # This is used to account bootstrap time in a dedicated workflow step; there's # no need to use this script locally. -CHIP_ROOT="$(dirname "$0")/../.." - -source "$CHIP_ROOT/scripts/activate.sh" +source "$(dirname "$0")/../../scripts/activate.sh" diff --git a/scripts/examples/gn_build_example.sh b/scripts/examples/gn_build_example.sh index 6bad1075ae945e..67073ec31aba87 100755 --- a/scripts/examples/gn_build_example.sh +++ b/scripts/examples/gn_build_example.sh @@ -20,9 +20,7 @@ set -e # Build script for GN examples GitHub workflow. -CHIP_ROOT="$(dirname "$0")/../.." - -source "$CHIP_ROOT/scripts/activate.sh" +source "$(dirname "$0")/../../scripts/activate.sh" GN_ARGS=() diff --git a/scripts/examples/gn_efr32_example.sh b/scripts/examples/gn_efr32_example.sh index 3132d365b78464..184f0350e9a106 100755 --- a/scripts/examples/gn_efr32_example.sh +++ b/scripts/examples/gn_efr32_example.sh @@ -20,9 +20,7 @@ set -e # Build script for GN EFT32 examples GitHub workflow. -CHIP_ROOT="$(dirname "$0")/../.." - -source "$CHIP_ROOT/scripts/activate.sh" +source "$(dirname "$0")/../../scripts/activate.sh" set -x env diff --git a/scripts/flashing/nrf5_firmware_utils.py b/scripts/flashing/nrf5_firmware_utils.py index 4d058afd8a5810..266f5cd7125c9b 100755 --- a/scripts/flashing/nrf5_firmware_utils.py +++ b/scripts/flashing/nrf5_firmware_utils.py @@ -51,6 +51,7 @@ """ import errno +import os import sys import firmware_utils @@ -189,6 +190,25 @@ def actions(self): return self +### Mobly integration +class Nrf5Platform: + def __init__(self, flasher_args): + self.flasher = Flasher(**flasher_args) + + def flash(self): + self.flasher.flash_command([os.getcwd()]) + +def verify_platform_args(platform_args): + required_args = ['application', 'softdevice'] + for r in required_args: + if not r in platform_args: + raise ValueError("Required argument %s missing" % r) + +def create_platform(platform_args): + verify_platform_args(platform_args[0]) + return Nrf5Platform(platform_args[0]) + +### End of Mobly integration if __name__ == '__main__': sys.exit(Flasher().flash_command(sys.argv)) From 7b0ea63b918e25c48bc726ed9a2748d6c822e86b Mon Sep 17 00:00:00 2001 From: Pankaj Garg Date: Fri, 16 Oct 2020 09:54:50 -0700 Subject: [PATCH 31/40] Enable BLE for Darwin platform (#3279) --- src/platform/device.gni | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/platform/device.gni b/src/platform/device.gni index 16cf04561067ff..381575b3c7b797 100644 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -40,7 +40,8 @@ declare_args() { chip_enable_wifi = chip_device_platform == "linux" # Enable ble support. - chip_enable_ble = chip_device_platform == "linux" + chip_enable_ble = + chip_device_platform == "linux" || chip_device_platform == "darwin" } _chip_device_layer = "none" From ea3f3866eb7e4259b9a08a34e552d87071511231 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20Kr=C3=B3lik?= <66667989+Damian-Nordic@users.noreply.github.com> Date: Fri, 16 Oct 2020 18:56:39 +0200 Subject: [PATCH 32/40] [examples] Update session manager after successful rendezvous (#3265) * [examples] Update session manager after successful rendezvous * Declare SessionManager() in header file * Apply suggestion from code review --- .../chip-app-server/RendezvousServer.cpp | 28 +++++++++++++++ examples/common/chip-app-server/Server.cpp | 34 +++++++------------ .../include/RendezvousServer.h | 1 + .../common/chip-app-server/include/Server.h | 3 -- .../chip-app-server/include/SessionManager.h | 24 +++++++++++++ 5 files changed, 66 insertions(+), 24 deletions(-) create mode 100644 examples/common/chip-app-server/include/SessionManager.h diff --git a/examples/common/chip-app-server/RendezvousServer.cpp b/examples/common/chip-app-server/RendezvousServer.cpp index 775d6e8115d901..343a691ee8decc 100644 --- a/examples/common/chip-app-server/RendezvousServer.cpp +++ b/examples/common/chip-app-server/RendezvousServer.cpp @@ -16,6 +16,13 @@ */ #include "RendezvousServer.h" + +#include "SessionManager.h" + +#include +#include +#include + #if CHIP_ENABLE_OPENTHREAD #include #include @@ -115,4 +122,25 @@ void RendezvousServer::OnRendezvousMessageReceived(PacketBuffer * buffer) chip::System::PacketBuffer::Free(buffer); } +void RendezvousServer::OnRendezvousStatusUpdate(Status status, CHIP_ERROR err) +{ + VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(AppServer, "OnRendezvousStatusUpdate: %s", chip::ErrorStr(err))); + + switch (status) + { + case RendezvousSessionDelegate::SecurePairingSuccess: + ChipLogProgress(AppServer, "Device completed SPAKE2+ handshake"); + SessionManager().NewPairing(Optional{}, &mRendezvousSession.GetPairingSession()); + break; + case RendezvousSessionDelegate::NetworkProvisioningSuccess: + ChipLogProgress(AppServer, "Device was assigned network credentials"); + break; + default: + break; + }; + +exit: + return; +} + } // namespace chip diff --git a/examples/common/chip-app-server/Server.cpp b/examples/common/chip-app-server/Server.cpp index 014f39a0cd2513..d348a01323582a 100644 --- a/examples/common/chip-app-server/Server.cpp +++ b/examples/common/chip-app-server/Server.cpp @@ -17,7 +17,9 @@ #include "Server.h" -#include +#include "DataModelHandler.h" +#include "RendezvousServer.h" +#include "SessionManager.h" #include #include @@ -32,9 +34,6 @@ #include #include -#include "DataModelHandler.h" -#include "RendezvousServer.h" - using namespace ::chip; using namespace ::chip::Inet; using namespace ::chip::Transport; @@ -44,19 +43,6 @@ using namespace ::chip::DeviceLayer; #define EXAMPLE_SERVER_NODEID 12344321 #endif // EXAMPLE_SERVER_NODEID -// Transport Callbacks - -DemoSessionManager sessions; - -namespace chip { - -SecureSessionMgrBase & SessionManager() -{ - return sessions; -} - -} // namespace chip - namespace { class ServerCallback : public SecureSessionMgrDelegate @@ -96,12 +82,18 @@ class ServerCallback : public SecureSessionMgrDelegate } }; +DemoSessionManager gSessions; ServerCallback gCallbacks; SecurePairingUsingTestSecret gTestPairing; RendezvousServer gRendezvousServer; } // namespace +SecureSessionMgrBase & chip::SessionManager() +{ + return gSessions; +} + // The function will initialize datamodel handler and then start the server // The server assumes the platform's networking has been setup already void InitServer() @@ -111,8 +103,8 @@ void InitServer() InitDataModelHandler(); - err = sessions.Init(EXAMPLE_SERVER_NODEID, &DeviceLayer::SystemLayer, - UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6)); + err = gSessions.Init(EXAMPLE_SERVER_NODEID, &DeviceLayer::SystemLayer, + UdpListenParameters(&DeviceLayer::InetLayer).SetAddressType(kIPAddressType_IPv6)); SuccessOrExit(err); // This flag is used to bypass BLE in the cirque test @@ -130,10 +122,10 @@ void InitServer() } #endif - err = sessions.NewPairing(peer, &gTestPairing); + err = gSessions.NewPairing(peer, &gTestPairing); SuccessOrExit(err); - sessions.SetDelegate(&gCallbacks); + gSessions.SetDelegate(&gCallbacks); exit: if (err != CHIP_NO_ERROR) diff --git a/examples/common/chip-app-server/include/RendezvousServer.h b/examples/common/chip-app-server/include/RendezvousServer.h index ff943be1c2c308..ce19810a6d6525 100644 --- a/examples/common/chip-app-server/include/RendezvousServer.h +++ b/examples/common/chip-app-server/include/RendezvousServer.h @@ -33,6 +33,7 @@ class RendezvousServer : public RendezvousSessionDelegate void OnRendezvousConnectionClosed() override; void OnRendezvousError(CHIP_ERROR err) override; void OnRendezvousMessageReceived(System::PacketBuffer * buffer) override; + void OnRendezvousStatusUpdate(Status status, CHIP_ERROR err) override; private: RendezvousSession mRendezvousSession; diff --git a/examples/common/chip-app-server/include/Server.h b/examples/common/chip-app-server/include/Server.h index 1034a69ade8113..b4be5aba1f53ac 100644 --- a/examples/common/chip-app-server/include/Server.h +++ b/examples/common/chip-app-server/include/Server.h @@ -17,9 +17,6 @@ #pragma once -#include -#include -#include #include #include diff --git a/examples/common/chip-app-server/include/SessionManager.h b/examples/common/chip-app-server/include/SessionManager.h new file mode 100644 index 00000000000000..ebfc2d8c78f9f5 --- /dev/null +++ b/examples/common/chip-app-server/include/SessionManager.h @@ -0,0 +1,24 @@ +/* + * + * Copyright (c) 2020 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. + */ + +#pragma once + +#include + +namespace chip { +SecureSessionMgrBase & SessionManager(); +} // namespace chip From 17924c78ea155023233647a2f653ae3ae7f4feb1 Mon Sep 17 00:00:00 2001 From: Rob Walker Date: Fri, 16 Oct 2020 09:59:41 -0700 Subject: [PATCH 33/40] Optionally suppress submodules and activate in Xcode builds (#3264) --- src/darwin/Framework/chip_xcode_build_connector.sh | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/darwin/Framework/chip_xcode_build_connector.sh b/src/darwin/Framework/chip_xcode_build_connector.sh index 8eeef3e2ec821d..d33e6382d49b88 100755 --- a/src/darwin/Framework/chip_xcode_build_connector.sh +++ b/src/darwin/Framework/chip_xcode_build_connector.sh @@ -102,12 +102,14 @@ fi ( cd "$CHIP_ROOT" # pushd and popd because we need the env vars from activate - git submodule update --init - set +ex - echo PW_ENVSETUP_QUIET=1 . scripts/activate.sh >&2 - PW_ENVSETUP_QUIET=1 . scripts/activate.sh - (($? != 0)) && echo "Please source $CHIP_ROOT/scripts/bootstrap.sh before building" && exit 1 - set -ex + [[ -n $CHIP_NO_SUBMODULES ]] || git submodule update --init + if [[ -z $CHIP_NO_ACTIVATE ]]; then + set +ex + echo PW_ENVSETUP_QUIET=1 . scripts/activate.sh >&2 + PW_ENVSETUP_QUIET=1 . scripts/activate.sh + (($? != 0)) && echo "Please source $CHIP_ROOT/scripts/bootstrap.sh before building" && exit 1 + set -ex + fi cd "$TEMP_DIR" # [[ -f out/build.ninja ]] ? From d519da6695f362962cfc96706f4db83886eebbe0 Mon Sep 17 00:00:00 2001 From: Pankaj Garg Date: Fri, 16 Oct 2020 13:36:50 -0700 Subject: [PATCH 34/40] Fix Darwin build failure in TestCHIPoBLEStackMgr.cpp (#3282) --- src/platform/Darwin/BLEManagerImpl.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/platform/Darwin/BLEManagerImpl.h b/src/platform/Darwin/BLEManagerImpl.h index 5e4e7e86b6cf50..4cc7171c6ba849 100644 --- a/src/platform/Darwin/BLEManagerImpl.h +++ b/src/platform/Darwin/BLEManagerImpl.h @@ -40,6 +40,9 @@ class BLEManagerImpl final : public BLEManager, private BleLayer // the implementation methods provided by this class. friend BLEManager; +public: + CHIP_ERROR ConfigureBle(uint32_t aNodeId, bool aIsCentral) { return CHIP_NO_ERROR; } + private: // ===== Members that implement the BLEManager internal interface. From f7c23fc2424a2a505624786211ffd52d23867bdb Mon Sep 17 00:00:00 2001 From: Kevin Schoedel <67607049+kpschoedel@users.noreply.github.com> Date: Fri, 16 Oct 2020 18:08:47 -0400 Subject: [PATCH 35/40] Convert operator new and delete to use CHIPMem.h (#3260) * Convert operator new and delete to use CHIPMem.h #### Problem Embedded device-side code should only use heap through CHIPMem.h. In particular it should not use the C++ new and delete operators for heap allocation without explicit placement using Platform::MemoryAlloc(). #### Summary of Changes - Added Platform::New<>() and Delete<>(). - Convert uses of operator new and delete. Fixes #3232 Remove explicit use of `new` from first-party embedded-device code * chip-tool was missing MemoryInit --- .../chip-tool/commands/common/Commands.cpp | 30 +++++---- .../common/screen-framework/ScreenManager.cpp | 4 +- .../screen-framework/include/ListScreen.h | 4 +- .../esp32/main/RendezvousDeviceDelegate.cpp | 3 +- .../wifi-echo/server/esp32/main/wifi-echo.cpp | 66 ++++++++++--------- src/controller/CHIPDeviceController.cpp | 33 +++++----- src/inet/tests/TapAddrAutoconf.h | 1 - src/inet/tests/TestInetCommon.cpp | 1 - src/lib/core/ReferenceCounted.h | 4 +- src/lib/core/tests/TestCHIPCallback.cpp | 29 ++++++-- src/lib/message/CHIPFabricState.cpp | 18 +---- src/lib/support/CHIPMem.h | 32 +++++++++ .../support/tests/TestPersistedCounter.cpp | 1 - .../ESP32/bluedroid/BLEManagerImpl.cpp | 2 - src/platform/ESP32/nimble/BLEManagerImpl.cpp | 2 - .../nrfconnect/ConnectivityManagerImpl.cpp | 2 - .../QRCodeSetupPayloadParser.cpp | 17 +++-- src/setup_payload/tests/TestQRCodeTLV.cpp | 24 ++++++- src/system/SystemLayer.cpp | 9 +-- src/transport/RendezvousSession.cpp | 3 +- 20 files changed, 180 insertions(+), 105 deletions(-) diff --git a/examples/chip-tool/commands/common/Commands.cpp b/examples/chip-tool/commands/common/Commands.cpp index 0eab0309edbbac..8ff7797d00dca1 100644 --- a/examples/chip-tool/commands/common/Commands.cpp +++ b/examples/chip-tool/commands/common/Commands.cpp @@ -36,21 +36,29 @@ int Commands::Run(NodeId localId, NodeId remoteId, int argc, char ** argv) { ConfigureChipLogging(); - CHIP_ERROR err = CHIP_NO_ERROR; - ChipDeviceController dc; + CHIP_ERROR err = chip::Platform::MemoryInit(); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "Init Memory failure: %s", chip::ErrorStr(err)); + } + else + { - err = dc.Init(localId); - VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure: %s", chip::ErrorStr(err))); + ChipDeviceController dc; - err = dc.ServiceEvents(); - VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init Run Loop failure: %s", chip::ErrorStr(err))); + err = dc.Init(localId); + VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure: %s", chip::ErrorStr(err))); - err = RunCommand(dc, remoteId, argc, argv); - SuccessOrExit(err); + err = dc.ServiceEvents(); + VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init Run Loop failure: %s", chip::ErrorStr(err))); -exit: - dc.ServiceEventSignal(); - dc.Shutdown(); + err = RunCommand(dc, remoteId, argc, argv); + SuccessOrExit(err); + + exit: + dc.ServiceEventSignal(); + dc.Shutdown(); + } return (err == CHIP_NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/examples/common/screen-framework/ScreenManager.cpp b/examples/common/screen-framework/ScreenManager.cpp index bc63766b10aa28..2100c3d7865d35 100644 --- a/examples/common/screen-framework/ScreenManager.cpp +++ b/examples/common/screen-framework/ScreenManager.cpp @@ -27,6 +27,8 @@ #if CONFIG_HAVE_DISPLAY +#include + #include #include @@ -260,7 +262,7 @@ void ScreenManager::PopScreen() Screen * screen = screens.back(); screens.pop_back(); // screen is popped immediately before last exit screen->Exit(true); // screen is not top when exit/popped - delete screen; + chip::Platform::Delete(screen); focusBack = false; diff --git a/examples/common/screen-framework/include/ListScreen.h b/examples/common/screen-framework/include/ListScreen.h index 49e46cab98491d..2dd35d53d8b483 100644 --- a/examples/common/screen-framework/include/ListScreen.h +++ b/examples/common/screen-framework/include/ListScreen.h @@ -30,6 +30,8 @@ #if CONFIG_HAVE_DISPLAY +#include + #include #include #include @@ -56,7 +58,7 @@ class ListScreen : public Screen public: ListScreen(Model * model) : model(model) {} - virtual ~ListScreen() { delete model; } + virtual ~ListScreen() { chip::Platform::Delete(model); } virtual std::string GetTitle() { return model->GetTitle(); } diff --git a/examples/wifi-echo/server/esp32/main/RendezvousDeviceDelegate.cpp b/examples/wifi-echo/server/esp32/main/RendezvousDeviceDelegate.cpp index 7a3ae7aba18f4d..a0b9444b748183 100644 --- a/examples/wifi-echo/server/esp32/main/RendezvousDeviceDelegate.cpp +++ b/examples/wifi-echo/server/esp32/main/RendezvousDeviceDelegate.cpp @@ -21,6 +21,7 @@ #include "RendezvousMessageHandler.h" #include "esp_log.h" #include +#include #include #include #include @@ -46,7 +47,7 @@ RendezvousDeviceDelegate::RendezvousDeviceDelegate() params.SetSetupPINCode(setupPINCode).SetLocalNodeId(kLocalNodeId).SetBleLayer(DeviceLayer::ConnectivityMgr().GetBleLayer()); - mRendezvousSession = new RendezvousSession(this, &mDeviceNetworkProvisioningDelegate); + mRendezvousSession = chip::Platform::New(this, &mDeviceNetworkProvisioningDelegate); err = mRendezvousSession->Init(params); exit: diff --git a/examples/wifi-echo/server/esp32/main/wifi-echo.cpp b/examples/wifi-echo/server/esp32/main/wifi-echo.cpp index 5ffa8e21af7639..ebe95facb1ed3d 100644 --- a/examples/wifi-echo/server/esp32/main/wifi-echo.cpp +++ b/examples/wifi-echo/server/esp32/main/wifi-echo.cpp @@ -45,6 +45,7 @@ #include #include #include +#include #include #include @@ -203,7 +204,7 @@ class AttributeListModel : public ListScreen::Model virtual void ItemAction(int i) { ESP_LOGI(TAG, "Opening attribute %d", i); - ScreenManager::PushScreen(new ListScreen(new EditAttributeListModel(d, e, c, i))); + ScreenManager::PushScreen(chip::Platform::New(chip::Platform::New(d, e, c, i))); } }; @@ -220,7 +221,7 @@ class ClusterListModel : public ListScreen::Model virtual void ItemAction(int i) { ESP_LOGI(TAG, "Opening cluster %d", i); - ScreenManager::PushScreen(new ListScreen(new AttributeListModel(d, e, i))); + ScreenManager::PushScreen(chip::Platform::New(chip::Platform::New(d, e, i))); } }; @@ -236,7 +237,7 @@ class EndpointListModel : public ListScreen::Model virtual void ItemAction(int i) { ESP_LOGI(TAG, "Opening endpoint %d", i); - ScreenManager::PushScreen(new ListScreen(new ClusterListModel(d, i))); + ScreenManager::PushScreen(chip::Platform::New(chip::Platform::New(d, i))); } }; @@ -249,7 +250,7 @@ class DeviceListModel : public ListScreen::Model virtual void ItemAction(int i) { ESP_LOGI(TAG, "Opening device %d", i); - ScreenManager::PushScreen(new ListScreen(new EndpointListModel(i))); + ScreenManager::PushScreen(chip::Platform::New(chip::Platform::New(i))); } }; @@ -480,7 +481,7 @@ extern "C" void app_main() if (isRendezvousBLE()) { - rendezvousDelegate = new RendezvousDeviceDelegate(); + rendezvousDelegate = chip::Platform::New(); } else if (isRendezvousBypassed()) { @@ -513,33 +514,34 @@ extern "C" void app_main() // Initialize the screen manager and push a rudimentary user interface. ScreenManager::Init(); - ScreenManager::PushScreen(new ListScreen((new SimpleListModel()) - ->Title("CHIP") - ->Action([](int i) { ESP_LOGI(TAG, "action on item %d", i); }) - ->Item("Devices", - []() { - ESP_LOGI(TAG, "Opening device list"); - ScreenManager::PushScreen(new ListScreen(new DeviceListModel())); - }) - ->Item("Custom", - []() { - ESP_LOGI(TAG, "Opening custom screen"); - ScreenManager::PushScreen(new CustomScreen()); - }) - ->Item("QR Code", - [=]() { - ESP_LOGI(TAG, "Opening QR code screen"); - ScreenManager::PushScreen(new QRCodeScreen(qrCodeText)); - }) - ->Item("Setup", - [=]() { - ESP_LOGI(TAG, "Opening Setup list"); - ScreenManager::PushScreen(new ListScreen(new SetupListModel())); - }) - ->Item("More") - ->Item("Items") - ->Item("For") - ->Item("Demo"))); + ScreenManager::PushScreen(chip::Platform::New( + (chip::Platform::New()) + ->Title("CHIP") + ->Action([](int i) { ESP_LOGI(TAG, "action on item %d", i); }) + ->Item("Devices", + []() { + ESP_LOGI(TAG, "Opening device list"); + ScreenManager::PushScreen(chip::Platform::New(chip::Platform::New())); + }) + ->Item("Custom", + []() { + ESP_LOGI(TAG, "Opening custom screen"); + ScreenManager::PushScreen(chip::Platform::New()); + }) + ->Item("QR Code", + [=]() { + ESP_LOGI(TAG, "Opening QR code screen"); + ScreenManager::PushScreen(chip::Platform::New(qrCodeText)); + }) + ->Item("Setup", + [=]() { + ESP_LOGI(TAG, "Opening Setup list"); + ScreenManager::PushScreen(chip::Platform::New(chip::Platform::New())); + }) + ->Item("More") + ->Item("Items") + ->Item("For") + ->Item("Demo"))); // Connect the status LED to VLEDs. { diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 4fc4b785e5eb9c..db59dbf665b26f 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -80,7 +80,7 @@ ChipDeviceController::~ChipDeviceController() { if (mTestSecurePairingSecret != nullptr) { - delete mTestSecurePairingSecret; + chip::Platform::Delete(mTestSecurePairingSecret); } } @@ -144,8 +144,8 @@ CHIP_ERROR ChipDeviceController::Shutdown() #else mSystemLayer->Shutdown(); mInetLayer->Shutdown(); - delete mSystemLayer; - delete mInetLayer; + chip::Platform::Delete(mSystemLayer); + chip::Platform::Delete(mInetLayer); #endif // CONFIG_DEVICE_LAYER mSystemLayer = nullptr; @@ -153,13 +153,13 @@ CHIP_ERROR ChipDeviceController::Shutdown() if (mSessionManager != nullptr) { - delete mSessionManager; + chip::Platform::Delete(mSessionManager); mSessionManager = nullptr; } if (mRendezvousSession != nullptr) { - delete mRendezvousSession; + chip::Platform::Delete(mRendezvousSession); mRendezvousSession = nullptr; } @@ -190,7 +190,7 @@ CHIP_ERROR ChipDeviceController::ConnectDevice(NodeId remoteDeviceId, Rendezvous } #endif // CONFIG_DEVICE_LAYER && CONFIG_NETWORK_LAYER_BLE - mRendezvousSession = new RendezvousSession(this); + mRendezvousSession = chip::Platform::New(this); err = mRendezvousSession->Init(params.SetLocalNodeId(mLocalDeviceId)); SuccessOrExit(err); @@ -209,7 +209,7 @@ CHIP_ERROR ChipDeviceController::ConnectDevice(NodeId remoteDeviceId, Rendezvous exit: if (err != CHIP_NO_ERROR && mRendezvousSession != nullptr) { - delete mRendezvousSession; + chip::Platform::Delete(mRendezvousSession); mRendezvousSession = nullptr; } @@ -223,10 +223,11 @@ CHIP_ERROR ChipDeviceController::ConnectDeviceWithoutSecurePairing(NodeId remote { if (mTestSecurePairingSecret != nullptr) { - delete mTestSecurePairingSecret; + chip::Platform::Delete(mTestSecurePairingSecret); } - mTestSecurePairingSecret = new SecurePairingUsingTestSecret(Optional::Value(remoteDeviceId), 0, 0); + mTestSecurePairingSecret = chip::Platform::New( + Optional::Value(remoteDeviceId), static_cast(0), static_cast(0)); mSecurePairingSession = mTestSecurePairingSecret; @@ -259,7 +260,7 @@ CHIP_ERROR ChipDeviceController::EstablishSecureSession() ExitNow(err = CHIP_ERROR_INCORRECT_STATE); } - mSessionManager = new SecureSessionMgr(); + mSessionManager = chip::Platform::New>(); err = mSessionManager->Init(mLocalDeviceId, mSystemLayer, Transport::UdpListenParameters(mInetLayer).SetAddressType(mDeviceAddr.Type())); @@ -282,7 +283,7 @@ CHIP_ERROR ChipDeviceController::EstablishSecureSession() { if (mSessionManager != nullptr) { - delete mSessionManager; + chip::Platform::Delete(mSessionManager); mSessionManager = nullptr; } mConState = kConnectionState_NotConnected; @@ -299,7 +300,7 @@ CHIP_ERROR ChipDeviceController::ResumeSecureSession() if (mSessionManager != nullptr) { - delete mSessionManager; + chip::Platform::Delete(mSessionManager); mSessionManager = nullptr; } @@ -341,13 +342,13 @@ CHIP_ERROR ChipDeviceController::DisconnectDevice() if (mSessionManager != nullptr) { - delete mSessionManager; + chip::Platform::Delete(mSessionManager); mSessionManager = nullptr; } if (mRendezvousSession != nullptr) { - delete mRendezvousSession; + chip::Platform::Delete(mRendezvousSession); mRendezvousSession = nullptr; } @@ -479,7 +480,7 @@ void ChipDeviceController::OnRendezvousComplete() { if (mRendezvousSession != nullptr) { - delete mRendezvousSession; + chip::Platform::Delete(mRendezvousSession); mRendezvousSession = nullptr; } } @@ -492,7 +493,7 @@ void ChipDeviceController::OnRendezvousMessageReceived(PacketBuffer * buffer) // to clean up the session if (mRendezvousSession != nullptr) { - delete mRendezvousSession; + chip::Platform::Delete(mRendezvousSession); mRendezvousSession = nullptr; } } diff --git a/src/inet/tests/TapAddrAutoconf.h b/src/inet/tests/TapAddrAutoconf.h index 2a51c941324510..8b1d8c9bd75f5f 100644 --- a/src/inet/tests/TapAddrAutoconf.h +++ b/src/inet/tests/TapAddrAutoconf.h @@ -23,7 +23,6 @@ * from the corresponding configuration on the tap interface. */ -#include #include int CollectTapAddresses(std::vector & addresses, const char * ifName); diff --git a/src/inet/tests/TestInetCommon.cpp b/src/inet/tests/TestInetCommon.cpp index 7aa131917383e1..ef1176eff68801 100644 --- a/src/inet/tests/TestInetCommon.cpp +++ b/src/inet/tests/TestInetCommon.cpp @@ -36,7 +36,6 @@ #include "TestInetCommon.h" -#include #include #include diff --git a/src/lib/core/ReferenceCounted.h b/src/lib/core/ReferenceCounted.h index 7527c6a05bb56a..b876ce521d71b6 100644 --- a/src/lib/core/ReferenceCounted.h +++ b/src/lib/core/ReferenceCounted.h @@ -26,6 +26,8 @@ #include #include +#include + namespace chip { /** @@ -62,7 +64,7 @@ class ReferenceCounted if (--mRefCount == 0) { - delete this; + chip::Platform::Delete(this); } } diff --git a/src/lib/core/tests/TestCHIPCallback.cpp b/src/lib/core/tests/TestCHIPCallback.cpp index c95ac5af29abf2..a8c8df63e640cc 100644 --- a/src/lib/core/tests/TestCHIPCallback.cpp +++ b/src/lib/core/tests/TestCHIPCallback.cpp @@ -25,6 +25,7 @@ #include "TestCore.h" #include +#include #include #include @@ -136,7 +137,7 @@ static void ResumerTest(nlTestSuite * inSuite, void * inContext) resumer.Dispatch(); NL_TEST_ASSERT(inSuite, n == 3); - Callback<> * pcb = new Callback<>(reinterpret_cast(increment), &n); + Callback<> * pcb = chip::Platform::New>(reinterpret_cast(increment), &n); n = 1; // cancel on destruct @@ -145,7 +146,7 @@ static void ResumerTest(nlTestSuite * inSuite, void * inContext) NL_TEST_ASSERT(inSuite, n == 2); resumer.Resume(pcb); - delete pcb; + chip::Platform::Delete(pcb); resumer.Dispatch(); NL_TEST_ASSERT(inSuite, n == 2); } @@ -217,6 +218,26 @@ static void NotifierTest(nlTestSuite * inSuite, void * inContext) NL_TEST_ASSERT(inSuite, n == 1); } +/** + * Set up the test suite. + */ +int TestCHIPCallback_Setup(void * inContext) +{ + CHIP_ERROR error = chip::Platform::MemoryInit(); + if (error != CHIP_NO_ERROR) + return FAILURE; + return SUCCESS; +} + +/** + * Tear down the test suite. + */ +int TestCHIPCallback_Teardown(void * inContext) +{ + chip::Platform::MemoryShutdown(); + return SUCCESS; +} + /** * Test Suite. It lists all the test functions. */ @@ -238,8 +259,8 @@ int TestCHIPCallback(void) { "CHIPCallback", &sTests[0], - nullptr, - nullptr + TestCHIPCallback_Setup, + TestCHIPCallback_Teardown }; // clang-format on diff --git a/src/lib/message/CHIPFabricState.cpp b/src/lib/message/CHIPFabricState.cpp index 51a2fbdbf6ee2b..1dab058f163a04 100644 --- a/src/lib/message/CHIPFabricState.cpp +++ b/src/lib/message/CHIPFabricState.cpp @@ -46,24 +46,12 @@ #include #include #include +#include #include #include #include #include -#if HAVE_NEW -#include -#else -inline void * operator new(size_t, void * p) throw() -{ - return p; -} -inline void * operator new[](size_t, void * p) throw() -{ - return p; -} -#endif - using namespace chip::Crypto; using namespace chip::Encoding; using namespace chip::Inet; @@ -220,9 +208,7 @@ ChipFabricState::ChipFabricState() CHIP_ERROR ChipFabricState::Init() { - static nlDEFINE_ALIGNED_VAR(sDummyGroupKeyStore, sizeof(DummyGroupKeyStore), void *); - - return Init(new (&sDummyGroupKeyStore) DummyGroupKeyStore()); + return Init(chip::Platform::New()); } CHIP_ERROR ChipFabricState::Init(GroupKeyStoreBase * groupKeyStore) diff --git a/src/lib/support/CHIPMem.h b/src/lib/support/CHIPMem.h index 2072a8b6b7868b..92ce8f68ba3ca5 100644 --- a/src/lib/support/CHIPMem.h +++ b/src/lib/support/CHIPMem.h @@ -27,6 +27,9 @@ #include #include +#include +#include + namespace chip { namespace Platform { @@ -144,5 +147,34 @@ extern void * MemoryRealloc(void * p, size_t size); */ extern void MemoryFree(void * p); +/** + * This function wraps the operator `new` with placement-new using MemoryAlloc(). + * Instead of + * p = new T(arguments) + * use + * p = New(arguments) + * In a few cases it may be necessary to add explicit casts to arguments, notably + * when passing integer constants to smaller integer parameters. + */ +template +inline T * New(Args &&... args) +{ + return new (MemoryAlloc(sizeof(T))) T(std::forward(args)...); +} + +/** + * This function wraps the operator `delete` with using MemoryFree(). + * Instead of + * delete p + * use + * Delete(p) + */ +template +inline void Delete(T * p) +{ + p->~T(); + MemoryFree(p); +} + } // namespace Platform } // namespace chip diff --git a/src/lib/support/tests/TestPersistedCounter.cpp b/src/lib/support/tests/TestPersistedCounter.cpp index e3d2ad28a4771d..e3dbcbeda7edca 100644 --- a/src/lib/support/tests/TestPersistedCounter.cpp +++ b/src/lib/support/tests/TestPersistedCounter.cpp @@ -27,7 +27,6 @@ #define __STDC_FORMAT_MACROS #endif -#include #include #include #include diff --git a/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp b/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp index ef497382aca2af..e15fa6ccb08d9f 100644 --- a/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp +++ b/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp @@ -43,8 +43,6 @@ #include "esp_gatts_api.h" #include "esp_log.h" -#include - #define MAX_ADV_DATA_LEN 31 #define CHIP_ADV_DATA_TYPE_FLAGS 0x01 #define CHIP_ADV_DATA_FLAGS 0x06 diff --git a/src/platform/ESP32/nimble/BLEManagerImpl.cpp b/src/platform/ESP32/nimble/BLEManagerImpl.cpp index 521333b5e42dcf..21e4a486e717da 100644 --- a/src/platform/ESP32/nimble/BLEManagerImpl.cpp +++ b/src/platform/ESP32/nimble/BLEManagerImpl.cpp @@ -45,8 +45,6 @@ #include "services/gap/ble_svc_gap.h" #include "services/gatt/ble_svc_gatt.h" -#include - #define MAX_ADV_DATA_LEN 31 #define CHIP_ADV_DATA_TYPE_FLAGS 0x01 #define CHIP_ADV_DATA_FLAGS 0x06 diff --git a/src/platform/nrfconnect/ConnectivityManagerImpl.cpp b/src/platform/nrfconnect/ConnectivityManagerImpl.cpp index 10a398eed5778c..b79bffb20e0307 100644 --- a/src/platform/nrfconnect/ConnectivityManagerImpl.cpp +++ b/src/platform/nrfconnect/ConnectivityManagerImpl.cpp @@ -20,8 +20,6 @@ #include #include -#include - #include #include diff --git a/src/setup_payload/QRCodeSetupPayloadParser.cpp b/src/setup_payload/QRCodeSetupPayloadParser.cpp index 789e95771d5822..c098552285e442 100644 --- a/src/setup_payload/QRCodeSetupPayloadParser.cpp +++ b/src/setup_payload/QRCodeSetupPayloadParser.cpp @@ -36,6 +36,7 @@ #include #include #include +#include using namespace chip; using namespace std; @@ -83,14 +84,17 @@ static CHIP_ERROR openTLVContainer(TLVReader & reader, TLVType type, uint64_t ta static CHIP_ERROR retrieveOptionalInfoString(TLVReader & reader, OptionalQRCodeInfo & info) { + CHIP_ERROR err; uint32_t valLength = reader.GetLength(); - unique_ptr value(new char[valLength + 1]); + chip::Platform::ScopedMemoryBuffer value; + value.Alloc(valLength + 1); + VerifyOrExit(value, err = CHIP_ERROR_NO_MEMORY); - CHIP_ERROR err = reader.GetString(value.get(), valLength + 1); + err = reader.GetString(value.Get(), valLength + 1); SuccessOrExit(err); info.type = optionalQRCodeInfoTypeString; - info.data = string(value.get()); + info.data = string(value.Get()); exit: return err; @@ -292,11 +296,12 @@ CHIP_ERROR QRCodeSetupPayloadParser::populateTLV(SetupPayload & outPayload, cons CHIP_ERROR err = CHIP_NO_ERROR; size_t bitsLeftToRead = (buf.size() * 8) - index; size_t tlvBytesLength = ceil(double(bitsLeftToRead) / 8); - unique_ptr tlvArray; + chip::Platform::ScopedMemoryBuffer tlvArray; SuccessOrExit(tlvBytesLength == 0); + tlvArray.Alloc(tlvBytesLength); + VerifyOrExit(tlvArray, err = CHIP_ERROR_NO_MEMORY); - tlvArray = unique_ptr(new uint8_t[tlvBytesLength]); for (size_t i = 0; i < tlvBytesLength; i++) { uint64_t dest; @@ -304,7 +309,7 @@ CHIP_ERROR QRCodeSetupPayloadParser::populateTLV(SetupPayload & outPayload, cons tlvArray[i] = static_cast(dest); } - err = parseTLVFields(outPayload, tlvArray.get(), tlvBytesLength); + err = parseTLVFields(outPayload, tlvArray.Get(), tlvBytesLength); SuccessOrExit(err); exit: diff --git a/src/setup_payload/tests/TestQRCodeTLV.cpp b/src/setup_payload/tests/TestQRCodeTLV.cpp index 37027b3d8c10a4..46e10b74082b1c 100644 --- a/src/setup_payload/tests/TestQRCodeTLV.cpp +++ b/src/setup_payload/tests/TestQRCodeTLV.cpp @@ -280,6 +280,26 @@ struct TestContext nlTestSuite * mSuite; }; +/** + * Set up the test suite. + */ +int TestQRCodeTLV_Setup(void * inContext) +{ + CHIP_ERROR error = chip::Platform::MemoryInit(); + if (error != CHIP_NO_ERROR) + return FAILURE; + return SUCCESS; +} + +/** + * Tear down the test suite. + */ +int TestQRCodeTLV_Teardown(void * inContext) +{ + chip::Platform::MemoryShutdown(); + return SUCCESS; +} + } // namespace /** @@ -292,8 +312,8 @@ int TestQRCodeTLV() { "chip-qrcode-optional-info-tests", &sTests[0], - nullptr, - nullptr + TestQRCodeTLV_Setup, + TestQRCodeTLV_Teardown }; // clang-format on TestContext context; diff --git a/src/system/SystemLayer.cpp b/src/system/SystemLayer.cpp index bcd71060b9744e..aa0ebb5be07c3c 100644 --- a/src/system/SystemLayer.cpp +++ b/src/system/SystemLayer.cpp @@ -33,6 +33,7 @@ #include // Include additional CHIP headers +#include #include #include #include @@ -1097,15 +1098,15 @@ DLL_EXPORT Error PostEvent(Layer & aLayer, void * aContext, Object & aTarget, Ev VerifyOrExit(aContext != NULL, lReturn = CHIP_SYSTEM_ERROR_BAD_ARGS); lSysMbox = reinterpret_cast(aContext); - ev = new LwIPEvent; - VerifyOrExit(ev != NULL, lReturn = CHIP_SYSTEM_ERROR_NO_MEMORY); + ev = chip::Platform::New(); + VerifyOrExit(ev != nullptr, lReturn = CHIP_SYSTEM_ERROR_NO_MEMORY); ev->Type = aType; ev->Target = &aTarget; ev->Argument = aArgument; lLwIPError = sys_mbox_trypost(&lSysMbox, ev); - VerifyOrExit(lLwIPError == ERR_OK, delete ev; lReturn = chip::System::MapErrorLwIP(lLwIPError)); + VerifyOrExit(lLwIPError == ERR_OK, chip::Platform::Delete(ev); lReturn = chip::System::MapErrorLwIP(lLwIPError)); exit: return lReturn; @@ -1151,7 +1152,7 @@ DLL_EXPORT Error DispatchEvents(Layer & aLayer, void * aContext) VerifyOrExit(lEvent != NULL && lEvent->Target != NULL, lReturn = CHIP_SYSTEM_ERROR_UNEXPECTED_EVENT); lReturn = aLayer.HandleEvent(*lEvent->Target, lEvent->Type, lEvent->Argument); - delete lEvent; + chip::Platform::Delete(lEvent); SuccessOrExit(lReturn); } diff --git a/src/transport/RendezvousSession.cpp b/src/transport/RendezvousSession.cpp index d818063233dc3f..b6b7e6801e92be 100644 --- a/src/transport/RendezvousSession.cpp +++ b/src/transport/RendezvousSession.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -48,7 +49,7 @@ CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params) err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; #if CONFIG_NETWORK_LAYER_BLE { - Transport::BLE * transport = new Transport::BLE(); + Transport::BLE * transport = chip::Platform::New(); err = transport->Init(this, mParams); mTransport = transport; mTransport->Retain(); From 5c06f7acd61bfd32752daa8bc87507a2f417d2d6 Mon Sep 17 00:00:00 2001 From: Zang MingJie Date: Sat, 17 Oct 2020 07:25:53 +0800 Subject: [PATCH 36/40] make class ReferenceCounted use a deletor instead of virtual destruction (#3267) There are a few benefits to use a deletor. 1. it may save memory if SUBCLASS is not virtual class 2. allow use of custom deletor --- src/lib/core/ReferenceCounted.h | 15 +++-- src/lib/core/tests/TestReferenceCounted.cpp | 63 +++++++++++++++++++-- src/transport/NetworkProvisioning.h | 4 +- src/transport/SecurePairingSession.h | 2 +- src/transport/SecureSessionMgr.h | 4 +- src/transport/raw/Base.h | 2 +- 6 files changed, 75 insertions(+), 15 deletions(-) diff --git a/src/lib/core/ReferenceCounted.h b/src/lib/core/ReferenceCounted.h index b876ce521d71b6..3e053e5cdba2d4 100644 --- a/src/lib/core/ReferenceCounted.h +++ b/src/lib/core/ReferenceCounted.h @@ -30,16 +30,21 @@ namespace chip { +template +class DeleteDeletor +{ +public: + static void Release(T * obj) { chip::Platform::Delete(obj); } +}; + /** * A reference counted object maintains a count of usages and when the usage * count drops to 0, it deletes itself. */ -template +template > class ReferenceCounted { public: - virtual ~ReferenceCounted() {} - typedef uint32_t count_type; /** Adds one to the usage count of this class */ @@ -51,7 +56,7 @@ class ReferenceCounted } ++mRefCount; - return reinterpret_cast(this); + return static_cast(this); } /** Release usage of this class */ @@ -64,7 +69,7 @@ class ReferenceCounted if (--mRefCount == 0) { - chip::Platform::Delete(this); + DELETOR::Release(static_cast(this)); } } diff --git a/src/lib/core/tests/TestReferenceCounted.cpp b/src/lib/core/tests/TestReferenceCounted.cpp index ea40aee1239e85..77a9af59cc5f8e 100644 --- a/src/lib/core/tests/TestReferenceCounted.cpp +++ b/src/lib/core/tests/TestReferenceCounted.cpp @@ -36,14 +36,54 @@ using namespace chip; +class TestClass : public ReferenceCounted +{ +}; + static void TestRetainRelease(nlTestSuite * inSuite, void * inContext) { - ReferenceCounted testObj; + TestClass * testObj = chip::Platform::New(); + NL_TEST_ASSERT(inSuite, testObj->GetReferenceCount() == 1); + testObj->Retain(); + NL_TEST_ASSERT(inSuite, testObj->GetReferenceCount() == 2); + testObj->Release(); + NL_TEST_ASSERT(inSuite, testObj->GetReferenceCount() == 1); + testObj->Release(); +} + +class TestClassNonHeap; +class Deletor +{ +public: + static void Release(TestClassNonHeap * obj); +}; + +class TestClassNonHeap : public ReferenceCounted +{ +public: + bool deleted; +}; + +void Deletor::Release(TestClassNonHeap * obj) +{ + obj->deleted = true; +} + +static void TestRetainReleaseNonHeap(nlTestSuite * inSuite, void * inContext) +{ + TestClassNonHeap testObj; + testObj.deleted = false; NL_TEST_ASSERT(inSuite, testObj.GetReferenceCount() == 1); + NL_TEST_ASSERT(inSuite, testObj.deleted == false); testObj.Retain(); NL_TEST_ASSERT(inSuite, testObj.GetReferenceCount() == 2); + NL_TEST_ASSERT(inSuite, testObj.deleted == false); testObj.Release(); NL_TEST_ASSERT(inSuite, testObj.GetReferenceCount() == 1); + NL_TEST_ASSERT(inSuite, testObj.deleted == false); + testObj.Release(); + NL_TEST_ASSERT(inSuite, testObj.GetReferenceCount() == 0); + NL_TEST_ASSERT(inSuite, testObj.deleted == true); } /** @@ -54,20 +94,35 @@ static void TestRetainRelease(nlTestSuite * inSuite, void * inContext) static const nlTest sTests[] = { NL_TEST_DEF("ReferenceCountedRetain", TestRetainRelease), + NL_TEST_DEF("ReferenceCountedRetainNonHeap", TestRetainReleaseNonHeap), NL_TEST_SENTINEL() }; // clang-format on +int TestReferenceCounted_Setup(void * inContext) +{ + CHIP_ERROR error = chip::Platform::MemoryInit(); + if (error != CHIP_NO_ERROR) + return FAILURE; + return SUCCESS; +} + +int TestReferenceCounted_Teardown(void * inContext) +{ + chip::Platform::MemoryShutdown(); + return SUCCESS; +} + int TestReferenceCounted(void) { // clang-format off nlTestSuite theSuite = - { + { "Reference-Counted", &sTests[0], - nullptr, - nullptr + TestReferenceCounted_Setup, + TestReferenceCounted_Teardown }; // clang-format on diff --git a/src/transport/NetworkProvisioning.h b/src/transport/NetworkProvisioning.h index 6adc2c9f743d75..364d64a2869946 100644 --- a/src/transport/NetworkProvisioning.h +++ b/src/transport/NetworkProvisioning.h @@ -48,7 +48,7 @@ class DLL_EXPORT DeviceNetworkProvisioningDelegate : public ReferenceCounted @@ -82,7 +82,7 @@ class DLL_EXPORT NetworkProvisioningDelegate : public ReferenceCounted @@ -103,7 +103,7 @@ class DLL_EXPORT SecureSessionMgrBase : public ReferenceCounted { public: - ~Base() override {} + virtual ~Base() {} /** * Sets the message receive handler and associated argument From 00f03da961574e2f69e2998befca571e26a9e077 Mon Sep 17 00:00:00 2001 From: Yufeng Wang <44623591+yufengwangca@users.noreply.github.com> Date: Fri, 16 Oct 2020 20:58:56 -0700 Subject: [PATCH 37/40] Define ExchangeManager Header file for Transport layer (#3097) * Define ExchangeManager Header file for Transport layer * Use chip::BitFlags to define internal flags * Address review comments * Use a static constexpr for the -1 * Restyled by clang-format * Add document for API StartTimerT * Update header descriptions * Move ExchangeManager internal flags defination into class ExchangeManager * Remove tickle retransmition APIs * Address documentation comments * Update the interfaces based on the latest feedbacks. * Move functions not used by protocols private in ExchangeContext * Restyled by clang-format --- src/messaging/ExchangeContext.h | 261 ++++++++++++++++++++++++++++++++ src/messaging/ExchangeMgr.h | 211 ++++++++++++++++++++++++++ 2 files changed, 472 insertions(+) create mode 100644 src/messaging/ExchangeContext.h create mode 100644 src/messaging/ExchangeMgr.h diff --git a/src/messaging/ExchangeContext.h b/src/messaging/ExchangeContext.h new file mode 100644 index 00000000000000..47c7f82adbea5b --- /dev/null +++ b/src/messaging/ExchangeContext.h @@ -0,0 +1,261 @@ +/* + * + * Copyright (c) 2020 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. + */ + +/** + * @file + * This file defines the classes corresponding to CHIP Exchange Context. + * + */ + +#pragma once + +#include +#include +#include +#include + +namespace chip { + +class ExchangeManager; +class ExchangeContext; + +/** + * @brief + * This class provides a skeleton for the callback functions. The functions will be + * called by ExchangeContext object on specific events. If the user of ExchangeContext + * is interested in receiving these callbacks, they can specialize this class and handle + * each trigger in their implementation of this class. + */ +class DLL_EXPORT ExchangeContextDelegate +{ +public: + virtual ~ExchangeContextDelegate() {} + + /** + * @brief + * This function is the protocol callback for handling a received CHIP message. + * + * @param[in] ec A pointer to the ExchangeContext object. + * @param[in] packetHeader A reference to the PacketHeader object. + * @param[in] protocolId The protocol identifier of the received message. + * @param[in] msgType The message type of the corresponding protocol. + * @param[in] payload A pointer to the PacketBuffer object holding the message payload. + */ + virtual void OnMessageReceived(ExchangeContext * ec, const PacketHeader & packetHeader, uint32_t protocolId, uint8_t msgType, + System::PacketBuffer * payload) = 0; + + /** + * @brief + * This function is the protocol callback to invoke when the timeout for the receipt + * of a response message has expired. + * + * @param[in] ec A pointer to the ExchangeContext object. + */ + virtual void OnResponseTimeout(ExchangeContext * ec) = 0; +}; + +/** + * @brief + * This class represents an ongoing conversation (ExchangeContext) between two or more nodes. + * It defines methods for encoding and communicating CHIP messages within an ExchangeContext + * over various transport mechanisms, for example, TCP, UDP, or CHIP Reliable Messaging. + */ +class DLL_EXPORT ExchangeContext +{ + friend class ExchangeManager; + +public: + enum + { + kSendFlag_ExpectResponse = 0x0001, // Used to indicate that a response is expected within a specified timeout. + kSendFlag_RetainBuffer = 0x0002, // Used to indicate that the message buffer should not be freed after sending. + }; + + /** + * This function is the protocol callback of an unsolicited message handler. + * + * @param[in] ec A pointer to the ExchangeContext object. + * + * @param[in] packetHeader A reference to the PacketHeader object. + * + * @param[in] protocolId The protocol identifier of the received message. + * + * @param[in] msgType The message type of the corresponding protocol. + * + * @param[in] payload A pointer to the PacketBuffer object holding the message payload. + */ + typedef void (*MessageReceiveFunct)(ExchangeContext * ec, const PacketHeader & packetHeader, uint32_t protocolId, + uint8_t msgType, System::PacketBuffer * payload); + + /** + * Determine whether the context is the initiator of the exchange. + * + * @return Returns 'true' if it is the initiator, else 'false'. + */ + bool IsInitiator() const; + + /** + * Determine whether a response is expected for messages sent over + * this exchange. + * + * @return Returns 'true' if response expected, else 'false'. + */ + bool IsResponseExpected() const; + + /** + * Set whether a response is expected on this exchange. + * + * @param[in] inResponseExpected A Boolean indicating whether (true) or not + * (false) a response is expected on this + * exchange. + */ + void SetResponseExpected(bool inResponseExpected); + + /** + * Send a CHIP message on this exchange. + * + * @param[in] protocolId The protocol identifier of the CHIP message to be sent. + * + * @param[in] msgType The message type of the corresponding protocol. + * + * @param[in] msgPayload A pointer to the PacketBuffer object holding the CHIP message. + * + * @param[in] sendFlags Flags set by the application for the CHIP message being sent. + * + * @param[in] msgCtxt A pointer to an application-specific context object to be associated + * with the message being sent. + + * @retval #CHIP_ERROR_INVALID_ARGUMENT if an invalid argument was passed to this SendMessage API. + * @retval #CHIP_ERROR_SEND_THROTTLED if this exchange context has been throttled when using the + * CHIP reliable messaging protocol. + * @retval #CHIP_ERROR_WRONG_MSG_VERSION_FOR_EXCHANGE if there is a mismatch in the specific send operation and the + * CHIP message protocol version that is supported. + * @retval #CHIP_ERROR_NOT_CONNECTED if the context was associated with a connection that is now + * closed. + * @retval #CHIP_ERROR_INCORRECT_STATE if the state of the exchange context is incorrect. + * @retval #CHIP_NO_ERROR if the CHIP layer successfully sent the message down to the + * network layer. + */ + CHIP_ERROR SendMessage(uint16_t protocolId, uint8_t msgType, System::PacketBuffer * msgPayload, uint16_t sendFlags = 0, + void * msgCtxt = nullptr); + + /** + * Handle a received CHIP message on this exchange. + * + * @param[in] packetHeader A reference to the PacketHeader object. + * + * @param[in] payloadHeader A reference to the PayloadHeader object. + * + * @param[in] msgBuf A pointer to the PacketBuffer object holding the CHIP message. + * + * @retval #CHIP_ERROR_INVALID_ARGUMENT if an invalid argument was passed to this HandleMessage API. + * @retval #CHIP_ERROR_INCORRECT_STATE if the state of the exchange context is incorrect. + * @retval #CHIP_NO_ERROR if the CHIP layer successfully delivered the message up to the + * protocol layer. + */ + CHIP_ERROR HandleMessage(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, System::PacketBuffer * msgBuf); + + /** + * Handle a received CHIP message on this exchange. + * + * @param[in] packetHeader A reference to the PacketHeader object. + * + * @param[in] payloadHeader A reference to the PayloadHeader object. + * + * @param[in] msgBuf A pointer to the PacketBuffer object holding the CHIP message. + * + * @param[in] umhandler A unsolicited message callback handler. + * + * @retval #CHIP_ERROR_INVALID_ARGUMENT if an invalid argument was passed to this HandleMessage API. + * @retval #CHIP_ERROR_INCORRECT_STATE if the state of the exchange context is incorrect. + * @retval #CHIP_NO_ERROR if the CHIP layer successfully delivered the message up to the + * protocol layer. + */ + CHIP_ERROR HandleMessage(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, System::PacketBuffer * msgBuf, + ExchangeContext::MessageReceiveFunct umhandler); + + void SetDelegate(ExchangeContextDelegate * delegate) { mDelegate = delegate; } + + ExchangeContextDelegate * GetDelegate() const { return mDelegate; } + + ExchangeManager * GetExchangeMgr() const { return mExchangeMgr; } + + uint64_t GetPeerNodeId() const { return mPeerNodeId; } + + uint16_t GetExchangeId() const { return mExchangeId; } + + void * GetAppState() const { return mAppState; } + + /* + * In order to use reference counting (see refCount below) we use a hold/free paradigm where users of the exchange + * can hold onto it while it's out of their direct control to make sure it isn't closed before everyone's ready. + * A customized version of reference counting is used since there are some extra stuff to do within Release. + */ + void AddRef(); + void Close(); + void Abort(); + void Release(); + void SetRefCount(uint8_t value) { mRefCount = value; } + +private: + enum class ExFlagValues : uint16_t + { + kFlagInitiator = 0x0001, // This context is the initiator of the exchange. + kFlagResponseExpected = 0x0002, // If a response is expected for a message that is being sent. + }; + + typedef uint32_t Timeout; // Type used to express the timeout in this ExchangeContext, in milliseconds + + Timeout mResponseTimeout; // Maximum time to wait for response (in milliseconds); 0 disables response timeout. + System::PacketBuffer * mMsg; // If we are re-transmitting, then this is the pointer to the message being retransmitted + ExchangeContextDelegate * mDelegate = nullptr; + ExchangeManager * mExchangeMgr; + void * mAppState; // Pointer to application-specific state object. + + uint64_t mPeerNodeId; // Node ID of peer node. + uint16_t mExchangeId; // Assigned exchange ID. + uint8_t mRefCount; // Reference counter of the current instance + + BitFlags mFlags; // Internal state flags + + /** + * Search for an existing exchange that the message applies to. + * + * @param[in] packetHeader A reference to the PacketHeader object. + * + * @param[in] payloadHeader A reference to the PayloadHeader object. + * + * @retval true If a match is found. + * @retval false If a match is not found. + */ + bool MatchExchange(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader); + + void SetInitiator(bool inInitiator); + void SetPeerNodeId(uint64_t nodeId) { mPeerNodeId = nodeId; } + void SetExchangeId(uint16_t exId) { mExchangeId = exId; } + void SetExchangeMgr(ExchangeManager * exMgr) { mExchangeMgr = exMgr; } + void SetAppState(void * state) { mAppState = state; } + + CHIP_ERROR ResendMessage(); + CHIP_ERROR StartResponseTimer(); + void CancelResponseTimer(); + static void HandleResponseTimeout(System::Layer * aSystemLayer, void * aAppState, System::Error aError); + + void DoClose(bool clearRetransTable); +}; + +} // namespace chip diff --git a/src/messaging/ExchangeMgr.h b/src/messaging/ExchangeMgr.h new file mode 100644 index 00000000000000..8fe50f5a9824d4 --- /dev/null +++ b/src/messaging/ExchangeMgr.h @@ -0,0 +1,211 @@ +/* + * + * Copyright (c) 2020 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. + */ + +/** + * @file + * Defines the CHIP ExchangeManager class and its supporting types + * for Exchange management. + * + */ + +#pragma once + +#include +#include +#include + +namespace chip { + +class ExchangeContext; + +static constexpr int16_t kAnyMessageType = -1; + +/** + * @brief + * This class is used to manage ExchangeContexts with other CHIP nodes. + * It works on be behalf of higher layers, creating ExchangeContexts and + * handling the registration/unregistration of unsolicited message handlers. + */ +class DLL_EXPORT ExchangeManager : public SecureSessionMgrDelegate +{ +public: + ExchangeManager(); + ExchangeManager(const ExchangeManager &) = delete; + ExchangeManager operator=(const ExchangeManager &) = delete; + + /** + * Initialize the ExchangeManager object. Within the lifetime + * of this instance, this method is invoked once after object + * construction until a call to Shutdown is made to terminate the + * instance. + * + * @param[in] sessionMgr A pointer to the SecureSessionMgrBase object. + * + * @retval #CHIP_ERROR_INCORRECT_STATE If the state is not equal to + * kState_NotInitialized. + * @retval #CHIP_NO_ERROR On success. + * + */ + CHIP_ERROR Init(SecureSessionMgrBase * sessionMgr); + + /** + * Shutdown the ExchangeManager. This terminates this instance + * of the object and releases all held resources. + * + * @note + * The protocol should only call this function after ensuring that + * there are no active ExchangeContext objects. Furthermore, it is the + * onus of the application to de-allocate the ExchangeManager + * object after calling ExchangeManager::Shutdown(). + * + * @return #CHIP_NO_ERROR unconditionally. + */ + CHIP_ERROR Shutdown(); + + /** + * Creates a new ExchangeContext with a given peer CHIP node specified by the peer node identifier. + * + * @param[in] peerNodeId The node identifier of the peer with which the ExchangeContext is being set up. + * + * @param[in] appState A pointer to a higher layer object that holds context state. + * + * @return A pointer to the created ExchangeContext object On success. Otherwise NULL if no object + * can be allocated or is available. + */ + ExchangeContext * NewContext(const uint64_t & peerNodeId, void * appState = nullptr); + + /** + * Find the ExchangeContext from a pool matching a given set of parameters. + * + * @param[in] peerNodeId The node identifier of the peer with which the ExchangeContext has been set up. + * + * @param[in] appState A pointer to a higher layer object that holds context state. + * + * @param[in] isInitiator Boolean indicator of whether the local node is the initiator of the exchange. + * + * @return A pointer to the ExchangeContext object matching the provided parameters On success, NULL on no match. + */ + ExchangeContext * FindContext(uint64_t peerNodeId, void * appState, bool isInitiator); + + /** + * Register an unsolicited message handler for a given protocol identifier. This handler would be + * invoked for all messages of the given protocol. + * + * @param[in] protocolId The protocol identifier of the received message. + * + * @param[in] handler The unsolicited message handler. + * + * @param[in] appState A pointer to a higher layer object that holds context state. + * + * @retval #CHIP_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS If the unsolicited message handler pool + * is full and a new one cannot be allocated. + * @retval #CHIP_NO_ERROR On success. + */ + CHIP_ERROR RegisterUnsolicitedMessageHandler(uint32_t protocolId, ExchangeContext::MessageReceiveFunct handler, + void * appState); + + /** + * Register an unsolicited message handler for a given protocol identifier and message type. + * + * @param[in] protocolId The protocol identifier of the received message. + * + * @param[in] msgType The message type of the corresponding protocol. + * + * @param[in] handler The unsolicited message handler. + * + * @param[in] appState A pointer to a higher layer object that holds context state. + * + * @retval #CHIP_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS If the unsolicited message handler pool + * is full and a new one cannot be allocated. + * @retval #CHIP_NO_ERROR On success. + */ + CHIP_ERROR RegisterUnsolicitedMessageHandler(uint32_t protocolId, uint8_t msgType, ExchangeContext::MessageReceiveFunct handler, + void * appState); + + /** + * Unregister an unsolicited message handler for a given protocol identifier. + * + * @param[in] protocolId The protocol identifier of the received message. + * + * @retval #CHIP_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER If the matching unsolicited message handler + * is not found. + * @retval #CHIP_NO_ERROR On success. + */ + CHIP_ERROR UnregisterUnsolicitedMessageHandler(uint32_t protocolId); + + /** + * Unregister an unsolicited message handler for a given protocol identifier and message type. + * + * @param[in] protocolId The protocol identifier of the received message. + * + * @param[in] msgType The message type of the corresponding protocol. + * + * @retval #CHIP_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER If the matching unsolicited message handler + * is not found. + * @retval #CHIP_NO_ERROR On success. + */ + CHIP_ERROR UnregisterUnsolicitedMessageHandler(uint32_t protocolId, uint8_t msgType); + + /** + * Decrement current context in use by 1. + */ + void DecrementContextsInUse(); + + SecureSessionMgrBase * GetSessionMgr() const { return mSessionMgr; } + + size_t GetContextsInUse() const { return mContextsInUse; } + +private: + enum class State + { + kState_NotInitialized = 0, // Used to indicate that the ExchangeManager is not initialized. + kState_Initialized = 1 // Used to indicate that the ExchangeManager is initialized. + }; + + struct UnsolicitedMessageHandler + { + ExchangeContext::MessageReceiveFunct Handler; + void * AppState; + uint32_t ProtocolId; + int16_t MessageType; + }; + + uint16_t mNextExchangeId; + State mState; + SecureSessionMgrBase * mSessionMgr; + + ExchangeContext ContextPool[CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS]; + size_t mContextsInUse; + + UnsolicitedMessageHandler UMHandlerPool[CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS]; + void (*OnExchangeContextChanged)(size_t numContextsInUse); + + ExchangeContext * AllocContext(); + + void DispatchMessage(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, System::PacketBuffer * msgBuf); + + CHIP_ERROR RegisterUMH(uint32_t protocolId, int16_t msgType, ExchangeContext::MessageReceiveFunct handler, void * appState); + CHIP_ERROR UnregisterUMH(uint32_t protocolId, int16_t msgType); + + void OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgrBase * msgLayer) override; + + void OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, + Transport::PeerConnectionState * state, System::PacketBuffer * msgBuf, + SecureSessionMgrBase * msgLayer) override; +}; + +} // namespace chip From 5386fea3c44df9a26d2f2ba1b5f65c50fc4fb788 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Sun, 18 Oct 2020 19:01:01 -0400 Subject: [PATCH 38/40] Add sdkconfig direct include in PlatformConfig, to depend outside -isystem includes (#3287) --- src/platform/ESP32/CHIPPlatformConfig.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/platform/ESP32/CHIPPlatformConfig.h b/src/platform/ESP32/CHIPPlatformConfig.h index c12954824b26c3..654caa64ac43e9 100644 --- a/src/platform/ESP32/CHIPPlatformConfig.h +++ b/src/platform/ESP32/CHIPPlatformConfig.h @@ -25,6 +25,14 @@ #pragma once +/* Force sdkconfig to be added as a dependecy. That file is also included as a sideffect of + * esp_err.h -> assert.h -> sdkconfig.h however since esp_err.h and above are -isystem includes, + * they are not added as dependencies by GN build systems. + * + * This triggers a rebuild of files including CHIPPlatformConfig if sdkconfig.h changes. + */ +#include + #include "esp_err.h" // ==================== General Platform Adaptations ==================== From 9219f0336dc53ac552f999601bbadc674926e58c Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Mon, 19 Oct 2020 05:21:02 +0200 Subject: [PATCH 39/40] Generate Global Commands Response code and use it inside chip-tool (#3270) --- .../chip-tool/commands/clusters/Commands.h | 2953 ++++++++++++++--- .../commands/common/ModelCommand.cpp | 134 +- .../chip-tool/commands/common/ModelCommand.h | 17 +- .../commands/common/ModelCommandResponse.h | 41 + 4 files changed, 2463 insertions(+), 682 deletions(-) create mode 100644 examples/chip-tool/commands/common/ModelCommandResponse.h diff --git a/examples/chip-tool/commands/clusters/Commands.h b/examples/chip-tool/commands/clusters/Commands.h index 321847ec879c21..6b1f70874535ff 100644 --- a/examples/chip-tool/commands/clusters/Commands.h +++ b/examples/chip-tool/commands/clusters/Commands.h @@ -21,6 +21,369 @@ #pragma once #include "../common/ModelCommand.h" +#include "../common/ModelCommandResponse.h" + +#include + +bool ReadAnyType(uint8_t *& message) +{ + uint8_t type = chip::Encoding::Read8(message); + ChipLogProgress(chipTool, " type: 0x%02x", type); + + // FIXME: Should we have a mapping of type ids to types, based on + // table 2.6.2.2 in Rev 8 of the ZCL spec? + switch (type) + { + case 0x00: // nodata / No data + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0x08: // data8 / 8-bit data + ChipLogProgress(chipTool, " value: 0x%02x", chip::Encoding::Read8(message)); + return true; + break; + case 0x09: // data16 / 16-bit data + ChipLogProgress(chipTool, " value: 0x%04x", chip::Encoding::LittleEndian::Read16(message)); + return true; + break; + case 0x0A: // data24 / 24-bit data + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 3; + break; + case 0x0B: // data32 / 32-bit data + ChipLogProgress(chipTool, " value: 0x%08x", chip::Encoding::LittleEndian::Read32(message)); + return true; + break; + case 0x0C: // data40 / 40-bit data + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 5; + break; + case 0x0D: // data48 / 48-bit data + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 6; + break; + case 0x0E: // data56 / 56-bit data + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 7; + break; + case 0x0F: // data64 / 64-bit data + ChipLogProgress(chipTool, " value: 0x%16x", chip::Encoding::LittleEndian::Read64(message)); + return true; + break; + case 0x10: // bool / Boolean + ChipLogProgress(chipTool, " value: 0x%02x", chip::Encoding::Read8(message)); + return true; + break; + case 0x18: // map8 / 8-bit bitmap + ChipLogProgress(chipTool, " value: 0x%02x", chip::Encoding::Read8(message)); + return true; + break; + case 0x19: // map16 / 16-bit bitmap + ChipLogProgress(chipTool, " value: 0x%04x", chip::Encoding::LittleEndian::Read16(message)); + return true; + break; + case 0x1A: // map24 / 24-bit bitmap + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 3; + break; + case 0x1B: // map32 / 32-bit bitmap + ChipLogProgress(chipTool, " value: 0x%08x", chip::Encoding::LittleEndian::Read32(message)); + return true; + break; + case 0x1C: // map40 / 40-bit bitmap + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 5; + break; + case 0x1D: // map48 / 48-bit bitmap + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 6; + break; + case 0x1E: // map56 / 56-bit bitmap + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 7; + break; + case 0x1F: // map64 / 64-bit bitmap + ChipLogProgress(chipTool, " value: 0x%16x", chip::Encoding::LittleEndian::Read64(message)); + return true; + break; + case 0x20: // uint8 / Unsigned 8-bit integer + ChipLogProgress(chipTool, " value: 0x%02x", chip::Encoding::Read8(message)); + return true; + break; + case 0x21: // uint16 / Unsigned 16-bit integer + ChipLogProgress(chipTool, " value: 0x%04x", chip::Encoding::LittleEndian::Read16(message)); + return true; + break; + case 0x22: // uint24 / Unsigned 24-bit integer + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 3; + break; + case 0x23: // uint32 / Unsigned 32-bit integer + ChipLogProgress(chipTool, " value: 0x%08x", chip::Encoding::LittleEndian::Read32(message)); + return true; + break; + case 0x24: // uint40 / Unsigned 40-bit integer + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 5; + break; + case 0x25: // uint48 / Unsigned 48-bit integer + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 6; + break; + case 0x26: // uint56 / Unsigned 56-bit integer + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 7; + break; + case 0x27: // uint64 / Unsigned 64-bit integer + ChipLogProgress(chipTool, " value: 0x%16x", chip::Encoding::LittleEndian::Read64(message)); + return true; + break; + case 0x28: // int8 / Signed 8-bit integer + ChipLogProgress(chipTool, " value: %d", chip::CastToSigned(chip::Encoding::Read8(message))); + return true; + break; + case 0x29: // int16 / Signed 16-bit integer + ChipLogProgress(chipTool, " value: %d", chip::CastToSigned(chip::Encoding::LittleEndian::Read16(message))); + return true; + break; + case 0x2A: // int24 / Signed 24-bit integer + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 3; + break; + case 0x2B: // int32 / Signed 32-bit integer + ChipLogProgress(chipTool, " value: %d", chip::CastToSigned(chip::Encoding::LittleEndian::Read32(message))); + return true; + break; + case 0x2C: // int40 / Signed 40-bit integer + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 5; + break; + case 0x2D: // int48 / Signed 48-bit integer + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 6; + break; + case 0x2E: // int56 / Signed 56-bit integer + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 7; + break; + case 0x2F: // int64 / Signed 64-bit integer + ChipLogProgress(chipTool, " value: %d", chip::CastToSigned(chip::Encoding::LittleEndian::Read64(message))); + return true; + break; + case 0x30: // enum8 / 8-bit enumeration + ChipLogProgress(chipTool, " value: 0x%02x", chip::Encoding::Read8(message)); + return true; + break; + case 0x31: // enum16 / 16-bit enumeration + ChipLogProgress(chipTool, " value: 0x%04x", chip::Encoding::LittleEndian::Read16(message)); + return true; + break; + case 0x38: // semi / Semi-precision + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0x39: // single / Single precision + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0x3A: // double / Double precision + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0x41: // octstr / Octet string + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0x42: // string / Character string + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0x43: // octstr16 / Long octet string + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 2; + break; + case 0x44: // string16 / Long character string + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 2; + break; + case 0x48: // array / Array + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0x49: // struct / Structure + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0x50: // set / Set + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0x51: // bag / Bag + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0xE0: // ToD / Time of day + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0xE1: // date / Date + ChipLogProgress(chipTool, " value: 0x%08x", chip::Encoding::LittleEndian::Read32(message)); + return true; + break; + case 0xE2: // UTC / UTCTime + ChipLogProgress(chipTool, " value: 0x%08x", chip::Encoding::LittleEndian::Read32(message)); + return true; + break; + case 0xE8: // clusterId / Cluster ID + ChipLogProgress(chipTool, " value: 0x%04x", chip::Encoding::LittleEndian::Read16(message)); + return true; + break; + case 0xE9: // attribId / Attribute ID + ChipLogProgress(chipTool, " value: 0x%04x", chip::Encoding::LittleEndian::Read16(message)); + return true; + break; + case 0xEA: // bacOID / BACnet OID + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + case 0xF0: // EUI64 / IEEE address + ChipLogProgress(chipTool, " value: 0x%16x", chip::Encoding::LittleEndian::Read64(message)); + return true; + break; + case 0xF1: // key128 / 128-bit security key + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 16; + break; + case 0xFF: // unk / Unknown + ChipLogError(chipTool, "Type 0x%02x is not supported", type); + message += 0; + break; + } + + return false; +} + +/*----------------------------------------------------------------------------*\ +| Global Command Responses | ID | +|------------------------------------------------------------------------------| +| * ReadAttributesResponse | 0x01 | +| * WriteAttributesResponse | 0x04 | +| * WriteAttributesNoResponse | 0x05 | +| * DefaultResponse | 0x0B | +| * DiscoverAttributesResponse | 0x0D | +\*----------------------------------------------------------------------------*/ + +/* + * Command ReadAttributesResponse + */ +class ReadAttributesResponse : public ModelCommandResponse +{ +public: + ReadAttributesResponse() : ModelCommandResponse(0x01) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "ReadAttributesResponse (0x01):"); + // struct readAttributeResponseRecord[] + uint8_t * messageEnd = message + messageLen; + do + { + ChipLogProgress(chipTool, " %s: 0x%04x", "attributeId", chip::Encoding::LittleEndian::Read16(message)); // attribId + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ReadAnyType(message); + } while (message < messageEnd); + + return true; + } +}; + +/* + * Command WriteAttributesResponse + */ +class WriteAttributesResponse : public ModelCommandResponse +{ +public: + WriteAttributesResponse() : ModelCommandResponse(0x04) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "WriteAttributesResponse (0x04):"); + // struct writeAttributeResponseRecord[] + uint8_t * messageEnd = message + messageLen; + do + { + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%04x", "attributeId", chip::Encoding::LittleEndian::Read16(message)); // attribId + } while (message < messageEnd); + + return true; + } +}; + +/* + * Command WriteAttributesNoResponse + */ +class WriteAttributesNoResponse : public ModelCommandResponse +{ +public: + WriteAttributesNoResponse() : ModelCommandResponse(0x05) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "WriteAttributesNoResponse (0x05):"); + // struct writeAttributeRecord[] + uint8_t * messageEnd = message + messageLen; + do + { + ChipLogProgress(chipTool, " %s: 0x%04x", "attributeId", chip::Encoding::LittleEndian::Read16(message)); // attribId + ReadAnyType(message); + } while (message < messageEnd); + + return true; + } +}; + +/* + * Command DefaultResponse + */ +class DefaultResponse : public ModelCommandResponse +{ +public: + DefaultResponse() : ModelCommandResponse(0x0B) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "DefaultResponse (0x0B):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "commandId", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%02x", "statusCode", chip::Encoding::Read8(message)); // zclStatus + + return true; + } +}; + +/* + * Command DiscoverAttributesResponse + */ +class DiscoverAttributesResponse : public ModelCommandResponse +{ +public: + DiscoverAttributesResponse() : ModelCommandResponse(0x0D) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "DiscoverAttributesResponse (0x0D):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "discoveryComplete", chip::Encoding::Read8(message)); // bool + // struct discoverAttributesResponseRecord[] + uint8_t * messageEnd = message + messageLen; + do + { + ChipLogProgress(chipTool, " %s: 0x%04x", "attributeId", chip::Encoding::LittleEndian::Read16(message)); // attribId + ChipLogProgress(chipTool, " %s: 0x%02x", "attributeType", chip::Encoding::Read8(message)); // zclType + } while (message < messageEnd); + + return true; + } +}; /*----------------------------------------------------------------------------*\ | Cluster Name | ID | @@ -37,25 +400,27 @@ | TemperatureMeasurement | 0x0402 | \*----------------------------------------------------------------------------*/ -#define BARRIER_CONTROL_CLUSTER_ID 0x0103 -#define BASIC_CLUSTER_ID 0x0000 -#define COLOR_CONTROL_CLUSTER_ID 0x0300 -#define DOOR_LOCK_CLUSTER_ID 0x0101 -#define GROUPS_CLUSTER_ID 0x0004 -#define IDENTIFY_CLUSTER_ID 0x0003 -#define LEVEL_CLUSTER_ID 0x0008 -#define ON_OFF_CLUSTER_ID 0x0006 -#define SCENES_CLUSTER_ID 0x0005 -#define TEMPERATURE_MEASUREMENT_CLUSTER_ID 0x0402 +constexpr uint16_t kBarrierControlClusterId = 0x0103; +constexpr uint16_t kBasicClusterId = 0x0000; +constexpr uint16_t kColorControlClusterId = 0x0300; +constexpr uint16_t kDoorLockClusterId = 0x0101; +constexpr uint16_t kGroupsClusterId = 0x0004; +constexpr uint16_t kIdentifyClusterId = 0x0003; +constexpr uint16_t kLevelClusterId = 0x0008; +constexpr uint16_t kOnOffClusterId = 0x0006; +constexpr uint16_t kScenesClusterId = 0x0005; +constexpr uint16_t kTempMeasurementClusterId = 0x0402; /*----------------------------------------------------------------------------*\ | Cluster BarrierControl | 0x0103 | |------------------------------------------------------------------------------| +| Responses: | | +| | | +|------------------------------------------------------------------------------| | Commands: | | | * GoToPercent | 0x00 | -| | | |------------------------------------------------------------------------------| -| Attributes:: | | +| Attributes: | | | * MovingState | 0x0001 | | * SafetyStatus | 0x0002 | | * Capabilities | 0x0003 | @@ -68,7 +433,7 @@ class BarrierControlGoToPercent : public ModelCommand { public: - BarrierControlGoToPercent() : ModelCommand("go-to-percent", BARRIER_CONTROL_CLUSTER_ID) + BarrierControlGoToPercent() : ModelCommand("go-to-percent", kBarrierControlClusterId, 0x00) { AddArgument("percentOpen", 0, UINT8_MAX, &mPercentOpen); } @@ -78,6 +443,13 @@ class BarrierControlGoToPercent : public ModelCommand return encodeBarrierControlClusterGoToPercentCommand(buffer->Start(), bufferSize, endPointId, mPercentOpen); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mPercentOpen; }; @@ -88,12 +460,22 @@ class BarrierControlGoToPercent : public ModelCommand class ReadBarrierControlMovingState : public ModelCommand { public: - ReadBarrierControlMovingState() : ModelCommand("read", BARRIER_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "moving-state"); } + ReadBarrierControlMovingState() : ModelCommand("read", kBarrierControlClusterId, 0x00) + { + AddArgument("attr-name", "moving-state"); + } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBarrierControlClusterReadMovingStateAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -102,7 +484,7 @@ class ReadBarrierControlMovingState : public ModelCommand class ReadBarrierControlSafetyStatus : public ModelCommand { public: - ReadBarrierControlSafetyStatus() : ModelCommand("read", BARRIER_CONTROL_CLUSTER_ID) + ReadBarrierControlSafetyStatus() : ModelCommand("read", kBarrierControlClusterId, 0x00) { AddArgument("attr-name", "safety-status"); } @@ -111,6 +493,13 @@ class ReadBarrierControlSafetyStatus : public ModelCommand { return encodeBarrierControlClusterReadSafetyStatusAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -119,7 +508,7 @@ class ReadBarrierControlSafetyStatus : public ModelCommand class ReadBarrierControlCapabilities : public ModelCommand { public: - ReadBarrierControlCapabilities() : ModelCommand("read", BARRIER_CONTROL_CLUSTER_ID) + ReadBarrierControlCapabilities() : ModelCommand("read", kBarrierControlClusterId, 0x00) { AddArgument("attr-name", "capabilities"); } @@ -128,6 +517,13 @@ class ReadBarrierControlCapabilities : public ModelCommand { return encodeBarrierControlClusterReadCapabilitiesAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -136,7 +532,7 @@ class ReadBarrierControlCapabilities : public ModelCommand class ReadBarrierControlBarrierPosition : public ModelCommand { public: - ReadBarrierControlBarrierPosition() : ModelCommand("read", BARRIER_CONTROL_CLUSTER_ID) + ReadBarrierControlBarrierPosition() : ModelCommand("read", kBarrierControlClusterId, 0x00) { AddArgument("attr-name", "barrier-position"); } @@ -145,16 +541,25 @@ class ReadBarrierControlBarrierPosition : public ModelCommand { return encodeBarrierControlClusterReadBarrierPositionAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /*----------------------------------------------------------------------------*\ | Cluster Basic | 0x0000 | |------------------------------------------------------------------------------| +| Responses: | | +| | | +|------------------------------------------------------------------------------| | Commands: | | | * ResetToFactoryDefaults | 0x00 | -| | | |------------------------------------------------------------------------------| -| Attributes:: | | +| Attributes: | | | * ZCLVersion | 0x0000 | | * ApplicationVersion | 0x0001 | | * StackVersion | 0x0002 | @@ -176,12 +581,19 @@ class ReadBarrierControlBarrierPosition : public ModelCommand class BasicResetToFactoryDefaults : public ModelCommand { public: - BasicResetToFactoryDefaults() : ModelCommand("reset-to-factory-defaults", BASIC_CLUSTER_ID) {} + BasicResetToFactoryDefaults() : ModelCommand("reset-to-factory-defaults", kBasicClusterId, 0x00) {} uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterResetToFactoryDefaultsCommand(buffer->Start(), bufferSize, endPointId); } + + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -190,12 +602,19 @@ class BasicResetToFactoryDefaults : public ModelCommand class ReadBasicZCLVersion : public ModelCommand { public: - ReadBasicZCLVersion() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "zclversion"); } + ReadBasicZCLVersion() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "zclversion"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadZCLVersionAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -204,12 +623,19 @@ class ReadBasicZCLVersion : public ModelCommand class ReadBasicApplicationVersion : public ModelCommand { public: - ReadBasicApplicationVersion() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "application-version"); } + ReadBasicApplicationVersion() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "application-version"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadApplicationVersionAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -218,12 +644,19 @@ class ReadBasicApplicationVersion : public ModelCommand class ReadBasicStackVersion : public ModelCommand { public: - ReadBasicStackVersion() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "stack-version"); } + ReadBasicStackVersion() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "stack-version"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadStackVersionAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -232,12 +665,19 @@ class ReadBasicStackVersion : public ModelCommand class ReadBasicHWVersion : public ModelCommand { public: - ReadBasicHWVersion() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "hwversion"); } + ReadBasicHWVersion() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "hwversion"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadHWVersionAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -246,12 +686,19 @@ class ReadBasicHWVersion : public ModelCommand class ReadBasicManufacturerName : public ModelCommand { public: - ReadBasicManufacturerName() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "manufacturer-name"); } + ReadBasicManufacturerName() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "manufacturer-name"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadManufacturerNameAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -260,12 +707,19 @@ class ReadBasicManufacturerName : public ModelCommand class ReadBasicModelIdentifier : public ModelCommand { public: - ReadBasicModelIdentifier() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "model-identifier"); } + ReadBasicModelIdentifier() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "model-identifier"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadModelIdentifierAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -274,12 +728,19 @@ class ReadBasicModelIdentifier : public ModelCommand class ReadBasicDateCode : public ModelCommand { public: - ReadBasicDateCode() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "date-code"); } + ReadBasicDateCode() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "date-code"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadDateCodeAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -288,12 +749,19 @@ class ReadBasicDateCode : public ModelCommand class ReadBasicPowerSource : public ModelCommand { public: - ReadBasicPowerSource() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "power-source"); } + ReadBasicPowerSource() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "power-source"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadPowerSourceAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -302,12 +770,22 @@ class ReadBasicPowerSource : public ModelCommand class ReadBasicGenericDeviceClass : public ModelCommand { public: - ReadBasicGenericDeviceClass() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "generic-device-class"); } + ReadBasicGenericDeviceClass() : ModelCommand("read", kBasicClusterId, 0x00) + { + AddArgument("attr-name", "generic-device-class"); + } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadGenericDeviceClassAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -316,12 +794,19 @@ class ReadBasicGenericDeviceClass : public ModelCommand class ReadBasicGenericDeviceType : public ModelCommand { public: - ReadBasicGenericDeviceType() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "generic-device-type"); } + ReadBasicGenericDeviceType() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "generic-device-type"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadGenericDeviceTypeAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -330,12 +815,19 @@ class ReadBasicGenericDeviceType : public ModelCommand class ReadBasicProductCode : public ModelCommand { public: - ReadBasicProductCode() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "product-code"); } + ReadBasicProductCode() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "product-code"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadProductCodeAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -344,12 +836,19 @@ class ReadBasicProductCode : public ModelCommand class ReadBasicProductURL : public ModelCommand { public: - ReadBasicProductURL() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "product-url"); } + ReadBasicProductURL() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "product-url"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadProductURLAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -358,17 +857,27 @@ class ReadBasicProductURL : public ModelCommand class ReadBasicSWBuildID : public ModelCommand { public: - ReadBasicSWBuildID() : ModelCommand("read", BASIC_CLUSTER_ID) { AddArgument("attr-name", "swbuild-id"); } + ReadBasicSWBuildID() : ModelCommand("read", kBasicClusterId, 0x00) { AddArgument("attr-name", "swbuild-id"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeBasicClusterReadSWBuildIDAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /*----------------------------------------------------------------------------*\ | Cluster ColorControl | 0x0300 | |------------------------------------------------------------------------------| +| Responses: | | +| | | +|------------------------------------------------------------------------------| | Commands: | | | * MoveColor | 0x08 | | * MoveColorTemperature | 0x4B | @@ -384,9 +893,8 @@ class ReadBasicSWBuildID : public ModelCommand | * StepHue | 0x02 | | * StepSaturation | 0x05 | | * StopMoveStep | 0x47 | -| | | |------------------------------------------------------------------------------| -| Attributes:: | | +| Attributes: | | | * CurrentHue | 0x0000 | | * CurrentSaturation | 0x0001 | | * CurrentX | 0x0003 | @@ -433,7 +941,7 @@ class ReadBasicSWBuildID : public ModelCommand class ColorControlMoveColor : public ModelCommand { public: - ColorControlMoveColor() : ModelCommand("move-color", COLOR_CONTROL_CLUSTER_ID) + ColorControlMoveColor() : ModelCommand("move-color", kColorControlClusterId, 0x08) { AddArgument("rateX", INT16_MIN, INT16_MAX, &mRateX); AddArgument("rateY", INT16_MIN, INT16_MAX, &mRateY); @@ -447,6 +955,13 @@ class ColorControlMoveColor : public ModelCommand mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: int16_t mRateX; int16_t mRateY; @@ -460,7 +975,7 @@ class ColorControlMoveColor : public ModelCommand class ColorControlMoveColorTemperature : public ModelCommand { public: - ColorControlMoveColorTemperature() : ModelCommand("move-color-temperature", COLOR_CONTROL_CLUSTER_ID) + ColorControlMoveColorTemperature() : ModelCommand("move-color-temperature", kColorControlClusterId, 0x4B) { AddArgument("moveMode", 0, UINT8_MAX, &mMoveMode); AddArgument("rate", 0, UINT16_MAX, &mRate); @@ -477,6 +992,13 @@ class ColorControlMoveColorTemperature : public ModelCommand mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mMoveMode; uint16_t mRate; @@ -492,7 +1014,7 @@ class ColorControlMoveColorTemperature : public ModelCommand class ColorControlMoveHue : public ModelCommand { public: - ColorControlMoveHue() : ModelCommand("move-hue", COLOR_CONTROL_CLUSTER_ID) + ColorControlMoveHue() : ModelCommand("move-hue", kColorControlClusterId, 0x01) { AddArgument("moveMode", 0, UINT8_MAX, &mMoveMode); AddArgument("rate", 0, UINT8_MAX, &mRate); @@ -506,6 +1028,13 @@ class ColorControlMoveHue : public ModelCommand mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mMoveMode; uint8_t mRate; @@ -519,7 +1048,7 @@ class ColorControlMoveHue : public ModelCommand class ColorControlMoveSaturation : public ModelCommand { public: - ColorControlMoveSaturation() : ModelCommand("move-saturation", COLOR_CONTROL_CLUSTER_ID) + ColorControlMoveSaturation() : ModelCommand("move-saturation", kColorControlClusterId, 0x04) { AddArgument("moveMode", 0, UINT8_MAX, &mMoveMode); AddArgument("rate", 0, UINT8_MAX, &mRate); @@ -533,6 +1062,13 @@ class ColorControlMoveSaturation : public ModelCommand mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mMoveMode; uint8_t mRate; @@ -546,7 +1082,7 @@ class ColorControlMoveSaturation : public ModelCommand class ColorControlMoveToColor : public ModelCommand { public: - ColorControlMoveToColor() : ModelCommand("move-to-color", COLOR_CONTROL_CLUSTER_ID) + ColorControlMoveToColor() : ModelCommand("move-to-color", kColorControlClusterId, 0x07) { AddArgument("colorX", 0, UINT16_MAX, &mColorX); AddArgument("colorY", 0, UINT16_MAX, &mColorY); @@ -561,6 +1097,13 @@ class ColorControlMoveToColor : public ModelCommand mTransitionTime, mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint16_t mColorX; uint16_t mColorY; @@ -575,7 +1118,7 @@ class ColorControlMoveToColor : public ModelCommand class ColorControlMoveToColorTemperature : public ModelCommand { public: - ColorControlMoveToColorTemperature() : ModelCommand("move-to-color-temperature", COLOR_CONTROL_CLUSTER_ID) + ColorControlMoveToColorTemperature() : ModelCommand("move-to-color-temperature", kColorControlClusterId, 0x0A) { AddArgument("colorTemperatureMireds", 0, UINT16_MAX, &mColorTemperatureMireds); AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime); @@ -589,6 +1132,13 @@ class ColorControlMoveToColorTemperature : public ModelCommand buffer->Start(), bufferSize, endPointId, mColorTemperatureMireds, mTransitionTime, mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint16_t mColorTemperatureMireds; uint16_t mTransitionTime; @@ -602,7 +1152,7 @@ class ColorControlMoveToColorTemperature : public ModelCommand class ColorControlMoveToHue : public ModelCommand { public: - ColorControlMoveToHue() : ModelCommand("move-to-hue", COLOR_CONTROL_CLUSTER_ID) + ColorControlMoveToHue() : ModelCommand("move-to-hue", kColorControlClusterId, 0x00) { AddArgument("hue", 0, UINT8_MAX, &mHue); AddArgument("direction", 0, UINT8_MAX, &mDirection); @@ -617,6 +1167,13 @@ class ColorControlMoveToHue : public ModelCommand mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mHue; uint8_t mDirection; @@ -631,7 +1188,7 @@ class ColorControlMoveToHue : public ModelCommand class ColorControlMoveToHueAndSaturation : public ModelCommand { public: - ColorControlMoveToHueAndSaturation() : ModelCommand("move-to-hue-and-saturation", COLOR_CONTROL_CLUSTER_ID) + ColorControlMoveToHueAndSaturation() : ModelCommand("move-to-hue-and-saturation", kColorControlClusterId, 0x06) { AddArgument("hue", 0, UINT8_MAX, &mHue); AddArgument("saturation", 0, UINT8_MAX, &mSaturation); @@ -646,6 +1203,13 @@ class ColorControlMoveToHueAndSaturation : public ModelCommand mTransitionTime, mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mHue; uint8_t mSaturation; @@ -660,7 +1224,7 @@ class ColorControlMoveToHueAndSaturation : public ModelCommand class ColorControlMoveToSaturation : public ModelCommand { public: - ColorControlMoveToSaturation() : ModelCommand("move-to-saturation", COLOR_CONTROL_CLUSTER_ID) + ColorControlMoveToSaturation() : ModelCommand("move-to-saturation", kColorControlClusterId, 0x03) { AddArgument("saturation", 0, UINT8_MAX, &mSaturation); AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime); @@ -674,6 +1238,13 @@ class ColorControlMoveToSaturation : public ModelCommand mTransitionTime, mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mSaturation; uint16_t mTransitionTime; @@ -687,7 +1258,7 @@ class ColorControlMoveToSaturation : public ModelCommand class ColorControlStepColor : public ModelCommand { public: - ColorControlStepColor() : ModelCommand("step-color", COLOR_CONTROL_CLUSTER_ID) + ColorControlStepColor() : ModelCommand("step-color", kColorControlClusterId, 0x09) { AddArgument("stepX", INT16_MIN, INT16_MAX, &mStepX); AddArgument("stepY", INT16_MIN, INT16_MAX, &mStepY); @@ -702,6 +1273,13 @@ class ColorControlStepColor : public ModelCommand mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: int16_t mStepX; int16_t mStepY; @@ -716,7 +1294,7 @@ class ColorControlStepColor : public ModelCommand class ColorControlStepColorTemperature : public ModelCommand { public: - ColorControlStepColorTemperature() : ModelCommand("step-color-temperature", COLOR_CONTROL_CLUSTER_ID) + ColorControlStepColorTemperature() : ModelCommand("step-color-temperature", kColorControlClusterId, 0x4C) { AddArgument("stepMode", 0, UINT8_MAX, &mStepMode); AddArgument("stepSize", 0, UINT16_MAX, &mStepSize); @@ -734,6 +1312,13 @@ class ColorControlStepColorTemperature : public ModelCommand mColorTemperatureMaximumMireds, mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mStepMode; uint16_t mStepSize; @@ -750,7 +1335,7 @@ class ColorControlStepColorTemperature : public ModelCommand class ColorControlStepHue : public ModelCommand { public: - ColorControlStepHue() : ModelCommand("step-hue", COLOR_CONTROL_CLUSTER_ID) + ColorControlStepHue() : ModelCommand("step-hue", kColorControlClusterId, 0x02) { AddArgument("stepMode", 0, UINT8_MAX, &mStepMode); AddArgument("stepSize", 0, UINT8_MAX, &mStepSize); @@ -765,6 +1350,13 @@ class ColorControlStepHue : public ModelCommand mTransitionTime, mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mStepMode; uint8_t mStepSize; @@ -779,7 +1371,7 @@ class ColorControlStepHue : public ModelCommand class ColorControlStepSaturation : public ModelCommand { public: - ColorControlStepSaturation() : ModelCommand("step-saturation", COLOR_CONTROL_CLUSTER_ID) + ColorControlStepSaturation() : ModelCommand("step-saturation", kColorControlClusterId, 0x05) { AddArgument("stepMode", 0, UINT8_MAX, &mStepMode); AddArgument("stepSize", 0, UINT8_MAX, &mStepSize); @@ -794,6 +1386,13 @@ class ColorControlStepSaturation : public ModelCommand mTransitionTime, mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mStepMode; uint8_t mStepSize; @@ -808,7 +1407,7 @@ class ColorControlStepSaturation : public ModelCommand class ColorControlStopMoveStep : public ModelCommand { public: - ColorControlStopMoveStep() : ModelCommand("stop-move-step", COLOR_CONTROL_CLUSTER_ID) + ColorControlStopMoveStep() : ModelCommand("stop-move-step", kColorControlClusterId, 0x47) { AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask); AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); @@ -820,6 +1419,13 @@ class ColorControlStopMoveStep : public ModelCommand mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mOptionsMask; uint8_t mOptionsOverride; @@ -831,12 +1437,19 @@ class ColorControlStopMoveStep : public ModelCommand class ReadColorControlCurrentHue : public ModelCommand { public: - ReadColorControlCurrentHue() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "current-hue"); } + ReadColorControlCurrentHue() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "current-hue"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadCurrentHueAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -845,7 +1458,7 @@ class ReadColorControlCurrentHue : public ModelCommand class ReadColorControlCurrentSaturation : public ModelCommand { public: - ReadColorControlCurrentSaturation() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlCurrentSaturation() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "current-saturation"); } @@ -854,6 +1467,13 @@ class ReadColorControlCurrentSaturation : public ModelCommand { return encodeColorControlClusterReadCurrentSaturationAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -862,12 +1482,19 @@ class ReadColorControlCurrentSaturation : public ModelCommand class ReadColorControlCurrentX : public ModelCommand { public: - ReadColorControlCurrentX() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "current-x"); } + ReadColorControlCurrentX() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "current-x"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadCurrentXAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -876,12 +1503,19 @@ class ReadColorControlCurrentX : public ModelCommand class ReadColorControlCurrentY : public ModelCommand { public: - ReadColorControlCurrentY() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "current-y"); } + ReadColorControlCurrentY() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "current-y"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadCurrentYAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -890,7 +1524,7 @@ class ReadColorControlCurrentY : public ModelCommand class ReadColorControlColorTemperatureMireds : public ModelCommand { public: - ReadColorControlColorTemperatureMireds() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlColorTemperatureMireds() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "color-temperature-mireds"); } @@ -899,6 +1533,13 @@ class ReadColorControlColorTemperatureMireds : public ModelCommand { return encodeColorControlClusterReadColorTemperatureMiredsAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -907,12 +1548,19 @@ class ReadColorControlColorTemperatureMireds : public ModelCommand class ReadColorControlColorMode : public ModelCommand { public: - ReadColorControlColorMode() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "color-mode"); } + ReadColorControlColorMode() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "color-mode"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadColorModeAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -921,12 +1569,19 @@ class ReadColorControlColorMode : public ModelCommand class ReadColorControlOptions : public ModelCommand { public: - ReadColorControlOptions() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "options"); } + ReadColorControlOptions() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "options"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadOptionsAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -935,7 +1590,7 @@ class ReadColorControlOptions : public ModelCommand class ReadColorControlNumberOfPrimaries : public ModelCommand { public: - ReadColorControlNumberOfPrimaries() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlNumberOfPrimaries() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "number-of-primaries"); } @@ -944,6 +1599,13 @@ class ReadColorControlNumberOfPrimaries : public ModelCommand { return encodeColorControlClusterReadNumberOfPrimariesAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -952,12 +1614,19 @@ class ReadColorControlNumberOfPrimaries : public ModelCommand class ReadColorControlPrimary1X : public ModelCommand { public: - ReadColorControlPrimary1X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary1-x"); } + ReadColorControlPrimary1X() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary1-x"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary1XAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -966,12 +1635,19 @@ class ReadColorControlPrimary1X : public ModelCommand class ReadColorControlPrimary1Y : public ModelCommand { public: - ReadColorControlPrimary1Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary1-y"); } + ReadColorControlPrimary1Y() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary1-y"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary1YAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -980,7 +1656,7 @@ class ReadColorControlPrimary1Y : public ModelCommand class ReadColorControlPrimary1Intensity : public ModelCommand { public: - ReadColorControlPrimary1Intensity() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlPrimary1Intensity() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary1-intensity"); } @@ -989,6 +1665,13 @@ class ReadColorControlPrimary1Intensity : public ModelCommand { return encodeColorControlClusterReadPrimary1IntensityAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -997,12 +1680,19 @@ class ReadColorControlPrimary1Intensity : public ModelCommand class ReadColorControlPrimary2X : public ModelCommand { public: - ReadColorControlPrimary2X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary2-x"); } + ReadColorControlPrimary2X() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary2-x"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary2XAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1011,12 +1701,19 @@ class ReadColorControlPrimary2X : public ModelCommand class ReadColorControlPrimary2Y : public ModelCommand { public: - ReadColorControlPrimary2Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary2-y"); } + ReadColorControlPrimary2Y() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary2-y"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary2YAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1025,7 +1722,7 @@ class ReadColorControlPrimary2Y : public ModelCommand class ReadColorControlPrimary2Intensity : public ModelCommand { public: - ReadColorControlPrimary2Intensity() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlPrimary2Intensity() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary2-intensity"); } @@ -1034,6 +1731,13 @@ class ReadColorControlPrimary2Intensity : public ModelCommand { return encodeColorControlClusterReadPrimary2IntensityAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1042,12 +1746,19 @@ class ReadColorControlPrimary2Intensity : public ModelCommand class ReadColorControlPrimary3X : public ModelCommand { public: - ReadColorControlPrimary3X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary3-x"); } + ReadColorControlPrimary3X() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary3-x"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary3XAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1056,12 +1767,19 @@ class ReadColorControlPrimary3X : public ModelCommand class ReadColorControlPrimary3Y : public ModelCommand { public: - ReadColorControlPrimary3Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary3-y"); } + ReadColorControlPrimary3Y() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary3-y"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary3YAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1070,7 +1788,7 @@ class ReadColorControlPrimary3Y : public ModelCommand class ReadColorControlPrimary3Intensity : public ModelCommand { public: - ReadColorControlPrimary3Intensity() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlPrimary3Intensity() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary3-intensity"); } @@ -1079,6 +1797,13 @@ class ReadColorControlPrimary3Intensity : public ModelCommand { return encodeColorControlClusterReadPrimary3IntensityAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1087,12 +1812,19 @@ class ReadColorControlPrimary3Intensity : public ModelCommand class ReadColorControlPrimary4X : public ModelCommand { public: - ReadColorControlPrimary4X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary4-x"); } + ReadColorControlPrimary4X() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary4-x"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary4XAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1101,13 +1833,20 @@ class ReadColorControlPrimary4X : public ModelCommand class ReadColorControlPrimary4Y : public ModelCommand { public: - ReadColorControlPrimary4Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary4-y"); } + ReadColorControlPrimary4Y() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary4-y"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary4YAttribute(buffer->Start(), bufferSize, endPointId); } -}; + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } +}; /* * Attribute Primary4Intensity @@ -1115,7 +1854,7 @@ class ReadColorControlPrimary4Y : public ModelCommand class ReadColorControlPrimary4Intensity : public ModelCommand { public: - ReadColorControlPrimary4Intensity() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlPrimary4Intensity() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary4-intensity"); } @@ -1124,6 +1863,13 @@ class ReadColorControlPrimary4Intensity : public ModelCommand { return encodeColorControlClusterReadPrimary4IntensityAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1132,12 +1878,19 @@ class ReadColorControlPrimary4Intensity : public ModelCommand class ReadColorControlPrimary5X : public ModelCommand { public: - ReadColorControlPrimary5X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary5-x"); } + ReadColorControlPrimary5X() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary5-x"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary5XAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1146,12 +1899,19 @@ class ReadColorControlPrimary5X : public ModelCommand class ReadColorControlPrimary5Y : public ModelCommand { public: - ReadColorControlPrimary5Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary5-y"); } + ReadColorControlPrimary5Y() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary5-y"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary5YAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1160,7 +1920,7 @@ class ReadColorControlPrimary5Y : public ModelCommand class ReadColorControlPrimary5Intensity : public ModelCommand { public: - ReadColorControlPrimary5Intensity() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlPrimary5Intensity() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary5-intensity"); } @@ -1169,6 +1929,13 @@ class ReadColorControlPrimary5Intensity : public ModelCommand { return encodeColorControlClusterReadPrimary5IntensityAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1177,12 +1944,19 @@ class ReadColorControlPrimary5Intensity : public ModelCommand class ReadColorControlPrimary6X : public ModelCommand { public: - ReadColorControlPrimary6X() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary6-x"); } + ReadColorControlPrimary6X() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary6-x"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary6XAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1191,12 +1965,19 @@ class ReadColorControlPrimary6X : public ModelCommand class ReadColorControlPrimary6Y : public ModelCommand { public: - ReadColorControlPrimary6Y() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) { AddArgument("attr-name", "primary6-y"); } + ReadColorControlPrimary6Y() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary6-y"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeColorControlClusterReadPrimary6YAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1205,7 +1986,7 @@ class ReadColorControlPrimary6Y : public ModelCommand class ReadColorControlPrimary6Intensity : public ModelCommand { public: - ReadColorControlPrimary6Intensity() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlPrimary6Intensity() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "primary6-intensity"); } @@ -1214,6 +1995,13 @@ class ReadColorControlPrimary6Intensity : public ModelCommand { return encodeColorControlClusterReadPrimary6IntensityAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1222,7 +2010,7 @@ class ReadColorControlPrimary6Intensity : public ModelCommand class ReadColorControlEnhancedCurrentHue : public ModelCommand { public: - ReadColorControlEnhancedCurrentHue() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlEnhancedCurrentHue() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "enhanced-current-hue"); } @@ -1231,6 +2019,13 @@ class ReadColorControlEnhancedCurrentHue : public ModelCommand { return encodeColorControlClusterReadEnhancedCurrentHueAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1239,7 +2034,7 @@ class ReadColorControlEnhancedCurrentHue : public ModelCommand class ReadColorControlEnhancedColorMode : public ModelCommand { public: - ReadColorControlEnhancedColorMode() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlEnhancedColorMode() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "enhanced-color-mode"); } @@ -1248,6 +2043,13 @@ class ReadColorControlEnhancedColorMode : public ModelCommand { return encodeColorControlClusterReadEnhancedColorModeAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1256,7 +2058,7 @@ class ReadColorControlEnhancedColorMode : public ModelCommand class ReadColorControlColorLoopActive : public ModelCommand { public: - ReadColorControlColorLoopActive() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlColorLoopActive() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "color-loop-active"); } @@ -1265,6 +2067,13 @@ class ReadColorControlColorLoopActive : public ModelCommand { return encodeColorControlClusterReadColorLoopActiveAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1273,7 +2082,7 @@ class ReadColorControlColorLoopActive : public ModelCommand class ReadColorControlColorLoopDirection : public ModelCommand { public: - ReadColorControlColorLoopDirection() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlColorLoopDirection() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "color-loop-direction"); } @@ -1282,6 +2091,13 @@ class ReadColorControlColorLoopDirection : public ModelCommand { return encodeColorControlClusterReadColorLoopDirectionAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1290,7 +2106,7 @@ class ReadColorControlColorLoopDirection : public ModelCommand class ReadColorControlColorLoopTime : public ModelCommand { public: - ReadColorControlColorLoopTime() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlColorLoopTime() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "color-loop-time"); } @@ -1299,6 +2115,13 @@ class ReadColorControlColorLoopTime : public ModelCommand { return encodeColorControlClusterReadColorLoopTimeAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1307,7 +2130,7 @@ class ReadColorControlColorLoopTime : public ModelCommand class ReadColorControlColorLoopStartEnhancedHue : public ModelCommand { public: - ReadColorControlColorLoopStartEnhancedHue() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlColorLoopStartEnhancedHue() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "color-loop-start-enhanced-hue"); } @@ -1316,6 +2139,13 @@ class ReadColorControlColorLoopStartEnhancedHue : public ModelCommand { return encodeColorControlClusterReadColorLoopStartEnhancedHueAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1324,7 +2154,7 @@ class ReadColorControlColorLoopStartEnhancedHue : public ModelCommand class ReadColorControlColorLoopStoredEnhancedHue : public ModelCommand { public: - ReadColorControlColorLoopStoredEnhancedHue() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlColorLoopStoredEnhancedHue() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "color-loop-stored-enhanced-hue"); } @@ -1333,6 +2163,13 @@ class ReadColorControlColorLoopStoredEnhancedHue : public ModelCommand { return encodeColorControlClusterReadColorLoopStoredEnhancedHueAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1341,7 +2178,7 @@ class ReadColorControlColorLoopStoredEnhancedHue : public ModelCommand class ReadColorControlColorCapabilities : public ModelCommand { public: - ReadColorControlColorCapabilities() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlColorCapabilities() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "color-capabilities"); } @@ -1350,6 +2187,13 @@ class ReadColorControlColorCapabilities : public ModelCommand { return encodeColorControlClusterReadColorCapabilitiesAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1358,7 +2202,7 @@ class ReadColorControlColorCapabilities : public ModelCommand class ReadColorControlColorTempPhysicalMinMireds : public ModelCommand { public: - ReadColorControlColorTempPhysicalMinMireds() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlColorTempPhysicalMinMireds() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "color-temp-physical-min-mireds"); } @@ -1367,6 +2211,13 @@ class ReadColorControlColorTempPhysicalMinMireds : public ModelCommand { return encodeColorControlClusterReadColorTempPhysicalMinMiredsAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1375,7 +2226,7 @@ class ReadColorControlColorTempPhysicalMinMireds : public ModelCommand class ReadColorControlColorTempPhysicalMaxMireds : public ModelCommand { public: - ReadColorControlColorTempPhysicalMaxMireds() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlColorTempPhysicalMaxMireds() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "color-temp-physical-max-mireds"); } @@ -1384,6 +2235,13 @@ class ReadColorControlColorTempPhysicalMaxMireds : public ModelCommand { return encodeColorControlClusterReadColorTempPhysicalMaxMiredsAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1392,7 +2250,7 @@ class ReadColorControlColorTempPhysicalMaxMireds : public ModelCommand class ReadColorControlCoupleColorTempToLevelMinMireds : public ModelCommand { public: - ReadColorControlCoupleColorTempToLevelMinMireds() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlCoupleColorTempToLevelMinMireds() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "couple-color-temp-to-level-min-mireds"); } @@ -1401,6 +2259,13 @@ class ReadColorControlCoupleColorTempToLevelMinMireds : public ModelCommand { return encodeColorControlClusterReadCoupleColorTempToLevelMinMiredsAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -1409,7 +2274,7 @@ class ReadColorControlCoupleColorTempToLevelMinMireds : public ModelCommand class ReadColorControlStartUpColorTemperatureMireds : public ModelCommand { public: - ReadColorControlStartUpColorTemperatureMireds() : ModelCommand("read", COLOR_CONTROL_CLUSTER_ID) + ReadColorControlStartUpColorTemperatureMireds() : ModelCommand("read", kColorControlClusterId, 0x00) { AddArgument("attr-name", "start-up-color-temperature-mireds"); } @@ -1418,11 +2283,44 @@ class ReadColorControlStartUpColorTemperatureMireds : public ModelCommand { return encodeColorControlClusterReadStartUpColorTemperatureMiredsAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /*----------------------------------------------------------------------------*\ | Cluster DoorLock | 0x0101 | |------------------------------------------------------------------------------| +| Responses: | | +| * ClearAllPINCodesResponse | 0x08 | +| * ClearAllRFIDCodesResponse | 0x19 | +| * ClearHolidayScheduleResponse | 0x13 | +| * ClearPINCodeResponse | 0x07 | +| * ClearRFIDCodeResponse | 0x18 | +| * ClearWeekdayScheduleResponse | 0x0D | +| * ClearYearDayScheduleResponse | 0x10 | +| * GetHolidayScheduleResponse | 0x12 | +| * GetLogRecordResponse | 0x04 | +| * GetPINCodeResponse | 0x06 | +| * GetRFIDCodeResponse | 0x17 | +| * GetUserTypeResponse | 0x15 | +| * GetWeekdayScheduleResponse | 0x0C | +| * GetYearDayScheduleResponse | 0x0F | +| * LockDoorResponse | 0x00 | +| * SetHolidayScheduleResponse | 0x11 | +| * SetPINCodeResponse | 0x05 | +| * SetRFIDCodeResponse | 0x16 | +| * SetUserTypeResponse | 0x14 | +| * SetWeekdayScheduleResponse | 0x0B | +| * SetYearDayScheduleResponse | 0x0E | +| * UnlockDoorResponse | 0x01 | +| * UnlockWithTimeoutResponse | 0x03 | +| | | +|------------------------------------------------------------------------------| | Commands: | | | * ClearAllPINCodes | 0x08 | | * ClearAllRFIDCodes | 0x19 | @@ -1447,36 +2345,457 @@ class ReadColorControlStartUpColorTemperatureMireds : public ModelCommand | * SetYearDaySchedule | 0x0E | | * UnlockDoor | 0x01 | | * UnlockWithTimeout | 0x03 | -| | | |------------------------------------------------------------------------------| -| Attributes:: | | +| Attributes: | | | * LockState | 0x0000 | | * LockType | 0x0001 | | * ActuatorEnabled | 0x0002 | \*----------------------------------------------------------------------------*/ +/* + * Command Response ClearAllPINCodesResponse + */ +class ClearAllPINCodesResponse : public ModelCommandResponse +{ +public: + ClearAllPINCodesResponse() : ModelCommandResponse(0x08) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "ClearAllPINCodesResponse (0x08):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response ClearAllRFIDCodesResponse + */ +class ClearAllRFIDCodesResponse : public ModelCommandResponse +{ +public: + ClearAllRFIDCodesResponse() : ModelCommandResponse(0x19) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "ClearAllRFIDCodesResponse (0x19):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response ClearHolidayScheduleResponse + */ +class ClearHolidayScheduleResponse : public ModelCommandResponse +{ +public: + ClearHolidayScheduleResponse() : ModelCommandResponse(0x13) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "ClearHolidayScheduleResponse (0x13):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response ClearPINCodeResponse + */ +class ClearPINCodeResponse : public ModelCommandResponse +{ +public: + ClearPINCodeResponse() : ModelCommandResponse(0x07) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "ClearPINCodeResponse (0x07):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response ClearRFIDCodeResponse + */ +class ClearRFIDCodeResponse : public ModelCommandResponse +{ +public: + ClearRFIDCodeResponse() : ModelCommandResponse(0x18) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "ClearRFIDCodeResponse (0x18):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response ClearWeekdayScheduleResponse + */ +class ClearWeekdayScheduleResponse : public ModelCommandResponse +{ +public: + ClearWeekdayScheduleResponse() : ModelCommandResponse(0x0D) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "ClearWeekdayScheduleResponse (0x0D):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response ClearYearDayScheduleResponse + */ +class ClearYearDayScheduleResponse : public ModelCommandResponse +{ +public: + ClearYearDayScheduleResponse() : ModelCommandResponse(0x10) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "ClearYearDayScheduleResponse (0x10):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response GetHolidayScheduleResponse + */ +class GetHolidayScheduleResponse : public ModelCommandResponse +{ +public: + GetHolidayScheduleResponse() : ModelCommandResponse(0x12) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "GetHolidayScheduleResponse (0x12):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "holidayScheduleId", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%08x", "localStartTime", chip::Encoding::LittleEndian::Read32(message)); // uint32 + ChipLogProgress(chipTool, " %s: 0x%08x", "localEndTime", chip::Encoding::LittleEndian::Read32(message)); // uint32 + ChipLogProgress(chipTool, " %s: 0x%02x", "operatingModeDuringHoliday", chip::Encoding::Read8(message)); // DrlkOperMode + + return true; + } +}; + +/* + * Command Response GetLogRecordResponse + */ +class GetLogRecordResponse : public ModelCommandResponse +{ +public: + GetLogRecordResponse() : ModelCommandResponse(0x04) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "GetLogRecordResponse (0x04):"); + ChipLogProgress(chipTool, " %s: 0x%04x", "logEntryId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%08x", "timestamp", chip::Encoding::LittleEndian::Read32(message)); // uint32 + ChipLogProgress(chipTool, " %s: 0x%02x", "eventType", chip::Encoding::Read8(message)); // enum8 + ChipLogProgress(chipTool, " %s: 0x%02x", "sourceOperationEvent", chip::Encoding::Read8(message)); // DrlkOperEventSource + ChipLogProgress(chipTool, " %s: 0x%02x", "eventIdOrAlarmCode", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%04x", "userId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "pIN", chip::Encoding::Read8(message)); // octstr + + return true; + } +}; + +/* + * Command Response GetPINCodeResponse + */ +class GetPINCodeResponse : public ModelCommandResponse +{ +public: + GetPINCodeResponse() : ModelCommandResponse(0x06) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "GetPINCodeResponse (0x06):"); + ChipLogProgress(chipTool, " %s: 0x%04x", "userId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "userStatus", chip::Encoding::Read8(message)); // DrlkUserStatus + ChipLogProgress(chipTool, " %s: 0x%02x", "userType", chip::Encoding::Read8(message)); // DrlkUserType + ChipLogProgress(chipTool, " %s: 0x%02x", "code", chip::Encoding::Read8(message)); // octstr + + return true; + } +}; + +/* + * Command Response GetRFIDCodeResponse + */ +class GetRFIDCodeResponse : public ModelCommandResponse +{ +public: + GetRFIDCodeResponse() : ModelCommandResponse(0x17) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "GetRFIDCodeResponse (0x17):"); + ChipLogProgress(chipTool, " %s: 0x%04x", "userId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "userStatus", chip::Encoding::Read8(message)); // DrlkUserStatus + ChipLogProgress(chipTool, " %s: 0x%02x", "userType", chip::Encoding::Read8(message)); // DrlkUserType + ChipLogProgress(chipTool, " %s: 0x%02x", "rFIdCode", chip::Encoding::Read8(message)); // octstr + + return true; + } +}; + +/* + * Command Response GetUserTypeResponse + */ +class GetUserTypeResponse : public ModelCommandResponse +{ +public: + GetUserTypeResponse() : ModelCommandResponse(0x15) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "GetUserTypeResponse (0x15):"); + ChipLogProgress(chipTool, " %s: 0x%04x", "userId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "userType", chip::Encoding::Read8(message)); // DrlkUserType + + return true; + } +}; + +/* + * Command Response GetWeekdayScheduleResponse + */ +class GetWeekdayScheduleResponse : public ModelCommandResponse +{ +public: + GetWeekdayScheduleResponse() : ModelCommandResponse(0x0C) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "GetWeekdayScheduleResponse (0x0C):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "scheduleId", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%04x", "userId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%02x", "daysMask", chip::Encoding::Read8(message)); // DrlkDaysMask + ChipLogProgress(chipTool, " %s: 0x%02x", "startHour", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%02x", "startMinute", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%02x", "endHour", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%02x", "endMinute", chip::Encoding::Read8(message)); // uint8 + + return true; + } +}; + +/* + * Command Response GetYearDayScheduleResponse + */ +class GetYearDayScheduleResponse : public ModelCommandResponse +{ +public: + GetYearDayScheduleResponse() : ModelCommandResponse(0x0F) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "GetYearDayScheduleResponse (0x0F):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "scheduleId", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%04x", "userId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%08x", "localStartTime", chip::Encoding::LittleEndian::Read32(message)); // uint32 + ChipLogProgress(chipTool, " %s: 0x%08x", "localEndTime", chip::Encoding::LittleEndian::Read32(message)); // uint32 + + return true; + } +}; + +/* + * Command Response LockDoorResponse + */ +class LockDoorResponse : public ModelCommandResponse +{ +public: + LockDoorResponse() : ModelCommandResponse(0x00) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "LockDoorResponse (0x00):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + + return true; + } +}; + +/* + * Command Response SetHolidayScheduleResponse + */ +class SetHolidayScheduleResponse : public ModelCommandResponse +{ +public: + SetHolidayScheduleResponse() : ModelCommandResponse(0x11) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "SetHolidayScheduleResponse (0x11):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response SetPINCodeResponse + */ +class SetPINCodeResponse : public ModelCommandResponse +{ +public: + SetPINCodeResponse() : ModelCommandResponse(0x05) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "SetPINCodeResponse (0x05):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkSetCodeStatus + + return true; + } +}; + +/* + * Command Response SetRFIDCodeResponse + */ +class SetRFIDCodeResponse : public ModelCommandResponse +{ +public: + SetRFIDCodeResponse() : ModelCommandResponse(0x16) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "SetRFIDCodeResponse (0x16):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkSetCodeStatus + + return true; + } +}; + +/* + * Command Response SetUserTypeResponse + */ +class SetUserTypeResponse : public ModelCommandResponse +{ +public: + SetUserTypeResponse() : ModelCommandResponse(0x14) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "SetUserTypeResponse (0x14):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response SetWeekdayScheduleResponse + */ +class SetWeekdayScheduleResponse : public ModelCommandResponse +{ +public: + SetWeekdayScheduleResponse() : ModelCommandResponse(0x0B) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "SetWeekdayScheduleResponse (0x0B):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response SetYearDayScheduleResponse + */ +class SetYearDayScheduleResponse : public ModelCommandResponse +{ +public: + SetYearDayScheduleResponse() : ModelCommandResponse(0x0E) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "SetYearDayScheduleResponse (0x0E):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // DrlkPassFailStatus + + return true; + } +}; + +/* + * Command Response UnlockDoorResponse + */ +class UnlockDoorResponse : public ModelCommandResponse +{ +public: + UnlockDoorResponse() : ModelCommandResponse(0x01) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "UnlockDoorResponse (0x01):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + + return true; + } +}; + +/* + * Command Response UnlockWithTimeoutResponse + */ +class UnlockWithTimeoutResponse : public ModelCommandResponse +{ +public: + UnlockWithTimeoutResponse() : ModelCommandResponse(0x03) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "UnlockWithTimeoutResponse (0x03):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + + return true; + } +}; + /* * Command ClearAllPINCodes */ class DoorLockClearAllPINCodes : public ModelCommand { public: - DoorLockClearAllPINCodes() : ModelCommand("clear-all-pincodes", DOOR_LOCK_CLUSTER_ID) {} + DoorLockClearAllPINCodes() : ModelCommand("clear-all-pincodes", kDoorLockClusterId, 0x08) {} uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterClearAllPINCodesCommand(buffer->Start(), bufferSize, endPointId); } - // Cluster Specific Response: ClearAllPINCodesResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "ClearAllPINCodesResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: ClearAllPINCodesResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ClearAllPINCodesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } }; @@ -1486,22 +2805,25 @@ class DoorLockClearAllPINCodes : public ModelCommand class DoorLockClearAllRFIDCodes : public ModelCommand { public: - DoorLockClearAllRFIDCodes() : ModelCommand("clear-all-rfidcodes", DOOR_LOCK_CLUSTER_ID) {} + DoorLockClearAllRFIDCodes() : ModelCommand("clear-all-rfidcodes", kDoorLockClusterId, 0x19) {} uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterClearAllRFIDCodesCommand(buffer->Start(), bufferSize, endPointId); } - // Cluster Specific Response: ClearAllRFIDCodesResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "ClearAllRFIDCodesResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: ClearAllRFIDCodesResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ClearAllRFIDCodesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } }; @@ -1511,7 +2833,7 @@ class DoorLockClearAllRFIDCodes : public ModelCommand class DoorLockClearHolidaySchedule : public ModelCommand { public: - DoorLockClearHolidaySchedule() : ModelCommand("clear-holiday-schedule", DOOR_LOCK_CLUSTER_ID) + DoorLockClearHolidaySchedule() : ModelCommand("clear-holiday-schedule", kDoorLockClusterId, 0x13) { AddArgument("holidayScheduleID", 0, UINT8_MAX, &mHolidayScheduleID); } @@ -1521,15 +2843,18 @@ class DoorLockClearHolidaySchedule : public ModelCommand return encodeDoorLockClusterClearHolidayScheduleCommand(buffer->Start(), bufferSize, endPointId, mHolidayScheduleID); } - // Cluster Specific Response: ClearHolidayScheduleResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "ClearHolidayScheduleResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: ClearHolidayScheduleResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ClearHolidayScheduleResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1542,22 +2867,28 @@ class DoorLockClearHolidaySchedule : public ModelCommand class DoorLockClearPINCode : public ModelCommand { public: - DoorLockClearPINCode() : ModelCommand("clear-pincode", DOOR_LOCK_CLUSTER_ID) { AddArgument("userID", 0, UINT16_MAX, &mUserID); } + DoorLockClearPINCode() : ModelCommand("clear-pincode", kDoorLockClusterId, 0x07) + { + AddArgument("userID", 0, UINT16_MAX, &mUserID); + } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterClearPINCodeCommand(buffer->Start(), bufferSize, endPointId, mUserID); } - // Cluster Specific Response: ClearPINCodeResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "ClearPINCodeResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: ClearPINCodeResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ClearPINCodeResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1570,7 +2901,7 @@ class DoorLockClearPINCode : public ModelCommand class DoorLockClearRFIDCode : public ModelCommand { public: - DoorLockClearRFIDCode() : ModelCommand("clear-rfidcode", DOOR_LOCK_CLUSTER_ID) + DoorLockClearRFIDCode() : ModelCommand("clear-rfidcode", kDoorLockClusterId, 0x18) { AddArgument("userID", 0, UINT16_MAX, &mUserID); } @@ -1580,15 +2911,18 @@ class DoorLockClearRFIDCode : public ModelCommand return encodeDoorLockClusterClearRFIDCodeCommand(buffer->Start(), bufferSize, endPointId, mUserID); } - // Cluster Specific Response: ClearRFIDCodeResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "ClearRFIDCodeResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: ClearRFIDCodeResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ClearRFIDCodeResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1601,7 +2935,7 @@ class DoorLockClearRFIDCode : public ModelCommand class DoorLockClearWeekdaySchedule : public ModelCommand { public: - DoorLockClearWeekdaySchedule() : ModelCommand("clear-weekday-schedule", DOOR_LOCK_CLUSTER_ID) + DoorLockClearWeekdaySchedule() : ModelCommand("clear-weekday-schedule", kDoorLockClusterId, 0x0D) { AddArgument("scheduleID", 0, UINT8_MAX, &mScheduleID); AddArgument("userID", 0, UINT16_MAX, &mUserID); @@ -1612,15 +2946,18 @@ class DoorLockClearWeekdaySchedule : public ModelCommand return encodeDoorLockClusterClearWeekdayScheduleCommand(buffer->Start(), bufferSize, endPointId, mScheduleID, mUserID); } - // Cluster Specific Response: ClearWeekdayScheduleResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "ClearWeekdayScheduleResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: ClearWeekdayScheduleResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ClearWeekdayScheduleResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1634,7 +2971,7 @@ class DoorLockClearWeekdaySchedule : public ModelCommand class DoorLockClearYearDaySchedule : public ModelCommand { public: - DoorLockClearYearDaySchedule() : ModelCommand("clear-year-day-schedule", DOOR_LOCK_CLUSTER_ID) + DoorLockClearYearDaySchedule() : ModelCommand("clear-year-day-schedule", kDoorLockClusterId, 0x10) { AddArgument("scheduleID", 0, UINT8_MAX, &mScheduleID); AddArgument("userID", 0, UINT16_MAX, &mUserID); @@ -1645,15 +2982,18 @@ class DoorLockClearYearDaySchedule : public ModelCommand return encodeDoorLockClusterClearYearDayScheduleCommand(buffer->Start(), bufferSize, endPointId, mScheduleID, mUserID); } - // Cluster Specific Response: ClearYearDayScheduleResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "ClearYearDayScheduleResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: ClearYearDayScheduleResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ClearYearDayScheduleResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1667,7 +3007,7 @@ class DoorLockClearYearDaySchedule : public ModelCommand class DoorLockGetHolidaySchedule : public ModelCommand { public: - DoorLockGetHolidaySchedule() : ModelCommand("get-holiday-schedule", DOOR_LOCK_CLUSTER_ID) + DoorLockGetHolidaySchedule() : ModelCommand("get-holiday-schedule", kDoorLockClusterId, 0x12) { AddArgument("holidayScheduleID", 0, UINT8_MAX, &mHolidayScheduleID); } @@ -1677,23 +3017,18 @@ class DoorLockGetHolidaySchedule : public ModelCommand return encodeDoorLockClusterGetHolidayScheduleCommand(buffer->Start(), bufferSize, endPointId, mHolidayScheduleID); } - // Cluster Specific Response: GetHolidayScheduleResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t holidayScheduleID = chip::Encoding::Read8(message); - uint8_t status = chip::Encoding::Read8(message); - uint32_t localStartTime = chip::Encoding::LittleEndian::Read32(message); - uint32_t localEndTime = chip::Encoding::LittleEndian::Read32(message); - uint8_t operatingModeDuringHoliday = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "GetHolidayScheduleResponse:"); - ChipLogProgress(chipTool, " holidayScheduleID: 0x%02x", holidayScheduleID); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " localStartTime: 0x%08x", localStartTime); - ChipLogProgress(chipTool, " localEndTime: 0x%08x", localEndTime); - ChipLogProgress(chipTool, " operatingModeDuringHoliday: 0x%02x", operatingModeDuringHoliday); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: GetHolidayScheduleResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + GetHolidayScheduleResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1706,7 +3041,7 @@ class DoorLockGetHolidaySchedule : public ModelCommand class DoorLockGetLogRecord : public ModelCommand { public: - DoorLockGetLogRecord() : ModelCommand("get-log-record", DOOR_LOCK_CLUSTER_ID) + DoorLockGetLogRecord() : ModelCommand("get-log-record", kDoorLockClusterId, 0x04) { AddArgument("logIndex", 0, UINT16_MAX, &mLogIndex); } @@ -1716,27 +3051,18 @@ class DoorLockGetLogRecord : public ModelCommand return encodeDoorLockClusterGetLogRecordCommand(buffer->Start(), bufferSize, endPointId, mLogIndex); } - // Cluster Specific Response: GetLogRecordResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint16_t logEntryID = chip::Encoding::LittleEndian::Read16(message); - uint32_t timestamp = chip::Encoding::LittleEndian::Read32(message); - uint8_t eventType = chip::Encoding::Read8(message); - uint8_t sourceOperationEvent = chip::Encoding::Read8(message); - uint8_t eventIDOrAlarmCode = chip::Encoding::Read8(message); - uint16_t userID = chip::Encoding::LittleEndian::Read16(message); - uint8_t msgLen = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "GetLogRecordResponse:"); - ChipLogProgress(chipTool, " logEntryID: 0x%04x", logEntryID); - ChipLogProgress(chipTool, " timestamp: 0x%08x", timestamp); - ChipLogProgress(chipTool, " eventType: 0x%02x", eventType); - ChipLogProgress(chipTool, " sourceOperationEvent: 0x%02x", sourceOperationEvent); - ChipLogProgress(chipTool, " eventIDOrAlarmCode: 0x%02x", eventIDOrAlarmCode); - ChipLogProgress(chipTool, " userID: 0x%04x", userID); - ChipLogProgress(chipTool, " pIN len: 0x%02x", msgLen); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: GetLogRecordResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + GetLogRecordResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1749,28 +3075,25 @@ class DoorLockGetLogRecord : public ModelCommand class DoorLockGetPINCode : public ModelCommand { public: - DoorLockGetPINCode() : ModelCommand("get-pincode", DOOR_LOCK_CLUSTER_ID) { AddArgument("userID", 0, UINT16_MAX, &mUserID); } + DoorLockGetPINCode() : ModelCommand("get-pincode", kDoorLockClusterId, 0x06) { AddArgument("userID", 0, UINT16_MAX, &mUserID); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterGetPINCodeCommand(buffer->Start(), bufferSize, endPointId, mUserID); } - // Cluster Specific Response: GetPINCodeResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint16_t userID = chip::Encoding::LittleEndian::Read16(message); - uint8_t userStatus = chip::Encoding::Read8(message); - uint8_t userType = chip::Encoding::Read8(message); - uint8_t msgLen = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "GetPINCodeResponse:"); - ChipLogProgress(chipTool, " userID: 0x%04x", userID); - ChipLogProgress(chipTool, " userStatus: 0x%02x", userStatus); - ChipLogProgress(chipTool, " userType: 0x%02x", userType); - ChipLogProgress(chipTool, " code len: 0x%02x", msgLen); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: GetPINCodeResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + GetPINCodeResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1783,28 +3106,28 @@ class DoorLockGetPINCode : public ModelCommand class DoorLockGetRFIDCode : public ModelCommand { public: - DoorLockGetRFIDCode() : ModelCommand("get-rfidcode", DOOR_LOCK_CLUSTER_ID) { AddArgument("userID", 0, UINT16_MAX, &mUserID); } + DoorLockGetRFIDCode() : ModelCommand("get-rfidcode", kDoorLockClusterId, 0x17) + { + AddArgument("userID", 0, UINT16_MAX, &mUserID); + } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterGetRFIDCodeCommand(buffer->Start(), bufferSize, endPointId, mUserID); } - // Cluster Specific Response: GetRFIDCodeResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint16_t userID = chip::Encoding::LittleEndian::Read16(message); - uint8_t userStatus = chip::Encoding::Read8(message); - uint8_t userType = chip::Encoding::Read8(message); - uint8_t msgLen = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "GetRFIDCodeResponse:"); - ChipLogProgress(chipTool, " userID: 0x%04x", userID); - ChipLogProgress(chipTool, " userStatus: 0x%02x", userStatus); - ChipLogProgress(chipTool, " userType: 0x%02x", userType); - ChipLogProgress(chipTool, " rFIDCode len: 0x%02x", msgLen); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: GetRFIDCodeResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + GetRFIDCodeResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1817,24 +3140,28 @@ class DoorLockGetRFIDCode : public ModelCommand class DoorLockGetUserType : public ModelCommand { public: - DoorLockGetUserType() : ModelCommand("get-user-type", DOOR_LOCK_CLUSTER_ID) { AddArgument("userID", 0, UINT16_MAX, &mUserID); } + DoorLockGetUserType() : ModelCommand("get-user-type", kDoorLockClusterId, 0x15) + { + AddArgument("userID", 0, UINT16_MAX, &mUserID); + } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterGetUserTypeCommand(buffer->Start(), bufferSize, endPointId, mUserID); } - // Cluster Specific Response: GetUserTypeResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint16_t userID = chip::Encoding::LittleEndian::Read16(message); - uint8_t userType = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "GetUserTypeResponse:"); - ChipLogProgress(chipTool, " userID: 0x%04x", userID); - ChipLogProgress(chipTool, " userType: 0x%02x", userType); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: GetUserTypeResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + GetUserTypeResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1847,7 +3174,7 @@ class DoorLockGetUserType : public ModelCommand class DoorLockGetWeekdaySchedule : public ModelCommand { public: - DoorLockGetWeekdaySchedule() : ModelCommand("get-weekday-schedule", DOOR_LOCK_CLUSTER_ID) + DoorLockGetWeekdaySchedule() : ModelCommand("get-weekday-schedule", kDoorLockClusterId, 0x0C) { AddArgument("scheduleID", 0, UINT8_MAX, &mScheduleID); AddArgument("userID", 0, UINT16_MAX, &mUserID); @@ -1858,29 +3185,18 @@ class DoorLockGetWeekdaySchedule : public ModelCommand return encodeDoorLockClusterGetWeekdayScheduleCommand(buffer->Start(), bufferSize, endPointId, mScheduleID, mUserID); } - // Cluster Specific Response: GetWeekdayScheduleResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t scheduleID = chip::Encoding::Read8(message); - uint16_t userID = chip::Encoding::LittleEndian::Read16(message); - uint8_t status = chip::Encoding::Read8(message); - uint8_t daysMask = chip::Encoding::Read8(message); - uint8_t startHour = chip::Encoding::Read8(message); - uint8_t startMinute = chip::Encoding::Read8(message); - uint8_t endHour = chip::Encoding::Read8(message); - uint8_t endMinute = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "GetWeekdayScheduleResponse:"); - ChipLogProgress(chipTool, " scheduleID: 0x%02x", scheduleID); - ChipLogProgress(chipTool, " userID: 0x%04x", userID); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " daysMask: 0x%02x", daysMask); - ChipLogProgress(chipTool, " startHour: 0x%02x", startHour); - ChipLogProgress(chipTool, " startMinute: 0x%02x", startMinute); - ChipLogProgress(chipTool, " endHour: 0x%02x", endHour); - ChipLogProgress(chipTool, " endMinute: 0x%02x", endMinute); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: GetWeekdayScheduleResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + GetWeekdayScheduleResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1894,7 +3210,7 @@ class DoorLockGetWeekdaySchedule : public ModelCommand class DoorLockGetYearDaySchedule : public ModelCommand { public: - DoorLockGetYearDaySchedule() : ModelCommand("get-year-day-schedule", DOOR_LOCK_CLUSTER_ID) + DoorLockGetYearDaySchedule() : ModelCommand("get-year-day-schedule", kDoorLockClusterId, 0x0F) { AddArgument("scheduleID", 0, UINT8_MAX, &mScheduleID); AddArgument("userID", 0, UINT16_MAX, &mUserID); @@ -1905,23 +3221,18 @@ class DoorLockGetYearDaySchedule : public ModelCommand return encodeDoorLockClusterGetYearDayScheduleCommand(buffer->Start(), bufferSize, endPointId, mScheduleID, mUserID); } - // Cluster Specific Response: GetYearDayScheduleResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t scheduleID = chip::Encoding::Read8(message); - uint16_t userID = chip::Encoding::LittleEndian::Read16(message); - uint8_t status = chip::Encoding::Read8(message); - uint32_t localStartTime = chip::Encoding::LittleEndian::Read32(message); - uint32_t localEndTime = chip::Encoding::LittleEndian::Read32(message); - - ChipLogProgress(chipTool, "GetYearDayScheduleResponse:"); - ChipLogProgress(chipTool, " scheduleID: 0x%02x", scheduleID); - ChipLogProgress(chipTool, " userID: 0x%04x", userID); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " localStartTime: 0x%08x", localStartTime); - ChipLogProgress(chipTool, " localEndTime: 0x%08x", localEndTime); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: GetYearDayScheduleResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + GetYearDayScheduleResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1935,22 +3246,25 @@ class DoorLockGetYearDaySchedule : public ModelCommand class DoorLockLockDoor : public ModelCommand { public: - DoorLockLockDoor() : ModelCommand("lock-door", DOOR_LOCK_CLUSTER_ID) { AddArgument("pINOrRFIDCode", &mPINOrRFIDCode); } + DoorLockLockDoor() : ModelCommand("lock-door", kDoorLockClusterId, 0x00) { AddArgument("pINOrRFIDCode", &mPINOrRFIDCode); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterLockDoorCommand(buffer->Start(), bufferSize, endPointId, mPINOrRFIDCode); } - // Cluster Specific Response: LockDoorResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "LockDoorResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: LockDoorResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + LockDoorResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -1963,7 +3277,7 @@ class DoorLockLockDoor : public ModelCommand class DoorLockSetHolidaySchedule : public ModelCommand { public: - DoorLockSetHolidaySchedule() : ModelCommand("set-holiday-schedule", DOOR_LOCK_CLUSTER_ID) + DoorLockSetHolidaySchedule() : ModelCommand("set-holiday-schedule", kDoorLockClusterId, 0x11) { AddArgument("holidayScheduleID", 0, UINT8_MAX, &mHolidayScheduleID); AddArgument("localStartTime", 0, UINT32_MAX, &mLocalStartTime); @@ -1977,15 +3291,18 @@ class DoorLockSetHolidaySchedule : public ModelCommand mLocalStartTime, mLocalEndTime, mOperatingModeDuringHoliday); } - // Cluster Specific Response: SetHolidayScheduleResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "SetHolidayScheduleResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: SetHolidayScheduleResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + SetHolidayScheduleResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2001,7 +3318,7 @@ class DoorLockSetHolidaySchedule : public ModelCommand class DoorLockSetPINCode : public ModelCommand { public: - DoorLockSetPINCode() : ModelCommand("set-pincode", DOOR_LOCK_CLUSTER_ID) + DoorLockSetPINCode() : ModelCommand("set-pincode", kDoorLockClusterId, 0x05) { AddArgument("userID", 0, UINT16_MAX, &mUserID); AddArgument("userStatus", 0, UINT8_MAX, &mUserStatus); @@ -2015,15 +3332,18 @@ class DoorLockSetPINCode : public ModelCommand mPIN); } - // Cluster Specific Response: SetPINCodeResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "SetPINCodeResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: SetPINCodeResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + SetPINCodeResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2039,7 +3359,7 @@ class DoorLockSetPINCode : public ModelCommand class DoorLockSetRFIDCode : public ModelCommand { public: - DoorLockSetRFIDCode() : ModelCommand("set-rfidcode", DOOR_LOCK_CLUSTER_ID) + DoorLockSetRFIDCode() : ModelCommand("set-rfidcode", kDoorLockClusterId, 0x16) { AddArgument("userID", 0, UINT16_MAX, &mUserID); AddArgument("userStatus", 0, UINT8_MAX, &mUserStatus); @@ -2053,15 +3373,18 @@ class DoorLockSetRFIDCode : public ModelCommand mRFIDCode); } - // Cluster Specific Response: SetRFIDCodeResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "SetRFIDCodeResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: SetRFIDCodeResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + SetRFIDCodeResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2077,7 +3400,7 @@ class DoorLockSetRFIDCode : public ModelCommand class DoorLockSetUserType : public ModelCommand { public: - DoorLockSetUserType() : ModelCommand("set-user-type", DOOR_LOCK_CLUSTER_ID) + DoorLockSetUserType() : ModelCommand("set-user-type", kDoorLockClusterId, 0x14) { AddArgument("userID", 0, UINT16_MAX, &mUserID); AddArgument("userType", 0, UINT8_MAX, &mUserType); @@ -2088,15 +3411,18 @@ class DoorLockSetUserType : public ModelCommand return encodeDoorLockClusterSetUserTypeCommand(buffer->Start(), bufferSize, endPointId, mUserID, mUserType); } - // Cluster Specific Response: SetUserTypeResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "SetUserTypeResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: SetUserTypeResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + SetUserTypeResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2110,7 +3436,7 @@ class DoorLockSetUserType : public ModelCommand class DoorLockSetWeekdaySchedule : public ModelCommand { public: - DoorLockSetWeekdaySchedule() : ModelCommand("set-weekday-schedule", DOOR_LOCK_CLUSTER_ID) + DoorLockSetWeekdaySchedule() : ModelCommand("set-weekday-schedule", kDoorLockClusterId, 0x0B) { AddArgument("scheduleID", 0, UINT8_MAX, &mScheduleID); AddArgument("userID", 0, UINT16_MAX, &mUserID); @@ -2127,15 +3453,18 @@ class DoorLockSetWeekdaySchedule : public ModelCommand mDaysMask, mStartHour, mStartMinute, mEndHour, mEndMinute); } - // Cluster Specific Response: SetWeekdayScheduleResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "SetWeekdayScheduleResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: SetWeekdayScheduleResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + SetWeekdayScheduleResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2154,7 +3483,7 @@ class DoorLockSetWeekdaySchedule : public ModelCommand class DoorLockSetYearDaySchedule : public ModelCommand { public: - DoorLockSetYearDaySchedule() : ModelCommand("set-year-day-schedule", DOOR_LOCK_CLUSTER_ID) + DoorLockSetYearDaySchedule() : ModelCommand("set-year-day-schedule", kDoorLockClusterId, 0x0E) { AddArgument("scheduleID", 0, UINT8_MAX, &mScheduleID); AddArgument("userID", 0, UINT16_MAX, &mUserID); @@ -2168,15 +3497,18 @@ class DoorLockSetYearDaySchedule : public ModelCommand mLocalStartTime, mLocalEndTime); } - // Cluster Specific Response: SetYearDayScheduleResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "SetYearDayScheduleResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: SetYearDayScheduleResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + SetYearDayScheduleResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2192,22 +3524,25 @@ class DoorLockSetYearDaySchedule : public ModelCommand class DoorLockUnlockDoor : public ModelCommand { public: - DoorLockUnlockDoor() : ModelCommand("unlock-door", DOOR_LOCK_CLUSTER_ID) { AddArgument("pINOrRFIDCode", &mPINOrRFIDCode); } + DoorLockUnlockDoor() : ModelCommand("unlock-door", kDoorLockClusterId, 0x01) { AddArgument("pINOrRFIDCode", &mPINOrRFIDCode); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterUnlockDoorCommand(buffer->Start(), bufferSize, endPointId, mPINOrRFIDCode); } - // Cluster Specific Response: UnlockDoorResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "UnlockDoorResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: UnlockDoorResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + UnlockDoorResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2220,7 +3555,7 @@ class DoorLockUnlockDoor : public ModelCommand class DoorLockUnlockWithTimeout : public ModelCommand { public: - DoorLockUnlockWithTimeout() : ModelCommand("unlock-with-timeout", DOOR_LOCK_CLUSTER_ID) + DoorLockUnlockWithTimeout() : ModelCommand("unlock-with-timeout", kDoorLockClusterId, 0x03) { AddArgument("timeoutInSeconds", 0, UINT16_MAX, &mTimeoutInSeconds); AddArgument("pINOrRFIDCode", &mPINOrRFIDCode); @@ -2232,15 +3567,18 @@ class DoorLockUnlockWithTimeout : public ModelCommand mPINOrRFIDCode); } - // Cluster Specific Response: UnlockWithTimeoutResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "UnlockWithTimeoutResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: UnlockWithTimeoutResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + UnlockWithTimeoutResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2254,12 +3592,19 @@ class DoorLockUnlockWithTimeout : public ModelCommand class ReadDoorLockLockState : public ModelCommand { public: - ReadDoorLockLockState() : ModelCommand("read", DOOR_LOCK_CLUSTER_ID) { AddArgument("attr-name", "lock-state"); } + ReadDoorLockLockState() : ModelCommand("read", kDoorLockClusterId, 0x00) { AddArgument("attr-name", "lock-state"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterReadLockStateAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -2268,12 +3613,19 @@ class ReadDoorLockLockState : public ModelCommand class ReadDoorLockLockType : public ModelCommand { public: - ReadDoorLockLockType() : ModelCommand("read", DOOR_LOCK_CLUSTER_ID) { AddArgument("attr-name", "lock-type"); } + ReadDoorLockLockType() : ModelCommand("read", kDoorLockClusterId, 0x00) { AddArgument("attr-name", "lock-type"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterReadLockTypeAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -2282,17 +3634,31 @@ class ReadDoorLockLockType : public ModelCommand class ReadDoorLockActuatorEnabled : public ModelCommand { public: - ReadDoorLockActuatorEnabled() : ModelCommand("read", DOOR_LOCK_CLUSTER_ID) { AddArgument("attr-name", "actuator-enabled"); } + ReadDoorLockActuatorEnabled() : ModelCommand("read", kDoorLockClusterId, 0x00) { AddArgument("attr-name", "actuator-enabled"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeDoorLockClusterReadActuatorEnabledAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /*----------------------------------------------------------------------------*\ | Cluster Groups | 0x0004 | |------------------------------------------------------------------------------| +| Responses: | | +| * AddGroupResponse | 0x00 | +| * GetGroupMembershipResponse | 0x02 | +| * RemoveGroupResponse | 0x03 | +| * ViewGroupResponse | 0x01 | +| | | +|------------------------------------------------------------------------------| | Commands: | | | * AddGroup | 0x00 | | * AddGroupIfIdentifying | 0x05 | @@ -2300,19 +3666,96 @@ class ReadDoorLockActuatorEnabled : public ModelCommand | * RemoveAllGroups | 0x04 | | * RemoveGroup | 0x03 | | * ViewGroup | 0x01 | -| | | |------------------------------------------------------------------------------| -| Attributes:: | | +| Attributes: | | | * NameSupport | 0x0000 | \*----------------------------------------------------------------------------*/ +/* + * Command Response AddGroupResponse + */ +class AddGroupResponse : public ModelCommandResponse +{ +public: + AddGroupResponse() : ModelCommandResponse(0x00) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "AddGroupResponse (0x00):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // enum8 + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + + return true; + } +}; + +/* + * Command Response GetGroupMembershipResponse + */ +class GetGroupMembershipResponse : public ModelCommandResponse +{ +public: + GetGroupMembershipResponse() : ModelCommandResponse(0x02) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "GetGroupMembershipResponse (0x02):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "capacity", chip::Encoding::Read8(message)); // uint8 + // uint16_t uint16[] + uint8_t * messageEnd = message + messageLen; + do + { + ChipLogProgress(chipTool, " %s: 0x%04x", "groupList", chip::Encoding::LittleEndian::Read16(message)); // uint16 + } while (message < messageEnd); + + return true; + } +}; + +/* + * Command Response RemoveGroupResponse + */ +class RemoveGroupResponse : public ModelCommandResponse +{ +public: + RemoveGroupResponse() : ModelCommandResponse(0x03) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "RemoveGroupResponse (0x03):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // enum8 + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + + return true; + } +}; + +/* + * Command Response ViewGroupResponse + */ +class ViewGroupResponse : public ModelCommandResponse +{ +public: + ViewGroupResponse() : ModelCommandResponse(0x01) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "ViewGroupResponse (0x01):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // enum8 + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "groupName", chip::Encoding::Read8(message)); // string + + return true; + } +}; + /* * Command AddGroup */ class GroupsAddGroup : public ModelCommand { public: - GroupsAddGroup() : ModelCommand("add-group", GROUPS_CLUSTER_ID) + GroupsAddGroup() : ModelCommand("add-group", kGroupsClusterId, 0x00) { AddArgument("groupId", 0, UINT16_MAX, &mGroupId); AddArgument("groupName", &mGroupName); @@ -2323,17 +3766,18 @@ class GroupsAddGroup : public ModelCommand return encodeGroupsClusterAddGroupCommand(buffer->Start(), bufferSize, endPointId, mGroupId, mGroupName); } - // Cluster Specific Response: AddGroupResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupId = chip::Encoding::LittleEndian::Read16(message); - - ChipLogProgress(chipTool, "AddGroupResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupId: 0x%04x", groupId); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: AddGroupResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + AddGroupResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2347,7 +3791,7 @@ class GroupsAddGroup : public ModelCommand class GroupsAddGroupIfIdentifying : public ModelCommand { public: - GroupsAddGroupIfIdentifying() : ModelCommand("add-group-if-identifying", GROUPS_CLUSTER_ID) + GroupsAddGroupIfIdentifying() : ModelCommand("add-group-if-identifying", kGroupsClusterId, 0x05) { AddArgument("groupId", 0, UINT16_MAX, &mGroupId); AddArgument("groupName", &mGroupName); @@ -2358,6 +3802,13 @@ class GroupsAddGroupIfIdentifying : public ModelCommand return encodeGroupsClusterAddGroupIfIdentifyingCommand(buffer->Start(), bufferSize, endPointId, mGroupId, mGroupName); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint16_t mGroupId; char * mGroupName; @@ -2369,7 +3820,7 @@ class GroupsAddGroupIfIdentifying : public ModelCommand class GroupsGetGroupMembership : public ModelCommand { public: - GroupsGetGroupMembership() : ModelCommand("get-group-membership", GROUPS_CLUSTER_ID) + GroupsGetGroupMembership() : ModelCommand("get-group-membership", kGroupsClusterId, 0x02) { AddArgument("groupList", 0, UINT16_MAX, &mGroupList); } @@ -2379,17 +3830,18 @@ class GroupsGetGroupMembership : public ModelCommand return encodeGroupsClusterGetGroupMembershipCommand(buffer->Start(), bufferSize, endPointId, mGroupList); } - // Cluster Specific Response: GetGroupMembershipResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t capacity = chip::Encoding::Read8(message); - uint16_t groupList = chip::Encoding::LittleEndian::Read16(message); - - ChipLogProgress(chipTool, "GetGroupMembershipResponse:"); - ChipLogProgress(chipTool, " capacity: 0x%02x", capacity); - ChipLogProgress(chipTool, " groupList: 0x%04x", groupList); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: GetGroupMembershipResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + GetGroupMembershipResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2402,12 +3854,19 @@ class GroupsGetGroupMembership : public ModelCommand class GroupsRemoveAllGroups : public ModelCommand { public: - GroupsRemoveAllGroups() : ModelCommand("remove-all-groups", GROUPS_CLUSTER_ID) {} + GroupsRemoveAllGroups() : ModelCommand("remove-all-groups", kGroupsClusterId, 0x04) {} uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterRemoveAllGroupsCommand(buffer->Start(), bufferSize, endPointId); } + + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -2416,24 +3875,25 @@ class GroupsRemoveAllGroups : public ModelCommand class GroupsRemoveGroup : public ModelCommand { public: - GroupsRemoveGroup() : ModelCommand("remove-group", GROUPS_CLUSTER_ID) { AddArgument("groupId", 0, UINT16_MAX, &mGroupId); } + GroupsRemoveGroup() : ModelCommand("remove-group", kGroupsClusterId, 0x03) { AddArgument("groupId", 0, UINT16_MAX, &mGroupId); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterRemoveGroupCommand(buffer->Start(), bufferSize, endPointId, mGroupId); } - // Cluster Specific Response: RemoveGroupResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupId = chip::Encoding::LittleEndian::Read16(message); - - ChipLogProgress(chipTool, "RemoveGroupResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupId: 0x%04x", groupId); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: RemoveGroupResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + RemoveGroupResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2446,26 +3906,25 @@ class GroupsRemoveGroup : public ModelCommand class GroupsViewGroup : public ModelCommand { public: - GroupsViewGroup() : ModelCommand("view-group", GROUPS_CLUSTER_ID) { AddArgument("groupId", 0, UINT16_MAX, &mGroupId); } + GroupsViewGroup() : ModelCommand("view-group", kGroupsClusterId, 0x01) { AddArgument("groupId", 0, UINT16_MAX, &mGroupId); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterViewGroupCommand(buffer->Start(), bufferSize, endPointId, mGroupId); } - // Cluster Specific Response: ViewGroupResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupId = chip::Encoding::LittleEndian::Read16(message); - uint8_t msgLen = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "ViewGroupResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupId: 0x%04x", groupId); - ChipLogProgress(chipTool, " groupName len: 0x%02x", msgLen); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: ViewGroupResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ViewGroupResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2478,33 +3937,60 @@ class GroupsViewGroup : public ModelCommand class ReadGroupsNameSupport : public ModelCommand { public: - ReadGroupsNameSupport() : ModelCommand("read", GROUPS_CLUSTER_ID) { AddArgument("attr-name", "name-support"); } + ReadGroupsNameSupport() : ModelCommand("read", kGroupsClusterId, 0x00) { AddArgument("attr-name", "name-support"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeGroupsClusterReadNameSupportAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /*----------------------------------------------------------------------------*\ | Cluster Identify | 0x0003 | |------------------------------------------------------------------------------| +| Responses: | | +| * IdentifyQueryResponse | 0x00 | +| | | +|------------------------------------------------------------------------------| | Commands: | | | * Identify | 0x00 | | * IdentifyQuery | 0x01 | -| | | |------------------------------------------------------------------------------| -| Attributes:: | | +| Attributes: | | | * IdentifyTime | 0x0000 | \*----------------------------------------------------------------------------*/ +/* + * Command Response IdentifyQueryResponse + */ +class IdentifyQueryResponse : public ModelCommandResponse +{ +public: + IdentifyQueryResponse() : ModelCommandResponse(0x00) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "IdentifyQueryResponse (0x00):"); + ChipLogProgress(chipTool, " %s: 0x%04x", "timeout", chip::Encoding::LittleEndian::Read16(message)); // uint16 + + return true; + } +}; + /* * Command Identify */ class IdentifyIdentify : public ModelCommand { public: - IdentifyIdentify() : ModelCommand("identify", IDENTIFY_CLUSTER_ID) + IdentifyIdentify() : ModelCommand("identify", kIdentifyClusterId, 0x00) { AddArgument("identifyTime", 0, UINT16_MAX, &mIdentifyTime); } @@ -2514,6 +4000,13 @@ class IdentifyIdentify : public ModelCommand return encodeIdentifyClusterIdentifyCommand(buffer->Start(), bufferSize, endPointId, mIdentifyTime); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint16_t mIdentifyTime; }; @@ -2524,22 +4017,25 @@ class IdentifyIdentify : public ModelCommand class IdentifyIdentifyQuery : public ModelCommand { public: - IdentifyIdentifyQuery() : ModelCommand("identify-query", IDENTIFY_CLUSTER_ID) {} + IdentifyIdentifyQuery() : ModelCommand("identify-query", kIdentifyClusterId, 0x01) {} uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeIdentifyClusterIdentifyQueryCommand(buffer->Start(), bufferSize, endPointId); } - // Cluster Specific Response: IdentifyQueryResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint16_t timeout = chip::Encoding::LittleEndian::Read16(message); - - ChipLogProgress(chipTool, "IdentifyQueryResponse:"); - ChipLogProgress(chipTool, " timeout: 0x%04x", timeout); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: IdentifyQueryResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + IdentifyQueryResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } }; @@ -2549,17 +4045,27 @@ class IdentifyIdentifyQuery : public ModelCommand class ReadIdentifyIdentifyTime : public ModelCommand { public: - ReadIdentifyIdentifyTime() : ModelCommand("read", IDENTIFY_CLUSTER_ID) { AddArgument("attr-name", "identify-time"); } + ReadIdentifyIdentifyTime() : ModelCommand("read", kIdentifyClusterId, 0x00) { AddArgument("attr-name", "identify-time"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeIdentifyClusterReadIdentifyTimeAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /*----------------------------------------------------------------------------*\ | Cluster Level | 0x0008 | |------------------------------------------------------------------------------| +| Responses: | | +| | | +|------------------------------------------------------------------------------| | Commands: | | | * Move | 0x01 | | * MoveToLevel | 0x00 | @@ -2569,9 +4075,8 @@ class ReadIdentifyIdentifyTime : public ModelCommand | * StepWithOnOff | 0x06 | | * Stop | 0x03 | | * StopWithOnOff | 0x07 | -| | | |------------------------------------------------------------------------------| -| Attributes:: | | +| Attributes: | | | * CurrentLevel | 0x0000 | | * RemainingTime | 0x0001 | | * Options | 0x000F | @@ -2583,7 +4088,7 @@ class ReadIdentifyIdentifyTime : public ModelCommand class LevelMove : public ModelCommand { public: - LevelMove() : ModelCommand("move", LEVEL_CLUSTER_ID) + LevelMove() : ModelCommand("move", kLevelClusterId, 0x01) { AddArgument("moveMode", 0, UINT8_MAX, &mMoveMode); AddArgument("rate", 0, UINT8_MAX, &mRate); @@ -2597,6 +4102,13 @@ class LevelMove : public ModelCommand mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mMoveMode; uint8_t mRate; @@ -2610,7 +4122,7 @@ class LevelMove : public ModelCommand class LevelMoveToLevel : public ModelCommand { public: - LevelMoveToLevel() : ModelCommand("move-to-level", LEVEL_CLUSTER_ID) + LevelMoveToLevel() : ModelCommand("move-to-level", kLevelClusterId, 0x00) { AddArgument("level", 0, UINT8_MAX, &mLevel); AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime); @@ -2624,6 +4136,13 @@ class LevelMoveToLevel : public ModelCommand mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mLevel; uint16_t mTransitionTime; @@ -2637,7 +4156,7 @@ class LevelMoveToLevel : public ModelCommand class LevelMoveToLevelWithOnOff : public ModelCommand { public: - LevelMoveToLevelWithOnOff() : ModelCommand("move-to-level-with-on-off", LEVEL_CLUSTER_ID) + LevelMoveToLevelWithOnOff() : ModelCommand("move-to-level-with-on-off", kLevelClusterId, 0x04) { AddArgument("level", 0, UINT8_MAX, &mLevel); AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime); @@ -2651,6 +4170,13 @@ class LevelMoveToLevelWithOnOff : public ModelCommand mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mLevel; uint16_t mTransitionTime; @@ -2664,7 +4190,7 @@ class LevelMoveToLevelWithOnOff : public ModelCommand class LevelMoveWithOnOff : public ModelCommand { public: - LevelMoveWithOnOff() : ModelCommand("move-with-on-off", LEVEL_CLUSTER_ID) + LevelMoveWithOnOff() : ModelCommand("move-with-on-off", kLevelClusterId, 0x05) { AddArgument("moveMode", 0, UINT8_MAX, &mMoveMode); AddArgument("rate", 0, UINT8_MAX, &mRate); @@ -2678,6 +4204,13 @@ class LevelMoveWithOnOff : public ModelCommand mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mMoveMode; uint8_t mRate; @@ -2691,7 +4224,7 @@ class LevelMoveWithOnOff : public ModelCommand class LevelStep : public ModelCommand { public: - LevelStep() : ModelCommand("step", LEVEL_CLUSTER_ID) + LevelStep() : ModelCommand("step", kLevelClusterId, 0x02) { AddArgument("stepMode", 0, UINT8_MAX, &mStepMode); AddArgument("stepSize", 0, UINT8_MAX, &mStepSize); @@ -2706,6 +4239,13 @@ class LevelStep : public ModelCommand mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mStepMode; uint8_t mStepSize; @@ -2720,7 +4260,7 @@ class LevelStep : public ModelCommand class LevelStepWithOnOff : public ModelCommand { public: - LevelStepWithOnOff() : ModelCommand("step-with-on-off", LEVEL_CLUSTER_ID) + LevelStepWithOnOff() : ModelCommand("step-with-on-off", kLevelClusterId, 0x06) { AddArgument("stepMode", 0, UINT8_MAX, &mStepMode); AddArgument("stepSize", 0, UINT8_MAX, &mStepSize); @@ -2735,6 +4275,13 @@ class LevelStepWithOnOff : public ModelCommand mTransitionTime, mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mStepMode; uint8_t mStepSize; @@ -2749,7 +4296,7 @@ class LevelStepWithOnOff : public ModelCommand class LevelStop : public ModelCommand { public: - LevelStop() : ModelCommand("stop", LEVEL_CLUSTER_ID) + LevelStop() : ModelCommand("stop", kLevelClusterId, 0x03) { AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask); AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); @@ -2760,6 +4307,13 @@ class LevelStop : public ModelCommand return encodeLevelClusterStopCommand(buffer->Start(), bufferSize, endPointId, mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mOptionsMask; uint8_t mOptionsOverride; @@ -2771,7 +4325,7 @@ class LevelStop : public ModelCommand class LevelStopWithOnOff : public ModelCommand { public: - LevelStopWithOnOff() : ModelCommand("stop-with-on-off", LEVEL_CLUSTER_ID) + LevelStopWithOnOff() : ModelCommand("stop-with-on-off", kLevelClusterId, 0x07) { AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask); AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride); @@ -2782,6 +4336,13 @@ class LevelStopWithOnOff : public ModelCommand return encodeLevelClusterStopWithOnOffCommand(buffer->Start(), bufferSize, endPointId, mOptionsMask, mOptionsOverride); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint8_t mOptionsMask; uint8_t mOptionsOverride; @@ -2793,12 +4354,19 @@ class LevelStopWithOnOff : public ModelCommand class ReadLevelCurrentLevel : public ModelCommand { public: - ReadLevelCurrentLevel() : ModelCommand("read", LEVEL_CLUSTER_ID) { AddArgument("attr-name", "current-level"); } + ReadLevelCurrentLevel() : ModelCommand("read", kLevelClusterId, 0x00) { AddArgument("attr-name", "current-level"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterReadCurrentLevelAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -2807,12 +4375,19 @@ class ReadLevelCurrentLevel : public ModelCommand class ReadLevelRemainingTime : public ModelCommand { public: - ReadLevelRemainingTime() : ModelCommand("read", LEVEL_CLUSTER_ID) { AddArgument("attr-name", "remaining-time"); } + ReadLevelRemainingTime() : ModelCommand("read", kLevelClusterId, 0x00) { AddArgument("attr-name", "remaining-time"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterReadRemainingTimeAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -2821,24 +4396,33 @@ class ReadLevelRemainingTime : public ModelCommand class ReadLevelOptions : public ModelCommand { public: - ReadLevelOptions() : ModelCommand("read", LEVEL_CLUSTER_ID) { AddArgument("attr-name", "options"); } + ReadLevelOptions() : ModelCommand("read", kLevelClusterId, 0x00) { AddArgument("attr-name", "options"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeLevelClusterReadOptionsAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /*----------------------------------------------------------------------------*\ | Cluster OnOff | 0x0006 | |------------------------------------------------------------------------------| +| Responses: | | +| | | +|------------------------------------------------------------------------------| | Commands: | | | * Off | 0x00 | | * On | 0x01 | | * Toggle | 0x02 | -| | | |------------------------------------------------------------------------------| -| Attributes:: | | +| Attributes: | | | * OnOff | 0x0000 | \*----------------------------------------------------------------------------*/ @@ -2848,12 +4432,19 @@ class ReadLevelOptions : public ModelCommand class OnOffOff : public ModelCommand { public: - OnOffOff() : ModelCommand("off", ON_OFF_CLUSTER_ID) {} + OnOffOff() : ModelCommand("off", kOnOffClusterId, 0x00) {} uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeOnOffClusterOffCommand(buffer->Start(), bufferSize, endPointId); } + + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -2862,12 +4453,19 @@ class OnOffOff : public ModelCommand class OnOffOn : public ModelCommand { public: - OnOffOn() : ModelCommand("on", ON_OFF_CLUSTER_ID) {} + OnOffOn() : ModelCommand("on", kOnOffClusterId, 0x01) {} uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeOnOffClusterOnCommand(buffer->Start(), bufferSize, endPointId); } + + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -2876,12 +4474,19 @@ class OnOffOn : public ModelCommand class OnOffToggle : public ModelCommand { public: - OnOffToggle() : ModelCommand("toggle", ON_OFF_CLUSTER_ID) {} + OnOffToggle() : ModelCommand("toggle", kOnOffClusterId, 0x02) {} uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeOnOffClusterToggleCommand(buffer->Start(), bufferSize, endPointId); } + + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -2890,17 +4495,36 @@ class OnOffToggle : public ModelCommand class ReadOnOffOnOff : public ModelCommand { public: - ReadOnOffOnOff() : ModelCommand("read", ON_OFF_CLUSTER_ID) { AddArgument("attr-name", "on-off"); } + ReadOnOffOnOff() : ModelCommand("read", kOnOffClusterId, 0x00) { AddArgument("attr-name", "on-off"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeOnOffClusterReadOnOffAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /*----------------------------------------------------------------------------*\ | Cluster Scenes | 0x0005 | |------------------------------------------------------------------------------| +| Responses: | | +| * AddSceneResponse | 0x00 | +| * CopySceneResponse | 0x42 | +| * EnhancedAddSceneResponse | 0x40 | +| * EnhancedViewSceneResponse | 0x41 | +| * GetSceneMembershipResponse | 0x06 | +| * RemoveAllScenesResponse | 0x03 | +| * RemoveSceneResponse | 0x02 | +| * StoreSceneResponse | 0x04 | +| * ViewSceneResponse | 0x01 | +| | | +|------------------------------------------------------------------------------| | Commands: | | | * AddScene | 0x00 | | * CopyScene | 0x42 | @@ -2912,9 +4536,8 @@ class ReadOnOffOnOff : public ModelCommand | * RemoveScene | 0x02 | | * StoreScene | 0x04 | | * ViewScene | 0x01 | -| | | |------------------------------------------------------------------------------| -| Attributes:: | | +| Attributes: | | | * SceneCount | 0x0000 | | * CurrentScene | 0x0001 | | * CurrentGroup | 0x0002 | @@ -2922,13 +4545,207 @@ class ReadOnOffOnOff : public ModelCommand | * NameSupport | 0x0004 | \*----------------------------------------------------------------------------*/ +/* + * Command Response AddSceneResponse + */ +class AddSceneResponse : public ModelCommandResponse +{ +public: + AddSceneResponse() : ModelCommandResponse(0x00) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "AddSceneResponse (0x00):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // SGroupId + ChipLogProgress(chipTool, " %s: 0x%02x", "sceneId", chip::Encoding::Read8(message)); // uint8 + + return true; + } +}; + +/* + * Command Response CopySceneResponse + */ +class CopySceneResponse : public ModelCommandResponse +{ +public: + CopySceneResponse() : ModelCommandResponse(0x42) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "CopySceneResponse (0x42):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%04x", "groupIdFrom", chip::Encoding::LittleEndian::Read16(message)); // SGroupId + ChipLogProgress(chipTool, " %s: 0x%02x", "sceneIdFrom", chip::Encoding::Read8(message)); // uint8 + + return true; + } +}; + +/* + * Command Response EnhancedAddSceneResponse + */ +class EnhancedAddSceneResponse : public ModelCommandResponse +{ +public: + EnhancedAddSceneResponse() : ModelCommandResponse(0x40) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "EnhancedAddSceneResponse (0x40):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // SGroupId + ChipLogProgress(chipTool, " %s: 0x%02x", "sceneId", chip::Encoding::Read8(message)); // uint8 + + return true; + } +}; + +/* + * Command Response EnhancedViewSceneResponse + */ +class EnhancedViewSceneResponse : public ModelCommandResponse +{ +public: + EnhancedViewSceneResponse() : ModelCommandResponse(0x41) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "EnhancedViewSceneResponse (0x41):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // SGroupId + ChipLogProgress(chipTool, " %s: 0x%02x", "sceneId", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%04x", "transitionTime", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "sceneName", chip::Encoding::Read8(message)); // SSceneName + // struct SExtensionFieldSetList[] + uint8_t * messageEnd = message + messageLen; + do + { + ChipLogProgress(chipTool, " %s: 0x%04x", "clusterId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "extensionFieldSet", chip::Encoding::Read8(message)); // octstr + } while (message < messageEnd); + + return true; + } +}; + +/* + * Command Response GetSceneMembershipResponse + */ +class GetSceneMembershipResponse : public ModelCommandResponse +{ +public: + GetSceneMembershipResponse() : ModelCommandResponse(0x06) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "GetSceneMembershipResponse (0x06):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%02x", "capacity", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // SGroupId + // uint8_t uint8[] + uint8_t * messageEnd = message + messageLen; + do + { + ChipLogProgress(chipTool, " %s: 0x%02x", "sceneList", chip::Encoding::Read8(message)); // uint8 + } while (message < messageEnd); + + return true; + } +}; + +/* + * Command Response RemoveAllScenesResponse + */ +class RemoveAllScenesResponse : public ModelCommandResponse +{ +public: + RemoveAllScenesResponse() : ModelCommandResponse(0x03) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "RemoveAllScenesResponse (0x03):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // SGroupId + + return true; + } +}; + +/* + * Command Response RemoveSceneResponse + */ +class RemoveSceneResponse : public ModelCommandResponse +{ +public: + RemoveSceneResponse() : ModelCommandResponse(0x02) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "RemoveSceneResponse (0x02):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // SGroupId + ChipLogProgress(chipTool, " %s: 0x%02x", "sceneId", chip::Encoding::Read8(message)); // uint8 + + return true; + } +}; + +/* + * Command Response StoreSceneResponse + */ +class StoreSceneResponse : public ModelCommandResponse +{ +public: + StoreSceneResponse() : ModelCommandResponse(0x04) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "StoreSceneResponse (0x04):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // SGroupId + ChipLogProgress(chipTool, " %s: 0x%02x", "sceneId", chip::Encoding::Read8(message)); // uint8 + + return true; + } +}; + +/* + * Command Response ViewSceneResponse + */ +class ViewSceneResponse : public ModelCommandResponse +{ +public: + ViewSceneResponse() : ModelCommandResponse(0x01) {} + + bool HandleResponse(uint8_t * message, uint16_t messageLen) const override + { + ChipLogProgress(chipTool, "ViewSceneResponse (0x01):"); + ChipLogProgress(chipTool, " %s: 0x%02x", "status", chip::Encoding::Read8(message)); // zclStatus + ChipLogProgress(chipTool, " %s: 0x%04x", "groupId", chip::Encoding::LittleEndian::Read16(message)); // SGroupId + ChipLogProgress(chipTool, " %s: 0x%02x", "sceneId", chip::Encoding::Read8(message)); // uint8 + ChipLogProgress(chipTool, " %s: 0x%04x", "transitionTime", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "sceneName", chip::Encoding::Read8(message)); // SSceneName + // struct SExtensionFieldSetList[] + uint8_t * messageEnd = message + messageLen; + do + { + ChipLogProgress(chipTool, " %s: 0x%04x", "clusterId", chip::Encoding::LittleEndian::Read16(message)); // uint16 + ChipLogProgress(chipTool, " %s: 0x%02x", "extensionFieldSet", chip::Encoding::Read8(message)); // octstr + } while (message < messageEnd); + + return true; + } +}; + /* * Command AddScene */ class ScenesAddScene : public ModelCommand { public: - ScenesAddScene() : ModelCommand("add-scene", SCENES_CLUSTER_ID) + ScenesAddScene() : ModelCommand("add-scene", kScenesClusterId, 0x00) { AddArgument("groupID", 0, UINT16_MAX, &mGroupID); AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); @@ -2944,19 +4761,18 @@ class ScenesAddScene : public ModelCommand mSceneName, mExtensionFieldSets); } - // Cluster Specific Response: AddSceneResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupID = chip::Encoding::LittleEndian::Read16(message); - uint8_t sceneID = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "AddSceneResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupID: 0x%04x", groupID); - ChipLogProgress(chipTool, " sceneID: 0x%02x", sceneID); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: AddSceneResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + AddSceneResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -2964,6 +4780,7 @@ class ScenesAddScene : public ModelCommand uint8_t mSceneID; uint16_t mTransitionTime; char * mSceneName; + // FIXME - SExtensionFieldSetList is not supported. void * mExtensionFieldSets; }; @@ -2973,7 +4790,7 @@ class ScenesAddScene : public ModelCommand class ScenesCopyScene : public ModelCommand { public: - ScenesCopyScene() : ModelCommand("copy-scene", SCENES_CLUSTER_ID) + ScenesCopyScene() : ModelCommand("copy-scene", kScenesClusterId, 0x42) { AddArgument("mode", 0, UINT8_MAX, &mMode); AddArgument("groupIdentifierFrom", 0, UINT16_MAX, &mGroupIdentifierFrom); @@ -2988,19 +4805,18 @@ class ScenesCopyScene : public ModelCommand mSceneIdentifierFrom, mGroupIdentifierTo, mSceneIdentifierTo); } - // Cluster Specific Response: CopySceneResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupIdentifierFrom = chip::Encoding::LittleEndian::Read16(message); - uint8_t sceneIdentifierFrom = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "CopySceneResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupIdentifierFrom: 0x%04x", groupIdentifierFrom); - ChipLogProgress(chipTool, " sceneIdentifierFrom: 0x%02x", sceneIdentifierFrom); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: CopySceneResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + CopySceneResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -3017,7 +4833,7 @@ class ScenesCopyScene : public ModelCommand class ScenesEnhancedAddScene : public ModelCommand { public: - ScenesEnhancedAddScene() : ModelCommand("enhanced-add-scene", SCENES_CLUSTER_ID) + ScenesEnhancedAddScene() : ModelCommand("enhanced-add-scene", kScenesClusterId, 0x40) { AddArgument("groupID", 0, UINT16_MAX, &mGroupID); AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); @@ -3033,19 +4849,18 @@ class ScenesEnhancedAddScene : public ModelCommand mTransitionTime, mSceneName, mExtensionFieldSets); } - // Cluster Specific Response: EnhancedAddSceneResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupID = chip::Encoding::LittleEndian::Read16(message); - uint8_t sceneID = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "EnhancedAddSceneResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupID: 0x%04x", groupID); - ChipLogProgress(chipTool, " sceneID: 0x%02x", sceneID); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: EnhancedAddSceneResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + EnhancedAddSceneResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -3053,6 +4868,7 @@ class ScenesEnhancedAddScene : public ModelCommand uint8_t mSceneID; uint16_t mTransitionTime; char * mSceneName; + // FIXME - SExtensionFieldSetList is not supported. void * mExtensionFieldSets; }; @@ -3062,7 +4878,7 @@ class ScenesEnhancedAddScene : public ModelCommand class ScenesEnhancedViewScene : public ModelCommand { public: - ScenesEnhancedViewScene() : ModelCommand("enhanced-view-scene", SCENES_CLUSTER_ID) + ScenesEnhancedViewScene() : ModelCommand("enhanced-view-scene", kScenesClusterId, 0x41) { AddArgument("groupID", 0, UINT16_MAX, &mGroupID); AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); @@ -3073,24 +4889,18 @@ class ScenesEnhancedViewScene : public ModelCommand return encodeScenesClusterEnhancedViewSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID); } - // Cluster Specific Response: EnhancedViewSceneResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupID = chip::Encoding::LittleEndian::Read16(message); - uint8_t sceneID = chip::Encoding::Read8(message); - uint16_t transitionTime = chip::Encoding::LittleEndian::Read16(message); - uint8_t msgLen = chip::Encoding::Read8(message); - // FIXME - SExtensionFieldSetList is not supported. - - ChipLogProgress(chipTool, "EnhancedViewSceneResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupID: 0x%04x", groupID); - ChipLogProgress(chipTool, " sceneID: 0x%02x", sceneID); - ChipLogProgress(chipTool, " transitionTime: 0x%04x", transitionTime); - ChipLogProgress(chipTool, " sceneName len: 0x%02x", msgLen); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: EnhancedViewSceneResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + EnhancedViewSceneResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -3104,7 +4914,7 @@ class ScenesEnhancedViewScene : public ModelCommand class ScenesGetSceneMembership : public ModelCommand { public: - ScenesGetSceneMembership() : ModelCommand("get-scene-membership", SCENES_CLUSTER_ID) + ScenesGetSceneMembership() : ModelCommand("get-scene-membership", kScenesClusterId, 0x06) { AddArgument("groupID", 0, UINT16_MAX, &mGroupID); } @@ -3114,21 +4924,18 @@ class ScenesGetSceneMembership : public ModelCommand return encodeScenesClusterGetSceneMembershipCommand(buffer->Start(), bufferSize, endPointId, mGroupID); } - // Cluster Specific Response: GetSceneMembershipResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint8_t capacity = chip::Encoding::Read8(message); - uint16_t groupID = chip::Encoding::LittleEndian::Read16(message); - uint8_t sceneList = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "GetSceneMembershipResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " capacity: 0x%02x", capacity); - ChipLogProgress(chipTool, " groupID: 0x%04x", groupID); - ChipLogProgress(chipTool, " sceneList: 0x%02x", sceneList); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: GetSceneMembershipResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + GetSceneMembershipResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -3141,7 +4948,7 @@ class ScenesGetSceneMembership : public ModelCommand class ScenesRecallScene : public ModelCommand { public: - ScenesRecallScene() : ModelCommand("recall-scene", SCENES_CLUSTER_ID) + ScenesRecallScene() : ModelCommand("recall-scene", kScenesClusterId, 0x05) { AddArgument("groupID", 0, UINT16_MAX, &mGroupID); AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); @@ -3153,6 +4960,13 @@ class ScenesRecallScene : public ModelCommand return encodeScenesClusterRecallSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID, mTransitionTime); } + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } + private: uint16_t mGroupID; uint8_t mSceneID; @@ -3165,7 +4979,7 @@ class ScenesRecallScene : public ModelCommand class ScenesRemoveAllScenes : public ModelCommand { public: - ScenesRemoveAllScenes() : ModelCommand("remove-all-scenes", SCENES_CLUSTER_ID) + ScenesRemoveAllScenes() : ModelCommand("remove-all-scenes", kScenesClusterId, 0x03) { AddArgument("groupID", 0, UINT16_MAX, &mGroupID); } @@ -3175,17 +4989,18 @@ class ScenesRemoveAllScenes : public ModelCommand return encodeScenesClusterRemoveAllScenesCommand(buffer->Start(), bufferSize, endPointId, mGroupID); } - // Cluster Specific Response: RemoveAllScenesResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupID = chip::Encoding::LittleEndian::Read16(message); - - ChipLogProgress(chipTool, "RemoveAllScenesResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupID: 0x%04x", groupID); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: RemoveAllScenesResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + RemoveAllScenesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -3198,7 +5013,7 @@ class ScenesRemoveAllScenes : public ModelCommand class ScenesRemoveScene : public ModelCommand { public: - ScenesRemoveScene() : ModelCommand("remove-scene", SCENES_CLUSTER_ID) + ScenesRemoveScene() : ModelCommand("remove-scene", kScenesClusterId, 0x02) { AddArgument("groupID", 0, UINT16_MAX, &mGroupID); AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); @@ -3209,19 +5024,18 @@ class ScenesRemoveScene : public ModelCommand return encodeScenesClusterRemoveSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID); } - // Cluster Specific Response: RemoveSceneResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupID = chip::Encoding::LittleEndian::Read16(message); - uint8_t sceneID = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "RemoveSceneResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupID: 0x%04x", groupID); - ChipLogProgress(chipTool, " sceneID: 0x%02x", sceneID); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: RemoveSceneResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + RemoveSceneResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -3235,7 +5049,7 @@ class ScenesRemoveScene : public ModelCommand class ScenesStoreScene : public ModelCommand { public: - ScenesStoreScene() : ModelCommand("store-scene", SCENES_CLUSTER_ID) + ScenesStoreScene() : ModelCommand("store-scene", kScenesClusterId, 0x04) { AddArgument("groupID", 0, UINT16_MAX, &mGroupID); AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); @@ -3246,19 +5060,18 @@ class ScenesStoreScene : public ModelCommand return encodeScenesClusterStoreSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID); } - // Cluster Specific Response: StoreSceneResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupID = chip::Encoding::LittleEndian::Read16(message); - uint8_t sceneID = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "StoreSceneResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupID: 0x%04x", groupID); - ChipLogProgress(chipTool, " sceneID: 0x%02x", sceneID); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: StoreSceneResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + StoreSceneResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -3272,7 +5085,7 @@ class ScenesStoreScene : public ModelCommand class ScenesViewScene : public ModelCommand { public: - ScenesViewScene() : ModelCommand("view-scene", SCENES_CLUSTER_ID) + ScenesViewScene() : ModelCommand("view-scene", kScenesClusterId, 0x01) { AddArgument("groupID", 0, UINT16_MAX, &mGroupID); AddArgument("sceneID", 0, UINT8_MAX, &mSceneID); @@ -3283,24 +5096,18 @@ class ScenesViewScene : public ModelCommand return encodeScenesClusterViewSceneCommand(buffer->Start(), bufferSize, endPointId, mGroupID, mSceneID); } - // Cluster Specific Response: ViewSceneResponse - bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const override + // Global Response: DefaultResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override { - uint8_t status = chip::Encoding::Read8(message); - uint16_t groupID = chip::Encoding::LittleEndian::Read16(message); - uint8_t sceneID = chip::Encoding::Read8(message); - uint16_t transitionTime = chip::Encoding::LittleEndian::Read16(message); - uint8_t msgLen = chip::Encoding::Read8(message); - // FIXME - SExtensionFieldSetList is not supported. - - ChipLogProgress(chipTool, "ViewSceneResponse:"); - ChipLogProgress(chipTool, " status: 0x%02x", status); - ChipLogProgress(chipTool, " groupID: 0x%04x", groupID); - ChipLogProgress(chipTool, " sceneID: 0x%02x", sceneID); - ChipLogProgress(chipTool, " transitionTime: 0x%04x", transitionTime); - ChipLogProgress(chipTool, " sceneName len: 0x%02x", msgLen); + DefaultResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } - return true; + // Specific Response: ViewSceneResponse + bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ViewSceneResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); } private: @@ -3314,12 +5121,19 @@ class ScenesViewScene : public ModelCommand class ReadScenesSceneCount : public ModelCommand { public: - ReadScenesSceneCount() : ModelCommand("read", SCENES_CLUSTER_ID) { AddArgument("attr-name", "scene-count"); } + ReadScenesSceneCount() : ModelCommand("read", kScenesClusterId, 0x00) { AddArgument("attr-name", "scene-count"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterReadSceneCountAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -3328,12 +5142,19 @@ class ReadScenesSceneCount : public ModelCommand class ReadScenesCurrentScene : public ModelCommand { public: - ReadScenesCurrentScene() : ModelCommand("read", SCENES_CLUSTER_ID) { AddArgument("attr-name", "current-scene"); } + ReadScenesCurrentScene() : ModelCommand("read", kScenesClusterId, 0x00) { AddArgument("attr-name", "current-scene"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterReadCurrentSceneAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -3342,12 +5163,19 @@ class ReadScenesCurrentScene : public ModelCommand class ReadScenesCurrentGroup : public ModelCommand { public: - ReadScenesCurrentGroup() : ModelCommand("read", SCENES_CLUSTER_ID) { AddArgument("attr-name", "current-group"); } + ReadScenesCurrentGroup() : ModelCommand("read", kScenesClusterId, 0x00) { AddArgument("attr-name", "current-group"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterReadCurrentGroupAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -3356,12 +5184,19 @@ class ReadScenesCurrentGroup : public ModelCommand class ReadScenesSceneValid : public ModelCommand { public: - ReadScenesSceneValid() : ModelCommand("read", SCENES_CLUSTER_ID) { AddArgument("attr-name", "scene-valid"); } + ReadScenesSceneValid() : ModelCommand("read", kScenesClusterId, 0x00) { AddArgument("attr-name", "scene-valid"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterReadSceneValidAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -3370,21 +5205,30 @@ class ReadScenesSceneValid : public ModelCommand class ReadScenesNameSupport : public ModelCommand { public: - ReadScenesNameSupport() : ModelCommand("read", SCENES_CLUSTER_ID) { AddArgument("attr-name", "name-support"); } + ReadScenesNameSupport() : ModelCommand("read", kScenesClusterId, 0x00) { AddArgument("attr-name", "name-support"); } uint16_t EncodeCommand(PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) override { return encodeScenesClusterReadNameSupportAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /*----------------------------------------------------------------------------*\ | Cluster TemperatureMeasurement | 0x0402 | |------------------------------------------------------------------------------| -| Commands: | | +| Responses: | | | | | |------------------------------------------------------------------------------| -| Attributes:: | | +| Commands: | | +|------------------------------------------------------------------------------| +| Attributes: | | | * MeasuredValue | 0x0000 | | * MinMeasuredValue | 0x0001 | | * MaxMeasuredValue | 0x0002 | @@ -3396,7 +5240,7 @@ class ReadScenesNameSupport : public ModelCommand class ReadTemperatureMeasurementMeasuredValue : public ModelCommand { public: - ReadTemperatureMeasurementMeasuredValue() : ModelCommand("read", TEMPERATURE_MEASUREMENT_CLUSTER_ID) + ReadTemperatureMeasurementMeasuredValue() : ModelCommand("read", kTempMeasurementClusterId, 0x00) { AddArgument("attr-name", "measured-value"); } @@ -3405,6 +5249,13 @@ class ReadTemperatureMeasurementMeasuredValue : public ModelCommand { return encodeTemperatureMeasurementClusterReadMeasuredValueAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -3413,7 +5264,7 @@ class ReadTemperatureMeasurementMeasuredValue : public ModelCommand class ReadTemperatureMeasurementMinMeasuredValue : public ModelCommand { public: - ReadTemperatureMeasurementMinMeasuredValue() : ModelCommand("read", TEMPERATURE_MEASUREMENT_CLUSTER_ID) + ReadTemperatureMeasurementMinMeasuredValue() : ModelCommand("read", kTempMeasurementClusterId, 0x00) { AddArgument("attr-name", "min-measured-value"); } @@ -3422,6 +5273,13 @@ class ReadTemperatureMeasurementMinMeasuredValue : public ModelCommand { return encodeTemperatureMeasurementClusterReadMinMeasuredValueAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /* @@ -3430,7 +5288,7 @@ class ReadTemperatureMeasurementMinMeasuredValue : public ModelCommand class ReadTemperatureMeasurementMaxMeasuredValue : public ModelCommand { public: - ReadTemperatureMeasurementMaxMeasuredValue() : ModelCommand("read", TEMPERATURE_MEASUREMENT_CLUSTER_ID) + ReadTemperatureMeasurementMaxMeasuredValue() : ModelCommand("read", kTempMeasurementClusterId, 0x00) { AddArgument("attr-name", "max-measured-value"); } @@ -3439,6 +5297,13 @@ class ReadTemperatureMeasurementMaxMeasuredValue : public ModelCommand { return encodeTemperatureMeasurementClusterReadMaxMeasuredValueAttribute(buffer->Start(), bufferSize, endPointId); } + + // Global Response: ReadAttributesResponse + bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const override + { + ReadAttributesResponse response; + return response.HandleCommandResponse(commandId, message, messageLen); + } }; /*----------------------------------------------------------------------------*\ @@ -3648,7 +5513,7 @@ void registerClusterScenes(Commands & commands) commands.Register(clusterName, clusterCommands); } -void registerClusterTemperatureMeasurement(Commands & commands) +void registerClusterTempMeasurement(Commands & commands) { const char * clusterName = "TemperatureMeasurement"; @@ -3672,5 +5537,5 @@ void registerClusters(Commands & commands) registerClusterLevel(commands); registerClusterOnOff(commands); registerClusterScenes(commands); - registerClusterTemperatureMeasurement(commands); + registerClusterTempMeasurement(commands); } diff --git a/examples/chip-tool/commands/common/ModelCommand.cpp b/examples/chip-tool/commands/common/ModelCommand.cpp index 76405de88b03b5..3ea6bd9e5485d3 100644 --- a/examples/chip-tool/commands/common/ModelCommand.cpp +++ b/examples/chip-tool/commands/common/ModelCommand.cpp @@ -23,16 +23,9 @@ #include #include -#include - using namespace ::chip; using namespace ::chip::DeviceController; -namespace { -constexpr uint8_t kDefaultResponseCommandId = 0x0b; -constexpr uint8_t kReadAttributesResponseCommandId = 0x01; -} // namespace - namespace { constexpr uint8_t kZCLGlobalCmdFrameControlHeader = 8; constexpr uint8_t kZCLClusterCmdFrameControlHeader = 9; @@ -94,6 +87,9 @@ bool ModelCommand::SendCommand(ChipDeviceController * dc) return false; } + ChipLogProgress(chipTool, "Endpoint id: '0x%02x', Cluster id: '0x%04x', Command id: '0x%02x'", mEndPointId, mClusterId, + mCommandId); + uint16_t dataLength = EncodeCommand(buffer, bufferSize, mEndPointId); if (dataLength == 0) { @@ -141,133 +137,17 @@ void ModelCommand::ReceiveCommandResponse(ChipDeviceController * dc, PacketBuffe VerifyOrExit(isValidFrame(frameControl), ChipLogError(chipTool, "Unexpected frame control byte: 0x%02x", frameControl)); VerifyOrExit(sequenceNumber == 1, ChipLogError(chipTool, "Unexpected sequence number: %d", sequenceNumber)); - VerifyOrExit( - mEndPointId == frame.sourceEndpoint, - ChipLogError(chipTool, "Invalid endpoint '0x%02x'. Expected endpoint '0x%02x'", frame.sourceEndpoint, mEndPointId)); - VerifyOrExit(mClusterId == frame.clusterId, - ChipLogError(chipTool, "Invalid cluster '0x%04x'. Expected cluster '0x%04x'", frame.clusterId, mClusterId)); + VerifyOrExit(mEndPointId == frame.sourceEndpoint, + ChipLogError(chipTool, "Unexpected endpoint id '0x%02x'", frame.sourceEndpoint)); + VerifyOrExit(mClusterId == frame.clusterId, ChipLogError(chipTool, "Unexpected cluster id '0x%04x'", frame.clusterId)); isGlobalCommand = (frameControl == kZCLGlobalCmdFrameControlHeader); - isGlobalCommand ? ParseGlobalResponseCommand(commandId, message, messageLen) - : ParseSpecificClusterResponseCommand(commandId, message, messageLen); - -exit: - return; -} - -void ModelCommand::ParseGlobalResponseCommand(uint8_t commandId, uint8_t * message, uint16_t messageLen) const -{ - switch (commandId) - { - case kDefaultResponseCommandId: - ParseDefaultResponseCommand(message, messageLen); - break; - case kReadAttributesResponseCommandId: - ParseReadAttributeResponseCommand(message, messageLen); - break; - default: - ChipLogError(chipTool, "Unexpected command '0x%02x'", commandId); - break; - } -} - -void ModelCommand::ParseDefaultResponseCommand(uint8_t * message, uint16_t messageLen) const -{ - uint8_t commandId; - uint8_t status; - - CHECK_MESSAGE_LENGTH(messageLen == 2); - - commandId = chip::Encoding::Read8(message); - status = chip::Encoding::Read8(message); - - ChipLogProgress(chipTool, "Got default response to command '0x%02x' for cluster '0x%04x'. Status is '0x%02x'", commandId, - mClusterId, status); - -exit: - return; -} - -void ModelCommand::ParseReadAttributeResponseCommand(uint8_t * message, uint16_t messageLen) const -{ - uint16_t attrId; - uint8_t status; - - // Remaining bytes are a list of (attr id, 0, attr type, attr value) or (attr id, failure status) - // tuples. - // - // But for now we only support one attribute value, and that value is a boolean. - CHECK_MESSAGE_LENGTH(messageLen >= 3); - - attrId = chip::Encoding::LittleEndian::Read16(message); - status = chip::Encoding::Read8(message); - messageLen = static_cast(messageLen - 3); - - if (status == 0) - { - ParseReadAttributeResponseCommandSuccess(attrId, message, messageLen); - } - else - { - ParseReadAttributeResponseCommandFailure(attrId, status, messageLen); - } + isGlobalCommand ? HandleGlobalResponse(commandId, message, messageLen) : HandleSpecificResponse(commandId, message, messageLen); exit: return; } -void ModelCommand::ParseReadAttributeResponseCommandSuccess(uint16_t attrId, uint8_t * message, uint16_t messageLen) const -{ - uint8_t type = chip::Encoding::Read8(message); - messageLen--; - - VerifyOrExit(type == 0x10 || type == 0x29, ChipLogError(chipTool, "Unexpected attribute type: '0x%02x'", type)); - - ChipLogProgress(chipTool, "Read attribute '0x%04x' for cluster '0x%04x'. Type is '0x%02x'", attrId, mClusterId, type); - - // FIXME: Should we have a mapping of type ids to types, based on - // table 2.6.2.2 in Rev 8 of the ZCL spec? - switch (type) - { - case 0x10: { // "Boolean" - uint8_t value; - CHECK_MESSAGE_LENGTH(messageLen == 1); - value = chip::Encoding::Read8(message); - ChipLogProgress(chipTool, "Attribute value: '0x%02x'", value); - break; - } - case 0x29: { // "Int16" - int16_t value; - CHECK_MESSAGE_LENGTH(messageLen == 2); - value = CastToSigned(chip::Encoding::LittleEndian::Read16(message)); - ChipLogProgress(chipTool, "Attribute value: '0x%d'", value); - break; - } - } - -exit: - return; -} - -void ModelCommand::ParseReadAttributeResponseCommandFailure(uint16_t attrId, uint8_t status, uint16_t messageLen) const -{ - CHECK_MESSAGE_LENGTH(messageLen == 0); - ChipLogProgress(chipTool, "Reading attribute '0x%04x' for cluster '0x%04x' failed with status '0x%02x'", attrId, mClusterId, - status); - -exit: - return; -} - -void ModelCommand::ParseSpecificClusterResponseCommand(uint8_t commandId, uint8_t * message, uint16_t messageLen) const -{ - ChipLogProgress(chipTool, "Parsing cluster id '0x%04x' response command '0x%02x'", mClusterId, commandId); - if (!HandleClusterResponse(message, messageLen)) - { - ChipLogError(chipTool, "Not handling command '0x%02x'", commandId); - } -} - void ModelCommand::UpdateWaitForResponse(bool value) { { diff --git a/examples/chip-tool/commands/common/ModelCommand.h b/examples/chip-tool/commands/common/ModelCommand.h index e7a4fa1fb0ab46..0093881c86f857 100644 --- a/examples/chip-tool/commands/common/ModelCommand.h +++ b/examples/chip-tool/commands/common/ModelCommand.h @@ -37,10 +37,10 @@ class ModelCommand : public NetworkCommand { public: - ModelCommand(const char * commandName, const uint16_t clusterId) : NetworkCommand(commandName, NetworkType::UDP) + ModelCommand(const char * commandName, uint16_t clusterId, uint8_t commandId) : + NetworkCommand(commandName, NetworkType::UDP), mClusterId(clusterId), mCommandId(commandId) { AddArgument("endpoint-id", CHIP_ZCL_ENDPOINT_MIN, CHIP_ZCL_ENDPOINT_MAX, &mEndPointId); - mClusterId = clusterId; } /////////// Command Interface ///////// @@ -52,19 +52,13 @@ class ModelCommand : public NetworkCommand void OnMessage(ChipDeviceController * dc, chip::System::PacketBuffer * buffer) override; virtual uint16_t EncodeCommand(chip::System::PacketBuffer * buffer, uint16_t bufferSize, uint8_t endPointId) = 0; - virtual bool HandleClusterResponse(uint8_t * message, uint16_t messageLen) const { return false; } + virtual bool HandleGlobalResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const { return false; } + virtual bool HandleSpecificResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) const { return false; } private: bool SendCommand(ChipDeviceController * dc); void ReceiveCommandResponse(ChipDeviceController * dc, chip::System::PacketBuffer * buffer) const; - void ParseGlobalResponseCommand(uint8_t commandId, uint8_t * message, uint16_t messageLen) const; - void ParseDefaultResponseCommand(uint8_t * message, uint16_t messageLen) const; - void ParseReadAttributeResponseCommand(uint8_t * message, uint16_t messageLen) const; - void ParseReadAttributeResponseCommandSuccess(uint16_t attrId, uint8_t * message, uint16_t messageLen) const; - void ParseReadAttributeResponseCommandFailure(uint16_t attrId, uint8_t status, uint16_t messageLen) const; - void ParseSpecificClusterResponseCommand(uint8_t commandId, uint8_t * message, uint16_t messageLen) const; - void UpdateWaitForResponse(bool value); void WaitForResponse(void); void PrintBuffer(chip::System::PacketBuffer * buffer) const; @@ -72,6 +66,7 @@ class ModelCommand : public NetworkCommand std::condition_variable cvWaitingForResponse; std::mutex cvWaitingForResponseMutex; bool mWaitingForResponse{ false }; - uint16_t mClusterId; + const uint16_t mClusterId; + const uint8_t mCommandId; uint8_t mEndPointId; }; diff --git a/examples/chip-tool/commands/common/ModelCommandResponse.h b/examples/chip-tool/commands/common/ModelCommandResponse.h new file mode 100644 index 00000000000000..e47f229d9ad3de --- /dev/null +++ b/examples/chip-tool/commands/common/ModelCommandResponse.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2020 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 + +class ModelCommandResponse +{ +public: + ModelCommandResponse(uint8_t commandId) : mCommandId(commandId) {} + virtual ~ModelCommandResponse() {} + + bool HandleCommandResponse(uint8_t commandId, uint8_t * message, uint16_t messageLen) + { + if (commandId != mCommandId) + { + ChipLogError(chipTool, "Unexpected command response id: '0x%02x'. Expecting: '0x%02x'", commandId, mCommandId); + return false; + } + return HandleResponse(message, messageLen); + } + + virtual bool HandleResponse(uint8_t * message, uint16_t messageLen) const = 0; + +private: + const uint8_t mCommandId; +}; From 33927fe0ac50961785e09937b6c92445f06d0a24 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Sun, 18 Oct 2020 23:38:03 -0400 Subject: [PATCH 40/40] Add checks to make sure we don't read off the end of our packet. (#3288) There were two issues here: 1) We never checked that the payload length in the packet is valid given the packet size. We now add a check for this, and pass the correct number of available bytes to MessageAuthenticationCode::Decode. 2) We never checked that the number of bytes we have available to read is enough to store a payload header. We now pass the correct buffer length to PayloadHeader::Decode, to ensure it doesn't read off the end of the buffer. --- src/transport/RendezvousSession.cpp | 8 +++++--- src/transport/SecureSessionMgr.cpp | 10 +++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/transport/RendezvousSession.cpp b/src/transport/RendezvousSession.cpp index b6b7e6801e92be..7055a3c69c5680 100644 --- a/src/transport/RendezvousSession.cpp +++ b/src/transport/RendezvousSession.cpp @@ -331,6 +331,7 @@ CHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf) uint16_t len = 0; uint16_t decodedSize = 0; uint16_t taglen = 0; + uint16_t payloadlen = 0; System::PacketBuffer * origMsg = nullptr; err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize); @@ -352,8 +353,9 @@ CHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf) #endif plainText = msgBuf->Start(); - // TODO: We need length checks here! https://github.com/project-chip/connectedhomeip/issues/2928 - err = mac.Decode(packetHeader, &data[packetHeader.GetPayloadLength()], kMaxTagLen, &taglen); + payloadlen = packetHeader.GetPayloadLength(); + VerifyOrExit(payloadlen <= len, err = CHIP_ERROR_INCORRECT_STATE); + err = mac.Decode(packetHeader, &data[payloadlen], len - payloadlen, &taglen); SuccessOrExit(err); len = static_cast(len - taglen); @@ -362,7 +364,7 @@ CHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf) err = mSecureSession.Decrypt(data, len, plainText, packetHeader, payloadHeader.GetEncodePacketFlags(), mac); SuccessOrExit(err); - err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, headerSize, &decodedSize); + err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, len, &decodedSize); SuccessOrExit(err); VerifyOrExit(headerSize == decodedSize, err = CHIP_ERROR_INCORRECT_STATE); diff --git a/src/transport/SecureSessionMgr.cpp b/src/transport/SecureSessionMgr.cpp index e3e5d8a17cbee2..bb3e1321fb1df4 100644 --- a/src/transport/SecureSessionMgr.cpp +++ b/src/transport/SecureSessionMgr.cpp @@ -260,6 +260,7 @@ void SecureSessionMgrBase::HandleDataReceived(const PacketHeader & packetHeader, const uint16_t headerSize = payloadHeader.EncodeSizeBytes(); uint16_t decodedSize = 0; uint16_t taglen = 0; + uint16_t payloadlen = 0; #if CHIP_SYSTEM_CONFIG_USE_LWIP /* This is a workaround for the case where PacketBuffer payload is not @@ -271,8 +272,11 @@ void SecureSessionMgrBase::HandleDataReceived(const PacketHeader & packetHeader, #endif plainText = msg->Start(); - // TODO: We need length checks here! https://github.com/project-chip/connectedhomeip/issues/2928 - err = mac.Decode(packetHeader, &data[packetHeader.GetPayloadLength()], kMaxTagLen, &taglen); + payloadlen = packetHeader.GetPayloadLength(); + VerifyOrExit( + payloadlen <= len, + (ChipLogError(Inet, "Secure transport can't find MAC Tag; buffer too short"), err = CHIP_ERROR_INCORRECT_STATE)); + err = mac.Decode(packetHeader, &data[payloadlen], len - payloadlen, &taglen); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Inet, "Secure transport failed to decode MAC Tag: err %d", err)); len = static_cast(len - taglen); msg->SetDataLength(len, nullptr); @@ -280,7 +284,7 @@ void SecureSessionMgrBase::HandleDataReceived(const PacketHeader & packetHeader, err = state->GetSecureSession().Decrypt(data, len, plainText, packetHeader, payloadHeader.GetEncodePacketFlags(), mac); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Inet, "Secure transport failed to decrypt msg: err %d", err)); - err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, headerSize, &decodedSize); + err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, len, &decodedSize); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Inet, "Secure transport failed to decode encrypted header: err %d", err)); VerifyOrExit(headerSize == decodedSize, ChipLogError(Inet, "Secure transport decode encrypted header length mismatched"));