From e8b74363b08edcfd373e5dcb85142f351434c0e3 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Thu, 5 Oct 2023 06:21:10 -0700 Subject: [PATCH 01/21] [java-matter-controller]Improve the readability and maintainability from code review (#29571) --- .../controller/commands/common/Command.kt | 64 +++++++++---------- .../commands/common/CommandManager.kt | 22 +++---- .../commands/common/CredentialsIssuer.kt | 5 +- .../commands/common/FutureResult.kt | 13 ++-- .../commands/common/MatterCommand.kt | 5 -- .../controller/commands/common/RealResult.kt | 10 +-- 6 files changed, 49 insertions(+), 70 deletions(-) diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Command.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Command.kt index fde197900dcc9e..1b05e0205f9a0b 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Command.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Command.kt @@ -28,17 +28,9 @@ import java.util.concurrent.atomic.AtomicLong * that may be performed. Commands are verb-like, such as pair a Matter device or discover Matter * devices from the environment. */ -abstract class Command(private val name: String, private val helpText: String? = null) { +abstract class Command(val name: String, val helpText: String? = null) { private val arguments = ArrayList() - fun getName(): String { - return name - } - - fun getHelpText(): String? { - return helpText - } - fun getArgumentName(index: Int): String { return arguments[index].name } @@ -92,8 +84,8 @@ abstract class Command(private val name: String, private val helpText: String? = * @return The number of arguments currently added to the command * @brief Add a bool command argument */ - fun addArgument(name: String?, out: AtomicBoolean?, desc: String?, optional: Boolean) { - val arg = Argument(name!!, out!!, desc, optional) + fun addArgument(name: String, out: AtomicBoolean, desc: String?, optional: Boolean) { + val arg = Argument(name, out, desc, optional) addArgumentToList(arg) } @@ -108,14 +100,14 @@ abstract class Command(private val name: String, private val helpText: String? = * @brief Add a short command argument */ fun addArgument( - name: String?, + name: String, min: Short, max: Short, - out: AtomicInteger?, + out: AtomicInteger, desc: String?, optional: Boolean ) { - val arg = Argument(name!!, min, max, out!!, desc, optional) + val arg = Argument(name, min, max, out, desc, optional) addArgumentToList(arg) } @@ -130,14 +122,14 @@ abstract class Command(private val name: String, private val helpText: String? = * @brief Add an int command argument */ fun addArgument( - name: String?, + name: String, min: Int, max: Int, - out: AtomicInteger?, + out: AtomicInteger, desc: String?, optional: Boolean ) { - val arg = Argument(name!!, min, max, out!!, desc, optional) + val arg = Argument(name, min, max, out, desc, optional) addArgumentToList(arg) } @@ -152,14 +144,14 @@ abstract class Command(private val name: String, private val helpText: String? = * @brief Add a long Integer command argument */ fun addArgument( - name: String?, + name: String, min: Short, max: Short, - out: AtomicLong?, + out: AtomicLong, desc: String?, optional: Boolean ) { - val arg = Argument(name!!, min, max, out!!, desc, optional) + val arg = Argument(name, min, max, out, desc, optional) addArgumentToList(arg) } @@ -174,14 +166,14 @@ abstract class Command(private val name: String, private val helpText: String? = * @brief Add a long Integer command argument */ fun addArgument( - name: String?, + name: String, min: Long, max: Long, - out: AtomicLong?, + out: AtomicLong, desc: String?, optional: Boolean ) { - val arg = Argument(name!!, min, max, out!!, desc, optional) + val arg = Argument(name, min, max, out, desc, optional) addArgumentToList(arg) } @@ -192,8 +184,8 @@ abstract class Command(private val name: String, private val helpText: String? = * @return The number of arguments currently added to the command * @brief Add an IP address command argument */ - fun addArgument(name: String?, out: IPAddress?, optional: Boolean) { - val arg = Argument(name!!, out!!, optional) + fun addArgument(name: String, out: IPAddress, optional: Boolean) { + val arg = Argument(name, out, optional) addArgumentToList(arg) } @@ -205,8 +197,8 @@ abstract class Command(private val name: String, private val helpText: String? = * @return The number of arguments currently added to the command * @brief Add a String command argument */ - fun addArgument(name: String?, out: StringBuffer?, desc: String?, optional: Boolean) { - val arg = Argument(name!!, out!!, desc, optional) + fun addArgument(name: String, out: StringBuffer, desc: String?, optional: Boolean) { + val arg = Argument(name, out, desc, optional) addArgumentToList(arg) } @@ -214,7 +206,7 @@ abstract class Command(private val name: String, private val helpText: String? = * @param args Supplied command-line arguments as an array of String objects. * @brief Initialize command arguments */ - fun initArguments(args: Array) { + fun setArgumentValues(args: Array) { val argc = args.size var mandatoryArgsCount = 0 var currentIndex = 0 @@ -224,12 +216,12 @@ abstract class Command(private val name: String, private val helpText: String? = } } require(argc >= mandatoryArgsCount) { - "initArguments: Wrong arguments number: $argc instead of $mandatoryArgsCount" + "setArgumentValues: Wrong arguments number: $argc instead of $mandatoryArgsCount" } // Initialize mandatory arguments for (i in 0 until mandatoryArgsCount) { - initArgument(currentIndex++, args[i]) + setArgumentValue(currentIndex++, args[i]) } // Initialize optional arguments @@ -242,18 +234,20 @@ abstract class Command(private val name: String, private val helpText: String? = !(args[i].length <= OPTIONAL_ARGUMENT_PREFIX_LENGTH && !args[i].startsWith(OPTIONAL_ARGUMENT_PREFIX)) ) { - "initArguments: Invalid optional argument: " + args[i] + "setArgumentValues: Invalid optional argument: " + args[i] } if (args[i].substring(OPTIONAL_ARGUMENT_PREFIX_LENGTH) == arguments[currentIndex].name) { - require(i + 1 < argc) { "initArguments: Optional argument " + args[i] + " missing value" } - initArgument(currentIndex++, args[i + 1]) + require(i + 1 < argc) { + "setArgumentValues: Optional argument " + args[i] + " missing value" + } + setArgumentValue(currentIndex++, args[i + 1]) } i += 2 } } - fun initArgument(argIndex: Int, argValue: String?) { - arguments[argIndex].setValue(argValue!!) + private fun setArgumentValue(argIndex: Int, argValue: String) { + arguments[argIndex].setValue(argValue) } @Throws(Exception::class) abstract fun run() diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/CommandManager.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/CommandManager.kt index 033e71086d610c..927be309aee9a2 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/CommandManager.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/CommandManager.kt @@ -35,13 +35,13 @@ class CommandManager { val command: Command? if (args.size < 1) { logger.log(Level.INFO, "Missing cluster name") - showClusters() + showHelpInfo() return } val commands = clusters[args[0]] if (commands == null) { logger.log(Level.INFO, "Unknown cluster: " + args[0]) - showClusters() + showHelpInfo() return } if (args.size < 2) { @@ -85,7 +85,7 @@ class CommandManager { // need skip over binary and command name and only get arguments val temp = Arrays.copyOfRange(args, 2, args.size) try { - command.initArguments(temp) + command.setArgumentValues(temp) } catch (e: IllegalArgumentException) { logger.log(Level.INFO, "Arguments init failed with exception: " + e.message) showCommand(args[0], command) @@ -108,7 +108,7 @@ class CommandManager { private fun getCommand(commands: List, commandName: String): Command? { for (command in commands) { - if (commandName == command.getName()) { + if (commandName == command.name) { return command } } @@ -121,14 +121,14 @@ class CommandManager { attributeName: String ): Command? { for (command in commands) { - if (commandName == command.getName() && attributeName == command.getAttribute()) { + if (commandName == command.name && attributeName == command.getAttribute()) { return command } } return null } - private fun showClusters() { + private fun showHelpInfo() { logger.log(Level.INFO, "Usage:") logger.log(Level.INFO, " java-matter-controller cluster_name command_name [param1 param2 ...]") logger.log(Level.INFO, "\n") @@ -176,7 +176,7 @@ class CommandManager { var subscribeEventCommand = false for (command in commands) { var shouldPrint = true - val cmdName = command.getName() + val cmdName = command.name if (isGlobalCommand(cmdName)) { if (cmdName == "read" && !readCommand) { readCommand = true @@ -227,7 +227,7 @@ class CommandManager { " +-------------------------------------------------------------------------------------+" ) for (command in commands) { - if (commandName == command.getName()) { + if (commandName == command.name) { System.out.printf(" | * %-82s|\n", command.getAttribute()) } } @@ -258,7 +258,7 @@ class CommandManager { " +-------------------------------------------------------------------------------------+" ) for (command in commands) { - if (commandName == command.getName()) { + if (commandName == command.name) { System.out.printf(" | * %-82s|\n", command.getAttribute()) } } @@ -270,7 +270,7 @@ class CommandManager { private fun showCommand(clusterName: String, command: Command) { logger.log(Level.INFO, "Usage:") - var arguments: String? = command.getName() + var arguments: String? = command.name var description = "" val argumentsCount = command.getArgumentsCount() for (i in 0 until argumentsCount) { @@ -295,7 +295,7 @@ class CommandManager { } } System.out.format(" java-matter-controller %s %s\n", clusterName, arguments) - val helpText = command.getHelpText() + val helpText = command.helpText if (helpText != null) { System.out.format("\n%s\n", helpText) } diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/CredentialsIssuer.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/CredentialsIssuer.kt index 806eac1635d486..d3e6d4e84fb48b 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/CredentialsIssuer.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/CredentialsIssuer.kt @@ -18,8 +18,7 @@ package com.matter.controller.commands.common /** - * @brief Credentials Issuer for the Command - * @details Contains all credential information of the issuer of the command, such as operational - * credentials for a given fabric, the DAC verifier of the commisioner, etc .. + * Credentials Issuer which contains all credential information of the issuer of the command, such + * as operational credentials for a given fabric, the DAC verifier of the commisioner, etc .. */ class CredentialsIssuer diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/FutureResult.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/FutureResult.kt index c7b16bdae2991c..c04abd99188e9b 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/FutureResult.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/FutureResult.kt @@ -18,6 +18,7 @@ package com.matter.controller.commands.common +import java.util.concurrent.TimeoutException import java.util.logging.Level import java.util.logging.Logger @@ -27,8 +28,6 @@ import java.util.logging.Logger * duration elapsed without receiving the expected realResult, the runtime exception would be * raised. */ -class RealResultException(message: String) : RuntimeException(message) - class FutureResult { private var realResult: RealResult? = null private var timeoutMs: Long = 0 @@ -42,7 +41,7 @@ class FutureResult { fun setRealResult(realResult: RealResult) { synchronized(lock) { if (this.realResult != null) { - throw RealResultException("Error, real result has been set!") + throw TimeoutException("Error, real result has been set!") } this.realResult = realResult lock.notifyAll() @@ -55,16 +54,16 @@ class FutureResult { while (realResult == null) { try { if (System.currentTimeMillis() > start + timeoutMs) { - throw RealResultException("Timeout!") + throw TimeoutException("Timeout!") } lock.wait() } catch (e: InterruptedException) { logger.log(Level.INFO, "Wait Result failed with exception: " + e.message) } } - if (realResult?.getResult() == false) { - logger.log(Level.INFO, "Error: ${realResult?.getError()}") - throw RealResultException("Received failure test result") + if (realResult?.result == false) { + logger.log(Level.INFO, "Error: ${realResult?.error}") + throw TimeoutException("Received failure test result") } } } diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/MatterCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/MatterCommand.kt index e2b3acf7efa314..8732ad6a3b521d 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/MatterCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/MatterCommand.kt @@ -20,7 +20,6 @@ package com.matter.controller.commands.common import chip.devicecontroller.ChipDeviceController import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong -import java.util.logging.Logger abstract class MatterCommand( private val chipDeviceController: ChipDeviceController, @@ -111,8 +110,4 @@ abstract class MatterCommand( fun clear() { futureResult.clear() } - - companion object { - private val logger = Logger.getLogger(MatterCommand::class.java.name) - } } diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/RealResult.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/RealResult.kt index 5cd5d80051efba..5ea218e32a2522 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/RealResult.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/RealResult.kt @@ -25,7 +25,7 @@ package com.matter.controller.commands.common * contain either a `true` value for `Success` or a `false` value in which case the failure will * also have an error string explaining the reason of the failure associated with it. */ -class RealResult(private val result: Boolean, private val error: String?) { +class RealResult(val result: Boolean, val error: String?) { constructor() : this(true, null) constructor(error: String?) : this(false, error) @@ -39,12 +39,4 @@ class RealResult(private val result: Boolean, private val error: String?) { return RealResult(error) } } - - fun getResult(): Boolean { - return result - } - - fun getError(): String? { - return error - } } From 25bc9cbfc035fa2dfd1b1dd6c96a98e8c2b7a3b8 Mon Sep 17 00:00:00 2001 From: shripad621git <79364691+shripad621git@users.noreply.github.com> Date: Thu, 5 Oct 2023 18:53:20 +0530 Subject: [PATCH 02/21] Implement the tracing macros using a backend for esp32. (#29543) * Implement the tracing macros using a backend for esp32. - This PR is aimed at addressing the review comments on PR https://github.com/project-chip/connectedhomeip/pull/29318. - This is a draft implementation of the backend. * Move esp32 tracing configs around: better location, integrate in build examples, carry over configurations * More options removals * Remove fixme text * Restrict tracing to light app, fix include paths in main, add ignore for authkey since that should not be checked in * Move dependencies around even more - esp32 now seems to compile with tracing enabled * Ensure tracing is actually enabled when insights is on * Restyle * Made esp32_trace backend in sync with existing version * Made the common include on the tracing config for all esp32 examples * Fixed the CI failure --------- Co-authored-by: Andrei Litvin --- config/esp32/BUILD.gn | 6 ++- config/esp32/components/chip/CMakeLists.txt | 17 +++++--- examples/lighting-app/esp32/.gitignore | 1 + .../lighting-app/esp32/main/CMakeLists.txt | 1 + examples/lighting-app/esp32/main/main.cpp | 35 ++++++++-------- scripts/build/build/targets.py | 1 + scripts/build/builders/esp32.py | 13 +++++- .../build/testdata/all_targets_linux_x64.txt | 2 +- .../dry_run_esp32-devkitc-light-rpc.txt | 2 + ...tack-all-clusters-minimal-rpc-ipv6only.txt | 2 + src/tracing/esp32_trace/BUILD.gn | 15 ++++++- .../macros_impl.cpp => esp32_tracing.cpp} | 40 ++++++++++++++----- src/tracing/esp32_trace/esp32_tracing.h | 34 ++++++++++++++++ .../include/matter/tracing/macros_impl.h | 39 +++++++++--------- src/tracing/tracing_args.gni | 23 +++-------- 15 files changed, 159 insertions(+), 72 deletions(-) rename src/tracing/esp32_trace/{include/matter/tracing/macros_impl.cpp => esp32_tracing.cpp} (64%) create mode 100644 src/tracing/esp32_trace/esp32_tracing.h diff --git a/config/esp32/BUILD.gn b/config/esp32/BUILD.gn index f8a1d83133f96d..1aacff5567ecf6 100644 --- a/config/esp32/BUILD.gn +++ b/config/esp32/BUILD.gn @@ -19,13 +19,17 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") import("${chip_root}/build/chip/tests.gni") +import("${chip_root}/src/tracing/tracing_args.gni") declare_args() { chip_build_pw_rpc_lib = false } group("esp32") { - deps = [ "${chip_root}/src/lib" ] + deps = [ + "${chip_root}/src/lib", + matter_trace_config, + ] if (chip_build_pw_rpc_lib) { deps += [ "//lib/pw_rpc" ] diff --git a/config/esp32/components/chip/CMakeLists.txt b/config/esp32/components/chip/CMakeLists.txt index 13beac09ce2153..3f0f59613db100 100644 --- a/config/esp32/components/chip/CMakeLists.txt +++ b/config/esp32/components/chip/CMakeLists.txt @@ -261,13 +261,18 @@ if (CONFIG_SEC_CERT_DAC_PROVIDER) endif() if (CONFIG_ENABLE_ESP_INSIGHTS_TRACE) - chip_gn_arg_append("matter_enable_esp_insights_trace" "true") + chip_gn_arg_bool("matter_enable_tracing_support" "true") + chip_gn_arg_append("matter_trace_config" "\"${CHIP_ROOT}/src/tracing/esp32_trace:esp32_trace_tracing\"") endif() if (CONFIG_USE_ESP32_ECDSA_PERIPHERAL) chip_gn_arg_append("chip_use_esp32_ecdsa_peripheral" "true") endif() +if (CONFIG_ENABLE_ESP_INSIGHTS_TRACE) + target_include_directories(${COMPONENT_LIB} INTERFACE "${CHIP_ROOT}/src/tracing/esp32_trace/include") +endif() + set(args_gn_input "${CMAKE_CURRENT_BINARY_DIR}/args.gn.in") file(GENERATE OUTPUT "${args_gn_input}" CONTENT "${chip_gn_args}") @@ -318,7 +323,11 @@ set(GN_ROOT_TARGET ${CHIP_ROOT}/config/esp32) set(chip_libraries "${CMAKE_CURRENT_BINARY_DIR}/lib/libCHIP.a") if(CONFIG_ENABLE_PW_RPC) - list(APPEND chip_libraries "${CMAKE_CURRENT_BINARY_DIR}/lib/libPwRpc.a") + list(APPEND chip_libraries "${CMAKE_CURRENT_BINARY_DIR}/lib/libPwRpc.a") +endif() + +if (CONFIG_ENABLE_ESP_INSIGHTS_TRACE) + list(APPEND chip_libraries "${CMAKE_CURRENT_BINARY_DIR}/lib/libEsp32TracingBackend.a") endif() # When using the pregenerated files, there is a edge case where an error appears for @@ -371,10 +380,6 @@ target_include_directories(${COMPONENT_LIB} INTERFACE "${CHIP_ROOT}/config/esp32/${CONFIG_CHIP_EXTERNAL_PLATFORM_DIR}/../../" ) -if (CONFIG_ENABLE_ESP_INSIGHTS_TRACE) - target_include_directories(${COMPONENT_LIB} INTERFACE "${CHIP_ROOT}/src/tracing/esp32_trace/include") -endif() - idf_component_get_property(mbedtls_lib mbedtls COMPONENT_LIB) idf_build_get_property(idf_target IDF_TARGET) diff --git a/examples/lighting-app/esp32/.gitignore b/examples/lighting-app/esp32/.gitignore index a90ab6f1e57d5a..601ff1b8e9e01e 100644 --- a/examples/lighting-app/esp32/.gitignore +++ b/examples/lighting-app/esp32/.gitignore @@ -1,3 +1,4 @@ /build/ /sdkconfig /sdkconfig.old +main/insights_auth_key.txt diff --git a/examples/lighting-app/esp32/main/CMakeLists.txt b/examples/lighting-app/esp32/main/CMakeLists.txt index a3149e3fc7df90..96279bd4d83dde 100644 --- a/examples/lighting-app/esp32/main/CMakeLists.txt +++ b/examples/lighting-app/esp32/main/CMakeLists.txt @@ -73,6 +73,7 @@ if(${IDF_TARGET} STREQUAL "esp32") list(APPEND PRIV_REQUIRES_LIST spidriver screen-framework) endif() + if (CONFIG_ENABLE_PW_RPC) # Append additional directories for RPC build set(PRIV_INCLUDE_DIRS_LIST "${PRIV_INCLUDE_DIRS_LIST}" diff --git a/examples/lighting-app/esp32/main/main.cpp b/examples/lighting-app/esp32/main/main.cpp index 79247258658dd8..280131263efa96 100644 --- a/examples/lighting-app/esp32/main/main.cpp +++ b/examples/lighting-app/esp32/main/main.cpp @@ -18,11 +18,10 @@ #include "DeviceCallbacks.h" #include "AppTask.h" +#include "esp_log.h" #include #include #include - -#include "esp_log.h" #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) #include "spi_flash_mmap.h" #else @@ -61,6 +60,8 @@ #if CONFIG_ENABLE_ESP_INSIGHTS_TRACE #include +#include +#include #endif using namespace ::chip; @@ -113,6 +114,22 @@ static void InitServer(intptr_t context) DeviceCallbacksDelegate::Instance().SetAppDelegate(&sAppDeviceCallbacksDelegate); Esp32AppServer::Init(); // Init ZCL Data Model and CHIP App Server AND Initialize device attestation config +#if CONFIG_ENABLE_ESP_INSIGHTS_TRACE + esp_insights_config_t config = { + .log_type = ESP_DIAG_LOG_TYPE_ERROR | ESP_DIAG_LOG_TYPE_WARNING | ESP_DIAG_LOG_TYPE_EVENT, + .auth_key = insights_auth_key_start, + }; + + esp_err_t ret = esp_insights_init(&config); + + if (ret != ESP_OK) + { + ESP_LOGE(TAG, "Failed to initialize ESP Insights, err:0x%x", ret); + } + + static Tracing::Insights::ESP32Backend backend; + Tracing::Register(backend); +#endif } extern "C" void app_main() @@ -134,20 +151,6 @@ extern "C" void app_main() chip::rpc::Init(); #endif -#if CONFIG_ENABLE_ESP_INSIGHTS_TRACE - esp_insights_config_t config = { - .log_type = ESP_DIAG_LOG_TYPE_ERROR | ESP_DIAG_LOG_TYPE_WARNING | ESP_DIAG_LOG_TYPE_EVENT, - .auth_key = insights_auth_key_start, - }; - - esp_err_t ret = esp_insights_init(&config); - - if (ret != ESP_OK) - { - ESP_LOGE(TAG, "Failed to initialize ESP Insights, err:0x%x", ret); - } -#endif - ESP_LOGI(TAG, "=================================================="); ESP_LOGI(TAG, "chip-esp32-light-example starting"); ESP_LOGI(TAG, "=================================================="); diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index 03089edd1d5571..758c10d80add19 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -206,6 +206,7 @@ def BuildEsp32Target(): target.AppendModifier('rpc', enable_rpcs=True) target.AppendModifier('ipv6only', enable_ipv4=False) + target.AppendModifier('tracing', enable_insights_trace=True).OnlyIfRe("light") return target diff --git a/scripts/build/builders/esp32.py b/scripts/build/builders/esp32.py index 9c7f62915686d2..39573a968e52f1 100644 --- a/scripts/build/builders/esp32.py +++ b/scripts/build/builders/esp32.py @@ -147,13 +147,15 @@ def __init__(self, board: Esp32Board = Esp32Board.M5Stack, app: Esp32App = Esp32App.ALL_CLUSTERS, enable_rpcs: bool = False, - enable_ipv4: bool = True + enable_ipv4: bool = True, + enable_insights_trace: bool = False ): super(Esp32Builder, self).__init__(root, runner) self.board = board self.app = app self.enable_rpcs = enable_rpcs self.enable_ipv4 = enable_ipv4 + self.enable_insights_trace = enable_insights_trace if not app.IsCompatible(board): raise Exception( @@ -191,6 +193,15 @@ def generate(self): self._Execute( ['bash', '-c', 'echo -e "\\nCONFIG_DISABLE_IPV4=y\\n" >>%s' % shlex.quote(defaults_out)]) + if self.enable_insights_trace: + insights_flag = 'y' + else: + insights_flag = 'n' + + # pre-requisite + self._Execute( + ['bash', '-c', 'echo -e "\\nCONFIG_ESP_INSIGHTS_ENABLED=%s\\nCONFIG_ENABLE_ESP_INSIGHTS_TRACE=%s\\n" >>%s' % (insights_flag, insights_flag, shlex.quote(defaults_out))]) + cmake_flags = [] if self.options.pregen_dir: diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index c78c87b83fda35..57604bc8e3aa08 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -7,7 +7,7 @@ ti-cc13x2x7_26x2x7-{lighting,lock,pump,pump-controller}[-mtd] ti-cc13x4_26x4-{all-clusters,lighting,lock,pump,pump-controller}[-mtd][-ftd] cyw30739-cyw930739m2evb_01-{light,lock,ota-requestor,switch} efr32-{brd4161a,brd4187c,brd4186c,brd4163a,brd4164a,brd4166a,brd4170a,brd4186a,brd4187a,brd4304a}-{window-covering,switch,unit-test,light,lock,thermostat,pump}[-rpc][-with-ota-requestor][-icd][-low-power][-shell][-no_logging][-openthread_mtd][-enable_heap_monitoring][-no_openthread_cli][-show_qr_code][-wifi][-rs911x][-wf200][-wifi_ipv4][-additional_data_advertising][-use_ot_lib][-use_ot_coap_lib][-no-version] -esp32-{m5stack,c3devkit,devkitc,qemu}-{all-clusters,all-clusters-minimal,ota-provider,ota-requestor,shell,light,lock,bridge,temperature-measurement,ota-requestor,tests}[-rpc][-ipv6only] +esp32-{m5stack,c3devkit,devkitc,qemu}-{all-clusters,all-clusters-minimal,ota-provider,ota-requestor,shell,light,lock,bridge,temperature-measurement,ota-requestor,tests}[-rpc][-ipv6only][-tracing] genio-lighting-app linux-fake-tests[-mbedtls][-boringssl][-asan][-tsan][-ubsan][-libfuzzer][-ossfuzz][-coverage][-dmalloc][-clang] linux-{x64,arm64}-{rpc-console,all-clusters,all-clusters-minimal,chip-tool,thermostat,java-matter-controller,minmdns,light,lock,shell,ota-provider,ota-requestor,simulated-app1,simulated-app2,python-bindings,tv-app,tv-casting-app,bridge,tests,chip-cert,address-resolve-tool,contact-sensor,dishwasher,refrigerator,rvc}[-nodeps][-platform-mdns][-minmdns-verbose][-libnl][-same-event-loop][-no-interactive][-ipv6only][-no-ble][-no-wifi][-no-thread][-mbedtls][-boringssl][-asan][-tsan][-ubsan][-libfuzzer][-ossfuzz][-coverage][-dmalloc][-clang][-test][-rpc][-with-ui] diff --git a/scripts/build/testdata/dry_run_esp32-devkitc-light-rpc.txt b/scripts/build/testdata/dry_run_esp32-devkitc-light-rpc.txt index e949510f99de97..cb5e3df310e36d 100644 --- a/scripts/build/testdata/dry_run_esp32-devkitc-light-rpc.txt +++ b/scripts/build/testdata/dry_run_esp32-devkitc-light-rpc.txt @@ -8,6 +8,8 @@ cp examples/lighting-app/esp32/sdkconfig_rpc.defaults {out}/esp32-devkitc-light- rm -f examples/lighting-app/esp32/sdkconfig +bash -c 'echo -e "\nCONFIG_ESP_INSIGHTS_ENABLED=n\nCONFIG_ENABLE_ESP_INSIGHTS_TRACE=n\n" >>{out}/esp32-devkitc-light-rpc/sdkconfig.defaults' + bash -c 'source $IDF_PATH/export.sh; source scripts/activate.sh; export SDKCONFIG_DEFAULTS={out}/esp32-devkitc-light-rpc/sdkconfig.defaults idf.py -C examples/lighting-app/esp32 -B {out}/esp32-devkitc-light-rpc reconfigure' diff --git a/scripts/build/testdata/dry_run_esp32-m5stack-all-clusters-minimal-rpc-ipv6only.txt b/scripts/build/testdata/dry_run_esp32-m5stack-all-clusters-minimal-rpc-ipv6only.txt index f82dd8a53e8a64..708d254115dc33 100644 --- a/scripts/build/testdata/dry_run_esp32-m5stack-all-clusters-minimal-rpc-ipv6only.txt +++ b/scripts/build/testdata/dry_run_esp32-m5stack-all-clusters-minimal-rpc-ipv6only.txt @@ -10,6 +10,8 @@ rm -f examples/all-clusters-minimal-app/esp32/sdkconfig bash -c 'echo -e "\nCONFIG_DISABLE_IPV4=y\n" >>{out}/esp32-m5stack-all-clusters-minimal-rpc-ipv6only/sdkconfig.defaults' +bash -c 'echo -e "\nCONFIG_ESP_INSIGHTS_ENABLED=n\nCONFIG_ENABLE_ESP_INSIGHTS_TRACE=n\n" >>{out}/esp32-m5stack-all-clusters-minimal-rpc-ipv6only/sdkconfig.defaults' + bash -c 'source $IDF_PATH/export.sh; source scripts/activate.sh; export SDKCONFIG_DEFAULTS={out}/esp32-m5stack-all-clusters-minimal-rpc-ipv6only/sdkconfig.defaults idf.py -C examples/all-clusters-minimal-app/esp32 -B {out}/esp32-m5stack-all-clusters-minimal-rpc-ipv6only reconfigure' diff --git a/src/tracing/esp32_trace/BUILD.gn b/src/tracing/esp32_trace/BUILD.gn index d7580a3e68ac2a..cb41004a74289b 100644 --- a/src/tracing/esp32_trace/BUILD.gn +++ b/src/tracing/esp32_trace/BUILD.gn @@ -20,8 +20,19 @@ config("tracing") { include_dirs = [ "include" ] } -source_set("esp32_trace") { +static_library("backend") { + output_name = "libEsp32TracingBackend" + output_dir = "${root_out_dir}/lib" + + sources = [ + "esp32_tracing.cpp", + "esp32_tracing.h", + ] + public_deps = [ "${chip_root}/src/tracing" ] +} + +source_set("esp32_trace_tracing") { public = [ "include/matter/tracing/macros_impl.h" ] - sources = [ "include/matter/tracing/macros_impl.cpp" ] public_configs = [ ":tracing" ] + deps = [ ":backend" ] } diff --git a/src/tracing/esp32_trace/include/matter/tracing/macros_impl.cpp b/src/tracing/esp32_trace/esp32_tracing.cpp similarity index 64% rename from src/tracing/esp32_trace/include/matter/tracing/macros_impl.cpp rename to src/tracing/esp32_trace/esp32_tracing.cpp index 7046dd9cc8d7d9..414cdd83edcc0d 100644 --- a/src/tracing/esp32_trace/include/matter/tracing/macros_impl.cpp +++ b/src/tracing/esp32_trace/esp32_tracing.cpp @@ -1,5 +1,7 @@ /* + * * Copyright (c) 2023 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. @@ -14,9 +16,15 @@ * limitations under the License. */ -#include "macros_impl.h" +#include "esp32_tracing.h" #include #include +#include +#include +#include + +namespace chip { +namespace Tracing { namespace Insights { #define LOG_HEAP_INFO(label, group, entry_exit) \ @@ -28,17 +36,31 @@ namespace Insights { heap_caps_get_free_size(MALLOC_CAP_8BIT)); \ } while (0) -ESP32Backend::ESP32Backend(const char * str, ...) +void ESP32Backend::LogMessageReceived(MessageReceivedInfo & info) {} + +void ESP32Backend::LogMessageSend(MessageSendInfo & info) {} + +void ESP32Backend::LogNodeLookup(NodeLookupInfo & info) {} + +void ESP32Backend::LogNodeDiscovered(NodeDiscoveredInfo & info) {} + +void ESP32Backend::LogNodeDiscoveryFailed(NodeDiscoveryFailedInfo & info) {} + +void ESP32Backend::TraceBegin(const char * label, const char * group) +{ + LOG_HEAP_INFO(label, group, "Entry"); +} + +void ESP32Backend::TraceEnd(const char * label, const char * group) { - va_list args; - va_start(args, str); - mlabel = str; - mgroup = va_arg(args, const char *); - LOG_HEAP_INFO(mlabel, mgroup, "Entry"); + LOG_HEAP_INFO(label, group, "Exit"); } -ESP32Backend::~ESP32Backend() +void ESP32Backend::TraceInstant(const char * label, const char * group) { - LOG_HEAP_INFO(mlabel, mgroup, "Exit"); + ESP_DIAG_EVENT("MTR_TRC", "Instant : %s -%s", label, group); } } // namespace Insights +} // namespace Tracing +} // namespace chip +// namespace chip diff --git a/src/tracing/esp32_trace/esp32_tracing.h b/src/tracing/esp32_trace/esp32_tracing.h new file mode 100644 index 00000000000000..9857eb111b2c3d --- /dev/null +++ b/src/tracing/esp32_trace/esp32_tracing.h @@ -0,0 +1,34 @@ +#include + +#include + +namespace chip { +namespace Tracing { +namespace Insights { + +/// A Backend that outputs data to chip logging. +/// +/// Structured data is formatted as json strings. +class ESP32Backend : public ::chip::Tracing::Backend +{ +public: + ESP32Backend() = default; + + void TraceBegin(const char * label, const char * group) override; + + void TraceEnd(const char * label, const char * group) override; + + /// Trace a zero-sized event + void TraceInstant(const char * label, const char * group) override; + + void LogMessageSend(MessageSendInfo &) override; + void LogMessageReceived(MessageReceivedInfo &) override; + + void LogNodeLookup(NodeLookupInfo &) override; + void LogNodeDiscovered(NodeDiscoveredInfo &) override; + void LogNodeDiscoveryFailed(NodeDiscoveryFailedInfo &) override; +}; + +} // namespace Insights +} // namespace Tracing +} // namespace chip diff --git a/src/tracing/esp32_trace/include/matter/tracing/macros_impl.h b/src/tracing/esp32_trace/include/matter/tracing/macros_impl.h index 1ab529313c3192..4d8a8a2a214525 100644 --- a/src/tracing/esp32_trace/include/matter/tracing/macros_impl.h +++ b/src/tracing/esp32_trace/include/matter/tracing/macros_impl.h @@ -1,4 +1,5 @@ /* + * * Copyright (c) 2023 Project CHIP Authors * All rights reserved. * @@ -21,30 +22,30 @@ #error "Tracing macros seem to be double defined" #endif +#include + +// This gets forwarded to the multiplexed instance +#define MATTER_TRACE_BEGIN(label, group) ::chip::Tracing::Internal::Begin(label, group) +#define MATTER_TRACE_END(label, group) ::chip::Tracing::Internal::End(label, group) +#define MATTER_TRACE_INSTANT(label, group) ::chip::Tracing::Internal::Instant(label, group) + +namespace chip { +namespace Tracing { namespace Insights { -class ESP32Backend +class Scoped { public: - ESP32Backend(const char * str, ...); - ~ESP32Backend(); + inline Scoped(const char * label, const char * group) : mLabel(label), mGroup(group) { MATTER_TRACE_BEGIN(label, group); } + inline ~Scoped() { MATTER_TRACE_END(mLabel, mGroup); } private: - const char * mlabel; - const char * mgroup; + const char * mLabel; + const char * mGroup; }; } // namespace Insights +} // namespace Tracing +} // namespace chip +#define _CONCAT_IMPL(a, b) a##b +#define _MACRO_CONCAT(a, b) _CONCAT_IMPL(a, b) -#define MATTER_TRACE_SCOPE(...) \ - do \ - { \ - Insights::ESP32Backend backend(__VA_ARGS__); \ - } while (0) - -#define _MATTER_TRACE_DISABLE(...) \ - do \ - { \ - } while (false) - -#define MATTER_TRACE_BEGIN(...) _MATTER_TRACE_DISABLE(__VA_ARGS__) -#define MATTER_TRACE_END(...) _MATTER_TRACE_DISABLE(__VA_ARGS__) -#define MATTER_TRACE_INSTANT(...) _MATTER_TRACE_DISABLE(__VA_ARGS__) +#define MATTER_TRACE_SCOPE(label, group) ::chip::Tracing::Insights::Scoped _MACRO_CONCAT(_trace_scope, __COUNTER__)(label, group) diff --git a/src/tracing/tracing_args.gni b/src/tracing/tracing_args.gni index 8c4dbd66656b88..d3741b5eba5f10 100644 --- a/src/tracing/tracing_args.gni +++ b/src/tracing/tracing_args.gni @@ -23,7 +23,7 @@ declare_args() { # # Additionally, if tracing is enabled, the main() function has to add # backends explicitly - matter_enable_tracing_support = false + matter_enable_tracing_support = current_os == "android" # Defines the trace backend. Current matter tracing splits the logic # into two parts: @@ -44,20 +44,9 @@ declare_args() { # since tracing is very noisy, we generally expect it to be explicitly # set up. # - matter_trace_config = "" - matter_enable_esp_insights_trace = false -} - -if (current_os == "android" || - (chip_device_platform == "esp32" && matter_enable_esp_insights_trace)) { - matter_enable_tracing_support = true -} - -if (current_os == "linux" || current_os == "android") { - matter_trace_config = "${chip_root}/src/tracing/perfetto:perfetto_tracing" -} else if (chip_device_platform == "esp32" && - matter_enable_esp_insights_trace) { - matter_trace_config = "${chip_root}/src/tracing/esp32_trace" -} else { - matter_trace_config = "${chip_root}/src/tracing/none" + if (current_os == "linux" || current_os == "android") { + matter_trace_config = "${chip_root}/src/tracing/perfetto:perfetto_tracing" + } else { + matter_trace_config = "${chip_root}/src/tracing/none" + } } From f03e9ef0623b6488045b64798bab045336bc28ac Mon Sep 17 00:00:00 2001 From: lpbeliveau-silabs <112982107+lpbeliveau-silabs@users.noreply.github.com> Date: Thu, 5 Oct 2023 09:27:10 -0400 Subject: [PATCH 03/21] [Scenes] Explicit feature flag (#29535) * Enforced Explicit support in scene server and added default values to scene cluster where enabled * Fixed overwrite in attributes --- .../all-clusters-app.matter | 16 +++++----- .../all-clusters-common/all-clusters-app.zap | 31 ++++++++++--------- .../all-clusters-minimal-app.matter | 16 +++++----- .../all-clusters-minimal-app.zap | 19 ++++++------ .../lighting-common/lighting-app.matter | 6 ++-- .../lighting-common/lighting-app.zap | 9 +++--- .../data_model/lighting-thread-app.matter | 2 +- .../silabs/data_model/lighting-thread-app.zap | 5 +-- .../data_model/lighting-wifi-app.matter | 6 ++-- .../silabs/data_model/lighting-wifi-app.zap | 9 +++--- .../clusters/scenes-server/scenes-server.cpp | 7 +++-- 11 files changed, 67 insertions(+), 59 deletions(-) diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter index 4b5bef308bf47c..1b65362b884cff 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter @@ -6558,15 +6558,15 @@ endpoint 1 { ram attribute currentScene default = 0x00; ram attribute currentGroup default = 0x0000; ram attribute sceneValid default = 0x00; - ram attribute nameSupport; + ram attribute nameSupport default = 0x80; ram attribute lastConfiguredBy; - ram attribute sceneTableSize; - callback attribute remainingCapacity; + ram attribute sceneTableSize default = 16; + callback attribute remainingCapacity default = 8; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute eventList; callback attribute attributeList; - ram attribute featureMap default = 0; + ram attribute featureMap default = 3; ram attribute clusterRevision default = 5; } @@ -7606,14 +7606,14 @@ endpoint 2 { ram attribute currentScene default = 0x00; ram attribute currentGroup default = 0x0000; ram attribute sceneValid default = 0x00; - ram attribute nameSupport; - ram attribute sceneTableSize; - callback attribute remainingCapacity; + ram attribute nameSupport default = 0x80; + ram attribute sceneTableSize default = 16; + callback attribute remainingCapacity default = 8; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute eventList; callback attribute attributeList; - ram attribute featureMap default = 0; + ram attribute featureMap default = 3; ram attribute clusterRevision default = 5; } diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap b/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap index c7ccc67b4b7089..ba764f395d8b43 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap @@ -16,6 +16,12 @@ } ], "package": [ + { + "pathRelativity": "relativeToZap", + "path": "../../../src/app/zap-templates/app-templates.json", + "type": "gen-templates-json", + "version": "chip-v1" + }, { "pathRelativity": "relativeToZap", "path": "../../../src/app/zap-templates/zcl/zcl-with-test-extensions.json", @@ -23,12 +29,6 @@ "category": "matter", "version": 1, "description": "Matter SDK ZCL data with some extensions" - }, - { - "pathRelativity": "relativeToZap", - "path": "../../../src/app/zap-templates/app-templates.json", - "type": "gen-templates-json", - "version": "chip-v1" } ], "endpointTypes": [ @@ -11207,7 +11207,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "0x80", "reportable": 1, "minInterval": 0, "maxInterval": 65344, @@ -11239,7 +11239,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "16", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -11255,7 +11255,7 @@ "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "8", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -11335,7 +11335,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "3", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -31301,7 +31301,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "0x80", "reportable": 1, "minInterval": 0, "maxInterval": 65344, @@ -31333,7 +31333,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "16", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -31349,7 +31349,7 @@ "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "8", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -31429,7 +31429,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "3", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -35392,5 +35392,6 @@ "endpointId": 65534, "networkId": 0 } - ] + ], + "log": [] } \ No newline at end of file diff --git a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter index 29b2c68c9592ca..5263ae74ab7aae 100644 --- a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter +++ b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter @@ -4285,15 +4285,15 @@ endpoint 1 { ram attribute currentScene default = 0x00; ram attribute currentGroup default = 0x0000; ram attribute sceneValid default = 0x00; - ram attribute nameSupport; + ram attribute nameSupport default = 0x80; ram attribute lastConfiguredBy; - ram attribute sceneTableSize; - callback attribute remainingCapacity; + ram attribute sceneTableSize default = 16; + callback attribute remainingCapacity default = 8; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute eventList; callback attribute attributeList; - ram attribute featureMap default = 0; + ram attribute featureMap default = 3; ram attribute clusterRevision default = 5; } @@ -4733,14 +4733,14 @@ endpoint 2 { ram attribute currentScene default = 0x00; ram attribute currentGroup default = 0x0000; ram attribute sceneValid default = 0x00; - ram attribute nameSupport; - ram attribute sceneTableSize; - callback attribute remainingCapacity; + ram attribute nameSupport default = 0x80; + ram attribute sceneTableSize default = 16; + callback attribute remainingCapacity default = 8; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute eventList; callback attribute attributeList; - ram attribute featureMap default = 0; + ram attribute featureMap default = 3; ram attribute clusterRevision default = 5; } diff --git a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap index 97f716a40c3269..66e573b7eee68d 100644 --- a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap +++ b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap @@ -10259,7 +10259,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "0x80", "reportable": 1, "minInterval": 0, "maxInterval": 65344, @@ -10291,7 +10291,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "16", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -10307,7 +10307,7 @@ "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "8", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -10387,7 +10387,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "3", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -23497,7 +23497,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "0x80", "reportable": 1, "minInterval": 0, "maxInterval": 65344, @@ -23529,7 +23529,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "16", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -23545,7 +23545,7 @@ "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "8", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -23625,7 +23625,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "3", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -27588,5 +27588,6 @@ "endpointId": 65534, "networkId": 0 } - ] + ], + "log": [] } \ No newline at end of file diff --git a/examples/lighting-app/lighting-common/lighting-app.matter b/examples/lighting-app/lighting-common/lighting-app.matter index dd21ff69f24b6b..8b23739d141ca2 100644 --- a/examples/lighting-app/lighting-common/lighting-app.matter +++ b/examples/lighting-app/lighting-common/lighting-app.matter @@ -2409,12 +2409,12 @@ endpoint 1 { ram attribute sceneValid default = 0x00; ram attribute nameSupport default = 0x80; ram attribute lastConfiguredBy; - ram attribute sceneTableSize; - callback attribute remainingCapacity; + ram attribute sceneTableSize default = 16; + callback attribute remainingCapacity default = 8; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute attributeList; - ram attribute featureMap default = 1; + ram attribute featureMap default = 3; ram attribute clusterRevision default = 5; } diff --git a/examples/lighting-app/lighting-common/lighting-app.zap b/examples/lighting-app/lighting-common/lighting-app.zap index f76450d1cf3da0..8691f80f322578 100644 --- a/examples/lighting-app/lighting-common/lighting-app.zap +++ b/examples/lighting-app/lighting-common/lighting-app.zap @@ -5332,7 +5332,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "16", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -5348,7 +5348,7 @@ "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "8", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -5428,7 +5428,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "1", + "defaultValue": "3", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -7796,5 +7796,6 @@ "endpointId": 1, "networkId": 0 } - ] + ], + "log": [] } \ No newline at end of file diff --git a/examples/lighting-app/silabs/data_model/lighting-thread-app.matter b/examples/lighting-app/silabs/data_model/lighting-thread-app.matter index 227c72d986bf53..c004f45f28032a 100644 --- a/examples/lighting-app/silabs/data_model/lighting-thread-app.matter +++ b/examples/lighting-app/silabs/data_model/lighting-thread-app.matter @@ -2435,7 +2435,7 @@ endpoint 1 { callback attribute acceptedCommandList; callback attribute eventList; callback attribute attributeList; - ram attribute featureMap default = 0; + ram attribute featureMap default = 3; ram attribute clusterRevision default = 5; } diff --git a/examples/lighting-app/silabs/data_model/lighting-thread-app.zap b/examples/lighting-app/silabs/data_model/lighting-thread-app.zap index d72f2154672a38..12a6f5113997cc 100644 --- a/examples/lighting-app/silabs/data_model/lighting-thread-app.zap +++ b/examples/lighting-app/silabs/data_model/lighting-thread-app.zap @@ -6673,7 +6673,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "3", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -9546,5 +9546,6 @@ "endpointId": 1, "networkId": 0 } - ] + ], + "log": [] } \ No newline at end of file diff --git a/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter b/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter index 2d6ba3b041704c..2f40d35ce34b71 100644 --- a/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter +++ b/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter @@ -2269,13 +2269,13 @@ endpoint 1 { ram attribute sceneValid default = 0x00; ram attribute nameSupport default = 0x80; ram attribute lastConfiguredBy; - ram attribute sceneTableSize; - callback attribute remainingCapacity; + ram attribute sceneTableSize default = 16; + callback attribute remainingCapacity default = 8; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute eventList; callback attribute attributeList; - ram attribute featureMap default = 1; + ram attribute featureMap default = 3; ram attribute clusterRevision default = 5; } diff --git a/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap b/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap index 83ba6bb6da3a47..10f51fcb45e0b9 100644 --- a/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap +++ b/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap @@ -6299,7 +6299,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "16", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -6315,7 +6315,7 @@ "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "8", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -6395,7 +6395,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "1", + "defaultValue": "3", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -9631,5 +9631,6 @@ "endpointId": 1, "networkId": 0 } - ] + ], + "log": [] } \ No newline at end of file diff --git a/src/app/clusters/scenes-server/scenes-server.cpp b/src/app/clusters/scenes-server/scenes-server.cpp index 4cfc016e7be038..9fe876315cdf5a 100644 --- a/src/app/clusters/scenes-server/scenes-server.cpp +++ b/src/app/clusters/scenes-server/scenes-server.cpp @@ -115,10 +115,13 @@ CHIP_ERROR ScenesServer::Init() for (auto endpoint : EnabledEndpointsWithServerCluster(Id)) { - EmberAfStatus status = Attributes::FeatureMap::Set(endpoint, to_underlying(Feature::kSceneNames)); + // Explicit AttributeValuePairs is mandatory for matter so we force it here, ScenesName is not but it is forced for now + // TODO: We currently force SceneNames on but this needs to be modified to read the value generated from Zap instead. + uint32_t featureMap = to_underlying(Feature::kExplicit) | to_underlying(Feature::kSceneNames); + EmberAfStatus status = Attributes::FeatureMap::Set(endpoint, featureMap); if (EMBER_ZCL_STATUS_SUCCESS != status) { - ChipLogDetail(Zcl, "ERR: setting feature map on Endpoint %hu Status: %x", endpoint, status); + ChipLogDetail(Zcl, "ERR: setting the scenes FeatureMap on Endpoint %hu Status: %x", endpoint, status); } // The bit of 7 the NameSupport attribute indicates whether or not scene names are supported // From 3f34c52cf5658621701061584bcd28b39356b3b9 Mon Sep 17 00:00:00 2001 From: ChinchillaWithGoggles <70608922+ChinchillaWithGoggles@users.noreply.github.com> Date: Thu, 5 Oct 2023 09:13:00 -0700 Subject: [PATCH 04/21] tests: Use CancellableReader for PW RPC clients (#29567) The CancellableReader provides a clean teardown of an RpcClient reader thread at exit. Switching from using readers and RpcClients directly to context statements makes sure the teardown is done. This change is adapts to a recent change in Pigweed's RPC Python library: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/172051 --- .../efr32/py/nl_test_runner/nl_test_runner.py | 12 +- .../common/pigweed_client.py | 18 ++- .../lighting-app/test_app.py | 112 +++++++++--------- .../integration_tests/lock-app/test_app.py | 112 +++++++++--------- .../integration_tests/pigweed-app/test_app.py | 10 +- 5 files changed, 140 insertions(+), 124 deletions(-) diff --git a/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py b/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py index b4f096afed100d..0fdb2e7aea7e3d 100644 --- a/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py +++ b/src/test_driver/efr32/py/nl_test_runner/nl_test_runner.py @@ -23,7 +23,7 @@ from typing import Any import serial # type: ignore -from pw_hdlc.rpc import HdlcRpcClient, default_channels, write_to_file +from pw_hdlc import rpc # RPC Protos from nl_test_service import nl_test_pb2 # isort:skip @@ -81,10 +81,10 @@ def flash_device(device: str, flash_image: str, **kwargs): def get_hdlc_rpc_client(device: str, baudrate: int, output: Any, **kwargs): """Get the HdlcRpcClient based on arguments.""" serial_device = serial.Serial(device, baudrate, timeout=1) - def read(): return serial_device.read(8192) + reader = rpc.SerialReader(serial_device, 8192) write = serial_device.write - return HdlcRpcClient(read, PROTOS, default_channels(write), - lambda data: write_to_file(data, output)) + return rpc.HdlcRpcClient(reader, PROTOS, rpc.default_channels(write), + lambda data: rpc.write_to_file(data, output)) def runner(client) -> int: @@ -133,8 +133,8 @@ def main() -> int: if args.flash_image: flash_device(**vars(args)) time.sleep(1) # Give time for device to boot - client = get_hdlc_rpc_client(**vars(args)) - return runner(client) + with get_hdlc_rpc_client(**vars(args)) as client: + return runner(client) if __name__ == '__main__': diff --git a/src/test_driver/mbed/integration_tests/common/pigweed_client.py b/src/test_driver/mbed/integration_tests/common/pigweed_client.py index 9d7d6a341a1613..b4c872fd58bf81 100644 --- a/src/test_driver/mbed/integration_tests/common/pigweed_client.py +++ b/src/test_driver/mbed/integration_tests/common/pigweed_client.py @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from pw_hdlc.rpc import HdlcRpcClient, default_channels +from pw_hdlc import rpc class PigweedClient: @@ -28,8 +28,11 @@ def __init__(self, device, protos): self.device.stop() self.last_timeout = self.device.serial.get_timeout() self.device.serial.set_timeout(0.01) - self._pw_rpc_client = HdlcRpcClient(lambda: self.device.serial.read(4096), - protos, default_channels(self.device.serial.write)) + reader = rpc.Serialreader(self.device.serial, 4096) + self._pw_rpc_client = rpc.HdlcRpcClient( + reader, + protos, + rpc.default_channels(self.device.serial.write)) self._rpcs = self._pw_rpc_client.rpcs() def __del__(self): @@ -39,3 +42,12 @@ def __del__(self): @property def rpcs(self): return self._rpcs + + def __enter__(self) -> 'PigweedClient': + return self + + def __exit__(self, *exc_info) -> None: + self.stop() + + def stop(self) -> None: + self._pw_rpc_client.stop() diff --git a/src/test_driver/mbed/integration_tests/lighting-app/test_app.py b/src/test_driver/mbed/integration_tests/lighting-app/test_app.py index 67041a6720b813..7c302fad32ae57 100644 --- a/src/test_driver/mbed/integration_tests/lighting-app/test_app.py +++ b/src/test_driver/mbed/integration_tests/lighting-app/test_app.py @@ -146,77 +146,79 @@ def test_light_ctrl(device, network): def test_device_info_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) - status, payload = pw_client.rpcs.chip.rpc.Device.GetDeviceInfo() - assert status.ok() is True - assert payload.vendor_id is not None and payload.product_id is not None and payload.serial_number is not None + with PigweedClient(device, RPC_PROTOS) as pw_client: + status, payload = pw_client.rpcs.chip.rpc.Device.GetDeviceInfo() + assert status.ok() is True + assert payload.vendor_id is not None and payload.product_id is not None and payload.serial_number is not None - device_details = get_device_details(device) - assert device_details is not None and len(device_details) != 0 + device_details = get_device_details(device) + assert device_details is not None and len(device_details) != 0 - assert int(device_details["VendorID"]) == payload.vendor_id - assert int(device_details["ProductID"]) == payload.product_id - assert int(device_details["Discriminator"] - ) == payload.pairing_info.discriminator - assert int(device_details["SetUpPINCode"]) == payload.pairing_info.code + assert int(device_details["VendorID"]) == payload.vendor_id + assert int(device_details["ProductID"]) == payload.product_id + assert int(device_details["Discriminator"] + ) == payload.pairing_info.discriminator + assert int(device_details["SetUpPINCode"]) == payload.pairing_info.code def test_device_factory_reset_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) - status, payload = pw_client.rpcs.chip.rpc.Device.FactoryReset() - assert status.ok() is True + with PigweedClient(device, RPC_PROTOS) as pw_client: + status, payload = pw_client.rpcs.chip.rpc.Device.FactoryReset() + assert status.ok() is True def test_device_reboot_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) - status, payload = pw_client.rpcs.chip.rpc.Device.Reboot() - assert status == Status.UNIMPLEMENTED + with PigweedClient(device, RPC_PROTOS) as pw_client: + status, payload = pw_client.rpcs.chip.rpc.Device.Reboot() + assert status == Status.UNIMPLEMENTED def test_device_ota_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) - status, payload = pw_client.rpcs.chip.rpc.Device.TriggerOta() - assert status == Status.UNIMPLEMENTED + with PigweedClient(device, RPC_PROTOS) as pw_client: + status, payload = pw_client.rpcs.chip.rpc.Device.TriggerOta() + assert status == Status.UNIMPLEMENTED def test_ligth_ctrl_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) + with PigweedClient(device, RPC_PROTOS) as pw_client: - # Check light on - status, payload = pw_client.rpcs.chip.rpc.Lighting.Set(on=True) - assert status.ok() is True - status, payload = pw_client.rpcs.chip.rpc.Lighting.Get() - assert status.ok() is True - assert payload.on is True + # Check light on + status, payload = pw_client.rpcs.chip.rpc.Lighting.Set(on=True) + assert status.ok() is True + status, payload = pw_client.rpcs.chip.rpc.Lighting.Get() + assert status.ok() is True + assert payload.on is True - # Check light off - status, payload = pw_client.rpcs.chip.rpc.Lighting.Set(on=False) - assert status.ok() is True - status, payload = pw_client.rpcs.chip.rpc.Lighting.Get() - assert status.ok() is True - assert payload.on is False + # Check light off + status, payload = pw_client.rpcs.chip.rpc.Lighting.Set(on=False) + assert status.ok() is True + status, payload = pw_client.rpcs.chip.rpc.Lighting.Get() + assert status.ok() is True + assert payload.on is False def test_button_ctrl_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) - - # Check button 0 (lighting) - status, payload = pw_client.rpcs.chip.rpc.Lighting.Get() - assert status.ok() is True - initial_state = bool(payload.on) - - compare_state = not initial_state - status, payload = pw_client.rpcs.chip.rpc.Button.Event(idx=0, pushed=True) - assert status.ok() is True - sleep(2) - status, payload = pw_client.rpcs.chip.rpc.Lighting.Get() - assert status.ok() is True - assert payload.on == compare_state - - compare_state = initial_state - status, payload = pw_client.rpcs.chip.rpc.Button.Event(idx=0, pushed=True) - assert status.ok() is True - sleep(2) - status, payload = pw_client.rpcs.chip.rpc.Lighting.Get() - assert status.ok() is True - assert payload.on == compare_state + with PigweedClient(device, RPC_PROTOS) as pw_client: + + # Check button 0 (lighting) + status, payload = pw_client.rpcs.chip.rpc.Lighting.Get() + assert status.ok() is True + initial_state = bool(payload.on) + + compare_state = not initial_state + status, payload = pw_client.rpcs.chip.rpc.Button.Event(idx=0, + pushed=True) + assert status.ok() is True + sleep(2) + status, payload = pw_client.rpcs.chip.rpc.Lighting.Get() + assert status.ok() is True + assert payload.on == compare_state + + compare_state = initial_state + status, payload = pw_client.rpcs.chip.rpc.Button.Event(idx=0, + pushed=True) + assert status.ok() is True + sleep(2) + status, payload = pw_client.rpcs.chip.rpc.Lighting.Get() + assert status.ok() is True + assert payload.on == compare_state diff --git a/src/test_driver/mbed/integration_tests/lock-app/test_app.py b/src/test_driver/mbed/integration_tests/lock-app/test_app.py index 0592846571d5ee..ffe86d7a369615 100644 --- a/src/test_driver/mbed/integration_tests/lock-app/test_app.py +++ b/src/test_driver/mbed/integration_tests/lock-app/test_app.py @@ -136,77 +136,79 @@ def test_lock_ctrl(device, network): def test_device_info_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) - status, payload = pw_client.rpcs.chip.rpc.Device.GetDeviceInfo() - assert status.ok() is True - assert payload.vendor_id is not None and payload.product_id is not None and payload.serial_number is not None + with PigweedClient(device, RPC_PROTOS) as pw_client: + status, payload = pw_client.rpcs.chip.rpc.Device.GetDeviceInfo() + assert status.ok() is True + assert payload.vendor_id is not None and payload.product_id is not None and payload.serial_number is not None - device_details = get_device_details(device) - assert device_details is not None and len(device_details) != 0 + device_details = get_device_details(device) + assert device_details is not None and len(device_details) != 0 - assert int(device_details["VendorID"]) == payload.vendor_id - assert int(device_details["ProductID"]) == payload.product_id - assert int(device_details["Discriminator"] - ) == payload.pairing_info.discriminator - assert int(device_details["SetUpPINCode"]) == payload.pairing_info.code + assert int(device_details["VendorID"]) == payload.vendor_id + assert int(device_details["ProductID"]) == payload.product_id + assert int(device_details["Discriminator"] + ) == payload.pairing_info.discriminator + assert int(device_details["SetUpPINCode"]) == payload.pairing_info.code def test_device_factory_reset_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) - status, payload = pw_client.rpcs.chip.rpc.Device.FactoryReset() - assert status.ok() is True + with PigweedClient(device, RPC_PROTOS) as pw_client: + status, payload = pw_client.rpcs.chip.rpc.Device.FactoryReset() + assert status.ok() is True def test_device_reboot_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) - status, payload = pw_client.rpcs.chip.rpc.Device.Reboot() - assert status == Status.UNIMPLEMENTED + with PigweedClient(device, RPC_PROTOS) as pw_client: + status, payload = pw_client.rpcs.chip.rpc.Device.Reboot() + assert status == Status.UNIMPLEMENTED def test_device_ota_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) - status, payload = pw_client.rpcs.chip.rpc.Device.TriggerOta() - assert status == Status.UNIMPLEMENTED + with PigweedClient(device, RPC_PROTOS) as pw_client: + status, payload = pw_client.rpcs.chip.rpc.Device.TriggerOta() + assert status == Status.UNIMPLEMENTED def test_lock_ctrl_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) + with PigweedClient(device, RPC_PROTOS) as pw_client: - # Check locked - status, payload = pw_client.rpcs.chip.rpc.Locking.Set(locked=True) - assert status.ok() is True - status, payload = pw_client.rpcs.chip.rpc.Locking.Get() - assert status.ok() is True - assert payload.locked is True + # Check locked + status, payload = pw_client.rpcs.chip.rpc.Locking.Set(locked=True) + assert status.ok() is True + status, payload = pw_client.rpcs.chip.rpc.Locking.Get() + assert status.ok() is True + assert payload.locked is True - # Check unlocked - status, payload = pw_client.rpcs.chip.rpc.Locking.Set(locked=False) - assert status.ok() is True - status, payload = pw_client.rpcs.chip.rpc.Locking.Get() - assert status.ok() is True - assert payload.locked is False + # Check unlocked + status, payload = pw_client.rpcs.chip.rpc.Locking.Set(locked=False) + assert status.ok() is True + status, payload = pw_client.rpcs.chip.rpc.Locking.Get() + assert status.ok() is True + assert payload.locked is False def test_button_ctrl_rpc(device): - pw_client = PigweedClient(device, RPC_PROTOS) - - # Check button 0 (locking) - status, payload = pw_client.rpcs.chip.rpc.Locking.Get() - assert status.ok() is True - initial_state = bool(payload.locked) - - compare_state = not initial_state - status, payload = pw_client.rpcs.chip.rpc.Button.Event(idx=0, pushed=True) - assert status.ok() is True - sleep(2) - status, payload = pw_client.rpcs.chip.rpc.Locking.Get() - assert status.ok() is True - assert payload.locked is compare_state - - compare_state = initial_state - status, payload = pw_client.rpcs.chip.rpc.Button.Event(idx=0, pushed=True) - assert status.ok() is True - sleep(2) - status, payload = pw_client.rpcs.chip.rpc.Locking.Get() - assert status.ok() is True - assert payload.locked == compare_state + with PigweedClient(device, RPC_PROTOS) as pw_client: + + # Check button 0 (locking) + status, payload = pw_client.rpcs.chip.rpc.Locking.Get() + assert status.ok() is True + initial_state = bool(payload.locked) + + compare_state = not initial_state + status, payload = pw_client.rpcs.chip.rpc.Button.Event(idx=0, + pushed=True) + assert status.ok() is True + sleep(2) + status, payload = pw_client.rpcs.chip.rpc.Locking.Get() + assert status.ok() is True + assert payload.locked is compare_state + + compare_state = initial_state + status, payload = pw_client.rpcs.chip.rpc.Button.Event(idx=0, + pushed=True) + assert status.ok() is True + sleep(2) + status, payload = pw_client.rpcs.chip.rpc.Locking.Get() + assert status.ok() is True + assert payload.locked == compare_state diff --git a/src/test_driver/mbed/integration_tests/pigweed-app/test_app.py b/src/test_driver/mbed/integration_tests/pigweed-app/test_app.py index 4d14d479ed1db1..e9273848e54b40 100644 --- a/src/test_driver/mbed/integration_tests/pigweed-app/test_app.py +++ b/src/test_driver/mbed/integration_tests/pigweed-app/test_app.py @@ -31,8 +31,8 @@ def test_smoke_test(device): def test_echo(device): - pw_client = PigweedClient(device, RPC_PROTOS) - status, payload = pw_client.rpcs.pw.rpc.EchoService.Echo( - msg=PW_ECHO_TEST_MESSAGE) - assert status.ok() is True - assert payload.msg == PW_ECHO_TEST_MESSAGE + with PigweedClient(device, RPC_PROTOS) as pw_client: + status, payload = pw_client.rpcs.pw.rpc.EchoService.Echo( + msg=PW_ECHO_TEST_MESSAGE) + assert status.ok() is True + assert payload.msg == PW_ECHO_TEST_MESSAGE From fc0ab421ead7410cd130695bda63af8f7d6f3bf0 Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Thu, 5 Oct 2023 12:52:08 -0400 Subject: [PATCH 05/21] Use copy of pigweed.json maintained in Matter SDK to prevent pulling in unneeded CIPD package (#29548) * Initial test to confirm issue * Remove rust CIPD package * Changed android workflow to no longer delete rust folder * Changed android smoketest workflow to no longer delete rust folder * Fix new clang tidy error * Address PR comment * Update .github/workflows/full-android.yaml Co-authored-by: Boris Zbarsky --------- Co-authored-by: Andrei Litvin Co-authored-by: Boris Zbarsky --- .github/workflows/full-android.yaml | 9 +- .github/workflows/smoketest-android.yaml | 9 +- .restyled.yaml | 1 + pigweed.json | 122 +++++++++++++++++++ scripts/setup/environment.json | 2 +- src/transport/retransmit/tests/TestCache.cpp | 2 +- 6 files changed, 131 insertions(+), 14 deletions(-) create mode 100644 pigweed.json diff --git a/.github/workflows/full-android.yaml b/.github/workflows/full-android.yaml index ee6fc243218531..2fdee8ea806308 100644 --- a/.github/workflows/full-android.yaml +++ b/.github/workflows/full-android.yaml @@ -62,13 +62,10 @@ jobs: - name: Cleanup pigweed CIPD packages # This should not generally be needed, however android CI runs out of space # We do not need pigweed cross compile here because we use android NDK - # compilers, so removing rust and arm compilers saves 2.5GB + # compilers. Removing this package saves a significant amount of space. run: | - du -sh .environment/cipd/packages/pigweed/rust \ - .environment/cipd/packages/arm - - rm -rf .environment/cipd/packages/pigweed/rust \ - .environment/cipd/packages/arm + du -sh .environment/cipd/packages/arm + rm -rf .environment/cipd/packages/arm - name: Build Android arm-chip-tool run: | ./scripts/run_in_build_env.sh \ diff --git a/.github/workflows/smoketest-android.yaml b/.github/workflows/smoketest-android.yaml index d97d55fbd11073..14d98dd5544b1f 100644 --- a/.github/workflows/smoketest-android.yaml +++ b/.github/workflows/smoketest-android.yaml @@ -51,13 +51,10 @@ jobs: - name: Cleanup pigweed CIPD packages # This should not generally be needed, however android CI runs out of space # We do not need pigweed cross compile here because we use android NDK - # compilers, so removing rust and arm compilers saves 2.5GB + # compilers. Removing this package save significant amount of space. run: | - du -sh .environment/cipd/packages/pigweed/rust \ - .environment/cipd/packages/arm - - rm -rf .environment/cipd/packages/pigweed/rust \ - .environment/cipd/packages/arm + du -sh .environment/cipd/packages/arm + rm -rf .environment/cipd/packages/arm - name: Build Android CHIPTool and CHIPTest (ARM64) run: | diff --git a/.restyled.yaml b/.restyled.yaml index 24d4a52be7341a..66e9f6028345f7 100644 --- a/.restyled.yaml +++ b/.restyled.yaml @@ -82,6 +82,7 @@ exclude: - "src/controller/java/zap-generated/**/*" # not formatted: generated files - "scripts/setup/bootstrap.sh" # tries to quote loop variable - "integrations/docker/build-all.sh" # tries to quote loop variable + - "pigweed.json" # TODO(#29547). This file is temporary copy from pigweed repo that has minor edits. No restyle help in diff. changed_paths: maximum: 100000 diff --git a/pigweed.json b/pigweed.json new file mode 100644 index 00000000000000..3147b578705073 --- /dev/null +++ b/pigweed.json @@ -0,0 +1,122 @@ +{ + "packages": [ + { + "path": "gn/gn/${platform}", + "platforms": [ + "linux-amd64", + "linux-arm64", + "mac-amd64", + "mac-arm64", + "windows-amd64" + ], + "tags": [ + "git_revision:991530ce394efb58fcd848195469022fa17ae126" + ], + "version_file": ".versions/gn.cipd_version" + }, + { + "path": "infra/3pp/tools/ninja/${platform}", + "platforms": [ + "linux-amd64", + "linux-arm64", + "mac-amd64", + "mac-arm64", + "windows-amd64" + ], + "tags": [ + "version:2@1.11.1.chromium.7" + ] + }, + { + "path": "fuchsia/third_party/bloaty/${platform}", + "platforms": [ + "linux-amd64", + "mac-amd64" + ], + "tags": [ + "git_revision:c057ba4f43db0506d4ba8c096925b054b02a8bd3" + ], + "version_file": ".versions/bloaty.cipd_version" + }, + { + "path": "infra/3pp/tools/protoc/${platform}", + "platforms": [ + "linux-amd64", + "linux-arm64", + "mac-amd64", + "windows-amd64" + ], + "tags": [ + "version:2@3.17.3" + ] + }, + { + "_comment": "Always get the amd64 version on Mac until there's an arm64 version", + "path": "infra/3pp/tools/protoc/mac-amd64", + "platforms": [ + "mac-arm64" + ], + "tags": [ + "version:2@3.17.3" + ] + }, + { + "path": "fuchsia/third_party/clang/${platform}", + "platforms": [ + "linux-amd64", + "linux-arm64", + "mac-amd64", + "mac-arm64", + "windows-amd64" + ], + "tags": [ + "git_revision:576b184d6e3b633f51b908b61ebd281d2ecbf66f" + ], + "version_file": ".versions/clang.cipd_version" + }, + { + "path": "infra/3pp/tools/openocd/${platform}", + "platforms": [ + "linux-amd64", + "linux-arm64", + "mac-amd64", + "mac-arm64" + ], + "tags": [ + "version:2@0.11.0-3" + ] + }, + { + "path": "pigweed/third_party/mingw64-x86_64-win32-seh/${platform}", + "platforms": [ + "windows-amd64" + ], + "tags": [ + "version:10.2.0-11" + ] + }, + { + "path": "fuchsia/third_party/qemu/${platform}", + "platforms": [ + "linux-amd64", + "linux-arm64", + "mac-amd64" + ], + "tags": [ + "git_revision:a342ce9dfeed8088c426e5d51d4a7e47f3764b84" + ], + "version_file": ".versions/qemu.cipd_version" + }, + { + "path": "fuchsia/third_party/sysroot/linux", + "platforms": [ + "linux-amd64", + "linux-arm64" + ], + "subdir": "clang_sysroot", + "tags": [ + "git_revision:d342388843734b6c5c50fb7e18cd3a76476b93aa" + ] + } + ] +} diff --git a/scripts/setup/environment.json b/scripts/setup/environment.json index 7ded85c3b43b0a..833ffe4fa8d922 100644 --- a/scripts/setup/environment.json +++ b/scripts/setup/environment.json @@ -1,7 +1,7 @@ { "cipd_package_files": [ "third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/cipd_setup/arm.json", - "third_party/pigweed/repo/pw_env_setup/py/pw_env_setup/cipd_setup/pigweed.json", + "pigweed.json", "scripts/setup/python.json", "scripts/setup/zap.json" ], diff --git a/src/transport/retransmit/tests/TestCache.cpp b/src/transport/retransmit/tests/TestCache.cpp index aac0b424c37080..8a619e9d1271cc 100644 --- a/src/transport/retransmit/tests/TestCache.cpp +++ b/src/transport/retransmit/tests/TestCache.cpp @@ -38,7 +38,7 @@ class TestableCache : public chip::Retransmit::Cache * Convenience add when types are trivially copyable, so no actual * reference needs to be created. */ - template ::value, int>> + template ::value, int> = 0> CHIP_ERROR AddValue(const KeyType & key, PayloadType payload) { return chip::Retransmit::Cache::Add(key, payload); From d15daf8a02b972948147536bc18c291bea2fd384 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 5 Oct 2023 13:12:33 -0400 Subject: [PATCH 06/21] Update python test CI: stop dirtying build env, cleanup build outputs (#29584) * Prevent dirtying the buildenv, make sure things are cleaned * Virtualenv seems to be installed in the buildenv ... use that so we do not need to globally install * Force bash shell because source requires it * Stop generating link map files for the python builds..they just take up space and this saves 2GB --- .github/workflows/build.yaml | 29 +++++++++++++++++++++-------- build/toolchain/gcc_toolchain.gni | 10 ++++++++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 569ff10a95c70b..d091dc346b9bf6 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -303,21 +303,34 @@ jobs: - name: Setup Build, Run Build and Run Tests run: | - scripts/build/gn_gen.sh --args="enable_rtti=true enable_pylib=true chip_config_memory_debug_checks=false chip_config_memory_debug_dmalloc=false" + scripts/build/gn_gen.sh --args="enable_rtti=true enable_pylib=true chip_config_memory_debug_checks=false chip_config_memory_debug_dmalloc=false chip_generate_link_map_file=false" scripts/run_in_build_env.sh "ninja -C ./out" scripts/tests/gn_tests.sh - - name: Run Python library specific unit tests + - name: Setup test python environment + shell: bash run: | - scripts/run_in_build_env.sh 'pip3 install ./out/controller/python/chip_core-0.0-cp37-abi3-linux_x86_64.whl' - scripts/run_in_build_env.sh 'pip3 install ./out/controller/python/chip_clusters-0.0-py3-none-any.whl' - scripts/run_in_build_env.sh 'pip3 install ./out/controller/python/chip_repl-0.0-py3-none-any.whl' - scripts/run_in_build_env.sh '(cd src/controller/python/test/unit_tests/ && python3 -m unittest -v)' + scripts/run_in_build_env.sh 'virtualenv pyenv' + source pyenv/bin/activate + pip3 install ./out/controller/python/chip_core-0.0-cp37-abi3-linux_x86_64.whl + pip3 install ./out/controller/python/chip_clusters-0.0-py3-none-any.whl + pip3 install ./out/controller/python/chip_repl-0.0-py3-none-any.whl + - name: Run Python tests + shell: bash + run: | + source pyenv/bin/activate + cd src/controller/python/test/unit_tests/ + python3 -m unittest -v + - name: Clean previous outputs + run: rm -rf out pyenv - name: Run Python Setup Payload Generator Test + shell: bash run: | scripts/run_in_build_env.sh 'scripts/examples/gn_build_example.sh examples/chip-tool out/' - scripts/run_in_build_env.sh 'pip3 install -r src/setup_payload/python/requirements.txt' - scripts/run_in_build_env.sh 'python3 src/setup_payload/tests/run_python_setup_payload_gen_test.py out/chip-tool' + scripts/run_in_build_env.sh 'virtualenv pyenv' + source pyenv/bin/activate + pip3 install -r src/setup_payload/python/requirements.txt + python3 src/setup_payload/tests/run_python_setup_payload_gen_test.py out/chip-tool build_darwin: name: Build on Darwin (clang, python_lib, simulated) diff --git a/build/toolchain/gcc_toolchain.gni b/build/toolchain/gcc_toolchain.gni index fba42eb8349f1f..b4b39daf711fb0 100644 --- a/build/toolchain/gcc_toolchain.gni +++ b/build/toolchain/gcc_toolchain.gni @@ -15,6 +15,14 @@ import("//build_overrides/pigweed.gni") import("$dir_pw_toolchain/generate_toolchain.gni") +declare_args() { + # Generate Linker map files. Can skip since they can + # be quite large. + # + # Note that toolchains can individually override this + chip_generate_link_map_file = true +} + template("gcc_toolchain") { invoker_toolchain_args = invoker.toolchain_args @@ -42,6 +50,8 @@ template("gcc_toolchain") { if (defined(invoker.link_generate_map_file)) { link_generate_map_file = invoker.link_generate_map_file + } else { + link_generate_map_file = chip_generate_link_map_file } is_host_toolchain = invoker_toolchain_args.current_os == host_os From 94facb544ba79205ed8260bbfacccc3bcada98ac Mon Sep 17 00:00:00 2001 From: Pradip De Date: Thu, 5 Oct 2023 12:24:13 -0700 Subject: [PATCH 07/21] Increment used TCPEndPoint count during incoming connection. (#29553) * Increment used endpoint count during incoming connection. Due to this issue, subsequent incoming connections were failing to connect as the value was getting decremented from zero resulting in a check failing. Also, remove duplicate code for freeing an active connection and move it into a separate function. * Update src/transport/raw/TCP.h Co-authored-by: Boris Zbarsky --------- Co-authored-by: Boris Zbarsky --- src/transport/raw/TCP.cpp | 36 ++++++++++++++++++------------------ src/transport/raw/TCP.h | 4 ++++ 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/src/transport/raw/TCP.cpp b/src/transport/raw/TCP.cpp index 8e6cae72da4f36..a1b1df1fe45a2d 100644 --- a/src/transport/raw/TCP.cpp +++ b/src/transport/raw/TCP.cpp @@ -325,6 +325,18 @@ CHIP_ERROR TCPBase::ProcessSingleMessage(const PeerAddress & peerAddress, Active return CHIP_NO_ERROR; } +void TCPBase::ReleaseActiveConnection(Inet::TCPEndPoint * endPoint) +{ + for (size_t i = 0; i < mActiveConnectionsSize; i++) + { + if (mActiveConnections[i].mEndPoint == endPoint) + { + mActiveConnections[i].Free(); + mUsedEndPointCount--; + } + } +} + CHIP_ERROR TCPBase::OnTcpReceive(Inet::TCPEndPoint * endPoint, System::PacketBufferHandle && buffer) { Inet::IPAddress ipAddress; @@ -425,15 +437,8 @@ void TCPBase::OnConnectionClosed(Inet::TCPEndPoint * endPoint, CHIP_ERROR err) ChipLogProgress(Inet, "Connection closed."); - for (size_t i = 0; i < tcp->mActiveConnectionsSize; i++) - { - if (tcp->mActiveConnections[i].mEndPoint == endPoint) - { - ChipLogProgress(Inet, "Freeing closed connection."); - tcp->mActiveConnections[i].Free(); - tcp->mUsedEndPointCount--; - } - } + ChipLogProgress(Inet, "Freeing closed connection."); + tcp->ReleaseActiveConnection(endPoint); } void TCPBase::OnConnectionReceived(Inet::TCPEndPoint * listenEndPoint, Inet::TCPEndPoint * endPoint, @@ -449,6 +454,7 @@ void TCPBase::OnConnectionReceived(Inet::TCPEndPoint * listenEndPoint, Inet::TCP if (!tcp->mActiveConnections[i].InUse()) { tcp->mActiveConnections[i].Init(endPoint); + tcp->mUsedEndPointCount++; break; } } @@ -502,15 +508,9 @@ void TCPBase::OnPeerClosed(Inet::TCPEndPoint * endPoint) { TCPBase * tcp = reinterpret_cast(endPoint->mAppState); - for (size_t i = 0; i < tcp->mActiveConnectionsSize; i++) - { - if (tcp->mActiveConnections[i].mEndPoint == endPoint) - { - ChipLogProgress(Inet, "Freeing connection: connection closed by peer"); - tcp->mActiveConnections[i].Free(); - tcp->mUsedEndPointCount--; - } - } + ChipLogProgress(Inet, "Freeing connection: connection closed by peer"); + + tcp->ReleaseActiveConnection(endPoint); } bool TCPBase::HasActiveConnections() const diff --git a/src/transport/raw/TCP.h b/src/transport/raw/TCP.h index 8f90a4242b187f..d9f78be1771b0f 100644 --- a/src/transport/raw/TCP.h +++ b/src/transport/raw/TCP.h @@ -225,6 +225,10 @@ class DLL_EXPORT TCPBase : public Base */ CHIP_ERROR ProcessSingleMessage(const PeerAddress & peerAddress, ActiveConnectionState * state, uint16_t messageSize); + // Release an active connection (corresponding to the passed TCPEndPoint) + // from the pool. + void ReleaseActiveConnection(Inet::TCPEndPoint * endPoint); + // Callback handler for TCPEndPoint. TCP message receive handler. // @see TCPEndpoint::OnDataReceivedFunct static CHIP_ERROR OnTcpReceive(Inet::TCPEndPoint * endPoint, System::PacketBufferHandle && buffer); From 257755e981353562b955317191d8aee45a8bf9d8 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 5 Oct 2023 16:25:30 -0400 Subject: [PATCH 08/21] Remove various defines that were effectively commenting out static functions that were never used (#29596) --- src/platform/Linux/bluez/Helper.cpp | 123 ---------------------------- 1 file changed, 123 deletions(-) diff --git a/src/platform/Linux/bluez/Helper.cpp b/src/platform/Linux/bluez/Helper.cpp index 89ab6f22f9defd..3513c846dd254d 100644 --- a/src/platform/Linux/bluez/Helper.cpp +++ b/src/platform/Linux/bluez/Helper.cpp @@ -314,39 +314,6 @@ static gboolean BluezCharacteristicReadValue(BluezGattCharacteristic1 * aChar, G return TRUE; } -#if CHIP_BLUEZ_CHAR_WRITE_VALUE -static gboolean BluezCharacteristicWriteValue(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, - GVariant * aValue, GVariant * aOptions, gpointer apEndpoint) -{ - const uint8_t * tmpBuf; - uint8_t * buf; - size_t len; - bool isSuccess = false; - BluezConnection * conn = nullptr; - - BluezEndpoint * endpoint = static_cast(apEndpoint); - VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); - - VerifyOrExit(aValue != nullptr, ChipLogError(DeviceLayer, "aValue is NULL in %s", __func__)); - - conn = GetBluezConnectionViaDevice(endpoint); - VerifyOrExit(conn != nullptr, - g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.Failed", "No CHIP Bluez connection")); - - bluez_gatt_characteristic1_set_value(aChar, g_variant_ref(aValue)); - - tmpBuf = (uint8_t *) (g_variant_get_fixed_array(aValue, &len, sizeof(uint8_t))); - buf = (uint8_t *) (g_memdup(tmpBuf, len)); - - BLEManagerImpl::HandleRXCharWrite(conn, buf, len); - bluez_gatt_characteristic1_complete_write_value(aChar, aInvocation); - isSuccess = true; - -exit: - return isSuccess ? TRUE : FALSE; -} -#endif - static gboolean BluezCharacteristicWriteValueError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aValue, GVariant * aOptions, gpointer apClosure) { @@ -1064,84 +1031,6 @@ static BluezConnection * GetBluezConnectionViaDevice(BluezEndpoint * apEndpoint) return retval; } -#if CHIP_BLUEZ_CENTRAL_SUPPORT -static BluezConnection * BluezCharacteristicGetBluezConnection(BluezGattCharacteristic1 * aChar, GVariant * aOptions, - BluezEndpoint * apEndpoint) -{ - BluezConnection * retval = nullptr; - GVariantDict * options = nullptr; - GVariant * option_device = nullptr; - - VerifyOrExit(apEndpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); - VerifyOrExit(apEndpoint->mIsCentral, ); - - /* TODO Unfortunately StartNotify/StopNotify doesn't provide info about - * peer device in call params so we need look this up ourselves. - */ - if (aOptions == nullptr) - { - GList * objects; - GList * l; - GList * ll; - - objects = g_dbus_object_manager_get_objects(apEndpoint->mpObjMgr); - for (l = objects; l != nullptr; l = l->next) - { - BluezDevice1 * device = bluez_object_get_device1(BLUEZ_OBJECT(l->data)); - if (device != nullptr) - { - if (BluezIsDeviceOnAdapter(device, apEndpoint->mpAdapter)) - { - for (ll = objects; ll != nullptr; ll = ll->next) - { - BluezGattService1 * service = bluez_object_get_gatt_service1(BLUEZ_OBJECT(ll->data)); - if (service != nullptr) - { - if (BluezIsServiceOnDevice(service, device)) - { - if (BluezIsCharOnService(aChar, service)) - { - retval = static_cast(g_hash_table_lookup( - apEndpoint->mpConnMap, g_dbus_proxy_get_object_path(G_DBUS_PROXY(device)))); - } - } - g_object_unref(service); - if (retval != nullptr) - break; - } - } - } - g_object_unref(device); - if (retval != nullptr) - break; - } - } - - g_list_free_full(objects, g_object_unref); - } - else - { - options = g_variant_dict_new(aOptions); - option_device = g_variant_dict_lookup_value(options, "device", G_VARIANT_TYPE_OBJECT_PATH); - VerifyOrExit(option_device != nullptr, ChipLogError(DeviceLayer, "FAIL: No device in options in %s", __func__);); - - retval = static_cast( - g_hash_table_lookup(apEndpoint->mpConnMap, g_variant_get_string(option_device, nullptr))); - } - -exit: - if (options != nullptr) - { - g_variant_dict_unref(options); - } - if (option_device != nullptr) - { - g_variant_unref(option_device); - } - return retval; -} -#endif // CHIP_BLUEZ_CENTRAL_SUPPORT - static void EndpointCleanup(BluezEndpoint * apEndpoint) { if (apEndpoint != nullptr) @@ -1323,18 +1212,6 @@ static void BluezOnBusAcquired(GDBusConnection * aConn, const gchar * aName, gpo return; } -#if CHIP_BLUEZ_NAME_MONITOR -static void BluezOnNameAcquired(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) -{ - ChipLogDetail(DeviceLayer, "TRACE: Owning name: Acquired %s", aName); -} - -static void BluezOnNameLost(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) -{ - ChipLogDetail(DeviceLayer, "TRACE: Owning name: lost %s", aName); -} -#endif - static CHIP_ERROR StartupEndpointBindings(BluezEndpoint * endpoint) { VerifyOrReturnError(endpoint != nullptr, CHIP_ERROR_INVALID_ARGUMENT, From ad655105c7bb01bc9cc90315f17de42eee275ce3 Mon Sep 17 00:00:00 2001 From: Kai Liao <140431279+kliao-csa@users.noreply.github.com> Date: Thu, 5 Oct 2023 16:36:40 -0600 Subject: [PATCH 09/21] Full day fail summary (#29609) * Update summarize_fail.py * Update recent_fail_summary.yaml * Update summarize_fail.py * Update summarize_fail.py * Update summarize_fail.py * Update summarize_fail.py * Update summarize_fail.py * Update recent_fail_summary.yaml * Update recent_fail_summary.yaml * Create build_fail_defs.yaml * Update build_fail_defs.yaml * Update summarize_fail.py * Update summarize_fail.py * Update summarize_fail.py * Update recent_fail_summary.yaml * Update summarize_fail.py * Update summarize_fail.py * Update recent_fail_summary.yaml * Update summarize_fail.py * Update summarize_fail.py * Update summarize_fail.py * Update summarize_fail.py * Update summarize_fail.py * Update summarize_fail.py * Update recent_fail_summary.yaml * Update recent_fail_summary.yaml * Update summarize_fail.py * Update recent_fail_summary.yaml * Update summarize_fail.py * Update summarize_fail.py * Update recent_fail_summary.yaml * Restyled by prettier-yaml * Restyled by autopep8 * Restyled by isort * Update summarize_fail.py --------- Co-authored-by: Restyled.io --- .github/workflows/recent_fail_summary.yaml | 20 +++- scripts/tools/build_fail_defs.yaml | 20 ++++ scripts/tools/summarize_fail.py | 102 +++++++++++---------- 3 files changed, 87 insertions(+), 55 deletions(-) create mode 100644 scripts/tools/build_fail_defs.yaml diff --git a/.github/workflows/recent_fail_summary.yaml b/.github/workflows/recent_fail_summary.yaml index 08f9a793eb91f8..5c23b5be881e73 100644 --- a/.github/workflows/recent_fail_summary.yaml +++ b/.github/workflows/recent_fail_summary.yaml @@ -15,7 +15,7 @@ name: Recent Fail Summary on: schedule: - - cron: "0 0 * * *" + - cron: "10 0 * * *" workflow_dispatch: concurrency: @@ -25,24 +25,34 @@ jobs: list_workflows: name: Summarize Recent Workflow Failures runs-on: ubuntu-latest + permissions: write-all steps: - uses: actions/checkout@v4 - - run: pip install pandas python-slugify + - run: pip install pandas python-slugify pyyaml tabulate - name: Run Summarization Script run: python scripts/tools/summarize_fail.py env: GH_TOKEN: ${{ github.token }} + - name: Update Docs + uses: test-room-7/action-update-file@v1 + with: + file-path: docs/daily_pass_percentage.md + commit-msg: Update daily pass percentage + github-token: ${{ secrets.GITHUB_TOKEN }} + branch: daily_pass_percentage - name: Upload Logs uses: actions/upload-artifact@v3 with: name: workflow-fail-summary path: | - run_list.json + fail_run_list.json + all_run_list.json recent_fails.csv recent_fails_frequency.csv failure_cause_summary.csv - workflow_fail_rate.csv + workflow_pass_rate.csv + workflow_pass_rate.sqlite3 recent_fails_logs - workflow_fail_rate + workflow_pass_rate retention-days: 5 diff --git a/scripts/tools/build_fail_defs.yaml b/scripts/tools/build_fail_defs.yaml new file mode 100644 index 00000000000000..8d6e782c2705b9 --- /dev/null +++ b/scripts/tools/build_fail_defs.yaml @@ -0,0 +1,20 @@ +CodeQL: + No space left on device: + short: Ran out of space + detail: Exception with signature "No space left on device" + Check that the disk containing the database directory has ample free space.: + short: Ran out of space + detail: + Fatal internal error with message indicating that disk space most + likely ran out +Build example: + Could not find a version that satisfies the requirement: + short: Requirements issue + detail: Unable to install a requirements in Python requirements.txt + No module named: + short: Missing module + detail: Expected module was missing +Full builds: + No space left on device: + short: Ran out of space + detail: Exception with signature "No space left on device diff --git a/scripts/tools/summarize_fail.py b/scripts/tools/summarize_fail.py index 85283784f9c50c..04b3b33077c4b6 100644 --- a/scripts/tools/summarize_fail.py +++ b/scripts/tools/summarize_fail.py @@ -1,38 +1,31 @@ +import datetime import logging import os +import sqlite3 import subprocess import pandas as pd +import yaml from slugify import slugify -error_catalog = { - "CodeQL": { - "No space left on device": { - "short": "Ran out of space", - "detail": "Exception with signature \"No space left on device\"" - }, - "Check that the disk containing the database directory has ample free space.": { - "short": "Ran out of space", - "detail": "Fatal internal error with message indicating that disk space most likely ran out" - } - }, - "Build example": { - "Could not find a version that satisfies the requirement": { - "short": "Requirements issue", - "detail": "Unable to install a requirements in Python requirements.txt" - }, - "No module named": { - "short": "Missing module", - "detail": "Expected module was missing" - } - }, - "Full builds": { - "No space left on device": { - "short": "Ran out of space", - "detail": "Exception with signature \"No space left on device\"" - } - } -} +yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%Y-%m-%d') + +with open("scripts/tools/build_fail_defs.yaml", "r") as fail_defs: + try: + error_catalog = yaml.safe_load(fail_defs) + except Exception: + logging.exception("Could not load fail definition file.") + + +def pass_fail_rate(workflow): + logging.info(f"Checking recent pass/fail rate of workflow {workflow}.") + workflow_fail_rate_output_path = f"workflow_pass_rate/{slugify(workflow)}" + if not os.path.exists(workflow_fail_rate_output_path): + os.makedirs(workflow_fail_rate_output_path) + subprocess.run( + f"gh run list -R project-chip/connectedhomeip -b master -w '{workflow}' -L 500 --created {yesterday} --json conclusion > {workflow_fail_rate_output_path}/run_list.json", shell=True) + else: + logging.info("This workflow has already been processed.") def process_fail(id, pr, start_time, workflow): @@ -57,28 +50,20 @@ def process_fail(id, pr, start_time, workflow): root_cause = error_catalog[workflow_category][error_message]["short"] break - logging.info(f"Checking recent pass/fail rate of workflow {workflow}.") - workflow_fail_rate_output_path = f"workflow_pass_rate/{slugify(workflow)}" - if not os.path.exists(workflow_fail_rate_output_path): - os.makedirs(workflow_fail_rate_output_path) - subprocess.run( - f"gh run list -R project-chip/connectedhomeip -b master -w '{workflow}' --json conclusion > {workflow_fail_rate_output_path}/run_list.json", shell=True) - else: - logging.info("This workflow has already been processed.") - return [pr, workflow, root_cause] def main(): - logging.info("Gathering recent fails information into run_list.json.") - subprocess.run("gh run list -R project-chip/connectedhomeip -b master -s failure --json databaseId,displayTitle,startedAt,workflowName > run_list.json", shell=True) + logging.info("Gathering recent fails information into fail_run_list.json.") + subprocess.run( + f"gh run list -R project-chip/connectedhomeip -b master -s failure -L 500 --created {yesterday} --json databaseId,displayTitle,startedAt,workflowName > fail_run_list.json", shell=True) - logging.info("Reading run_list.json into a DataFrame.") - df = pd.read_json("run_list.json") + logging.info("Reading fail_run_list.json into a DataFrame.") + df = pd.read_json("fail_run_list.json") - logging.info("Listing recent fails.") + logging.info(f"Listing recent fails from {yesterday}.") df.columns = ["ID", "Pull Request", "Start Time", "Workflow"] - print("Recent Fails:") + print(f"Recent Fails From {yesterday}:") print(df.to_string(columns=["Pull Request", "Workflow"], index=False)) print() df.to_csv("recent_fails.csv", index=False) @@ -91,6 +76,17 @@ def main(): print() frequency.to_csv("recent_workflow_fails_frequency.csv") + logging.info("Gathering recent runs information into all_run_list.json.") + subprocess.run( + f"gh run list -R project-chip/connectedhomeip -b master -L 5000 --created {yesterday} --json workflowName > all_run_list.json", shell=True) + + logging.info("Reading all_run_list.json into a DataFrame.") + all_df = pd.read_json("all_run_list.json") + + logging.info("Gathering pass/fail rate info.") + all_df.columns = ["Workflow"] + all_df.apply(lambda row: pass_fail_rate(row["Workflow"]), axis=1) + logging.info("Conducting fail information parsing.") root_causes = df.apply(lambda row: process_fail(row["ID"], row["Pull Request"], row["Start Time"], row["Workflow"]), axis=1, result_type="expand") @@ -100,19 +96,25 @@ def main(): print() root_causes.to_csv("failure_cause_summary.csv") - logging.info("Listing percent fail rate of recent fails by workflow.") - fail_rate = {} + logging.info("Listing percent pass rate of recent fails by workflow.") + pass_rate = {} for workflow in next(os.walk("workflow_pass_rate"))[1]: try: info = pd.read_json(f"workflow_pass_rate/{workflow}/run_list.json") info = info[info["conclusion"].str.len() > 0] - fail_rate[workflow] = [info.value_counts(normalize=True).mul(100).round()["failure"]] except Exception: logging.exception(f"Recent runs info for {workflow} was not collected.") - fail_rate = pd.DataFrame.from_dict(fail_rate, 'index', columns=["Fail Rate"]) - print("Recent Fail Rate of Each Workflow:") - print(fail_rate.to_string()) - fail_rate.to_csv("workflow_fail_rate.csv") + try: + pass_rate[workflow] = [info.value_counts(normalize=True).mul(100).round()["success"]] + except Exception: + pass_rate[workflow] = [0.0] + pass_rate = pd.DataFrame.from_dict(pass_rate, 'index', columns=["Pass Rate"]).sort_values("Pass Rate") + print("Recent Pass Rate of Each Workflow:") + pass_rate.to_markdown("docs/daily_pass_percentage.md") + pass_rate_sql = sqlite3.connect("workflow_pass_rate.sqlite3") + pass_rate.to_sql("workflow_pass_rate", pass_rate_sql, if_exists="replace") + print(pass_rate.to_string()) + pass_rate.to_csv("workflow_pass_rate.csv") if __name__ == "__main__": From 8296a7595f0118186f8dd0b26c8ebb1f4ecfbd6e Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 5 Oct 2023 19:05:57 -0400 Subject: [PATCH 10/21] Enable -Wundef by default. (#29582) * Enable -Wundef by default on some platforms. * Fixes https://github.com/project-chip/connectedhomeip/issues/29216 * Fix a bunch more errors. * Restrict -Wundef to where it actually passes CI. --- build/config/compiler/BUILD.gn | 14 ++++++++++++++ .../commands/common/MTRLogging.h | 2 +- examples/platform/linux/BUILD.gn | 4 +--- .../tv-app/tv-common/src/ZCLCallbacks.cpp | 1 + .../tv-casting-app/tv-casting-common/BUILD.gn | 2 ++ .../tv-casting-common/include/AppParams.h | 1 + src/app/tests/TestDataModelSerialization.cpp | 2 +- src/include/platform/CHIPDeviceConfig.h | 8 ++++++++ src/inet/InetInterface.cpp | 6 +++--- src/inet/UDPEndPointImplSockets.cpp | 8 ++++---- src/inet/tests/TestInetAddress.cpp | 5 +++-- src/inet/tests/TestInetLayer.cpp | 4 ++-- src/inet/tests/TestLwIPDNS.cpp | 19 ++++++++++--------- src/lib/support/CHIPArgParser.hpp | 4 ++++ src/lib/support/Pool.h | 10 +++++++--- src/lib/support/UnitTestRegistration.cpp | 4 ++-- src/platform/tests/TestCHIPoBLEStackMgr.h | 2 ++ .../tests/TestCHIPoBLEStackMgrDriver.cpp | 1 + src/system/SystemClock.cpp | 2 +- src/system/SystemPacketBufferInternal.h | 4 ++++ 20 files changed, 72 insertions(+), 31 deletions(-) diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index c508d657b17ab2..9f34a730563d4a 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn @@ -253,6 +253,20 @@ config("strict_warnings") { cflags += [ "-Wconversion" ] } + # For now we can't enable -Wundef across the board. Enable it where + # we can. Ideally this would be checking chip_device_platform or so + # to be more fine-grained than current_os, but it's not clear that + # we can access that here. + if (current_os != "android" && current_os != "freertos" && + current_os != "linux" && current_os != "mbed" && current_os != "tizen" && + current_os != "zephyr" && + # cmsis-rtos is OpenIOT + current_os != "cmsis-rtos" && + # cyw30739 is one of the Infineon builds + current_os != "cyw30739") { + cflags += [ "-Wundef" ] + } + if (matter_enable_java_compilation) { cflags -= [ "-Wshadow" ] } diff --git a/examples/darwin-framework-tool/commands/common/MTRLogging.h b/examples/darwin-framework-tool/commands/common/MTRLogging.h index 3e120c552a68b5..58e0f6b88b5a67 100644 --- a/examples/darwin-framework-tool/commands/common/MTRLogging.h +++ b/examples/darwin-framework-tool/commands/common/MTRLogging.h @@ -21,7 +21,7 @@ #import -#if DEBUG +#ifdef DEBUG #define MTR_LOG_DEBUG(format, ...) os_log(OS_LOG_DEFAULT, format, ##__VA_ARGS__) #define MTR_LOG_ERROR(format, ...) os_log(OS_LOG_DEFAULT, format, ##__VA_ARGS__) #define MTR_LOG_METHOD_ENTRY() \ diff --git a/examples/platform/linux/BUILD.gn b/examples/platform/linux/BUILD.gn index 44a96b12c00604..46229c5f7ed42c 100644 --- a/examples/platform/linux/BUILD.gn +++ b/examples/platform/linux/BUILD.gn @@ -94,9 +94,7 @@ source_set("app-main") { ] } - if (chip_enable_smoke_co_trigger) { - defines += [ "CHIP_DEVICE_CONFIG_ENABLE_SMOKE_CO_TRIGGER=1" ] - } + defines += [ "CHIP_DEVICE_CONFIG_ENABLE_SMOKE_CO_TRIGGER=${chip_enable_smoke_co_trigger}" ] public_configs = [ ":app-main-config" ] } diff --git a/examples/tv-app/tv-common/src/ZCLCallbacks.cpp b/examples/tv-app/tv-common/src/ZCLCallbacks.cpp index d980811a6c09ad..8522f1f3d71f5a 100644 --- a/examples/tv-app/tv-common/src/ZCLCallbacks.cpp +++ b/examples/tv-app/tv-common/src/ZCLCallbacks.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include "account-login/AccountLoginManager.h" #include "application-basic/ApplicationBasicManager.h" diff --git a/examples/tv-casting-app/tv-casting-common/BUILD.gn b/examples/tv-casting-app/tv-casting-common/BUILD.gn index f555a62a181a41..9d4a3d3b4faea3 100644 --- a/examples/tv-casting-app/tv-casting-common/BUILD.gn +++ b/examples/tv-casting-app/tv-casting-common/BUILD.gn @@ -27,6 +27,8 @@ config("config") { ] cflags = [ "-Wconversion" ] + + defines = [ "CONFIG_USE_SEPARATE_EVENTLOOP=0" ] } chip_data_model("tv-casting-common") { diff --git a/examples/tv-casting-app/tv-casting-common/include/AppParams.h b/examples/tv-casting-app/tv-casting-common/include/AppParams.h index 7a42c09b501dda..c981aba8fa0d46 100644 --- a/examples/tv-casting-app/tv-casting-common/include/AppParams.h +++ b/examples/tv-casting-app/tv-casting-common/include/AppParams.h @@ -20,6 +20,7 @@ #include #include +#include /** * @brief Parameters passed to the CastingServer at the time of startup (i.e. init call) diff --git a/src/app/tests/TestDataModelSerialization.cpp b/src/app/tests/TestDataModelSerialization.cpp index 06cf6a17609fe4..d94caed6b6c2d3 100644 --- a/src/app/tests/TestDataModelSerialization.cpp +++ b/src/app/tests/TestDataModelSerialization.cpp @@ -105,7 +105,7 @@ void TestDataModelSerialization::DumpBuf() // // Enable this once the TLV pretty printer has been checked in. // -#if ENABLE_TLV_PRINT_OUT +#if defined(ENABLE_TLV_PRINT_OUT) && ENABLE_TLV_PRINT_OUT TLV::Debug::Print(reader); #endif } diff --git a/src/include/platform/CHIPDeviceConfig.h b/src/include/platform/CHIPDeviceConfig.h index fd8937dcc2302c..e29c00161337db 100644 --- a/src/include/platform/CHIPDeviceConfig.h +++ b/src/include/platform/CHIPDeviceConfig.h @@ -1419,3 +1419,11 @@ #ifndef CHIP_DEVICE_CONFIG_ENABLE_NFC #define CHIP_DEVICE_CONFIG_ENABLE_NFC 0 #endif + +/** + * CHIP_DEVICE_ENABLE_PORT_PARAMS enables command-line parameters to set the + * port to use for POSIX example applications. + */ +#ifndef CHIP_DEVICE_ENABLE_PORT_PARAMS +#define CHIP_DEVICE_ENABLE_PORT_PARAMS 0 +#endif // CHIP_DEVICE_ENABLE_PORT_PARAMS diff --git a/src/inet/InetInterface.cpp b/src/inet/InetInterface.cpp index e1c14dcfde449f..4d30309752408e 100644 --- a/src/inet/InetInterface.cpp +++ b/src/inet/InetInterface.cpp @@ -502,7 +502,7 @@ void CloseIOCTLSocket() } } -#if __ANDROID__ +#ifdef __ANDROID__ static struct if_nameindex * backport_if_nameindex(void); static void backport_if_freenameindex(struct if_nameindex *); @@ -648,7 +648,7 @@ InterfaceIterator::~InterfaceIterator() { if (mIntfArray != nullptr) { -#if __ANDROID__ +#ifdef __ANDROID__ backport_if_freenameindex(mIntfArray); #else if_freenameindex(mIntfArray); @@ -666,7 +666,7 @@ bool InterfaceIterator::Next() { if (mIntfArray == nullptr) { -#if __ANDROID__ +#ifdef __ANDROID__ mIntfArray = backport_if_nameindex(); #else mIntfArray = if_nameindex(); diff --git a/src/inet/UDPEndPointImplSockets.cpp b/src/inet/UDPEndPointImplSockets.cpp index b681a56fabe92f..f5e89e69fc10fe 100644 --- a/src/inet/UDPEndPointImplSockets.cpp +++ b/src/inet/UDPEndPointImplSockets.cpp @@ -696,7 +696,7 @@ void UDPEndPointImplSockets::HandlePendingIO(System::SocketEvents events) } } -#if IP_MULTICAST_LOOP || IPV6_MULTICAST_LOOP +#ifdef IPV6_MULTICAST_LOOP static CHIP_ERROR SocketsSetMulticastLoopback(int aSocket, bool aLoopback, int aProtocol, int aOption) { const unsigned int lValue = static_cast(aLoopback); @@ -707,7 +707,7 @@ static CHIP_ERROR SocketsSetMulticastLoopback(int aSocket, bool aLoopback, int a return CHIP_NO_ERROR; } -#endif // IP_MULTICAST_LOOP || IPV6_MULTICAST_LOOP +#endif // IPV6_MULTICAST_LOOP static CHIP_ERROR SocketsSetMulticastLoopback(int aSocket, IPVersion aIPVersion, bool aLoopback) { @@ -721,11 +721,11 @@ static CHIP_ERROR SocketsSetMulticastLoopback(int aSocket, IPVersion aIPVersion, lRetval = SocketsSetMulticastLoopback(aSocket, aLoopback, IPPROTO_IPV6, IPV6_MULTICAST_LOOP); break; -#if INET_CONFIG_ENABLE_IPV4 +#if INET_CONFIG_ENABLE_IPV4 && defined(IP_MULTICAST_LOOP) case kIPVersion_4: lRetval = SocketsSetMulticastLoopback(aSocket, aLoopback, IPPROTO_IP, IP_MULTICAST_LOOP); break; -#endif // INET_CONFIG_ENABLE_IPV4 +#endif // INET_CONFIG_ENABLE_IPV4 && defined(IP_MULTICAST_LOOP) default: lRetval = INET_ERROR_WRONG_ADDRESS_TYPE; diff --git a/src/inet/tests/TestInetAddress.cpp b/src/inet/tests/TestInetAddress.cpp index f047f6dc751c12..e85000d4008487 100644 --- a/src/inet/tests/TestInetAddress.cpp +++ b/src/inet/tests/TestInetAddress.cpp @@ -23,6 +23,7 @@ * a class to store and format IPV4 and IPV6 Internet Protocol addresses. * */ +#include #include @@ -1205,7 +1206,7 @@ void CheckFromSocket(nlTestSuite * inSuite, void * inContext) #if CHIP_SYSTEM_CONFIG_USE_LWIP (void) inSuite; // This test is only supported for non LWIP stack. -#else // INET_LWIP +#else // CHIP_SYSTEM_CONFIG_USE_LWIP const struct TestContext * lContext = static_cast(inContext); IPAddressExpandedContextIterator lCurrent = lContext->mIPAddressExpandedContextRange.mBegin; IPAddressExpandedContextIterator lEnd = lContext->mIPAddressExpandedContextRange.mEnd; @@ -1260,7 +1261,7 @@ void CheckFromSocket(nlTestSuite * inSuite, void * inContext) ++lCurrent; } -#endif // INET_LWIP +#endif // CHIP_SYSTEM_CONFIG_USE_LWIP } /** diff --git a/src/inet/tests/TestInetLayer.cpp b/src/inet/tests/TestInetLayer.cpp index eb1d174af3611f..47e83316228b5f 100644 --- a/src/inet/tests/TestInetLayer.cpp +++ b/src/inet/tests/TestInetLayer.cpp @@ -205,7 +205,7 @@ static void CheckSucceededOrFailed(TestState & aTestState, bool & aOutSucceeded, { const TransferStats & lStats = aTestState.mStats; -#if DEBUG +#ifdef DEBUG_TCP_TEST printf("%u/%u sent, %u/%u received\n", lStats.mTransmit.mActual, lStats.mTransmit.mExpected, lStats.mReceive.mActual, lStats.mReceive.mExpected); #endif @@ -298,7 +298,7 @@ int main(int argc, char * argv[]) CheckSucceededOrFailed(sTestState, lSucceeded, lFailed); -#if DEBUG +#ifdef DEBUG_TCP_TEST // clang-format off printf("%s %s number of expected bytes\n", ((lSucceeded) ? "successfully" : diff --git a/src/inet/tests/TestLwIPDNS.cpp b/src/inet/tests/TestLwIPDNS.cpp index fad393aee3e54e..8681f7b2e54328 100644 --- a/src/inet/tests/TestLwIPDNS.cpp +++ b/src/inet/tests/TestLwIPDNS.cpp @@ -25,16 +25,17 @@ */ #include +#include #include #include #include -#if INET_LWIP +#if CHIP_SYSTEM_CONFIG_USE_LWIP #include #include -#endif // INET_LWIP +#endif // CHIP_SYSTEM_CONFIG_USE_LWIP #include @@ -54,10 +55,10 @@ static bool HandleNonOptionArgs(const char * progName, int argc, char * const ar // Globals -#if INET_LWIP +#if CHIP_SYSTEM_CONFIG_USE_LWIP static uint8_t sNumIpAddrs = DNS_MAX_ADDRS_PER_NAME; static ip_addr_t sIpAddrs[DNS_MAX_ADDRS_PER_NAME]; -#endif // INET_LWIP +#endif // CHIP_SYSTEM_CONFIG_USE_LWIP static const char * sHostname = nullptr; static const char * sDNSServerAddr = nullptr; @@ -76,7 +77,7 @@ static ArgParser::OptionSet * gToolOptionSets[] = }; // clang-format on -#if INET_LWIP +#if CHIP_SYSTEM_CONFIG_USE_LWIP static void found_multi(const char * aName, ip_addr_t * aIpAddrs, uint8_t aNumIpAddrs, void * callback_arg) { printf("\tfound_multi response\n"); @@ -205,7 +206,7 @@ static void TestLwIPDNS(void) printf("\tdns_gethostbyname_multi: %d (expected : ERR_OK)\n", res); } } -#endif // INET_LWIP +#endif // CHIP_SYSTEM_CONFIG_USE_LWIP int main(int argc, char * argv[]) { @@ -226,11 +227,11 @@ int main(int argc, char * argv[]) InitNetwork(); -#if INET_LWIP +#if CHIP_SYSTEM_CONFIG_USE_LWIP TestLwIPDNS(); #else - fprintf(stderr, "Please assert INET_LWIP to use this test.\n"); -#endif // INET_LWIP + fprintf(stderr, "Please assert CHIP_SYSTEM_CONFIG_USE_LWIP to use this test.\n"); +#endif // CHIP_SYSTEM_CONFIG_USE_LWIP ShutdownNetwork(); diff --git a/src/lib/support/CHIPArgParser.hpp b/src/lib/support/CHIPArgParser.hpp index 2c16a03f3a9239..57c68e353f58c6 100644 --- a/src/lib/support/CHIPArgParser.hpp +++ b/src/lib/support/CHIPArgParser.hpp @@ -32,6 +32,10 @@ #include #include +#ifndef CHIP_CONFIG_NON_POSIX_LONG_OPT +#define CHIP_CONFIG_NON_POSIX_LONG_OPT 0 +#endif + namespace chip { namespace ArgParser { diff --git a/src/lib/support/Pool.h b/src/lib/support/Pool.h index 72d1a1842b0e36..c2486f0c0e20b3 100644 --- a/src/lib/support/Pool.h +++ b/src/lib/support/Pool.h @@ -324,9 +324,13 @@ class HeapObjectPool : public internal::Statistics, public internal::PoolCommon< #ifdef __clang__ #if __has_feature(address_sanitizer) #define __SANITIZE_ADDRESS__ 1 -#endif -#endif -#endif +#else +#define __SANITIZE_ADDRESS__ 0 +#endif // __has_feature(address_sanitizer) +#else +#define __SANITIZE_ADDRESS__ 0 +#endif // __clang__ +#endif // __SANITIZE_ADDRESS__ #if __SANITIZE_ADDRESS__ // Free all remaining objects so that ASAN can catch specific use-after-free cases. ReleaseAll(); diff --git a/src/lib/support/UnitTestRegistration.cpp b/src/lib/support/UnitTestRegistration.cpp index e706bbc891d6a5..93ea135b85a9ca 100644 --- a/src/lib/support/UnitTestRegistration.cpp +++ b/src/lib/support/UnitTestRegistration.cpp @@ -32,7 +32,7 @@ typedef struct static test_suites_t gs_test_suites; -#if __ZEPHYR__ +#ifdef __ZEPHYR__ inline static bool AlreadyExists(UnitTestTriggerFunction tests) { for (uint32_t i = 0; i < gs_test_suites.num_test_suites; ++i) @@ -50,7 +50,7 @@ CHIP_ERROR RegisterUnitTests(UnitTestTriggerFunction tests) return CHIP_ERROR_NO_MEMORY; } -#if __ZEPHYR__ +#ifdef __ZEPHYR__ // Not sure yet if it's a Zephyr bug or misconfiguration, but global constructors are called // twice on native_posix platform - by libc and by Zephyr's main thread initialization code. // This makes sure tests are not run twice for that reason. diff --git a/src/platform/tests/TestCHIPoBLEStackMgr.h b/src/platform/tests/TestCHIPoBLEStackMgr.h index 2c97e8450f4b55..b0f4f59516f2b1 100644 --- a/src/platform/tests/TestCHIPoBLEStackMgr.h +++ b/src/platform/tests/TestCHIPoBLEStackMgr.h @@ -23,6 +23,8 @@ #pragma once +#include + #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE int TestCHIPoBLEStackManager(); #endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/tests/TestCHIPoBLEStackMgrDriver.cpp b/src/platform/tests/TestCHIPoBLEStackMgrDriver.cpp index e70fccd7e798e6..1d85fdcca4d1b2 100644 --- a/src/platform/tests/TestCHIPoBLEStackMgrDriver.cpp +++ b/src/platform/tests/TestCHIPoBLEStackMgrDriver.cpp @@ -16,6 +16,7 @@ */ #include "TestCHIPoBLEStackMgr.h" +#include #include int main(int argc, char * argv[]) diff --git a/src/system/SystemClock.cpp b/src/system/SystemClock.cpp index c52a1ecec0ed03..3ef63797598f1f 100644 --- a/src/system/SystemClock.cpp +++ b/src/system/SystemClock.cpp @@ -73,7 +73,7 @@ ClockBase * gClockBase = &gClockImpl; #if HAVE_CLOCK_GETTIME -#if HAVE_DECL_CLOCK_BOOTTIME +#if defined(HAVE_DECL_CLOCK_BOOTTIME) && HAVE_DECL_CLOCK_BOOTTIME // CLOCK_BOOTTIME is a Linux-specific option to clock_gettime for a clock which compensates for system sleep. #define MONOTONIC_CLOCK_ID CLOCK_BOOTTIME #define MONOTONIC_RAW_CLOCK_ID CLOCK_MONOTONIC_RAW diff --git a/src/system/SystemPacketBufferInternal.h b/src/system/SystemPacketBufferInternal.h index b0000f4e665df9..e6acb76f6b6e80 100644 --- a/src/system/SystemPacketBufferInternal.h +++ b/src/system/SystemPacketBufferInternal.h @@ -27,6 +27,10 @@ #include #include +#if CHIP_SYSTEM_CONFIG_USE_LWIP +#include +#endif // CHIP_SYSTEM_CONFIG_USE_LWIP + /** * CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_HEAP * From ccdbfee7bcbd0d1888710395a36aebf81d7a037a Mon Sep 17 00:00:00 2001 From: yunhanw-google Date: Thu, 5 Oct 2023 16:48:27 -0700 Subject: [PATCH 11/21] Fix JNI local and global reference leaks in controller (#29236) --- .../pairing/PairOnNetworkLongImReadCommand.kt | 39 +++- src/controller/java/AndroidCallbacks.cpp | 211 ++++++++++++------ src/controller/java/AndroidCallbacks.h | 3 +- .../java/AndroidCommissioningWindowOpener.cpp | 15 +- .../java/AndroidControllerExceptions.cpp | 11 +- .../java/AndroidDeviceControllerWrapper.cpp | 2 + .../devicecontroller/model/NodeState.java | 4 +- src/lib/support/JniTypeWrappers.h | 107 +++++++-- 8 files changed, 292 insertions(+), 100 deletions(-) diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImReadCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImReadCommand.kt index bdf43dfe02a1d5..e5f5711e359aef 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImReadCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImReadCommand.kt @@ -33,6 +33,13 @@ class PairOnNetworkLongImReadCommand( eventPath: ChipEventPath?, e: Exception ) { + if (attributePath != null && attributePath.clusterId.getId() == UNIT_TEST_CLUSTER) { + logger.log( + Level.INFO, + "TODO: skip the error check for unit test cluster that covers most error result" + ) + return + } logger.log(Level.INFO, "Read receive onError") setFailure("read failure") } @@ -55,11 +62,12 @@ class PairOnNetworkLongImReadCommand( fun checkStartUpEventJson(event: EventState): Boolean = event.getJson().toString() == """{"0:STRUCT":{"0:UINT":1}}""" - fun checkAllAttributesJsonForBasicCluster(cluster: String): Boolean { + fun checkAllAttributesJsonForFixedLabel(cluster: String): Boolean { val expected = - """{"16:BOOL":false,""" + - """"65531:ARRAY-UINT":[""" + - """0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20,65528,65529,65531,65532,65533]}""" + """{"65528:ARRAY-?":[],"0:ARRAY-STRUCT":[{"0:STRING":"room","1:STRING":"bedroom 2"},""" + + """{"0:STRING":"orientation","1:STRING":"North"},{"0:STRING":"floor","1:STRING":"2"},""" + + """{"0:STRING":"direction","1:STRING":"up"}],"65531:ARRAY-UINT":[0,65528,65529,65531,65532,65533],""" + + """"65533:UINT":1,"65529:ARRAY-?":[],"65532:UINT":0}""" return cluster.equals(expected) } @@ -67,11 +75,18 @@ class PairOnNetworkLongImReadCommand( val endpointZero = requireNotNull(nodeState.getEndpointState(0)) { "Endpoint zero not found." } + val endpointOne = requireNotNull(nodeState.getEndpointState(0)) { "Endpoint one not found." } + val basicCluster = requireNotNull(endpointZero.getClusterState(CLUSTER_ID_BASIC)) { "Basic cluster not found." } + val fixedLabelCluster = + requireNotNull(endpointOne.getClusterState(FIXED_LABEL_CLUSTER)) { + "fixed label cluster not found." + } + val localConfigDisabledAttribute = requireNotNull(basicCluster.getAttributeState(ATTR_ID_LOCAL_CONFIG_DISABLED)) { "No local config disabled attribute found." @@ -81,7 +96,9 @@ class PairOnNetworkLongImReadCommand( requireNotNull(basicCluster.getEventState(EVENT_ID_START_UP)) { "No start up event found." } val clusterAttributes = - requireNotNull(basicCluster.getAttributesJson()) { "No basicCluster attribute found." } + requireNotNull(fixedLabelCluster.getAttributesJson()) { + "No fixed label cluster attribute found." + } require(checkLocalConfigDisableAttributeTlv(localConfigDisabledAttribute)) { "Invalid local config disabled attribute TLV ${localConfigDisabledAttribute.getTlv().contentToString()}" @@ -101,8 +118,8 @@ class PairOnNetworkLongImReadCommand( "Invalid start up event Json ${startUpEvents[0].getJson().toString()}" } - require(checkAllAttributesJsonForBasicCluster(clusterAttributes)) { - "Invalid basic cluster attributes Json ${clusterAttributes}" + require(checkAllAttributesJsonForFixedLabel(clusterAttributes)) { + "Invalid fixed label cluster attributes Json ${clusterAttributes}" } } @@ -132,9 +149,9 @@ class PairOnNetworkLongImReadCommand( val attributePathList = listOf( ChipAttributePath.newInstance( - ChipPathId.forId(/* endpointId= */ 0), - ChipPathId.forId(CLUSTER_ID_BASIC), - ChipPathId.forId(ATTR_ID_LOCAL_CONFIG_DISABLED), + ChipPathId.forWildcard(), + ChipPathId.forWildcard(), + ChipPathId.forWildcard() ), ChipAttributePath.newInstance( ChipPathId.forId(/* endpointId= */ 0), @@ -176,6 +193,8 @@ class PairOnNetworkLongImReadCommand( private const val MATTER_PORT = 5540 private const val CLUSTER_ID_BASIC = 0x0028L + private const val FIXED_LABEL_CLUSTER = 0x0040L + private const val UNIT_TEST_CLUSTER = 0xfff1fc05 private const val ATTR_ID_LOCAL_CONFIG_DISABLED = 16L private const val EVENT_ID_START_UP = 0L private const val GLOBAL_ATTRIBUTE_LIST = 65531L diff --git a/src/controller/java/AndroidCallbacks.cpp b/src/controller/java/AndroidCallbacks.cpp index b387d504aac54d..2c4d3153400775 100644 --- a/src/controller/java/AndroidCallbacks.cpp +++ b/src/controller/java/AndroidCallbacks.cpp @@ -15,7 +15,6 @@ * limitations under the License. */ #include "AndroidCallbacks.h" -#include #include #if USE_JAVA_TLV_ENCODE_DECODE #include @@ -50,18 +49,28 @@ class JniChipAttributePath jclass attributePathCls = nullptr; ReturnOnFailure(mError = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/model/ChipAttributePath", attributePathCls)); - JniClass attributePathJniCls(attributePathCls); + JniObject attributePathJniCls(env, static_cast(attributePathCls)); jmethodID attributePathCtor = env->GetStaticMethodID(attributePathCls, "newInstance", "(IJJ)Lchip/devicecontroller/model/ChipAttributePath;"); VerifyOrReturn(attributePathCtor != nullptr, mError = CHIP_JNI_ERROR_METHOD_NOT_FOUND); - mData = env->CallStaticObjectMethod(attributePathCls, attributePathCtor, static_cast(aPath.mEndpointId), - static_cast(aPath.mClusterId), static_cast(aPath.mAttributeId)); + jobject localRef = + env->CallStaticObjectMethod(attributePathCls, attributePathCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mAttributeId)); + VerifyOrReturn(localRef != nullptr, mError = CHIP_JNI_ERROR_NULL_OBJECT); + mData = env->NewGlobalRef(localRef); VerifyOrReturn(mData != nullptr, mError = CHIP_JNI_ERROR_NULL_OBJECT); return; } - ~JniChipAttributePath() { mEnv->DeleteLocalRef(mData); } + ~JniChipAttributePath() + { + if (mEnv != nullptr && mData != nullptr) + { + mEnv->DeleteGlobalRef(mData); + mData = nullptr; + } + } CHIP_ERROR GetError() { return mError; } jobject GetData() { return mData; } @@ -80,19 +89,28 @@ class JniChipEventPath jclass eventPathCls = nullptr; ReturnOnFailure( mError = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/model/ChipEventPath", eventPathCls)); - JniClass eventPathJniCls(eventPathCls); + JniObject eventPathJniCls(env, static_cast(eventPathCls)); jmethodID eventPathCtor = env->GetStaticMethodID(eventPathCls, "newInstance", "(IJJ)Lchip/devicecontroller/model/ChipEventPath;"); VerifyOrReturn(eventPathCtor != nullptr, mError = CHIP_JNI_ERROR_METHOD_NOT_FOUND); - mData = env->CallStaticObjectMethod(eventPathCls, eventPathCtor, static_cast(aPath.mEndpointId), - static_cast(aPath.mClusterId), static_cast(aPath.mEventId)); + jobject localRef = env->CallStaticObjectMethod(eventPathCls, eventPathCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mEventId)); + VerifyOrReturn(localRef != nullptr, mError = CHIP_JNI_ERROR_NULL_OBJECT); + mData = (jclass) env->NewGlobalRef(localRef); VerifyOrReturn(mData != nullptr, mError = CHIP_JNI_ERROR_NULL_OBJECT); return; } - ~JniChipEventPath() { mEnv->DeleteLocalRef(mData); } + ~JniChipEventPath() + { + if (mEnv != nullptr && mData != nullptr) + { + mEnv->DeleteGlobalRef(mData); + mData = nullptr; + } + } CHIP_ERROR GetError() { return mError; } jobject GetData() { return mData; } @@ -124,16 +142,20 @@ GetConnectedDeviceCallback::~GetConnectedDeviceCallback() { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); - env->DeleteGlobalRef(mJavaCallbackRef); + if (mJavaCallbackRef != nullptr) + { + env->DeleteGlobalRef(mJavaCallbackRef); + } } void GetConnectedDeviceCallback::OnDeviceConnectedFn(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); auto * self = static_cast(context); jobject javaCallback = self->mJavaCallbackRef; - + JniLocalReferenceManager manager(env); // Release global ref so application can clean up. env->DeleteGlobalRef(self->mWrapperCallbackRef); @@ -142,7 +164,7 @@ void GetConnectedDeviceCallback::OnDeviceConnectedFn(void * context, Messaging:: getConnectedDeviceCallbackCls); VerifyOrReturn(getConnectedDeviceCallbackCls != nullptr, ChipLogError(Controller, "Could not find GetConnectedDeviceCallback class")); - JniClass getConnectedDeviceCallbackJniCls(getConnectedDeviceCallbackCls); + JniObject getConnectedDeviceCallbackJniCls(env, static_cast(getConnectedDeviceCallbackCls)); jmethodID successMethod; JniReferences::GetInstance().FindMethod(env, javaCallback, "onDeviceConnected", "(J)V", &successMethod); @@ -158,19 +180,18 @@ void GetConnectedDeviceCallback::OnDeviceConnectedFn(void * context, Messaging:: void GetConnectedDeviceCallback::OnDeviceConnectionFailureFn(void * context, const ScopedNodeId & peerId, CHIP_ERROR error) { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); auto * self = static_cast(context); jobject javaCallback = self->mJavaCallbackRef; - - // Release global ref so application can clean up. - env->DeleteGlobalRef(self->mWrapperCallbackRef); + JniLocalReferenceManager manager(env); jclass getConnectedDeviceCallbackCls = nullptr; JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/GetConnectedDeviceCallbackJni$GetConnectedDeviceCallback", getConnectedDeviceCallbackCls); VerifyOrReturn(getConnectedDeviceCallbackCls != nullptr, ChipLogError(Controller, "Could not find GetConnectedDeviceCallback class")); - JniClass getConnectedDeviceCallbackJniCls(getConnectedDeviceCallbackCls); + JniObject getConnectedDeviceCallbackJniCls(env, static_cast(getConnectedDeviceCallbackCls)); jmethodID failureMethod; JniReferences::GetInstance().FindMethod(env, javaCallback, "onConnectionFailure", "(JLjava/lang/Exception;)V", &failureMethod); @@ -184,7 +205,7 @@ void GetConnectedDeviceCallback::OnDeviceConnectionFailureFn(void * context, con ChipLogError(Controller, "Unable to create AndroidControllerException on GetConnectedDeviceCallback::OnDeviceConnectionFailureFn: %s", ErrorStr(err))); - + JniObject exceptionJniCls(env, static_cast(exception)); DeviceLayer::StackUnlock unlock; env->CallVoidMethod(javaCallback, failureMethod, peerId.GetNodeId(), exception); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); @@ -231,8 +252,21 @@ ReportCallback::~ReportCallback() if (mSubscriptionEstablishedCallbackRef != nullptr) { env->DeleteGlobalRef(mSubscriptionEstablishedCallbackRef); + mSubscriptionEstablishedCallbackRef = nullptr; } - env->DeleteGlobalRef(mReportCallbackRef); + + if (mReportCallbackRef != nullptr) + { + env->DeleteGlobalRef(mReportCallbackRef); + mReportCallbackRef = nullptr; + } + + if (mResubscriptionAttemptCallbackRef != nullptr) + { + env->DeleteGlobalRef(mResubscriptionAttemptCallbackRef); + mResubscriptionAttemptCallbackRef = nullptr; + } + if (mReadClient != nullptr) { Platform::Delete(mReadClient); @@ -241,18 +275,18 @@ ReportCallback::~ReportCallback() void ReportCallback::OnReportBegin() { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - CHIP_ERROR err = CHIP_NO_ERROR; - - err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/model/NodeState", mNodeStateCls); + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); + jclass nodeStateCls = nullptr; + CHIP_ERROR err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/model/NodeState", nodeStateCls); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not get NodeState class")); - jmethodID nodeStateCtor = env->GetMethodID(mNodeStateCls, "", "(Ljava/util/Map;)V"); + jmethodID nodeStateCtor = env->GetMethodID(nodeStateCls, "", "()V"); VerifyOrReturn(nodeStateCtor != nullptr, ChipLogError(Controller, "Could not find NodeState constructor")); - - jobject map = nullptr; - err = JniReferences::GetInstance().CreateHashMap(map); - VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not create HashMap")); - mNodeStateObj = env->NewObject(mNodeStateCls, nodeStateCtor, map); + jobject nodeState = env->NewObject(nodeStateCls, nodeStateCtor); + VerifyOrReturn(nodeState != nullptr, ChipLogError(Controller, "Could not create local object for nodeState")); + mNodeStateObj = env->NewGlobalRef(nodeState); + VerifyOrReturn(mNodeStateObj != nullptr, ChipLogError(Controller, "Could not create glboal reference for mNodeStateObj")); } void ReportCallback::OnDeallocatePaths(app::ReadPrepareParams && aReadPrepareParams) @@ -275,14 +309,19 @@ void ReportCallback::OnReportEnd() // Transform C++ jobject pair list to a Java HashMap, and call onReport() on the Java callback. CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); + jobject nodeStateObj = env->NewLocalRef(mNodeStateObj); + env->DeleteGlobalRef(mNodeStateObj); + VerifyOrReturn(nodeStateObj != nullptr, ChipLogError(Controller, "Could not create local reference for nodeStateObj")); jmethodID onReportMethod; err = JniReferences::GetInstance().FindMethod(env, mReportCallbackRef, "onReport", "(Lchip/devicecontroller/model/NodeState;)V", &onReportMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find onReport method")); DeviceLayer::StackUnlock unlock; - env->CallVoidMethod(mReportCallbackRef, onReportMethod, mNodeStateObj); + env->CallVoidMethod(mReportCallbackRef, onReportMethod, nodeStateObj); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); } @@ -317,6 +356,8 @@ void ReportCallback::OnAttributeData(const app::ConcreteDataAttributePath & aPat { CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); JniChipAttributePath attributePathObj(env, aPath); VerifyOrReturn(attributePathObj.GetError() == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to create Java ChipAttributePath: %s", ErrorStr(err))); @@ -384,7 +425,7 @@ void ReportCallback::OnAttributeData(const app::ConcreteDataAttributePath & aPat err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/model/AttributeState", attributeStateCls); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find AttributeState class")); VerifyOrReturn(attributeStateCls != nullptr, ChipLogError(Controller, "Could not find AttributeState class")); - chip::JniClass attributeStateJniCls(attributeStateCls); + JniObject attributeStateJniCls(env, static_cast(attributeStateCls)); jmethodID attributeStateCtor = env->GetMethodID(attributeStateCls, "", "(Ljava/lang/Object;[BLjava/lang/String;)V"); VerifyOrReturn(attributeStateCtor != nullptr, ChipLogError(Controller, "Could not find AttributeState constructor")); jobject attributeStateObj = @@ -399,7 +440,6 @@ void ReportCallback::OnAttributeData(const app::ConcreteDataAttributePath & aPat env->CallVoidMethod(mNodeStateObj, addAttributeMethod, static_cast(aPath.mEndpointId), static_cast(aPath.mClusterId), static_cast(aPath.mAttributeId), attributeStateObj); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); - env->DeleteLocalRef(attributeStateObj); UpdateClusterDataVersion(); } @@ -407,6 +447,7 @@ void ReportCallback::OnAttributeData(const app::ConcreteDataAttributePath & aPat void ReportCallback::UpdateClusterDataVersion() { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); chip::app::ConcreteClusterPath lastConcreteClusterPath; if (mClusterCacheAdapter.GetLastReportDataPath(lastConcreteClusterPath) != CHIP_NO_ERROR) @@ -442,6 +483,7 @@ void ReportCallback::OnEventData(const app::EventHeader & aEventHeader, TLV::TLV { CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); JniChipEventPath eventPathObj(env, aEventHeader.mPath); VerifyOrReturn(eventPathObj.GetError() == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to create Java ChipEventPath: %s", ErrorStr(err))); @@ -515,7 +557,7 @@ void ReportCallback::OnEventData(const app::EventHeader & aEventHeader, TLV::TLV err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/model/EventState", eventStateCls); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Failed to find EventState class")); VerifyOrReturn(eventStateCls != nullptr, ChipLogError(Controller, "Could not find EventState class")); - chip::JniClass eventStateJniCls(eventStateCls); + JniObject eventStateJniCls(env, static_cast(eventStateCls)); jmethodID eventStateCtor = env->GetMethodID(eventStateCls, "", "(JIIJLjava/lang/Object;[BLjava/lang/String;)V"); VerifyOrReturn(eventStateCtor != nullptr, ChipLogError(Controller, "Could not find EventState constructor")); jobject eventStateObj = env->NewObject(eventStateCls, eventStateCtor, eventNumber, priorityLevel, timestampType, timestampValue, @@ -531,18 +573,17 @@ void ReportCallback::OnEventData(const app::EventHeader & aEventHeader, TLV::TLV static_cast(aEventHeader.mPath.mClusterId), static_cast(aEventHeader.mPath.mEventId), eventStateObj); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); - env->DeleteLocalRef(eventStateObj); } -CHIP_ERROR InvokeCallback::CreateInvokeElement(const app::ConcreteCommandPath & aPath, TLV::TLVReader * apData, jobject & outObj) +CHIP_ERROR InvokeCallback::CreateInvokeElement(JNIEnv * env, const app::ConcreteCommandPath & aPath, TLV::TLVReader * apData, + jobject & outObj) { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - CHIP_ERROR err = CHIP_NO_ERROR; - + CHIP_ERROR err = CHIP_NO_ERROR; jclass invokeElementCls = nullptr; + jobject localRef = nullptr; err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/model/InvokeElement", invokeElementCls); ReturnErrorOnFailure(err); - JniClass invokeElementJniCls(invokeElementCls); + JniObject invokeElementJniCls(env, static_cast(invokeElementCls)); jmethodID invokeElementCtor = env->GetStaticMethodID(invokeElementCls, "newInstance", "(IJJ[BLjava/lang/String;)Lchip/devicecontroller/model/InvokeElement;"); @@ -557,7 +598,7 @@ CHIP_ERROR InvokeCallback::CreateInvokeElement(const app::ConcreteCommandPath & // Create TLV byte array to pass to Java layer size_t bufferLen = readerForJavaTLV.GetRemainingLength() + readerForJavaTLV.GetLengthRead(); - ; + std::unique_ptr buffer = std::unique_ptr(new uint8_t[bufferLen]); uint32_t size = 0; @@ -576,18 +617,19 @@ CHIP_ERROR InvokeCallback::CreateInvokeElement(const app::ConcreteCommandPath & err = TlvToJson(readerForJson, json); ReturnErrorOnFailure(err); UtfString jsonString(env, json.c_str()); - outObj = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast(aPath.mEndpointId), - static_cast(aPath.mClusterId), static_cast(aPath.mCommandId), - jniByteArray.jniValue(), jsonString.jniValue()); + localRef = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mCommandId), + jniByteArray.jniValue(), jsonString.jniValue()); } else { - outObj = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast(aPath.mEndpointId), - static_cast(aPath.mClusterId), static_cast(aPath.mCommandId), nullptr, - nullptr); + localRef = env->CallStaticObjectMethod(invokeElementCls, invokeElementCtor, static_cast(aPath.mEndpointId), + static_cast(aPath.mClusterId), static_cast(aPath.mCommandId), nullptr, + nullptr); } + VerifyOrReturnError(localRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); + outObj = env->NewGlobalRef(localRef); VerifyOrReturnError(outObj != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); - return err; } @@ -600,6 +642,7 @@ void ReportCallback::OnDone(app::ReadClient *) { CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); jmethodID onDoneMethod; err = JniReferences::GetInstance().FindMethod(env, mReportCallbackRef, "onDone", "()V", &onDoneMethod); @@ -614,11 +657,18 @@ void ReportCallback::OnDone(app::ReadClient *) DeviceLayer::StackUnlock unlock; env->CallVoidMethod(mReportCallbackRef, onDoneMethod); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); - JniReferences::GetInstance().GetEnvForCurrentThread()->DeleteGlobalRef(mWrapperCallbackRef); + if (mWrapperCallbackRef != nullptr) + { + env->DeleteGlobalRef(mWrapperCallbackRef); + mWrapperCallbackRef = nullptr; + } } void ReportCallback::OnSubscriptionEstablished(SubscriptionId aSubscriptionId) { + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); DeviceLayer::StackUnlock unlock; JniReferences::GetInstance().CallSubscriptionEstablished(mSubscriptionEstablishedCallbackRef, aSubscriptionId); } @@ -628,9 +678,9 @@ CHIP_ERROR ReportCallback::OnResubscriptionNeeded(app::ReadClient * apReadClient VerifyOrReturnLogError(mResubscriptionAttemptCallbackRef != nullptr, CHIP_ERROR_INVALID_ARGUMENT); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INVALID_ARGUMENT); ReturnErrorOnFailure(app::ReadClient::Callback::OnResubscriptionNeeded(apReadClient, aTerminationCause)); - + JniLocalReferenceManager manager(env); jmethodID onResubscriptionAttemptMethod; ReturnLogErrorOnFailure(JniReferences::GetInstance().FindMethod( env, mResubscriptionAttemptCallbackRef, "onResubscriptionAttempt", "(JJ)V", &onResubscriptionAttemptMethod)); @@ -658,14 +708,15 @@ void ReportCallback::ReportError(jobject attributePath, jobject eventPath, const { CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); ChipLogError(Controller, "ReportCallback::ReportError is called with %u", errorCode); jthrowable exception; err = AndroidControllerExceptions::GetInstance().CreateAndroidControllerException(env, message, errorCode, exception); VerifyOrReturn( err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to create AndroidControllerException on ReportCallback::ReportError: %s", ErrorStr(err))); - + JniObject exceptionJniCls(env, static_cast(exception)); jmethodID onErrorMethod; err = JniReferences::GetInstance().FindMethod( env, mReportCallbackRef, "onError", @@ -688,6 +739,7 @@ WriteAttributesCallback::WriteAttributesCallback(jobject wrapperCallback, jobjec if (mWrapperCallbackRef == nullptr) { ChipLogError(Controller, "Could not create global reference for Wrapper WriteAttributesCallback"); + return; } mJavaCallbackRef = env->NewGlobalRef(javaCallback); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); @@ -701,7 +753,12 @@ WriteAttributesCallback::~WriteAttributesCallback() { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); - env->DeleteGlobalRef(mJavaCallbackRef); + if (mJavaCallbackRef != nullptr) + { + env->DeleteGlobalRef(mJavaCallbackRef); + mJavaCallbackRef = nullptr; + } + if (mWriteClient != nullptr) { Platform::Delete(mWriteClient); @@ -713,6 +770,8 @@ void WriteAttributesCallback::OnResponse(const app::WriteClient * apWriteClient, { CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); JniChipAttributePath attributePathObj(env, aPath); VerifyOrReturn(attributePathObj.GetError() == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to create Java ChipAttributePath: %s", ErrorStr(err))); @@ -742,7 +801,7 @@ void WriteAttributesCallback::OnDone(app::WriteClient *) { CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); jmethodID onDoneMethod; err = JniReferences::GetInstance().FindMethod(env, mJavaCallbackRef, "onDone", "()V", &onDoneMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find onDone method")); @@ -750,7 +809,11 @@ void WriteAttributesCallback::OnDone(app::WriteClient *) DeviceLayer::StackUnlock unlock; env->CallVoidMethod(mJavaCallbackRef, onDoneMethod); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); - JniReferences::GetInstance().GetEnvForCurrentThread()->DeleteGlobalRef(mWrapperCallbackRef); + if (mWrapperCallbackRef != nullptr) + { + env->DeleteGlobalRef(mWrapperCallbackRef); + mWrapperCallbackRef = nullptr; + } } void WriteAttributesCallback::ReportError(jobject attributePath, CHIP_ERROR err) @@ -767,7 +830,8 @@ void WriteAttributesCallback::ReportError(jobject attributePath, const char * me { CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); ChipLogError(Controller, "WriteAttributesCallback::ReportError is called with %u", errorCode); jthrowable exception; err = AndroidControllerExceptions::GetInstance().CreateAndroidControllerException(env, message, errorCode, exception); @@ -775,7 +839,7 @@ void WriteAttributesCallback::ReportError(jobject attributePath, const char * me ChipLogError(Controller, "Unable to create AndroidControllerException on WriteAttributesCallback::ReportError: %s", ErrorStr(err))); - + JniObject exceptionJniCls(env, static_cast(exception)); jmethodID onErrorMethod; err = JniReferences::GetInstance().FindMethod(env, mJavaCallbackRef, "onError", "(Lchip/devicecontroller/model/ChipAttributePath;Ljava/lang/Exception;)V", @@ -797,6 +861,7 @@ InvokeCallback::InvokeCallback(jobject wrapperCallback, jobject javaCallback) if (mWrapperCallbackRef == nullptr) { ChipLogError(Controller, "Could not create global reference for Wrapper InvokeCallback"); + return; } mJavaCallbackRef = env->NewGlobalRef(javaCallback); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); @@ -810,7 +875,12 @@ InvokeCallback::~InvokeCallback() { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); - env->DeleteGlobalRef(mJavaCallbackRef); + if (mJavaCallbackRef != nullptr) + { + env->DeleteGlobalRef(mJavaCallbackRef); + mJavaCallbackRef = nullptr; + } + if (mCommandSender != nullptr) { Platform::Delete(mCommandSender); @@ -820,13 +890,15 @@ InvokeCallback::~InvokeCallback() void InvokeCallback::OnResponse(app::CommandSender * apCommandSender, const app::ConcreteCommandPath & aPath, const app::StatusIB & aStatusIB, TLV::TLVReader * apData) { - CHIP_ERROR err = CHIP_NO_ERROR; - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + CHIP_ERROR err = CHIP_NO_ERROR; + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); jobject invokeElementObj = nullptr; jmethodID onResponseMethod; - - err = CreateInvokeElement(aPath, apData, invokeElementObj); + JniLocalReferenceManager manager(env); + err = CreateInvokeElement(env, aPath, apData, invokeElementObj); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to create Java InvokeElement: %s", ErrorStr(err))); + JniObject jniInvokeElementObj(env, invokeElementObj); err = JniReferences::GetInstance().FindMethod(env, mJavaCallbackRef, "onResponse", "(Lchip/devicecontroller/model/InvokeElement;J)V", &onResponseMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to find onResponse method: %s", ErrorStr(err))); @@ -854,7 +926,8 @@ void InvokeCallback::OnDone(app::CommandSender * apCommandSender) { CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); jmethodID onDoneMethod; err = JniReferences::GetInstance().FindMethod(env, mJavaCallbackRef, "onDone", "()V", &onDoneMethod); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Could not find onDone method")); @@ -862,7 +935,11 @@ void InvokeCallback::OnDone(app::CommandSender * apCommandSender) DeviceLayer::StackUnlock unlock; env->CallVoidMethod(mJavaCallbackRef, onDoneMethod); VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe()); - JniReferences::GetInstance().GetEnvForCurrentThread()->DeleteGlobalRef(mWrapperCallbackRef); + if (mWrapperCallbackRef != nullptr) + { + env->DeleteGlobalRef(mWrapperCallbackRef); + mWrapperCallbackRef = nullptr; + } } void InvokeCallback::ReportError(CHIP_ERROR err) @@ -879,13 +956,15 @@ void InvokeCallback::ReportError(const char * message, ChipError::StorageType er { CHIP_ERROR err = CHIP_NO_ERROR; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); ChipLogError(Controller, "InvokeCallback::ReportError is called with %u", errorCode); jthrowable exception; err = AndroidControllerExceptions::GetInstance().CreateAndroidControllerException(env, message, errorCode, exception); VerifyOrReturn( err == CHIP_NO_ERROR, ChipLogError(Controller, "Unable to create AndroidControllerException: %s on InvokeCallback::ReportError", ErrorStr(err))); + JniObject exceptionJniCls(env, static_cast(exception)); jmethodID onErrorMethod; err = JniReferences::GetInstance().FindMethod(env, mJavaCallbackRef, "onError", "(Ljava/lang/Exception;)V", &onErrorMethod); diff --git a/src/controller/java/AndroidCallbacks.h b/src/controller/java/AndroidCallbacks.h index f5170f88581d4f..8cccf5fe7881d6 100644 --- a/src/controller/java/AndroidCallbacks.h +++ b/src/controller/java/AndroidCallbacks.h @@ -89,7 +89,6 @@ struct ReportCallback : public app::ClusterStateCache::Callback jobject mReportCallbackRef = nullptr; // NodeState Java object that will be returned to the application. jobject mNodeStateObj = nullptr; - jclass mNodeStateCls = nullptr; }; struct WriteAttributesCallback : public app::WriteClient::Callback @@ -127,7 +126,7 @@ struct InvokeCallback : public app::CommandSender::Callback void OnDone(app::CommandSender * apCommandSender) override; - CHIP_ERROR CreateInvokeElement(const app::ConcreteCommandPath & aPath, TLV::TLVReader * apData, jobject & outObj); + CHIP_ERROR CreateInvokeElement(JNIEnv * env, const app::ConcreteCommandPath & aPath, TLV::TLVReader * apData, jobject & outObj); void ReportError(CHIP_ERROR err); void ReportError(Protocols::InteractionModel::Status status); void ReportError(const char * message, ChipError::StorageType errorCode); diff --git a/src/controller/java/AndroidCommissioningWindowOpener.cpp b/src/controller/java/AndroidCommissioningWindowOpener.cpp index c1a2c5ae09c164..222edcb441f9c8 100644 --- a/src/controller/java/AndroidCommissioningWindowOpener.cpp +++ b/src/controller/java/AndroidCommissioningWindowOpener.cpp @@ -38,6 +38,11 @@ AndroidCommissioningWindowOpener::AndroidCommissioningWindowOpener(DeviceControl { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); mJavaCallback = env->NewGlobalRef(jCallbackObject); + if (mJavaCallback == nullptr) + { + ChipLogError(Controller, "Failed to create global reference for mJavaCallback"); + return; + } jclass callbackClass = env->GetObjectClass(jCallbackObject); @@ -60,7 +65,10 @@ AndroidCommissioningWindowOpener::~AndroidCommissioningWindowOpener() { ChipLogError(Controller, "Delete AndroidCommissioningWindowOpener"); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - env->DeleteGlobalRef(mJavaCallback); + if (mJavaCallback != nullptr) + { + env->DeleteGlobalRef(mJavaCallback); + } } CHIP_ERROR AndroidCommissioningWindowOpener::OpenBasicCommissioningWindow(DeviceController * controller, NodeId deviceId, @@ -112,6 +120,8 @@ void AndroidCommissioningWindowOpener::OnOpenCommissioningWindowResponse(void * { auto * self = static_cast(context); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); VerifyOrExit(self->mJavaCallback != nullptr, ChipLogError(Controller, "mJavaCallback is not allocated.")); @@ -146,10 +156,11 @@ void AndroidCommissioningWindowOpener::OnOpenCommissioningWindowResponse(void * void AndroidCommissioningWindowOpener::OnOpenBasicCommissioningWindowResponse(void * context, NodeId deviceId, CHIP_ERROR status) { auto * self = static_cast(context); - if (self->mJavaCallback != nullptr) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); if (status == CHIP_NO_ERROR) { if (self->mOnSuccessMethod != nullptr) diff --git a/src/controller/java/AndroidControllerExceptions.cpp b/src/controller/java/AndroidControllerExceptions.cpp index e426759eade2e5..4f6932b2ad8640 100644 --- a/src/controller/java/AndroidControllerExceptions.cpp +++ b/src/controller/java/AndroidControllerExceptions.cpp @@ -31,12 +31,15 @@ CHIP_ERROR AndroidControllerExceptions::CreateAndroidControllerException(JNIEnv CHIP_ERROR err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/ChipDeviceControllerException", controllerExceptionCls); VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_JNI_ERROR_TYPE_NOT_FOUND); - JniClass controllerExceptionJniCls(controllerExceptionCls); + + JniObject controllerExceptionJniCls(env, static_cast(controllerExceptionCls)); jmethodID exceptionConstructor = env->GetMethodID(controllerExceptionCls, "", "(JLjava/lang/String;)V"); - outEx = (jthrowable) env->NewObject(controllerExceptionCls, exceptionConstructor, static_cast(errorCode), - env->NewStringUTF(message)); - VerifyOrReturnError(outEx != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND); + jobject localRef = + env->NewObject(controllerExceptionCls, exceptionConstructor, static_cast(errorCode), env->NewStringUTF(message)); + VerifyOrReturnError(localRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); + outEx = (jthrowable) (env->NewGlobalRef(localRef)); + VerifyOrReturnError(outEx != nullptr, CHIP_JNI_ERROR_NULL_OBJECT); return CHIP_NO_ERROR; } diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 53df84ac7302fd..8f0a65c33b2761 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -557,6 +557,8 @@ void AndroidDeviceControllerWrapper::OnCommissioningStatusUpdate(PeerId peerId, { chip::DeviceLayer::StackUnlock unlock; JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + JniLocalReferenceManager manager(env); jmethodID onCommissioningStatusUpdateMethod; CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mJavaObjectRef, "onCommissioningStatusUpdate", "(JLjava/lang/String;I)V", &onCommissioningStatusUpdateMethod); diff --git a/src/controller/java/src/chip/devicecontroller/model/NodeState.java b/src/controller/java/src/chip/devicecontroller/model/NodeState.java index c60e3b6205b2cd..decd9782f5369a 100644 --- a/src/controller/java/src/chip/devicecontroller/model/NodeState.java +++ b/src/controller/java/src/chip/devicecontroller/model/NodeState.java @@ -26,8 +26,8 @@ public final class NodeState { private Map endpoints; - public NodeState(Map endpoints) { - this.endpoints = endpoints; + public NodeState() { + this.endpoints = new HashMap<>(); } public Map getEndpointStates() { diff --git a/src/lib/support/JniTypeWrappers.h b/src/lib/support/JniTypeWrappers.h index ced71bb0e1b793..48d2648db268be 100644 --- a/src/lib/support/JniTypeWrappers.h +++ b/src/lib/support/JniTypeWrappers.h @@ -23,6 +23,7 @@ #include #include +#define JNI_LOCAL_REF_COUNT 256 namespace chip { /// Exposes the underlying UTF string from a jni string class JniUtfString @@ -87,19 +88,41 @@ class JniByteArray class UtfString { public: - UtfString(JNIEnv * env, const char * data) : mEnv(env) { mData = data != nullptr ? mEnv->NewStringUTF(data) : nullptr; } + UtfString(JNIEnv * env, const char * data) : mEnv(env) + { + jstring localRef = data != nullptr ? mEnv->NewStringUTF(data) : nullptr; + if (localRef == nullptr) + { + return; + } + mData = static_cast(env->NewGlobalRef(localRef)); + } + UtfString(JNIEnv * env, chip::CharSpan data) : mEnv(env) { std::string str(data.data(), data.size()); - mData = env->NewStringUTF(str.c_str()); + jstring localRef = env->NewStringUTF(str.c_str()); + if (localRef == nullptr) + { + return; + } + mData = static_cast(env->NewGlobalRef(localRef)); + } + + ~UtfString() + { + if (mEnv != nullptr && mData != nullptr) + { + mEnv->DeleteGlobalRef(mData); + mData = nullptr; + } } - ~UtfString() { mEnv->DeleteLocalRef(mData); } jstring jniValue() { return mData; } private: - JNIEnv * mEnv; - jstring mData; + JNIEnv * mEnv = nullptr; + jstring mData = nullptr; }; /// wrap a byte array as a JNI byte array @@ -108,27 +131,39 @@ class ByteArray public: ByteArray(JNIEnv * env, const jbyte * data, jsize dataLen) : mEnv(env) { - mArray = data != nullptr ? mEnv->NewByteArray(dataLen) : nullptr; - if (mArray != nullptr) + jbyteArray localRef = data != nullptr ? mEnv->NewByteArray(dataLen) : nullptr; + if (localRef == nullptr) { - env->SetByteArrayRegion(mArray, 0, dataLen, data); + return; } + env->SetByteArrayRegion(localRef, 0, dataLen, data); + mArray = static_cast(env->NewGlobalRef(localRef)); } + ByteArray(JNIEnv * env, chip::ByteSpan data) : mEnv(env) { - mArray = mEnv->NewByteArray(static_cast(data.size())); - if (mArray != nullptr) + jbyteArray localRef = mEnv->NewByteArray(static_cast(data.size())); + if (localRef == nullptr) { - env->SetByteArrayRegion(mArray, 0, static_cast(data.size()), reinterpret_cast(data.data())); + return; + } + env->SetByteArrayRegion(localRef, 0, static_cast(data.size()), reinterpret_cast(data.data())); + mArray = static_cast(env->NewGlobalRef(localRef)); + } + + ~ByteArray() + { + if (mEnv != nullptr && mArray != nullptr) + { + mEnv->DeleteGlobalRef(mArray); } } - ~ByteArray() { mEnv->DeleteLocalRef(mArray); } jbyteArray jniValue() { return mArray; } private: - JNIEnv * mEnv; - jbyteArray mArray; + JNIEnv * mEnv = nullptr; + jbyteArray mArray = nullptr; }; /// Manages an pre-existing global reference to a jclass. @@ -143,4 +178,48 @@ class JniClass private: jclass mClassRef; }; + +class JniLocalReferenceManager +{ +public: + JniLocalReferenceManager(JNIEnv * env) : mEnv(env) + { + if (mEnv->PushLocalFrame(JNI_LOCAL_REF_COUNT) == 0) + { + mlocalFramePushed = true; + } + } + ~JniLocalReferenceManager() + { + if (mlocalFramePushed) + { + mEnv->PopLocalFrame(nullptr); + mlocalFramePushed = false; + } + } + +private: + JNIEnv * mEnv = nullptr; + bool mlocalFramePushed = false; +}; + +class JniObject +{ +public: + JniObject(JNIEnv * aEnv, jobject aObjectRef) : mEnv(aEnv), mObjectRef(aObjectRef) {} + ~JniObject() + { + if (mEnv != nullptr && mObjectRef != nullptr) + { + mEnv->DeleteGlobalRef(mObjectRef); + } + } + + jobject objectRef() { return mObjectRef; } + +private: + JNIEnv * mEnv = nullptr; + jobject mObjectRef = nullptr; +}; + } // namespace chip From d825d5114ab934162c543980b3662b5d00c1e6ea Mon Sep 17 00:00:00 2001 From: Jean-Francois Penven <67962328+jepenven-silabs@users.noreply.github.com> Date: Thu, 5 Oct 2023 21:59:33 -0400 Subject: [PATCH 12/21] [ICD] Remove key from ICD Management cluster (#29562) * update cluster * Update Generated files * update tests --- .../all-clusters-app.matter | 1 - .../light-switch-app.matter | 1 - examples/lock-app/lock-common/lock-app.matter | 1 - .../smoke-co-alarm-app.matter | 1 - .../icd-management-server.cpp | 1 - .../suites/TestIcdManagementCluster.yaml | 47 +++---------------- .../chip/icd-management-cluster.xml | 2 +- .../data_model/controller-clusters.matter | 1 - ...mentClusterMonitoringRegistrationStruct.kt | 6 --- .../CHIPAttributeTLVValueDecoder.cpp | 13 ++--- .../java/zap-generated/CHIPReadCallbacks.cpp | 12 ++--- .../chip/devicecontroller/ChipStructs.java | 6 --- .../python/chip/clusters/Objects.py | 2 - .../MTRAttributeTLVValueDecoder.mm | 1 - .../CHIP/zap-generated/MTRCallbackBridge.mm | 1 - .../CHIP/zap-generated/MTRStructsObjc.h | 1 - .../CHIP/zap-generated/MTRStructsObjc.mm | 5 +- .../zap-generated/cluster-objects.cpp | 8 ---- .../zap-generated/cluster-objects.h | 6 +-- .../cluster/ComplexArgumentParser.cpp | 7 --- .../cluster/logging/DataModelLogger.cpp | 8 ---- .../zap-generated/test/Commands.h | 7 --- 22 files changed, 17 insertions(+), 121 deletions(-) diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter index 1b65362b884cff..635052df996693 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter @@ -2408,7 +2408,6 @@ server cluster IcdManagement = 70 { fabric_scoped struct MonitoringRegistrationStruct { fabric_sensitive node_id checkInNodeID = 1; fabric_sensitive int64u monitoredSubject = 2; - fabric_sensitive octet_string<16> key = 3; fabric_idx fabricIndex = 254; } diff --git a/examples/light-switch-app/light-switch-common/light-switch-app.matter b/examples/light-switch-app/light-switch-common/light-switch-app.matter index faea21aea6a5fc..5b774fed609304 100644 --- a/examples/light-switch-app/light-switch-common/light-switch-app.matter +++ b/examples/light-switch-app/light-switch-common/light-switch-app.matter @@ -1945,7 +1945,6 @@ server cluster IcdManagement = 70 { fabric_scoped struct MonitoringRegistrationStruct { fabric_sensitive node_id checkInNodeID = 1; fabric_sensitive int64u monitoredSubject = 2; - fabric_sensitive octet_string<16> key = 3; fabric_idx fabricIndex = 254; } diff --git a/examples/lock-app/lock-common/lock-app.matter b/examples/lock-app/lock-common/lock-app.matter index 94fcf03083ef2c..a9d48da67f2049 100644 --- a/examples/lock-app/lock-common/lock-app.matter +++ b/examples/lock-app/lock-common/lock-app.matter @@ -1676,7 +1676,6 @@ server cluster IcdManagement = 70 { fabric_scoped struct MonitoringRegistrationStruct { fabric_sensitive node_id checkInNodeID = 1; fabric_sensitive int64u monitoredSubject = 2; - fabric_sensitive octet_string<16> key = 3; fabric_idx fabricIndex = 254; } diff --git a/examples/smoke-co-alarm-app/smoke-co-alarm-common/smoke-co-alarm-app.matter b/examples/smoke-co-alarm-app/smoke-co-alarm-common/smoke-co-alarm-app.matter index 7e9812625b7fbe..6750ae11e42513 100644 --- a/examples/smoke-co-alarm-app/smoke-co-alarm-common/smoke-co-alarm-app.matter +++ b/examples/smoke-co-alarm-app/smoke-co-alarm-common/smoke-co-alarm-app.matter @@ -1558,7 +1558,6 @@ server cluster IcdManagement = 70 { fabric_scoped struct MonitoringRegistrationStruct { fabric_sensitive node_id checkInNodeID = 1; fabric_sensitive int64u monitoredSubject = 2; - fabric_sensitive octet_string<16> key = 3; fabric_idx fabricIndex = 254; } diff --git a/src/app/clusters/icd-management-server/icd-management-server.cpp b/src/app/clusters/icd-management-server/icd-management-server.cpp index a99cf22a3334bc..10e92c833c0dbf 100644 --- a/src/app/clusters/icd-management-server/icd-management-server.cpp +++ b/src/app/clusters/icd-management-server/icd-management-server.cpp @@ -126,7 +126,6 @@ CHIP_ERROR IcdManagementAttributeAccess::ReadRegisteredClients(EndpointId endpoi Structs::MonitoringRegistrationStruct::Type s{ .checkInNodeID = e.checkInNodeID, .monitoredSubject = e.monitoredSubject, - .key = e.key, .fabricIndex = e.fabricIndex }; ReturnErrorOnFailure(subEncoder.Encode(s)); } diff --git a/src/app/tests/suites/TestIcdManagementCluster.yaml b/src/app/tests/suites/TestIcdManagementCluster.yaml index d02a3a6d2a91ec..3b62c6837bb9c2 100644 --- a/src/app/tests/suites/TestIcdManagementCluster.yaml +++ b/src/app/tests/suites/TestIcdManagementCluster.yaml @@ -167,17 +167,8 @@ tests: response: value: [ - { - CheckInNodeID: 101, - MonitoredSubject: 1001, - Key: "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f", - }, - { - CheckInNodeID: 201, - MonitoredSubject: 2001, - Key: - "\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f", - }, + { CheckInNodeID: 101, MonitoredSubject: 1001 }, + { CheckInNodeID: 201, MonitoredSubject: 2001 }, ] - label: "Register 1.1" @@ -201,17 +192,8 @@ tests: response: value: [ - { - CheckInNodeID: 101, - MonitoredSubject: 1002, - Key: "\x01\x11\x21\x31\x41\x51\x61\x71\x81\x91\xa1\xb1\xc1\xd1\xe1\xf1", - }, - { - CheckInNodeID: 201, - MonitoredSubject: 2001, - Key: - "\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f", - }, + { CheckInNodeID: 101, MonitoredSubject: 1002 }, + { CheckInNodeID: 201, MonitoredSubject: 2001 }, ] - label: "Register 2.2 (wrong verification key)" @@ -238,16 +220,8 @@ tests: response: value: [ - { - CheckInNodeID: 101, - MonitoredSubject: 1002, - Key: "\x01\x11\x21\x31\x41\x51\x61\x71\x81\x91\xa1\xb1\xc1\xd1\xe1\xf1", - }, - { - CheckInNodeID: 201, - MonitoredSubject: 2002, - Key: "\x02\x12\x22\x32\x42\x52\x62\x72\x82\x92\xa2\xb2\xc2\xd2\xe2\x2f", - }, + { CheckInNodeID: 101, MonitoredSubject: 1002 }, + { CheckInNodeID: 201, MonitoredSubject: 2002 }, ] - label: "Unregister 1.1 (wrong key)" @@ -263,14 +237,7 @@ tests: command: "readAttribute" attribute: "RegisteredClients" response: - value: - [ - { - CheckInNodeID: 201, - MonitoredSubject: 2002, - Key: "\x02\x12\x22\x32\x42\x52\x62\x72\x82\x92\xa2\xb2\xc2\xd2\xe2\x2f", - }, - ] + value: [{ CheckInNodeID: 201, MonitoredSubject: 2002 }] - label: "Unregister 2.1" command: "UnregisterClient" diff --git a/src/app/zap-templates/zcl/data-model/chip/icd-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/icd-management-cluster.xml index b16101ee25da0e..6c0d73d166aeef 100644 --- a/src/app/zap-templates/zcl/data-model/chip/icd-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/icd-management-cluster.xml @@ -27,7 +27,7 @@ limitations under the License. - + diff --git a/src/controller/data_model/controller-clusters.matter b/src/controller/data_model/controller-clusters.matter index 5d9ec2b27415b7..e8730291e5cece 100644 --- a/src/controller/data_model/controller-clusters.matter +++ b/src/controller/data_model/controller-clusters.matter @@ -2713,7 +2713,6 @@ client cluster IcdManagement = 70 { fabric_scoped struct MonitoringRegistrationStruct { fabric_sensitive node_id checkInNodeID = 1; fabric_sensitive int64u monitoredSubject = 2; - fabric_sensitive octet_string<16> key = 3; fabric_idx fabricIndex = 254; } diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt index d7b59660342a48..88ff61a3be4864 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/IcdManagementClusterMonitoringRegistrationStruct.kt @@ -25,14 +25,12 @@ import chip.tlv.TlvWriter class IcdManagementClusterMonitoringRegistrationStruct( val checkInNodeID: ULong, val monitoredSubject: ULong, - val key: ByteArray, val fabricIndex: UInt ) { override fun toString(): String = buildString { append("IcdManagementClusterMonitoringRegistrationStruct {\n") append("\tcheckInNodeID : $checkInNodeID\n") append("\tmonitoredSubject : $monitoredSubject\n") - append("\tkey : $key\n") append("\tfabricIndex : $fabricIndex\n") append("}\n") } @@ -42,7 +40,6 @@ class IcdManagementClusterMonitoringRegistrationStruct( startStructure(tlvTag) put(ContextSpecificTag(TAG_CHECK_IN_NODE_I_D), checkInNodeID) put(ContextSpecificTag(TAG_MONITORED_SUBJECT), monitoredSubject) - put(ContextSpecificTag(TAG_KEY), key) put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex) endStructure() } @@ -51,7 +48,6 @@ class IcdManagementClusterMonitoringRegistrationStruct( companion object { private const val TAG_CHECK_IN_NODE_I_D = 1 private const val TAG_MONITORED_SUBJECT = 2 - private const val TAG_KEY = 3 private const val TAG_FABRIC_INDEX = 254 fun fromTlv( @@ -61,7 +57,6 @@ class IcdManagementClusterMonitoringRegistrationStruct( tlvReader.enterStructure(tlvTag) val checkInNodeID = tlvReader.getULong(ContextSpecificTag(TAG_CHECK_IN_NODE_I_D)) val monitoredSubject = tlvReader.getULong(ContextSpecificTag(TAG_MONITORED_SUBJECT)) - val key = tlvReader.getByteArray(ContextSpecificTag(TAG_KEY)) val fabricIndex = tlvReader.getUInt(ContextSpecificTag(TAG_FABRIC_INDEX)) tlvReader.exitContainer() @@ -69,7 +64,6 @@ class IcdManagementClusterMonitoringRegistrationStruct( return IcdManagementClusterMonitoringRegistrationStruct( checkInNodeID, monitoredSubject, - key, fabricIndex ) } diff --git a/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp b/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp index 6faa72db2086ba..b223c8522bc158 100644 --- a/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp +++ b/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp @@ -12377,11 +12377,6 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR chip::JniReferences::GetInstance().CreateBoxedObject( newElement_0_monitoredSubjectClassName.c_str(), newElement_0_monitoredSubjectCtorSignature.c_str(), jninewElement_0_monitoredSubject, newElement_0_monitoredSubject); - jobject newElement_0_key; - jbyteArray newElement_0_keyByteArray = env->NewByteArray(static_cast(entry_0.key.size())); - env->SetByteArrayRegion(newElement_0_keyByteArray, 0, static_cast(entry_0.key.size()), - reinterpret_cast(entry_0.key.data())); - newElement_0_key = newElement_0_keyByteArray; jobject newElement_0_fabricIndex; std::string newElement_0_fabricIndexClassName = "java/lang/Integer"; std::string newElement_0_fabricIndexCtorSignature = "(I)V"; @@ -12399,9 +12394,8 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR ChipLogError(Zcl, "Could not find class ChipStructs$IcdManagementClusterMonitoringRegistrationStruct"); return nullptr; } - jmethodID monitoringRegistrationStructStructCtor_1 = - env->GetMethodID(monitoringRegistrationStructStructClass_1, "", - "(Ljava/lang/Long;Ljava/lang/Long;[BLjava/lang/Integer;)V"); + jmethodID monitoringRegistrationStructStructCtor_1 = env->GetMethodID( + monitoringRegistrationStructStructClass_1, "", "(Ljava/lang/Long;Ljava/lang/Long;Ljava/lang/Integer;)V"); if (monitoringRegistrationStructStructCtor_1 == nullptr) { ChipLogError(Zcl, "Could not find ChipStructs$IcdManagementClusterMonitoringRegistrationStruct constructor"); @@ -12409,8 +12403,7 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR } newElement_0 = env->NewObject(monitoringRegistrationStructStructClass_1, monitoringRegistrationStructStructCtor_1, - newElement_0_checkInNodeID, newElement_0_monitoredSubject, newElement_0_key, - newElement_0_fabricIndex); + newElement_0_checkInNodeID, newElement_0_monitoredSubject, newElement_0_fabricIndex); chip::JniReferences::GetInstance().AddToList(value, newElement_0); } return value; diff --git a/src/controller/java/zap-generated/CHIPReadCallbacks.cpp b/src/controller/java/zap-generated/CHIPReadCallbacks.cpp index 47ecaa3c2c3b74..6fddee564cd0df 100644 --- a/src/controller/java/zap-generated/CHIPReadCallbacks.cpp +++ b/src/controller/java/zap-generated/CHIPReadCallbacks.cpp @@ -19170,11 +19170,6 @@ void CHIPIcdManagementRegisteredClientsAttributeCallback::CallbackFn( chip::JniReferences::GetInstance().CreateBoxedObject( newElement_0_monitoredSubjectClassName.c_str(), newElement_0_monitoredSubjectCtorSignature.c_str(), jninewElement_0_monitoredSubject, newElement_0_monitoredSubject); - jobject newElement_0_key; - jbyteArray newElement_0_keyByteArray = env->NewByteArray(static_cast(entry_0.key.size())); - env->SetByteArrayRegion(newElement_0_keyByteArray, 0, static_cast(entry_0.key.size()), - reinterpret_cast(entry_0.key.data())); - newElement_0_key = newElement_0_keyByteArray; jobject newElement_0_fabricIndex; std::string newElement_0_fabricIndexClassName = "java/lang/Integer"; std::string newElement_0_fabricIndexCtorSignature = "(I)V"; @@ -19193,16 +19188,15 @@ void CHIPIcdManagementRegisteredClientsAttributeCallback::CallbackFn( return; } jmethodID monitoringRegistrationStructStructCtor_1 = env->GetMethodID( - monitoringRegistrationStructStructClass_1, "", "(Ljava/lang/Long;Ljava/lang/Long;[BLjava/lang/Integer;)V"); + monitoringRegistrationStructStructClass_1, "", "(Ljava/lang/Long;Ljava/lang/Long;Ljava/lang/Integer;)V"); if (monitoringRegistrationStructStructCtor_1 == nullptr) { ChipLogError(Zcl, "Could not find ChipStructs$IcdManagementClusterMonitoringRegistrationStruct constructor"); return; } - newElement_0 = - env->NewObject(monitoringRegistrationStructStructClass_1, monitoringRegistrationStructStructCtor_1, - newElement_0_checkInNodeID, newElement_0_monitoredSubject, newElement_0_key, newElement_0_fabricIndex); + newElement_0 = env->NewObject(monitoringRegistrationStructStructClass_1, monitoringRegistrationStructStructCtor_1, + newElement_0_checkInNodeID, newElement_0_monitoredSubject, newElement_0_fabricIndex); chip::JniReferences::GetInstance().AddToList(arrayListObj, newElement_0); } diff --git a/src/controller/java/zap-generated/chip/devicecontroller/ChipStructs.java b/src/controller/java/zap-generated/chip/devicecontroller/ChipStructs.java index 6907c0912103af..e4495493213c61 100644 --- a/src/controller/java/zap-generated/chip/devicecontroller/ChipStructs.java +++ b/src/controller/java/zap-generated/chip/devicecontroller/ChipStructs.java @@ -1545,18 +1545,15 @@ public String toString() { public static class IcdManagementClusterMonitoringRegistrationStruct { public Long checkInNodeID; public Long monitoredSubject; -public byte[] key; public Integer fabricIndex; public IcdManagementClusterMonitoringRegistrationStruct( Long checkInNodeID , Long monitoredSubject - , byte[] key , Integer fabricIndex ) { this.checkInNodeID = checkInNodeID; this.monitoredSubject = monitoredSubject; - this.key = key; this.fabricIndex = fabricIndex; } @@ -1570,9 +1567,6 @@ public String toString() { output.append("\tmonitoredSubject: "); output.append(monitoredSubject); output.append("\n"); - output.append("\tkey: "); - output.append(Arrays.toString(key)); - output.append("\n"); output.append("\tfabricIndex: "); output.append(fabricIndex); output.append("\n"); diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index 39a3294b0470da..ccd8eff0932925 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -14674,13 +14674,11 @@ def descriptor(cls) -> ClusterObjectDescriptor: Fields=[ ClusterObjectFieldDescriptor(Label="checkInNodeID", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="monitoredSubject", Tag=2, Type=uint), - ClusterObjectFieldDescriptor(Label="key", Tag=3, Type=bytes), ClusterObjectFieldDescriptor(Label="fabricIndex", Tag=254, Type=uint), ]) checkInNodeID: 'uint' = 0 monitoredSubject: 'uint' = 0 - key: 'bytes' = b"" fabricIndex: 'uint' = 0 class Commands: diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm index 429b109c7de8bb..aa6b075c9e3cf0 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm @@ -5112,7 +5112,6 @@ static id _Nullable DecodeAttributeValueForICDManagementCluster(AttributeId aAtt newElement_0 = [MTRICDManagementClusterMonitoringRegistrationStruct new]; newElement_0.checkInNodeID = [NSNumber numberWithUnsignedLongLong:entry_0.checkInNodeID]; newElement_0.monitoredSubject = [NSNumber numberWithUnsignedLongLong:entry_0.monitoredSubject]; - newElement_0.key = AsData(entry_0.key); newElement_0.fabricIndex = [NSNumber numberWithUnsignedChar:entry_0.fabricIndex]; [array_0 addObject:newElement_0]; } diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRCallbackBridge.mm b/src/darwin/Framework/CHIP/zap-generated/MTRCallbackBridge.mm index 97d481dfcf7245..cd3d0947ea5379 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRCallbackBridge.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRCallbackBridge.mm @@ -8124,7 +8124,6 @@ newElement_0 = [MTRICDManagementClusterMonitoringRegistrationStruct new]; newElement_0.checkInNodeID = [NSNumber numberWithUnsignedLongLong:entry_0.checkInNodeID]; newElement_0.monitoredSubject = [NSNumber numberWithUnsignedLongLong:entry_0.monitoredSubject]; - newElement_0.key = AsData(entry_0.key); newElement_0.fabricIndex = [NSNumber numberWithUnsignedChar:entry_0.fabricIndex]; [array_0 addObject:newElement_0]; } diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h index 8d21c944217ae4..b4f24e39d67f53 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h @@ -773,7 +773,6 @@ MTR_PROVISIONALLY_AVAILABLE @interface MTRICDManagementClusterMonitoringRegistrationStruct : NSObject @property (nonatomic, copy) NSNumber * _Nonnull checkInNodeID MTR_PROVISIONALLY_AVAILABLE; @property (nonatomic, copy) NSNumber * _Nonnull monitoredSubject MTR_PROVISIONALLY_AVAILABLE; -@property (nonatomic, copy) NSData * _Nonnull key MTR_PROVISIONALLY_AVAILABLE; @property (nonatomic, copy) NSNumber * _Nonnull fabricIndex MTR_PROVISIONALLY_AVAILABLE; @end diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm index 965a1b6ef6cc15..9a4b63d7f67cc4 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm @@ -2839,8 +2839,6 @@ - (instancetype)init _monitoredSubject = @(0); - _key = [NSData data]; - _fabricIndex = @(0); } return self; @@ -2852,7 +2850,6 @@ - (id)copyWithZone:(NSZone * _Nullable)zone other.checkInNodeID = self.checkInNodeID; other.monitoredSubject = self.monitoredSubject; - other.key = self.key; other.fabricIndex = self.fabricIndex; return other; @@ -2860,7 +2857,7 @@ - (id)copyWithZone:(NSZone * _Nullable)zone - (NSString *)description { - NSString * descriptionString = [NSString stringWithFormat:@"<%@: checkInNodeID:%@; monitoredSubject:%@; key:%@; fabricIndex:%@; >", NSStringFromClass([self class]), _checkInNodeID, _monitoredSubject, [_key base64EncodedStringWithOptions:0], _fabricIndex]; + NSString * descriptionString = [NSString stringWithFormat:@"<%@: checkInNodeID:%@; monitoredSubject:%@; fabricIndex:%@; >", NSStringFromClass([self class]), _checkInNodeID, _monitoredSubject, _fabricIndex]; return descriptionString; } diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp index 5f8a0c555c4c68..263a23b1dc9200 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp @@ -10356,10 +10356,6 @@ CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optiona { ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMonitoredSubject), monitoredSubject)); } - if (includeSensitive) - { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kKey), key)); - } if (aAccessingFabricIndex.HasValue()) { ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); @@ -10390,10 +10386,6 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) { err = DataModel::Decode(reader, monitoredSubject); } - else if (__context_tag == to_underlying(Fields::kKey)) - { - err = DataModel::Decode(reader, key); - } else if (__context_tag == to_underlying(Fields::kFabricIndex)) { err = DataModel::Decode(reader, fabricIndex); diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h index a10542a3222de2..ca41b4b25a3dcd 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h @@ -13806,16 +13806,14 @@ enum class Fields : uint8_t { kCheckInNodeID = 1, kMonitoredSubject = 2, - kKey = 3, kFabricIndex = 254, }; struct Type { public: - chip::NodeId checkInNodeID = static_cast(0); - uint64_t monitoredSubject = static_cast(0); - chip::ByteSpan key; + chip::NodeId checkInNodeID = static_cast(0); + uint64_t monitoredSubject = static_cast(0); chip::FabricIndex fabricIndex = static_cast(0); CHIP_ERROR Decode(TLV::TLVReader & reader); diff --git a/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp b/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp index c72ad1d6409a65..e0c1360460b1c7 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp @@ -1980,8 +1980,6 @@ CHIP_ERROR ComplexArgumentParser::Setup(const char * label, value.isMember("checkInNodeID"))); ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("MonitoringRegistrationStruct.monitoredSubject", "monitoredSubject", value.isMember("monitoredSubject"))); - ReturnErrorOnFailure( - ComplexArgumentParser::EnsureMemberExist("MonitoringRegistrationStruct.key", "key", value.isMember("key"))); char labelWithMember[kMaxLabelLength]; snprintf(labelWithMember, sizeof(labelWithMember), "%s.%s", label, "checkInNodeID"); @@ -1992,10 +1990,6 @@ CHIP_ERROR ComplexArgumentParser::Setup(const char * label, ReturnErrorOnFailure(ComplexArgumentParser::Setup(labelWithMember, request.monitoredSubject, value["monitoredSubject"])); valueCopy.removeMember("monitoredSubject"); - snprintf(labelWithMember, sizeof(labelWithMember), "%s.%s", label, "key"); - ReturnErrorOnFailure(ComplexArgumentParser::Setup(labelWithMember, request.key, value["key"])); - valueCopy.removeMember("key"); - if (value.isMember("fabricIndex")) { snprintf(labelWithMember, sizeof(labelWithMember), "%s.%s", label, "fabricIndex"); @@ -2010,7 +2004,6 @@ void ComplexArgumentParser::Finalize(chip::app::Clusters::IcdManagement::Structs { ComplexArgumentParser::Finalize(request.checkInNodeID); ComplexArgumentParser::Finalize(request.monitoredSubject); - ComplexArgumentParser::Finalize(request.key); ComplexArgumentParser::Finalize(request.fabricIndex); } diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp index 14f88167fe5b44..5fe79f45fa1b5f 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp @@ -1789,14 +1789,6 @@ DataModelLogger::LogValue(const char * label, size_t indent, return err; } } - { - CHIP_ERROR err = LogValue("Key", indent + 1, value.key); - if (err != CHIP_NO_ERROR) - { - DataModelLogger::LogString(indent + 1, "Struct truncated due to invalid value for 'Key'"); - return err; - } - } { CHIP_ERROR err = LogValue("FabricIndex", indent + 1, value.fabricIndex); if (err != CHIP_NO_ERROR) diff --git a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h index 07b07acb67d4c3..60974f536d19d3 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h @@ -41256,10 +41256,8 @@ class TestIcdManagementCluster : public TestCommandBridge { VerifyOrReturn(CheckValue("RegisteredClients", [actualValue count], static_cast(2))); VerifyOrReturn(CheckValue("CheckInNodeID", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).checkInNodeID, 101ULL)); VerifyOrReturn(CheckValue("MonitoredSubject", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).monitoredSubject, 1001ULL)); - VerifyOrReturn(CheckValueAsString("Key", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).key, [[NSData alloc] initWithBytes:"\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" length:16])); VerifyOrReturn(CheckValue("CheckInNodeID", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[1]).checkInNodeID, 201ULL)); VerifyOrReturn(CheckValue("MonitoredSubject", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[1]).monitoredSubject, 2001ULL)); - VerifyOrReturn(CheckValueAsString("Key", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[1]).key, [[NSData alloc] initWithBytes:" !\042#$%&'()*+,-./" length:16])); } NextTest(); @@ -41318,10 +41316,8 @@ class TestIcdManagementCluster : public TestCommandBridge { VerifyOrReturn(CheckValue("RegisteredClients", [actualValue count], static_cast(2))); VerifyOrReturn(CheckValue("CheckInNodeID", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).checkInNodeID, 101ULL)); VerifyOrReturn(CheckValue("MonitoredSubject", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).monitoredSubject, 1002ULL)); - VerifyOrReturn(CheckValueAsString("Key", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).key, [[NSData alloc] initWithBytes:"\001\021!1AQaq\201\221\241\261\301\321\341\361" length:16])); VerifyOrReturn(CheckValue("CheckInNodeID", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[1]).checkInNodeID, 201ULL)); VerifyOrReturn(CheckValue("MonitoredSubject", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[1]).monitoredSubject, 2001ULL)); - VerifyOrReturn(CheckValueAsString("Key", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[1]).key, [[NSData alloc] initWithBytes:" !\042#$%&'()*+,-./" length:16])); } NextTest(); @@ -41382,10 +41378,8 @@ class TestIcdManagementCluster : public TestCommandBridge { VerifyOrReturn(CheckValue("RegisteredClients", [actualValue count], static_cast(2))); VerifyOrReturn(CheckValue("CheckInNodeID", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).checkInNodeID, 101ULL)); VerifyOrReturn(CheckValue("MonitoredSubject", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).monitoredSubject, 1002ULL)); - VerifyOrReturn(CheckValueAsString("Key", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).key, [[NSData alloc] initWithBytes:"\001\021!1AQaq\201\221\241\261\301\321\341\361" length:16])); VerifyOrReturn(CheckValue("CheckInNodeID", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[1]).checkInNodeID, 201ULL)); VerifyOrReturn(CheckValue("MonitoredSubject", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[1]).monitoredSubject, 2002ULL)); - VerifyOrReturn(CheckValueAsString("Key", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[1]).key, [[NSData alloc] initWithBytes:"\002\022\0422BRbr\202\222\242\262\302\322\342/" length:16])); } NextTest(); @@ -41437,7 +41431,6 @@ class TestIcdManagementCluster : public TestCommandBridge { VerifyOrReturn(CheckValue("RegisteredClients", [actualValue count], static_cast(1))); VerifyOrReturn(CheckValue("CheckInNodeID", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).checkInNodeID, 201ULL)); VerifyOrReturn(CheckValue("MonitoredSubject", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).monitoredSubject, 2002ULL)); - VerifyOrReturn(CheckValueAsString("Key", ((MTRICDManagementClusterMonitoringRegistrationStruct *) actualValue[0]).key, [[NSData alloc] initWithBytes:"\002\022\0422BRbr\202\222\242\262\302\322\342/" length:16])); } NextTest(); From f4c20943e03a0739dddf313666649820ee7f746e Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Thu, 5 Oct 2023 20:31:10 -0700 Subject: [PATCH 13/21] [Android]Initial implementation of Kotlin Matter Controller (#29574) * Initial implemenation of Kotlin Matter Controller * Rename to KotlinMatterController * Rename Interactions to InteractionClient * Address review comments * Restyled by gn --------- Co-authored-by: Restyled.io --- kotlin-detect-config.yaml | 2 + src/controller/java/BUILD.gn | 33 + .../controller/CompletionListenerAdapter.kt | 70 ++ .../src/matter/controller/ControllerParams.kt | 42 ++ .../matter/controller/InteractionClient.kt | 59 ++ .../src/matter/controller/MatterController.kt | 107 +++ .../controller/MatterControllerException.kt | 24 + .../matter/controller/MatterControllerImpl.kt | 612 ++++++++++++++++++ .../java/src/matter/controller/Messages.kt | 201 ++++++ .../matter/controller/OperationalKeyConfig.kt | 52 ++ .../java/src/matter/controller/model/Paths.kt | 59 ++ .../src/matter/controller/model/States.kt | 75 +++ 12 files changed, 1336 insertions(+) create mode 100644 src/controller/java/src/matter/controller/CompletionListenerAdapter.kt create mode 100644 src/controller/java/src/matter/controller/ControllerParams.kt create mode 100644 src/controller/java/src/matter/controller/InteractionClient.kt create mode 100644 src/controller/java/src/matter/controller/MatterController.kt create mode 100644 src/controller/java/src/matter/controller/MatterControllerException.kt create mode 100644 src/controller/java/src/matter/controller/MatterControllerImpl.kt create mode 100644 src/controller/java/src/matter/controller/Messages.kt create mode 100644 src/controller/java/src/matter/controller/OperationalKeyConfig.kt create mode 100644 src/controller/java/src/matter/controller/model/Paths.kt create mode 100644 src/controller/java/src/matter/controller/model/States.kt diff --git a/kotlin-detect-config.yaml b/kotlin-detect-config.yaml index 165bd85bec2917..d1e3b160e15974 100644 --- a/kotlin-detect-config.yaml +++ b/kotlin-detect-config.yaml @@ -289,6 +289,8 @@ complexity: - "**/src/controller/java/src/chip/onboardingpayload/OnboardingPayload.kt" - "**/src/controller/java/src/chip/tlv/TlvReader.kt" - "**/src/controller/java/src/chip/tlv/TlvWriter.kt" + - "**/src/controller/java/src/matter/controller/MatterControllerImpl.kt" + - "**/src/controller/java/src/matter/controller/CompletionListenerAdapter.kt" - "**/src/controller/java/tests/chip/jsontlv/JsonToTlvToJsonTest.kt" - "**/src/controller/java/tests/chip/onboardingpayload/ManualCodeTest.kt" - "**/src/controller/java/tests/chip/onboardingpayload/QRCodeTest.kt" diff --git a/src/controller/java/BUILD.gn b/src/controller/java/BUILD.gn index 0eb1bd9141a8ac..e7e4a949309a18 100644 --- a/src/controller/java/BUILD.gn +++ b/src/controller/java/BUILD.gn @@ -351,6 +351,39 @@ kotlin_library("chipcluster_test") { kotlinc_flags = [ "-Xlint:deprecation" ] } +kotlin_library("kotlin_matter_controller") { + output_name = "KotlinMatterController.jar" + + deps = [ + ":java", + "${chip_root}/third_party/java_deps:annotation", + ] + + sources = [ + "src/matter/controller/CompletionListenerAdapter.kt", + "src/matter/controller/ControllerParams.kt", + "src/matter/controller/InteractionClient.kt", + "src/matter/controller/MatterController.kt", + "src/matter/controller/MatterControllerException.kt", + "src/matter/controller/MatterControllerImpl.kt", + "src/matter/controller/Messages.kt", + "src/matter/controller/OperationalKeyConfig.kt", + "src/matter/controller/model/Paths.kt", + "src/matter/controller/model/States.kt", + ] + + if (matter_enable_java_compilation) { + deps += [ + "${chip_root}/third_party/java_deps:json", + "${chip_root}/third_party/java_deps:kotlin-stdlib", + "${chip_root}/third_party/java_deps:kotlinx-coroutines-core-jvm", + "${chip_root}/third_party/java_deps/stub_src", + ] + } else { + deps += [ ":android" ] + } +} + group("unit_tests") { deps = [ ":chipcluster_test", diff --git a/src/controller/java/src/matter/controller/CompletionListenerAdapter.kt b/src/controller/java/src/matter/controller/CompletionListenerAdapter.kt new file mode 100644 index 00000000000000..c1956154115d89 --- /dev/null +++ b/src/controller/java/src/matter/controller/CompletionListenerAdapter.kt @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2023 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. + * + */ +package matter.controller + +import chip.devicecontroller.ChipDeviceController +import java.util.logging.Level +import java.util.logging.Logger + +class CompletionListenerAdapter(val listener: MatterController.CompletionListener) : + chip.devicecontroller.ChipDeviceController.CompletionListener { + + override fun onConnectDeviceComplete() = listener.onConnectDeviceComplete() + + override fun onStatusUpdate(status: Int) = listener.onStatusUpdate(status) + + override fun onPairingComplete(errorCode: Int) = listener.onPairingComplete(errorCode) + + override fun onPairingDeleted(errorCode: Int) = listener.onPairingDeleted(errorCode) + + override fun onNotifyChipConnectionClosed() = listener.onNotifyChipConnectionClosed() + + override fun onCommissioningComplete(nodeId: Long, errorCode: Int) = + listener.onCommissioningComplete(nodeId, errorCode) + + override fun onCommissioningStatusUpdate(nodeId: Long, stage: String?, errorCode: Int) = + listener.onCommissioningStatusUpdate(nodeId, stage, errorCode) + + override fun onReadCommissioningInfo( + vendorId: Int, + productId: Int, + wifiEndpointId: Int, + threadEndpointId: Int + ) = listener.onReadCommissioningInfo(vendorId, productId, wifiEndpointId, threadEndpointId) + + override fun onOpCSRGenerationComplete(csr: ByteArray) = listener.onOpCSRGenerationComplete(csr) + + override fun onError(error: Throwable) = listener.onError(error) + + override fun onCloseBleComplete() { + logger.log(Level.INFO, "Not implemented, override the abstract function.") + } + + companion object { + private val logger = Logger.getLogger(MatterController::class.java.simpleName) + + fun from( + listener: MatterController.CompletionListener? + ): chip.devicecontroller.ChipDeviceController.CompletionListener? { + if (listener == null) { + return null + } + return CompletionListenerAdapter(listener) + } + } +} diff --git a/src/controller/java/src/matter/controller/ControllerParams.kt b/src/controller/java/src/matter/controller/ControllerParams.kt new file mode 100644 index 00000000000000..d0fb23222ea68e --- /dev/null +++ b/src/controller/java/src/matter/controller/ControllerParams.kt @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2023 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. + * + */ +package matter.controller + +/** + * Parameters representing initialization arguments for [MatterController]. + * + * @param operationalKeyConfig An optional signing configuration for operational control of devices. + * @param udpListenPort A port for UDP communications, or [UDP_PORT_AUTO] to select automatically. + * @param vendorId The identifier for the vendor using this controller. + * @param countryCode The Regulatory Location country code. + */ +class ControllerParams +@JvmOverloads +constructor( + val operationalKeyConfig: OperationalKeyConfig? = null, + val udpListenPort: Int = UDP_PORT_AUTO, + val vendorId: Int = VENDOR_ID_TEST, + val countryCode: String? = null, +) { + companion object { + /** Matter assigned vendor ID for Google. */ + const val VENDOR_ID_TEST = 0xFFF1 + /** Indicates that the UDP listen port should be chosen automatically. */ + const val UDP_PORT_AUTO = 0 + } +} diff --git a/src/controller/java/src/matter/controller/InteractionClient.kt b/src/controller/java/src/matter/controller/InteractionClient.kt new file mode 100644 index 00000000000000..71f86ff056228d --- /dev/null +++ b/src/controller/java/src/matter/controller/InteractionClient.kt @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023 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. + * + */ +package matter.controller + +import kotlinx.coroutines.flow.Flow + +interface InteractionClient { + /** + * Subscribes to periodic updates of all attributes and events from a device. + * + * @param request The Subscribe command's path and arguments. + * @return A Flow of SubscriptionState representing the subscription's state updates. + */ + fun subscribe(request: SubscribeRequest): Flow + + /** + * Issues a read request to a target device for specified attributes and events. + * + * @param request Read command's path and arguments. + * @return A response to the read request. + * @throws Generic Exception if an error occurs during the read operation. + */ + suspend fun read(request: ReadRequest): ReadResponse + + /** + * Issues attribute write requests to a target device. + * + * @param writeRequests A list of attribute WriteRequest. + * @return A response to the write request. + * @throws Generic Exception or MatterControllerException if an error occurs during the write + * operation. + */ + suspend fun write(writeRequests: WriteRequests): WriteResponse + + /** + * Invokes a command on a target device. + * + * @param request Invoke command's path and arguments. + * @return A response to the invoke request. + * @throws Generic Exception or MatterControllerException if an error occurs during the invoke + * operation. + */ + suspend fun invoke(request: InvokeRequest): InvokeResponse +} diff --git a/src/controller/java/src/matter/controller/MatterController.kt b/src/controller/java/src/matter/controller/MatterController.kt new file mode 100644 index 00000000000000..5ac5a85020db98 --- /dev/null +++ b/src/controller/java/src/matter/controller/MatterController.kt @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2023 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. + * + */ +package matter.controller + +import java.io.Closeable + +/** Controller interface for interacting with a CHIP device. */ +interface MatterController : Closeable, InteractionClient { + /** Interface for listening to callbacks from the MatterController. */ + interface CompletionListener { + /** Notifies the completion of the "ConnectDevice" command. */ + fun onConnectDeviceComplete() + + /** Notifies the pairing status. */ + fun onStatusUpdate(status: Int) + + /** Notifies the completion of pairing. */ + fun onPairingComplete(errorCode: Int) + + /** Notifies the deletion of a pairing session. */ + fun onPairingDeleted(errorCode: Int) + + /** Notifies that the CHIP connection has been closed. */ + fun onNotifyChipConnectionClosed() + + /** Notifies the completion of commissioning. */ + fun onCommissioningComplete(nodeId: Long, errorCode: Int) + + /** Notifies the completion of reading commissioning information. */ + fun onReadCommissioningInfo( + vendorId: Int, + productId: Int, + wifiEndpointId: Int, + threadEndpointId: Int + ) + + /** Notifies the completion of each stage of commissioning. */ + fun onCommissioningStatusUpdate(nodeId: Long, stage: String?, errorCode: Int) + + /** Notifies the listener of an error. */ + fun onError(error: Throwable) + + /** Notifies the Commissioner when the OpCSR for the Comissionee is generated. */ + fun onOpCSRGenerationComplete(csr: ByteArray) + } + + /** + * Sets a completion listener for receiving controller events. + * + * @param listener The listener to set. + */ + fun setCompletionListener(listener: CompletionListener?) + + /** + * Commissions a device into a Matter fabric. + * + * @param nodeId The ID of the node to connect to. + * @param address The IP address at which the node is located. + * @param port The port at which the node is located. + * @param discriminator A 12-bit value used to discern between multiple commissionable Matter + * device advertisements. + * @param pinCode The pincode for this node. + */ + fun pairDevice( + nodeId: Long, + address: String, + port: Int, + discriminator: Int, + pinCode: Long, + ) + + /** + * Removes pairing for a paired device. If the device is currently being paired, it will stop the + * pairing process. + * + * @param nodeId The remote device ID. + */ + fun unpairDevice(nodeId: Long) + + /** + * Establishes a secure PASE connection to the given device via IP address. + * + * @param nodeId The ID of the node to connect to. + * @param address The IP address at which the node is located. + * @param port The port at which the node is located. + * @param setupPincode The pincode for this node. + */ + fun establishPaseConnection(nodeId: Long, address: String, port: Int, setupPincode: Long) + + /** Closes any active connections through this device controller. */ + override fun close() +} diff --git a/src/controller/java/src/matter/controller/MatterControllerException.kt b/src/controller/java/src/matter/controller/MatterControllerException.kt new file mode 100644 index 00000000000000..dfe97947b19dba --- /dev/null +++ b/src/controller/java/src/matter/controller/MatterControllerException.kt @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2023 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. + * + */ +package matter.controller + +class MatterControllerException(errorCode: Long, message: String? = null) : + RuntimeException(message ?: "Error Code $errorCode") { + + val errorCode: Long = errorCode +} diff --git a/src/controller/java/src/matter/controller/MatterControllerImpl.kt b/src/controller/java/src/matter/controller/MatterControllerImpl.kt new file mode 100644 index 00000000000000..5583b69f330636 --- /dev/null +++ b/src/controller/java/src/matter/controller/MatterControllerImpl.kt @@ -0,0 +1,612 @@ +/* + * Copyright (c) 2023 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. + * + */ +package matter.controller + +import chip.devicecontroller.ChipDeviceController +import chip.devicecontroller.ChipDeviceControllerException +import chip.devicecontroller.GetConnectedDeviceCallbackJni.GetConnectedDeviceCallback +import chip.devicecontroller.InvokeCallback +import chip.devicecontroller.ReportCallback +import chip.devicecontroller.ResubscriptionAttemptCallback +import chip.devicecontroller.SubscriptionEstablishedCallback +import chip.devicecontroller.WriteAttributesCallback +import chip.devicecontroller.model.AttributeWriteRequest +import chip.devicecontroller.model.ChipAttributePath +import chip.devicecontroller.model.ChipEventPath +import chip.devicecontroller.model.ChipPathId +import chip.devicecontroller.model.InvokeElement +import java.util.logging.Level +import java.util.logging.Logger +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException +import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED +import kotlinx.coroutines.channels.awaitClose +import kotlinx.coroutines.channels.onFailure +import kotlinx.coroutines.channels.trySendBlocking +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.buffer +import kotlinx.coroutines.flow.callbackFlow +import kotlinx.coroutines.suspendCancellableCoroutine +import matter.controller.model.AttributePath +import matter.controller.model.AttributeState +import matter.controller.model.ClusterState +import matter.controller.model.EndpointState +import matter.controller.model.EventPath +import matter.controller.model.EventState +import matter.controller.model.NodeState + +/** Controller to interact with the CHIP device. */ +class MatterControllerImpl(params: ControllerParams) : MatterController { + private val deviceController: ChipDeviceController + private var nodeId: Long? = null + + override fun setCompletionListener(listener: MatterController.CompletionListener?) = + deviceController.setCompletionListener(CompletionListenerAdapter.from(listener)) + + override fun pairDevice( + nodeId: Long, + address: String, + port: Int, + discriminator: Int, + pinCode: Long, + ) { + this.nodeId = nodeId + deviceController.pairDeviceWithAddress(nodeId, address, port, discriminator, pinCode, null) + } + + override fun unpairDevice(nodeId: Long) { + deviceController.unpairDevice(nodeId) + this.nodeId = null + } + + override fun establishPaseConnection( + nodeId: Long, + address: String, + port: Int, + setupPincode: Long + ) { + deviceController.establishPaseConnection(nodeId, address, port, setupPincode) + } + + override fun subscribe(request: SubscribeRequest): Flow { + // To prevent potential issues related to concurrent modification, assign + // the value of the mutable property 'nodeId' to a temporary variable. + val nodeId = this.nodeId + check(nodeId != null) { "nodeId has not been initialized yet" } + + val attributePaths = generateAttributePaths(request) + val eventPaths = generateEventPaths(request) + val successes = mutableListOf() + val failures = mutableListOf() + + return callbackFlow { + val devicePtr: Long = getConnectedDevicePointer(nodeId) + val subscriptionEstablishedHandler = SubscriptionEstablishedCallback { + logger.log(Level.INFO, "Subscription to device established") + + trySendBlocking(SubscriptionState.SubscriptionEstablished).onFailure { ex -> + logger.log( + Level.SEVERE, + "Error sending SubscriptionCompletedNotification to subscriber: %s", + ex + ) + } + } + + val resubscriptionAttemptHandler = + ResubscriptionAttemptCallback { terminationCause, nextResubscribeIntervalMsec -> + logger.log( + Level.WARNING, + "ResubscriptionAttempt terminationCause:${terminationCause}, " + + "nextResubscribeIntervalMsec:${nextResubscribeIntervalMsec}" + ) + + trySendBlocking( + SubscriptionState.SubscriptionErrorNotification(terminationCause.toUInt()) + ) + .onFailure { ex -> + logger.log( + Level.SEVERE, + "Error sending ResubscriptionNotification to subscriber: %s", + ex + ) + } + } + + val reportHandler = + object : ReportCallback { + override fun onReport(nodeState: chip.devicecontroller.model.NodeState) { + logger.log(Level.INFO, "Received subscribe update report") + + val tmpNodeState: NodeState = nodeState.wrap() + + for (endpoint in tmpNodeState.endpoints) { + for (cluster in endpoint.value.clusters) { + for (attribute in cluster.value.attributes) { + val attributePath = + AttributePath( + endpointId = endpoint.key.toUShort(), + clusterId = cluster.key.toUInt(), + attributeId = attribute.key.toUInt() + ) + val readData = ReadData.Attribute(attributePath, attribute.value.tlvValue) + successes.add(readData) + } + + for (eventList in cluster.value.events) { + for (event in eventList.value) { + val timestamp: Timestamp = + when (event.timestampType) { + chip.devicecontroller.model.EventState.MILLIS_SINCE_BOOT -> + Timestamp.MillisSinceBoot(event.timestampValue) + chip.devicecontroller.model.EventState.MILLIS_SINCE_EPOCH -> + Timestamp.MillisSinceEpoch(event.timestampValue) + else -> { + logger.log(Level.SEVERE, "Unsupported event timestamp type - ignoring") + break + } + } + + val eventPath = + EventPath( + endpointId = endpoint.key.toUShort(), + clusterId = cluster.key.toUInt(), + eventId = eventList.key.toUInt() + ) + + val readData = + ReadData.Event( + path = eventPath, + eventNumber = event.eventNumber.toULong(), + priorityLevel = event.priorityLevel.toUByte(), + timeStamp = timestamp, + data = event.tlvValue + ) + successes.add(readData) + } + } + } + } + + trySendBlocking(SubscriptionState.NodeStateUpdate(ReadResponse(successes, failures))) + .onFailure { ex -> + logger.log(Level.SEVERE, "Error sending NodeStateUpdate to subscriber: %s", ex) + } + } + + override fun onError( + attributePath: ChipAttributePath?, + eventPath: ChipEventPath?, + ex: Exception + ) { + attributePath?.let { + logger.log(Level.INFO, "Report error for attributePath:%s", it.toString()) + val tmpAttributePath: AttributePath = attributePath.wrap() + val attributeFailure = ReadFailure.Attribute(path = tmpAttributePath, error = ex) + failures.add(attributeFailure) + } + eventPath?.let { + logger.log(Level.INFO, "Report error for eventPath:%s", it.toString()) + val tmpEventPath: EventPath = eventPath.wrap() + val eventFailure = ReadFailure.Event(path = tmpEventPath, error = ex) + failures.add(eventFailure) + } + + // The underlying subscription is terminated if both attributePath & eventPath are + // null + if (attributePath == null && eventPath == null) { + logger.log(Level.SEVERE, "The underlying subscription is terminated") + + trySendBlocking( + SubscriptionState.SubscriptionErrorNotification(CHIP_ERROR_UNEXPECTED_EVENT) + ) + .onFailure { exception -> + logger.log( + Level.SEVERE, + "Error sending SubscriptionErrorNotification to subscriber: %s", + exception + ) + } + } + } + + override fun onDone() { + logger.log(Level.INFO, "Subscription update completed") + } + } + + deviceController.subscribeToPath( + subscriptionEstablishedHandler, + resubscriptionAttemptHandler, + reportHandler, + devicePtr, + attributePaths, + eventPaths, + request.minInterval.seconds.toInt(), + request.maxInterval.seconds.toInt(), + request.keepSubscriptions, + request.fabricFiltered, + CHIP_IM_TIMEOUT_MS + ) + + awaitClose { logger.log(Level.FINE, "Closing flow") } + } + .buffer(capacity = UNLIMITED) + } + + override suspend fun read(request: ReadRequest): ReadResponse { + // To prevent potential issues related to concurrent modification, assign + // the value of the mutable property 'nodeId' to a temporary variable. + val nodeId = this.nodeId + check(nodeId != null) { "nodeId has not been initialized yet" } + + val devicePtr: Long = getConnectedDevicePointer(nodeId) + + val chipAttributePaths = + request.attributePaths.map { attributePath -> + val endpointId = attributePath.endpointId.toInt() + val clusterId = attributePath.clusterId.toLong() + val attributeId = attributePath.attributeId.toLong() + ChipAttributePath.newInstance(endpointId, clusterId, attributeId) + } + + val chipEventPaths = + request.eventPaths.map { eventPath -> + val endpointId = eventPath.endpointId.toInt() + val clusterId = eventPath.clusterId.toLong() + val eventId = eventPath.eventId.toLong() + ChipEventPath.newInstance(endpointId, clusterId, eventId) + } + + val successes = mutableListOf() + val failures = mutableListOf() + + return suspendCancellableCoroutine { continuation -> + val reportCallback = + object : ReportCallback { + override fun onReport(nodeState: chip.devicecontroller.model.NodeState) { + logger.log(Level.FINE, "Received read report") + + val tmpNodeState: NodeState = nodeState.wrap() + + for (endpoint in tmpNodeState.endpoints) { + for (cluster in endpoint.value.clusters) { + for (attribute in cluster.value.attributes) { + val attributePath = + AttributePath( + endpointId = endpoint.key.toUShort(), + clusterId = cluster.key.toUInt(), + attributeId = attribute.key.toUInt() + ) + val readData = ReadData.Attribute(attributePath, attribute.value.tlvValue) + successes.add(readData) + } + + for (eventList in cluster.value.events) { + for (event in eventList.value) { + val timestamp: Timestamp = + when (event.timestampType) { + chip.devicecontroller.model.EventState.MILLIS_SINCE_BOOT -> + Timestamp.MillisSinceBoot(event.timestampValue) + chip.devicecontroller.model.EventState.MILLIS_SINCE_EPOCH -> + Timestamp.MillisSinceEpoch(event.timestampValue) + else -> { + logger.log(Level.SEVERE, "Unsupported event timestamp type - ignoring") + break + } + } + val eventPath = + EventPath( + endpointId = endpoint.key.toUShort(), + clusterId = cluster.key.toUInt(), + eventId = eventList.key.toUInt() + ) + + val readData = + ReadData.Event( + path = eventPath, + eventNumber = event.eventNumber.toULong(), + priorityLevel = event.priorityLevel.toUByte(), + timeStamp = timestamp, + data = event.tlvValue + ) + successes.add(readData) + } + } + } + } + } + + override fun onError( + attributePath: ChipAttributePath?, + eventPath: ChipEventPath?, + ex: Exception + ) { + attributePath?.let { + logger.log(Level.INFO, "Report error for attributePath:%s", it.toString()) + val tmpAttributePath: AttributePath = attributePath.wrap() + val attributeFailure = ReadFailure.Attribute(path = tmpAttributePath, error = ex) + failures.add(attributeFailure) + } + eventPath?.let { + logger.log(Level.INFO, "Report error for eventPath:%s", it.toString()) + val tmpEventPath: EventPath = eventPath.wrap() + val eventFailure = ReadFailure.Event(path = tmpEventPath, error = ex) + failures.add(eventFailure) + } + + // The underlying subscription is terminated if both attributePath & eventPath are null + if (attributePath == null && eventPath == null) { + continuation.resumeWithException( + Exception("Read command failed with error ${ex.message}") + ) + } + } + + override fun onDone() { + logger.log(Level.FINE, "read command completed") + continuation.resume(ReadResponse(successes, failures)) + } + } + + deviceController.readPath( + reportCallback, + devicePtr, + chipAttributePaths, + chipEventPaths, + false, + CHIP_IM_TIMEOUT_MS, + ) + } + } + + override suspend fun write(writeRequests: WriteRequests): WriteResponse { + // To prevent potential issues related to concurrent modification, assign + // the value of the mutable property 'nodeId' to a temporary variable. + val nodeId = this.nodeId + check(nodeId != null) { "nodeId has not been initialized yet" } + + val devicePtr: Long = getConnectedDevicePointer(nodeId) + + val attributeWriteRequests = + writeRequests.requests.map { request -> + AttributeWriteRequest.newInstance( + ChipPathId.forId(request.attributePath.endpointId.toLong()), + ChipPathId.forId(request.attributePath.clusterId.toLong()), + ChipPathId.forId(request.attributePath.attributeId.toLong()), + request.tlvPayload + ) + } + + val failures = mutableListOf() + + return suspendCancellableCoroutine { continuation -> + val writeCallback = + object : WriteAttributesCallback { + override fun onResponse(attributePath: ChipAttributePath) { + logger.log(Level.INFO, "write success for attributePath:%s", attributePath.toString()) + } + + override fun onError(attributePath: ChipAttributePath?, ex: Exception) { + logger.log( + Level.SEVERE, + "Failed to write attribute at path: %s", + attributePath.toString() + ) + + if (attributePath == null) { + if (ex is ChipDeviceControllerException) { + continuation.resumeWithException( + MatterControllerException(ex.errorCode, ex.message) + ) + } else { + continuation.resumeWithException(ex) + } + } else { + failures.add(AttributeWriteError(attributePath.wrap(), ex)) + } + } + + override fun onDone() { + logger.log(Level.INFO, "writeAttributes onDone is received") + + if (failures.isNotEmpty()) { + continuation.resume(WriteResponse.PartialWriteFailure(failures)) + } else { + continuation.resume(WriteResponse.Success) + } + } + } + + deviceController.write( + writeCallback, + devicePtr, + attributeWriteRequests.toList(), + writeRequests.timedRequest?.toMillis()?.toInt() ?: 0, + CHIP_IM_TIMEOUT_MS, + ) + } + } + + override suspend fun invoke(request: InvokeRequest): InvokeResponse { + // To prevent potential issues related to concurrent modification, assign + // the value of the mutable property 'nodeId' to a temporary variable. + val nodeId = this.nodeId + check(nodeId != null) { "nodeId has not been initialized yet" } + + val devicePtr: Long = getConnectedDevicePointer(nodeId) + + val invokeRequest = + InvokeElement.newInstance( + ChipPathId.forId(request.commandPath.endpointId.toLong()), + ChipPathId.forId(request.commandPath.clusterId.toLong()), + ChipPathId.forId(request.commandPath.commandId.toLong()), + request.tlvPayload, + /* jsonString= */ null + ) + + return suspendCancellableCoroutine { continuation -> + var invokeCallback = + object : InvokeCallback { + override fun onResponse(invokeElement: InvokeElement?, successCode: Long) { + logger.log(Level.FINE, "Invoke onResponse is received") + val tlvByteArray = invokeElement?.getTlvByteArray() ?: byteArrayOf() + continuation.resume(InvokeResponse(tlvByteArray)) + } + + override fun onError(ex: Exception) { + if (ex is ChipDeviceControllerException) { + continuation.resumeWithException(MatterControllerException(ex.errorCode, ex.message)) + } else { + continuation.resumeWithException(ex) + } + } + } + + deviceController.invoke( + invokeCallback, + devicePtr, + invokeRequest, + request.timedRequest?.toMillis()?.toInt() ?: 0, + CHIP_IM_TIMEOUT_MS + ) + } + } + + override fun close() { + logger.log(Level.INFO, "MatterController is closed") + deviceController.shutdownCommissioning() + } + + private suspend fun getConnectedDevicePointer(nodeId: Long): Long { + return suspendCancellableCoroutine { cont -> + logger.log(Level.INFO, "Looking up pointer for %016X", nodeId) + deviceController.getConnectedDevicePointer( + nodeId, + object : GetConnectedDeviceCallback { + override fun onDeviceConnected(devicePointer: Long) { + logger.log(Level.INFO, "Resolved pointer ${devicePointer} for device ${nodeId}") + cont.resume(devicePointer) + } + + override fun onConnectionFailure(nodeId: Long, error: Exception) { + logger.log(Level.SEVERE, "Failed to establish CASE session for device ${nodeId}") + cont.resumeWithException( + Exception("Failed to establish CASE session for device %016X".format(nodeId)) + ) + } + } + ) + } + } + + private fun generateAttributePaths(request: SubscribeRequest): List { + return request.attributePaths.map { attributePath -> + ChipAttributePath.newInstance( + attributePath.endpointId.toInt(), + attributePath.clusterId.toLong(), + attributePath.attributeId.toLong() + ) + } + } + + private fun generateEventPaths(request: SubscribeRequest): List { + return request.eventPaths.map { eventPath -> + ChipEventPath.newInstance( + eventPath.endpointId.toInt(), + eventPath.clusterId.toLong(), + eventPath.eventId.toLong(), + false + ) + } + } + + private fun ChipAttributePath.wrap(): AttributePath { + return AttributePath( + endpointId.getId().toUShort(), + clusterId.getId().toUInt(), + attributeId.getId().toUInt() + ) + } + + private fun ChipEventPath.wrap(): EventPath { + return EventPath( + endpointId.getId().toUShort(), + clusterId.getId().toUInt(), + eventId.getId().toUInt() + ) + } + + private fun chip.devicecontroller.model.NodeState.wrap(): NodeState { + return NodeState( + endpoints = endpointStates.mapValues { (id, value) -> value.wrap(id) }, + ) + } + + private fun chip.devicecontroller.model.EndpointState.wrap(id: Int): EndpointState { + return EndpointState(id, clusterStates.mapValues { (id, value) -> value.wrap(id) }) + } + + private fun chip.devicecontroller.model.ClusterState.wrap(id: Long): ClusterState { + return ClusterState( + id, + attributeStates.mapValues { (id, value) -> value.wrap(id) }, + eventStates.mapValues { (id, value) -> value.map { eventState -> eventState.wrap(id) } } + ) + } + + private fun chip.devicecontroller.model.AttributeState.wrap(id: Long): AttributeState { + return AttributeState(id, tlv, json.toString()) + } + + private fun chip.devicecontroller.model.EventState.wrap(id: Long): EventState { + return EventState(id, eventNumber, priorityLevel, timestampType, timestampValue, tlv) + } + + init { + val config: OperationalKeyConfig? = params.operationalKeyConfig + val paramsBuilder = + chip.devicecontroller.ControllerParams.newBuilder() + .setUdpListenPort(params.udpListenPort) + .setControllerVendorId(params.vendorId) + .setCountryCode(params.countryCode) + + if (config != null) { + val intermediateCertificate = config.certificateData.intermediateCertificate + paramsBuilder + .setRootCertificate(config.certificateData.trustedRootCertificate) + .setIntermediateCertificate(intermediateCertificate ?: byteArrayOf()) + .setOperationalCertificate(config.certificateData.operationalCertificate) + .setKeypairDelegate(config.keypairDelegate) + .setIpk(config.ipk) + } + + deviceController = ChipDeviceController(paramsBuilder.build()) + } + + companion object { + private val logger = Logger.getLogger(MatterController::class.java.simpleName) + + // im interaction time out value, it would override the default value in c++ im + // layer if this value is non-zero. + private const val CHIP_IM_TIMEOUT_MS = 0 + + // CHIP error values, lift from ChipError.h in the Matter SDK. + private const val CHIP_ERROR_UNEXPECTED_EVENT: UInt = 0xc0u + } +} diff --git a/src/controller/java/src/matter/controller/Messages.kt b/src/controller/java/src/matter/controller/Messages.kt new file mode 100644 index 00000000000000..36f3fd6fc3ad2c --- /dev/null +++ b/src/controller/java/src/matter/controller/Messages.kt @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2023 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. + * + */ +package matter.controller + +import java.time.Duration +import matter.controller.model.AttributePath +import matter.controller.model.CommandPath +import matter.controller.model.EventPath + +private const val DEFAULT_SUBSCRIPTION_MIN_INTERVAL_S: Long = 0L +private const val DEFAULT_SUBSCRIPTION_MAX_INTERVAL_S: Long = 30L + +/** + * Representation of Timestamp type. + * + * This sealed class represents timestamps in two different formats: + * - [MillisSinceBoot]: System Time in milliseconds since boot. + * - [MillisSinceEpoch]: POSIX Time in milliseconds from the UNIX epoch (1970-01-01 00:00:00 UTC). + * + * @param value The time offset in milliseconds. + */ +sealed class Timestamp { + data class MillisSinceBoot(val value: Long) : Timestamp() + + data class MillisSinceEpoch(val value: Long) : Timestamp() +} + +/** + * Information about a read request element. + * + * @param eventPaths A list of event path information in the read request. + * @param attributePaths A list of attribute path information in the read request. + */ +class ReadRequest( + val eventPaths: List, + val attributePaths: List, +) + +/** Represents data received from a read operation. */ +sealed class ReadData { + /** + * Represents data related to an event. + * + * @param path The event path associated with the data. + * @param eventNumber the event number value that is scoped to the node + * @param priorityLevel the priority describes the usage semantics of the event + * @param timeStamp the timestamp at the time the event was created + * @param data The ByteArray containing the data in TLV format. + */ + class Event( + val path: EventPath, + val eventNumber: ULong, + val priorityLevel: UByte, + val timeStamp: Timestamp, + val data: ByteArray + ) : ReadData() + + /** + * Represents data related to an attribute. + * + * @param path The attribute path associated with the data. + * @param data The ByteArray containing the data in TLV format. + */ + class Attribute(val path: AttributePath, val data: ByteArray) : ReadData() +} + +/** Represents a failure that can occur during a read operation. */ +sealed class ReadFailure { + /** + * Represents a failure related to an event path. + * + * @param path The event path information associated with the failure. + * @param error The exception that describes the failure. + */ + class Event(val path: EventPath, val error: Exception) : ReadFailure() + + /** + * Represents a failure related to an attribute path. + * + * @param path The attribute path information associated with the failure. + * @param error The exception that describes the failure. + */ + class Attribute(val path: AttributePath, val error: Exception) : ReadFailure() +} + +/** + * Represents the response from a read operation, containing both successes and failures. + * + * @param successes A list of successfully read data elements. + * @param failures A list of failures that occurred during the read operation. + */ +class ReadResponse(val successes: List, val failures: List) + +/** + * Information about a subscribe request element. + * + * @param eventPaths A list of event path information in the read request. + * @param attributePaths A list of attribute path information in the read request. + * @param minInterval The minimum interval boundary floor in seconds. + * @param maxInterval The maximum interval boundary ceiling in seconds. + * @param keepSubscriptions Indicates whether to keep existing subscriptions. + * @param fabricFiltered Limits the data read within fabric-scoped lists to the accessing fabric. + */ +class SubscribeRequest( + val eventPaths: List, + val attributePaths: List, + val minInterval: Duration = Duration.ofSeconds(DEFAULT_SUBSCRIPTION_MIN_INTERVAL_S), + val maxInterval: Duration = Duration.ofSeconds(DEFAULT_SUBSCRIPTION_MAX_INTERVAL_S), + val keepSubscriptions: Boolean = true, + val fabricFiltered: Boolean = true +) + +/** An interface representing the possible states of a subscription. */ +sealed class SubscriptionState { + /** + * Represents an error notification in the subscription. + * + * @param terminationCause The cause of the subscription termination. + */ + class SubscriptionErrorNotification(val terminationCause: UInt) : SubscriptionState() + + /** + * Represents an update in the state of a subscribed node. + * + * @param updateState The state update received from the subscribed node. + */ + class NodeStateUpdate(val updateState: ReadResponse) : SubscriptionState() + + /** Represents the state where the subscription has been successfully established. */ + object SubscriptionEstablished : SubscriptionState() +} + +/** + * A write request representation. + * + * @param attributePath The attribute path information in the write request. + * @param tlvPayload The ByteArray representation of the TLV payload. + */ +class WriteRequest( + val attributePath: AttributePath, + val tlvPayload: ByteArray, +) + +/** + * Information about a collection of write request elements. + * + * @param requests A list of write request elements. + * @param timedRequest If set, indicates that this is a timed request with the specified duration. + */ +class WriteRequests(val requests: List, val timedRequest: Duration?) + +/** + * Information about a write attribute error. + * + * @param attributePath The attribute path field in write response. + * @param ex The IllegalStateException which encapsulated the error message. + */ +class AttributeWriteError(val attributePath: AttributePath, val ex: Exception) + +/** An interface representing the possible write responses. */ +sealed interface WriteResponse { + object Success : WriteResponse + + class PartialWriteFailure(val failures: List) : WriteResponse +} + +/** + * Information about a invoke request element. + * + * @param commandPath Invoked command's path information. + * @param tlvPayload The ByteArray representation of the TLV payload. + * @param timedRequest If set, indicates that this is a timed request with the specified duration. + */ +class InvokeRequest( + val commandPath: CommandPath, + val tlvPayload: ByteArray, + val timedRequest: Duration? +) + +/** + * InvokeResponse will be received when a invoke response has been successful received and + * processed. + * + * @param payload An invoke response that could contain tlv data or empty. + */ +class InvokeResponse(val payload: ByteArray) diff --git a/src/controller/java/src/matter/controller/OperationalKeyConfig.kt b/src/controller/java/src/matter/controller/OperationalKeyConfig.kt new file mode 100644 index 00000000000000..c8e4404906e527 --- /dev/null +++ b/src/controller/java/src/matter/controller/OperationalKeyConfig.kt @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2023 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. + * + */ +package matter.controller + +import chip.devicecontroller.KeypairDelegate + +/** + * CertificateData Configuration data for X.509 certificates. + * + * @property trustedRootCertificate The trusted root X.509 certificate in DER-encoded form. + * @property intermediateCertificate The optional intermediate X.509 certificate in DER-encoded + * form. + * @property operationalCertificate The node operational X.509 certificate in DER-encoded form. + */ +class CertificateData( + val trustedRootCertificate: ByteArray, + val intermediateCertificate: ByteArray?, + val operationalCertificate: ByteArray +) + +/** + * Configuration for use with CASE (Chip Authentication Session Establishment) session + * establishment. + * + * @property keypairDelegate A delegate for signing operations. + * @property certificateData Configuration data for X.509 certificates. + * @property ipk The Identity Protection Key. + * @property fabricId The fabric ID to which these operational credentials are associated. + * @property nodeId The Admin Node ID to which these operational credentials are associated. + */ +class OperationalKeyConfig( + val keypairDelegate: KeypairDelegate, + val certificateData: CertificateData, + val ipk: ByteArray, + val fabricId: Long, + val nodeId: Long +) diff --git a/src/controller/java/src/matter/controller/model/Paths.kt b/src/controller/java/src/matter/controller/model/Paths.kt new file mode 100644 index 00000000000000..76e26db62f0e1e --- /dev/null +++ b/src/controller/java/src/matter/controller/model/Paths.kt @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023 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. + * + */ +package matter.controller.model + +/** + * Represents a full path for reading an attribute from a node. + * + * @param endpointId The UShort representing the endpoint to read from. + * @param clusterId The UInt representing the cluster on the endpoint to read from. + * @param attributeId The UInt representing the attribute(s) on the cluster to read. + */ +data class AttributePath(val endpointId: UShort, val clusterId: UInt, val attributeId: UInt) { + override fun toString(): String = "$endpointId/$clusterId/$attributeId" +} + +/** + * Represents a full path to an event emitted from a node. + * + * @param endpointId The UShort representing the endpoint to read from. + * @param clusterId The UInt representing the cluster on the endpoint to read from. + * @param eventId The UInt representing the event(s) from the cluster. + */ +data class EventPath( + val endpointId: UShort, + val clusterId: UInt, + val eventId: UInt, +) { + override fun toString(): String = "$endpointId/$clusterId/$eventId" +} + +/** + * Represents a full path to a command sent to a node. + * + * @param endpointId The UShort representing the endpoint to read from. + * @param clusterId The UInt representing the cluster on the endpoint to read from. + * @param commandId The UInt representing the command(s) from the cluster. + */ +data class CommandPath( + val endpointId: UShort, + val clusterId: UInt, + val commandId: UInt, +) { + override fun toString(): String = "$endpointId/$clusterId/$commandId" +} diff --git a/src/controller/java/src/matter/controller/model/States.kt b/src/controller/java/src/matter/controller/model/States.kt new file mode 100644 index 00000000000000..39899e7ce735f8 --- /dev/null +++ b/src/controller/java/src/matter/controller/model/States.kt @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2023 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. + * + */ +package matter.controller.model + +/** + * Represents information about a node, including data on all available endpoints. + * + * @param endpoints A mapping of endpoint IDs with the associated cluster data. + */ +data class NodeState(val endpoints: Map) + +/** + * Represents information about an endpoint and its cluster data. + * + * @param id The endpoint ID. + * @param clusters A mapping of cluster IDs to the cluster data. + */ +data class EndpointState(val id: Int, val clusters: Map) + +/** + * Represents information about a cluster. + * + * @param id The cluster ID. + * @param attributes A mapping of attribute IDs in this cluster with their respective values. + * @param events A mapping of event IDs to lists of events that occurred on the node under this + * cluster. + */ +data class ClusterState( + val id: Long, + val attributes: Map, + val events: Map> +) + +/** + * Represents information about an attribute. + * + * @param id The attribute ID. + * @param tlvValue The raw TLV-encoded attribute value. + * @param jsonValue A JSON string representing the raw attribute value. + */ +data class AttributeState(val id: Long, val tlvValue: ByteArray, val jsonValue: String) + +/** + * Represents information about an event. + * + * @param eventId The event ID. + * @param eventNumber The event number value that is scoped to the node. + * @param priorityLevel The priority level describing the usage semantics of the event. + * @param timestampType Indicates POSIX Time or SYSTEM Time, in milliseconds. + * @param timestampValue Represents an offset, in milliseconds since the UNIX epoch or boot. + * @param tlvValue The raw TLV-encoded event value. + */ +data class EventState( + val eventId: Long, + val eventNumber: Long, + val priorityLevel: Int, + val timestampType: Int, + val timestampValue: Long, + val tlvValue: ByteArray +) From 2d07e2182a49e09fc243c13cb411ff0867353d51 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Fri, 6 Oct 2023 11:36:13 +0200 Subject: [PATCH 14/21] [Tizen] Make sure that all used defines are defined (#29607) * Remove unused defines * Do not leave undefined defines * Add missing include * Remove Tizen from exception --- build/config/compiler/BUILD.gn | 3 +-- examples/platform/tizen/OptionsProxy.cpp | 1 + src/platform/Beken/CHIPDevicePlatformConfig.h | 1 - src/platform/Tizen/CHIPDevicePlatformConfig.h | 7 +++++-- src/platform/Tizen/NetworkCommissioningDriver.h | 2 ++ src/platform/mt793x/CHIPDevicePlatformConfig.h | 2 -- src/platform/nxp/mw320/CHIPDevicePlatformConfig.h | 5 ----- 7 files changed, 9 insertions(+), 12 deletions(-) diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 9f34a730563d4a..4d729d76f6e07c 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn @@ -258,8 +258,7 @@ config("strict_warnings") { # to be more fine-grained than current_os, but it's not clear that # we can access that here. if (current_os != "android" && current_os != "freertos" && - current_os != "linux" && current_os != "mbed" && current_os != "tizen" && - current_os != "zephyr" && + current_os != "linux" && current_os != "mbed" && current_os != "zephyr" && # cmsis-rtos is OpenIOT current_os != "cmsis-rtos" && # cyw30739 is one of the Infineon builds diff --git a/examples/platform/tizen/OptionsProxy.cpp b/examples/platform/tizen/OptionsProxy.cpp index 158d0343f2b066..f970887ba140b1 100644 --- a/examples/platform/tizen/OptionsProxy.cpp +++ b/examples/platform/tizen/OptionsProxy.cpp @@ -22,6 +22,7 @@ #include +#include #include namespace { diff --git a/src/platform/Beken/CHIPDevicePlatformConfig.h b/src/platform/Beken/CHIPDevicePlatformConfig.h index 78050497555796..0b577345fb141c 100755 --- a/src/platform/Beken/CHIPDevicePlatformConfig.h +++ b/src/platform/Beken/CHIPDevicePlatformConfig.h @@ -67,4 +67,3 @@ #define CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY 2 #define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 -#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DISCOVERY 1 diff --git a/src/platform/Tizen/CHIPDevicePlatformConfig.h b/src/platform/Tizen/CHIPDevicePlatformConfig.h index cf54ede61d5909..110f383e16f6d1 100644 --- a/src/platform/Tizen/CHIPDevicePlatformConfig.h +++ b/src/platform/Tizen/CHIPDevicePlatformConfig.h @@ -36,11 +36,14 @@ #if CHIP_ENABLE_OPENTHREAD #define CHIP_DEVICE_CONFIG_ENABLE_THREAD 1 -#define CHIP_DEVICE_CONFIG_ENABLE_DNSSD 1 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_DNS_CLIENT 1 #define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 -#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DISCOVERY 1 +#else +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_DNS_CLIENT 0 +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 0 #endif #ifndef CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/Tizen/NetworkCommissioningDriver.h b/src/platform/Tizen/NetworkCommissioningDriver.h index 6654cbd0dc7930..cdd0ceecd2abd2 100644 --- a/src/platform/Tizen/NetworkCommissioningDriver.h +++ b/src/platform/Tizen/NetworkCommissioningDriver.h @@ -22,6 +22,8 @@ #include +#include "CHIPDevicePlatformConfig.h" + namespace chip { namespace DeviceLayer { namespace NetworkCommissioning { diff --git a/src/platform/mt793x/CHIPDevicePlatformConfig.h b/src/platform/mt793x/CHIPDevicePlatformConfig.h index 9e082811317902..2b5a03207cec3f 100644 --- a/src/platform/mt793x/CHIPDevicePlatformConfig.h +++ b/src/platform/mt793x/CHIPDevicePlatformConfig.h @@ -39,11 +39,9 @@ #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_DNS_CLIENT 1 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_COMMISSIONABLE_DISCOVERY 1 -#define CHIP_DEVICE_CONFIG_ENABLE_DNSSD 1 #endif /* CHIP_ENABLE_OPENTHREAD */ #define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 -#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DISCOVERY 1 #ifndef CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 diff --git a/src/platform/nxp/mw320/CHIPDevicePlatformConfig.h b/src/platform/nxp/mw320/CHIPDevicePlatformConfig.h index 678695e9b304c6..8806abb7d61db0 100644 --- a/src/platform/nxp/mw320/CHIPDevicePlatformConfig.h +++ b/src/platform/nxp/mw320/CHIPDevicePlatformConfig.h @@ -59,8 +59,3 @@ #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_TELEMETRY 0 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY 0 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY_FULL 0 - -// mdns/mdns_sd ++ -// #define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DISCOVERY 1 -#define CHIP_DEVICE_CONFIG_ENABLE_DNSSD 1 -// mdns/dns_sd -- From 22a54851748b3c3b205d7ba1b2e4634e5510cfdc Mon Sep 17 00:00:00 2001 From: Alex Tsitsiura Date: Fri, 6 Oct 2023 16:28:32 +0300 Subject: [PATCH 15/21] [Telink] Add air quality sensor app (#29579) * [Telink] add draft air quality app * [Telink] add air-quality example * [Telink] Clear code * [Telink] add air-quality example to github-CI * [Telink] Adopt to latest master chnages * [Telink] update AppTask of air-quality-sensor-app * [Telink] use new APIs * Restyled by whitespace * Restyled by autopep8 * [Telink] Remove read example due to spelling errors * [Telink] fix spelling errors * [Telink] Fix typo --------- Co-authored-by: UR6LAL Co-authored-by: Serhii Salamakha Co-authored-by: Restyled.io --- .github/workflows/examples-telink.yaml | 32 ++-- .vscode/tasks.json | 1 + .../air-quality-sensor-app/telink/.gitignore | 1 + .../telink/CMakeLists.txt | 86 +++++++++ .../air-quality-sensor-app/telink/Kconfig | 19 ++ .../air-quality-sensor-app/telink/README.md | 172 ++++++++++++++++++ .../telink/include/AppConfig.h | 28 +++ .../telink/include/AppTask.h | 42 +++++ .../telink/include/CHIPProjectConfig.h | 32 ++++ .../air-quality-sensor-app/telink/prj.conf | 57 ++++++ .../telink/src/AppTask.cpp | 66 +++++++ .../telink/src/ZclCallbacks.cpp | 59 ++++++ .../telink/third_party/connectedhomeip | 1 + .../telink/factory_data.overlay | 22 +++ scripts/build/build/targets.py | 1 + scripts/build/builders/telink.py | 9 +- .../build/testdata/all_targets_linux_x64.txt | 2 +- 17 files changed, 611 insertions(+), 19 deletions(-) create mode 100644 examples/air-quality-sensor-app/telink/.gitignore create mode 100644 examples/air-quality-sensor-app/telink/CMakeLists.txt create mode 100644 examples/air-quality-sensor-app/telink/Kconfig create mode 100644 examples/air-quality-sensor-app/telink/README.md create mode 100644 examples/air-quality-sensor-app/telink/include/AppConfig.h create mode 100644 examples/air-quality-sensor-app/telink/include/AppTask.h create mode 100644 examples/air-quality-sensor-app/telink/include/CHIPProjectConfig.h create mode 100644 examples/air-quality-sensor-app/telink/prj.conf create mode 100644 examples/air-quality-sensor-app/telink/src/AppTask.cpp create mode 100644 examples/air-quality-sensor-app/telink/src/ZclCallbacks.cpp create mode 120000 examples/air-quality-sensor-app/telink/third_party/connectedhomeip create mode 100644 examples/light-switch-app/telink/factory_data.overlay diff --git a/.github/workflows/examples-telink.yaml b/.github/workflows/examples-telink.yaml index 7951fe5ac46d1e..34afad3e0657e0 100644 --- a/.github/workflows/examples-telink.yaml +++ b/.github/workflows/examples-telink.yaml @@ -54,6 +54,18 @@ jobs: with: gh-context: ${{ toJson(github) }} + - name: Build example Telink (B92) Air Quality Sensor App + run: | + ./scripts/run_in_build_env.sh \ + "./scripts/build/build_examples.py --target 'telink-tlsr9528a-air-quality-sensor' build" + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ + telink tlsr9528a air-quality-sensor-app \ + out/telink-tlsr9528a-air-quality-sensor/zephyr/zephyr.elf \ + /tmp/bloat_reports/ + + - name: clean out build output + run: rm -rf ./out + - name: Build example Telink (B91) All Clusters App run: | ./scripts/run_in_build_env.sh \ @@ -124,25 +136,13 @@ jobs: - name: clean out build output (keep tools) run: rm -rf ./out/telink* - - name: Build example Telink (B92) Lighting App with RPC, Shell and Factory Data - run: | - ./scripts/run_in_build_env.sh \ - "./scripts/build/build_examples.py --target 'telink-tlsr9528a-light-rpc-shell-factory-data' build" - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - telink tlsr9528a lighting-app-rpc-shell-factory-data \ - out/telink-tlsr9528a-light-rpc-shell-factory-data/zephyr/zephyr.elf \ - /tmp/bloat_reports/ - - - name: clean out build output - run: rm -rf ./out - - - name: Build example Telink (B91) Light Switch App + - name: Build example Telink (B92) Light Switch App with RPC, Shell and Factory Data run: | ./scripts/run_in_build_env.sh \ - "./scripts/build/build_examples.py --target 'telink-tlsr9518adk80d-light-switch' build" + "./scripts/build/build_examples.py --target 'telink-tlsr9528a-light-switch-rpc-shell-factory-data' build" .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - telink tlsr9518adk80d light-switch-app \ - out/telink-tlsr9518adk80d-light-switch/zephyr/zephyr.elf \ + telink tlsr9528a light-switch-app-rpc-shell-factory-data \ + out/telink-tlsr9528a-light-switch-rpc-shell-factory-data/zephyr/zephyr.elf \ /tmp/bloat_reports/ - name: clean out build output diff --git a/.vscode/tasks.json b/.vscode/tasks.json index c5949bde691141..6d6c19e3f2b62f 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -663,6 +663,7 @@ "openiotsdk-lock", "openiotsdk-shell", "qpg-qpg6100-lock", + "telink-tlsr9518adk80d-air-quality-sensor", "telink-tlsr9518adk80d-all-clusters", "telink-tlsr9518adk80d-all-clusters-minimal", "telink-tlsr9518adk80d-bridge", diff --git a/examples/air-quality-sensor-app/telink/.gitignore b/examples/air-quality-sensor-app/telink/.gitignore new file mode 100644 index 00000000000000..84c048a73cc2e5 --- /dev/null +++ b/examples/air-quality-sensor-app/telink/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/examples/air-quality-sensor-app/telink/CMakeLists.txt b/examples/air-quality-sensor-app/telink/CMakeLists.txt new file mode 100644 index 00000000000000..9900d9bb4b5403 --- /dev/null +++ b/examples/air-quality-sensor-app/telink/CMakeLists.txt @@ -0,0 +1,86 @@ +# +# Copyright (c) 2023 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. +# +cmake_minimum_required(VERSION 3.13.1) + +get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/third_party/connectedhomeip REALPATH) +get_filename_component(TELINK_COMMON ${CHIP_ROOT}/examples/platform/telink REALPATH) +get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH) + +if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/boards/${BOARD}.overlay") + set(LOCAL_DTC_OVERLAY_FILE "${CMAKE_CURRENT_SOURCE_DIR}/boards/${BOARD}.overlay") +else() + unset(LOCAL_DTC_OVERLAY_FILE) +endif() + +if(EXISTS "${CHIP_ROOT}/src/platform/telink/${BOARD}.overlay") + set(GLOBAL_DTC_OVERLAY_FILE "${CHIP_ROOT}/src/platform/telink/${BOARD}.overlay") +else() + unset(GLOBAL_DTC_OVERLAY_FILE) +endif() + +if(DTC_OVERLAY_FILE) + set(DTC_OVERLAY_FILE + "${DTC_OVERLAY_FILE} ${GLOBAL_DTC_OVERLAY_FILE} ${LOCAL_DTC_OVERLAY_FILE}" + CACHE STRING "" FORCE + ) +else() + set(DTC_OVERLAY_FILE ${GLOBAL_DTC_OVERLAY_FILE} ${LOCAL_DTC_OVERLAY_FILE}) +endif() + +set(CONF_FILE prj.conf) + +# Load NCS/Zephyr build system +list(APPEND ZEPHYR_EXTRA_MODULES ${CHIP_ROOT}/config/telink/chip-module) +find_package(Zephyr HINTS $ENV{ZEPHYR_BASE}) + +project(chip-telink-air-quality-sensor-example) + +include(${CHIP_ROOT}/config/telink/app/enable-gnu-std.cmake) +include(${CHIP_ROOT}/src/app/chip_data_model.cmake) + +target_compile_options(app PRIVATE -fpermissive) + +target_include_directories(app PRIVATE + include + ${GEN_DIR}/app-common + ${GEN_DIR}/air-quality-sensor-app + ${TELINK_COMMON}/common/include + ${TELINK_COMMON}/util/include + ${CHIP_ROOT}/examples/air-quality-sensor-app/air-quality-sensor-common/include) + +add_definitions( + "-DCHIP_ADDRESS_RESOLVE_IMPL_INCLUDE_HEADER=" +) + +target_sources(app PRIVATE + src/AppTask.cpp + src/ZclCallbacks.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp + ${TELINK_COMMON}/util/src/LEDWidget.cpp + ${TELINK_COMMON}/util/src/ButtonManager.cpp + ${TELINK_COMMON}/util/src/ThreadUtil.cpp + ${TELINK_COMMON}/util/src/PWMDevice.cpp + ${CHIP_ROOT}/examples/air-quality-sensor-app/air-quality-sensor-common/src/air-quality-sensor-manager.cpp) + +chip_configure_data_model(app + INCLUDE_SERVER + ZAP_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../air-quality-sensor-common/air-quality-sensor-app.zap +) + +if(CONFIG_CHIP_OTA_REQUESTOR) + target_sources(app PRIVATE ${TELINK_COMMON}/util/src/OTAUtil.cpp) +endif() diff --git a/examples/air-quality-sensor-app/telink/Kconfig b/examples/air-quality-sensor-app/telink/Kconfig new file mode 100644 index 00000000000000..e7d4beefea20cc --- /dev/null +++ b/examples/air-quality-sensor-app/telink/Kconfig @@ -0,0 +1,19 @@ +# +# Copyright (c) 2023 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. +# +mainmenu "Matter Telink Air Quality Sensor Example Application" + +rsource "../../../config/telink/chip-module/Kconfig.defaults" +source "Kconfig.zephyr" diff --git a/examples/air-quality-sensor-app/telink/README.md b/examples/air-quality-sensor-app/telink/README.md new file mode 100644 index 00000000000000..371a26cc00639e --- /dev/null +++ b/examples/air-quality-sensor-app/telink/README.md @@ -0,0 +1,172 @@ +# Matter Telink Air Quality Sensor Example Application + +You can use this example as a reference for creating your own application. + +![Telink B91 EVK](http://wiki.telink-semi.cn/wiki/assets/Hardware/B91_Generic_Starter_Kit_Hardware_Guide/connection_chart.png) + +## Build and flash + +1. Run the Docker container: + + ```bash + $ docker run -it --rm -v $PWD:/host -w /host ghcr.io/project-chip/chip-build-telink:$(wget -q -O - https://raw.githubusercontent.com/project-chip/connectedhomeip/master/.github/workflows/examples-telink.yaml 2> /dev/null | grep chip-build-telink | awk -F: '{print $NF}') + ``` + + Compatible docker image version can be found in next file: + + ```bash + $ .github/workflows/examples-telink.yaml + ``` + +2. Activate the build environment: + + ```bash + $ source ./scripts/activate.sh + ``` + +3. In the example dir run (replace __ with your board name, for + example, `tlsr9518adk80d` or `tlsr9528a`): + + ```bash + $ west build -b + ``` + +4. Flash binary: + + ``` + $ west flash --erase + ``` + +## Usage + +### UART + +To get output from device, connect UART to following pins: + +| Name | Pin | +| :--: | :---------------------------- | +| RX | PB3 (pin 17 of J34 connector) | +| TX | PB2 (pin 16 of J34 connector) | +| GND | GND | + +### Buttons + +The following buttons are available on **tlsr9518adk80d** board: + +| Name | Function | Description | +| :------- | :--------------------- | :----------------------------------------------------------------------------------------------------- | +| Button 1 | Factory reset | Perform factory reset to forget currently commissioned Thread network and back to uncommissioned state | +| Button 2 | `AirQuality` control | Manually triggers the `AirQuality` state | +| Button 3 | Thread start | Commission thread with static credentials and enables the Thread on device | +| Button 4 | Open commission window | The button is opening commissioning window to perform commissioning over BLE | + +### LEDs + +#### Indicate current state of Thread network + +**Red** LED indicates current state of Thread network. It is able to be in +following states: + +| State | Description | +| :-------------------------- | :--------------------------------------------------------------------------- | +| Blinks with short pulses | Device is not commissioned to Thread, Thread is disabled | +| Blinks with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | +| Blinks with wide pulses | Device commissioned and joined to thread network as CHILD | + +#### Indicate identify of device + +**Green** LED used to identify the device. The LED starts blinking when the +Identify command of the Identify cluster is received. The command's argument can +be used to specify the the effect. It is able to be in following effects: + +| Effect | Description | +| :------------------------------ | :--------------------------------------------------------------------------- | +| Blinks (200 ms on/200 ms off) | Blink (`Clusters::Identify::EffectIdentifierEnum::kBlink`) | +| Breathe (during 1000 ms) | Breathe (`Clusters::Identify::EffectIdentifierEnum::kBreathe`) | +| Blinks (50 ms on/950 ms off) | Okay (`Clusters::Identify::EffectIdentifierEnum::kOkay`) | +| Blinks (1000 ms on/1000 ms off) | Channel Change ( `Clusters::Identify::EffectIdentifierEnum::kChannelChange`) | +| Blinks (950 ms on/50 ms off) | Finish ( `Clusters::Identify::EffectIdentifierEnum::kFinishEffect`) | +| LED off | Stop (`Clusters::Identify::EffectIdentifierEnum::kStopEffect`) | + +### CHIP tool commands + +1. Build + [chip-tool cli](https://github.com/project-chip/connectedhomeip/blob/master/examples/chip-tool/README.md) + +2. Pair with device + + ``` + ${CHIP_TOOL_DIR}/chip-tool pairing ble-thread ${NODE_ID} hex:${DATASET} ${PIN_CODE} ${DISCRIMINATOR} + ``` + + Example: + + ``` + ./chip-tool pairing ble-thread 1234 hex:0e080000000000010000000300000f35060004001fffe0020811111111222222220708fd61f77bd3df233e051000112233445566778899aabbccddeeff030e4f70656e54687265616444656d6f010212340410445f2b5ca6f2a93a55ce570a70efeecb0c0402a0fff8 20202021 3840 + ``` + +### OTA with Linux OTA Provider + +OTA feature enabled by default only for ota-requestor-app example. To enable OTA +feature for another Telink example: + +- set CONFIG_CHIP_OTA_REQUESTOR=y in corresponding "prj.conf" configuration + file. + +After build application with enabled OTA feature, use next binary files: + +- zephyr.bin - main binary to flash PCB (Use 2MB PCB). +- zephyr-ota.bin - binary for OTA Provider + +All binaries has the same SW version. To test OTA “zephyr-ota.bin” should have +higher SW version than base SW. Set CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=2 in +corresponding “prj.conf” configuration file. + +Usage of OTA: + +- Build the [Linux OTA Provider](../../ota-provider-app/linux) + + ``` + ./scripts/examples/gn_build_example.sh examples/ota-provider-app/linux out/ota-provider-app chip_config_network_layer_ble=false + ``` + +- Run the Linux OTA Provider with OTA image. + + ``` + ./chip-ota-provider-app -f zephyr-ota.bin + ``` + +- Provision the Linux OTA Provider using chip-tool + + ``` + ./chip-tool pairing onnetwork ${OTA_PROVIDER_NODE_ID} 20202021 + ``` + + here: + + - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider + +- Configure the ACL of the ota-provider-app to allow access + + ``` + ./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null}, {"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": null, "targets": null}]' ${OTA_PROVIDER_NODE_ID} 0 + ``` + + here: + + - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider + +- Use the chip-tool to announce the ota-provider-app to start the OTA process + + ``` + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ``` + + here: + + - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider + - \${DEVICE_NODE_ID} is the node id of paired device + +Once the transfer is complete, OTA requestor sends ApplyUpdateRequest command to +OTA provider for applying the image. Device will restart on successful +application of OTA image. diff --git a/examples/air-quality-sensor-app/telink/include/AppConfig.h b/examples/air-quality-sensor-app/telink/include/AppConfig.h new file mode 100644 index 00000000000000..ec5c54343cf852 --- /dev/null +++ b/examples/air-quality-sensor-app/telink/include/AppConfig.h @@ -0,0 +1,28 @@ +/* + * + * Copyright (c) 2023 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 + +// ---- Air Quality Example App Config ---- + +#define APP_USE_EXAMPLE_START_BUTTON 1 +#define APP_USE_BLE_START_BUTTON 0 +#define APP_USE_THREAD_START_BUTTON 0 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 0 +#define APP_USE_IDENTIFY_PWM 1 diff --git a/examples/air-quality-sensor-app/telink/include/AppTask.h b/examples/air-quality-sensor-app/telink/include/AppTask.h new file mode 100644 index 00000000000000..a1b55a9b83108f --- /dev/null +++ b/examples/air-quality-sensor-app/telink/include/AppTask.h @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2023 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 "AppTaskCommon.h" + +class AppTask : public AppTaskCommon +{ +public: + void UpdateClusterState(void); + +private: + friend AppTask & GetAppTask(void); + friend class AppTaskCommon; + + CHIP_ERROR Init(void); + + static void AirQualityActionEventHandler(AppEvent * aEvent); + + static AppTask sAppTask; +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/air-quality-sensor-app/telink/include/CHIPProjectConfig.h b/examples/air-quality-sensor-app/telink/include/CHIPProjectConfig.h new file mode 100644 index 00000000000000..8465c19cdd0537 --- /dev/null +++ b/examples/air-quality-sensor-app/telink/include/CHIPProjectConfig.h @@ -0,0 +1,32 @@ +/* + * + * Copyright (c) 2023 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 + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +// Use a default pairing code if one hasn't been provisioned in flash. +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 diff --git a/examples/air-quality-sensor-app/telink/prj.conf b/examples/air-quality-sensor-app/telink/prj.conf new file mode 100644 index 00000000000000..703e78efb7ed4a --- /dev/null +++ b/examples/air-quality-sensor-app/telink/prj.conf @@ -0,0 +1,57 @@ +# +# Copyright (c) 2023 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. +# + +# This sample uses sample-defaults.conf to set options common for all +# samples. This file should contain only options specific for this sample +# or overrides of default values. + +# Enable CHIP +CONFIG_CHIP=y +CONFIG_STD_CPP17=y + +# enable GPIO +CONFIG_GPIO=y + +# enable PWM +CONFIG_PWM=y + +# CHIP configuration +CONFIG_CHIP_PROJECT_CONFIG="include/CHIPProjectConfig.h" +CONFIG_CHIP_OPENTHREAD_CONFIG="../../platform/telink/project_include/OpenThreadConfig.h" + +# 32774 == 0x8006 (example air-quality-sensor-app) +CONFIG_CHIP_DEVICE_PRODUCT_ID=32774 + +# Bluetooth Low Energy configuration +CONFIG_BT_DEVICE_NAME="TelinkSensor" + +# Disable Matter OTA DFU +CONFIG_CHIP_OTA_REQUESTOR=n +CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=1 + +# Enable CHIP pairing automatically on application start. +CONFIG_CHIP_ENABLE_PAIRING_AUTOSTART=y + +# Disable CHIP shell support +CONFIG_CHIP_LIB_SHELL=n + +# Disable factory data support +CONFIG_CHIP_FACTORY_DATA=n +CONFIG_CHIP_FACTORY_DATA_BUILD=n +CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n + +# Enable Power Management +CONFIG_PM=y diff --git a/examples/air-quality-sensor-app/telink/src/AppTask.cpp b/examples/air-quality-sensor-app/telink/src/AppTask.cpp new file mode 100644 index 00000000000000..94988ea8bbe5a0 --- /dev/null +++ b/examples/air-quality-sensor-app/telink/src/AppTask.cpp @@ -0,0 +1,66 @@ +/* + * + * Copyright (c) 2023 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 "AppTask.h" +#include + +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); + +using namespace ::chip::app::Clusters; +using namespace ::chip::app::Clusters::AirQuality; + +AppTask AppTask::sAppTask; + +constexpr EndpointId kAirQualityEndpoint = 1; + +CHIP_ERROR AppTask::Init(void) +{ +#if APP_USE_EXAMPLE_START_BUTTON + SetExampleButtonCallbacks(AirQualityActionEventHandler); +#endif + InitCommonParts(); + + AirQualitySensorManager::InitInstance(kAirQualityEndpoint); + + return CHIP_NO_ERROR; +} + +void AppTask::UpdateClusterState(void) +{ + AirQualitySensorManager * mInstance = AirQualitySensorManager::GetInstance(); + + // Update AirQuality value + mInstance->OnAirQualityChangeHandler(AirQualityEnum::kModerate); + + // Update Carbon Dioxide + mInstance->OnCarbonDioxideMeasurementChangeHandler(400); + + // Update Temperature value + mInstance->OnTemperatureMeasurementChangeHandler(18); + + // Update Humidity value + mInstance->OnHumidityMeasurementChangeHandler(60); +} + +void AppTask::AirQualityActionEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type == AppEvent::kEventType_Button) + { + sAppTask.UpdateClusterState(); + } +} diff --git a/examples/air-quality-sensor-app/telink/src/ZclCallbacks.cpp b/examples/air-quality-sensor-app/telink/src/ZclCallbacks.cpp new file mode 100644 index 00000000000000..f9959be7525a93 --- /dev/null +++ b/examples/air-quality-sensor-app/telink/src/ZclCallbacks.cpp @@ -0,0 +1,59 @@ +/* + * + * Copyright (c) 2023 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 "AppTask.h" + +#include +#include +#include +#include + +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); + +using namespace chip; +using namespace chip::app::Clusters; + +void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size, + uint8_t * value) +{ + ClusterId clusterId = attributePath.mClusterId; + AttributeId attributeId = attributePath.mAttributeId; + ChipLogProgress(Zcl, "Cluster callback: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + + if (clusterId == AirQuality::Id && attributeId == AirQuality::Attributes::AirQuality::Id) + { + static_assert(sizeof(AirQuality::AirQualityEnum) == 1, "Wrong size"); + AirQuality::AirQualityEnum AirQuality = *(reinterpret_cast(value)); + ChipLogProgress(Zcl, "AirQuality cluster: " ChipLogFormatMEI " state %d", ChipLogValueMEI(clusterId), + to_underlying(AirQuality)); + } +} + +/** @brief AirQuality Cluster Init + * + * This function is called when a specific cluster is initialized. It gives the + * application an opportunity to take care of cluster initialization procedures. + * It is called exactly once for each endpoint where cluster is present. + * + * @param endpoint Ver.: always + * + */ +void emberAfAirQualityClusterInitCallback(EndpointId endpoint) +{ + // TODO: implement any additional Cluster Server init actions +} diff --git a/examples/air-quality-sensor-app/telink/third_party/connectedhomeip b/examples/air-quality-sensor-app/telink/third_party/connectedhomeip new file mode 120000 index 00000000000000..c866b86874994d --- /dev/null +++ b/examples/air-quality-sensor-app/telink/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../.. \ No newline at end of file diff --git a/examples/light-switch-app/telink/factory_data.overlay b/examples/light-switch-app/telink/factory_data.overlay new file mode 100644 index 00000000000000..4f7289d9bd15ca --- /dev/null +++ b/examples/light-switch-app/telink/factory_data.overlay @@ -0,0 +1,22 @@ +# +# Copyright (c) 2023 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. +# + +# This file should be used as a configuration overlay to enable Factory Data. + +# Enable factory data support. +CONFIG_CHIP_FACTORY_DATA=y +CONFIG_CHIP_FACTORY_DATA_BUILD=y +CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=y diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index 758c10d80add19..c1b0fad61be8ff 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -695,6 +695,7 @@ def BuildTelinkTarget(): ]) target.AppendFixedTargets([ + TargetPart('air-quality-sensor', app=TelinkApp.AIR_QUALITY_SENSOR), TargetPart('all-clusters', app=TelinkApp.ALL_CLUSTERS), TargetPart('all-clusters-minimal', app=TelinkApp.ALL_CLUSTERS_MINIMAL), TargetPart('bridge', app=TelinkApp.BRIDGE), diff --git a/scripts/build/builders/telink.py b/scripts/build/builders/telink.py index 5e62a5152bc205..9487a17a36dbb0 100644 --- a/scripts/build/builders/telink.py +++ b/scripts/build/builders/telink.py @@ -21,6 +21,7 @@ class TelinkApp(Enum): + AIR_QUALITY_SENSOR = auto() ALL_CLUSTERS = auto() ALL_CLUSTERS_MINIMAL = auto() BRIDGE = auto() @@ -39,7 +40,9 @@ class TelinkApp(Enum): WINDOW_COVERING = auto() def ExampleName(self): - if self == TelinkApp.ALL_CLUSTERS: + if self == TelinkApp.AIR_QUALITY_SENSOR: + return 'air-quality-sensor-app' + elif self == TelinkApp.ALL_CLUSTERS: return 'all-clusters-app' elif self == TelinkApp.ALL_CLUSTERS_MINIMAL: return 'all-clusters-minimal-app' @@ -75,7 +78,9 @@ def ExampleName(self): raise Exception('Unknown app type: %r' % self) def AppNamePrefix(self): - if self == TelinkApp.ALL_CLUSTERS: + if self == TelinkApp.AIR_QUALITY_SENSOR: + return 'chip-telink-air-quality-sensor-example' + elif self == TelinkApp.ALL_CLUSTERS: return 'chip-telink-all-clusters-example' elif self == TelinkApp.ALL_CLUSTERS_MINIMAL: return 'chip-telink-all-clusters-minimal-example' diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index 57604bc8e3aa08..dd29ccecea337c 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -22,5 +22,5 @@ nrf-native-posix-64-tests qpg-qpg6105-{lock,light,shell,persistent-storage} stm32-stm32wb5mm-dk-light tizen-arm-{all-clusters,all-clusters-minimal,chip-tool,light,tests}[-no-ble][-no-thread][-no-wifi][-asan][-ubsan] -telink-{tlsr9518adk80d,tlsr9528a}-{all-clusters,all-clusters-minimal,bridge,contact-sensor,light,light-switch,lock,ota-requestor,pump,pump-controller,resource-monitoring,shell,smoke-co-alarm,temperature-measurement,thermostat,window-covering}[-shell][-rpc][-factory-data] +telink-{tlsr9518adk80d,tlsr9528a}-{air-quality-sensor,all-clusters,all-clusters-minimal,bridge,contact-sensor,light,light-switch,lock,ota-requestor,pump,pump-controller,resource-monitoring,shell,smoke-co-alarm,temperature-measurement,thermostat,window-covering}[-shell][-rpc][-factory-data] openiotsdk-{shell,lock}[-mbedtls][-psa] From cff70e18b0d7149f968814c9c570e5fd161d4354 Mon Sep 17 00:00:00 2001 From: Timothy Maes Date: Fri, 6 Oct 2023 16:21:51 +0200 Subject: [PATCH 16/21] fix(QPG): Enable -Wundef and fix any errors for qpg based builds (#29617) * fix(QPG): Enable -Wundef and fix any errors for qpg based builds (Addresses #29591) * Restyled by gn --------- Co-authored-by: Restyled.io --- examples/lighting-app/qpg/BUILD.gn | 5 +---- .../lighting-app/qpg/include/CHIPProjectConfig.h | 9 +++++++++ examples/lock-app/qpg/BUILD.gn | 5 +---- examples/lock-app/qpg/include/CHIPProjectConfig.h | 14 ++++++++++++++ examples/platform/qpg/app/main.cpp | 10 +++++----- .../qpg/project_include/OpenThreadConfig.h | 4 ++++ .../GenericThreadStackManagerImpl_OpenThread.hpp | 2 +- src/platform/qpg/Logging.cpp | 4 ---- third_party/qpg_sdk/qpg_sdk.gni | 5 ++++- 9 files changed, 39 insertions(+), 19 deletions(-) diff --git a/examples/lighting-app/qpg/BUILD.gn b/examples/lighting-app/qpg/BUILD.gn index 361021fc21dcdc..981e7405150cb5 100644 --- a/examples/lighting-app/qpg/BUILD.gn +++ b/examples/lighting-app/qpg/BUILD.gn @@ -44,9 +44,7 @@ qpg_sdk("sdk") { "${qpg_project_dir}/include", ] - if (chip_enable_pw_rpc) { - defines = [ "PW_RPC_ENABLED" ] - } + defines = [ "PW_RPC_ENABLED=${chip_enable_pw_rpc}" ] } qpg_executable("lighting_app") { @@ -92,7 +90,6 @@ qpg_executable("lighting_app") { if (chip_enable_pw_rpc) { defines += [ - "PW_RPC_ENABLED", "PW_RPC_ATTRIBUTE_SERVICE=1", "PW_RPC_BUTTON_SERVICE=1", "PW_RPC_DEVICE_SERVICE=1", diff --git a/examples/lighting-app/qpg/include/CHIPProjectConfig.h b/examples/lighting-app/qpg/include/CHIPProjectConfig.h index 61dc9fdebc86af..2e23b214716be1 100644 --- a/examples/lighting-app/qpg/include/CHIPProjectConfig.h +++ b/examples/lighting-app/qpg/include/CHIPProjectConfig.h @@ -113,6 +113,15 @@ #define CHIP_DEVICE_CONFIG_ENABLE_SED 0 #endif +/** + * @def CHIP_DEVICE_CONFIG_ENABLE_SSED + * + * @brief Defines if a matter device is acting as a Synchronized Sleepy End Device(SSED) + */ +#ifndef CHIP_DEVICE_CONFIG_ENABLE_SSED +#define CHIP_DEVICE_CONFIG_ENABLE_SSED 0 +#endif + /** * @def CHIP_DEVICE_CONFIG_THREAD_FTD * diff --git a/examples/lock-app/qpg/BUILD.gn b/examples/lock-app/qpg/BUILD.gn index c8edc51a72545a..1023e9f2751ce2 100644 --- a/examples/lock-app/qpg/BUILD.gn +++ b/examples/lock-app/qpg/BUILD.gn @@ -44,9 +44,7 @@ qpg_sdk("sdk") { "${qpg_project_dir}/include", ] - if (chip_enable_pw_rpc) { - defines = [ "PW_RPC_ENABLED" ] - } + defines = [ "PW_RPC_ENABLED=${chip_enable_pw_rpc}" ] } qpg_executable("lock_app") { @@ -89,7 +87,6 @@ qpg_executable("lock_app") { if (chip_enable_pw_rpc) { defines += [ - "PW_RPC_ENABLED", "PW_RPC_ATTRIBUTE_SERVICE=1", "PW_RPC_BUTTON_SERVICE=1", "PW_RPC_DEVICE_SERVICE=1", diff --git a/examples/lock-app/qpg/include/CHIPProjectConfig.h b/examples/lock-app/qpg/include/CHIPProjectConfig.h index 4989ed2f85051d..826224654239ca 100644 --- a/examples/lock-app/qpg/include/CHIPProjectConfig.h +++ b/examples/lock-app/qpg/include/CHIPProjectConfig.h @@ -115,6 +115,20 @@ #define CHIP_DEVICE_CONFIG_ENABLE_SED 1 #endif +/** + * @def CHIP_DEVICE_CONFIG_ENABLE_SSED + * + * @brief Defines if a matter device is acting as a Synchronized Sleepy End Device(SSED) + */ +#ifndef CHIP_DEVICE_CONFIG_ENABLE_SSED +#define CHIP_DEVICE_CONFIG_ENABLE_SSED 0 +#endif + +/** + * @def CHIP_DEVICE_CONFIG_THREAD_FTD + * + * @brief Defines if a matter device is acting as Full Thread Device (FTD) + */ #ifndef CHIP_DEVICE_CONFIG_THREAD_FTD #define CHIP_DEVICE_CONFIG_THREAD_FTD 0 #endif diff --git a/examples/platform/qpg/app/main.cpp b/examples/platform/qpg/app/main.cpp index bc3b28e230efe8..d7ba22f4adb232 100644 --- a/examples/platform/qpg/app/main.cpp +++ b/examples/platform/qpg/app/main.cpp @@ -45,11 +45,11 @@ #include #include -#if PW_RPC_ENABLED +#if defined(PW_RPC_ENABLED) && PW_RPC_ENABLED #include "Rpc.h" #endif // PW_RPC_ENABLED -#if ENABLE_CHIP_SHELL +#if defined(ENABLE_CHIP_SHELL) && ENABLE_CHIP_SHELL #include "shell_common/shell.h" #endif // ENABLE_CHIP_SHELL @@ -142,7 +142,7 @@ CHIP_ERROR CHIP_Init(void) { CHIP_ERROR ret = CHIP_NO_ERROR; -#if PW_RPC_ENABLED +#if defined(PW_RPC_ENABLED) && PW_RPC_ENABLED ret = (CHIP_ERROR) chip::rpc::Init(); if (ret != CHIP_NO_ERROR) { @@ -158,7 +158,7 @@ CHIP_ERROR CHIP_Init(void) goto exit; } -#if ENABLE_CHIP_SHELL +#if defined(ENABLE_CHIP_SHELL) && ENABLE_CHIP_SHELL ret = (CHIP_ERROR) ShellTask::Start(); if (ret != CHIP_NO_ERROR) { @@ -184,7 +184,7 @@ CHIP_ERROR CHIP_Init(void) goto exit; } -#if CONFIG_CHIP_THREAD_SSED +#if defined(CHIP_DEVICE_CONFIG_ENABLE_SSED) && CHIP_DEVICE_CONFIG_ENABLE_SSED ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SynchronizedSleepyEndDevice); qvIO_EnableSleep(true); #elif CHIP_DEVICE_CONFIG_ENABLE_SED diff --git a/examples/platform/qpg/project_include/OpenThreadConfig.h b/examples/platform/qpg/project_include/OpenThreadConfig.h index 2771401022d190..9de2b7969a70f5 100644 --- a/examples/platform/qpg/project_include/OpenThreadConfig.h +++ b/examples/platform/qpg/project_include/OpenThreadConfig.h @@ -72,6 +72,10 @@ #define OPENTHREAD_CONFIG_DHCP6_CLIENT_ENABLE 0 #define OPENTHREAD_CONFIG_DHCP6_SERVER_ENABLE 0 #define OPENTHREAD_CONFIG_TCP_ENABLE 0 +#define OPENTHREAD_CONFIG_TLS_ENABLE 0 + +#define OPENTHREAD_ENABLE_VENDOR_EXTENSION 0 +#define OPENTHREAD_EXAMPLES_SIMULATION 0 // Use the Qorvo-supplied default platform configuration for remainder // of OpenThread config options. diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp index 4e89e6938520b4..a75f791966ac41 100644 --- a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp +++ b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp @@ -1710,7 +1710,7 @@ CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::DoInit(otInstanc VerifyOrExit(otErr == OT_ERROR_NONE, err = MapOpenThreadError(otErr)); // Enable automatic assignment of Thread advertised addresses. -#if OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE +#if defined(OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE) && OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE otIp6SetSlaacEnabled(otInst, true); #endif diff --git a/src/platform/qpg/Logging.cpp b/src/platform/qpg/Logging.cpp index 37c716028f667b..8a30a63210f622 100644 --- a/src/platform/qpg/Logging.cpp +++ b/src/platform/qpg/Logging.cpp @@ -19,10 +19,6 @@ #include #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD -#ifdef PW_RPC_ENABLED -#include "PigweedLogger.h" -#endif - constexpr uint8_t kPrintfModuleLwip = 0x01; constexpr uint8_t kPrintfModuleOpenThread = 0x02; constexpr uint8_t kPrintfModuleLogging = 0x03; diff --git a/third_party/qpg_sdk/qpg_sdk.gni b/third_party/qpg_sdk/qpg_sdk.gni index a9be7323fcd34c..67b0780d8fe731 100644 --- a/third_party/qpg_sdk/qpg_sdk.gni +++ b/third_party/qpg_sdk/qpg_sdk.gni @@ -98,7 +98,10 @@ template("qpg_sdk") { defines += [ "MBEDTLS_SW_ONLY" ] } - cflags = [] + #Wundef fix - to be updated in SDK + defines += [ "GP_SCHED_NR_OF_IDLE_CALLBACKS=0" ] + + cflags = [ "-Wundef" ] # Allow warning due to mbedtls cflags += [ From a81523507af793107f832a2821f978ffc814a42a Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 6 Oct 2023 12:07:56 -0400 Subject: [PATCH 17/21] Enable -Wundef on Linux and Android. (#29610) --- build/config/compiler/BUILD.gn | 4 ++-- src/controller/java/AndroidCallbacks.cpp | 6 +++--- src/platform/BUILD.gn | 5 ++++- third_party/mbedtls/mbedtls.gni | 2 ++ 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 4d729d76f6e07c..3fa6e2a2fb793c 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn @@ -257,8 +257,8 @@ config("strict_warnings") { # we can. Ideally this would be checking chip_device_platform or so # to be more fine-grained than current_os, but it's not clear that # we can access that here. - if (current_os != "android" && current_os != "freertos" && - current_os != "linux" && current_os != "mbed" && current_os != "zephyr" && + if (current_os != "freertos" && current_os != "mbed" && + current_os != "zephyr" && # cmsis-rtos is OpenIOT current_os != "cmsis-rtos" && # cyw30739 is one of the Infineon builds diff --git a/src/controller/java/AndroidCallbacks.cpp b/src/controller/java/AndroidCallbacks.cpp index 2c4d3153400775..69e5a0b68ad304 100644 --- a/src/controller/java/AndroidCallbacks.cpp +++ b/src/controller/java/AndroidCallbacks.cpp @@ -16,7 +16,7 @@ */ #include "AndroidCallbacks.h" #include -#if USE_JAVA_TLV_ENCODE_DECODE +#ifdef USE_JAVA_TLV_ENCODE_DECODE #include #include #endif @@ -384,7 +384,7 @@ void ReportCallback::OnAttributeData(const app::ConcreteDataAttributePath & aPat readerForJavaTLV.Init(*apData); jobject value = nullptr; -#if USE_JAVA_TLV_ENCODE_DECODE +#ifdef USE_JAVA_TLV_ENCODE_DECODE TLV::TLVReader readerForJavaObject; readerForJavaObject.Init(*apData); @@ -518,7 +518,7 @@ void ReportCallback::OnEventData(const app::EventHeader & aEventHeader, TLV::TLV } jobject value = nullptr; -#if USE_JAVA_TLV_ENCODE_DECODE +#ifdef USE_JAVA_TLV_ENCODE_DECODE TLV::TLVReader readerForJavaObject; readerForJavaObject.Init(*apData); value = DecodeEventValue(aEventHeader.mPath, readerForJavaObject, &err); diff --git a/src/platform/BUILD.gn b/src/platform/BUILD.gn index c588b94fa1621b..2b3188147311e9 100644 --- a/src/platform/BUILD.gn +++ b/src/platform/BUILD.gn @@ -241,7 +241,10 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { defines += [ "CHIP_DEVICE_LAYER_TARGET=fake" ] } else if (chip_device_platform == "android") { device_layer_target_define = "ANDROID" - defines += [ "CHIP_DEVICE_LAYER_TARGET=android" ] + defines += [ + "CHIP_DEVICE_LAYER_TARGET=android", + "CHIP_DEVICE_CONFIG_ENABLE_WIFI=${chip_enable_wifi}", + ] } else if (chip_device_platform == "ameba") { device_layer_target_define = "AMEBA" defines += [ diff --git a/third_party/mbedtls/mbedtls.gni b/third_party/mbedtls/mbedtls.gni index e865e9c6584ce9..d76a260e05b567 100644 --- a/third_party/mbedtls/mbedtls.gni +++ b/third_party/mbedtls/mbedtls.gni @@ -29,6 +29,8 @@ template("mbedtls_target") { "-Wno-unused-but-set-parameter", "-Wno-format-nonliteral", # Because of mbedtls_debug_print_msg "-Wno-conversion", # Lots of -Wconversion warnings, sadly. + "-Wno-undef", # At least MBEDTLS_AESNI_HAVE_CODE is used without being + # defined. ] if (is_clang) { From c73199d5b36a90ba510d7ef4248ffb2188d12683 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 6 Oct 2023 12:12:29 -0400 Subject: [PATCH 18/21] Make length validation of group names follow the spec. (#29604) Fixes https://github.com/project-chip/connectedhomeip/issues/29576 --- .../clusters/groups-server/groups-server.cpp | 1 + src/app/tests/suites/TestGroupsCluster.yaml | 25 ++- .../zap-generated/test/Commands.h | 176 +++++++++++------- 3 files changed, 129 insertions(+), 73 deletions(-) diff --git a/src/app/clusters/groups-server/groups-server.cpp b/src/app/clusters/groups-server/groups-server.cpp index ccb4fb1d439a72..7318523c118fbe 100644 --- a/src/app/clusters/groups-server/groups-server.cpp +++ b/src/app/clusters/groups-server/groups-server.cpp @@ -76,6 +76,7 @@ static bool KeyExists(FabricIndex fabricIndex, GroupId groupId) static Status GroupAdd(FabricIndex fabricIndex, EndpointId endpointId, GroupId groupId, const CharSpan & groupName) { VerifyOrReturnError(IsValidGroupId(groupId), Status::ConstraintError); + VerifyOrReturnError(groupName.size() <= GroupDataProvider::GroupInfo::kGroupNameMax, Status::ConstraintError); GroupDataProvider * provider = GetGroupDataProvider(); VerifyOrReturnError(nullptr != provider, Status::NotFound); diff --git a/src/app/tests/suites/TestGroupsCluster.yaml b/src/app/tests/suites/TestGroupsCluster.yaml index febb82c33978bb..9b93aaeea297dc 100644 --- a/src/app/tests/suites/TestGroupsCluster.yaml +++ b/src/app/tests/suites/TestGroupsCluster.yaml @@ -65,7 +65,7 @@ tests: response: values: - name: "Status" - value: 0x7e + value: 0x7e # UNSUPPORTED_ACCESS - name: "GroupID" value: 0x0101 @@ -100,6 +100,21 @@ tests: { FabricIndex: 1, GroupId: 0x0102, GroupKeySetID: 0x01a1 }, ] + - label: "Add First Group (name too long)" + command: "AddGroup" + arguments: + values: + - name: "GroupID" + value: 0x0101 + - name: "GroupName" + value: "12345678901234567" + response: + values: + - name: "Status" + value: 0x87 # CONSTRAINT_ERROR + - name: "GroupID" + value: 0x0101 + - label: "Add First Group (new)" command: "AddGroup" arguments: @@ -107,7 +122,7 @@ tests: - name: "GroupID" value: 0x0101 - name: "GroupName" - value: "Group #1" + value: "Group #101234567" # Maximal-length name, to check that this works response: values: - name: "Status" @@ -128,7 +143,7 @@ tests: - name: "GroupID" value: 0x0101 - name: "GroupName" - value: "Group #1" + value: "Group #101234567" - label: "View Second Group (not found)" command: "ViewGroup" @@ -229,7 +244,7 @@ tests: - name: "GroupID" value: 0x0101 - name: "GroupName" - value: "Group #1" + value: "Group #101234567" - label: "View Second Group (existing)" command: "ViewGroup" @@ -328,7 +343,7 @@ tests: - name: "GroupID" value: 0x0101 - name: "GroupName" - value: "Group #1" + value: "Group #101234567" - label: "View Second Group (removed)" command: "ViewGroup" diff --git a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h index 60974f536d19d3..7548717b142ae3 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h @@ -169956,88 +169956,92 @@ class TestGroupsCluster : public TestCommandBridge { err = TestWriteGroupKeys_5(); break; case 6: - ChipLogProgress(chipTool, " ***** Test Step 6 : Add First Group (new)\n"); - err = TestAddFirstGroupNew_6(); + ChipLogProgress(chipTool, " ***** Test Step 6 : Add First Group (name too long)\n"); + err = TestAddFirstGroupNameTooLong_6(); break; case 7: - ChipLogProgress(chipTool, " ***** Test Step 7 : View First Group (new)\n"); - err = TestViewFirstGroupNew_7(); + ChipLogProgress(chipTool, " ***** Test Step 7 : Add First Group (new)\n"); + err = TestAddFirstGroupNew_7(); break; case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : View Second Group (not found)\n"); - err = TestViewSecondGroupNotFound_8(); + ChipLogProgress(chipTool, " ***** Test Step 8 : View First Group (new)\n"); + err = TestViewFirstGroupNew_8(); break; case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Get Group Membership 1 (all)\n"); - err = TestGetGroupMembership1All_9(); + ChipLogProgress(chipTool, " ***** Test Step 9 : View Second Group (not found)\n"); + err = TestViewSecondGroupNotFound_9(); break; case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Add Second Group (new)\n"); - err = TestAddSecondGroupNew_10(); + ChipLogProgress(chipTool, " ***** Test Step 10 : Get Group Membership 1 (all)\n"); + err = TestGetGroupMembership1All_10(); break; case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : View Second Group (new)\n"); - err = TestViewSecondGroupNew_11(); + ChipLogProgress(chipTool, " ***** Test Step 11 : Add Second Group (new)\n"); + err = TestAddSecondGroupNew_11(); break; case 12: - ChipLogProgress(chipTool, " ***** Test Step 12 : View Group 3 (not found)\n"); - err = TestViewGroup3NotFound_12(); + ChipLogProgress(chipTool, " ***** Test Step 12 : View Second Group (new)\n"); + err = TestViewSecondGroupNew_12(); break; case 13: - ChipLogProgress(chipTool, " ***** Test Step 13 : View First Group (existing)\n"); - err = TestViewFirstGroupExisting_13(); + ChipLogProgress(chipTool, " ***** Test Step 13 : View Group 3 (not found)\n"); + err = TestViewGroup3NotFound_13(); break; case 14: - ChipLogProgress(chipTool, " ***** Test Step 14 : View Second Group (existing)\n"); - err = TestViewSecondGroupExisting_14(); + ChipLogProgress(chipTool, " ***** Test Step 14 : View First Group (existing)\n"); + err = TestViewFirstGroupExisting_14(); break; case 15: - ChipLogProgress(chipTool, " ***** Test Step 15 : Get Group Membership 2\n"); - err = TestGetGroupMembership2_15(); + ChipLogProgress(chipTool, " ***** Test Step 15 : View Second Group (existing)\n"); + err = TestViewSecondGroupExisting_15(); break; case 16: - ChipLogProgress(chipTool, " ***** Test Step 16 : Remove Group 0 (invalid)\n"); - err = TestRemoveGroup0Invalid_16(); + ChipLogProgress(chipTool, " ***** Test Step 16 : Get Group Membership 2\n"); + err = TestGetGroupMembership2_16(); break; case 17: - ChipLogProgress(chipTool, " ***** Test Step 17 : Remove Group 4 (not found)\n"); - err = TestRemoveGroup4NotFound_17(); + ChipLogProgress(chipTool, " ***** Test Step 17 : Remove Group 0 (invalid)\n"); + err = TestRemoveGroup0Invalid_17(); break; case 18: - ChipLogProgress(chipTool, " ***** Test Step 18 : Remove Second Group (existing)\n"); - err = TestRemoveSecondGroupExisting_18(); + ChipLogProgress(chipTool, " ***** Test Step 18 : Remove Group 4 (not found)\n"); + err = TestRemoveGroup4NotFound_18(); break; case 19: - ChipLogProgress(chipTool, " ***** Test Step 19 : View First Group (not removed)\n"); - err = TestViewFirstGroupNotRemoved_19(); + ChipLogProgress(chipTool, " ***** Test Step 19 : Remove Second Group (existing)\n"); + err = TestRemoveSecondGroupExisting_19(); break; case 20: - ChipLogProgress(chipTool, " ***** Test Step 20 : View Second Group (removed)\n"); - err = TestViewSecondGroupRemoved_20(); + ChipLogProgress(chipTool, " ***** Test Step 20 : View First Group (not removed)\n"); + err = TestViewFirstGroupNotRemoved_20(); break; case 21: - ChipLogProgress(chipTool, " ***** Test Step 21 : Get Group Membership 3\n"); - err = TestGetGroupMembership3_21(); + ChipLogProgress(chipTool, " ***** Test Step 21 : View Second Group (removed)\n"); + err = TestViewSecondGroupRemoved_21(); break; case 22: - ChipLogProgress(chipTool, " ***** Test Step 22 : Remove All\n"); - err = TestRemoveAll_22(); + ChipLogProgress(chipTool, " ***** Test Step 22 : Get Group Membership 3\n"); + err = TestGetGroupMembership3_22(); break; case 23: - ChipLogProgress(chipTool, " ***** Test Step 23 : View First Group (removed)\n"); - err = TestViewFirstGroupRemoved_23(); + ChipLogProgress(chipTool, " ***** Test Step 23 : Remove All\n"); + err = TestRemoveAll_23(); break; case 24: - ChipLogProgress(chipTool, " ***** Test Step 24 : View Second Group (still removed)\n"); - err = TestViewSecondGroupStillRemoved_24(); + ChipLogProgress(chipTool, " ***** Test Step 24 : View First Group (removed)\n"); + err = TestViewFirstGroupRemoved_24(); break; case 25: - ChipLogProgress(chipTool, " ***** Test Step 25 : View Group 3 (removed)\n"); - err = TestViewGroup3Removed_25(); + ChipLogProgress(chipTool, " ***** Test Step 25 : View Second Group (still removed)\n"); + err = TestViewSecondGroupStillRemoved_25(); break; case 26: - ChipLogProgress(chipTool, " ***** Test Step 26 : Get Group Membership 4\n"); - err = TestGetGroupMembership4_26(); + ChipLogProgress(chipTool, " ***** Test Step 26 : View Group 3 (removed)\n"); + err = TestViewGroup3Removed_26(); + break; + case 27: + ChipLogProgress(chipTool, " ***** Test Step 27 : Get Group Membership 4\n"); + err = TestGetGroupMembership4_27(); break; } @@ -170131,6 +170135,9 @@ class TestGroupsCluster : public TestCommandBridge { case 26: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); break; + case 27: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; } // Go on to the next test. @@ -170141,7 +170148,7 @@ class TestGroupsCluster : public TestCommandBridge { private: std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 27; + const uint16_t mTestCount = 28; chip::Optional mNodeId; chip::Optional mCluster; @@ -170330,7 +170337,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestAddFirstGroupNew_6() + CHIP_ERROR TestAddFirstGroupNameTooLong_6() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170340,7 +170347,40 @@ class TestGroupsCluster : public TestCommandBridge { __auto_type * params = [[MTRGroupsClusterAddGroupParams alloc] init]; params.groupID = [NSNumber numberWithUnsignedShort:257U]; - params.groupName = @"Group #1"; + params.groupName = @"12345678901234567"; + [cluster addGroupWithParams:params completion: + ^(MTRGroupsClusterAddGroupResponseParams * _Nullable values, NSError * _Nullable err) { + NSLog(@"Add First Group (name too long) Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + { + id actualValue = values.status; + VerifyOrReturn(CheckValue("Status", actualValue, 135U)); + } + + { + id actualValue = values.groupID; + VerifyOrReturn(CheckValue("GroupID", actualValue, 257U)); + } + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestAddFirstGroupNew_7() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterGroups alloc] initWithDevice:device endpointID:@(1) queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + __auto_type * params = [[MTRGroupsClusterAddGroupParams alloc] init]; + params.groupID = + [NSNumber numberWithUnsignedShort:257U]; + params.groupName = @"Group #101234567"; [cluster addGroupWithParams:params completion: ^(MTRGroupsClusterAddGroupResponseParams * _Nullable values, NSError * _Nullable err) { NSLog(@"Add First Group (new) Error: %@", err); @@ -170363,7 +170403,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewFirstGroupNew_7() + CHIP_ERROR TestViewFirstGroupNew_8() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170391,7 +170431,7 @@ class TestGroupsCluster : public TestCommandBridge { { id actualValue = values.groupName; - VerifyOrReturn(CheckValueAsString("GroupName", actualValue, @"Group #1")); + VerifyOrReturn(CheckValueAsString("GroupName", actualValue, @"Group #101234567")); } NextTest(); @@ -170400,7 +170440,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewSecondGroupNotFound_8() + CHIP_ERROR TestViewSecondGroupNotFound_9() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170432,7 +170472,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestGetGroupMembership1All_9() + CHIP_ERROR TestGetGroupMembership1All_10() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170467,7 +170507,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestAddSecondGroupNew_10() + CHIP_ERROR TestAddSecondGroupNew_11() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170500,7 +170540,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewSecondGroupNew_11() + CHIP_ERROR TestViewSecondGroupNew_12() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170537,7 +170577,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewGroup3NotFound_12() + CHIP_ERROR TestViewGroup3NotFound_13() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170569,7 +170609,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewFirstGroupExisting_13() + CHIP_ERROR TestViewFirstGroupExisting_14() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170597,7 +170637,7 @@ class TestGroupsCluster : public TestCommandBridge { { id actualValue = values.groupName; - VerifyOrReturn(CheckValueAsString("GroupName", actualValue, @"Group #1")); + VerifyOrReturn(CheckValueAsString("GroupName", actualValue, @"Group #101234567")); } NextTest(); @@ -170606,7 +170646,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewSecondGroupExisting_14() + CHIP_ERROR TestViewSecondGroupExisting_15() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170643,7 +170683,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestGetGroupMembership2_15() + CHIP_ERROR TestGetGroupMembership2_16() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170684,7 +170724,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestRemoveGroup0Invalid_16() + CHIP_ERROR TestRemoveGroup0Invalid_17() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170716,7 +170756,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestRemoveGroup4NotFound_17() + CHIP_ERROR TestRemoveGroup4NotFound_18() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170748,7 +170788,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestRemoveSecondGroupExisting_18() + CHIP_ERROR TestRemoveSecondGroupExisting_19() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170780,7 +170820,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewFirstGroupNotRemoved_19() + CHIP_ERROR TestViewFirstGroupNotRemoved_20() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170808,7 +170848,7 @@ class TestGroupsCluster : public TestCommandBridge { { id actualValue = values.groupName; - VerifyOrReturn(CheckValueAsString("GroupName", actualValue, @"Group #1")); + VerifyOrReturn(CheckValueAsString("GroupName", actualValue, @"Group #101234567")); } NextTest(); @@ -170817,7 +170857,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewSecondGroupRemoved_20() + CHIP_ERROR TestViewSecondGroupRemoved_21() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170849,7 +170889,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestGetGroupMembership3_21() + CHIP_ERROR TestGetGroupMembership3_22() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170892,7 +170932,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestRemoveAll_22() + CHIP_ERROR TestRemoveAll_23() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170911,7 +170951,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewFirstGroupRemoved_23() + CHIP_ERROR TestViewFirstGroupRemoved_24() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170943,7 +170983,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewSecondGroupStillRemoved_24() + CHIP_ERROR TestViewSecondGroupStillRemoved_25() { MTRBaseDevice * device = GetDevice("alpha"); @@ -170975,7 +171015,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestViewGroup3Removed_25() + CHIP_ERROR TestViewGroup3Removed_26() { MTRBaseDevice * device = GetDevice("alpha"); @@ -171007,7 +171047,7 @@ class TestGroupsCluster : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestGetGroupMembership4_26() + CHIP_ERROR TestGetGroupMembership4_27() { MTRBaseDevice * device = GetDevice("alpha"); From 43981ac36b3d5b7269574b4c3b808315166091ba Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 6 Oct 2023 14:27:35 -0400 Subject: [PATCH 19/21] Log more information when "darwin-framework-tool tests list" fails. (#29625) --- scripts/tests/chiptest/__init__.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/scripts/tests/chiptest/__init__.py b/scripts/tests/chiptest/__init__.py index 457ebb1d969c91..45e89df357c145 100644 --- a/scripts/tests/chiptest/__init__.py +++ b/scripts/tests/chiptest/__init__.py @@ -15,6 +15,7 @@ # import json +import logging import os import subprocess from dataclasses import dataclass @@ -246,8 +247,13 @@ def tests_with_command(chip_tool: str, is_manual: bool): if is_manual: cmd += "-manual" - result = subprocess.run([chip_tool, "tests", cmd], capture_output=True) - result.check_returncode() + cmd = [chip_tool, "tests", cmd] + result = subprocess.run(cmd, capture_output=True, encoding="utf-8") + if result.returncode != 0: + logging.error(f'Failed to run {cmd}:') + logging.error('STDOUT: ' + result.stdout) + logging.error('STDERR: ' + result.stderr) + result.check_returncode() test_tags = set() if is_manual: @@ -255,7 +261,7 @@ def tests_with_command(chip_tool: str, is_manual: bool): in_development_tests = [s.replace(".yaml", "") for s in _GetInDevelopmentTests()] - for name in result.stdout.decode("utf8").split("\n"): + for name in result.stdout.split("\n"): if not name: continue From fc44549d9e9c08d78668ee39fa2b8c2fb4450144 Mon Sep 17 00:00:00 2001 From: Tennessee Carmel-Veilleux Date: Fri, 6 Oct 2023 19:00:44 -0400 Subject: [PATCH 20/21] Save flash on generated struct encoding logic (#29608) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Save flash on generated struct encoding logic Problem: - Structural repetition in the generated code caused needless jumps to be inlined in very large numbers in `Encode` methods, in ways that could be factored-out. This PR: - Changes the generated code to use a proxy encoder class that reduces expanded inlined code, reduces 64 bit arguments usage and maintains correct early return behavior, while generating significantly smaller method bodies. Testing done: - Unit tests pass - Integration tests pass * Restyled by clang-format * Address review comments * Update src/app/data-model/WrappedStructEncoder.h Co-authored-by: Damian Królik <66667989+Damian-Nordic@users.noreply.github.com> * Regen --------- Co-authored-by: tennessee.carmelveilleux@gmail.com Co-authored-by: Restyled.io Co-authored-by: Damian Królik <66667989+Damian-Nordic@users.noreply.github.com> --- src/app/data-model/WrappedStructEncoder.h | 64 + .../partials/cluster-objects-struct.zapt | 24 +- .../templates/app/cluster-objects-src.zapt | 9 +- .../zap-generated/cluster-objects.cpp | 3761 ++++++++--------- 4 files changed, 1786 insertions(+), 2072 deletions(-) create mode 100644 src/app/data-model/WrappedStructEncoder.h diff --git a/src/app/data-model/WrappedStructEncoder.h b/src/app/data-model/WrappedStructEncoder.h new file mode 100644 index 00000000000000..7c5e77912ca5fe --- /dev/null +++ b/src/app/data-model/WrappedStructEncoder.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2023 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include +#include +#include + +#include + +namespace chip { +namespace app { +namespace DataModel { + +class WrappedStructEncoder +{ +public: + WrappedStructEncoder(TLV::TLVWriter & writer, TLV::Tag outerTag) : mWriter(writer) + { + mLastError = mWriter.StartContainer(outerTag, TLV::kTLVType_Structure, mOuter); + } + + template + void Encode(uint8_t contextTag, Args &&... args) + { + VerifyOrReturn(mLastError == CHIP_NO_ERROR); + mLastError = DataModel::Encode(mWriter, TLV::ContextTag(contextTag), std::forward(args)...); + } + + CHIP_ERROR Finalize() + { + if (mLastError == CHIP_NO_ERROR) + { + mLastError = mWriter.EndContainer(mOuter); + } + return mLastError; + } + +private: + TLV::TLVWriter & mWriter; + CHIP_ERROR mLastError = CHIP_NO_ERROR; + TLV::TLVType mOuter; +}; + +} // namespace DataModel +} // namespace app +} // namespace chip diff --git a/src/app/zap-templates/partials/cluster-objects-struct.zapt b/src/app/zap-templates/partials/cluster-objects-struct.zapt index ad39d631a515cb..020f38f13a56dc 100644 --- a/src/app/zap-templates/partials/cluster-objects-struct.zapt +++ b/src/app/zap-templates/partials/cluster-objects-struct.zapt @@ -64,6 +64,7 @@ namespace {{asUpperCamelCase name}} { } // namespace {{asUpperCamelCase name}} {{else}} + namespace {{asUpperCamelCase name}} { {{#if isFabricScoped}} CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const @@ -81,34 +82,33 @@ CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optiona {{#if struct_has_fabric_sensitive_fields}} bool includeSensitive = !aAccessingFabricIndex.HasValue() || (aAccessingFabricIndex.Value() == fabricIndex); {{/if}} - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); + + DataModel::WrappedStructEncoder encoder{aWriter, aTag}; + {{#zcl_struct_items}} {{#if (is_num_equal fieldIdentifier 254)}} if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::k{{asUpperCamelCase label}}), {{asLowerCamelCase label}})); + encoder.Encode(to_underlying(Fields::k{{asUpperCamelCase label}}), {{asLowerCamelCase label}}); } {{else if isFabricSensitive}} if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::k{{asUpperCamelCase label}}), {{asLowerCamelCase label}})); + encoder.Encode(to_underlying(Fields::k{{asUpperCamelCase label}}), {{asLowerCamelCase label}}); } {{else}} - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::k{{asUpperCamelCase label}}), {{asLowerCamelCase label}})); + encoder.Encode(to_underlying(Fields::k{{asUpperCamelCase label}}), {{asLowerCamelCase label}}); {{/if}} {{/zcl_struct_items}} - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } {{else}} CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); + DataModel::WrappedStructEncoder encoder{aWriter, aTag}; {{#zcl_struct_items}} - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::k{{asUpperCamelCase label}}), {{asLowerCamelCase label}})); + encoder.Encode(to_underlying(Fields::k{{asUpperCamelCase label}}), {{asLowerCamelCase label}}); {{/zcl_struct_items}} - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + return encoder.Finalize(); } {{/if}} diff --git a/src/app/zap-templates/templates/app/cluster-objects-src.zapt b/src/app/zap-templates/templates/app/cluster-objects-src.zapt index 6bdbf3cb4f8674..50bd812be31521 100644 --- a/src/app/zap-templates/templates/app/cluster-objects-src.zapt +++ b/src/app/zap-templates/templates/app/cluster-objects-src.zapt @@ -1,6 +1,8 @@ {{> header}} +#include #include + #include namespace chip { @@ -80,12 +82,11 @@ namespace Commands { {{#zcl_commands}} namespace {{asUpperCamelCase name}} { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const{ - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); + DataModel::WrappedStructEncoder encoder{aWriter, aTag}; {{#zcl_command_arguments}} - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::k{{asUpperCamelCase label}}), {{asLowerCamelCase label}})); + encoder.Encode(to_underlying(Fields::k{{asUpperCamelCase label}}), {{asLowerCamelCase label}}); {{/zcl_command_arguments}} - return aWriter.EndContainer(outer); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader &reader) { diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp index 263a23b1dc9200..8b7b6784ad0283 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp @@ -18,6 +18,8 @@ // THIS FILE IS GENERATED BY ZAP #include +#include + #include namespace chip { @@ -77,15 +79,14 @@ class StructDecodeIterator // Structs shared across multiple clusters. namespace Structs { + namespace ModeTagStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMfgCode), mfgCode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValue), value)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMfgCode), mfgCode); + encoder.Encode(to_underlying(Fields::kValue), value); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -119,16 +120,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace ModeTagStruct + namespace ModeOptionStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLabel), label)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMode), mode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kModeTags), modeTags)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kLabel), label); + encoder.Encode(to_underlying(Fields::kMode), mode); + encoder.Encode(to_underlying(Fields::kModeTags), modeTags); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -166,15 +166,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace ModeOptionStruct + namespace ApplicationStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCatalogVendorID), catalogVendorID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kApplicationID), applicationID)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCatalogVendorID), catalogVendorID); + encoder.Encode(to_underlying(Fields::kApplicationID), applicationID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -208,16 +207,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace ApplicationStruct + namespace ErrorStateStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kErrorStateID), errorStateID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kErrorStateLabel), errorStateLabel)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kErrorStateDetails), errorStateDetails)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kErrorStateID), errorStateID); + encoder.Encode(to_underlying(Fields::kErrorStateLabel), errorStateLabel); + encoder.Encode(to_underlying(Fields::kErrorStateDetails), errorStateDetails); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -255,15 +253,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace ErrorStateStruct + namespace LabelStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLabel), label)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValue), value)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kLabel), label); + encoder.Encode(to_underlying(Fields::kValue), value); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -297,15 +294,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace LabelStruct + namespace OperationalStateStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOperationalStateID), operationalStateID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOperationalStateLabel), operationalStateLabel)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOperationalStateID), operationalStateID); + encoder.Encode(to_underlying(Fields::kOperationalStateLabel), operationalStateLabel); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -348,10 +344,9 @@ namespace Commands { namespace Identify { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIdentifyTime), identifyTime)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kIdentifyTime), identifyTime); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -383,11 +378,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TriggerEffect { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEffectIdentifier), effectIdentifier)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEffectVariant), effectVariant)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kEffectIdentifier), effectIdentifier); + encoder.Encode(to_underlying(Fields::kEffectVariant), effectVariant); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -458,11 +452,10 @@ namespace Commands { namespace AddGroup { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupName), groupName)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kGroupName), groupName); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -498,11 +491,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace AddGroupResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -538,10 +530,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ViewGroup { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -573,12 +564,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ViewGroupResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupName), groupName)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kGroupName), groupName); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -618,10 +608,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetGroupMembership { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupList), groupList)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupList), groupList); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -653,11 +642,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetGroupMembershipResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCapacity), capacity)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupList), groupList)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCapacity), capacity); + encoder.Encode(to_underlying(Fields::kGroupList), groupList); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -693,10 +681,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RemoveGroup { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -728,11 +715,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RemoveGroupResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -768,9 +754,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RemoveAllGroups { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -789,11 +774,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace AddGroupIfIdentifying { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupName), groupName)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kGroupName), groupName); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -858,15 +842,14 @@ namespace Events {} // namespace Events } // namespace Groups namespace Scenes { namespace Structs { + namespace AttributeValuePair { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAttributeID), attributeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAttributeValue), attributeValue)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kAttributeID), attributeID); + encoder.Encode(to_underlying(Fields::kAttributeValue), attributeValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -900,15 +883,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace AttributeValuePair + namespace ExtensionFieldSet { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kClusterID), clusterID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAttributeValueList), attributeValueList)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kClusterID), clusterID); + encoder.Encode(to_underlying(Fields::kAttributeValueList), attributeValueList); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -948,14 +930,13 @@ namespace Commands { namespace AddScene { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneName), sceneName)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExtensionFieldSets), extensionFieldSets)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kSceneName), sceneName); + encoder.Encode(to_underlying(Fields::kExtensionFieldSets), extensionFieldSets); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1003,12 +984,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace AddSceneResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1048,11 +1028,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ViewScene { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1088,15 +1067,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ViewSceneResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneName), sceneName)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExtensionFieldSets), extensionFieldSets)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kSceneName), sceneName); + encoder.Encode(to_underlying(Fields::kExtensionFieldSets), extensionFieldSets); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1148,11 +1126,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RemoveScene { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1188,12 +1165,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RemoveSceneResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1233,10 +1209,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RemoveAllScenes { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1268,11 +1243,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RemoveAllScenesResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1308,11 +1282,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StoreScene { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1348,12 +1321,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StoreSceneResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1393,12 +1365,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RecallScene { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1438,10 +1409,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetSceneMembership { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1473,13 +1443,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetSceneMembershipResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCapacity), capacity)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneList), sceneList)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kCapacity), capacity); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneList), sceneList); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1523,14 +1492,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace EnhancedAddScene { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneName), sceneName)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExtensionFieldSets), extensionFieldSets)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kSceneName), sceneName); + encoder.Encode(to_underlying(Fields::kExtensionFieldSets), extensionFieldSets); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1578,12 +1546,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace EnhancedAddSceneResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1623,11 +1590,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace EnhancedViewScene { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1663,15 +1629,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace EnhancedViewSceneResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupID), groupID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneID), sceneID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneName), sceneName)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExtensionFieldSets), extensionFieldSets)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupID), groupID); + encoder.Encode(to_underlying(Fields::kSceneID), sceneID); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kSceneName), sceneName); + encoder.Encode(to_underlying(Fields::kExtensionFieldSets), extensionFieldSets); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1723,14 +1688,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace CopyScene { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMode), mode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupIdentifierFrom), groupIdentifierFrom)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneIdentifierFrom), sceneIdentifierFrom)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupIdentifierTo), groupIdentifierTo)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneIdentifierTo), sceneIdentifierTo)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMode), mode); + encoder.Encode(to_underlying(Fields::kGroupIdentifierFrom), groupIdentifierFrom); + encoder.Encode(to_underlying(Fields::kSceneIdentifierFrom), sceneIdentifierFrom); + encoder.Encode(to_underlying(Fields::kGroupIdentifierTo), groupIdentifierTo); + encoder.Encode(to_underlying(Fields::kSceneIdentifierTo), sceneIdentifierTo); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1778,12 +1742,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace CopySceneResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupIdentifierFrom), groupIdentifierFrom)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSceneIdentifierFrom), sceneIdentifierFrom)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kGroupIdentifierFrom), groupIdentifierFrom); + encoder.Encode(to_underlying(Fields::kSceneIdentifierFrom), sceneIdentifierFrom); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1870,9 +1833,8 @@ namespace Commands { namespace Off { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1891,9 +1853,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace On { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1912,9 +1873,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Toggle { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1933,11 +1893,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace OffWithEffect { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEffectIdentifier), effectIdentifier)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEffectVariant), effectVariant)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kEffectIdentifier), effectIdentifier); + encoder.Encode(to_underlying(Fields::kEffectVariant), effectVariant); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1973,9 +1932,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace OnWithRecallGlobalScene { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -1994,12 +1952,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace OnWithTimedOff { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOnOffControl), onOffControl)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOnTime), onTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOffWaitTime), offWaitTime)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOnOffControl), onOffControl); + encoder.Encode(to_underlying(Fields::kOnTime), onTime); + encoder.Encode(to_underlying(Fields::kOffWaitTime), offWaitTime); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2114,13 +2071,12 @@ namespace Commands { namespace MoveToLevel { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLevel), level)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kLevel), level); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2164,13 +2120,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Move { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMoveMode), moveMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRate), rate)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMoveMode), moveMode); + encoder.Encode(to_underlying(Fields::kRate), rate); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2214,14 +2169,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Step { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepMode), stepMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepSize), stepSize)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStepMode), stepMode); + encoder.Encode(to_underlying(Fields::kStepSize), stepSize); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2269,11 +2223,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Stop { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2309,13 +2262,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveToLevelWithOnOff { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLevel), level)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kLevel), level); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2359,13 +2311,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveWithOnOff { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMoveMode), moveMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRate), rate)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMoveMode), moveMode); + encoder.Encode(to_underlying(Fields::kRate), rate); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2409,14 +2360,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StepWithOnOff { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepMode), stepMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepSize), stepSize)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStepMode), stepMode); + encoder.Encode(to_underlying(Fields::kStepSize), stepSize); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2464,11 +2414,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StopWithOnOff { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2504,10 +2453,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveToClosestFrequency { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFrequency), frequency)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kFrequency), frequency); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2672,15 +2620,14 @@ namespace Events {} // namespace Events } // namespace PulseWidthModulation namespace Descriptor { namespace Structs { + namespace DeviceTypeStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDeviceType), deviceType)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRevision), revision)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kDeviceType), deviceType); + encoder.Encode(to_underlying(Fields::kRevision), revision); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2714,17 +2661,16 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace DeviceTypeStruct + namespace SemanticTagStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMfgCode), mfgCode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNamespaceID), namespaceID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTag), tag)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLabel), label)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMfgCode), mfgCode); + encoder.Encode(to_underlying(Fields::kNamespaceID), namespaceID); + encoder.Encode(to_underlying(Fields::kTag), tag); + encoder.Encode(to_underlying(Fields::kLabel), label); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2808,6 +2754,7 @@ namespace Events {} // namespace Events } // namespace Descriptor namespace Binding { namespace Structs { + namespace TargetStruct { CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { @@ -2821,18 +2768,19 @@ CHIP_ERROR Type::EncodeForRead(TLV::TLVWriter & aWriter, TLV::Tag aTag, FabricIn CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optional & aAccessingFabricIndex) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNode), node)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroup), group)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpoint), endpoint)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCluster), cluster)); + + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + + encoder.Encode(to_underlying(Fields::kNode), node); + encoder.Encode(to_underlying(Fields::kGroup), group); + encoder.Encode(to_underlying(Fields::kEndpoint), endpoint); + encoder.Encode(to_underlying(Fields::kCluster), cluster); if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); } - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2912,16 +2860,15 @@ namespace Events {} // namespace Events } // namespace Binding namespace AccessControl { namespace Structs { + namespace AccessControlTargetStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCluster), cluster)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpoint), endpoint)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDeviceType), deviceType)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCluster), cluster); + encoder.Encode(to_underlying(Fields::kEndpoint), endpoint); + encoder.Encode(to_underlying(Fields::kDeviceType), deviceType); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -2959,6 +2906,7 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace AccessControlTargetStruct + namespace AccessControlEntryStruct { CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { @@ -2973,30 +2921,31 @@ CHIP_ERROR Type::EncodeForRead(TLV::TLVWriter & aWriter, TLV::Tag aTag, FabricIn CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optional & aAccessingFabricIndex) const { bool includeSensitive = !aAccessingFabricIndex.HasValue() || (aAccessingFabricIndex.Value() == fabricIndex); - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); + + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPrivilege), privilege)); + encoder.Encode(to_underlying(Fields::kPrivilege), privilege); } if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAuthMode), authMode)); + encoder.Encode(to_underlying(Fields::kAuthMode), authMode); } if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSubjects), subjects)); + encoder.Encode(to_underlying(Fields::kSubjects), subjects); } if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTargets), targets)); + encoder.Encode(to_underlying(Fields::kTargets), targets); } if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); } - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3042,6 +2991,7 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace AccessControlEntryStruct + namespace AccessControlExtensionStruct { CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { @@ -3056,18 +3006,19 @@ CHIP_ERROR Type::EncodeForRead(TLV::TLVWriter & aWriter, TLV::Tag aTag, FabricIn CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optional & aAccessingFabricIndex) const { bool includeSensitive = !aAccessingFabricIndex.HasValue() || (aAccessingFabricIndex.Value() == fabricIndex); - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); + + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kData), data)); + encoder.Encode(to_underlying(Fields::kData), data); } if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); } - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3254,19 +3205,18 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } // namespace AccessControl namespace Actions { namespace Structs { + namespace ActionStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kType), type)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpointListID), endpointListID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSupportedCommands), supportedCommands)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kState), state)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kName), name); + encoder.Encode(to_underlying(Fields::kType), type); + encoder.Encode(to_underlying(Fields::kEndpointListID), endpointListID); + encoder.Encode(to_underlying(Fields::kSupportedCommands), supportedCommands); + encoder.Encode(to_underlying(Fields::kState), state); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3316,17 +3266,16 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace ActionStruct + namespace EndpointListStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpointListID), endpointListID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kType), type)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpoints), endpoints)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kEndpointListID), endpointListID); + encoder.Encode(to_underlying(Fields::kName), name); + encoder.Encode(to_underlying(Fields::kType), type); + encoder.Encode(to_underlying(Fields::kEndpoints), endpoints); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3374,11 +3323,10 @@ namespace Commands { namespace InstantAction { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3414,12 +3362,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace InstantActionWithTransition { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3459,11 +3406,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StartAction { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3499,12 +3445,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StartActionWithDuration { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDuration), duration)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + encoder.Encode(to_underlying(Fields::kDuration), duration); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3544,11 +3489,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StopAction { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3584,11 +3528,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace PauseAction { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3624,12 +3567,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace PauseActionWithDuration { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDuration), duration)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + encoder.Encode(to_underlying(Fields::kDuration), duration); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3669,11 +3611,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ResumeAction { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3709,11 +3650,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace EnableAction { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3749,12 +3689,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace EnableActionWithDuration { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDuration), duration)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + encoder.Encode(to_underlying(Fields::kDuration), duration); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3794,11 +3733,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace DisableAction { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -3834,12 +3772,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace DisableActionWithDuration { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActionID), actionID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInvokeID), invokeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDuration), duration)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActionID), actionID); + encoder.Encode(to_underlying(Fields::kInvokeID), invokeID); + encoder.Encode(to_underlying(Fields::kDuration), duration); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -4008,15 +3945,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } // namespace Actions namespace BasicInformation { namespace Structs { + namespace CapabilityMinimaStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCaseSessionsPerFabric), caseSessionsPerFabric)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSubscriptionsPerFabric), subscriptionsPerFabric)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCaseSessionsPerFabric), caseSessionsPerFabric); + encoder.Encode(to_underlying(Fields::kSubscriptionsPerFabric), subscriptionsPerFabric); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -4050,15 +3986,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace CapabilityMinimaStruct + namespace ProductAppearanceStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFinish), finish)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPrimaryColor), primaryColor)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kFinish), finish); + encoder.Encode(to_underlying(Fields::kPrimaryColor), primaryColor); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -4098,9 +4033,8 @@ namespace Commands { namespace MfgSpecificPing { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -4319,17 +4253,16 @@ namespace Commands { namespace QueryImage { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kVendorID), vendorID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProductID), productID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSoftwareVersion), softwareVersion)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProtocolsSupported), protocolsSupported)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kHardwareVersion), hardwareVersion)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLocation), location)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRequestorCanConsent), requestorCanConsent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMetadataForProvider), metadataForProvider)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kVendorID), vendorID); + encoder.Encode(to_underlying(Fields::kProductID), productID); + encoder.Encode(to_underlying(Fields::kSoftwareVersion), softwareVersion); + encoder.Encode(to_underlying(Fields::kProtocolsSupported), protocolsSupported); + encoder.Encode(to_underlying(Fields::kHardwareVersion), hardwareVersion); + encoder.Encode(to_underlying(Fields::kLocation), location); + encoder.Encode(to_underlying(Fields::kRequestorCanConsent), requestorCanConsent); + encoder.Encode(to_underlying(Fields::kMetadataForProvider), metadataForProvider); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -4389,17 +4322,16 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace QueryImageResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDelayedActionTime), delayedActionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kImageURI), imageURI)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSoftwareVersion), softwareVersion)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSoftwareVersionString), softwareVersionString)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUpdateToken), updateToken)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserConsentNeeded), userConsentNeeded)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMetadataForRequestor), metadataForRequestor)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kDelayedActionTime), delayedActionTime); + encoder.Encode(to_underlying(Fields::kImageURI), imageURI); + encoder.Encode(to_underlying(Fields::kSoftwareVersion), softwareVersion); + encoder.Encode(to_underlying(Fields::kSoftwareVersionString), softwareVersionString); + encoder.Encode(to_underlying(Fields::kUpdateToken), updateToken); + encoder.Encode(to_underlying(Fields::kUserConsentNeeded), userConsentNeeded); + encoder.Encode(to_underlying(Fields::kMetadataForRequestor), metadataForRequestor); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -4459,11 +4391,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ApplyUpdateRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUpdateToken), updateToken)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNewVersion), newVersion)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kUpdateToken), updateToken); + encoder.Encode(to_underlying(Fields::kNewVersion), newVersion); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -4499,11 +4430,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ApplyUpdateResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAction), action)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDelayedActionTime), delayedActionTime)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kAction), action); + encoder.Encode(to_underlying(Fields::kDelayedActionTime), delayedActionTime); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -4539,11 +4469,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace NotifyUpdateApplied { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUpdateToken), updateToken)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSoftwareVersion), softwareVersion)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kUpdateToken), updateToken); + encoder.Encode(to_underlying(Fields::kSoftwareVersion), softwareVersion); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -4606,6 +4535,7 @@ namespace Events {} // namespace Events } // namespace OtaSoftwareUpdateProvider namespace OtaSoftwareUpdateRequestor { namespace Structs { + namespace ProviderLocation { CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { @@ -4619,16 +4549,17 @@ CHIP_ERROR Type::EncodeForRead(TLV::TLVWriter & aWriter, TLV::Tag aTag, FabricIn CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optional & aAccessingFabricIndex) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProviderNodeID), providerNodeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpoint), endpoint)); + + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + + encoder.Encode(to_underlying(Fields::kProviderNodeID), providerNodeID); + encoder.Encode(to_underlying(Fields::kEndpoint), endpoint); if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); } - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -4672,14 +4603,13 @@ namespace Commands { namespace AnnounceOTAProvider { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProviderNodeID), providerNodeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kVendorID), vendorID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAnnouncementReason), announcementReason)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMetadataForNode), metadataForNode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpoint), endpoint)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kProviderNodeID), providerNodeID); + encoder.Encode(to_underlying(Fields::kVendorID), vendorID); + encoder.Encode(to_underlying(Fields::kAnnouncementReason), announcementReason); + encoder.Encode(to_underlying(Fields::kMetadataForNode), metadataForNode); + encoder.Encode(to_underlying(Fields::kEndpoint), endpoint); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5037,15 +4967,14 @@ namespace Events {} // namespace Events } // namespace PowerSourceConfiguration namespace PowerSource { namespace Structs { + namespace BatChargeFaultChangeType { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCurrent), current)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPrevious), previous)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCurrent), current); + encoder.Encode(to_underlying(Fields::kPrevious), previous); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5079,15 +5008,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace BatChargeFaultChangeType + namespace BatFaultChangeType { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCurrent), current)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPrevious), previous)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCurrent), current); + encoder.Encode(to_underlying(Fields::kPrevious), previous); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5121,15 +5049,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace BatFaultChangeType + namespace WiredFaultChangeType { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCurrent), current)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPrevious), previous)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCurrent), current); + encoder.Encode(to_underlying(Fields::kPrevious), previous); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5380,17 +5307,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } // namespace PowerSource namespace GeneralCommissioning { namespace Structs { + namespace BasicCommissioningInfo { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFailSafeExpiryLengthSeconds), failSafeExpiryLengthSeconds)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMaxCumulativeFailsafeSeconds), maxCumulativeFailsafeSeconds)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kFailSafeExpiryLengthSeconds), failSafeExpiryLengthSeconds); + encoder.Encode(to_underlying(Fields::kMaxCumulativeFailsafeSeconds), maxCumulativeFailsafeSeconds); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5430,11 +5354,10 @@ namespace Commands { namespace ArmFailSafe { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExpiryLengthSeconds), expiryLengthSeconds)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBreadcrumb), breadcrumb)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kExpiryLengthSeconds), expiryLengthSeconds); + encoder.Encode(to_underlying(Fields::kBreadcrumb), breadcrumb); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5470,11 +5393,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ArmFailSafeResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kErrorCode), errorCode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDebugText), debugText)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kErrorCode), errorCode); + encoder.Encode(to_underlying(Fields::kDebugText), debugText); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5510,12 +5432,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetRegulatoryConfig { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNewRegulatoryConfig), newRegulatoryConfig)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCountryCode), countryCode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBreadcrumb), breadcrumb)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNewRegulatoryConfig), newRegulatoryConfig); + encoder.Encode(to_underlying(Fields::kCountryCode), countryCode); + encoder.Encode(to_underlying(Fields::kBreadcrumb), breadcrumb); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5555,11 +5476,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetRegulatoryConfigResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kErrorCode), errorCode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDebugText), debugText)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kErrorCode), errorCode); + encoder.Encode(to_underlying(Fields::kDebugText), debugText); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5595,9 +5515,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace CommissioningComplete { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5616,11 +5535,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace CommissioningCompleteResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kErrorCode), errorCode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDebugText), debugText)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kErrorCode), errorCode); + encoder.Encode(to_underlying(Fields::kDebugText), debugText); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5693,15 +5611,14 @@ namespace Events {} // namespace Events } // namespace GeneralCommissioning namespace NetworkCommissioning { namespace Structs { + namespace NetworkInfoStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkID), networkID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kConnected), connected)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNetworkID), networkID); + encoder.Encode(to_underlying(Fields::kConnected), connected); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5735,21 +5652,20 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace NetworkInfoStruct + namespace ThreadInterfaceScanResultStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPanId), panId)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExtendedPanId), extendedPanId)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkName), networkName)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kChannel), channel)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kVersion), version)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExtendedAddress), extendedAddress)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRssi), rssi)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLqi), lqi)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kPanId), panId); + encoder.Encode(to_underlying(Fields::kExtendedPanId), extendedPanId); + encoder.Encode(to_underlying(Fields::kNetworkName), networkName); + encoder.Encode(to_underlying(Fields::kChannel), channel); + encoder.Encode(to_underlying(Fields::kVersion), version); + encoder.Encode(to_underlying(Fields::kExtendedAddress), extendedAddress); + encoder.Encode(to_underlying(Fields::kRssi), rssi); + encoder.Encode(to_underlying(Fields::kLqi), lqi); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5807,19 +5723,18 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace ThreadInterfaceScanResultStruct + namespace WiFiInterfaceScanResultStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSecurity), security)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSsid), ssid)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBssid), bssid)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kChannel), channel)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWiFiBand), wiFiBand)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRssi), rssi)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kSecurity), security); + encoder.Encode(to_underlying(Fields::kSsid), ssid); + encoder.Encode(to_underlying(Fields::kBssid), bssid); + encoder.Encode(to_underlying(Fields::kChannel), channel); + encoder.Encode(to_underlying(Fields::kWiFiBand), wiFiBand); + encoder.Encode(to_underlying(Fields::kRssi), rssi); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5875,11 +5790,10 @@ namespace Commands { namespace ScanNetworks { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSsid), ssid)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBreadcrumb), breadcrumb)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kSsid), ssid); + encoder.Encode(to_underlying(Fields::kBreadcrumb), breadcrumb); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5915,13 +5829,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ScanNetworksResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkingStatus), networkingStatus)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDebugText), debugText)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWiFiScanResults), wiFiScanResults)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kThreadScanResults), threadScanResults)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNetworkingStatus), networkingStatus); + encoder.Encode(to_underlying(Fields::kDebugText), debugText); + encoder.Encode(to_underlying(Fields::kWiFiScanResults), wiFiScanResults); + encoder.Encode(to_underlying(Fields::kThreadScanResults), threadScanResults); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -5965,12 +5878,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace AddOrUpdateWiFiNetwork { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSsid), ssid)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredentials), credentials)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBreadcrumb), breadcrumb)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kSsid), ssid); + encoder.Encode(to_underlying(Fields::kCredentials), credentials); + encoder.Encode(to_underlying(Fields::kBreadcrumb), breadcrumb); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6010,11 +5922,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace AddOrUpdateThreadNetwork { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOperationalDataset), operationalDataset)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBreadcrumb), breadcrumb)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOperationalDataset), operationalDataset); + encoder.Encode(to_underlying(Fields::kBreadcrumb), breadcrumb); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6050,11 +5961,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RemoveNetwork { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkID), networkID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBreadcrumb), breadcrumb)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNetworkID), networkID); + encoder.Encode(to_underlying(Fields::kBreadcrumb), breadcrumb); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6090,12 +6000,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace NetworkConfigResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkingStatus), networkingStatus)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDebugText), debugText)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkIndex), networkIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNetworkingStatus), networkingStatus); + encoder.Encode(to_underlying(Fields::kDebugText), debugText); + encoder.Encode(to_underlying(Fields::kNetworkIndex), networkIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6135,11 +6044,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ConnectNetwork { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkID), networkID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBreadcrumb), breadcrumb)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNetworkID), networkID); + encoder.Encode(to_underlying(Fields::kBreadcrumb), breadcrumb); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6175,12 +6083,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ConnectNetworkResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkingStatus), networkingStatus)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDebugText), debugText)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kErrorValue), errorValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNetworkingStatus), networkingStatus); + encoder.Encode(to_underlying(Fields::kDebugText), debugText); + encoder.Encode(to_underlying(Fields::kErrorValue), errorValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6220,12 +6127,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ReorderNetwork { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkID), networkID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkIndex), networkIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBreadcrumb), breadcrumb)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNetworkID), networkID); + encoder.Encode(to_underlying(Fields::kNetworkIndex), networkIndex); + encoder.Encode(to_underlying(Fields::kBreadcrumb), breadcrumb); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6312,12 +6218,11 @@ namespace Commands { namespace RetrieveLogsRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIntent), intent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRequestedProtocol), requestedProtocol)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransferFileDesignator), transferFileDesignator)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kIntent), intent); + encoder.Encode(to_underlying(Fields::kRequestedProtocol), requestedProtocol); + encoder.Encode(to_underlying(Fields::kTransferFileDesignator), transferFileDesignator); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6357,13 +6262,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RetrieveLogsResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLogContent), logContent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUTCTimeStamp), UTCTimeStamp)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTimeSinceBoot), timeSinceBoot)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kLogContent), logContent); + encoder.Encode(to_underlying(Fields::kUTCTimeStamp), UTCTimeStamp); + encoder.Encode(to_underlying(Fields::kTimeSinceBoot), timeSinceBoot); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6434,23 +6338,20 @@ namespace Events {} // namespace Events } // namespace DiagnosticLogs namespace GeneralDiagnostics { namespace Structs { + namespace NetworkInterface { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIsOperational), isOperational)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOffPremiseServicesReachableIPv4), offPremiseServicesReachableIPv4)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOffPremiseServicesReachableIPv6), offPremiseServicesReachableIPv6)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kHardwareAddress), hardwareAddress)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIPv4Addresses), IPv4Addresses)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIPv6Addresses), IPv6Addresses)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kType), type)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kName), name); + encoder.Encode(to_underlying(Fields::kIsOperational), isOperational); + encoder.Encode(to_underlying(Fields::kOffPremiseServicesReachableIPv4), offPremiseServicesReachableIPv4); + encoder.Encode(to_underlying(Fields::kOffPremiseServicesReachableIPv6), offPremiseServicesReachableIPv6); + encoder.Encode(to_underlying(Fields::kHardwareAddress), hardwareAddress); + encoder.Encode(to_underlying(Fields::kIPv4Addresses), IPv4Addresses); + encoder.Encode(to_underlying(Fields::kIPv6Addresses), IPv6Addresses); + encoder.Encode(to_underlying(Fields::kType), type); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6514,11 +6415,10 @@ namespace Commands { namespace TestEventTrigger { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEnableKey), enableKey)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEventTrigger), eventTrigger)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kEnableKey), enableKey); + encoder.Encode(to_underlying(Fields::kEventTrigger), eventTrigger); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6757,18 +6657,17 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } // namespace GeneralDiagnostics namespace SoftwareDiagnostics { namespace Structs { + namespace ThreadMetricsStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kId), id)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStackFreeCurrent), stackFreeCurrent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStackFreeMinimum), stackFreeMinimum)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStackSize), stackSize)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kId), id); + encoder.Encode(to_underlying(Fields::kName), name); + encoder.Encode(to_underlying(Fields::kStackFreeCurrent), stackFreeCurrent); + encoder.Encode(to_underlying(Fields::kStackFreeMinimum), stackFreeMinimum); + encoder.Encode(to_underlying(Fields::kStackSize), stackSize); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6820,9 +6719,8 @@ namespace Commands { namespace ResetWatermarks { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -6922,27 +6820,26 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } // namespace SoftwareDiagnostics namespace ThreadNetworkDiagnostics { namespace Structs { + namespace NeighborTableStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExtAddress), extAddress)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAge), age)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRloc16), rloc16)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLinkFrameCounter), linkFrameCounter)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMleFrameCounter), mleFrameCounter)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLqi), lqi)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAverageRssi), averageRssi)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLastRssi), lastRssi)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFrameErrorRate), frameErrorRate)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMessageErrorRate), messageErrorRate)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRxOnWhenIdle), rxOnWhenIdle)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFullThreadDevice), fullThreadDevice)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFullNetworkData), fullNetworkData)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIsChild), isChild)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kExtAddress), extAddress); + encoder.Encode(to_underlying(Fields::kAge), age); + encoder.Encode(to_underlying(Fields::kRloc16), rloc16); + encoder.Encode(to_underlying(Fields::kLinkFrameCounter), linkFrameCounter); + encoder.Encode(to_underlying(Fields::kMleFrameCounter), mleFrameCounter); + encoder.Encode(to_underlying(Fields::kLqi), lqi); + encoder.Encode(to_underlying(Fields::kAverageRssi), averageRssi); + encoder.Encode(to_underlying(Fields::kLastRssi), lastRssi); + encoder.Encode(to_underlying(Fields::kFrameErrorRate), frameErrorRate); + encoder.Encode(to_underlying(Fields::kMessageErrorRate), messageErrorRate); + encoder.Encode(to_underlying(Fields::kRxOnWhenIdle), rxOnWhenIdle); + encoder.Encode(to_underlying(Fields::kFullThreadDevice), fullThreadDevice); + encoder.Encode(to_underlying(Fields::kFullNetworkData), fullNetworkData); + encoder.Encode(to_underlying(Fields::kIsChild), isChild); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7024,25 +6921,24 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace NeighborTableStruct + namespace OperationalDatasetComponents { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kActiveTimestampPresent), activeTimestampPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPendingTimestampPresent), pendingTimestampPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMasterKeyPresent), masterKeyPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNetworkNamePresent), networkNamePresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExtendedPanIdPresent), extendedPanIdPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMeshLocalPrefixPresent), meshLocalPrefixPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDelayPresent), delayPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPanIdPresent), panIdPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kChannelPresent), channelPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPskcPresent), pskcPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSecurityPolicyPresent), securityPolicyPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kChannelMaskPresent), channelMaskPresent)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kActiveTimestampPresent), activeTimestampPresent); + encoder.Encode(to_underlying(Fields::kPendingTimestampPresent), pendingTimestampPresent); + encoder.Encode(to_underlying(Fields::kMasterKeyPresent), masterKeyPresent); + encoder.Encode(to_underlying(Fields::kNetworkNamePresent), networkNamePresent); + encoder.Encode(to_underlying(Fields::kExtendedPanIdPresent), extendedPanIdPresent); + encoder.Encode(to_underlying(Fields::kMeshLocalPrefixPresent), meshLocalPrefixPresent); + encoder.Encode(to_underlying(Fields::kDelayPresent), delayPresent); + encoder.Encode(to_underlying(Fields::kPanIdPresent), panIdPresent); + encoder.Encode(to_underlying(Fields::kChannelPresent), channelPresent); + encoder.Encode(to_underlying(Fields::kPskcPresent), pskcPresent); + encoder.Encode(to_underlying(Fields::kSecurityPolicyPresent), securityPolicyPresent); + encoder.Encode(to_underlying(Fields::kChannelMaskPresent), channelMaskPresent); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7116,23 +7012,22 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace OperationalDatasetComponents + namespace RouteTableStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExtAddress), extAddress)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRloc16), rloc16)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRouterId), routerId)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNextHop), nextHop)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPathCost), pathCost)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLQIIn), LQIIn)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLQIOut), LQIOut)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAge), age)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAllocated), allocated)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLinkEstablished), linkEstablished)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kExtAddress), extAddress); + encoder.Encode(to_underlying(Fields::kRloc16), rloc16); + encoder.Encode(to_underlying(Fields::kRouterId), routerId); + encoder.Encode(to_underlying(Fields::kNextHop), nextHop); + encoder.Encode(to_underlying(Fields::kPathCost), pathCost); + encoder.Encode(to_underlying(Fields::kLQIIn), LQIIn); + encoder.Encode(to_underlying(Fields::kLQIOut), LQIOut); + encoder.Encode(to_underlying(Fields::kAge), age); + encoder.Encode(to_underlying(Fields::kAllocated), allocated); + encoder.Encode(to_underlying(Fields::kLinkEstablished), linkEstablished); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7198,15 +7093,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace RouteTableStruct + namespace SecurityPolicy { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRotationTime), rotationTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFlags), flags)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kRotationTime), rotationTime); + encoder.Encode(to_underlying(Fields::kFlags), flags); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7246,9 +7140,8 @@ namespace Commands { namespace ResetCounts { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7500,9 +7393,8 @@ namespace Commands { namespace ResetCounts { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7689,9 +7581,8 @@ namespace Commands { namespace ResetCounts { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7755,16 +7646,15 @@ namespace Events {} // namespace Events } // namespace EthernetNetworkDiagnostics namespace TimeSynchronization { namespace Structs { + namespace DSTOffsetStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOffset), offset)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValidStarting), validStarting)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValidUntil), validUntil)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOffset), offset); + encoder.Encode(to_underlying(Fields::kValidStarting), validStarting); + encoder.Encode(to_underlying(Fields::kValidUntil), validUntil); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7802,15 +7692,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace DSTOffsetStruct + namespace FabricScopedTrustedTimeSourceStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNodeID), nodeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpoint), endpoint)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNodeID), nodeID); + encoder.Encode(to_underlying(Fields::kEndpoint), endpoint); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7844,16 +7733,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace FabricScopedTrustedTimeSourceStruct + namespace TimeZoneStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOffset), offset)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValidAt), validAt)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOffset), offset); + encoder.Encode(to_underlying(Fields::kValidAt), validAt); + encoder.Encode(to_underlying(Fields::kName), name); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7891,16 +7779,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace TimeZoneStruct + namespace TrustedTimeSourceStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNodeID), nodeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpoint), endpoint)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); + encoder.Encode(to_underlying(Fields::kNodeID), nodeID); + encoder.Encode(to_underlying(Fields::kEndpoint), endpoint); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7944,12 +7831,11 @@ namespace Commands { namespace SetUTCTime { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUTCTime), UTCTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGranularity), granularity)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTimeSource), timeSource)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kUTCTime), UTCTime); + encoder.Encode(to_underlying(Fields::kGranularity), granularity); + encoder.Encode(to_underlying(Fields::kTimeSource), timeSource); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -7989,10 +7875,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetTrustedTimeSource { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTrustedTimeSource), trustedTimeSource)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kTrustedTimeSource), trustedTimeSource); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -8024,10 +7909,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetTimeZone { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTimeZone), timeZone)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kTimeZone), timeZone); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -8059,10 +7943,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetTimeZoneResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDSTOffsetRequired), DSTOffsetRequired)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kDSTOffsetRequired), DSTOffsetRequired); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -8094,10 +7977,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetDSTOffset { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDSTOffset), DSTOffset)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kDSTOffset), DSTOffset); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -8129,10 +8011,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetDefaultNTP { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDefaultNTP), defaultNTP)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kDefaultNTP), defaultNTP); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -8356,15 +8237,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } // namespace TimeSynchronization namespace BridgedDeviceBasicInformation { namespace Structs { + namespace ProductAppearanceStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFinish), finish)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPrimaryColor), primaryColor)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kFinish), finish); + encoder.Encode(to_underlying(Fields::kPrimaryColor), primaryColor); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -8873,14 +8753,13 @@ namespace Commands { namespace OpenCommissioningWindow { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCommissioningTimeout), commissioningTimeout)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPAKEPasscodeVerifier), PAKEPasscodeVerifier)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDiscriminator), discriminator)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIterations), iterations)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSalt), salt)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCommissioningTimeout), commissioningTimeout); + encoder.Encode(to_underlying(Fields::kPAKEPasscodeVerifier), PAKEPasscodeVerifier); + encoder.Encode(to_underlying(Fields::kDiscriminator), discriminator); + encoder.Encode(to_underlying(Fields::kIterations), iterations); + encoder.Encode(to_underlying(Fields::kSalt), salt); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -8928,10 +8807,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace OpenBasicCommissioningWindow { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCommissioningTimeout), commissioningTimeout)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCommissioningTimeout), commissioningTimeout); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -8963,9 +8841,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RevokeCommissioning { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9017,6 +8894,7 @@ namespace Events {} // namespace Events } // namespace AdministratorCommissioning namespace OperationalCredentials { namespace Structs { + namespace FabricDescriptorStruct { CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { @@ -9030,19 +8908,20 @@ CHIP_ERROR Type::EncodeForRead(TLV::TLVWriter & aWriter, TLV::Tag aTag, FabricIn CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optional & aAccessingFabricIndex) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRootPublicKey), rootPublicKey)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kVendorID), vendorID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricID), fabricID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNodeID), nodeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLabel), label)); + + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + + encoder.Encode(to_underlying(Fields::kRootPublicKey), rootPublicKey); + encoder.Encode(to_underlying(Fields::kVendorID), vendorID); + encoder.Encode(to_underlying(Fields::kFabricID), fabricID); + encoder.Encode(to_underlying(Fields::kNodeID), nodeID); + encoder.Encode(to_underlying(Fields::kLabel), label); if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); } - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9092,6 +8971,7 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace FabricDescriptorStruct + namespace NOCStruct { CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { @@ -9106,22 +8986,23 @@ CHIP_ERROR Type::EncodeForRead(TLV::TLVWriter & aWriter, TLV::Tag aTag, FabricIn CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optional & aAccessingFabricIndex) const { bool includeSensitive = !aAccessingFabricIndex.HasValue() || (aAccessingFabricIndex.Value() == fabricIndex); - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); + + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNoc), noc)); + encoder.Encode(to_underlying(Fields::kNoc), noc); } if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIcac), icac)); + encoder.Encode(to_underlying(Fields::kIcac), icac); } if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); } - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9165,10 +9046,9 @@ namespace Commands { namespace AttestationRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAttestationNonce), attestationNonce)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kAttestationNonce), attestationNonce); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9200,11 +9080,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace AttestationResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAttestationElements), attestationElements)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAttestationSignature), attestationSignature)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kAttestationElements), attestationElements); + encoder.Encode(to_underlying(Fields::kAttestationSignature), attestationSignature); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9240,10 +9119,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace CertificateChainRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCertificateType), certificateType)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCertificateType), certificateType); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9275,10 +9153,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace CertificateChainResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCertificate), certificate)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCertificate), certificate); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9310,11 +9187,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace CSRRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCSRNonce), CSRNonce)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIsForUpdateNOC), isForUpdateNOC)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCSRNonce), CSRNonce); + encoder.Encode(to_underlying(Fields::kIsForUpdateNOC), isForUpdateNOC); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9350,11 +9226,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace CSRResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNOCSRElements), NOCSRElements)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAttestationSignature), attestationSignature)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNOCSRElements), NOCSRElements); + encoder.Encode(to_underlying(Fields::kAttestationSignature), attestationSignature); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9390,14 +9265,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace AddNOC { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNOCValue), NOCValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kICACValue), ICACValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIPKValue), IPKValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCaseAdminSubject), caseAdminSubject)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAdminVendorId), adminVendorId)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNOCValue), NOCValue); + encoder.Encode(to_underlying(Fields::kICACValue), ICACValue); + encoder.Encode(to_underlying(Fields::kIPKValue), IPKValue); + encoder.Encode(to_underlying(Fields::kCaseAdminSubject), caseAdminSubject); + encoder.Encode(to_underlying(Fields::kAdminVendorId), adminVendorId); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9445,11 +9319,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace UpdateNOC { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNOCValue), NOCValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kICACValue), ICACValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNOCValue), NOCValue); + encoder.Encode(to_underlying(Fields::kICACValue), ICACValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9485,12 +9358,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace NOCResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatusCode), statusCode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDebugText), debugText)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatusCode), statusCode); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); + encoder.Encode(to_underlying(Fields::kDebugText), debugText); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9530,10 +9402,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace UpdateFabricLabel { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLabel), label)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kLabel), label); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9565,10 +9436,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RemoveFabric { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9600,10 +9470,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace AddTrustedRootCertificate { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRootCACertificate), rootCACertificate)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kRootCACertificate), rootCACertificate); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9674,6 +9543,7 @@ namespace Events {} // namespace Events } // namespace OperationalCredentials namespace GroupKeyManagement { namespace Structs { + namespace GroupInfoMapStruct { CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { @@ -9687,17 +9557,18 @@ CHIP_ERROR Type::EncodeForRead(TLV::TLVWriter & aWriter, TLV::Tag aTag, FabricIn CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optional & aAccessingFabricIndex) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupId), groupId)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpoints), endpoints)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupName), groupName)); + + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + + encoder.Encode(to_underlying(Fields::kGroupId), groupId); + encoder.Encode(to_underlying(Fields::kEndpoints), endpoints); + encoder.Encode(to_underlying(Fields::kGroupName), groupName); if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); } - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9739,6 +9610,7 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace GroupInfoMapStruct + namespace GroupKeyMapStruct { CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { @@ -9752,16 +9624,17 @@ CHIP_ERROR Type::EncodeForRead(TLV::TLVWriter & aWriter, TLV::Tag aTag, FabricIn CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optional & aAccessingFabricIndex) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupId), groupId)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupKeySetID), groupKeySetID)); + + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + + encoder.Encode(to_underlying(Fields::kGroupId), groupId); + encoder.Encode(to_underlying(Fields::kGroupKeySetID), groupKeySetID); if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); } - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9799,21 +9672,20 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace GroupKeyMapStruct + namespace GroupKeySetStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupKeySetID), groupKeySetID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupKeySecurityPolicy), groupKeySecurityPolicy)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEpochKey0), epochKey0)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEpochStartTime0), epochStartTime0)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEpochKey1), epochKey1)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEpochStartTime1), epochStartTime1)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEpochKey2), epochKey2)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEpochStartTime2), epochStartTime2)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupKeySetID), groupKeySetID); + encoder.Encode(to_underlying(Fields::kGroupKeySecurityPolicy), groupKeySecurityPolicy); + encoder.Encode(to_underlying(Fields::kEpochKey0), epochKey0); + encoder.Encode(to_underlying(Fields::kEpochStartTime0), epochStartTime0); + encoder.Encode(to_underlying(Fields::kEpochKey1), epochKey1); + encoder.Encode(to_underlying(Fields::kEpochStartTime1), epochStartTime1); + encoder.Encode(to_underlying(Fields::kEpochKey2), epochKey2); + encoder.Encode(to_underlying(Fields::kEpochStartTime2), epochStartTime2); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9877,10 +9749,9 @@ namespace Commands { namespace KeySetWrite { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupKeySet), groupKeySet)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupKeySet), groupKeySet); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9912,10 +9783,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace KeySetRead { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupKeySetID), groupKeySetID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupKeySetID), groupKeySetID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9947,10 +9817,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace KeySetReadResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupKeySet), groupKeySet)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupKeySet), groupKeySet); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -9982,10 +9851,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace KeySetRemove { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupKeySetID), groupKeySetID)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupKeySetID), groupKeySetID); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10017,9 +9885,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace KeySetReadAllIndices { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10038,10 +9905,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace KeySetReadAllIndicesResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kGroupKeySetIDs), groupKeySetIDs)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kGroupKeySetIDs), groupKeySetIDs); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10332,6 +10198,7 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } // namespace BooleanState namespace IcdManagement { namespace Structs { + namespace MonitoringRegistrationStruct { CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { @@ -10346,22 +10213,23 @@ CHIP_ERROR Type::EncodeForRead(TLV::TLVWriter & aWriter, TLV::Tag aTag, FabricIn CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optional & aAccessingFabricIndex) const { bool includeSensitive = !aAccessingFabricIndex.HasValue() || (aAccessingFabricIndex.Value() == fabricIndex); - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); + + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCheckInNodeID), checkInNodeID)); + encoder.Encode(to_underlying(Fields::kCheckInNodeID), checkInNodeID); } if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMonitoredSubject), monitoredSubject)); + encoder.Encode(to_underlying(Fields::kMonitoredSubject), monitoredSubject); } if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); } - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10405,13 +10273,12 @@ namespace Commands { namespace RegisterClient { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCheckInNodeID), checkInNodeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMonitoredSubject), monitoredSubject)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kKey), key)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kVerificationKey), verificationKey)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCheckInNodeID), checkInNodeID); + encoder.Encode(to_underlying(Fields::kMonitoredSubject), monitoredSubject); + encoder.Encode(to_underlying(Fields::kKey), key); + encoder.Encode(to_underlying(Fields::kVerificationKey), verificationKey); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10455,10 +10322,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RegisterClientResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kICDCounter), ICDCounter)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kICDCounter), ICDCounter); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10490,11 +10356,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace UnregisterClient { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCheckInNodeID), checkInNodeID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kVerificationKey), verificationKey)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCheckInNodeID), checkInNodeID); + encoder.Encode(to_underlying(Fields::kVerificationKey), verificationKey); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10530,9 +10395,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StayActiveRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10590,15 +10454,14 @@ namespace Events {} // namespace Events } // namespace IcdManagement namespace ModeSelect { namespace Structs { + namespace SemanticTagStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMfgCode), mfgCode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValue), value)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMfgCode), mfgCode); + encoder.Encode(to_underlying(Fields::kValue), value); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10632,16 +10495,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace SemanticTagStruct + namespace ModeOptionStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLabel), label)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMode), mode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSemanticTags), semanticTags)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kLabel), label); + encoder.Encode(to_underlying(Fields::kMode), mode); + encoder.Encode(to_underlying(Fields::kSemanticTags), semanticTags); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10685,10 +10547,9 @@ namespace Commands { namespace ChangeToMode { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNewMode), newMode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNewMode), newMode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10764,10 +10625,9 @@ namespace Commands { namespace ChangeToMode { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNewMode), newMode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNewMode), newMode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10799,11 +10659,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ChangeToModeResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatusText), statusText)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kStatusText), statusText); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10879,10 +10738,9 @@ namespace Commands { namespace ChangeToMode { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNewMode), newMode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNewMode), newMode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -10914,11 +10772,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ChangeToModeResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatusText), statusText)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kStatusText), statusText); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -11032,10 +10889,9 @@ namespace Commands { namespace ChangeToMode { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNewMode), newMode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNewMode), newMode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -11067,11 +10923,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ChangeToModeResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatusText), statusText)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kStatusText), statusText); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -11147,10 +11002,9 @@ namespace Commands { namespace ChangeToMode { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNewMode), newMode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNewMode), newMode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -11182,11 +11036,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ChangeToModeResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatusText), statusText)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kStatusText), statusText); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -11261,11 +11114,10 @@ namespace Commands { namespace SetTemperature { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTargetTemperature), targetTemperature)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTargetTemperatureLevel), targetTemperatureLevel)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kTargetTemperature), targetTemperature); + encoder.Encode(to_underlying(Fields::kTargetTemperatureLevel), targetTemperatureLevel); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -11432,10 +11284,9 @@ namespace Commands { namespace ChangeToMode { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNewMode), newMode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNewMode), newMode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -11467,11 +11318,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ChangeToModeResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatusText), statusText)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kStatusText), statusText); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -11578,9 +11428,8 @@ namespace Commands { namespace SelfTestRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -11958,10 +11807,9 @@ namespace Commands { namespace Reset { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAlarms), alarms)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kAlarms), alarms); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -11993,10 +11841,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ModifyEnabledAlarms { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMask), mask)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMask), mask); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12119,9 +11966,8 @@ namespace Commands { namespace Pause { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12140,9 +11986,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Stop { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12161,9 +12006,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Start { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12182,9 +12026,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Resume { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12203,10 +12046,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace OperationalCommandResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCommandResponseState), commandResponseState)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCommandResponseState), commandResponseState); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12363,9 +12205,8 @@ namespace Commands { namespace Pause { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12384,9 +12225,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Stop { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12405,9 +12245,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Start { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12426,9 +12265,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Resume { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12447,10 +12285,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace OperationalCommandResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCommandResponseState), commandResponseState)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCommandResponseState), commandResponseState); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12602,15 +12439,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } // namespace RvcOperationalState namespace HepaFilterMonitoring { namespace Structs { + namespace ReplacementProductStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProductIdentifierType), productIdentifierType)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProductIdentifierValue), productIdentifierValue)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kProductIdentifierType), productIdentifierType); + encoder.Encode(to_underlying(Fields::kProductIdentifierValue), productIdentifierValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12650,9 +12486,8 @@ namespace Commands { namespace ResetCondition { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12710,15 +12545,14 @@ namespace Events {} // namespace Events } // namespace HepaFilterMonitoring namespace ActivatedCarbonFilterMonitoring { namespace Structs { + namespace ReplacementProductStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProductIdentifierType), productIdentifierType)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProductIdentifierValue), productIdentifierValue)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kProductIdentifierType), productIdentifierType); + encoder.Encode(to_underlying(Fields::kProductIdentifierValue), productIdentifierValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12758,9 +12592,8 @@ namespace Commands { namespace ResetCondition { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12818,15 +12651,14 @@ namespace Events {} // namespace Events } // namespace ActivatedCarbonFilterMonitoring namespace DoorLock { namespace Structs { + namespace CredentialStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredentialType), credentialType)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredentialIndex), credentialIndex)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCredentialType), credentialType); + encoder.Encode(to_underlying(Fields::kCredentialIndex), credentialIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12866,10 +12698,9 @@ namespace Commands { namespace LockDoor { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPINCode), PINCode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kPINCode), PINCode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12901,10 +12732,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace UnlockDoor { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPINCode), PINCode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kPINCode), PINCode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12936,11 +12766,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace UnlockWithTimeout { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTimeout), timeout)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPINCode), PINCode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kTimeout), timeout); + encoder.Encode(to_underlying(Fields::kPINCode), PINCode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -12976,16 +12805,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetWeekDaySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWeekDayIndex), weekDayIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDaysMask), daysMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStartHour), startHour)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStartMinute), startMinute)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndHour), endHour)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndMinute), endMinute)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kWeekDayIndex), weekDayIndex); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + encoder.Encode(to_underlying(Fields::kDaysMask), daysMask); + encoder.Encode(to_underlying(Fields::kStartHour), startHour); + encoder.Encode(to_underlying(Fields::kStartMinute), startMinute); + encoder.Encode(to_underlying(Fields::kEndHour), endHour); + encoder.Encode(to_underlying(Fields::kEndMinute), endMinute); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13041,11 +12869,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetWeekDaySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWeekDayIndex), weekDayIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kWeekDayIndex), weekDayIndex); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13081,17 +12908,16 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetWeekDayScheduleResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWeekDayIndex), weekDayIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDaysMask), daysMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStartHour), startHour)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStartMinute), startMinute)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndHour), endHour)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndMinute), endMinute)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kWeekDayIndex), weekDayIndex); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kDaysMask), daysMask); + encoder.Encode(to_underlying(Fields::kStartHour), startHour); + encoder.Encode(to_underlying(Fields::kStartMinute), startMinute); + encoder.Encode(to_underlying(Fields::kEndHour), endHour); + encoder.Encode(to_underlying(Fields::kEndMinute), endMinute); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13151,11 +12977,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ClearWeekDaySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWeekDayIndex), weekDayIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kWeekDayIndex), weekDayIndex); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13191,13 +13016,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetYearDaySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kYearDayIndex), yearDayIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLocalStartTime), localStartTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLocalEndTime), localEndTime)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kYearDayIndex), yearDayIndex); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + encoder.Encode(to_underlying(Fields::kLocalStartTime), localStartTime); + encoder.Encode(to_underlying(Fields::kLocalEndTime), localEndTime); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13241,11 +13065,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetYearDaySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kYearDayIndex), yearDayIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kYearDayIndex), yearDayIndex); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13281,14 +13104,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetYearDayScheduleResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kYearDayIndex), yearDayIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLocalStartTime), localStartTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLocalEndTime), localEndTime)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kYearDayIndex), yearDayIndex); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kLocalStartTime), localStartTime); + encoder.Encode(to_underlying(Fields::kLocalEndTime), localEndTime); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13336,11 +13158,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ClearYearDaySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kYearDayIndex), yearDayIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kYearDayIndex), yearDayIndex); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13376,13 +13197,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetHolidaySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kHolidayIndex), holidayIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLocalStartTime), localStartTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLocalEndTime), localEndTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOperatingMode), operatingMode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kHolidayIndex), holidayIndex); + encoder.Encode(to_underlying(Fields::kLocalStartTime), localStartTime); + encoder.Encode(to_underlying(Fields::kLocalEndTime), localEndTime); + encoder.Encode(to_underlying(Fields::kOperatingMode), operatingMode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13426,10 +13246,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetHolidaySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kHolidayIndex), holidayIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kHolidayIndex), holidayIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13461,14 +13280,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetHolidayScheduleResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kHolidayIndex), holidayIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLocalStartTime), localStartTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLocalEndTime), localEndTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOperatingMode), operatingMode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kHolidayIndex), holidayIndex); + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kLocalStartTime), localStartTime); + encoder.Encode(to_underlying(Fields::kLocalEndTime), localEndTime); + encoder.Encode(to_underlying(Fields::kOperatingMode), operatingMode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13516,10 +13334,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ClearHolidaySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kHolidayIndex), holidayIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kHolidayIndex), holidayIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13551,16 +13368,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetUser { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOperationType), operationType)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserName), userName)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserUniqueID), userUniqueID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserStatus), userStatus)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserType), userType)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredentialRule), credentialRule)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOperationType), operationType); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + encoder.Encode(to_underlying(Fields::kUserName), userName); + encoder.Encode(to_underlying(Fields::kUserUniqueID), userUniqueID); + encoder.Encode(to_underlying(Fields::kUserStatus), userStatus); + encoder.Encode(to_underlying(Fields::kUserType), userType); + encoder.Encode(to_underlying(Fields::kCredentialRule), credentialRule); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13616,10 +13432,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetUser { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13651,19 +13466,18 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetUserResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserName), userName)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserUniqueID), userUniqueID)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserStatus), userStatus)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserType), userType)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredentialRule), credentialRule)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredentials), credentials)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCreatorFabricIndex), creatorFabricIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLastModifiedFabricIndex), lastModifiedFabricIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNextUserIndex), nextUserIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + encoder.Encode(to_underlying(Fields::kUserName), userName); + encoder.Encode(to_underlying(Fields::kUserUniqueID), userUniqueID); + encoder.Encode(to_underlying(Fields::kUserStatus), userStatus); + encoder.Encode(to_underlying(Fields::kUserType), userType); + encoder.Encode(to_underlying(Fields::kCredentialRule), credentialRule); + encoder.Encode(to_underlying(Fields::kCredentials), credentials); + encoder.Encode(to_underlying(Fields::kCreatorFabricIndex), creatorFabricIndex); + encoder.Encode(to_underlying(Fields::kLastModifiedFabricIndex), lastModifiedFabricIndex); + encoder.Encode(to_underlying(Fields::kNextUserIndex), nextUserIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13731,10 +13545,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ClearUser { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13766,15 +13579,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetCredential { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOperationType), operationType)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredential), credential)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredentialData), credentialData)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserStatus), userStatus)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserType), userType)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOperationType), operationType); + encoder.Encode(to_underlying(Fields::kCredential), credential); + encoder.Encode(to_underlying(Fields::kCredentialData), credentialData); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + encoder.Encode(to_underlying(Fields::kUserStatus), userStatus); + encoder.Encode(to_underlying(Fields::kUserType), userType); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13826,12 +13638,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetCredentialResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNextCredentialIndex), nextCredentialIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + encoder.Encode(to_underlying(Fields::kNextCredentialIndex), nextCredentialIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13871,10 +13682,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetCredentialStatus { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredential), credential)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCredential), credential); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13906,14 +13716,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetCredentialStatusResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredentialExists), credentialExists)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUserIndex), userIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCreatorFabricIndex), creatorFabricIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLastModifiedFabricIndex), lastModifiedFabricIndex)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNextCredentialIndex), nextCredentialIndex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCredentialExists), credentialExists); + encoder.Encode(to_underlying(Fields::kUserIndex), userIndex); + encoder.Encode(to_underlying(Fields::kCreatorFabricIndex), creatorFabricIndex); + encoder.Encode(to_underlying(Fields::kLastModifiedFabricIndex), lastModifiedFabricIndex); + encoder.Encode(to_underlying(Fields::kNextCredentialIndex), nextCredentialIndex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13961,10 +13770,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ClearCredential { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCredential), credential)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCredential), credential); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -13996,10 +13804,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace UnboltDoor { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPINCode), PINCode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kPINCode), PINCode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -14395,9 +14202,8 @@ namespace Commands { namespace UpOrOpen { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -14416,9 +14222,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace DownOrClose { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -14437,9 +14242,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StopMotion { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -14458,10 +14262,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GoToLiftValue { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLiftValue), liftValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kLiftValue), liftValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -14493,10 +14296,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GoToLiftPercentage { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLiftPercent100thsValue), liftPercent100thsValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kLiftPercent100thsValue), liftPercent100thsValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -14528,10 +14330,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GoToTiltValue { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTiltValue), tiltValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kTiltValue), tiltValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -14563,10 +14364,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GoToTiltPercentage { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTiltPercent100thsValue), tiltPercent100thsValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kTiltPercent100thsValue), tiltPercent100thsValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -14673,10 +14473,9 @@ namespace Commands { namespace BarrierControlGoToPercent { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPercentOpen), percentOpen)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kPercentOpen), percentOpen); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -14708,9 +14507,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace BarrierControlStop { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15210,16 +15008,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } // namespace PumpConfigurationAndControl namespace Thermostat { namespace Structs { + namespace ThermostatScheduleTransition { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kHeatSetpoint), heatSetpoint)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCoolSetpoint), coolSetpoint)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kHeatSetpoint), heatSetpoint); + encoder.Encode(to_underlying(Fields::kCoolSetpoint), coolSetpoint); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15263,11 +15060,10 @@ namespace Commands { namespace SetpointRaiseLower { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMode), mode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAmount), amount)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMode), mode); + encoder.Encode(to_underlying(Fields::kAmount), amount); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15303,14 +15099,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetWeeklyScheduleResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNumberOfTransitionsForSequence), numberOfTransitionsForSequence)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDayOfWeekForSequence), dayOfWeekForSequence)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kModeForSequence), modeForSequence)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitions), transitions)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNumberOfTransitionsForSequence), numberOfTransitionsForSequence); + encoder.Encode(to_underlying(Fields::kDayOfWeekForSequence), dayOfWeekForSequence); + encoder.Encode(to_underlying(Fields::kModeForSequence), modeForSequence); + encoder.Encode(to_underlying(Fields::kTransitions), transitions); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15354,14 +15148,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SetWeeklySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNumberOfTransitionsForSequence), numberOfTransitionsForSequence)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDayOfWeekForSequence), dayOfWeekForSequence)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kModeForSequence), modeForSequence)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitions), transitions)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNumberOfTransitionsForSequence), numberOfTransitionsForSequence); + encoder.Encode(to_underlying(Fields::kDayOfWeekForSequence), dayOfWeekForSequence); + encoder.Encode(to_underlying(Fields::kModeForSequence), modeForSequence); + encoder.Encode(to_underlying(Fields::kTransitions), transitions); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15405,11 +15197,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetWeeklySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDaysToReturn), daysToReturn)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kModeToReturn), modeToReturn)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kDaysToReturn), daysToReturn); + encoder.Encode(to_underlying(Fields::kModeToReturn), modeToReturn); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15445,9 +15236,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ClearWeeklySchedule { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15595,12 +15385,11 @@ namespace Commands { namespace Step { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDirection), direction)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWrap), wrap)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLowestOff), lowestOff)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kDirection), direction); + encoder.Encode(to_underlying(Fields::kWrap), wrap); + encoder.Encode(to_underlying(Fields::kLowestOff), lowestOff); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15731,14 +15520,13 @@ namespace Commands { namespace MoveToHue { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kHue), hue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDirection), direction)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kHue), hue); + encoder.Encode(to_underlying(Fields::kDirection), direction); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15786,13 +15574,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveHue { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMoveMode), moveMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRate), rate)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMoveMode), moveMode); + encoder.Encode(to_underlying(Fields::kRate), rate); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15836,14 +15623,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StepHue { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepMode), stepMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepSize), stepSize)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStepMode), stepMode); + encoder.Encode(to_underlying(Fields::kStepSize), stepSize); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15891,13 +15677,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveToSaturation { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSaturation), saturation)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kSaturation), saturation); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15941,13 +15726,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveSaturation { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMoveMode), moveMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRate), rate)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMoveMode), moveMode); + encoder.Encode(to_underlying(Fields::kRate), rate); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -15991,14 +15775,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StepSaturation { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepMode), stepMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepSize), stepSize)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStepMode), stepMode); + encoder.Encode(to_underlying(Fields::kStepSize), stepSize); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16046,14 +15829,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveToHueAndSaturation { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kHue), hue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSaturation), saturation)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kHue), hue); + encoder.Encode(to_underlying(Fields::kSaturation), saturation); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16101,14 +15883,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveToColor { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kColorX), colorX)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kColorY), colorY)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kColorX), colorX); + encoder.Encode(to_underlying(Fields::kColorY), colorY); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16156,13 +15937,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveColor { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRateX), rateX)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRateY), rateY)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kRateX), rateX); + encoder.Encode(to_underlying(Fields::kRateY), rateY); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16206,14 +15986,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StepColor { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepX), stepX)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepY), stepY)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStepX), stepX); + encoder.Encode(to_underlying(Fields::kStepY), stepY); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16261,13 +16040,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveToColorTemperature { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kColorTemperatureMireds), colorTemperatureMireds)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kColorTemperatureMireds), colorTemperatureMireds); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16311,14 +16089,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace EnhancedMoveToHue { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEnhancedHue), enhancedHue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDirection), direction)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kEnhancedHue), enhancedHue); + encoder.Encode(to_underlying(Fields::kDirection), direction); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16366,13 +16143,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace EnhancedMoveHue { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMoveMode), moveMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRate), rate)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMoveMode), moveMode); + encoder.Encode(to_underlying(Fields::kRate), rate); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16416,14 +16192,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace EnhancedStepHue { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepMode), stepMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepSize), stepSize)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStepMode), stepMode); + encoder.Encode(to_underlying(Fields::kStepSize), stepSize); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16471,14 +16246,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace EnhancedMoveToHueAndSaturation { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEnhancedHue), enhancedHue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSaturation), saturation)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kEnhancedHue), enhancedHue); + encoder.Encode(to_underlying(Fields::kSaturation), saturation); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16526,16 +16300,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ColorLoopSet { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUpdateFlags), updateFlags)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAction), action)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDirection), direction)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTime), time)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStartHue), startHue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kUpdateFlags), updateFlags); + encoder.Encode(to_underlying(Fields::kAction), action); + encoder.Encode(to_underlying(Fields::kDirection), direction); + encoder.Encode(to_underlying(Fields::kTime), time); + encoder.Encode(to_underlying(Fields::kStartHue), startHue); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16591,11 +16364,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StopMoveStep { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16631,17 +16403,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace MoveColorTemperature { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMoveMode), moveMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kRate), rate)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kColorTemperatureMinimumMireds), colorTemperatureMinimumMireds)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kColorTemperatureMaximumMireds), colorTemperatureMaximumMireds)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMoveMode), moveMode); + encoder.Encode(to_underlying(Fields::kRate), rate); + encoder.Encode(to_underlying(Fields::kColorTemperatureMinimumMireds), colorTemperatureMinimumMireds); + encoder.Encode(to_underlying(Fields::kColorTemperatureMaximumMireds), colorTemperatureMaximumMireds); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -16693,18 +16462,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StepColorTemperature { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepMode), stepMode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStepSize), stepSize)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTransitionTime), transitionTime)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kColorTemperatureMinimumMireds), colorTemperatureMinimumMireds)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kColorTemperatureMaximumMireds), colorTemperatureMaximumMireds)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsMask), optionsMask)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionsOverride), optionsOverride)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStepMode), stepMode); + encoder.Encode(to_underlying(Fields::kStepSize), stepSize); + encoder.Encode(to_underlying(Fields::kTransitionTime), transitionTime); + encoder.Encode(to_underlying(Fields::kColorTemperatureMinimumMireds), colorTemperatureMinimumMireds); + encoder.Encode(to_underlying(Fields::kColorTemperatureMaximumMireds), colorTemperatureMaximumMireds); + encoder.Encode(to_underlying(Fields::kOptionsMask), optionsMask); + encoder.Encode(to_underlying(Fields::kOptionsOverride), optionsOverride); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -17757,18 +17523,17 @@ namespace Events {} // namespace Events } // namespace WakeOnLan namespace Channel { namespace Structs { + namespace ChannelInfoStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMajorNumber), majorNumber)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMinorNumber), minorNumber)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCallSign), callSign)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAffiliateCallSign), affiliateCallSign)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMajorNumber), majorNumber); + encoder.Encode(to_underlying(Fields::kMinorNumber), minorNumber); + encoder.Encode(to_underlying(Fields::kName), name); + encoder.Encode(to_underlying(Fields::kCallSign), callSign); + encoder.Encode(to_underlying(Fields::kAffiliateCallSign), affiliateCallSign); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -17814,17 +17579,16 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace ChannelInfoStruct + namespace LineupInfoStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOperatorName), operatorName)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLineupName), lineupName)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPostalCode), postalCode)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLineupInfoType), lineupInfoType)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kOperatorName), operatorName); + encoder.Encode(to_underlying(Fields::kLineupName), lineupName); + encoder.Encode(to_underlying(Fields::kPostalCode), postalCode); + encoder.Encode(to_underlying(Fields::kLineupInfoType), lineupInfoType); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -17872,10 +17636,9 @@ namespace Commands { namespace ChangeChannel { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMatch), match)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMatch), match); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -17907,11 +17670,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ChangeChannelResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kData), data)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kData), data); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -17947,11 +17709,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ChangeChannelByNumber { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMajorNumber), majorNumber)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMinorNumber), minorNumber)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMajorNumber), majorNumber); + encoder.Encode(to_underlying(Fields::kMinorNumber), minorNumber); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -17987,10 +17748,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SkipChannel { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kCount), count)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kCount), count); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18055,15 +17815,14 @@ namespace Events {} // namespace Events } // namespace Channel namespace TargetNavigator { namespace Structs { + namespace TargetInfoStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIdentifier), identifier)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kIdentifier), identifier); + encoder.Encode(to_underlying(Fields::kName), name); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18103,11 +17862,10 @@ namespace Commands { namespace NavigateTarget { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTarget), target)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kData), data)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kTarget), target); + encoder.Encode(to_underlying(Fields::kData), data); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18143,11 +17901,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace NavigateTargetResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kData), data)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kData), data); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18214,15 +17971,14 @@ namespace Events {} // namespace Events } // namespace TargetNavigator namespace MediaPlayback { namespace Structs { + namespace PlaybackPositionStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kUpdatedAt), updatedAt)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPosition), position)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kUpdatedAt), updatedAt); + encoder.Encode(to_underlying(Fields::kPosition), position); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18262,9 +18018,8 @@ namespace Commands { namespace Play { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18283,9 +18038,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Pause { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18304,9 +18058,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Stop { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18325,9 +18078,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StartOver { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18346,9 +18098,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Previous { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18367,9 +18118,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Next { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18388,9 +18138,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Rewind { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18409,9 +18158,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace FastForward { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18430,11 +18178,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SkipForward { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDeltaPositionMilliseconds), deltaPositionMilliseconds)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kDeltaPositionMilliseconds), deltaPositionMilliseconds); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18466,11 +18212,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SkipBackward { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDeltaPositionMilliseconds), deltaPositionMilliseconds)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kDeltaPositionMilliseconds), deltaPositionMilliseconds); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18502,11 +18246,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace PlaybackResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kData), data)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kData), data); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18542,10 +18285,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Seek { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPosition), position)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kPosition), position); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18618,17 +18360,16 @@ namespace Events {} // namespace Events } // namespace MediaPlayback namespace MediaInput { namespace Structs { + namespace InputInfoStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIndex), index)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kInputType), inputType)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDescription), description)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kIndex), index); + encoder.Encode(to_underlying(Fields::kInputType), inputType); + encoder.Encode(to_underlying(Fields::kName), name); + encoder.Encode(to_underlying(Fields::kDescription), description); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18676,10 +18417,9 @@ namespace Commands { namespace SelectInput { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIndex), index)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kIndex), index); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18711,9 +18451,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace ShowInputStatus { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18732,9 +18471,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace HideInputStatus { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18753,11 +18491,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RenameInput { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIndex), index)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kIndex), index); + encoder.Encode(to_underlying(Fields::kName), name); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18828,9 +18565,8 @@ namespace Commands { namespace Sleep { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18880,10 +18616,9 @@ namespace Commands { namespace SendKey { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kKeyCode), keyCode)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kKeyCode), keyCode); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18915,10 +18650,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SendKeyResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -18977,16 +18711,15 @@ namespace Events {} // namespace Events } // namespace KeypadInput namespace ContentLauncher { namespace Structs { + namespace DimensionStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWidth), width)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kHeight), height)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMetric), metric)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kWidth), width); + encoder.Encode(to_underlying(Fields::kHeight), height); + encoder.Encode(to_underlying(Fields::kMetric), metric); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19024,15 +18757,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace DimensionStruct + namespace AdditionalInfoStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValue), value)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kName), name); + encoder.Encode(to_underlying(Fields::kValue), value); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19066,16 +18798,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace AdditionalInfoStruct + namespace ParameterStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kType), type)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValue), value)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kExternalIDList), externalIDList)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kType), type); + encoder.Encode(to_underlying(Fields::kValue), value); + encoder.Encode(to_underlying(Fields::kExternalIDList), externalIDList); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19113,14 +18844,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace ParameterStruct + namespace ContentSearchStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kParameterList), parameterList)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kParameterList), parameterList); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19150,16 +18880,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace ContentSearchStruct + namespace StyleInformationStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kImageURL), imageURL)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kColor), color)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSize), size)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kImageURL), imageURL); + encoder.Encode(to_underlying(Fields::kColor), color); + encoder.Encode(to_underlying(Fields::kSize), size); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19197,19 +18926,18 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace StyleInformationStruct + namespace BrandingInformationStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProviderName), providerName)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBackground), background)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kLogo), logo)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProgressBar), progressBar)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSplash), splash)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWaterMark), waterMark)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kProviderName), providerName); + encoder.Encode(to_underlying(Fields::kBackground), background); + encoder.Encode(to_underlying(Fields::kLogo), logo); + encoder.Encode(to_underlying(Fields::kProgressBar), progressBar); + encoder.Encode(to_underlying(Fields::kSplash), splash); + encoder.Encode(to_underlying(Fields::kWaterMark), waterMark); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19265,12 +18993,11 @@ namespace Commands { namespace LaunchContent { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSearch), search)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAutoPlay), autoPlay)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kData), data)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kSearch), search); + encoder.Encode(to_underlying(Fields::kAutoPlay), autoPlay); + encoder.Encode(to_underlying(Fields::kData), data); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19310,12 +19037,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace LaunchURL { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kContentURL), contentURL)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kDisplayString), displayString)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kBrandingInformation), brandingInformation)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kContentURL), contentURL); + encoder.Encode(to_underlying(Fields::kDisplayString), displayString); + encoder.Encode(to_underlying(Fields::kBrandingInformation), brandingInformation); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19355,11 +19081,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace LauncherResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kData), data)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kData), data); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19426,16 +19151,15 @@ namespace Events {} // namespace Events } // namespace ContentLauncher namespace AudioOutput { namespace Structs { + namespace OutputInfoStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIndex), index)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOutputType), outputType)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kIndex), index); + encoder.Encode(to_underlying(Fields::kOutputType), outputType); + encoder.Encode(to_underlying(Fields::kName), name); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19479,10 +19203,9 @@ namespace Commands { namespace SelectOutput { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIndex), index)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kIndex), index); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19514,11 +19237,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace RenameOutput { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIndex), index)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kName), name)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kIndex), index); + encoder.Encode(to_underlying(Fields::kName), name); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19585,15 +19307,14 @@ namespace Events {} // namespace Events } // namespace AudioOutput namespace ApplicationLauncher { namespace Structs { + namespace ApplicationEPStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kApplication), application)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kEndpoint), endpoint)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kApplication), application); + encoder.Encode(to_underlying(Fields::kEndpoint), endpoint); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19633,11 +19354,10 @@ namespace Commands { namespace LaunchApp { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kApplication), application)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kData), data)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kApplication), application); + encoder.Encode(to_underlying(Fields::kData), data); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19673,10 +19393,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace StopApp { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kApplication), application)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kApplication), application); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19708,10 +19427,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace HideApp { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kApplication), application)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kApplication), application); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19743,11 +19461,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace LauncherResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kData), data)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kData), data); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19865,10 +19582,9 @@ namespace Commands { namespace GetSetupPIN { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTempAccountIdentifier), tempAccountIdentifier)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kTempAccountIdentifier), tempAccountIdentifier); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19900,10 +19616,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetSetupPINResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSetupPIN), setupPIN)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kSetupPIN), setupPIN); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19935,11 +19650,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Login { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTempAccountIdentifier), tempAccountIdentifier)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kSetupPIN), setupPIN)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kTempAccountIdentifier), tempAccountIdentifier); + encoder.Encode(to_underlying(Fields::kSetupPIN), setupPIN); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -19975,9 +19689,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace Logout { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20027,13 +19740,12 @@ namespace Commands { namespace GetProfileInfoResponseCommand { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProfileCount), profileCount)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProfileIntervalPeriod), profileIntervalPeriod)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMaxNumberOfIntervals), maxNumberOfIntervals)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kListOfAttributes), listOfAttributes)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kProfileCount), profileCount); + encoder.Encode(to_underlying(Fields::kProfileIntervalPeriod), profileIntervalPeriod); + encoder.Encode(to_underlying(Fields::kMaxNumberOfIntervals), maxNumberOfIntervals); + encoder.Encode(to_underlying(Fields::kListOfAttributes), listOfAttributes); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20077,9 +19789,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetProfileInfoCommand { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20098,16 +19809,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetMeasurementProfileResponseCommand { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStartTime), startTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStatus), status)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kProfileIntervalPeriod), profileIntervalPeriod)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNumberOfIntervalsDelivered), numberOfIntervalsDelivered)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAttributeId), attributeId)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kIntervals), intervals)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kStartTime), startTime); + encoder.Encode(to_underlying(Fields::kStatus), status); + encoder.Encode(to_underlying(Fields::kProfileIntervalPeriod), profileIntervalPeriod); + encoder.Encode(to_underlying(Fields::kNumberOfIntervalsDelivered), numberOfIntervalsDelivered); + encoder.Encode(to_underlying(Fields::kAttributeId), attributeId); + encoder.Encode(to_underlying(Fields::kIntervals), intervals); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20159,12 +19868,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace GetMeasurementProfileCommand { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kAttributeId), attributeId)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kStartTime), startTime)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNumberOfIntervals), numberOfIntervals)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kAttributeId), attributeId); + encoder.Encode(to_underlying(Fields::kStartTime), startTime); + encoder.Encode(to_underlying(Fields::kNumberOfIntervals), numberOfIntervals); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20487,21 +20195,20 @@ namespace Events {} // namespace Events } // namespace ElectricalMeasurement namespace UnitTesting { namespace Structs { + namespace SimpleStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kA), a)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kB), b)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kC), c)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kD), d)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kE), e)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kF), f)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kG), g)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kH), h)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kA), a); + encoder.Encode(to_underlying(Fields::kB), b); + encoder.Encode(to_underlying(Fields::kC), c); + encoder.Encode(to_underlying(Fields::kD), d); + encoder.Encode(to_underlying(Fields::kE), e); + encoder.Encode(to_underlying(Fields::kF), f); + encoder.Encode(to_underlying(Fields::kG), g); + encoder.Encode(to_underlying(Fields::kH), h); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20559,6 +20266,7 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace SimpleStruct + namespace TestFabricScoped { CHIP_ERROR Type::EncodeForWrite(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { @@ -20573,47 +20281,43 @@ CHIP_ERROR Type::EncodeForRead(TLV::TLVWriter & aWriter, TLV::Tag aTag, FabricIn CHIP_ERROR Type::DoEncode(TLV::TLVWriter & aWriter, TLV::Tag aTag, const Optional & aAccessingFabricIndex) const { bool includeSensitive = !aAccessingFabricIndex.HasValue() || (aAccessingFabricIndex.Value() == fabricIndex); - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); + + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricSensitiveInt8u), fabricSensitiveInt8u)); + encoder.Encode(to_underlying(Fields::kFabricSensitiveInt8u), fabricSensitiveInt8u); } if (includeSensitive) { - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalFabricSensitiveInt8u), optionalFabricSensitiveInt8u)); + encoder.Encode(to_underlying(Fields::kOptionalFabricSensitiveInt8u), optionalFabricSensitiveInt8u); } if (includeSensitive) { - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableFabricSensitiveInt8u), nullableFabricSensitiveInt8u)); + encoder.Encode(to_underlying(Fields::kNullableFabricSensitiveInt8u), nullableFabricSensitiveInt8u); } if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalFabricSensitiveInt8u), - nullableOptionalFabricSensitiveInt8u)); + encoder.Encode(to_underlying(Fields::kNullableOptionalFabricSensitiveInt8u), nullableOptionalFabricSensitiveInt8u); } if (includeSensitive) { - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricSensitiveCharString), fabricSensitiveCharString)); + encoder.Encode(to_underlying(Fields::kFabricSensitiveCharString), fabricSensitiveCharString); } if (includeSensitive) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricSensitiveStruct), fabricSensitiveStruct)); + encoder.Encode(to_underlying(Fields::kFabricSensitiveStruct), fabricSensitiveStruct); } if (includeSensitive) { - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricSensitiveInt8uList), fabricSensitiveInt8uList)); + encoder.Encode(to_underlying(Fields::kFabricSensitiveInt8uList), fabricSensitiveInt8uList); } if (aAccessingFabricIndex.HasValue()) { - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kFabricIndex), fabricIndex)); + encoder.Encode(to_underlying(Fields::kFabricIndex), fabricIndex); } - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20671,25 +20375,24 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace TestFabricScoped + namespace NullablesAndOptionalsStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableInt), nullableInt)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalInt), optionalInt)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalInt), nullableOptionalInt)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableString), nullableString)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalString), optionalString)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalString), nullableOptionalString)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableStruct), nullableStruct)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalStruct), optionalStruct)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalStruct), nullableOptionalStruct)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableList), nullableList)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalList), optionalList)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalList), nullableOptionalList)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNullableInt), nullableInt); + encoder.Encode(to_underlying(Fields::kOptionalInt), optionalInt); + encoder.Encode(to_underlying(Fields::kNullableOptionalInt), nullableOptionalInt); + encoder.Encode(to_underlying(Fields::kNullableString), nullableString); + encoder.Encode(to_underlying(Fields::kOptionalString), optionalString); + encoder.Encode(to_underlying(Fields::kNullableOptionalString), nullableOptionalString); + encoder.Encode(to_underlying(Fields::kNullableStruct), nullableStruct); + encoder.Encode(to_underlying(Fields::kOptionalStruct), optionalStruct); + encoder.Encode(to_underlying(Fields::kNullableOptionalStruct), nullableOptionalStruct); + encoder.Encode(to_underlying(Fields::kNullableList), nullableList); + encoder.Encode(to_underlying(Fields::kOptionalList), optionalList); + encoder.Encode(to_underlying(Fields::kNullableOptionalList), nullableOptionalList); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20763,16 +20466,15 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace NullablesAndOptionalsStruct + namespace NestedStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kA), a)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kB), b)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kC), c)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kA), a); + encoder.Encode(to_underlying(Fields::kB), b); + encoder.Encode(to_underlying(Fields::kC), c); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20810,20 +20512,19 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace NestedStruct + namespace NestedStructList { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kA), a)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kB), b)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kC), c)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kD), d)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kE), e)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kF), f)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kG), g)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kA), a); + encoder.Encode(to_underlying(Fields::kB), b); + encoder.Encode(to_underlying(Fields::kC), c); + encoder.Encode(to_underlying(Fields::kD), d); + encoder.Encode(to_underlying(Fields::kE), e); + encoder.Encode(to_underlying(Fields::kF), f); + encoder.Encode(to_underlying(Fields::kG), g); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20877,14 +20578,13 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace NestedStructList + namespace DoubleNestedStructList { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kA), a)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kA), a); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20914,15 +20614,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } // namespace DoubleNestedStructList + namespace TestListStructOctet { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMember1), member1)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kMember2), member2)); - ReturnErrorOnFailure(aWriter.EndContainer(outer)); - return CHIP_NO_ERROR; + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kMember1), member1); + encoder.Encode(to_underlying(Fields::kMember2), member2); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20962,9 +20661,8 @@ namespace Commands { namespace Test { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -20983,10 +20681,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestSpecificResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kReturnValue), returnValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kReturnValue), returnValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21018,9 +20715,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestNotHandled { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21039,10 +20735,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestAddArgumentsResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kReturnValue), returnValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kReturnValue), returnValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21074,9 +20769,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestSpecific { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21095,10 +20789,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestSimpleArgumentResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kReturnValue), returnValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kReturnValue), returnValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21130,9 +20823,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestUnknownCommand { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21151,15 +20843,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestStructArrayArgumentResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg2), arg2)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg3), arg3)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg4), arg4)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg5), arg5)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg6), arg6)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + encoder.Encode(to_underlying(Fields::kArg2), arg2); + encoder.Encode(to_underlying(Fields::kArg3), arg3); + encoder.Encode(to_underlying(Fields::kArg4), arg4); + encoder.Encode(to_underlying(Fields::kArg5), arg5); + encoder.Encode(to_underlying(Fields::kArg6), arg6); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21211,11 +20902,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestAddArguments { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg2), arg2)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + encoder.Encode(to_underlying(Fields::kArg2), arg2); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21251,10 +20941,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestListInt8UReverseResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21286,10 +20975,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestSimpleArgumentRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21321,11 +21009,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestEnumsResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg2), arg2)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + encoder.Encode(to_underlying(Fields::kArg2), arg2); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21361,15 +21048,14 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestStructArrayArgumentRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg2), arg2)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg3), arg3)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg4), arg4)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg5), arg5)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg6), arg6)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + encoder.Encode(to_underlying(Fields::kArg2), arg2); + encoder.Encode(to_underlying(Fields::kArg3), arg3); + encoder.Encode(to_underlying(Fields::kArg4), arg4); + encoder.Encode(to_underlying(Fields::kArg5), arg5); + encoder.Encode(to_underlying(Fields::kArg6), arg6); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21421,13 +21107,12 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestNullableOptionalResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWasPresent), wasPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kWasNull), wasNull)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValue), value)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOriginalValue), originalValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kWasPresent), wasPresent); + encoder.Encode(to_underlying(Fields::kWasNull), wasNull); + encoder.Encode(to_underlying(Fields::kValue), value); + encoder.Encode(to_underlying(Fields::kOriginalValue), originalValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21471,10 +21156,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestStructArgumentRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21506,48 +21190,36 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestComplexNullableOptionalResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableIntWasNull), nullableIntWasNull)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableIntValue), nullableIntValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalIntWasPresent), optionalIntWasPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalIntValue), optionalIntValue)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalIntWasPresent), nullableOptionalIntWasPresent)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalIntWasNull), nullableOptionalIntWasNull)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalIntValue), nullableOptionalIntValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableStringWasNull), nullableStringWasNull)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableStringValue), nullableStringValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalStringWasPresent), optionalStringWasPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalStringValue), optionalStringValue)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalStringWasPresent), nullableOptionalStringWasPresent)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalStringWasNull), nullableOptionalStringWasNull)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalStringValue), nullableOptionalStringValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableStructWasNull), nullableStructWasNull)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableStructValue), nullableStructValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalStructWasPresent), optionalStructWasPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalStructValue), optionalStructValue)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalStructWasPresent), nullableOptionalStructWasPresent)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalStructWasNull), nullableOptionalStructWasNull)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalStructValue), nullableOptionalStructValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableListWasNull), nullableListWasNull)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableListValue), nullableListValue)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalListWasPresent), optionalListWasPresent)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalListValue), optionalListValue)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalListWasPresent), nullableOptionalListWasPresent)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalListWasNull), nullableOptionalListWasNull)); - ReturnErrorOnFailure( - DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalListValue), nullableOptionalListValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNullableIntWasNull), nullableIntWasNull); + encoder.Encode(to_underlying(Fields::kNullableIntValue), nullableIntValue); + encoder.Encode(to_underlying(Fields::kOptionalIntWasPresent), optionalIntWasPresent); + encoder.Encode(to_underlying(Fields::kOptionalIntValue), optionalIntValue); + encoder.Encode(to_underlying(Fields::kNullableOptionalIntWasPresent), nullableOptionalIntWasPresent); + encoder.Encode(to_underlying(Fields::kNullableOptionalIntWasNull), nullableOptionalIntWasNull); + encoder.Encode(to_underlying(Fields::kNullableOptionalIntValue), nullableOptionalIntValue); + encoder.Encode(to_underlying(Fields::kNullableStringWasNull), nullableStringWasNull); + encoder.Encode(to_underlying(Fields::kNullableStringValue), nullableStringValue); + encoder.Encode(to_underlying(Fields::kOptionalStringWasPresent), optionalStringWasPresent); + encoder.Encode(to_underlying(Fields::kOptionalStringValue), optionalStringValue); + encoder.Encode(to_underlying(Fields::kNullableOptionalStringWasPresent), nullableOptionalStringWasPresent); + encoder.Encode(to_underlying(Fields::kNullableOptionalStringWasNull), nullableOptionalStringWasNull); + encoder.Encode(to_underlying(Fields::kNullableOptionalStringValue), nullableOptionalStringValue); + encoder.Encode(to_underlying(Fields::kNullableStructWasNull), nullableStructWasNull); + encoder.Encode(to_underlying(Fields::kNullableStructValue), nullableStructValue); + encoder.Encode(to_underlying(Fields::kOptionalStructWasPresent), optionalStructWasPresent); + encoder.Encode(to_underlying(Fields::kOptionalStructValue), optionalStructValue); + encoder.Encode(to_underlying(Fields::kNullableOptionalStructWasPresent), nullableOptionalStructWasPresent); + encoder.Encode(to_underlying(Fields::kNullableOptionalStructWasNull), nullableOptionalStructWasNull); + encoder.Encode(to_underlying(Fields::kNullableOptionalStructValue), nullableOptionalStructValue); + encoder.Encode(to_underlying(Fields::kNullableListWasNull), nullableListWasNull); + encoder.Encode(to_underlying(Fields::kNullableListValue), nullableListValue); + encoder.Encode(to_underlying(Fields::kOptionalListWasPresent), optionalListWasPresent); + encoder.Encode(to_underlying(Fields::kOptionalListValue), optionalListValue); + encoder.Encode(to_underlying(Fields::kNullableOptionalListWasPresent), nullableOptionalListWasPresent); + encoder.Encode(to_underlying(Fields::kNullableOptionalListWasNull), nullableOptionalListWasNull); + encoder.Encode(to_underlying(Fields::kNullableOptionalListValue), nullableOptionalListValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21687,10 +21359,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestNestedStructArgumentRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21722,10 +21393,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace BooleanResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValue), value)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kValue), value); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21757,10 +21427,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestListStructArgumentRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21792,10 +21461,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SimpleStructResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21827,10 +21495,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestListInt8UArgumentRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21862,10 +21529,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestEmitTestEventResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValue), value)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kValue), value); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21897,10 +21563,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestNestedStructListArgumentRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21932,10 +21597,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestEmitTestFabricScopedEventResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kValue), value)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kValue), value); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -21967,10 +21631,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestListNestedStructListArgumentRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22002,10 +21665,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestListInt8UReverseRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22037,11 +21699,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestEnumsRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg2), arg2)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + encoder.Encode(to_underlying(Fields::kArg2), arg2); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22077,10 +21738,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestNullableOptionalRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22112,21 +21772,20 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestComplexNullableOptionalRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableInt), nullableInt)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalInt), optionalInt)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalInt), nullableOptionalInt)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableString), nullableString)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalString), optionalString)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalString), nullableOptionalString)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableStruct), nullableStruct)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalStruct), optionalStruct)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalStruct), nullableOptionalStruct)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableList), nullableList)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kOptionalList), optionalList)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNullableOptionalList), nullableOptionalList)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kNullableInt), nullableInt); + encoder.Encode(to_underlying(Fields::kOptionalInt), optionalInt); + encoder.Encode(to_underlying(Fields::kNullableOptionalInt), nullableOptionalInt); + encoder.Encode(to_underlying(Fields::kNullableString), nullableString); + encoder.Encode(to_underlying(Fields::kOptionalString), optionalString); + encoder.Encode(to_underlying(Fields::kNullableOptionalString), nullableOptionalString); + encoder.Encode(to_underlying(Fields::kNullableStruct), nullableStruct); + encoder.Encode(to_underlying(Fields::kOptionalStruct), optionalStruct); + encoder.Encode(to_underlying(Fields::kNullableOptionalStruct), nullableOptionalStruct); + encoder.Encode(to_underlying(Fields::kNullableList), nullableList); + encoder.Encode(to_underlying(Fields::kOptionalList), optionalList); + encoder.Encode(to_underlying(Fields::kNullableOptionalList), nullableOptionalList); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22202,10 +21861,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace SimpleStructEchoRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22237,9 +21895,8 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TimedInvokeRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22258,10 +21915,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestSimpleOptionalArgumentRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22293,12 +21949,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestEmitTestEventRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg2), arg2)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg3), arg3)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + encoder.Encode(to_underlying(Fields::kArg2), arg2); + encoder.Encode(to_underlying(Fields::kArg3), arg3); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22338,10 +21993,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace TestEmitTestFabricScopedEventRequest { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22664,14 +22318,13 @@ namespace Commands { namespace FailAtFault { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kType), type)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kId), id)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNumCallsToSkip), numCallsToSkip)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kNumCallsToFail), numCallsToFail)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kTakeMutex), takeMutex)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kType), type); + encoder.Encode(to_underlying(Fields::kId), id); + encoder.Encode(to_underlying(Fields::kNumCallsToSkip), numCallsToSkip); + encoder.Encode(to_underlying(Fields::kNumCallsToFail), numCallsToFail); + encoder.Encode(to_underlying(Fields::kTakeMutex), takeMutex); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22719,12 +22372,11 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace FailRandomlyAtFault { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kType), type)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kId), id)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kPercentage), percentage)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kType), type); + encoder.Encode(to_underlying(Fields::kId), id); + encoder.Encode(to_underlying(Fields::kPercentage), percentage); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22795,9 +22447,8 @@ namespace Commands { namespace Ping { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22816,10 +22467,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace AddArgumentsResponse { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kReturnValue), returnValue)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kReturnValue), returnValue); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) @@ -22851,11 +22501,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) namespace AddArguments { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { - TLV::TLVType outer; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outer)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg1), arg1)); - ReturnErrorOnFailure(DataModel::Encode(aWriter, TLV::ContextTag(Fields::kArg2), arg2)); - return aWriter.EndContainer(outer); + DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; + encoder.Encode(to_underlying(Fields::kArg1), arg1); + encoder.Encode(to_underlying(Fields::kArg2), arg2); + return encoder.Finalize(); } CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) From f34b13cd861dae644d6c08ba20440de30c151bb8 Mon Sep 17 00:00:00 2001 From: mkardous-silabs <84793247+mkardous-silabs@users.noreply.github.com> Date: Sat, 7 Oct 2023 02:57:15 -0400 Subject: [PATCH 21/21] remove minimum reqs (#29620) --- .../zcl/data-model/chip/icd-management-cluster.xml | 4 ++-- src/python_testing/TC_ICDM_2_1.py | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/app/zap-templates/zcl/data-model/chip/icd-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/icd-management-cluster.xml index 6c0d73d166aeef..2377c77a243df2 100644 --- a/src/app/zap-templates/zcl/data-model/chip/icd-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/icd-management-cluster.xml @@ -43,8 +43,8 @@ limitations under the License. IdleModeInterval - ActiveModeInterval - ActiveModeThreshold + ActiveModeInterval + ActiveModeThreshold RegisteredClients diff --git a/src/python_testing/TC_ICDM_2_1.py b/src/python_testing/TC_ICDM_2_1.py index 97d20fca723837..808a53403ebd88 100644 --- a/src/python_testing/TC_ICDM_2_1.py +++ b/src/python_testing/TC_ICDM_2_1.py @@ -51,8 +51,8 @@ async def test_TC_ICDM_2_1(self): idleModeInterval *= 1000 # Convert seconds to milliseconds activeModeInterval = await self.read_icdm_attribute_expect_success(endpoint=endpoint, attribute=attributes.ActiveModeInterval) - asserts.assert_greater_equal(activeModeInterval, 300, - "ActiveModeInterval attribute is smaller than minimum value (300).") + asserts.assert_true(0 <= activeModeInterval <= 65535, + "ActiveModeInterval attribute does not fit in a uint16.") asserts.assert_less_equal(activeModeInterval, idleModeInterval, "ActiveModeInterval attribute is greater than the IdleModeInterval attrbiute.") else: @@ -64,8 +64,8 @@ async def test_TC_ICDM_2_1(self): activeModeThreshold = await self.read_icdm_attribute_expect_success(endpoint=endpoint, attribute=attributes.ActiveModeThreshold) - asserts.assert_greater_equal(activeModeThreshold, 300, - "ActiveModeThreshold attribute is smaller than minimum value (300).") + asserts.assert_true(0 <= activeModeThreshold <= 65535, + "ActiveModeThreshold attribute does not fit in a uint16.") else: asserts.assert_true(False, "ActiveModeThreshold is a mandatory attribute and must be present in the PICS file")