[Realtek] Add support for Zephyr OS (#39894)
* [Realtek] Add config files for realtek zephyr
* [Realtek] Add platform files for realtek zephyr
* [Realtek] Add lighting app for realtek zephyr
* [Realtek] Restyle files
* [Realtek] Fix code static check issue
* [Realtek] Fix code static check issue
* [Realtek] Update overlay for entropy configuration
* [Realtek] Add Realtek platform support to labeler and CODEOWNERS
* [Realtek] Optimise platform files
* [Realtek] Support compile with build_examples.py for zephyr os
* [Realtek] Fix conflict
* [Realtek] Fix build issue & update README
* [Realtek] Optimize build script
diff --git a/.github/labeler.yml b/.github/labeler.yml
index 81a8346..b05131e 100644
--- a/.github/labeler.yml
+++ b/.github/labeler.yml
@@ -353,3 +353,11 @@
- src/platform/Tizen/**/*
- src/test_driver/tizen/*
- src/test_driver/tizen/**/*
+
+realtek:
+ - changed-files:
+ - any-glob-to-any-file:
+ - examples/platform/realtek/*
+ - examples/platform/realtek/**/*
+ - src/platform/realtek/*
+ - src/platform/realtek/**/*
diff --git a/CODEOWNERS b/CODEOWNERS
index 852f05c..3e46d39 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -5,6 +5,9 @@
/src/platform/Ameba/ @pankore
ameba/ @pankore
chip-build-ameba/ @pankore
+/src/platform/realtek/ @pankore
+realtek/ @pankore
+chip-build-realtek/ @pankore
/src/platform/Beken/ @zhengyaohan
diff --git a/config/realtek/app/bootloader.conf b/config/realtek/app/bootloader.conf
new file mode 100644
index 0000000..bd2aac1
--- /dev/null
+++ b/config/realtek/app/bootloader.conf
@@ -0,0 +1,44 @@
+#
+# 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.
+#
+
+# Enable this option in case if restoring the slot0 partition is expected from slot1
+# partition in case if slot0 is not bootable or damaged
+CONFIG_BOOT_BOOTSTRAP=y
+
+# Enable this option in case if SWAP_MOVE logic need to be used
+CONFIG_BOOT_SWAP_USING_MOVE=y
+
+# Enable this option in case if SWAP_MOVE using scratch logic need to be used
+# Enabling this option expecting the availability of scratch partition in DTS
+CONFIG_BOOT_SWAP_USING_SCRATCH=n
+
+# Enable this option in case if the whole slot0 image need to be validated
+# With disabled option the only image magic is validated
+CONFIG_BOOT_VALIDATE_SLOT0=y
+
+# Maximum number of image sectors supported by the bootloader.
+CONFIG_BOOT_MAX_IMG_SECTORS=4096
+
+# Sets log level for modules which don't specify it explicitly.
+# When set to 0 it means log will not be activated for those modules.
+# Levels are:
+# - 0 OFF, do not write by default
+# - 1 ERROR, default to only write LOG_LEVEL_ERR
+# - 2 WARNING, default to write LOG_LEVEL_WRN
+# - 3 INFO, default to write LOG_LEVEL_INFO
+# - 4 DEBUG, default to write LOG_LEVEL_DBG
+CONFIG_LOG_DEFAULT_LEVEL=1
+
diff --git a/config/realtek/app/enable-gnu-std.cmake b/config/realtek/app/enable-gnu-std.cmake
new file mode 100644
index 0000000..b165900
--- /dev/null
+++ b/config/realtek/app/enable-gnu-std.cmake
@@ -0,0 +1,19 @@
+#
+# Copyright (c) 2021 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.
+#
+
+add_library(gnu17 INTERFACE)
+target_compile_options(gnu17 INTERFACE $<$<COMPILE_LANGUAGE:CXX>:-std=gnu++17> $<$<COMPILE_LANGUAGE:CXX>:-Wno-register> -D_DEFAULT_SOURCE)
+target_link_libraries(app PRIVATE gnu17)
diff --git a/config/realtek/chip-gn/.gn b/config/realtek/chip-gn/.gn
new file mode 100644
index 0000000..694b67e
--- /dev/null
+++ b/config/realtek/chip-gn/.gn
@@ -0,0 +1,29 @@
+# Copyright (c) 2021 Project CHIP Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import("//build_overrides/build.gni")
+import("//build_overrides/chip.gni")
+
+# The location of the build configuration file.
+buildconfig = "${build_root}/config/BUILDCONFIG.gn"
+
+# CHIP uses angle bracket includes.
+check_system_includes = true
+
+default_args = {
+ target_cpu = "arm"
+ target_os = "zephyr"
+
+ import("${chip_root}/config/realtek/chip-gn/args.gni")
+}
diff --git a/config/realtek/chip-gn/BUILD.gn b/config/realtek/chip-gn/BUILD.gn
new file mode 100644
index 0000000..cccf81c
--- /dev/null
+++ b/config/realtek/chip-gn/BUILD.gn
@@ -0,0 +1,40 @@
+# Copyright (c) 2022 Project CHIP Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import("//build_overrides/build.gni")
+import("//build_overrides/chip.gni")
+
+import("${chip_root}/build/chip/tests.gni")
+
+assert(current_os == "zephyr")
+
+declare_args() {
+ chip_build_example_providers = false
+}
+
+group("realtek_zephyr") {
+ deps = [ "${chip_root}/src/lib" ]
+
+ if (chip_build_tests) {
+ deps += [ "${chip_root}/src:tests" ]
+ }
+
+ if (chip_build_example_providers) {
+ deps += [ "${chip_root}/examples/providers:device_info_provider_please_do_not_reuse_as_is" ]
+ }
+}
+
+group("default") {
+ deps = [ ":realtek_zephyr" ]
+}
diff --git a/config/realtek/chip-gn/args.gni b/config/realtek/chip-gn/args.gni
new file mode 100644
index 0000000..33e4e22
--- /dev/null
+++ b/config/realtek/chip-gn/args.gni
@@ -0,0 +1,32 @@
+# Copyright (c) 2021 Project CHIP Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import("//build_overrides/chip.gni")
+
+import("${chip_root}/src/crypto/crypto.gni")
+
+chip_device_platform = "realtek_zephyr"
+
+chip_build_tests = false
+
+chip_project_config_include = ""
+chip_system_project_config_include = ""
+chip_ble_project_config_include = ""
+
+chip_crypto = "mbedtls"
+chip_external_mbedtls = true
+
+custom_toolchain = "${chip_root}/config/realtek/chip-gn/toolchain:zephyr"
+
+pw_build_PIP_CONSTRAINTS = [ "${chip_root}/scripts/setup/constraints.txt" ]
diff --git a/config/realtek/chip-gn/toolchain/BUILD.gn b/config/realtek/chip-gn/toolchain/BUILD.gn
new file mode 100644
index 0000000..da5e291
--- /dev/null
+++ b/config/realtek/chip-gn/toolchain/BUILD.gn
@@ -0,0 +1,34 @@
+# Copyright (c) 2021 Project CHIP Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import("//build_overrides/build.gni")
+
+import("${build_root}/toolchain/arm_gcc/arm_toolchain.gni")
+
+declare_args() {
+ zephyr_ar = ""
+ zephyr_cc = ""
+ zephyr_cxx = ""
+}
+
+gcc_toolchain("zephyr") {
+ ar = zephyr_ar
+ cc = zephyr_cc
+ cxx = zephyr_cxx
+
+ toolchain_args = {
+ current_os = "zephyr"
+ is_clang = false
+ }
+}
diff --git a/config/realtek/chip-module/CMakeLists.txt b/config/realtek/chip-module/CMakeLists.txt
new file mode 100644
index 0000000..1d829d9
--- /dev/null
+++ b/config/realtek/chip-module/CMakeLists.txt
@@ -0,0 +1,200 @@
+#
+# Copyright (c) 2022-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.
+#
+
+#
+# @file
+# CMake sub-project defining 'chip' target which represents CHIP library
+# Since CHIP doesn't provide native CMake support, ExternalProject
+# module is used to build the required artifacts with GN meta-build
+# system. It is assumed that find_package(Zephyr) has been called before
+# including this file.
+#
+
+if (CONFIG_CHIP)
+
+include(ExternalProject)
+include(../../zephyr/ota-image.cmake)
+include(../../zephyr/zephyr-util.cmake)
+
+# ==============================================================================
+# Prepare CHIP configuration based on the project Kconfig configuration
+# ==============================================================================
+
+if (NOT CHIP_ROOT)
+ get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../../.. REALPATH)
+endif()
+get_filename_component(GN_ROOT_TARGET ${CHIP_ROOT}/config/realtek/chip-gn REALPATH)
+get_filename_component(COMMON_CMAKE_SOURCE_DIR ${CHIP_ROOT}/config/common/cmake REALPATH)
+
+# Get common Cmake sources
+
+include(${COMMON_CMAKE_SOURCE_DIR}/chip_gn_args.cmake)
+include(${COMMON_CMAKE_SOURCE_DIR}/chip_gn.cmake)
+
+# Prepare compiler flags
+if (CHIP_CFLAGS)
+ matter_add_flags("${CHIP_CFLAGS}")
+endif()
+
+matter_add_flags(-D_POSIX_C_SOURCE=200809)
+
+if (CONFIG_ARM)
+ matter_add_cflags(--specs=nosys.specs)
+endif()
+
+if(CONFIG_MBEDTLS)
+ zephyr_include_directories($<TARGET_PROPERTY:mbedTLS,INTERFACE_INCLUDE_DIRECTORIES>)
+ zephyr_compile_definitions($<TARGET_PROPERTY:mbedTLS,INTERFACE_COMPILE_DEFINITIONS>)
+endif()
+
+if (CONFIG_POSIX_API)
+ matter_add_flags(-D_DEFAULT_SOURCE)
+ matter_add_flags(-isystem${ZEPHYR_BASE}/include/zephyr/posix)
+endif()
+
+matter_add_flags(-DNL_ASSERT_USE_FLAGS_DEFAULT=1)
+
+zephyr_include_directories(
+ ${CHIP_ROOT}/src/platform/realtek/zephyr
+ ${CHIP_ROOT}/src/platform/realtek/zephyr/hw_acc
+ ${ZEPHYR_BASE}/../modules/crypto/mbedtls/library/
+)
+
+zephyr_get_compile_flags(ZEPHYR_CFLAGS_C C)
+matter_add_cflags("${ZEPHYR_CFLAGS_C}")
+zephyr_get_compile_flags(ZEPHYR_CFLAGS_CC CXX)
+matter_add_cxxflags("${ZEPHYR_CFLAGS_CC}")
+zephyr_get_gnu_cpp_standard(ZEPHYR_GNU_CPP_STD)
+matter_add_cxxflags(${ZEPHYR_GNU_CPP_STD})
+
+matter_add_flags(-DMBEDTLS_USER_CONFIG_FILE=<bee4-mbedtls-config.h>)
+
+# Set up custom OpenThread configuration
+
+if (CONFIG_CHIP_OPENTHREAD_CONFIG)
+ get_filename_component(CHIP_OPENTHREAD_CONFIG
+ ${CONFIG_CHIP_OPENTHREAD_CONFIG}
+ REALPATH
+ BASE_DIR ${CMAKE_SOURCE_DIR}
+ )
+ zephyr_set_openthread_config(${CHIP_OPENTHREAD_CONFIG})
+endif()
+
+# ==============================================================================
+# Generate configuration for CHIP GN build system
+# ==============================================================================
+
+matter_common_gn_args(
+ DEBUG CONFIG_DEBUG
+ LIB_SHELL CONFIG_CHIP_LIB_SHELL
+ LIB_TESTS CONFIG_CHIP_BUILD_TESTS
+ PROJECT_CONFIG ${CONFIG_CHIP_PROJECT_CONFIG}
+ DEVICE_INFO_EXAMPLE_PROVIDER CONFIG_CHIP_EXAMPLE_DEVICE_INFO_PROVIDER
+)
+matter_add_gn_arg_string("zephyr_ar" ${CMAKE_AR})
+matter_add_gn_arg_string("zephyr_cc" ${CMAKE_C_COMPILER})
+matter_add_gn_arg_string("zephyr_cxx" ${CMAKE_CXX_COMPILER})
+matter_add_gn_arg_bool ("chip_logging" CONFIG_LOG)
+matter_add_gn_arg_bool ("chip_enable_openthread" CONFIG_NET_L2_OPENTHREAD)
+matter_add_gn_arg_bool ("chip_openthread_ftd" CONFIG_OPENTHREAD_FTD)
+matter_add_gn_arg_bool ("chip_config_network_layer_ble" CONFIG_BT)
+matter_add_gn_arg_bool ("chip_inet_config_enable_ipv4" CONFIG_NET_IPV4)
+matter_add_gn_arg_bool ("chip_enable_ota_requestor" CONFIG_CHIP_OTA_REQUESTOR)
+matter_add_gn_arg_bool ("chip_inet_config_enable_tcp_endpoint" CONFIG_CHIP_BUILD_TESTS)
+matter_add_gn_arg_bool ("chip_error_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 1)
+matter_add_gn_arg_bool ("chip_progress_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 3)
+matter_add_gn_arg_bool ("chip_detail_logging" CONFIG_MATTER_LOG_LEVEL GREATER_EQUAL 4)
+matter_add_gn_arg_bool ("chip_automation_logging" FALSE)
+matter_add_gn_arg_bool ("chip_malloc_sys_heap" CONFIG_CHIP_MALLOC_SYS_HEAP)
+matter_add_gn_arg_bool ("chip_enable_icd_server" CONFIG_CHIP_ENABLE_ICD_SUPPORT)
+matter_add_gn_arg_bool ("chip_enable_wifi" FALSE)
+
+if (CONFIG_CHIP_ENABLE_ICD_SUPPORT)
+ matter_add_gn_arg_bool ("chip_enable_icd_lit" CONFIG_CHIP_ICD_LIT_SUPPORT)
+ matter_add_gn_arg_bool ("chip_enable_icd_checkin" CONFIG_CHIP_ICD_CHECK_IN_SUPPORT)
+ matter_add_gn_arg_bool ("chip_enable_icd_user_active_mode_trigger" CONFIG_CHIP_ICD_UAT_SUPPORT)
+endif()
+
+if (CONFIG_CHIP_FACTORY_DATA)
+ matter_add_gn_arg_bool ("chip_use_transitional_commissionable_data_provider" "false")
+ matter_add_gn_arg_bool ("chip_enable_factory_data" "true")
+elseif (CONFIG_CHIP_FACTORY_DATA_CUSTOM_BACKEND)
+ matter_add_gn_arg_bool ("chip_use_transitional_commissionable_data_provider" "false")
+endif()
+
+if (CONFIG_CHIP_ROTATING_DEVICE_ID)
+ matter_add_gn_arg_bool("chip_enable_rotating_device_id" "true")
+ matter_add_gn_arg_bool("chip_enable_additional_data_advertising" "true")
+endif()
+
+if (CONFIG_CHIP_ENABLE_DNSSD_SRP)
+ matter_add_gn_arg_string("chip_mdns" "platform")
+endif()
+
+if (CONFIG_CHIP_PW_RPC)
+ set(PIGWEED_DIR "//third_party/pigweed/repo")
+ matter_add_gn_arg_string("pw_assert_BACKEND" ${PIGWEED_DIR}/pw_assert_log:check_backend)
+ matter_add_gn_arg_string("pw_log_BACKEND" ${PIGWEED_DIR}/pw_log_basic)
+ matter_add_gn_arg("pw_build_LINK_DEPS" [\"${PIGWEED_DIR}/pw_assert:impl\",\ \"${PIGWEED_DIR}/pw_log:impl\"])
+endif()
+
+matter_generate_args_tmp_file()
+
+# ==============================================================================
+# Build chip library
+# ==============================================================================
+matter_build(chip
+ LIB_SHELL ${CONFIG_CHIP_LIB_SHELL}
+ DEVICE_INFO_EXAMPLE_PROVIDER ${CONFIG_CHIP_EXAMPLE_DEVICE_INFO_PROVIDER}
+ GN_DEPENDENCIES kernel
+)
+set_property(GLOBAL APPEND PROPERTY ZEPHYR_INTERFACE_LIBS chip)
+
+if (CONFIG_CHIP_MALLOC_SYS_HEAP_OVERRIDE)
+ target_link_options(chip INTERFACE
+ -Wl,--wrap=malloc
+ -Wl,--wrap=calloc
+ -Wl,--wrap=realloc
+ -Wl,--wrap=free
+ -Wl,--wrap=_malloc_r
+ -Wl,--wrap=_calloc_r
+ -Wl,--wrap=_realloc_r
+ -Wl,--wrap=_free_r
+ )
+endif()
+
+if(EXISTS "${CHIP_ROOT}/config/realtek/app/bootloader.conf")
+ set(GLOBAL_BOOTLOADER_CONF_OVERLAY_FILE "${CHIP_ROOT}/config/realtek/app/bootloader.conf")
+else()
+ unset(GLOBAL_BOOTLOADER_CONF_OVERLAY_FILE)
+endif()
+
+set(BLOCK_SIZE "1024")
+
+# get code-partition mcuboot_partition size
+dt_nodelabel(dts_partition_path NODELABEL "boot_patch_0")
+dt_reg_size(mcuboot_size PATH ${dts_partition_path})
+math(EXPR boot_blocks "${mcuboot_size} / ${BLOCK_SIZE}" OUTPUT_FORMAT DECIMAL)
+
+# ==============================================================================
+# Define 'factory_data' target for generating a factory data partition
+# ==============================================================================
+
+if (CONFIG_CHIP_FACTORY_DATA_BUILD)
+ realtek_generate_factory_data()
+endif()
+
+endif() # CONFIG_CHIP
diff --git a/config/realtek/chip-module/Kconfig b/config/realtek/chip-module/Kconfig
new file mode 100644
index 0000000..8ba5f8d
--- /dev/null
+++ b/config/realtek/chip-module/Kconfig
@@ -0,0 +1,200 @@
+#
+# 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.
+#
+
+rsource "../../zephyr/Kconfig"
+
+if CHIP
+
+# See config/zephyr/Kconfig for full definition
+config CHIP_DEVICE_VENDOR_NAME
+ default "Realtek Semiconductor"
+
+config CHIP_APP_LOG_LEVEL
+ int "Logging level in application"
+ default LOG_DEFAULT_LEVEL
+ depends on LOG
+ help
+ Sets the logging level in the Matter application. Use this configuration
+ option only within the application. To set the logging level for the
+ Matter stack, use the MATTER_LOG_LEVEL configuration option.
+
+config CHIP_NFC_COMMISSIONING
+ bool "Share onboarding payload in NFC tag"
+ default n
+ imply I2C
+ imply ST25DVXXKC
+ imply NFC
+ imply NFC_NDEF
+ imply NFC_NDEF_MSG
+ imply NFC_NDEF_RECORD
+ imply NFC_NDEF_URI_REC
+ imply NFC_NDEF_URI_MSG
+ help
+ Enables sharing the onboarding payload in the NFC tag.
+
+# See config/zephyr/Kconfig for full definition
+config CHIP_OTA_IMAGE_BUILD
+ bool
+ default y if CHIP_OTA_REQUESTOR
+
+config CHIP_ROTATING_DEVICE_ID
+ bool "Generate rotating device ID"
+ default y
+ help
+ Enables the rotating device identifier that provides a non-trackable
+ identifier. The identifier is unique per device and rotates at pre-defined
+ moments.
+
+config CHIP_EXAMPLE_DEVICE_INFO_PROVIDER
+ bool "Include default device information provider build"
+ default y
+
+config CHIP_MALLOC_SYS_HEAP
+ default y if !ARCH_POSIX
+
+config CHIP_FACTORY_DATA
+ bool "Enable Factory Data support"
+ select ZCBOR
+ help
+ Enables support for reading factory data from flash memory partition.
+ It requires factory_data partition to exist.
+
+config CHIP_FACTORY_DATA_CUSTOM_BACKEND
+ bool "Enable Factory Data custom backend"
+ depends on !CHIP_FACTORY_DATA
+ help
+ Enables user custom factory data implementation. It cannot be used
+ with the CHIP_FACTORY_DATA that enabled default Telink factory data
+ implementation.
+
+config CHIP_FACTORY_DATA_BUILD
+ bool "Enable Factory Data build"
+ default n
+ help
+ Enables generation of factory data during the building.
+ It requires factory_data partition to exist.
+ As a result a new output file factory_data.bin will be created.
+
+config CHIP_FACTORY_DATA_VERSION
+ int
+ default 1
+ help
+ The Factory data version contains a current version of a factory data
+ parameter set that the user cannot change.
+ After moving to the next version of the factory data set, change the default value.
+ This config is used to validate the version of a factory data set on a device-side
+ with the version of factory data saved in the Flash memory.
+
+if CHIP_FACTORY_DATA_BUILD
+
+# Factory data definitions
+config CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE
+ bool "Enable merging generated factory data with the build target .bin file"
+ default y
+ help
+ Enables merging generated factory data with the build target zephyr.bin file.
+ As a result, output file zephyr.bin will consist of all partitions including
+ factory data.
+
+# Use default certificates without generating or providing them
+config CHIP_FACTORY_DATA_USE_DEFAULT_CERTS
+ bool "Use default certificates located in Matter repository"
+ default y
+ help
+ Pre-generated certificates can be used for development purpose.
+ This config includes default pre-generated certificates
+ which are located in credentials/development/attestation/ directory
+ instead of generating new ones.
+ If this config is set to `n` new certificates will be generated.
+
+# Configs for SPAKE2 generation
+config CHIP_FACTORY_DATA_GENERATE_SPAKE2_VERIFIER
+ bool "Enable spake2 verifier generation"
+ help
+ Enables generation of spake2 verifier according to
+ given iteration counter, salt and passcode.
+ To generate Spake2 verifier a spake2p executable must be available
+ from system variables environment.
+
+config CHIP_DEVICE_GENERATE_ROTATING_DEVICE_UID
+ bool "Enable generation of a new Rotating device id unique id"
+ default y
+ help
+ Enables generation of a new Rotating device id unique id.
+
+endif #CHIP_FACTORY_DATA_BUILD
+
+# See config/zephyr/Kconfig for full definition
+config CHIP_FACTORY_RESET_ERASE_NVS
+ bool
+ default y
+
+config CHIP_LOG_SIZE_OPTIMIZATION
+ bool "Disable some detailed logs to decrease flash usage"
+ help
+ Disables some log levels for specific Matter log modules that provide
+ information that is too detailed to be used in most cases. You can find
+ full configuration enabled by this option in the
+ platform/realtek/zephyr/CHIPPlatformConfig.h file.
+
+config CHIP_BUTTON_MANAGER_IRQ_MODE
+ bool "Use GPIO in an IRQ mode instead of polling the GPIO"
+ default PM
+ help
+ Use GPIO in an IRQ mode to avoid button polling loop and extend the battery lifetime by waking up by GPIO event.
+ GPIO events are working only with GPIO IRQ. This option changes button matrix configuration.
+
+config CHIP_ENABLE_APPLICATION_STATUS_LED
+ bool "Enable application status LED"
+ default !(PM)
+ help
+ Enable application status LED.
+
+config CHIP_ENABLE_PM_DURING_BLE
+ bool "Enable PM during BLE operation"
+ default PM
+ help
+ Enable PM during BLE operation.
+
+config CHIP_OPENTHREAD_TX_POWER
+ int "OpenThread Transmission power"
+ range -30 9
+ default 0
+ help
+ OpenThread Transmission power in dBm.
+
+config SHELL_BACKEND_SERIAL_RX_RING_BUFFER_SIZE
+ int
+ default 255 if SHELL_BACKEND_SERIAL
+
+config CHIP_ENABLE_POWER_ON_FACTORY_RESET
+ bool "Enable power on factory reset sequence"
+ default n
+ help
+ Enable power on factory reset sequence. If device power triggered off during
+ first 5 seconds after power on and this sequence repeated 5 times - factory
+ reset will be involved.
+
+config CHIP_TASK_STACK_SIZE
+ int
+ default 8192
+
+config REALTEK_OTA_BANK1
+ bool "OTA BANK1 APP"
+ default n
+ depends on CHIP_OTA_REQUESTOR
+
+endif # CONFIG_CHIP
\ No newline at end of file
diff --git a/config/realtek/chip-module/Kconfig.defaults b/config/realtek/chip-module/Kconfig.defaults
new file mode 100644
index 0000000..c123671
--- /dev/null
+++ b/config/realtek/chip-module/Kconfig.defaults
@@ -0,0 +1,299 @@
+#
+# 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.
+#
+
+# The purpose of this file is to define new default values of settings used when building Matter samples.
+# This file only changes defaults and thus all symbols here must be promptless
+# and safeguarded so that they only are applied when building Matter.
+
+if CHIP
+
+config LOG
+ default y
+
+if LOG
+
+choice LOG_MODE
+ default LOG_MODE_MINIMAL
+endchoice
+
+choice MATTER_LOG_LEVEL_CHOICE
+ default MATTER_LOG_LEVEL_DBG
+endchoice
+
+config CHIP_APP_LOG_LEVEL
+ default 4 # info
+
+config LOG_DEFAULT_LEVEL
+ default 1 # error
+
+config CHIP_LOG_SIZE_OPTIMIZATION
+ default y
+
+endif
+
+config PRINTK_SYNC
+ default y
+
+config ASSERT
+ default n
+
+config ASSERT_NO_COND_INFO
+ default n
+
+config ASSERT_NO_MSG_INFO
+ default n
+
+config HW_STACK_PROTECTION
+ default y
+
+config SHELL
+ default y if CHIP_LIB_SHELL
+
+config PTHREAD_IPC
+ bool
+ default n
+
+config POSIX_MAX_FDS
+ int
+ default 16
+
+choice LIBC_IMPLEMENTATION
+ default NEWLIB_LIBC
+endchoice
+
+# Application stack size
+config MAIN_STACK_SIZE
+ default 8192
+
+config INIT_STACKS
+ default y
+
+config SYSTEM_WORKQUEUE_STACK_SIZE
+ default 2048
+
+config HEAP_MEM_POOL_SIZE
+ default 1024
+
+config CHIP_MALLOC_SYS_HEAP_SIZE
+ default 8192 if NET_L2_OPENTHREAD
+
+config COMMON_LIBC_MALLOC_ARENA_SIZE
+ default 8192
+
+config NET_IPV6_MLD
+ default y
+
+# Network buffers
+config NET_PKT_RX_COUNT
+ default 8
+
+config NET_PKT_TX_COUNT
+ default 8
+
+config NET_BUF_RX_COUNT
+ default 32
+
+config NET_BUF_TX_COUNT
+ default 32
+
+config GPIO
+ default y
+
+# Bluetooth Low Energy configs
+
+config BT
+ default y
+
+config BT_PERIPHERAL
+ default y
+
+config BT_GATT_DYNAMIC_DB
+ default y
+
+config BT_DEVICE_NAME_DYNAMIC
+ default y
+
+config BT_DEVICE_NAME_MAX
+ default 15
+
+config BT_MAX_CONN
+ default 1
+
+config BT_L2CAP_TX_MTU
+ default 247
+
+config BT_BUF_ACL_RX_SIZE
+ default 251
+
+config BT_BUF_ACL_TX_SIZE
+ default 251
+
+config BT_RX_STACK_SIZE
+ default 2200
+
+config BT_HCI_TX_STACK_SIZE
+ default 1024
+
+config BT_DEVICE_NAME_GATT_WRITABLE
+ bool
+ default n
+
+# Config dynamic interrupts to have posibility to switch between BLE/Thread radio drivers
+config DYNAMIC_INTERRUPTS
+ default y
+
+config CHIP_OTA_REQUESTOR
+ default n
+
+# In current config/zephyr/Kconfig
+# next deprecated values are selected
+# warning: Deprecated symbol CPLUSPLUS is enabled.
+# warning: Deprecated symbol LIB_CPLUSPLUS is enabled.
+# new one are:
+# CONFIG_CPP
+# CONFIG_LIBCPP_IMPLEMENTATION
+# See https://docs.zephyrproject.org/latest/releases/release-notes-3.3.html
+# Since not only Telink is using Zephyr just suppress warnings
+config WARN_DEPRECATED
+ default n
+
+config NVS_LOOKUP_CACHE
+ default y
+
+config NVS_LOOKUP_CACHE_SIZE
+ default 512
+
+# Set multiplicator of Name Value Storage (NVS) as 1 to reach NVS sector size 4KB
+# nvs_sector_size = flash_page_size * mult = 4KB * 1 = 4KB
+config SETTINGS_NVS_SECTOR_SIZE_MULT
+ default 1
+
+# Set sector counter of NVS
+config SETTINGS_NVS_SECTOR_COUNT
+ default 8
+
+# Enable OpenThread
+
+config NET_L2_OPENTHREAD
+ default y
+
+choice CHIP_THREAD_DEVICE_ROLE
+ prompt "Thread network device role"
+ default CHIP_THREAD_DEVICE_ROLE_ROUTER
+config CHIP_THREAD_DEVICE_ROLE_ROUTER
+ depends on !PM
+ bool "thread device router"
+config CHIP_THREAD_DEVICE_ROLE_END_DEVICE
+ depends on !PM
+ bool "thread end device"
+config CHIP_THREAD_DEVICE_ROLE_SLEEPY_END_DEVICE
+ bool "thread sleepy end device"
+endchoice
+
+choice OPENTHREAD_DEVICE_TYPE
+ default OPENTHREAD_FTD if CHIP_THREAD_DEVICE_ROLE_ROUTER
+ default OPENTHREAD_MTD if CHIP_THREAD_DEVICE_ROLE_END_DEVICE || CHIP_THREAD_DEVICE_ROLE_SLEEPY_END_DEVICE
+endchoice
+
+config CHIP_ENABLE_ICD_SUPPORT
+ default y if CHIP_THREAD_DEVICE_ROLE_SLEEPY_END_DEVICE
+
+config OPENTHREAD_SLAAC
+ default y
+
+config OPENTHREAD_MANUAL_START
+ default y
+
+# Disable certain parts of Zephyr IPv6 stack
+config NET_IPV6_NBR_CACHE
+ bool
+ default n
+
+config NET_MAX_CONN
+ default 1
+
+config NET_MAX_CONTEXTS
+ default 1
+
+config NET_CONFIG_INIT_TIMEOUT
+ default 0
+
+# Configure MBEDTLS lib
+config MBEDTLS_USER_CONFIG_ENABLE
+ default y
+
+config MBEDTLS_USER_CONFIG_FILE
+ default "bee4-mbedtls-config.h"
+
+config MBEDTLS_ZEPHYR_ENTROPY
+ default y
+
+config MBEDTLS_ENABLE_HEAP
+ default y
+
+config MBEDTLS_HEAP_SIZE
+ default 8192
+
+config MBEDTLS_ECP_C
+ default y
+
+
+# getopt version
+config GETOPT_LONG
+ default y
+
+# Disable not used shell modules
+
+config SHELL_WILDCARD
+ default n
+
+config SHELL_VT100_COLORS
+ default n
+
+config SHELL_STATS
+ default n
+
+config KERNEL_SHELL
+ default n
+
+config SENSOR_SHELL
+ default n
+
+config DEVICE_SHELL
+ default n
+
+config DATE_SHELL
+ default n
+
+config DEVMEM_SHELL
+ default n
+
+config MCUBOOT_SHELL
+ default n
+
+config FLASH_SHELL
+ default n
+
+config HWINFO_SHELL
+ default n
+
+config PWM_SHELL
+ default n
+
+config OPENTHREAD_SHELL
+ default n
+
+endif
diff --git a/config/realtek/chip-module/zephyr/module.yml b/config/realtek/chip-module/zephyr/module.yml
new file mode 100644
index 0000000..c09c9ea
--- /dev/null
+++ b/config/realtek/chip-module/zephyr/module.yml
@@ -0,0 +1,22 @@
+#
+# Copyright (c) 2021 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.
+#
+
+name: connectedhomeip
+build:
+ cmake: .
+ kconfig: Kconfig
+ depends:
+ - openthread
diff --git a/examples/lighting-app/realtek/zephyr/.gitignore b/examples/lighting-app/realtek/zephyr/.gitignore
new file mode 100644
index 0000000..84c048a
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/.gitignore
@@ -0,0 +1 @@
+/build/
diff --git a/examples/lighting-app/realtek/zephyr/CMakeLists.txt b/examples/lighting-app/realtek/zephyr/CMakeLists.txt
new file mode 100755
index 0000000..1f8adaf
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/CMakeLists.txt
@@ -0,0 +1,236 @@
+#
+# Copyright (c) 2022 Project CHIP Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+cmake_minimum_required(VERSION 3.13.1)
+
+get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/third_party/connectedhomeip REALPATH)
+get_filename_component(REALTEK_COMMON ${CHIP_ROOT}/examples/platform/realtek REALPATH)
+get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH)
+
+if(EXISTS "${CHIP_ROOT}/src/platform/realtek/zephyr/${BOARD}.overlay")
+ set(GLOBAL_DTC_OVERLAY_FILE "${CHIP_ROOT}/src/platform/realtek/zephyr/${BOARD}.overlay")
+else()
+ unset(GLOBAL_DTC_OVERLAY_FILE)
+endif()
+
+if(DTC_OVERLAY_FILE)
+ set(DTC_OVERLAY_FILE
+ "${DTC_OVERLAY_FILE} ${GLOBAL_DTC_OVERLAY_FILE}"
+ CACHE STRING "" FORCE
+ )
+else()
+ set(DTC_OVERLAY_FILE ${GLOBAL_DTC_OVERLAY_FILE})
+endif()
+
+set(CONF_FILE prj.conf)
+
+# Load NCS/Zephyr build system
+list(APPEND ZEPHYR_EXTRA_MODULES ${CHIP_ROOT}/config/realtek/chip-module)
+find_package(Zephyr HINTS $ENV{ZEPHYR_BASE})
+
+project(chip-realtek-lighting-example)
+
+include(${CHIP_ROOT}/config/realtek/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
+ main/include
+ ${GEN_DIR}/app-common
+ ${GEN_DIR}/lighting-app
+ ${REALTEK_COMMON}/bee/ota
+ ${REALTEK_COMMON}/zephyr
+ ${ZEPHYR_BASE}/../modules/hal/realtek/bee/drivers/wdt/inc
+ ${ZEPHYR_BASE}/../realtek-zephyr-project/applications/matter_common)
+
+target_sources(app PRIVATE
+ main/main.cpp
+ main/AppTask.cpp
+ main/ZclCallbacks.cpp
+ ${REALTEK_COMMON}/zephyr/LEDWidget.cpp
+ ${REALTEK_COMMON}/zephyr/matter_button.c)
+
+target_link_options(app
+ PUBLIC
+ -Wl,--wrap,mac_EnterCritical_rom
+ -Wl,--wrap,mac_ExitCritical_rom
+ -Wl,--wrap,mac_RstRF_rom
+ -Wl,--wrap,otPlatReset
+ )
+
+chip_configure_data_model(app
+ INCLUDE_SERVER
+ ZAP_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../../lighting-common/lighting-app.zap
+)
+
+if(CONFIG_CHIP_OTA_REQUESTOR)
+ target_sources(app PRIVATE
+ ${REALTEK_COMMON}/bee/ota/OTAInitializer.cpp
+ ${ZEPHYR_BASE}/../realtek-zephyr-project/applications/matter_common/matter_ota.c)
+endif()
+
+# Fix for unused swap parameter in: zephyr/include/zephyr/arch/riscv/irq.h:70
+add_compile_options(-Wno-error=unused-parameter)
+
+if (CONFIG_CHIP_PW_RPC)
+
+# Make all targets created below depend on zephyr_interface to inherit MCU-related compilation flags
+link_libraries($<BUILD_INTERFACE:zephyr_interface>)
+
+set(PIGWEED_ROOT "${CHIP_ROOT}/third_party/pigweed/repo")
+include(${PIGWEED_ROOT}/pw_build/pigweed.cmake)
+include(${PIGWEED_ROOT}/pw_protobuf_compiler/proto.cmake)
+
+include($ENV{PW_ROOT}/pw_assert/backend.cmake)
+include($ENV{PW_ROOT}/pw_log/backend.cmake)
+include($ENV{PW_ROOT}/pw_sys_io/backend.cmake)
+
+pw_set_module_config(pw_rpc_CONFIG pw_rpc.disable_global_mutex_config)
+pw_set_backend(pw_log pw_log_basic)
+pw_set_backend(pw_assert.check pw_assert_log.check_backend)
+pw_set_backend(pw_assert.assert pw_assert.assert_compatibility_backend)
+pw_set_backend(pw_sys_io pw_sys_io.realtek_zephyr)
+
+set(dir_pw_third_party_nanopb "${CHIP_ROOT}/third_party/nanopb/repo" CACHE STRING "" FORCE)
+
+add_subdirectory(third_party/connectedhomeip/third_party/pigweed/repo)
+add_subdirectory(third_party/connectedhomeip/third_party/nanopb/repo)
+add_subdirectory(third_party/connectedhomeip/examples/platform/realtek/bee/pw_sys_io)
+
+pw_proto_library(attributes_service
+ SOURCES
+ ${CHIP_ROOT}/examples/common/pigweed/protos/attributes_service.proto
+ INPUTS
+ ${CHIP_ROOT}/examples/common/pigweed/protos/attributes_service.options
+ PREFIX
+ attributes_service
+ STRIP_PREFIX
+ ${CHIP_ROOT}/examples/common/pigweed/protos
+ DEPS
+ pw_protobuf.common_proto
+)
+
+pw_proto_library(button_service
+ SOURCES
+ ${CHIP_ROOT}/examples/common/pigweed/protos/button_service.proto
+ PREFIX
+ button_service
+ STRIP_PREFIX
+ ${CHIP_ROOT}/examples/common/pigweed/protos
+ DEPS
+ pw_protobuf.common_proto
+)
+
+pw_proto_library(descriptor_service
+ SOURCES
+ ${CHIP_ROOT}/examples/common/pigweed/protos/descriptor_service.proto
+ PREFIX
+ descriptor_service
+ STRIP_PREFIX
+ ${CHIP_ROOT}/examples/common/pigweed/protos
+ DEPS
+ pw_protobuf.common_proto
+)
+
+pw_proto_library(device_service
+ SOURCES
+ ${CHIP_ROOT}/examples/common/pigweed/protos/device_service.proto
+ INPUTS
+ ${CHIP_ROOT}/examples/common/pigweed/protos/device_service.options
+ PREFIX
+ device_service
+ STRIP_PREFIX
+ ${CHIP_ROOT}/examples/common/pigweed/protos
+ DEPS
+ pw_protobuf.common_proto
+)
+
+pw_proto_library(lighting_service
+ SOURCES
+ ${CHIP_ROOT}/examples/common/pigweed/protos/lighting_service.proto
+ STRIP_PREFIX
+ ${CHIP_ROOT}/examples/common/pigweed/protos
+ PREFIX
+ lighting_service
+ DEPS
+ pw_protobuf.common_proto
+)
+
+pw_proto_library(ot_cli_service
+ SOURCES
+ ${CHIP_ROOT}/examples/common/pigweed/protos/ot_cli_service.proto
+ INPUTS
+ ${CHIP_ROOT}/examples/common/pigweed/protos/ot_cli_service.options
+ STRIP_PREFIX
+ ${CHIP_ROOT}/examples/common/pigweed/protos
+ PREFIX
+ ot_cli_service
+ DEPS
+ pw_protobuf.common_proto
+)
+
+pw_proto_library(thread_service
+ SOURCES
+ ${CHIP_ROOT}/examples/common/pigweed/protos/thread_service.proto
+ INPUTS
+ ${CHIP_ROOT}/examples/common/pigweed/protos/thread_service.options
+ STRIP_PREFIX
+ ${CHIP_ROOT}/examples/common/pigweed/protos
+ PREFIX
+ thread_service
+ DEPS
+ pw_protobuf.common_proto
+)
+
+target_sources(app PRIVATE
+ ../../common/pigweed/RpcService.cpp
+ ../../common/pigweed/realtek/PigweedLoggerMutex.cpp
+ ${REALTEK_COMMON}/bee/Rpc.cpp
+ ${REALTEK_COMMON}/bee/PigweedLogger.cpp
+)
+
+target_include_directories(app PRIVATE
+ ${PIGWEED_ROOT}/pw_sys_io/public
+ ${CHIP_ROOT}/src/lib/support
+ ${CHIP_ROOT}/src/system
+ ${REALTEK_COMMON}/bee
+ ../../common
+ ../../common/pigweed
+ ../../common/pigweed/realtek)
+
+target_compile_options(app PRIVATE
+ "-DPW_RPC_ATTRIBUTE_SERVICE=1"
+ "-DPW_RPC_BUTTON_SERVICE=1"
+ "-DPW_RPC_DESCRIPTOR_SERVICE=1"
+ "-DPW_RPC_DEVICE_SERVICE=1"
+ "-DPW_RPC_LIGHTING_SERVICE=1"
+ "-DPW_RPC_THREAD_SERVICE=1")
+
+target_link_libraries(app PRIVATE
+ attributes_service.nanopb_rpc
+ button_service.nanopb_rpc
+ descriptor_service.nanopb_rpc
+ device_service.nanopb_rpc
+ lighting_service.nanopb_rpc
+ thread_service.nanopb_rpc
+ pw_checksum
+ pw_hdlc
+ pw_log
+ pw_rpc.server
+ pw_sys_io
+)
+
+endif(CONFIG_CHIP_PW_RPC)
diff --git a/examples/lighting-app/realtek/zephyr/Kconfig b/examples/lighting-app/realtek/zephyr/Kconfig
new file mode 100644
index 0000000..8507b30
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/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 Realtek Lighting Example Application"
+
+rsource "../../../../config/realtek/chip-module/Kconfig.defaults"
+source "Kconfig.zephyr"
diff --git a/examples/lighting-app/realtek/zephyr/README.md b/examples/lighting-app/realtek/zephyr/README.md
new file mode 100755
index 0000000..d94d3c3
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/README.md
@@ -0,0 +1,83 @@
+# Matter Realtek Lighting Example Application
+
+This reference application implements an On/Off Light device type. It uses
+buttons to test changing the lighting and device states and LEDs to show the
+state of these changes. You can use this example as a reference for creating
+your own application.
+
+The example is based on:
+
+- [Matter](https://github.com/project-chip/connectedhomeip)
+- [Realtek zephyr SDK](https://github.com/rtkconnectivity/zephyr)
+- [Realtek HAL module](https://github.com/rtkconnectivity/hal_realtek)
+
+## Supported Device
+
+- RTL87x2G
+
+## Introduction
+
+The application showcases a light bulb device that communicates with clients
+over a low-power, 802.15.4 Thread network.
+
+It can be commissioned into an existing Matter network using a controller such
+as `chip-tool`.
+
+This example implements a `Standard commissioning flow`, meaning devices not
+connected to the network automatically broadcast advertising when powered on.
+The initial commissioning is done through `ble-thread` pairing method.
+
+The Thread network dataset will be transferred on the device using a secure
+session over Bluetooth LE.To pair successfully, the commissioner must know the
+commissioning information corresponding to the device: setup passcode and
+discriminator. This data is usually encoded within a QR code or printed to the
+UART console.
+
+## Prerequisites for building
+
+In order to build the example, it is recommended to use a Linux distribution.
+Please visit the supported Operating Systems list in
+[BUILDING.md](../../../../docs/guides/BUILDING.md#prerequisites).
+
+- Make sure that below prerequisites are correctly installed (as described in
+ [BUILDING.md](../../../../docs/guides/BUILDING.md#prerequisites))
+
+```
+sudo apt-get install git gcc g++ pkg-config libssl-dev libdbus-1-dev libglib2.0-dev libavahi-client-dev ninja-build python3-venv python3-dev python3-pip unzip libgirepository1.0-dev libcairo2-dev libreadline-dev
+```
+
+- Step 1: Pull docker image
+
+ ```bash
+ $ docker pull ghcr.io/project-chip/chip-build-realtek-zephyr:167
+ ```
+
+- Step 2: Run docker container:
+
+ ```bash
+ $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-realtek-zephyr:167
+ ```
+
+- Step 3: Activate build environment
+
+ ```bash
+ $ source ./scripts/activate.sh
+ ```
+
+ If the script says the environment is out of date, you can update it by
+ running the following command:
+
+ ```bash
+ $ source ./scripts/bootstrap.sh
+ ```
+
+## Building
+
+- To build the demo application:
+
+ ```bash
+ $ ./scripts/build/build_examples.py --target realtek-rtl87x2g-lighting build
+ ```
+
+ The output `zephyr.hex` file will be available in the
+ `out/realtek-rtl87x2g-lighting/zephyr` directory.
diff --git a/examples/lighting-app/realtek/zephyr/main/AppTask.cpp b/examples/lighting-app/realtek/zephyr/main/AppTask.cpp
new file mode 100644
index 0000000..c8e9373
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/main/AppTask.cpp
@@ -0,0 +1,472 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "AppTask.h"
+
+#include "AppConfig.h"
+#include "AppEvent.h"
+#include "LEDWidget.h"
+#include "matter_button.h"
+
+#include <DeviceInfoProviderImpl.h>
+#include <app-common/zap-generated/attributes/Accessors.h>
+#include <app/TestEventTriggerDelegate.h>
+#include <app/clusters/identify-server/identify-server.h>
+#include <app/clusters/ota-requestor/OTATestEventTriggerHandler.h>
+#include <app/server/Dnssd.h>
+#include <app/server/Server.h>
+#include <credentials/DeviceAttestationCredsProvider.h>
+#include <credentials/examples/DeviceAttestationCredsExample.h>
+#include <lib/core/ErrorStr.h>
+#include <lib/support/CHIPMem.h>
+#include <lib/support/CodeUtils.h>
+#include <setup_payload/OnboardingCodesUtil.h>
+#include <system/SystemClock.h>
+
+#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR
+#include <OTAInitializer.h>
+#endif
+
+#include <zephyr/kernel.h>
+#include <zephyr/logging/log.h>
+
+LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL);
+
+using namespace ::chip;
+using namespace ::chip::app;
+using namespace ::chip::Credentials;
+using namespace ::chip::DeviceLayer;
+
+namespace {
+
+constexpr int kFactoryResetTriggerTimeout = 3000;
+constexpr int kFactoryResetCancelWindowTimeout = 3000;
+constexpr int kAppEventQueueSize = 10;
+constexpr EndpointId kLightEndpointId = 1;
+
+K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent));
+k_timer sFunctionTimer;
+
+Identify sIdentify = { kLightEndpointId, AppTask::IdentifyStartHandler, AppTask::IdentifyStopHandler,
+ Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator };
+
+LEDWidget sStatusLED;
+LEDWidget sIdentifyLED;
+
+bool sIsNetworkProvisioned = false;
+bool sIsNetworkEnabled = false;
+bool sHaveBLEConnections = false;
+
+chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider;
+
+#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR
+static bool isOTAInitialized = false;
+constexpr uint32_t kInitOTARequestorDelaySec = 3;
+
+void InitOTARequestorHandler(System::Layer * systemLayer, void * appState)
+{
+ ChipLogProgress(Zcl, "InitOTARequestorHandler");
+ OTAInitializer::Instance().InitOTARequestor();
+}
+#endif
+} // namespace
+
+namespace LedConsts {
+constexpr uint32_t kBlinkRate_ms{ 500 };
+constexpr uint32_t kIdentifyBlinkRate_ms{ 500 };
+
+namespace StatusLed {
+namespace Unprovisioned {
+constexpr uint32_t kOn_ms{ 100 };
+constexpr uint32_t kOff_ms{ kOn_ms };
+} // namespace Unprovisioned
+namespace Provisioned {
+constexpr uint32_t kOn_ms{ 50 };
+constexpr uint32_t kOff_ms{ 950 };
+} // namespace Provisioned
+
+} // namespace StatusLed
+} // namespace LedConsts
+
+CHIP_ERROR AppTask::Init()
+{
+ // Initialize LEDs
+ LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler);
+
+ sStatusLED.Init(GPIO_DT_SPEC_GET_OR(DT_ALIAS(led0), gpios, {}));
+ sIdentifyLED.Init(GPIO_DT_SPEC_GET_OR(DT_ALIAS(led1), gpios, {}));
+ sIdentifyLED.Set(false);
+
+ UpdateStatusLED();
+
+ // Initialize buttons
+ int ret = matter_button_init(ButtonEventHandler);
+ if (ret)
+ {
+ LOG_ERR("matter_button_init() failed");
+ return chip::System::MapErrorZephyr(ret);
+ }
+
+ // Initialize CHIP stack
+ LOG_INF("Init CHIP stack");
+
+ CHIP_ERROR err = chip::Platform::MemoryInit();
+ if (err != CHIP_NO_ERROR)
+ {
+ LOG_ERR("Platform::MemoryInit() failed");
+ return err;
+ }
+
+ err = PlatformMgr().InitChipStack();
+ if (err != CHIP_NO_ERROR)
+ {
+ LOG_ERR("PlatformMgr().InitChipStack() failed");
+ return err;
+ }
+
+#if CHIP_ENABLE_OPENTHREAD
+ err = ThreadStackMgr().InitThreadStack();
+ if (err != CHIP_NO_ERROR)
+ {
+ LOG_ERR("ThreadStackMgr().InitThreadStack() failed");
+ return err;
+ }
+
+#if CHIP_DEVICE_CONFIG_THREAD_FTD
+ err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router);
+#elif CHIP_DEVICE_CONFIG_THREAD_SSED
+ err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SynchronizedSleepyEndDevice);
+#else
+ err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice);
+#endif
+
+ if (err != CHIP_NO_ERROR)
+ {
+ LOG_ERR("ConnectivityMgr().SetThreadDeviceType() failed");
+ return err;
+ }
+#else
+ return CHIP_ERROR_INTERNAL;
+#endif // CHIP_ENABLE_OPENTHREAD
+
+ // Initialize function button timer
+ k_timer_init(&sFunctionTimer, &AppTask::FunctionTimerTimeoutCallback, nullptr);
+ k_timer_user_data_set(&sFunctionTimer, this);
+
+#ifdef CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR
+ /* OTA image confirmation must be done before the factory data init. */
+ // OtaConfirmNewImage();
+#endif
+
+ // Initialize CHIP server
+#if CONFIG_CHIP_FACTORY_DATA
+ ReturnErrorOnFailure(mFactoryDataProvider.Init());
+ SetDeviceInstanceInfoProvider(&mFactoryDataProvider);
+ SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider);
+ SetCommissionableDataProvider(&mFactoryDataProvider);
+#else
+ SetDeviceInstanceInfoProvider(&DeviceInstanceInfoProviderMgrImpl());
+ SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider());
+#endif
+
+ // Init ZCL Data Model and CHIP App Server
+ static chip::CommonCaseDeviceServerInitParams initParams;
+ initParams.InitializeStaticResourcesBeforeServerInit();
+ ReturnErrorOnFailure(chip::Server::GetInstance().Init(initParams));
+
+ gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage());
+ chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider);
+
+ ConfigurationMgr().LogDeviceConfig();
+ PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE));
+
+#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
+ ChipLogProgress(DeviceLayer, "Start BLE Adv");
+ if (CONFIG_NETWORK_LAYER_BLE)
+ {
+ ConnectivityMgr().SetBLEAdvertisingEnabled(true);
+ }
+#endif
+
+ // Add CHIP event handler and start CHIP thread.
+ // Note that all the initialization code should happen prior to this point to avoid data races
+ // between the main and the CHIP threads.
+ PlatformMgr().AddEventHandler(ChipEventHandler, 0);
+
+ err = PlatformMgr().StartEventLoopTask();
+ if (err != CHIP_NO_ERROR)
+ {
+ LOG_ERR("PlatformMgr().StartEventLoopTask() failed");
+ }
+
+ return err;
+}
+
+CHIP_ERROR AppTask::StartApp()
+{
+ ReturnErrorOnFailure(Init());
+
+ AppEvent event = {};
+
+ while (true)
+ {
+ k_msgq_get(&sAppEventQueue, &event, K_FOREVER);
+ DispatchEvent(event);
+ }
+
+ return CHIP_NO_ERROR;
+}
+
+void AppTask::IdentifyStartHandler(Identify *)
+{
+ AppEvent event;
+ event.Type = AppEventType::IdentifyStart;
+ event.Handler = [](const AppEvent &) { sIdentifyLED.Blink(LedConsts::kIdentifyBlinkRate_ms); };
+ PostEvent(event);
+}
+
+void AppTask::IdentifyStopHandler(Identify *)
+{
+ AppEvent event;
+ event.Type = AppEventType::IdentifyStop;
+ event.Handler = [](const AppEvent &) { sIdentifyLED.Set(false); };
+ PostEvent(event);
+}
+
+LEDWidget & AppTask::GetLightingDevice(void)
+{
+ return sIdentifyLED;
+}
+
+void AppTask::ButtonEventHandler(uint8_t buttonIdx, uint8_t state)
+{
+ AppEvent button_event;
+
+ button_event.Type = AppEventType::Button;
+ button_event.ButtonEvent.ButtonIdx = buttonIdx;
+ button_event.ButtonEvent.Action =
+ static_cast<uint8_t>((state == MATTER_BUTTON_STATE_PRESS) ? AppEventType::ButtonPushed : AppEventType::ButtonReleased);
+ button_event.Handler = FunctionHandler;
+ PostEvent(button_event);
+}
+
+void AppTask::FunctionTimerTimeoutCallback(k_timer * timer)
+{
+ if (!timer)
+ {
+ return;
+ }
+
+ AppEvent event;
+ event.Type = AppEventType::Timer;
+ event.TimerEvent.Context = k_timer_user_data_get(timer);
+ event.Handler = FunctionTimerEventHandler;
+ PostEvent(event);
+}
+
+void AppTask::FunctionTimerEventHandler(const AppEvent & event)
+{
+ if (event.Type != AppEventType::Timer)
+ {
+ return;
+ }
+
+ // If we reached here, the button was held past kFactoryResetTriggerTimeout, initiate factory reset
+ if (Instance().mFunction == FunctionEvent::SoftwareUpdate)
+ {
+ LOG_INF("Factory Reset Triggered. Release button within %ums to cancel.", kFactoryResetTriggerTimeout);
+
+ // Start timer for kFactoryResetCancelWindowTimeout to allow user to cancel, if required.
+ Instance().StartTimer(kFactoryResetCancelWindowTimeout);
+ Instance().mFunction = FunctionEvent::FactoryReset;
+
+ // Turn off all LEDs before starting blink to make sure blink is co-ordinated.
+ sStatusLED.Set(false);
+ sStatusLED.Blink(LedConsts::kBlinkRate_ms);
+ }
+ else if (Instance().mFunction == FunctionEvent::FactoryReset)
+ {
+ // Actually trigger Factory Reset
+ Instance().mFunction = FunctionEvent::NoneSelected;
+ chip::Server::GetInstance().ScheduleFactoryReset();
+ }
+}
+
+void AppTask::FunctionHandler(const AppEvent & event)
+{
+ LOG_INF("Button state changed: index %d, action %d", event.ButtonEvent.ButtonIdx, event.ButtonEvent.Action);
+
+ switch (event.ButtonEvent.ButtonIdx)
+ {
+ case 0: {
+ // To trigger software update: press the FUNCTION_BUTTON button briefly (< kFactoryResetTriggerTimeout)
+ // To initiate factory reset: press the FUNCTION_BUTTON for kFactoryResetTriggerTimeout + kFactoryResetCancelWindowTimeout
+ // All LEDs start blinking after kFactoryResetTriggerTimeout to signal factory reset has been initiated.
+ // To cancel factory reset: release the FUNCTION_BUTTON once all LEDs start blinking within the
+ // kFactoryResetCancelWindowTimeout
+ if (event.ButtonEvent.Action == static_cast<uint8_t>(AppEventType::ButtonPushed))
+ {
+ if (!Instance().mFunctionTimerActive && Instance().mFunction == FunctionEvent::NoneSelected)
+ {
+ Instance().StartTimer(kFactoryResetTriggerTimeout);
+ Instance().mFunction = FunctionEvent::SoftwareUpdate;
+ }
+ }
+ else
+ {
+ // If the button was released before factory reset got initiated, trigger a software update.
+ if (Instance().mFunctionTimerActive && Instance().mFunction == FunctionEvent::SoftwareUpdate)
+ {
+ Instance().CancelTimer();
+ Instance().mFunction = FunctionEvent::NoneSelected;
+
+ LOG_INF("Software update is disabled");
+ }
+ else if (Instance().mFunctionTimerActive && Instance().mFunction == FunctionEvent::FactoryReset)
+ {
+ UpdateStatusLED();
+ Instance().CancelTimer();
+ Instance().mFunction = FunctionEvent::NoneSelected;
+ LOG_INF("Factory Reset has been Canceled");
+ }
+ }
+ }
+ break;
+
+ default:
+ break;
+ }
+}
+
+void AppTask::UpdateLedStateEventHandler(const AppEvent & event)
+{
+ if (event.Type == AppEventType::UpdateLedState)
+ {
+ event.UpdateLedStateEvent.LedWidget->UpdateState();
+ }
+}
+
+void AppTask::LEDStateUpdateHandler(LEDWidget & ledWidget)
+{
+ AppEvent event;
+ event.Type = AppEventType::UpdateLedState;
+ event.Handler = UpdateLedStateEventHandler;
+ event.UpdateLedStateEvent.LedWidget = &ledWidget;
+ PostEvent(event);
+}
+
+void AppTask::UpdateStatusLED()
+{
+ // Update the status LED.
+ //
+ // If IPv6 network and service provisioned, keep the LED On constantly.
+ //
+ // If the system has ble connection(s) uptill the stage above, THEN blink the LED at an even
+ // rate of 100ms.
+ //
+ // Otherwise, blink the LED for a very short time.
+ if (sIsNetworkProvisioned && sIsNetworkEnabled)
+ {
+ sStatusLED.Set(true);
+ }
+ else if (sHaveBLEConnections)
+ {
+ sStatusLED.Blink(LedConsts::StatusLed::Unprovisioned::kOn_ms, LedConsts::StatusLed::Unprovisioned::kOff_ms);
+ }
+ else
+ {
+ sStatusLED.Blink(LedConsts::StatusLed::Provisioned::kOn_ms, LedConsts::StatusLed::Provisioned::kOff_ms);
+ }
+}
+
+void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */)
+{
+ switch (event->Type)
+ {
+ case DeviceEventType::kCHIPoBLEAdvertisingChange:
+ sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0;
+ UpdateStatusLED();
+ break;
+
+ case DeviceEventType::kThreadStateChange:
+ sIsNetworkProvisioned = ConnectivityMgr().IsThreadProvisioned();
+ sIsNetworkEnabled = ConnectivityMgr().IsThreadEnabled();
+ UpdateStatusLED();
+ break;
+
+ case DeviceEventType::kServerReady:
+#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR
+ if (!isOTAInitialized)
+ {
+ chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec),
+ InitOTARequestorHandler, nullptr);
+ isOTAInitialized = true;
+ }
+#endif
+ break;
+
+ default:
+ break;
+ }
+}
+
+void AppTask::CancelTimer()
+{
+ k_timer_stop(&sFunctionTimer);
+ mFunctionTimerActive = false;
+}
+
+void AppTask::StartTimer(uint32_t timeoutInMs)
+{
+ k_timer_start(&sFunctionTimer, K_MSEC(timeoutInMs), K_NO_WAIT);
+ mFunctionTimerActive = true;
+}
+
+void AppTask::PostEvent(const AppEvent & event)
+{
+ if (k_msgq_put(&sAppEventQueue, &event, K_NO_WAIT) != 0)
+ {
+ LOG_INF("Failed to post event to app task event queue");
+ }
+}
+
+void AppTask::DispatchEvent(const AppEvent & event)
+{
+ if (event.Handler)
+ {
+ event.Handler(event);
+ }
+ else
+ {
+ LOG_INF("Event received with no handler. Dropping event.");
+ }
+}
+
+void AppTask::UpdateClusterState()
+{
+ SystemLayer().ScheduleLambda([this] {
+ // write the new on/off value
+ Protocols::InteractionModel::Status status =
+ Clusters::OnOff::Attributes::OnOff::Set(kLightEndpointId, sIdentifyLED.IsTurnedOn());
+
+ if (status != Protocols::InteractionModel::Status::Success)
+ {
+ LOG_ERR("Updating on/off cluster failed: %x", to_underlying(status));
+ }
+ });
+}
diff --git a/examples/lighting-app/realtek/zephyr/main/ZclCallbacks.cpp b/examples/lighting-app/realtek/zephyr/main/ZclCallbacks.cpp
new file mode 100755
index 0000000..3b506d3
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/main/ZclCallbacks.cpp
@@ -0,0 +1,67 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "AppTask.h"
+
+#include <app-common/zap-generated/attributes/Accessors.h>
+#include <app-common/zap-generated/ids/Attributes.h>
+#include <app-common/zap-generated/ids/Clusters.h>
+#include <app/ConcreteAttributePath.h>
+#include <lib/support/logging/CHIPLogging.h>
+
+using namespace chip;
+using namespace chip::app::Clusters;
+using namespace chip::app::Clusters::OnOff;
+
+void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size,
+ uint8_t * value)
+{
+ ClusterId clusterId = attributePath.mClusterId;
+ AttributeId attributeId = attributePath.mAttributeId;
+
+ if (clusterId == OnOff::Id && attributeId == OnOff::Attributes::OnOff::Id)
+ {
+ ChipLogProgress(Zcl, "Cluster OnOff: attribute OnOff set to %u", *value);
+ AppTask::Instance().GetLightingDevice().Set(*value);
+ }
+}
+
+/** @brief OnOff 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 emberAfOnOffClusterInitCallback(EndpointId endpoint)
+{
+ Protocols::InteractionModel::Status status;
+ bool storedValue;
+
+ // Read storedValue on/off value
+ status = Attributes::OnOff::Get(endpoint, &storedValue);
+ if (status == Protocols::InteractionModel::Status::Success)
+ {
+ // Set actual state to the cluster state that was last persisted
+ AppTask::Instance().GetLightingDevice().Set(storedValue);
+ }
+
+ AppTask::Instance().UpdateClusterState();
+}
diff --git a/examples/lighting-app/realtek/zephyr/main/include/AppConfig.h b/examples/lighting-app/realtek/zephyr/main/include/AppConfig.h
new file mode 100644
index 0000000..4c5c82a
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/main/include/AppConfig.h
@@ -0,0 +1,24 @@
+/*
+ *
+ * Copyright (c) 2021 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+// ---- Lighting Example App Config ----
+
+// Lighting LED config
+#define USE_RGB_PWM 0
diff --git a/examples/lighting-app/realtek/zephyr/main/include/AppEvent.h b/examples/lighting-app/realtek/zephyr/main/include/AppEvent.h
new file mode 100644
index 0000000..b387e91
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/main/include/AppEvent.h
@@ -0,0 +1,75 @@
+/*
+ *
+ * Copyright (c) 2018 Nest Labs, Inc.
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <cstdint>
+
+struct AppEvent;
+using EventHandler = void (*)(const AppEvent &);
+
+class LEDWidget;
+
+enum class AppEventType : uint8_t
+{
+ None = 0,
+ Button,
+ ButtonPushed,
+ ButtonReleased,
+ Timer,
+ UpdateLedState,
+ Lighting,
+ IdentifyStart,
+ IdentifyStop,
+};
+
+enum class FunctionEvent : uint8_t
+{
+ NoneSelected = 0,
+ SoftwareUpdate = 1,
+ FactoryReset,
+ AdvertisingStart
+};
+
+struct AppEvent
+{
+ union
+ {
+ struct
+ {
+ uint8_t ButtonIdx;
+ uint8_t Action;
+ } ButtonEvent;
+ struct
+ {
+ void * Context;
+ } TimerEvent;
+ struct
+ {
+ uint8_t Action;
+ int32_t Actor;
+ } LightingEvent;
+ struct
+ {
+ LEDWidget * LedWidget;
+ } UpdateLedStateEvent;
+ };
+
+ AppEventType Type{ AppEventType::None };
+ EventHandler Handler;
+};
diff --git a/examples/lighting-app/realtek/zephyr/main/include/AppTask.h b/examples/lighting-app/realtek/zephyr/main/include/AppTask.h
new file mode 100644
index 0000000..13dbd8d
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/main/include/AppTask.h
@@ -0,0 +1,83 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "AppEvent.h"
+#include "LEDWidget.h"
+#include <cstdint>
+
+#include <platform/CHIPDeviceLayer.h>
+
+#if CONFIG_CHIP_FACTORY_DATA
+#include <platform/realtek/zephyr/FactoryDataProvider.h>
+#else
+#include <platform/realtek/zephyr/DeviceInstanceInfoProviderImpl.h>
+#endif
+
+#ifdef CONFIG_CHIP_PW_RPC
+#include "Rpc.h"
+#endif
+
+struct k_timer;
+struct Identify;
+
+class AppTask
+{
+public:
+ static AppTask & Instance()
+ {
+ static AppTask sAppTask;
+ return sAppTask;
+ };
+
+ CHIP_ERROR StartApp();
+
+ void UpdateClusterState();
+
+ static void IdentifyStartHandler(Identify *);
+ static void IdentifyStopHandler(Identify *);
+
+ LEDWidget & GetLightingDevice(void);
+
+private:
+ CHIP_ERROR Init();
+
+ void CancelTimer();
+ void StartTimer(uint32_t timeoutInMs);
+
+ static void PostEvent(const AppEvent & event);
+ static void DispatchEvent(const AppEvent & event);
+ static void FunctionTimerEventHandler(const AppEvent & event);
+ static void UpdateLedStateEventHandler(const AppEvent & event);
+
+ static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg);
+ static void ButtonEventHandler(uint8_t buttonIdx, uint8_t state);
+ static void FunctionTimerTimeoutCallback(k_timer * timer);
+
+ static void UpdateStatusLED();
+ static void LEDStateUpdateHandler(LEDWidget & ledWidget);
+ static void FunctionHandler(const AppEvent & event);
+
+ FunctionEvent mFunction = FunctionEvent::NoneSelected;
+ bool mFunctionTimerActive = false;
+
+#if CONFIG_CHIP_FACTORY_DATA
+ chip::DeviceLayer::FactoryDataProvider<chip::DeviceLayer::InternalFlashFactoryData> mFactoryDataProvider;
+#endif
+};
diff --git a/examples/lighting-app/realtek/zephyr/main/include/CHIPProjectConfig.h b/examples/lighting-app/realtek/zephyr/main/include/CHIPProjectConfig.h
new file mode 100644
index 0000000..e8d4a05
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/main/include/CHIPProjectConfig.h
@@ -0,0 +1,146 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ * Copyright (c) 2019 Google LLC.
+ * 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
+
+/**
+ * @def CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE
+ *
+ * @brief
+ * Test Spake2p passcode to use.
+ */
+#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE
+#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021
+#endif
+
+/**
+ * @def CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR
+ *
+ * @brief
+ * Setup discriminator to use.
+ */
+#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR
+#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00
+#endif
+
+// For convenience, Chip Security Test Mode can be enabled and the
+// requirement for authentication in various protocols can be disabled.
+//
+// WARNING: These options make it possible to circumvent basic Chip security functionality,
+// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS.
+//
+// #define CHIP_CONFIG_SECURITY_TEST_MODE 0
+
+/**
+ * CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID
+ *
+ * The CHIP-assigned vendor id for the organization responsible for producing the device.
+ *
+ * Default is the Test VendorID of 0xFFF1.
+ */
+#ifndef CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID
+#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID 0xFFF1
+#endif
+
+/**
+ * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID
+ *
+ * The unique id assigned by the device vendor to identify the product or device type. This
+ * number is scoped to the device vendor id.
+ */
+#ifndef CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID
+#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID 0x8001
+#endif
+
+/**
+ * CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME
+ *
+ * Human readable vendor name for the organization responsible for producing the device.
+ */
+#ifndef CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME
+#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME "TEST_VENDOR"
+#endif
+
+/**
+ * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME
+ *
+ * Human readable name of the device model.
+ */
+#ifndef CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME
+#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME "TEST_PRODUCT"
+#endif
+
+/**
+ * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER
+ *
+ * Enables the use of a hard-coded default serial number.
+ */
+#ifndef CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER
+#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN"
+#endif
+
+/**
+ * CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION
+ *
+ * The default hardware version number assigned to the device or product by the device vendor.
+ *
+ * Hardware versions are specific to a particular device vendor and product id, and typically
+ * correspond to a revision of the physical device, a change to its packaging, and/or a change
+ * to its marketing presentation. This value is generally *not* incremented for device software
+ * revisions.
+ */
+#ifndef CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION
+#define CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION 1
+#endif
+
+/**
+ * CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING
+ *
+ * Human readable string identifying version of the product assigned by the device vendor.
+ */
+#ifndef CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING
+#define CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING "1.0"
+#endif
+
+/**
+ * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION
+ *
+ * A monotonic number identifying the software version running on the device.
+ */
+#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION
+#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 1
+#endif
+
+/**
+ * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING
+ *
+ * A string identifying the software version running on the device.
+ */
+#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING
+#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0"
+#endif
diff --git a/examples/lighting-app/realtek/zephyr/main/main.cpp b/examples/lighting-app/realtek/zephyr/main/main.cpp
new file mode 100644
index 0000000..655ffcf
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/main/main.cpp
@@ -0,0 +1,66 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "AppTask.h"
+#include <system/SystemError.h>
+#include <zephyr/logging/log.h>
+#include <zephyr/sys/reboot.h>
+
+#ifdef CONFIG_CHIP_PW_RPC
+#include "Rpc.h"
+#endif
+
+LOG_MODULE_REGISTER(app, CONFIG_CHIP_APP_LOG_LEVEL);
+
+using namespace ::chip;
+
+#include "rtl_wdt.h"
+#include "soc.h"
+#include <openthread-system.h>
+#include <openthread/instance.h>
+#include <openthread/platform/alarm-micro.h>
+#include <openthread/platform/alarm-milli.h>
+#include <openthread/platform/time.h>
+
+extern "C" {
+// replace misc.c
+
+extern void WDG_SystemReset(WDTMode_TypeDef wdt_mode, int reset_reason);
+void __wrap_otPlatReset(otInstance * aInstance)
+{
+ ARG_UNUSED(aInstance);
+ WDG_SystemReset(RESET_ALL, 0xff);
+}
+}
+
+int main()
+{
+ CHIP_ERROR err = CHIP_NO_ERROR;
+
+#ifdef CONFIG_CHIP_PW_RPC
+ rpc::Init();
+#endif
+
+ if (err == CHIP_NO_ERROR)
+ {
+ err = AppTask::Instance().StartApp();
+ }
+
+ LOG_ERR("Exited with code %" CHIP_ERROR_FORMAT, err.Format());
+ return err == CHIP_NO_ERROR ? EXIT_SUCCESS : EXIT_FAILURE;
+}
diff --git a/examples/lighting-app/realtek/zephyr/prj.conf b/examples/lighting-app/realtek/zephyr/prj.conf
new file mode 100644
index 0000000..d285f6f
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/prj.conf
@@ -0,0 +1,105 @@
+#
+# Copyright (c) 2021-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.
+
+CONFIG_REALTEK_MAC_802154=y
+
+# Enable CHIP
+CONFIG_CHIP=y
+CONFIG_STD_CPP17=y
+
+# CHIP configuration
+CONFIG_CHIP_PROJECT_CONFIG="main/include/CHIPProjectConfig.h"
+
+# 32773 == 0x8005 (example lighting-app)
+CONFIG_CHIP_DEVICE_PRODUCT_ID=32773
+
+# Bluetooth Low Energy configuration
+CONFIG_BT_DEVICE_NAME="RealtekLight"
+
+# Enable Matter OTA DFU
+# CONFIG_REALTEK_OTA=n
+# 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_SHELL=n
+CONFIG_CHIP_LIB_SHELL=n
+CONFIG_OPENTHREAD_SHELL=n
+
+# Disable CHIP NFC for commissioning
+CONFIG_CHIP_NFC_COMMISSIONING=n
+
+# Disable factory data support
+CONFIG_CHIP_FACTORY_DATA=n
+CONFIG_CHIP_FACTORY_DATA_BUILD=n
+CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n
+CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE=n
+
+#Enable PWM
+CONFIG_PWM=n
+
+# Enable Power Management
+CONFIG_PM=n
+
+CONFIG_MAIN_STACK_SIZE=8192
+CONFIG_NEWLIB_LIBC=y
+
+# Enable OpenThread features set
+CONFIG_OPENTHREAD_THREAD_VERSION_1_3=y
+CONFIG_OPENTHREAD_COAP=y
+CONFIG_OPENTHREAD_COAPS=y
+CONFIG_OPENTHREAD_COMMISSIONER=y
+CONFIG_OPENTHREAD_DIAG=y
+CONFIG_OPENTHREAD_DNS_CLIENT=y
+CONFIG_OPENTHREAD_DHCP6_SERVER=y
+CONFIG_OPENTHREAD_DHCP6_CLIENT=y
+CONFIG_OPENTHREAD_ECDSA=y
+CONFIG_OPENTHREAD_ENABLE_SERVICE=y
+CONFIG_OPENTHREAD_EXTERNAL_HEAP=y
+CONFIG_OPENTHREAD_IP6_FRAGM=y
+CONFIG_OPENTHREAD_JAM_DETECTION=y
+CONFIG_OPENTHREAD_JOINER=y
+CONFIG_OPENTHREAD_MAC_FILTER=y
+CONFIG_OPENTHREAD_NETDIAG_CLIENT=y
+CONFIG_OPENTHREAD_RAW=y
+CONFIG_OPENTHREAD_SLAAC=y
+CONFIG_OPENTHREAD_SNTP_CLIENT=y
+CONFIG_OPENTHREAD_SRP_CLIENT=y
+CONFIG_OPENTHREAD_UDP_FORWARD=y
+CONFIG_OPENTHREAD_DUA=y
+CONFIG_OPENTHREAD_MLR=y
+CONFIG_OPENTHREAD_LINK_METRICS_INITIATOR=y
+CONFIG_OPENTHREAD_LINK_METRICS_SUBJECT=y
+CONFIG_OPENTHREAD_CSL_RECEIVER=y
+
+# Openthread L2
+CONFIG_OPENTHREAD_MANUAL_START=y
+CONFIG_NET_L2_OPENTHREAD=y
+
+# Generic networking options
+CONFIG_NETWORKING=y
+CONFIG_NET_PKT_TXTIME=y
+CONFIG_NET_PKT_TIMESTAMP=y
+
+# CONFIG_LOG_MODE_DEFERRED=y
+# CONFIG_LOG_BUFFER_SIZE=4096
diff --git a/examples/lighting-app/realtek/zephyr/third_party/connectedhomeip b/examples/lighting-app/realtek/zephyr/third_party/connectedhomeip
new file mode 120000
index 0000000..3efed95
--- /dev/null
+++ b/examples/lighting-app/realtek/zephyr/third_party/connectedhomeip
@@ -0,0 +1 @@
+../../../../../
\ No newline at end of file
diff --git a/examples/platform/realtek/zephyr/LEDWidget.cpp b/examples/platform/realtek/zephyr/LEDWidget.cpp
new file mode 100755
index 0000000..973263c
--- /dev/null
+++ b/examples/platform/realtek/zephyr/LEDWidget.cpp
@@ -0,0 +1,124 @@
+/*
+ *
+ * Copyright (c) 2021 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "LEDWidget.h"
+
+#include <zephyr/kernel.h>
+#include <zephyr/logging/log.h>
+
+LOG_MODULE_REGISTER(LEDWidget, CONFIG_CHIP_APP_LOG_LEVEL);
+
+static LEDWidget::LEDWidgetStateUpdateHandler sStateUpdateCallback;
+
+void LEDWidget::SetStateUpdateCallback(LEDWidgetStateUpdateHandler stateUpdateCb)
+{
+ if (stateUpdateCb)
+ sStateUpdateCallback = stateUpdateCb;
+}
+
+void LEDWidget::Init(gpio_dt_spec gpio)
+{
+ mBlinkOnTimeMS = 0;
+ mBlinkOffTimeMS = 0;
+ mGPIO = gpio;
+ mState = false;
+
+ if (!gpio_is_ready_dt(&mGPIO))
+ {
+ LOG_ERR("GPIO device not ready");
+ }
+ else
+ {
+ int ret = gpio_pin_configure_dt(&mGPIO, GPIO_OUTPUT_ACTIVE);
+ if (ret < 0)
+ {
+ LOG_ERR("GPIO pin %d configure - fail. Status%d\n", mGPIO.pin, ret);
+ }
+ }
+
+ k_timer_init(&mLedTimer, &LEDWidget::LedStateTimerHandler, nullptr);
+ k_timer_user_data_set(&mLedTimer, this);
+
+ Set(false);
+}
+
+void LEDWidget::Invert(void)
+{
+ Set(!mState);
+}
+
+void LEDWidget::Set(bool state)
+{
+ k_timer_stop(&mLedTimer);
+ mBlinkOnTimeMS = mBlinkOffTimeMS = 0;
+ DoSet(state);
+}
+
+void LEDWidget::Blink(uint32_t changeRateMS)
+{
+ Blink(changeRateMS, changeRateMS);
+}
+
+void LEDWidget::Blink(uint32_t onTimeMS, uint32_t offTimeMS)
+{
+ k_timer_stop(&mLedTimer);
+
+ mBlinkOnTimeMS = onTimeMS;
+ mBlinkOffTimeMS = offTimeMS;
+
+ if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0)
+ {
+ DoSet(!mState);
+ ScheduleStateChange();
+ }
+}
+
+void LEDWidget::ScheduleStateChange()
+{
+ k_timer_start(&mLedTimer, K_MSEC(mState ? mBlinkOnTimeMS : mBlinkOffTimeMS), K_NO_WAIT);
+}
+
+void LEDWidget::DoSet(bool state)
+{
+ if (!gpio_is_ready_dt(&mGPIO))
+ {
+ return;
+ }
+ mState = state;
+ int ret = gpio_pin_set_dt(&mGPIO, state);
+ if (ret < 0)
+ {
+ LOG_ERR("GPIO pin %d set -fail. Status: %d\n", mGPIO.pin, ret);
+ }
+}
+
+void LEDWidget::UpdateState()
+{
+ /* Prevent from keep updating the state if LED was set to solid On/Off value */
+ if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0)
+ {
+ DoSet(!mState);
+ ScheduleStateChange();
+ }
+}
+
+void LEDWidget::LedStateTimerHandler(k_timer * timer)
+{
+ if (sStateUpdateCallback)
+ sStateUpdateCallback(reinterpret_cast<LEDWidget *>(timer->user_data));
+}
diff --git a/examples/platform/realtek/zephyr/LEDWidget.h b/examples/platform/realtek/zephyr/LEDWidget.h
new file mode 100755
index 0000000..752b0ff
--- /dev/null
+++ b/examples/platform/realtek/zephyr/LEDWidget.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2021 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <zephyr/drivers/gpio.h>
+#include <zephyr/kernel.h>
+
+class LEDWidget
+{
+public:
+ typedef void (*LEDWidgetStateUpdateHandler)(LEDWidget * ledWidget);
+
+ static void SetStateUpdateCallback(LEDWidgetStateUpdateHandler stateUpdateCb);
+ void Init(gpio_dt_spec gpio);
+ void Set(bool state);
+ void Invert(void);
+ void Blink(uint32_t changeRateMS);
+ void Blink(uint32_t onTimeMS, uint32_t offTimeMS);
+ void UpdateState();
+ bool IsTurnedOn() { return mState; }
+
+private:
+ uint32_t mBlinkOnTimeMS;
+ uint32_t mBlinkOffTimeMS;
+ gpio_dt_spec mGPIO;
+ bool mState;
+ k_timer mLedTimer;
+
+ static void LedStateTimerHandler(k_timer * timer);
+
+ void DoSet(bool state);
+ void ScheduleStateChange();
+};
diff --git a/examples/platform/realtek/zephyr/matter_button.c b/examples/platform/realtek/zephyr/matter_button.c
new file mode 100644
index 0000000..2a6e36e
--- /dev/null
+++ b/examples/platform/realtek/zephyr/matter_button.c
@@ -0,0 +1,127 @@
+/*
+ *
+ * Copyright (c) 2021 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "matter_button.h"
+
+#include <zephyr/device.h>
+#include <zephyr/drivers/gpio.h>
+#include <zephyr/kernel.h>
+#include <zephyr/logging/log.h>
+#include <zephyr/sys/util.h>
+
+LOG_MODULE_REGISTER(matter_button, CONFIG_CHIP_APP_LOG_LEVEL);
+
+#define BUTTONS_NODE DT_PATH(buttons)
+#define INCREMENT_BY_ONE(button) +1
+#define NUMBER_OF_BUTTONS (0 DT_FOREACH_CHILD(BUTTONS_NODE, INCREMENT_BY_ONE))
+#define GPIO_SPEC_AND_COMMA(button) GPIO_DT_SPEC_GET(button, gpios),
+
+static const struct gpio_dt_spec buttons[] = {
+#if DT_NODE_EXISTS(BUTTONS_NODE)
+ DT_FOREACH_CHILD(BUTTONS_NODE, GPIO_SPEC_AND_COMMA)
+#endif
+};
+static uint8_t key_trigger_level[NUMBER_OF_BUTTONS];
+static struct gpio_callback button_cb_data;
+static button_handler_t button_handler_cb;
+
+void button_pressed(const struct device * dev, struct gpio_callback * cb, uint32_t pins)
+{
+ uint8_t state;
+ uint8_t i;
+
+ for (i = 0; i < ARRAY_SIZE(buttons); i++)
+ {
+ if (pins == BIT(buttons[i].pin))
+ {
+ break;
+ }
+ }
+
+ if (i == ARRAY_SIZE(buttons))
+ {
+ return;
+ }
+
+ if (key_trigger_level[i] == GPIO_ACTIVE_HIGH)
+ {
+ gpio_pin_interrupt_configure_dt(&buttons[i], GPIO_INT_EDGE_TO_INACTIVE);
+ key_trigger_level[i] = GPIO_ACTIVE_LOW;
+ state = MATTER_BUTTON_STATE_PRESS;
+ }
+ else
+ {
+ gpio_pin_interrupt_configure_dt(&buttons[i], GPIO_INT_EDGE_TO_ACTIVE);
+ key_trigger_level[i] = GPIO_ACTIVE_HIGH;
+ state = MATTER_BUTTON_STATE_RELEASE;
+ }
+
+ if (button_handler_cb != NULL)
+ {
+ button_handler_cb(i, state);
+ }
+}
+
+int matter_button_init(button_handler_t button_handler)
+{
+ uint32_t pin_mask = 0;
+ int err;
+
+ button_handler_cb = button_handler;
+
+ for (size_t i = 0; i < ARRAY_SIZE(buttons); i++)
+ {
+ key_trigger_level[i] = GPIO_ACTIVE_HIGH;
+
+ if (!gpio_is_ready_dt(&buttons[i]))
+ {
+ LOG_ERR("button device %s is not ready", buttons[i].port->name);
+ return -EIO;
+ }
+
+ err = gpio_pin_configure_dt(&buttons[i], GPIO_INPUT);
+ if (err)
+ {
+ LOG_ERR("Error %d: failed to configure %s pin %d", err, buttons[i].port->name, buttons[i].pin);
+ return err;
+ }
+
+ err = gpio_pin_interrupt_configure_dt(&buttons[i], GPIO_INT_EDGE_TO_ACTIVE);
+ if (err != 0)
+ {
+ LOG_ERR("Error %d: failed to configure interrupt on %s pin %d", err, buttons[i].port->name, buttons[i].pin);
+ return err;
+ }
+
+ pin_mask |= BIT(buttons[i].pin);
+ }
+
+ gpio_init_callback(&button_cb_data, button_pressed, pin_mask);
+
+ for (size_t i = 0; i < ARRAY_SIZE(buttons); i++)
+ {
+ err = gpio_add_callback(buttons[i].port, &button_cb_data);
+ if (err)
+ {
+ LOG_ERR("Cannot add callback");
+ return err;
+ }
+ }
+
+ return err;
+}
diff --git a/examples/platform/realtek/zephyr/matter_button.h b/examples/platform/realtek/zephyr/matter_button.h
new file mode 100644
index 0000000..a36320b
--- /dev/null
+++ b/examples/platform/realtek/zephyr/matter_button.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2021 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <zephyr/drivers/gpio.h>
+#include <zephyr/kernel.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define MATTER_BUTTON_STATE_RELEASE 0
+#define MATTER_BUTTON_STATE_PRESS 1
+
+typedef void (*button_handler_t)(uint8_t button_index, uint8_t state);
+
+int matter_button_init(button_handler_t button_handler);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py
index 36d1914..f3974b0 100755
--- a/scripts/build/build/targets.py
+++ b/scripts/build/build/targets.py
@@ -836,6 +836,7 @@
# board
target.AppendFixedTargets([
TargetPart('rtl8777g', board=RealtekBoard.RTL8777G),
+ TargetPart('rtl87x2g', board=RealtekBoard.RTL87X2G),
])
# apps
diff --git a/scripts/build/builders/realtek.py b/scripts/build/builders/realtek.py
index 4e74984..e99d626 100644
--- a/scripts/build/builders/realtek.py
+++ b/scripts/build/builders/realtek.py
@@ -18,12 +18,31 @@
from .builder import Builder, BuilderOutput
+class RtkOsUsed(Enum):
+ FREERTOS = auto()
+ ZEPHYR = auto()
+
+ def OsEnv(self):
+ if self == RtkOsUsed.ZEPHYR:
+ return 'zephyr'
+ elif self == RtkOsUsed.FREERTOS:
+ return 'freertos'
+ else:
+ raise Exception('Unknown OS type: %r' % self)
+
+
class RealtekBoard(Enum):
RTL8777G = auto()
+ RTL87X2G = auto()
@property
def BoardName(self):
- return 'rtl8777g'
+ if self == RealtekBoard.RTL8777G:
+ return 'rtl8777g'
+ elif self == RealtekBoard.RTL87X2G:
+ return 'rtl87x2g'
+ else:
+ raise Exception('Unknown board type: %r' % self)
class RealtekApp(Enum):
@@ -111,6 +130,13 @@
self.enable_shell = enable_shell
self.ot_src_dir = os.path.join(os.getcwd(), 'third_party/openthread/ot-realtek')
+ if self.board == RealtekBoard.RTL87X2G:
+ self.os_env = RtkOsUsed.ZEPHYR
+ elif self.board == RealtekBoard.RTL8777G:
+ self.os_env = RtkOsUsed.FREERTOS
+ else:
+ raise Exception('Unknown board type: %r' % self.board)
+
def CmakeBuildFlags(self) -> str:
flags = [
"-DCMAKE_BUILD_TYPE=Release",
@@ -135,31 +161,67 @@
flags.append("-DENABLE_SHELL=OFF")
return " ".join(flags)
+ def get_cmd_prefixes(self):
+ # Zephyr base
+ if 'ZEPHYR_REALTEK_BASE' not in os.environ:
+ raise Exception("Realtek builds require ZEPHYR_REALTEK_BASE")
+
+ cmd = 'export ZEPHYR_BASE="$ZEPHYR_REALTEK_BASE"\n'
+
+ if 'ZEPHYR_REALTEK_SDK_INSTALL_DIR' in os.environ:
+ cmd += 'export ZEPHYR_SDK_INSTALL_DIR="$ZEPHYR_REALTEK_SDK_INSTALL_DIR"\n'
+
+ return cmd
+
def generate(self):
- cmd = 'arm-none-eabi-gcc -D BUILD_BANK=0 -E -P -x c {ot_src_dir}/src/bee4/{board_name}/app.ld -o {ot_src_dir}/src/bee4/{board_name}/app.ld.gen'.format(
- ot_src_dir=self.ot_src_dir,
- board_name=self.board.BoardName)
- self._Execute(['bash', '-c', cmd])
- cmd = 'cmake -GNinja -DOT_COMPILE_WARNING_AS_ERROR=ON {build_flags} {example_folder} -B{out_folder}'.format(
- build_flags=self.CmakeBuildFlags(),
- example_folder=self.ot_src_dir,
- out_folder=self.output_dir)
- self._Execute(['bash', '-c', cmd], title='Generating ' + self.identifier)
+ if self.os_env != RtkOsUsed.FREERTOS:
+ # For freertos, app.ld needs to be precompiled with gcc
+ return
+ else:
+ cmd = 'arm-none-eabi-gcc -D BUILD_BANK=0 -E -P -x c {ot_src_dir}/src/bee4/{board_name}/app.ld -o {ot_src_dir}/src/bee4/{board_name}/app.ld.gen'.format(
+ ot_src_dir=self.ot_src_dir,
+ board_name=self.board.BoardName)
+ self._Execute(['bash', '-c', cmd])
+ cmd = 'cmake -GNinja -DOT_COMPILE_WARNING_AS_ERROR=ON {build_flags} {example_folder} -B{out_folder}'.format(
+ build_flags=self.CmakeBuildFlags(),
+ example_folder=self.ot_src_dir,
+ out_folder=self.output_dir)
+ self._Execute(['bash', '-c', cmd], title='Generating ' + self.identifier)
def _build(self):
- cmd = ['ninja', '-C', self.output_dir]
- if self.ninja_jobs is not None:
- cmd.append('-j' + str(self.ninja_jobs))
- cmd.append(self.app.TargetName)
- self._Execute(cmd, title='Building ' + self.identifier)
- cleanup_cmd = ['rm', '-rf', f"{self.root}/third_party/openthread/ot-realtek/src/bee4/{self.board.BoardName}/*.gen"]
- self._Execute(cleanup_cmd, title='Cleaning up generated files')
+ if self.os_env == RtkOsUsed.FREERTOS:
+ cmd = ['ninja', '-C', self.output_dir]
+ if self.ninja_jobs is not None:
+ cmd.append('-j' + str(self.ninja_jobs))
+ cmd.append(self.app.TargetName)
+ self._Execute(cmd, title='Building ' + self.identifier)
+ cleanup_cmd = ['rm', '-rf', f"{self.root}/third_party/openthread/ot-realtek/src/bee4/{self.board.BoardName}/*.gen"]
+ self._Execute(cleanup_cmd, title='Cleaning up generated files')
+ else:
+ cmd = self.get_cmd_prefixes()
+ cmd += '\nsource "$ZEPHYR_BASE/zephyr-env.sh"'
+ cmd += '\nwest build -b rtl87x2g_evb -d {out_folder} {example_folder} --pristine'.format(
+ out_folder=self.output_dir,
+ example_folder=os.path.join(self.root, 'examples', self.app.ExampleName, 'realtek', 'zephyr'))
+ self._Execute(['bash', '-c', cmd], title='Building ' + self.identifier)
def build_outputs(self):
- yield BuilderOutput(
- os.path.join(self.output_dir, 'bin', self.app.TargetName),
- self.app.AppNamePrefix)
- if self.options.enable_link_map_file:
+ if self.os_env == RtkOsUsed.FREERTOS:
yield BuilderOutput(
- os.path.join(self.output_dir, 'map.map'),
- self.app.AppNamePrefix + '.map')
+ os.path.join(self.output_dir, 'bin', self.app.TargetName),
+ self.app.AppNamePrefix)
+ if self.options.enable_link_map_file:
+ yield BuilderOutput(
+ os.path.join(self.output_dir, 'map.map'),
+ self.app.AppNamePrefix + '.map')
+ else:
+ yield BuilderOutput(
+ os.path.join(self.output_dir, 'zephyr', 'zephyr.elf'),
+ self.app.AppNamePrefix + '.elf')
+ yield BuilderOutput(
+ os.path.join(self.output_dir, 'zephyr', 'zephyr.bin'),
+ self.app.AppNamePrefix + '.bin')
+ if self.options.enable_link_map_file:
+ yield BuilderOutput(
+ os.path.join(self.output_dir, 'zephyr', 'zephyr.map'),
+ self.app.AppNamePrefix + '.map')
diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt
index 2a968ec..3a10505 100644
--- a/scripts/build/testdata/all_targets_linux_x64.txt
+++ b/scripts/build/testdata/all_targets_linux_x64.txt
@@ -19,7 +19,7 @@
nrf-native-sim-tests
nuttx-x64-light
qpg-qpg6200-{light,light-switch,lock,persistent-storage,shell,thermostat}[-updateimage]
-realtek-rtl8777g-{all-clusters,light-switch,lighting,lock,ota-requestor,thermostat,window}
+realtek-{rtl8777g,rtl87x2g}-{all-clusters,light-switch,lighting,lock,ota-requestor,thermostat,window}
stm32-stm32wb5mm-dk-light
tizen-{arm,arm64}-{all-clusters,chip-tool,light,tests}[-asan][-coverage][-no-ble][-no-thread][-no-wifi][-ubsan][-with-ui]
telink-{tl3218x,tl3218x_ml3m,tl3218x_retention,tl7218x,tl7218x_ml7g,tl7218x_ml7m,tl7218x_retention,tlsr9118bdk40d,tlsr9518adk80d,tlsr9528a,tlsr9528a_retention}-{air-quality-sensor,all-clusters,all-clusters-minimal,bridge,contact-sensor,light,light-switch,lock,ota-requestor,pump,pump-controller,shell,smoke-co-alarm,temperature-measurement,thermostat,window-covering}[-4mb][-compress-lzma][-dfu][-factory-data][-mars][-ota][-precompiled-ot][-rpc][-shell][-tflm][-thread-analyzer][-usb]
diff --git a/src/platform/BUILD.gn b/src/platform/BUILD.gn
index bda0d90..6a99858 100644
--- a/src/platform/BUILD.gn
+++ b/src/platform/BUILD.gn
@@ -304,6 +304,9 @@
} else if (chip_device_platform == "realtek_bee") {
device_layer_target_define = "REALTEK_BEE"
defines += [ "CHIP_DEVICE_LAYER_TARGET=realtek/BEE" ]
+ } else if (chip_device_platform == "realtek_zephyr") {
+ device_layer_target_define = "REALTEK_ZEPHYR"
+ defines += [ "CHIP_DEVICE_LAYER_TARGET=realtek/zephyr" ]
} else if (chip_device_platform == "cyw30739") {
device_layer_target_define = "CYW30739"
defines += [ "CHIP_DEVICE_LAYER_TARGET=Infineon/CYW30739" ]
@@ -373,6 +376,7 @@
"ANDROID",
"AMEBA",
"REALTEK_BEE",
+ "REALTEK_ZEPHYR",
"CYW30739",
"WEBOS",
"MW320",
@@ -631,6 +635,8 @@
_platform_target = "Ameba"
} else if (chip_device_platform == "realtek_bee") {
_platform_target = "realtek/BEE"
+ } else if (chip_device_platform == "realtek_zephyr") {
+ _platform_target = "realtek/zephyr:realtek_zephyr"
} else if (chip_device_platform == "webos") {
_platform_target = "webos"
} else if (chip_device_platform == "bl602") {
diff --git a/src/platform/device.gni b/src/platform/device.gni
index 4e37c85..e73fed8 100644
--- a/src/platform/device.gni
+++ b/src/platform/device.gni
@@ -174,6 +174,8 @@
_chip_device_layer = "qpg"
} else if (chip_device_platform == "realtek_bee") {
_chip_device_layer = "realtek/BEE"
+} else if (chip_device_platform == "realtek_zephyr") {
+ _chip_device_layer = "realtek/zephyr"
} else if (chip_device_platform == "nxp") {
import("//build_overrides/nxp_sdk.gni")
import("${nxp_sdk_build_root}/nxp_sdk.gni")
@@ -275,6 +277,7 @@
chip_device_platform == "external" || chip_device_platform == "linux" ||
chip_device_platform == "tizen" ||
chip_device_platform == "realtek_bee" ||
+ chip_device_platform == "realtek_zephyr" ||
chip_device_platform == "nrfconnect" || chip_device_platform == "nxp" ||
chip_device_platform == "nxp_zephyr" || chip_device_platform == "qpg" ||
chip_device_platform == "telink" || chip_device_platform == "mbed" ||
diff --git a/src/platform/logging/BUILD.gn b/src/platform/logging/BUILD.gn
index 2192c8c..f7495ec 100644
--- a/src/platform/logging/BUILD.gn
+++ b/src/platform/logging/BUILD.gn
@@ -35,6 +35,8 @@
deps += [ "${chip_root}/src/platform/Ameba:logging" ]
} else if (chip_device_platform == "realtek_bee") {
deps += [ "${chip_root}/src/platform/realtek/BEE:logging" ]
+ } else if (chip_device_platform == "realtek_zephyr") {
+ deps += [ "${chip_root}/src/platform/realtek/zephyr:logging" ]
} else if (chip_device_platform == "asr") {
deps += [ "${chip_root}/src/platform/ASR:logging" ]
} else if (chip_device_platform == "webos") {
diff --git a/src/platform/realtek/zephyr/BLEManagerImpl.h b/src/platform/realtek/zephyr/BLEManagerImpl.h
new file mode 100755
index 0000000..885c1d8
--- /dev/null
+++ b/src/platform/realtek/zephyr/BLEManagerImpl.h
@@ -0,0 +1,21 @@
+/*
+ *
+ * Copyright (c) 2020-2021 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <platform/Zephyr/BLEManagerImpl.h>
diff --git a/src/platform/realtek/zephyr/BUILD.gn b/src/platform/realtek/zephyr/BUILD.gn
new file mode 100755
index 0000000..7141621
--- /dev/null
+++ b/src/platform/realtek/zephyr/BUILD.gn
@@ -0,0 +1,118 @@
+# Copyright (c) 2021 Project CHIP Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import("//build_overrides/chip.gni")
+
+import("${chip_root}/src/platform/device.gni")
+import("${chip_root}/src/platform/realtek/zephyr/args.gni")
+
+assert(chip_device_platform == "realtek_zephyr")
+
+static_library("realtek_zephyr") {
+ sources = [
+ "../../SingletonConfigurationManager.cpp",
+ "../../Zephyr/BLEAdvertisingArbiter.cpp",
+ "../../Zephyr/BLEAdvertisingArbiter.h",
+ "../../Zephyr/BLEManagerImpl.cpp",
+ "../../Zephyr/ConfigurationManagerImpl.cpp",
+ "../../Zephyr/DiagnosticDataProviderImpl.cpp",
+ "../../Zephyr/DiagnosticDataProviderImpl.h",
+ "../../Zephyr/DiagnosticDataProviderImplGetter.cpp",
+ "../../Zephyr/KeyValueStoreManagerImpl.cpp",
+ "../../Zephyr/PlatformManagerImpl.cpp",
+ "../../Zephyr/SysHeapMalloc.h",
+ "../../Zephyr/SystemTimeSupport.cpp",
+ "../../Zephyr/ZephyrConfig.cpp",
+ "../../Zephyr/ZephyrConfig.h",
+ "BLEManagerImpl.h",
+ "BlePlatformConfig.h",
+ "CHIPDevicePlatformConfig.h",
+ "CHIPDevicePlatformEvent.h",
+ "CHIPPlatformConfig.h",
+ "ConfigurationManagerImpl.h",
+ "ConnectivityManagerImpl.cpp",
+ "ConnectivityManagerImpl.h",
+ "DiagnosticDataProviderImpl.h",
+ "InetPlatformConfig.h",
+ "KeyValueStoreManagerImpl.h",
+ "PlatformManagerImpl.h",
+ "SystemPlatformConfig.h",
+ "bee4-mbedtls-config.h",
+ ]
+
+ deps = [ "${chip_root}/src/platform/logging:headers" ]
+
+ public = [
+ "${chip_root}/src/credentials/CHIPCert.h",
+ "${chip_root}/src/credentials/CertificationDeclaration.h",
+ "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h",
+ "${chip_root}/src/credentials/attestation_verifier/DefaultDeviceAttestationVerifier.h",
+ "${chip_root}/src/credentials/attestation_verifier/DeviceAttestationVerifier.h",
+ "${chip_root}/src/credentials/examples/DeviceAttestationCredsExample.h",
+ "${chip_root}/src/credentials/examples/ExampleDACs.h",
+ "${chip_root}/src/credentials/examples/ExamplePAI.h",
+ ]
+
+ public_deps = [ "${chip_root}/src/platform:platform_base" ]
+
+ if (chip_enable_factory_data) {
+ sources += [
+ "FactoryDataDecoder.cpp",
+ "FactoryDataDecoder.h",
+ "FactoryDataProvider.cpp",
+ "FactoryDataProvider.h",
+ ]
+ } else {
+ sources += [
+ "DeviceInstanceInfoProviderImpl.cpp",
+ "DeviceInstanceInfoProviderImpl.h",
+ ]
+ }
+
+ if (chip_malloc_sys_heap) {
+ sources += [ "../../Zephyr/SysHeapMalloc.cpp" ]
+ }
+
+ if (chip_enable_openthread) {
+ sources += [
+ "../../OpenThread/OpenThreadUtils.cpp",
+ "../../Zephyr/ThreadStackManagerImpl.cpp",
+ "ThreadStackManagerImpl.h",
+ ]
+
+ if (chip_mdns == "platform") {
+ sources += [
+ "../../OpenThread/DnssdImpl.cpp",
+ "../../OpenThread/OpenThreadDnssdImpl.cpp",
+ "../../OpenThread/OpenThreadDnssdImpl.h",
+ ]
+ deps += [ "${chip_root}/src/lib/dnssd:platform_header" ]
+ }
+ }
+
+ if (chip_enable_ota_requestor) {
+ sources += [
+ "OTAImageProcessorImpl.cpp",
+ "OTAImageProcessorImpl.h",
+ ]
+ }
+}
+
+source_set("logging") {
+ deps = [
+ "${chip_root}/src/platform:platform_base",
+ "${chip_root}/src/platform/logging:headers",
+ ]
+ sources = [ "../../Zephyr/Logging.cpp" ]
+}
diff --git a/src/platform/realtek/zephyr/BlePlatformConfig.h b/src/platform/realtek/zephyr/BlePlatformConfig.h
new file mode 100644
index 0000000..c2734dc
--- /dev/null
+++ b/src/platform/realtek/zephyr/BlePlatformConfig.h
@@ -0,0 +1,31 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <zephyr/bluetooth/bluetooth.h>
+
+// ==================== Platform Adaptations ====================
+
+#define BLE_CONNECTION_OBJECT bt_conn *
+#define BLE_CONNECTION_UNINITIALIZED nullptr
+#define BLE_MAX_RECEIVE_WINDOW_SIZE 5
+
+// ========== Platform-specific Configuration Overrides =========
+
+/* none so far */
diff --git a/src/platform/realtek/zephyr/CHIPDevicePlatformConfig.h b/src/platform/realtek/zephyr/CHIPDevicePlatformConfig.h
new file mode 100755
index 0000000..5aeafd3
--- /dev/null
+++ b/src/platform/realtek/zephyr/CHIPDevicePlatformConfig.h
@@ -0,0 +1,92 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+// ==================== Platform Adaptations ====================
+
+#ifndef CHIP_DEVICE_CONFIG_ENABLE_WIFI
+#define CHIP_DEVICE_CONFIG_ENABLE_WIFI 0
+#endif
+
+#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
+#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 1
+#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0
+#else
+#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 0
+#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0
+#endif
+
+// realtek platform does not support ethernet yet, but we need this config defined as we share the Zephyr platform
+#ifndef CHIP_DEVICE_CONFIG_ENABLE_ETHERNET
+#define CHIP_DEVICE_CONFIG_ENABLE_ETHERNET 0
+#endif // CHIP_DEVICE_CONFIG_ENABLE_ETHERNET
+
+#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1
+
+#if CHIP_ENABLE_OPENTHREAD
+#define CHIP_DEVICE_CONFIG_ENABLE_THREAD 1
+#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 OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE 1
+#endif
+
+// ========== Platform-specific Configuration =========
+
+// These are configuration options that are unique to the platform.
+// These can be overridden by the application as needed.
+
+#ifndef CHIP_DEVICE_CONFIG_SETTINGS_KEY
+/// Key for all Matter persistent data stored using the Zephyr Settings API
+#define CHIP_DEVICE_CONFIG_SETTINGS_KEY "mt"
+#endif //
+
+#ifndef CHIP_DEVICE_CONFIG_HEAP_STATISTICS_MALLINFO
+#if !defined(CONFIG_CHIP_MALLOC_SYS_HEAP) && defined(CONFIG_NEWLIB_LIBC)
+/// Use mallinfo() to obtain the heap usage statistics exposed by SoftwareDiagnostics cluster attributes.
+#define CHIP_DEVICE_CONFIG_HEAP_STATISTICS_MALLINFO 1
+#else
+#define CHIP_DEVICE_CONFIG_HEAP_STATISTICS_MALLINFO 0
+#endif // !defined(CONFIG_CHIP_MALLOC_SYS_HEAP) && defined(CONFIG_NEWLIB_LIBC)
+#endif // CHIP_DEVICE_CONFIG_HEAP_STATISTICS_MALLINFO
+
+#ifndef CHIP_DEVICE_BLE_ADVERTISING_PRIORITY
+/// Priority of the Matter BLE advertising when there are multiple application
+/// components that compete for the BLE advertising.
+#define CHIP_DEVICE_BLE_ADVERTISING_PRIORITY 0
+#endif // CHIP_DEVICE_BLE_ADVERTISING_PRIORITY
+
+// ========== Platform-specific Configuration Overrides =========
+
+#ifndef CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY
+#define CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY (K_PRIO_PREEMPT(1))
+#endif // CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY
+
+#ifndef CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE
+#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE (8 * 1024)
+#endif // CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE
+
+#ifndef CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE
+#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE (7 * 1024)
+#endif // CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE
+
+#define CHIP_DEVICE_CONFIG_MAX_EVENT_QUEUE_SIZE 25
+
+#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
diff --git a/src/platform/realtek/zephyr/CHIPDevicePlatformEvent.h b/src/platform/realtek/zephyr/CHIPDevicePlatformEvent.h
new file mode 100755
index 0000000..682bc0c
--- /dev/null
+++ b/src/platform/realtek/zephyr/CHIPDevicePlatformEvent.h
@@ -0,0 +1,20 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <platform/Zephyr/CHIPDevicePlatformEvent.h>
diff --git a/src/platform/realtek/zephyr/CHIPPlatformConfig.h b/src/platform/realtek/zephyr/CHIPPlatformConfig.h
new file mode 100755
index 0000000..40beda0
--- /dev/null
+++ b/src/platform/realtek/zephyr/CHIPPlatformConfig.h
@@ -0,0 +1,88 @@
+/*
+ *
+ * Copyright (c) 2020-2022 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+// ==================== General Platform Adaptations ====================
+
+#define CHIP_CONFIG_ABORT() abort()
+
+#define CHIP_CONFIG_ENABLE_TUNNELING 0
+#define CHIP_CONFIG_MAX_TUNNELS 0
+#define CHIP_CONFIG_ENABLE_SERVICE_DIRECTORY 0
+
+#define CHIP_CONFIG_PERSISTED_STORAGE_ENC_MSG_CNTR_ID 1
+#define CHIP_CONFIG_PERSISTED_STORAGE_MAX_KEY_LENGTH 2
+
+// ==================== Security Adaptations ====================
+
+// ==================== General Configuration Overrides ====================
+
+#ifndef CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS
+#define CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS 16
+#endif // CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS
+
+#ifndef CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS
+#define CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS 8
+#endif // CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS
+
+#ifndef CHIP_CONFIG_WRMP_TIMER_DEFAULT_PERIOD
+#define CHIP_CONFIG_WRMP_TIMER_DEFAULT_PERIOD 50
+#endif // CHIP_CONFIG_WRMP_TIMER_DEFAULT_PERIOD
+
+#ifndef CHIP_LOG_FILTERING
+#define CHIP_LOG_FILTERING 0
+#endif // CHIP_LOG_FILTERING
+
+#ifndef CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS
+#define CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS 1
+#endif // CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS
+
+#ifndef CHIP_CONFIG_MAX_FABRICS
+#define CHIP_CONFIG_MAX_FABRICS 5
+#endif // CHIP_CONFIG_MAX_FABRICS
+
+// Set MRP retry intervals for Thread and Wi-Fi to test-proven values.
+#ifndef CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL
+#if CHIP_ENABLE_OPENTHREAD
+#define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL (800_ms32)
+#else
+#define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL (2000_ms32)
+#endif // CHIP_ENABLE_OPENTHREAD
+#endif // CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL
+
+#ifndef CHIP_CONFIG_MRP_LOCAL_IDLE_RETRY_INTERVAL
+#if CHIP_ENABLE_OPENTHREAD
+#define CHIP_CONFIG_MRP_LOCAL_IDLE_RETRY_INTERVAL (800_ms32)
+#else
+#define CHIP_CONFIG_MRP_LOCAL_IDLE_RETRY_INTERVAL (2000_ms32)
+#endif // CHIP_ENABLE_OPENTHREAD
+#endif // CHIP_CONFIG_MRP_LOCAL_IDLE_RETRY_INTERVAL
+
+// ==================== Security Configuration Overrides ====================
+
+#ifndef CHIP_CONFIG_FREERTOS_USE_STATIC_QUEUE
+#define CHIP_CONFIG_FREERTOS_USE_STATIC_QUEUE 0
+#endif
+
+#ifndef CHIP_CONFIG_FREERTOS_USE_STATIC_TASK
+#define CHIP_CONFIG_FREERTOS_USE_STATIC_TASK 0
+#endif
+
+#ifndef CHIP_CONFIG_FREERTOS_USE_STATIC_SEMAPHORE
+#define CHIP_CONFIG_FREERTOS_USE_STATIC_SEMAPHORE 0
+#endif
diff --git a/src/platform/realtek/zephyr/ConfigurationManagerImpl.h b/src/platform/realtek/zephyr/ConfigurationManagerImpl.h
new file mode 100644
index 0000000..52fa93d
--- /dev/null
+++ b/src/platform/realtek/zephyr/ConfigurationManagerImpl.h
@@ -0,0 +1,21 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <platform/Zephyr/ConfigurationManagerImpl.h>
diff --git a/src/platform/realtek/zephyr/ConnectivityManagerImpl.cpp b/src/platform/realtek/zephyr/ConnectivityManagerImpl.cpp
new file mode 100755
index 0000000..504b0d0
--- /dev/null
+++ b/src/platform/realtek/zephyr/ConnectivityManagerImpl.cpp
@@ -0,0 +1,69 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <platform/internal/CHIPDeviceLayerInternal.h>
+
+#include <platform/ConnectivityManager.h>
+#include <platform/internal/BLEManager.h>
+
+#include <lib/support/CodeUtils.h>
+#include <lib/support/logging/CHIPLogging.h>
+
+#include <platform/internal/GenericConnectivityManagerImpl_UDP.ipp>
+
+#if INET_CONFIG_ENABLE_TCP_ENDPOINT
+#include <platform/internal/GenericConnectivityManagerImpl_TCP.ipp>
+#endif
+
+#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
+#include <platform/internal/GenericConnectivityManagerImpl_BLE.ipp>
+#endif
+
+#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
+#include <platform/internal/GenericConnectivityManagerImpl_Thread.ipp>
+#endif
+
+using namespace ::chip;
+using namespace ::chip::TLV;
+using namespace ::chip::DeviceLayer::Internal;
+
+namespace chip {
+namespace DeviceLayer {
+
+ConnectivityManagerImpl ConnectivityManagerImpl::sInstance;
+
+CHIP_ERROR ConnectivityManagerImpl::_Init()
+{
+#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
+ GenericConnectivityManagerImpl_Thread<ConnectivityManagerImpl>::_Init();
+#endif
+#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
+ ReturnErrorOnFailure(InitWiFi());
+#endif
+ return CHIP_NO_ERROR;
+}
+
+void ConnectivityManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event)
+{
+ // Forward the event to the generic base classes as needed.
+#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
+ GenericConnectivityManagerImpl_Thread<ConnectivityManagerImpl>::_OnPlatformEvent(event);
+#endif
+}
+
+} // namespace DeviceLayer
+} // namespace chip
diff --git a/src/platform/realtek/zephyr/ConnectivityManagerImpl.h b/src/platform/realtek/zephyr/ConnectivityManagerImpl.h
new file mode 100755
index 0000000..6c122f6
--- /dev/null
+++ b/src/platform/realtek/zephyr/ConnectivityManagerImpl.h
@@ -0,0 +1,110 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <platform/ConnectivityManager.h>
+#include <platform/internal/GenericConnectivityManagerImpl.h>
+#include <platform/internal/GenericConnectivityManagerImpl_UDP.h>
+#if INET_CONFIG_ENABLE_TCP_ENDPOINT
+#include <platform/internal/GenericConnectivityManagerImpl_TCP.h>
+#endif
+#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
+#include <platform/internal/GenericConnectivityManagerImpl_BLE.h>
+#else
+#include <platform/internal/GenericConnectivityManagerImpl_NoBLE.h>
+#endif
+#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
+#include <platform/internal/GenericConnectivityManagerImpl_Thread.h>
+#else
+#include <platform/internal/GenericConnectivityManagerImpl_NoThread.h>
+#endif
+#include <platform/internal/GenericConnectivityManagerImpl_NoWiFi.h>
+
+namespace chip {
+namespace Inet {
+class IPAddress;
+} // namespace Inet
+} // namespace chip
+
+namespace chip {
+namespace DeviceLayer {
+
+/**
+ * Concrete implementation of the ConnectivityManager singleton object for Zephyr platforms.
+ */
+class ConnectivityManagerImpl final : public ConnectivityManager,
+ public Internal::GenericConnectivityManagerImpl<ConnectivityManagerImpl>,
+ public Internal::GenericConnectivityManagerImpl_UDP<ConnectivityManagerImpl>,
+#if INET_CONFIG_ENABLE_TCP_ENDPOINT
+ public Internal::GenericConnectivityManagerImpl_TCP<ConnectivityManagerImpl>,
+#endif
+#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
+ public Internal::GenericConnectivityManagerImpl_BLE<ConnectivityManagerImpl>,
+#else
+ public Internal::GenericConnectivityManagerImpl_NoBLE<ConnectivityManagerImpl>,
+#endif
+#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
+ public Internal::GenericConnectivityManagerImpl_Thread<ConnectivityManagerImpl>,
+#else
+ public Internal::GenericConnectivityManagerImpl_NoThread<ConnectivityManagerImpl>,
+#endif
+ public Internal::GenericConnectivityManagerImpl_NoWiFi<ConnectivityManagerImpl>
+{
+ // Allow the ConnectivityManager interface class to delegate method calls to
+ // the implementation methods provided by this class.
+ friend class ConnectivityManager;
+
+private:
+ // ===== Members that implement the ConnectivityManager abstract interface.
+
+ CHIP_ERROR _Init(void);
+ void _OnPlatformEvent(const ChipDeviceEvent * event);
+
+ // ===== Members for internal use by the following friends.
+
+ friend ConnectivityManager & ConnectivityMgr(void);
+ friend ConnectivityManagerImpl & ConnectivityMgrImpl(void);
+
+ static ConnectivityManagerImpl sInstance;
+};
+
+/**
+ * Returns the public interface of the ConnectivityManager singleton object.
+ *
+ * Chip applications should use this to access features of the ConnectivityManager object
+ * that are common to all platforms.
+ */
+inline ConnectivityManager & ConnectivityMgr(void)
+{
+ return ConnectivityManagerImpl::sInstance;
+}
+
+/**
+ * Returns the platform-specific implementation of the ConnectivityManager singleton object.
+ *
+ * Chip applications can use this to gain access to features of the ConnectivityManager
+ * that are specific to the QPG platform.
+ */
+inline ConnectivityManagerImpl & ConnectivityMgrImpl(void)
+{
+ return ConnectivityManagerImpl::sInstance;
+}
+
+} // namespace DeviceLayer
+} // namespace chip
diff --git a/src/platform/realtek/zephyr/DeviceInstanceInfoProviderImpl.cpp b/src/platform/realtek/zephyr/DeviceInstanceInfoProviderImpl.cpp
new file mode 100644
index 0000000..1d30d5a
--- /dev/null
+++ b/src/platform/realtek/zephyr/DeviceInstanceInfoProviderImpl.cpp
@@ -0,0 +1,47 @@
+/*
+ *
+ * Copyright (c) 2022 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "DeviceInstanceInfoProviderImpl.h"
+#include <lib/support/BytesToHex.h>
+
+namespace chip {
+namespace DeviceLayer {
+
+CHIP_ERROR DeviceInstanceInfoProviderImpl::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan)
+{
+#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CONFIG_CHIP_DEVICE_ROTATING_DEVICE_UID)
+ static_assert(ConfigurationManager::kRotatingDeviceIDUniqueIDLength >= ConfigurationManager::kMinRotatingDeviceIDUniqueIDLength,
+ "Length of unique ID for rotating device ID is smaller than minimum.");
+
+ VerifyOrReturnError(ConfigurationManager::kRotatingDeviceIDUniqueIDLength <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL);
+
+ size_t bytesLen = chip::Encoding::HexToBytes(CONFIG_CHIP_DEVICE_ROTATING_DEVICE_UID,
+ ConfigurationManager::kRotatingDeviceIDUniqueIDLength * 2, uniqueIdSpan.data(),
+ uniqueIdSpan.size());
+
+ VerifyOrReturnError(bytesLen == ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_INVALID_STRING_LENGTH);
+ uniqueIdSpan.reduce_size(bytesLen);
+
+ return CHIP_NO_ERROR;
+#endif // CHIP_ENABLE_ROTATING_DEVICE_ID
+
+ return CHIP_ERROR_NOT_IMPLEMENTED;
+}
+
+} // namespace DeviceLayer
+} // namespace chip
diff --git a/src/platform/realtek/zephyr/DeviceInstanceInfoProviderImpl.h b/src/platform/realtek/zephyr/DeviceInstanceInfoProviderImpl.h
new file mode 100644
index 0000000..1489f28
--- /dev/null
+++ b/src/platform/realtek/zephyr/DeviceInstanceInfoProviderImpl.h
@@ -0,0 +1,43 @@
+/*
+ *
+ * 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 <platform/Zephyr/ConfigurationManagerImpl.h>
+#include <platform/internal/GenericDeviceInstanceInfoProvider.h>
+
+namespace chip {
+namespace DeviceLayer {
+
+class DeviceInstanceInfoProviderImpl : public Internal::GenericDeviceInstanceInfoProvider<Internal::ZephyrConfig>
+{
+public:
+ CHIP_ERROR GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) override;
+
+ DeviceInstanceInfoProviderImpl(ConfigurationManagerImpl & configManager) :
+ Internal::GenericDeviceInstanceInfoProvider<Internal::ZephyrConfig>(configManager)
+ {}
+};
+
+inline DeviceInstanceInfoProviderImpl & DeviceInstanceInfoProviderMgrImpl()
+{
+ static DeviceInstanceInfoProviderImpl sInstance(ConfigurationManagerImpl::GetDefaultInstance());
+ return sInstance;
+}
+} // namespace DeviceLayer
+} // namespace chip
diff --git a/src/platform/realtek/zephyr/DiagnosticDataProviderImpl.h b/src/platform/realtek/zephyr/DiagnosticDataProviderImpl.h
new file mode 100755
index 0000000..7825b71
--- /dev/null
+++ b/src/platform/realtek/zephyr/DiagnosticDataProviderImpl.h
@@ -0,0 +1,20 @@
+/*
+ *
+ * Copyright (c) 2021 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <platform/Zephyr/DiagnosticDataProviderImpl.h>
diff --git a/src/platform/realtek/zephyr/FactoryDataDecoder.cpp b/src/platform/realtek/zephyr/FactoryDataDecoder.cpp
new file mode 100644
index 0000000..ab61517
--- /dev/null
+++ b/src/platform/realtek/zephyr/FactoryDataDecoder.cpp
@@ -0,0 +1,37 @@
+/*
+ *
+ * Copyright (c) 2022 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "FactoryDataDecoder.h"
+#include <platform/internal/CHIPDeviceLayerInternal.h>
+
+namespace chip {
+namespace DeviceLayer {
+
+extern "C" {
+
+CHIP_ERROR FactoryDataDecoder::ReadFactoryData(uint8_t * buffer, uint16_t * pfactorydata_len)
+{
+ return CHIP_ERROR_NOT_IMPLEMENTED;
+}
+
+CHIP_ERROR FactoryDataDecoder::DecodeFactoryData(uint8_t * buffer, FactoryData * fdata, uint16_t factorydata_len)
+{
+ return CHIP_ERROR_NOT_IMPLEMENTED;
+}
+}
+} // namespace DeviceLayer
+} // namespace chip
diff --git a/src/platform/realtek/zephyr/FactoryDataDecoder.h b/src/platform/realtek/zephyr/FactoryDataDecoder.h
new file mode 100644
index 0000000..623eb8e
--- /dev/null
+++ b/src/platform/realtek/zephyr/FactoryDataDecoder.h
@@ -0,0 +1,38 @@
+/*
+ *
+ * Copyright (c) 2022 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <platform/internal/CHIPDeviceLayerInternal.h>
+
+namespace chip {
+namespace DeviceLayer {
+
+class FactoryDataDecoder
+{
+public:
+ CHIP_ERROR ReadFactoryData(uint8_t * buffer, uint16_t * pfactorydata_len);
+ CHIP_ERROR DecodeFactoryData(uint8_t * buffer, FactoryData * fdata, uint16_t factorydata_len);
+ static FactoryDataDecoder & GetInstance()
+ {
+ static FactoryDataDecoder instance;
+ return instance;
+ }
+};
+
+} // namespace DeviceLayer
+} // namespace chip
diff --git a/src/platform/realtek/zephyr/FactoryDataProvider.cpp b/src/platform/realtek/zephyr/FactoryDataProvider.cpp
new file mode 100755
index 0000000..0f68380
--- /dev/null
+++ b/src/platform/realtek/zephyr/FactoryDataProvider.cpp
@@ -0,0 +1,626 @@
+/*
+ *
+ * Copyright (c) 2022 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "FactoryDataProvider.h"
+
+#include "FactoryDataDecoder.h"
+#include <crypto/CHIPCryptoPAL.h>
+#include <lib/core/CHIPError.h>
+#include <lib/support/Base64.h>
+#include <lib/support/BytesToHex.h>
+#include <lib/support/CHIPMem.h>
+#include <lib/support/Span.h>
+#include <platform/CHIPDeviceConfig.h>
+#include <platform/CHIPDeviceLayer.h>
+#include <platform/ConnectivityManager.h>
+#include <platform/internal/CHIPDeviceLayerInternal.h>
+#include <platform/internal/GenericConfigurationManagerImpl.ipp>
+#include <platform/realtek/zephyr/CHIPDevicePlatformConfig.h>
+
+using namespace ::chip::DeviceLayer::Internal;
+using chip::Platform::MemoryCalloc;
+using chip::Platform::MemoryFree;
+
+#define RTK_FACTORY_DATA_MAX_LENGTH 2048
+
+namespace chip {
+namespace DeviceLayer {
+
+// TODO: This should be moved to a method of P256Keypair
+CHIP_ERROR LoadKeypairFromRaw(ByteSpan private_key, ByteSpan public_key, Crypto::P256Keypair & keypair)
+{
+ Crypto::P256SerializedKeypair serialized_keypair;
+ ReturnErrorOnFailure(serialized_keypair.SetLength(private_key.size() + public_key.size()));
+ memcpy(serialized_keypair.Bytes(), public_key.data(), public_key.size());
+ memcpy(serialized_keypair.Bytes() + public_key.size(), private_key.data(), private_key.size());
+ return keypair.Deserialize(serialized_keypair);
+}
+
+CHIP_ERROR FactoryDataProvider::Init()
+{
+ CHIP_ERROR err = CHIP_NO_ERROR;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ uint8_t * buffer = static_cast<uint8_t *>(MemoryCalloc(1, RTK_FACTORY_DATA_MAX_LENGTH));
+ uint16_t factorydata_len;
+
+ if (buffer)
+ {
+ FactoryDataDecoder decoder = FactoryDataDecoder::GetInstance();
+ err = decoder.ReadFactoryData(buffer, &factorydata_len);
+ ChipLogDetail(DeviceLayer, "DecodeFactoryData factorydata_len %d!", factorydata_len);
+ if (err != CHIP_NO_ERROR)
+ {
+ ChipLogError(DeviceLayer, "ReadFactoryData failed!");
+ MemoryFree(buffer);
+ return err;
+ }
+ err = decoder.DecodeFactoryData(buffer, &mFactoryData, factorydata_len);
+ if (err != CHIP_NO_ERROR)
+ {
+ ChipLogError(DeviceLayer, "DecodeFactoryData failed!");
+ MemoryFree(buffer);
+ return err;
+ }
+
+ ChipLogProgress(DeviceLayer, "FactoryData of length: %d retrieved successfully", factorydata_len);
+
+ MemoryFree(buffer);
+ }
+
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetCertificationDeclaration(MutableByteSpan & outBuffer)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(outBuffer.size() >= mFactoryData.dac.cd.len, CHIP_ERROR_BUFFER_TOO_SMALL);
+ VerifyOrReturnError(mFactoryData.dac.cd.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+
+ memcpy(outBuffer.data(), mFactoryData.dac.cd.value, mFactoryData.dac.cd.len);
+
+ outBuffer.reduce_size(mFactoryData.dac.cd.len);
+ err = CHIP_NO_ERROR;
+#else
+ const uint8_t kCdForAllExamples[] = {
+ 0x30, 0x82, 0x02, 0x19, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02, 0xa0, 0x82, 0x02, 0x0a, 0x30,
+ 0x82, 0x02, 0x06, 0x02, 0x01, 0x03, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
+ 0x01, 0x30, 0x82, 0x01, 0x71, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x82, 0x01, 0x62,
+ 0x04, 0x82, 0x01, 0x5e, 0x15, 0x24, 0x00, 0x01, 0x25, 0x01, 0xf1, 0xff, 0x36, 0x02, 0x05, 0x00, 0x80, 0x05, 0x01, 0x80,
+ 0x05, 0x02, 0x80, 0x05, 0x03, 0x80, 0x05, 0x04, 0x80, 0x05, 0x05, 0x80, 0x05, 0x06, 0x80, 0x05, 0x07, 0x80, 0x05, 0x08,
+ 0x80, 0x05, 0x09, 0x80, 0x05, 0x0a, 0x80, 0x05, 0x0b, 0x80, 0x05, 0x0c, 0x80, 0x05, 0x0d, 0x80, 0x05, 0x0e, 0x80, 0x05,
+ 0x0f, 0x80, 0x05, 0x10, 0x80, 0x05, 0x11, 0x80, 0x05, 0x12, 0x80, 0x05, 0x13, 0x80, 0x05, 0x14, 0x80, 0x05, 0x15, 0x80,
+ 0x05, 0x16, 0x80, 0x05, 0x17, 0x80, 0x05, 0x18, 0x80, 0x05, 0x19, 0x80, 0x05, 0x1a, 0x80, 0x05, 0x1b, 0x80, 0x05, 0x1c,
+ 0x80, 0x05, 0x1d, 0x80, 0x05, 0x1e, 0x80, 0x05, 0x1f, 0x80, 0x05, 0x20, 0x80, 0x05, 0x21, 0x80, 0x05, 0x22, 0x80, 0x05,
+ 0x23, 0x80, 0x05, 0x24, 0x80, 0x05, 0x25, 0x80, 0x05, 0x26, 0x80, 0x05, 0x27, 0x80, 0x05, 0x28, 0x80, 0x05, 0x29, 0x80,
+ 0x05, 0x2a, 0x80, 0x05, 0x2b, 0x80, 0x05, 0x2c, 0x80, 0x05, 0x2d, 0x80, 0x05, 0x2e, 0x80, 0x05, 0x2f, 0x80, 0x05, 0x30,
+ 0x80, 0x05, 0x31, 0x80, 0x05, 0x32, 0x80, 0x05, 0x33, 0x80, 0x05, 0x34, 0x80, 0x05, 0x35, 0x80, 0x05, 0x36, 0x80, 0x05,
+ 0x37, 0x80, 0x05, 0x38, 0x80, 0x05, 0x39, 0x80, 0x05, 0x3a, 0x80, 0x05, 0x3b, 0x80, 0x05, 0x3c, 0x80, 0x05, 0x3d, 0x80,
+ 0x05, 0x3e, 0x80, 0x05, 0x3f, 0x80, 0x05, 0x40, 0x80, 0x05, 0x41, 0x80, 0x05, 0x42, 0x80, 0x05, 0x43, 0x80, 0x05, 0x44,
+ 0x80, 0x05, 0x45, 0x80, 0x05, 0x46, 0x80, 0x05, 0x47, 0x80, 0x05, 0x48, 0x80, 0x05, 0x49, 0x80, 0x05, 0x4a, 0x80, 0x05,
+ 0x4b, 0x80, 0x05, 0x4c, 0x80, 0x05, 0x4d, 0x80, 0x05, 0x4e, 0x80, 0x05, 0x4f, 0x80, 0x05, 0x50, 0x80, 0x05, 0x51, 0x80,
+ 0x05, 0x52, 0x80, 0x05, 0x53, 0x80, 0x05, 0x54, 0x80, 0x05, 0x55, 0x80, 0x05, 0x56, 0x80, 0x05, 0x57, 0x80, 0x05, 0x58,
+ 0x80, 0x05, 0x59, 0x80, 0x05, 0x5a, 0x80, 0x05, 0x5b, 0x80, 0x05, 0x5c, 0x80, 0x05, 0x5d, 0x80, 0x05, 0x5e, 0x80, 0x05,
+ 0x5f, 0x80, 0x05, 0x60, 0x80, 0x05, 0x61, 0x80, 0x05, 0x62, 0x80, 0x05, 0x63, 0x80, 0x18, 0x24, 0x03, 0x16, 0x2c, 0x04,
+ 0x13, 0x5a, 0x49, 0x47, 0x32, 0x30, 0x31, 0x34, 0x32, 0x5a, 0x42, 0x33, 0x33, 0x30, 0x30, 0x30, 0x33, 0x2d, 0x32, 0x34,
+ 0x24, 0x05, 0x00, 0x24, 0x06, 0x00, 0x25, 0x07, 0x94, 0x26, 0x24, 0x08, 0x00, 0x18, 0x31, 0x7d, 0x30, 0x7b, 0x02, 0x01,
+ 0x03, 0x80, 0x14, 0x62, 0xfa, 0x82, 0x33, 0x59, 0xac, 0xfa, 0xa9, 0x96, 0x3e, 0x1c, 0xfa, 0x14, 0x0a, 0xdd, 0xf5, 0x04,
+ 0xf3, 0x71, 0x60, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x30, 0x0a, 0x06, 0x08,
+ 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x04, 0x47, 0x30, 0x45, 0x02, 0x20, 0x24, 0xe5, 0xd1, 0xf4, 0x7a, 0x7d,
+ 0x7b, 0x0d, 0x20, 0x6a, 0x26, 0xef, 0x69, 0x9b, 0x7c, 0x97, 0x57, 0xb7, 0x2d, 0x46, 0x90, 0x89, 0xde, 0x31, 0x92, 0xe6,
+ 0x78, 0xc7, 0x45, 0xe7, 0xf6, 0x0c, 0x02, 0x21, 0x00, 0xf8, 0xaa, 0x2f, 0xa7, 0x11, 0xfc, 0xb7, 0x9b, 0x97, 0xe3, 0x97,
+ 0xce, 0xda, 0x66, 0x7b, 0xae, 0x46, 0x4e, 0x2b, 0xd3, 0xff, 0xdf, 0xc3, 0xcc, 0xed, 0x7a, 0xa8, 0xca, 0x5f, 0x4c, 0x1a,
+ 0x7c,
+ };
+
+ err = CopySpanToMutableSpan(ByteSpan(kCdForAllExamples), outBuffer);
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer)
+{
+ // TODO: We need a real example FirmwareInformation to be populated.
+ out_firmware_info_buffer.reduce_size(0);
+
+ return CHIP_NO_ERROR;
+}
+
+CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBuffer)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(outBuffer.size() >= mFactoryData.dac.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL);
+ VerifyOrReturnError(mFactoryData.dac.dac_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+
+ memcpy(outBuffer.data(), mFactoryData.dac.dac_cert.value, mFactoryData.dac.dac_cert.len);
+
+ outBuffer.reduce_size(mFactoryData.dac.dac_cert.len);
+ err = CHIP_NO_ERROR;
+#else
+ const uint8_t kDacCert[] = {
+ 0x30, 0x82, 0x01, 0xe7, 0x30, 0x82, 0x01, 0x8e, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x69, 0xcd, 0xf1, 0x0d, 0xe9,
+ 0xe5, 0x4e, 0xd1, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x3d, 0x31, 0x25, 0x30,
+ 0x23, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1c, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x44, 0x65, 0x76, 0x20, 0x50,
+ 0x41, 0x49, 0x20, 0x30, 0x78, 0x46, 0x46, 0x46, 0x31, 0x20, 0x6e, 0x6f, 0x20, 0x50, 0x49, 0x44, 0x31, 0x14, 0x30, 0x12,
+ 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x31, 0x30, 0x20,
+ 0x17, 0x0d, 0x32, 0x32, 0x30, 0x32, 0x30, 0x35, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x18, 0x0f, 0x39, 0x39, 0x39,
+ 0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30, 0x53, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03,
+ 0x55, 0x04, 0x03, 0x0c, 0x1c, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x44, 0x65, 0x76, 0x20, 0x44, 0x41, 0x43, 0x20,
+ 0x30, 0x78, 0x46, 0x46, 0x46, 0x31, 0x2f, 0x30, 0x78, 0x38, 0x30, 0x30, 0x31, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b,
+ 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x31, 0x31, 0x14, 0x30, 0x12, 0x06,
+ 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x02, 0x0c, 0x04, 0x38, 0x30, 0x30, 0x31, 0x30, 0x59, 0x30,
+ 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07,
+ 0x03, 0x42, 0x00, 0x04, 0x46, 0x3a, 0xc6, 0x93, 0x42, 0x91, 0x0a, 0x0e, 0x55, 0x88, 0xfc, 0x6f, 0xf5, 0x6b, 0xb6, 0x3e,
+ 0x62, 0xec, 0xce, 0xcb, 0x14, 0x8f, 0x7d, 0x4e, 0xb0, 0x3e, 0xe5, 0x52, 0x60, 0x14, 0x15, 0x76, 0x7d, 0x16, 0xa5, 0xc6,
+ 0x63, 0xf7, 0x93, 0xe4, 0x91, 0x23, 0x26, 0x0b, 0x82, 0x97, 0xa7, 0xcd, 0x7e, 0x7c, 0xfc, 0x7b, 0x31, 0x6b, 0x39, 0xd9,
+ 0x8e, 0x90, 0xd2, 0x93, 0x77, 0x73, 0x8e, 0x82, 0xa3, 0x60, 0x30, 0x5e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01,
+ 0x01, 0xff, 0x04, 0x02, 0x30, 0x00, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02,
+ 0x07, 0x80, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x88, 0xdd, 0xe7, 0xb3, 0x00, 0x38, 0x29,
+ 0x32, 0xcf, 0xf7, 0x34, 0xc0, 0x46, 0x24, 0x81, 0x0f, 0x44, 0x16, 0x8a, 0x6f, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23,
+ 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x63, 0x54, 0x0e, 0x47, 0xf6, 0x4b, 0x1c, 0x38, 0xd1, 0x38, 0x84, 0xa4, 0x62, 0xd1,
+ 0x6c, 0x19, 0x5d, 0x8f, 0xfb, 0x3c, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x47,
+ 0x00, 0x30, 0x44, 0x02, 0x20, 0x01, 0x27, 0xa2, 0x7b, 0x4b, 0x44, 0x61, 0x0e, 0xe2, 0xfc, 0xdc, 0x4d, 0x2b, 0x78, 0x85,
+ 0x56, 0x36, 0x60, 0xbc, 0x0f, 0x76, 0xf1, 0x72, 0x19, 0xed, 0x6a, 0x08, 0xdf, 0xb2, 0xb3, 0xc1, 0xcd, 0x02, 0x20, 0x6b,
+ 0x59, 0xe0, 0xaf, 0x45, 0xf3, 0xeb, 0x2a, 0x85, 0xb9, 0x19, 0xd3, 0x57, 0x31, 0x52, 0x8c, 0x60, 0x28, 0xc4, 0x15, 0x23,
+ 0x95, 0x45, 0xe1, 0x08, 0xe4, 0xe5, 0x4e, 0x70, 0x97, 0x13, 0x53,
+ };
+
+ err = CopySpanToMutableSpan(ByteSpan(kDacCert), outBuffer);
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer)
+{
+ CHIP_ERROR err = CHIP_NO_ERROR;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(outBuffer.size() >= mFactoryData.dac.pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL);
+ VerifyOrReturnError(mFactoryData.dac.pai_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+
+ memcpy(outBuffer.data(), mFactoryData.dac.pai_cert.value, mFactoryData.dac.pai_cert.len);
+
+ outBuffer.reduce_size(mFactoryData.dac.pai_cert.len);
+ err = CHIP_NO_ERROR;
+#else
+ const uint8_t kPaiCert[] = {
+ 0x30, 0x82, 0x01, 0xcb, 0x30, 0x82, 0x01, 0x71, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x56, 0xad, 0x82, 0x22, 0xad,
+ 0x94, 0x5b, 0x64, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x30, 0x31, 0x18, 0x30,
+ 0x16, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x0f, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20,
+ 0x50, 0x41, 0x41, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c,
+ 0x04, 0x46, 0x46, 0x46, 0x31, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x32, 0x30, 0x32, 0x30, 0x35, 0x30, 0x30, 0x30, 0x30, 0x30,
+ 0x30, 0x5a, 0x18, 0x0f, 0x39, 0x39, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30,
+ 0x3d, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1c, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x44,
+ 0x65, 0x76, 0x20, 0x50, 0x41, 0x49, 0x20, 0x30, 0x78, 0x46, 0x46, 0x46, 0x31, 0x20, 0x6e, 0x6f, 0x20, 0x50, 0x49, 0x44,
+ 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46,
+ 0x46, 0x31, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48,
+ 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x41, 0x9a, 0x93, 0x15, 0xc2, 0x17, 0x3e, 0x0c, 0x8c, 0x87, 0x6d,
+ 0x03, 0xcc, 0xfc, 0x94, 0x48, 0x52, 0x64, 0x7f, 0x7f, 0xec, 0x5e, 0x50, 0x82, 0xf4, 0x05, 0x99, 0x28, 0xec, 0xa8, 0x94,
+ 0xc5, 0x94, 0x15, 0x13, 0x09, 0xac, 0x63, 0x1e, 0x4c, 0xb0, 0x33, 0x92, 0xaf, 0x68, 0x4b, 0x0b, 0xaf, 0xb7, 0xe6, 0x5b,
+ 0x3b, 0x81, 0x62, 0xc2, 0xf5, 0x2b, 0xf9, 0x31, 0xb8, 0xe7, 0x7a, 0xaa, 0x82, 0xa3, 0x66, 0x30, 0x64, 0x30, 0x12, 0x06,
+ 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x08, 0x30, 0x06, 0x01, 0x01, 0xff, 0x02, 0x01, 0x00, 0x30, 0x0e, 0x06,
+ 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e,
+ 0x04, 0x16, 0x04, 0x14, 0x63, 0x54, 0x0e, 0x47, 0xf6, 0x4b, 0x1c, 0x38, 0xd1, 0x38, 0x84, 0xa4, 0x62, 0xd1, 0x6c, 0x19,
+ 0x5d, 0x8f, 0xfb, 0x3c, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x6a, 0xfd, 0x22,
+ 0x77, 0x1f, 0x51, 0x1f, 0xec, 0xbf, 0x16, 0x41, 0x97, 0x67, 0x10, 0xdc, 0xdc, 0x31, 0xa1, 0x71, 0x7e, 0x30, 0x0a, 0x06,
+ 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x21, 0x00, 0xb2, 0xef, 0x27,
+ 0xf4, 0x9a, 0xe9, 0xb5, 0x0f, 0xb9, 0x1e, 0xea, 0xc9, 0x4c, 0x4d, 0x0b, 0xdb, 0xb8, 0xd7, 0x92, 0x9c, 0x6c, 0xb8, 0x8f,
+ 0xac, 0xe5, 0x29, 0x36, 0x8d, 0x12, 0x05, 0x4c, 0x0c, 0x02, 0x20, 0x65, 0x5d, 0xc9, 0x2b, 0x86, 0xbd, 0x90, 0x98, 0x82,
+ 0xa6, 0xc6, 0x21, 0x77, 0xb8, 0x25, 0xd7, 0xd0, 0x5e, 0xdb, 0xe7, 0xc2, 0x2f, 0x9f, 0xea, 0x71, 0x22, 0x0e, 0x7e, 0xa7,
+ 0x03, 0xf8, 0x91,
+ };
+
+ err = CopySpanToMutableSpan(ByteSpan{ kPaiCert }, outBuffer);
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return CHIP_NO_ERROR;
+}
+
+CHIP_ERROR FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer)
+{
+ Crypto::P256ECDSASignature signature;
+ Crypto::P256Keypair keypair;
+
+ VerifyOrReturnError(IsSpanUsable(outSignBuffer), CHIP_ERROR_INVALID_ARGUMENT);
+ VerifyOrReturnError(IsSpanUsable(messageToSign), CHIP_ERROR_INVALID_ARGUMENT);
+ VerifyOrReturnError(outSignBuffer.size() >= signature.Capacity(), CHIP_ERROR_BUFFER_TOO_SMALL);
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(mFactoryData.dac.dac_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+ VerifyOrReturnError(mFactoryData.dac.dac_key.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+ // Extract public key from DAC cert.
+ ByteSpan dacCertSpan{ reinterpret_cast<uint8_t *>(mFactoryData.dac.dac_cert.value), mFactoryData.dac.dac_cert.len };
+ chip::Crypto::P256PublicKey dacPublicKey;
+
+ ReturnErrorOnFailure(chip::Crypto::ExtractPubkeyFromX509Cert(dacCertSpan, dacPublicKey));
+ ReturnErrorOnFailure(
+ LoadKeypairFromRaw(ByteSpan(reinterpret_cast<uint8_t *>(mFactoryData.dac.dac_key.value), mFactoryData.dac.dac_key.len),
+ ByteSpan(dacPublicKey.Bytes(), dacPublicKey.Length()), keypair));
+#else
+ const uint8_t kDacPublicKey[65] = {
+ 0x04, 0x46, 0x3a, 0xc6, 0x93, 0x42, 0x91, 0x0a, 0x0e, 0x55, 0x88, 0xfc, 0x6f, 0xf5, 0x6b, 0xb6, 0x3e,
+ 0x62, 0xec, 0xce, 0xcb, 0x14, 0x8f, 0x7d, 0x4e, 0xb0, 0x3e, 0xe5, 0x52, 0x60, 0x14, 0x15, 0x76, 0x7d,
+ 0x16, 0xa5, 0xc6, 0x63, 0xf7, 0x93, 0xe4, 0x91, 0x23, 0x26, 0x0b, 0x82, 0x97, 0xa7, 0xcd, 0x7e, 0x7c,
+ 0xfc, 0x7b, 0x31, 0x6b, 0x39, 0xd9, 0x8e, 0x90, 0xd2, 0x93, 0x77, 0x73, 0x8e, 0x82,
+ };
+
+ const uint8_t kDacPrivateKey[32] = {
+ 0xaa, 0xb6, 0x00, 0xae, 0x8a, 0xe8, 0xaa, 0xb7, 0xd7, 0x36, 0x27, 0xc2, 0x17, 0xb7, 0xc2, 0x04,
+ 0x70, 0x9c, 0xa6, 0x94, 0x6a, 0xf5, 0xf2, 0xf7, 0x53, 0x08, 0x33, 0xa5, 0x2b, 0x44, 0xfb, 0xff,
+ };
+
+ ReturnErrorOnFailure(LoadKeypairFromRaw(ByteSpan(kDacPrivateKey), ByteSpan(kDacPublicKey), keypair));
+#endif
+
+ ReturnErrorOnFailure(keypair.ECDSA_sign_msg(messageToSign.data(), messageToSign.size(), signature));
+
+ return CopySpanToMutableSpan(ByteSpan{ signature.ConstBytes(), signature.Length() }, outSignBuffer);
+}
+
+CHIP_ERROR FactoryDataProvider::GetSetupDiscriminator(uint16_t & setupDiscriminator)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ setupDiscriminator = mFactoryData.cdata.discriminator;
+ err = CHIP_NO_ERROR;
+#else
+#if defined(CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR) && CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR
+ setupDiscriminator = CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR;
+ err = CHIP_NO_ERROR;
+#endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR) && CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::SetSetupDiscriminator(uint16_t setupDiscriminator)
+{
+ return CHIP_ERROR_NOT_IMPLEMENTED;
+}
+
+CHIP_ERROR FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(mFactoryData.cdata.spake2_it != 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+ iterationCount = mFactoryData.cdata.spake2_it;
+ err = CHIP_NO_ERROR;
+#else
+#if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT) && CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT
+ iterationCount = CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT;
+ err = CHIP_NO_ERROR;
+#endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT) && CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf)
+{
+ static constexpr size_t kSpake2pSalt_MaxBase64Len = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length) + 1;
+
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+ char saltB64[kSpake2pSalt_MaxBase64Len] = { 0 };
+ size_t saltB64Len = 0;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ saltB64Len = mFactoryData.cdata.spake2_salt.len;
+ VerifyOrReturnError(saltB64Len <= sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL);
+ memcpy(saltB64, mFactoryData.cdata.spake2_salt.value, saltB64Len);
+ err = CHIP_NO_ERROR;
+#else
+#if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT)
+ saltB64Len = strlen(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT);
+ VerifyOrReturnError(saltB64Len <= sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL);
+ memcpy(saltB64, CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT, saltB64Len);
+ err = CHIP_NO_ERROR;
+#endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT)
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ ReturnErrorOnFailure(err);
+ size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, reinterpret_cast<uint8_t *>(saltB64));
+
+ VerifyOrReturnError(saltLen <= saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL);
+ memcpy(saltBuf.data(), saltB64, saltLen);
+ saltBuf.reduce_size(saltLen);
+
+ return CHIP_NO_ERROR;
+}
+
+CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen)
+{
+ static constexpr size_t kSpake2pSerializedVerifier_MaxBase64Len =
+ BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_VerifierSerialized_Length) + 1;
+
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+ char verifierB64[kSpake2pSerializedVerifier_MaxBase64Len] = { 0 };
+ size_t verifierB64Len = 0;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ verifierB64Len = mFactoryData.cdata.spake2_verifier.len;
+ VerifyOrReturnError(verifierB64Len <= sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL);
+ memcpy(verifierB64, mFactoryData.cdata.spake2_verifier.value, verifierB64Len);
+ err = CHIP_NO_ERROR;
+#else
+#if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER)
+ verifierB64Len = strlen(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER);
+ VerifyOrReturnError(verifierB64Len <= sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL);
+ memcpy(verifierB64, CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER, verifierB64Len);
+ err = CHIP_NO_ERROR;
+#endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER)
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ ReturnErrorOnFailure(err);
+ verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast<uint8_t *>(verifierB64));
+ VerifyOrReturnError(verifierLen <= verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL);
+ memcpy(verifierBuf.data(), verifierB64, verifierLen);
+ verifierBuf.reduce_size(verifierLen);
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(mFactoryData.cdata.passcode != 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+ setupPasscode = mFactoryData.cdata.passcode;
+ err = CHIP_NO_ERROR;
+#else
+#if defined(CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE) && CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE
+ setupPasscode = CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE;
+ err = CHIP_NO_ERROR;
+#endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE) && CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::SetSetupPasscode(uint32_t setupPasscode)
+{
+ return CHIP_ERROR_NOT_IMPLEMENTED;
+}
+
+CHIP_ERROR FactoryDataProvider::GetVendorName(char * buf, size_t bufSize)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(bufSize >= mFactoryData.dii.vendor_name.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL);
+ VerifyOrReturnError(mFactoryData.dii.vendor_name.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+ memcpy(buf, mFactoryData.dii.vendor_name.value, mFactoryData.dii.vendor_name.len);
+ buf[mFactoryData.dii.vendor_name.len] = 0;
+ err = CHIP_NO_ERROR;
+#else
+ VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME), CHIP_ERROR_BUFFER_TOO_SMALL);
+ strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME);
+ err = CHIP_NO_ERROR;
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetVendorId(uint16_t & vendorId)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ vendorId = mFactoryData.dii.vendor_id;
+ err = CHIP_NO_ERROR;
+#else
+ vendorId = static_cast<uint16_t>(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID);
+ err = CHIP_NO_ERROR;
+#endif // CONFIG_ENABLE_FACTORY_DATA
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetProductName(char * buf, size_t bufSize)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(bufSize >= mFactoryData.dii.product_name.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL);
+ VerifyOrReturnError(mFactoryData.dii.product_name.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+ memcpy(buf, mFactoryData.dii.product_name.value, mFactoryData.dii.product_name.len);
+ buf[mFactoryData.dii.product_name.len] = 0;
+ err = CHIP_NO_ERROR;
+#else
+ VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL);
+ strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME);
+ err = CHIP_NO_ERROR;
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetProductId(uint16_t & productId)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ productId = mFactoryData.dii.product_id;
+ err = CHIP_NO_ERROR;
+#else
+ productId = static_cast<uint16_t>(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID);
+ err = CHIP_NO_ERROR;
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetPartNumber(char * buf, size_t bufSize)
+{
+ return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
+}
+
+CHIP_ERROR FactoryDataProvider::GetProductURL(char * buf, size_t bufSize)
+{
+ return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
+}
+
+CHIP_ERROR FactoryDataProvider::GetProductLabel(char * buf, size_t bufSize)
+{
+ return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
+}
+
+CHIP_ERROR FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(bufSize >= mFactoryData.dii.serial_num.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL);
+ VerifyOrReturnError(mFactoryData.dii.serial_num.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+ memcpy(buf, mFactoryData.dii.serial_num.value, mFactoryData.dii.serial_num.len);
+ buf[mFactoryData.dii.serial_num.len] = 0;
+ err = CHIP_NO_ERROR;
+#else
+ size_t serialNumLen = 0; // without counting null-terminator
+#ifdef CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER
+ if (CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER[0] != 0)
+ {
+ VerifyOrReturnError(sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER) <= bufSize, CHIP_ERROR_BUFFER_TOO_SMALL);
+ memcpy(buf, CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER, sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER));
+ serialNumLen = sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER) - 1;
+ err = CHIP_NO_ERROR;
+ }
+#endif // CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER
+
+ VerifyOrReturnError(serialNumLen < bufSize, CHIP_ERROR_BUFFER_TOO_SMALL);
+ VerifyOrReturnError(buf[serialNumLen] == 0, CHIP_ERROR_INVALID_STRING_LENGTH);
+
+ err = CHIP_NO_ERROR;
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ enum
+ {
+ kDateStringLength = 10 // YYYY-MM-DD
+ };
+ char * parseEnd;
+ size_t dateLen;
+ dateLen = mFactoryData.dii.mfg_date.len;
+ VerifyOrExit(dateLen == kDateStringLength, err = CHIP_ERROR_INVALID_ARGUMENT);
+
+ // Cast does not lose information, because we then check that we only parsed
+ // 4 digits, so our number can't be bigger than 9999.
+ year = static_cast<uint16_t>(strtoul((char *) mFactoryData.dii.mfg_date.value, &parseEnd, 10));
+ VerifyOrExit(parseEnd == (char *) mFactoryData.dii.mfg_date.value + 4, err = CHIP_ERROR_INVALID_ARGUMENT);
+
+ // Cast does not lose information, because we then check that we only parsed
+ // 2 digits, so our number can't be bigger than 99.
+ month = static_cast<uint8_t>(strtoul((char *) mFactoryData.dii.mfg_date.value + 5, &parseEnd, 10));
+ VerifyOrExit(parseEnd == (char *) mFactoryData.dii.mfg_date.value + 7, err = CHIP_ERROR_INVALID_ARGUMENT);
+
+ // Cast does not lose information, because we then check that we only parsed
+ // 2 digits, so our number can't be bigger than 99.
+ day = static_cast<uint8_t>(strtoul((char *) mFactoryData.dii.mfg_date.value + 8, &parseEnd, 10));
+ VerifyOrExit(parseEnd == (char *) mFactoryData.dii.mfg_date.value + 10, err = CHIP_ERROR_INVALID_ARGUMENT);
+
+ err = CHIP_NO_ERROR;
+#else
+ err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+exit:
+ if (err != CHIP_NO_ERROR && err != CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND && err != CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE)
+ {
+ ChipLogError(DeviceLayer, "Invalid manufacturing date: %s", mFactoryData.dii.mfg_date.value);
+ }
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetHardwareVersion(uint16_t & hardwareVersion)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ hardwareVersion = mFactoryData.dii.hw_ver;
+ err = CHIP_NO_ERROR;
+#else
+ hardwareVersion = static_cast<uint16_t>(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION);
+ err = CHIP_NO_ERROR;
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufSize)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(bufSize >= mFactoryData.dii.hw_ver_string.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL);
+ VerifyOrReturnError(mFactoryData.dii.hw_ver_string.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+ memcpy(buf, mFactoryData.dii.hw_ver_string.value, mFactoryData.dii.hw_ver_string.len);
+ buf[mFactoryData.dii.hw_ver_string.len] = 0;
+ err = CHIP_NO_ERROR;
+#else
+ VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL);
+ strcpy(buf, CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING);
+ err = CHIP_NO_ERROR;
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan)
+{
+ CHIP_ERROR err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND;
+
+#if CONFIG_ENABLE_FACTORY_DATA
+ VerifyOrReturnError(uniqueIdSpan.size() >= mFactoryData.dii.rd_id_uid.len, CHIP_ERROR_BUFFER_TOO_SMALL);
+ VerifyOrReturnError(mFactoryData.dii.rd_id_uid.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
+ memcpy(uniqueIdSpan.data(), mFactoryData.dii.rd_id_uid.value, mFactoryData.dii.rd_id_uid.len);
+ err = CHIP_NO_ERROR;
+#else
+ err = CHIP_ERROR_NOT_IMPLEMENTED;
+#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID)
+ static_assert(ConfigurationManager::kRotatingDeviceIDUniqueIDLength >= ConfigurationManager::kMinRotatingDeviceIDUniqueIDLength,
+ "Length of unique ID for rotating device ID is smaller than minimum.");
+ constexpr uint8_t uniqueId[] = CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID;
+
+ VerifyOrReturnError(sizeof(uniqueId) <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL);
+ VerifyOrReturnError(sizeof(uniqueId) == ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_BUFFER_TOO_SMALL);
+ memcpy(uniqueIdSpan.data(), uniqueId, sizeof(uniqueId));
+ uniqueIdSpan.reduce_size(sizeof(uniqueId));
+ err = CHIP_NO_ERROR;
+#endif
+#endif // CONFIG_ENABLE_FACTORY_DATA
+
+ return err;
+}
+
+} // namespace DeviceLayer
+} // namespace chip
diff --git a/src/platform/realtek/zephyr/FactoryDataProvider.h b/src/platform/realtek/zephyr/FactoryDataProvider.h
new file mode 100644
index 0000000..4424013
--- /dev/null
+++ b/src/platform/realtek/zephyr/FactoryDataProvider.h
@@ -0,0 +1,71 @@
+/*
+ *
+ * Copyright (c) 2022 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <credentials/DeviceAttestationCredsProvider.h>
+#include <platform/CommissionableDataProvider.h>
+#include <platform/DeviceInstanceInfoProvider.h>
+
+namespace chip {
+namespace DeviceLayer {
+
+class FactoryDataProvider : public chip::Credentials::DeviceAttestationCredentialsProvider,
+ public CommissionableDataProvider,
+ public DeviceInstanceInfoProvider
+{
+public:
+ // ===== Members functions that implement the DeviceAttestationCredentialsProvider
+ CHIP_ERROR Init(void);
+ CHIP_ERROR GetCertificationDeclaration(MutableByteSpan & outBuffer) override;
+ CHIP_ERROR GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer) override;
+ CHIP_ERROR GetDeviceAttestationCert(MutableByteSpan & outBuffer) override;
+ CHIP_ERROR GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) override;
+ CHIP_ERROR SignWithDeviceAttestationKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) override;
+
+ // ===== Members functions that implement the CommissionableDataProvider
+ CHIP_ERROR GetSetupDiscriminator(uint16_t & setupDiscriminator) override;
+ CHIP_ERROR SetSetupDiscriminator(uint16_t setupDiscriminator) override;
+ CHIP_ERROR GetSpake2pIterationCount(uint32_t & iterationCount) override;
+ CHIP_ERROR GetSpake2pSalt(MutableByteSpan & saltBuf) override;
+ CHIP_ERROR GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) override;
+ CHIP_ERROR GetSetupPasscode(uint32_t & setupPasscode) override;
+ CHIP_ERROR SetSetupPasscode(uint32_t setupPasscode) override;
+
+ // ===== Members functions that implement the DeviceInstanceInfoProvider
+ CHIP_ERROR GetVendorName(char * buf, size_t bufSize) override;
+ CHIP_ERROR GetVendorId(uint16_t & vendorId) override;
+ CHIP_ERROR GetProductName(char * buf, size_t bufSize) override;
+ CHIP_ERROR GetProductId(uint16_t & productId) override;
+ CHIP_ERROR GetPartNumber(char * buf, size_t bufSize) override;
+ CHIP_ERROR GetProductURL(char * buf, size_t bufSize) override;
+ CHIP_ERROR GetProductLabel(char * buf, size_t bufSize) override;
+ CHIP_ERROR GetSerialNumber(char * buf, size_t bufSize) override;
+ CHIP_ERROR GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) override;
+ CHIP_ERROR GetHardwareVersion(uint16_t & hardwareVersion) override;
+ CHIP_ERROR GetHardwareVersionString(char * buf, size_t bufSize) override;
+ CHIP_ERROR GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) override;
+
+private:
+ static constexpr uint8_t kDACPrivateKeyLength = 32;
+ static constexpr uint8_t kDACPublicKeyLength = 65;
+
+ FactoryData mFactoryData = { 0 };
+};
+
+} // namespace DeviceLayer
+} // namespace chip
diff --git a/src/platform/realtek/zephyr/InetPlatformConfig.h b/src/platform/realtek/zephyr/InetPlatformConfig.h
new file mode 100755
index 0000000..a38d274
--- /dev/null
+++ b/src/platform/realtek/zephyr/InetPlatformConfig.h
@@ -0,0 +1,34 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+// ==================== Platform Adaptations ====================
+
+#ifndef INET_CONFIG_ENABLE_IPV4
+#error Inet IPv4 configuration should be configured at build generation time
+#endif
+
+// ========== Platform-specific Configuration Overrides =========
+
+#ifndef INET_CONFIG_NUM_TCP_ENDPOINTS
+#define INET_CONFIG_NUM_TCP_ENDPOINTS 4
+#endif // INET_CONFIG_NUM_TCP_ENDPOINTS
+
+#ifndef INET_CONFIG_NUM_UDP_ENDPOINTS
+#define INET_CONFIG_NUM_UDP_ENDPOINTS 4
+#endif // INET_CONFIG_NUM_UDP_ENDPOINTS
diff --git a/src/platform/realtek/zephyr/KeyValueStoreManagerImpl.h b/src/platform/realtek/zephyr/KeyValueStoreManagerImpl.h
new file mode 100755
index 0000000..45f754c
--- /dev/null
+++ b/src/platform/realtek/zephyr/KeyValueStoreManagerImpl.h
@@ -0,0 +1,21 @@
+/*
+ *
+ * Copyright (c) 2021 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <platform/Zephyr/KeyValueStoreManagerImpl.h>
diff --git a/src/platform/realtek/zephyr/OTAImageProcessorImpl.cpp b/src/platform/realtek/zephyr/OTAImageProcessorImpl.cpp
new file mode 100644
index 0000000..6ae8829
--- /dev/null
+++ b/src/platform/realtek/zephyr/OTAImageProcessorImpl.cpp
@@ -0,0 +1,291 @@
+/*
+ *
+ * Copyright (c) 2021 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "OTAImageProcessorImpl.h"
+#include "matter_ota.h"
+#include <app/clusters/ota-requestor/OTADownloader.h>
+#include <app/clusters/ota-requestor/OTARequestorInterface.h>
+
+namespace chip {
+
+bool OTAImageProcessorImpl::IsFirstImageRun()
+{
+ OTARequestorInterface * requestor = chip::GetRequestorInstance();
+ if (requestor == nullptr)
+ {
+ return false;
+ }
+
+ return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying;
+}
+
+CHIP_ERROR OTAImageProcessorImpl::ConfirmCurrentImage()
+{
+ OTARequestorInterface * requestor = chip::GetRequestorInstance();
+ if (requestor == nullptr)
+ {
+ return CHIP_ERROR_INTERNAL;
+ }
+
+ uint32_t currentVersion;
+ uint32_t targetVersion = requestor->GetTargetVersion();
+ ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(currentVersion));
+
+ if (currentVersion != targetVersion)
+ {
+ ChipLogError(SoftwareUpdate, "Current software version = %" PRIu32 ", expected software version = %" PRIu32, currentVersion,
+ targetVersion);
+ return CHIP_ERROR_INCORRECT_STATE;
+ }
+
+ return CHIP_NO_ERROR;
+}
+
+CHIP_ERROR OTAImageProcessorImpl::PrepareDownload()
+{
+ ChipLogProgress(SoftwareUpdate, "Prepare download");
+
+ DeviceLayer::PlatformMgr().ScheduleWork(HandlePrepareDownload, reinterpret_cast<intptr_t>(this));
+ return CHIP_NO_ERROR;
+}
+
+CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block)
+{
+ if (mHeaderParser.IsInitialized())
+ {
+ OTAImageHeader header;
+ CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header);
+
+ // Needs more data to decode the header
+ VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR);
+ ReturnErrorOnFailure(error);
+
+ mParams.totalFileBytes = header.mPayloadSize;
+ mHeaderParser.Clear();
+ }
+
+ return CHIP_NO_ERROR;
+}
+
+CHIP_ERROR OTAImageProcessorImpl::Finalize()
+{
+ ChipLogProgress(SoftwareUpdate, "Finalize");
+
+ DeviceLayer::PlatformMgr().ScheduleWork(HandleFinalize, reinterpret_cast<intptr_t>(this));
+ return CHIP_NO_ERROR;
+}
+
+CHIP_ERROR OTAImageProcessorImpl::Apply()
+{
+ ChipLogProgress(SoftwareUpdate, "Apply");
+
+ DeviceLayer::PlatformMgr().ScheduleWork(HandleApply, reinterpret_cast<intptr_t>(this));
+ return CHIP_NO_ERROR;
+}
+
+CHIP_ERROR OTAImageProcessorImpl::Abort()
+{
+ ChipLogProgress(SoftwareUpdate, "Abort");
+
+ DeviceLayer::PlatformMgr().ScheduleWork(HandleAbort, reinterpret_cast<intptr_t>(this));
+ return CHIP_NO_ERROR;
+}
+
+CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block)
+{
+ if ((block.data() == nullptr) || block.empty())
+ {
+ return CHIP_ERROR_INVALID_ARGUMENT;
+ }
+
+ CHIP_ERROR err = SetBlock(block);
+ if (err != CHIP_NO_ERROR)
+ {
+ ChipLogError(SoftwareUpdate, "Cannot set block data: %" CHIP_ERROR_FORMAT, err.Format());
+ return err;
+ }
+
+ DeviceLayer::PlatformMgr().ScheduleWork(HandleProcessBlock, reinterpret_cast<intptr_t>(this));
+ return CHIP_NO_ERROR;
+}
+
+void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context)
+{
+ auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);
+ if (imageProcessor == nullptr)
+ {
+ ChipLogError(SoftwareUpdate, "ImageProcessor context is null");
+ return;
+ }
+ else if (imageProcessor->mDownloader == nullptr)
+ {
+ ChipLogError(SoftwareUpdate, "mDownloader is null");
+ return;
+ }
+
+ // Initialize tracking variables
+ imageProcessor->mParams.downloadedBytes = 0;
+
+ if (rtk_matter_ota_prepare() != 0)
+ {
+ ChipLogError(SoftwareUpdate, "HandlePrepareDownload: rtk_matter_ota_prepare failed");
+ return;
+ }
+
+ imageProcessor->mHeaderParser.Init();
+ imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR);
+}
+
+void OTAImageProcessorImpl::HandleFinalize(intptr_t context)
+{
+ auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);
+ if (imageProcessor == nullptr)
+ {
+ return;
+ }
+
+ if (rtk_matter_ota_finalize() != 0)
+ {
+ ChipLogError(SoftwareUpdate, "Failed to finalize OTA upgrade");
+ return;
+ }
+
+ ChipLogProgress(SoftwareUpdate, "OTA image downloaded size %lldB", imageProcessor->mParams.downloadedBytes);
+
+ imageProcessor->ReleaseBlock();
+ imageProcessor->mParams.downloadedBytes = 0;
+}
+
+void OTAImageProcessorImpl::HandleAbort(intptr_t context)
+{
+ auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);
+ if (imageProcessor == nullptr)
+ {
+ return;
+ }
+
+ rtk_matter_ota_abort();
+
+ ChipLogError(SoftwareUpdate, "OTA upgrade was aborted");
+
+ imageProcessor->ReleaseBlock();
+ imageProcessor->mParams.downloadedBytes = 0;
+}
+
+void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context)
+{
+ auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);
+ if (imageProcessor == nullptr)
+ {
+ ChipLogError(SoftwareUpdate, "ImageProcessor context is null");
+ return;
+ }
+ else if (imageProcessor->mDownloader == nullptr)
+ {
+ ChipLogError(SoftwareUpdate, "mDownloader is null");
+ return;
+ }
+
+ ByteSpan block = imageProcessor->mBlock;
+ CHIP_ERROR error = imageProcessor->ProcessHeader(block);
+ if (error != CHIP_NO_ERROR)
+ {
+ ChipLogError(SoftwareUpdate, "Failed to process OTA image header");
+ imageProcessor->mDownloader->EndDownload(error);
+ return;
+ }
+
+ if (0 != rtk_matter_ota_process_block((uint8_t *) block.data(), static_cast<std::uint16_t>(block.size())))
+ {
+ ChipLogError(SoftwareUpdate, "Flash write failed");
+ imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED);
+ return;
+ }
+
+ ChipLogProgress(SoftwareUpdate, "HandleProcessBlock 0x%x bytes", block.size());
+
+ imageProcessor->mParams.downloadedBytes += block.size();
+ imageProcessor->mDownloader->FetchNextData();
+}
+
+void OTAImageProcessorImpl::HandleApply(intptr_t context)
+{
+ auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);
+ if (imageProcessor == nullptr)
+ {
+ ChipLogError(SoftwareUpdate, "ImageProcessor context is null");
+ return;
+ }
+
+ ChipLogProgress(SoftwareUpdate, "Rebooting in 10 seconds...");
+
+ DeviceLayer::SystemLayer().StartTimer(
+ System::Clock::Seconds32(10),
+ [](chip::System::Layer *, void *) {
+ ChipLogProgress(SoftwareUpdate, "Rebooting...");
+ rtk_matter_ota_apply();
+ },
+ nullptr);
+}
+
+CHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block)
+{
+ if (!IsSpanUsable(block))
+ {
+ ReleaseBlock();
+ return CHIP_NO_ERROR;
+ }
+
+ if (mBlock.size() < block.size())
+ {
+ if (!mBlock.empty())
+ {
+ ReleaseBlock();
+ }
+
+ uint8_t * mBlock_ptr = static_cast<uint8_t *>(chip::Platform::MemoryAlloc(block.size()));
+ if (mBlock_ptr == nullptr)
+ {
+ return CHIP_ERROR_NO_MEMORY;
+ }
+
+ mBlock = MutableByteSpan(mBlock_ptr, block.size());
+ }
+
+ CHIP_ERROR err = CopySpanToMutableSpan(block, mBlock);
+ if (err != CHIP_NO_ERROR)
+ {
+ ChipLogError(SoftwareUpdate, "Cannot copy block data: %" CHIP_ERROR_FORMAT, err.Format());
+ return err;
+ }
+
+ return CHIP_NO_ERROR;
+}
+
+CHIP_ERROR OTAImageProcessorImpl::ReleaseBlock()
+{
+ if (mBlock.data() != nullptr)
+ {
+ chip::Platform::MemoryFree(mBlock.data());
+ }
+
+ mBlock = MutableByteSpan();
+ return CHIP_NO_ERROR;
+}
+
+} // namespace chip
diff --git a/src/platform/realtek/zephyr/OTAImageProcessorImpl.h b/src/platform/realtek/zephyr/OTAImageProcessorImpl.h
new file mode 100644
index 0000000..31f85af
--- /dev/null
+++ b/src/platform/realtek/zephyr/OTAImageProcessorImpl.h
@@ -0,0 +1,69 @@
+/*
+ *
+ * Copyright (c) 2021 Project CHIP Authors
+ * All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <app/clusters/ota-requestor/OTADownloader.h>
+#include <lib/core/OTAImageHeader.h>
+#include <platform/CHIPDeviceLayer.h>
+#include <platform/OTAImageProcessor.h>
+
+namespace chip {
+
+class OTAImageProcessorImpl : public OTAImageProcessorInterface
+{
+public:
+ //////////// OTAImageProcessorInterface Implementation ///////////////
+ CHIP_ERROR PrepareDownload() override;
+ CHIP_ERROR Finalize() override;
+ CHIP_ERROR Apply() override;
+ CHIP_ERROR Abort() override;
+ CHIP_ERROR ProcessBlock(ByteSpan & block) override;
+ bool IsFirstImageRun() override;
+ CHIP_ERROR ConfirmCurrentImage() override;
+
+ void SetOTADownloader(OTADownloader * downloader) { mDownloader = downloader; }
+
+private:
+ //////////// Actual handlers for the OTAImageProcessorInterface ///////////////
+ CHIP_ERROR ProcessHeader(ByteSpan & block);
+ static void HandlePrepareDownload(intptr_t context);
+ static void HandleFinalize(intptr_t context);
+ static void HandleAbort(intptr_t context);
+ static void HandleProcessBlock(intptr_t context);
+ static void HandleApply(intptr_t context);
+
+ /**
+ * Called to allocate memory for mBlock if necessary and set it to block
+ */
+ CHIP_ERROR SetBlock(ByteSpan & block);
+
+ /**
+ * Called to release allocated memory for mBlock
+ */
+ CHIP_ERROR ReleaseBlock();
+
+ std::uint32_t mSwVer;
+ std::uint32_t mHwVer;
+
+ MutableByteSpan mBlock;
+ OTADownloader * mDownloader = nullptr;
+ OTAImageHeaderParser mHeaderParser;
+};
+
+} // namespace chip
diff --git a/src/platform/realtek/zephyr/PlatformManagerImpl.h b/src/platform/realtek/zephyr/PlatformManagerImpl.h
new file mode 100755
index 0000000..ee28c70
--- /dev/null
+++ b/src/platform/realtek/zephyr/PlatformManagerImpl.h
@@ -0,0 +1,20 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <platform/Zephyr/PlatformManagerImpl.h>
diff --git a/src/platform/realtek/zephyr/README.md b/src/platform/realtek/zephyr/README.md
new file mode 100755
index 0000000..1edc4d6
--- /dev/null
+++ b/src/platform/realtek/zephyr/README.md
@@ -0,0 +1,31 @@
+# Overview of CHIP Realtek Zephyr Adaption
+
+The following is an overview of the Realtek adaptation of CHIP. Most of this
+code will have parallels in any new adaptation.
+
+(All file names are relative to
+`connectedhomeip/src/platform/realtek/zephyr...`).
+
+`PlatformManagerImpl.h`<br>`PlatformManagerImpl.cpp`
+
+- Concrete implementation of PlatformManager interface
+- Provides initialization of the CHIP stack and core event loop for the chip
+ task
+- Relies on GenericPlatformManagerImpl_FreeRTOS<> class to provide most of the
+ implementation
+
+`ConfigurationManagerImpl.h`<br>`ConfigurationManagerImpl.cpp`
+
+- Concrete implementation of ConfigurationManager interface
+- Manages storage and retrieval of persistent configuration data
+- Relies on GenericConfigurationManagerImpl<> classes to implement most API
+ functionality
+- Delegates low-level reading and writing of persistent values to NRF5Config
+ class
+
+`ConnectivityManagerImpl.h`<br>`ConnectivityManagerImpl.cpp`
+
+- Concrete implementation of ConnectivityManager interface
+- Provides high-level APIs for managing device connectivity
+- Relies on GenericConnectivityManagerImpl_Thread<> class to provide most of
+ the implementation
diff --git a/src/platform/realtek/zephyr/SystemPlatformConfig.h b/src/platform/realtek/zephyr/SystemPlatformConfig.h
new file mode 100755
index 0000000..c546e80
--- /dev/null
+++ b/src/platform/realtek/zephyr/SystemPlatformConfig.h
@@ -0,0 +1,48 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <stdint.h>
+
+namespace chip {
+namespace DeviceLayer {
+struct ChipDeviceEvent;
+} // namespace DeviceLayer
+} // namespace chip
+
+// ==================== Platform Adaptations ====================
+
+#ifndef CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS
+#define CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS 0
+#endif // CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS
+
+#if CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS
+#define CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME 0
+#else // CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS
+#define CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME 1
+#endif // CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS
+
+#define CHIP_SYSTEM_CONFIG_USE_LWIP 0
+#define CHIP_SYSTEM_CONFIG_USE_SOCKETS 1
+
+// ========== Platform-specific Configuration Overrides =========
+// Disable Thread Local Storage (TLS) since Realtek SDK does not support it.
+#define CHIP_SYSTEM_CONFIG_THREAD_LOCAL_STORAGE 0
+
+// Disable Zephyr Socket extensions module, as the Zephyr RTOS now implements recvmsg()
+#define CHIP_SYSTEM_CONFIG_USE_ZEPHYR_SOCKET_EXTENSIONS 0
diff --git a/src/platform/realtek/zephyr/ThreadStackManagerImpl.h b/src/platform/realtek/zephyr/ThreadStackManagerImpl.h
new file mode 100755
index 0000000..e811a86
--- /dev/null
+++ b/src/platform/realtek/zephyr/ThreadStackManagerImpl.h
@@ -0,0 +1,20 @@
+/*
+ *
+ * Copyright (c) 2020 Project CHIP Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <platform/Zephyr/ThreadStackManagerImpl.h>
diff --git a/src/platform/realtek/zephyr/args.gni b/src/platform/realtek/zephyr/args.gni
new file mode 100755
index 0000000..5a67c92
--- /dev/null
+++ b/src/platform/realtek/zephyr/args.gni
@@ -0,0 +1,25 @@
+# Copyright (c) 2020 Project CHIP Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+chip_device_platform = "realtek_zephyr"
+
+chip_inet_config_enable_ipv4 = false
+chip_inet_config_enable_tcp_endpoint = false
+
+declare_args() {
+ chip_malloc_sys_heap = false
+
+ # Enable factory data support
+ chip_enable_factory_data = false
+}
diff --git a/src/platform/realtek/zephyr/bee4-mbedtls-config.h b/src/platform/realtek/zephyr/bee4-mbedtls-config.h
new file mode 100755
index 0000000..b441c5b
--- /dev/null
+++ b/src/platform/realtek/zephyr/bee4-mbedtls-config.h
@@ -0,0 +1,72 @@
+#ifndef BEE4_MBEDTLS_CONFIG_H
+#define BEE4_MBEDTLS_CONFIG_H
+
+#define MBEDTLS_CIPHER_MODE_CTR
+
+#define MBEDTLS_ERROR_C
+#define MBEDTLS_ERROR_STRERROR_DUMMY
+#define MBEDTLS_HKDF_C
+#define MBEDTLS_PKCS5_C
+#define MBEDTLS_X509_CSR_PARSE_C
+#define MBEDTLS_X509_CSR_WRITE_C
+#define MBEDTLS_X509_CREATE_C
+
+// #define MBEDTLS_ECP_ALT
+// #include "hw_acc/crypto_engine_nsc.h"
+
+#define ENABLE_HW_RSA_VERIFY (1)
+#define ENABLE_HW_ECC_VERIFY (1)
+#define ENABLE_HW_EDDSA_VERIFY (1)
+#define ENABLE_HW_AES_VERIFY (1)
+#define ENABLE_HW_TRNG (1)
+#define ENABLE_HW_SHA256_VERIFY (1)
+
+#if ENABLE_HW_ECC_VERIFY == 1 || ENABLE_HW_EDDSA_VERIFY == 1 || ENABLE_HW_RSA_VERIFY == 1
+#define RTK_PUBKEY_ECC_MUL_ENTRY 0x1
+#define RTK_PUBKEY_MOD_MUL_ENTRY 0x2
+#define RTK_PUBKEY_MOD_ADD_ENTRY 0x3
+#define RTK_PUBKEY_Px_MOD_ENTRY 0x4
+#define RTK_PUBKEY_R_SQAR_ENTRY 0x5
+#define RTK_PUBKEY_N_INV_ENTRY 0x6
+#define RTK_PUBKEY_K_INV_ENTRY 0x7
+#define RTK_PUBKEY_ECC_ADD_POINT_ENTRY 0x8
+#define RTK_PUBKEY_ECC_POINT_CHECK_ENTRY 0x9
+#define RTK_PUBKEY_SET_A_FROM_P_ENTRY 0xa
+#define RTK_PUBKEY_K_INV_BIN_ENTRY 0x11
+#define RTK_PUBKEY_MOD_MUL_BIN_ENTRY 0xb
+#define RTK_PUBKEY_MOD_ADD_BIN_ENTRY 0xc
+#define RTK_PUBKEY_MOD_COMP_BIN_ENTRY 0xd
+#define RTK_PUBKEY_X_MOD_N_ENTRY 0xe
+#define RTK_PUBKEY_MOD_SUB_ENTRY 0xf
+
+#define GO_TO_END_LOOP 1
+#define RR_MOD_N_READY 1
+
+#define ECC_PRIME_MODE 0 // 3'b000
+#define ECC_BINARY_MODE 1 // 3'b001
+#define RSA_MODE 2 // 3'b010
+#define ECC_EDWARDS_CURVE 3 // 3'b011
+#define ECC_MONTGOMERY_CURVE 7 // 3'b111
+
+#define PKE_MMEM_ADDR 0x50090000
+
+#define RSA_N_ADDR (PKE_MMEM_ADDR + 0)
+#define RSA_E_ADDR (PKE_MMEM_ADDR + 0x180)
+#define RSA_A_ADDR (PKE_MMEM_ADDR + 0x300)
+#define RSA_RESULT_ADDR (PKE_MMEM_ADDR + 0x480)
+#define RSA_GEN_KEY_RESULT_ADDR (PKE_MMEM_ADDR + 0x3CC)
+
+#define ECC_N_ADDR (PKE_MMEM_ADDR + 0)
+#define ECC_E_ADDR (PKE_MMEM_ADDR + 0x40)
+#define ECC_CURVE_A_ADDR (PKE_MMEM_ADDR + 0x80)
+#define ECC_RR_MOD_N_ADDR (PKE_MMEM_ADDR + 0xC0)
+#define ECC_CURVE_B_ADDR (PKE_MMEM_ADDR + 0x100)
+#define ECC_X_ADDR (PKE_MMEM_ADDR + 0x140)
+#define ECC_Y_ADDR (PKE_MMEM_ADDR + 0x180)
+#define ECC_Z_ADDR (PKE_MMEM_ADDR + 0x1C0)
+#define ECC_X_RESULT_ADDR (PKE_MMEM_ADDR + 0x200)
+#define ECC_Y_RESULT_ADDR (PKE_MMEM_ADDR + 0x240)
+#define ECC_Z_RESULT_ADDR (PKE_MMEM_ADDR + 0x280)
+#endif
+
+#endif // BEE4_MBEDTLS_CONFIG_H
diff --git a/src/platform/realtek/zephyr/rtl87x2g_evb.overlay b/src/platform/realtek/zephyr/rtl87x2g_evb.overlay
new file mode 100644
index 0000000..60c3790
--- /dev/null
+++ b/src/platform/realtek/zephyr/rtl87x2g_evb.overlay
@@ -0,0 +1,127 @@
+/ {
+ chosen {
+ zephyr,ieee802154 = &ieee802154;
+ zephyr,code-partition = &app_partition_0;
+ zephyr,entropy = &trng;
+ };
+
+ leds {
+ compatible = "gpio-leds";
+ led0: led_0 {
+ gpios = <&gpioa 1 GPIO_ACTIVE_HIGH>;
+ label = "Green LED 0";
+ };
+ led1: led_1 {
+ gpios = <&gpioa 2 GPIO_ACTIVE_HIGH>;
+ label = "Green LED 1";
+ };
+ };
+
+ buttons {
+ compatible = "gpio-keys";
+ button0: button_0 {
+ gpios = <&gpiob 5 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>;
+ label = "Push button switch 0";
+ };
+ button1: button_1 {
+ gpios = <&gpiob 6 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>;
+ label = "Push button switch 1";
+ };
+ button2: button_2 {
+ gpios = <&gpioa 25 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>;
+ label = "Push button switch 2";
+ };
+ button3: button_3 {
+ gpios = <&gpioa 24 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>;
+ label = "Push button switch 3";
+ };
+ button4: button_4 {
+ gpios = <&gpiob 2 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>;
+ label = "Push button switch 4";
+ };
+ };
+
+ /* These aliases are provided for compatibility with samples */
+ aliases {
+ led0 = &led0;
+ led1 = &led1;
+ sw0 = &button0;
+ sw1 = &button1;
+ sw2 = &button2;
+ sw3 = &button3;
+ sw4 = &button4;
+ };
+
+ tcm {
+ /delete-node/ memory@100c00;
+ /delete-node/ memory@119c00;
+ /delete-node/ memory@133c00;
+
+ ram_data: memory@100c00 {
+ device_type = "ram data region";
+ reg = <0x100c00 0x30000>;
+ };
+ ram_code: memory@130C00 {
+ device_type = "ram code region";
+ compatible = "zephyr,memory-region", "arm,itcm";
+ reg = <0x130C00 0x7000>;
+ zephyr,memory-region = "ITCM";
+ };
+ heap: memory@137C00 {
+ device_type = "heap region";
+ reg = <0x137C00 0x5000>;
+ };
+ };
+};
+
+&gpioa {
+ status = "okay";
+};
+
+&gpiob {
+ status = "okay";
+};
+
+&flash {
+ reg = <0x4000000 DT_SIZE_M(4)>;
+ partitions {
+ /delete-node/ partition@2d000;
+ /delete-node/ partition@94000;
+ /delete-node/ partition@fc000;
+
+ app_partition_0: partition@2d000 {
+ label = "app-image";
+ reg = <0x2D000 DT_SIZE_K(1024)>;
+ };
+ /* Bank 1 */
+ ota_header_1: partition@12d000 {
+ label = "ota-header-1-image";
+ reg = <0x12D000 DT_SIZE_K(4)>;
+ };
+ system_patch_1: partition@12e000 {
+ label = "system-patch-1-image";
+ reg = <0x12E000 DT_SIZE_K(32)>;
+ };
+ stack_patch_1: partition@1360000 {
+ label = "stack-patch-1-image";
+ reg = <0x1360000 DT_SIZE_K(72)>;
+ };
+ app_partition_1: partition@148000 {
+ label = "app-image-1";
+ reg = <0x148000 DT_SIZE_K(1024)>;
+ };
+ /* storage */
+ storage_partition: partition@248000 {
+ label = "storage";
+ reg = <0x248000 DT_SIZE_K(32)>;
+ };
+ };
+};
+
+&trng {
+ status = "okay";
+};
+
+&ieee802154 {
+ status = "okay";
+};
\ No newline at end of file