diff --git a/.devcontainer/build.sh b/.devcontainer/build.sh new file mode 100755 index 00000000000000..761d911ef4467e --- /dev/null +++ b/.devcontainer/build.sh @@ -0,0 +1,85 @@ +#!/bin/bash + +# +# 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. +# + +HERE="$(dirname "$0")" +CHIP_ROOT="$(realpath "$HERE"/..)" +BUILD_VERSION="latest" +IMAGE_TAG="matter-dev-environment:local" +USER_UID=$UID + +function show_usage() { + cat < Preferences > Settings > Remote. - "settings": { - "terminal.integrated.shell.linux": "/bin/bash" + "customizations": { + "vscode": { + // Add the IDs of extensions you want installed when the container is created in the array below. + "extensions": [ + "mcu-debug.debug-tracker-vscode", + "aaron-bond.better-comments", + "augustocdias.tasks-shell-input", + "christian-kohler.path-intellisense", + "eamodio.gitlens", + "editorconfig.editorconfig", + "esbenp.prettier-vscode", + "foxundermoon.shell-format", + "github.vscode-pull-request-github", + "maelvalais.autoconf", + "marus25.cortex-debug", + "ms-azuretools.vscode-docker", + "ms-vscode.cpptools", + "msedge-dev.gnls", + "redhat.vscode-yaml", + "vadimcn.vscode-lldb", + "xaver.clang-format", + "yuichinukiyama.vscode-preview-server", + "yzhang.markdown-all-in-one" + ], + "settings": { + "terminal.integrated.defaultProfile.linux": "bash", + "terminal.integrated.profiles.linux": { + "bash": { + "path": "/bin/bash", + "args": ["-l"] + } + } + } + } }, "remoteEnv": { "GIT_PS1_SHOWDIRTYSTATE": "1", diff --git a/.github/.wordlist.txt b/.github/.wordlist.txt index d77e05b4f26c58..251fa2fee90749 100644 --- a/.github/.wordlist.txt +++ b/.github/.wordlist.txt @@ -88,6 +88,7 @@ armv ASAN asdk AssertionError +ASR AST ASYNC atomics diff --git a/.github/workflows/bloat_check.yaml b/.github/workflows/bloat_check.yaml index 99d279c20970c6..01f041cdd0a506 100644 --- a/.github/workflows/bloat_check.yaml +++ b/.github/workflows/bloat_check.yaml @@ -41,7 +41,6 @@ jobs: with: action: actions/checkout@v3 with: | - submodules: true token: ${{ github.token }} attempt_limit: 3 attempt_delay: 2000 diff --git a/.github/workflows/examples-cc13x2x7_26x2x7.yaml b/.github/workflows/examples-cc13x2x7_26x2x7.yaml index aaeaf094910373..f3703f38b85f69 100644 --- a/.github/workflows/examples-cc13x2x7_26x2x7.yaml +++ b/.github/workflows/examples-cc13x2x7_26x2x7.yaml @@ -53,7 +53,7 @@ jobs: attempt_limit: 3 attempt_delay: 2000 - name: Checkout submodules - run: scripts/checkout_submodules.py --allow-changing-global-git-config --shallow --platform cc13x2_26x2 + run: scripts/checkout_submodules.py --allow-changing-global-git-config --shallow --platform cc13xx_26xx - name: Set up environment for size reports if: ${{ !env.ACT }} env: @@ -79,75 +79,5 @@ jobs: path: | .environment/gn_out/.ninja_log .environment/pigweed-venv/*.log + - - name: Build examples - timeout-minutes: 100 - run: | - scripts/run_in_build_env.sh "\ - ./scripts/build/build_examples.py \ - --target cc13x2x7_26x2x7-all-clusters-mtd \ - --target cc13x2x7_26x2x7-all-clusters-minimal \ - --target cc13x2x7_26x2x7-lock-ftd \ - --target cc13x2x7_26x2x7-lock-mtd \ - --target cc13x2x7_26x2x7-pump \ - --target cc13x2x7_26x2x7-pump-controller \ - --target cc13x2x7_26x2x7-shell \ - build \ - --copy-artifacts-to out/artifacts \ - " - - name: Get lock FTD size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 lock-ftd \ - out/artifacts/cc13x2x7_26x2x7-lock-ftd/chip-LP_CC2652R7-lock-example.out \ - /tmp/bloat_reports/ - - name: Get lock MTD size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 lock-mtd \ - out/artifacts/cc13x2x7_26x2x7-lock-mtd/chip-LP_CC2652R7-lock-example.out \ - /tmp/bloat_reports/ - - name: Get Pump App size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 pump-app \ - out/artifacts/cc13x2x7_26x2x7-pump/chip-LP_CC2652R7-pump-example.out \ - /tmp/bloat_reports/ - - name: Get Pump Controller App size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 pump-controller-app \ - out/artifacts/cc13x2x7_26x2x7-pump-controller/chip-LP_CC2652R7-pump-controller-example.out \ - /tmp/bloat_reports/ - - name: Get All Clusters App size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 all-clusters-app \ - out/artifacts/cc13x2x7_26x2x7-all-clusters-mtd/chip-LP_CC2652R7-all-clusters-example.out \ - /tmp/bloat_reports/ - - name: Get All Clusters Minimal App size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 all-clusters-minimal-app \ - out/artifacts/cc13x2x7_26x2x7-all-clusters-minimal/chip-LP_CC2652R7-all-clusters-minimal-example.out \ - /tmp/bloat_reports/ - - name: Get Shell App size stats - timeout-minutes: 5 - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cc13x2_26x2 LP_CC2652R7 shell \ - out/artifacts/cc13x2x7_26x2x7-shell/chip-LP_CC2652R7-shell-example.out \ - /tmp/bloat_reports/ - - name: Uploading Size Reports - uses: actions/upload-artifact@v3 - if: ${{ !env.ACT }} - with: - name: Size,cc13x2x7_26x2x7-Examples,${{ env.GH_EVENT_PR }},${{ env.GH_EVENT_HASH }},${{ env.GH_EVENT_PARENT }},${{ github.event_name }} - path: | - /tmp/bloat_reports/ diff --git a/.github/workflows/examples-openiotsdk.yaml b/.github/workflows/examples-openiotsdk.yaml index e34b079f2b81d7..d2f2e904c70827 100644 --- a/.github/workflows/examples-openiotsdk.yaml +++ b/.github/workflows/examples-openiotsdk.yaml @@ -32,7 +32,7 @@ env: jobs: openiotsdk: name: Open IoT SDK examples building - timeout-minutes: 140 + timeout-minutes: 90 env: TEST_NETWORK_NAME: OIStest @@ -107,25 +107,22 @@ jobs: run: | scripts/examples/openiotsdk_example.sh unit-tests - - name: Test shell example - # Temporarily disable test due to performance issue with FVP - if: false #steps.build_shell.outcome == 'success' + - name: "Test: shell example" + if: steps.build_shell.outcome == 'success' timeout-minutes: 5 run: | scripts/examples/openiotsdk_example.sh -C test shell - - name: Test lock-app example - # Temporarily disable test due to performance issue with FVP - if: false #steps.build_lock_app.outcome == 'success' + - name: "Test: lock-app example" + if: steps.build_lock_app.outcome == 'success' timeout-minutes: 5 run: | scripts/setup/openiotsdk/network_setup.sh -n $TEST_NETWORK_NAME up scripts/run_in_ns.sh ${TEST_NETWORK_NAME}ns scripts/examples/openiotsdk_example.sh -C test -n ${TEST_NETWORK_NAME}tap lock-app scripts/setup/openiotsdk/network_setup.sh -n $TEST_NETWORK_NAME down - - name: Run unit tests - # Temporarily disable test due to performance issue with FVP - if: false #steps.build_unit_tests.outcome == 'success' && github.event_name == 'pull_request' - timeout-minutes: 90 + - name: "Test: unit-tests" + if: steps.build_unit_tests.outcome == 'success' + timeout-minutes: 40 run: | - scripts/examples/openiotsdk_example.sh -C run unit-tests + scripts/examples/openiotsdk_example.sh -C test unit-tests diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index fef2d3e1c8dabf..129a1de287cc6b 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -214,3 +214,8 @@ jobs: if: always() run: | git grep -n 'SuccessOrExit(CHIP_ERROR' -- './*' ':(exclude).github/workflows/lint.yml' && exit 1 || exit 0 + + - name: Check that our hardcoded SHA for clang-format on ARM mac matches the pigweed SHA. + if: always() + run: | + ./scripts/lints/clang-format-version-matches.py diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 4266a3abe945dc..443b2940a7154a 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -121,6 +121,7 @@ jobs: src/app/zap-templates/zcl/data-model/chip/access-control-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/account-login-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/administrator-commissioning-cluster.xml \ + src/app/zap-templates/zcl/data-model/chip/air-quality-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/application-basic-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/application-launcher-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/audio-output-cluster.xml \ @@ -192,6 +193,7 @@ jobs: src/app/zap-templates/zcl/data-model/draft/electrical-measurement-cluster.xml \ src/app/zap-templates/zcl/data-model/draft/input-output-value-clusters.xml \ src/app/zap-templates/zcl/data-model/draft/onoff-switch-configuration-cluster.xml \ + src/app/zap-templates/zcl/data-model/chip/replacable-monitoring-cluster.xml \ " - name: Build Apps timeout-minutes: 60 @@ -674,6 +676,30 @@ jobs: --tool-args "address-paseonly --nodeid 1 --setup-pin-code 20202021 --address ::1 --port 5540 -t 1000" \ --factoryreset \ ' + - name: Run Pairing SetupQRCode Test + timeout-minutes: 10 + run: | + scripts/run_in_build_env.sh \ + './scripts/tests/run_java_test.py \ + --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app \ + --app-args "--discriminator 3840 --interface-id -1" \ + --tool-path out/linux-x64-java-matter-controller \ + --tool-cluster "pairing" \ + --tool-args "code --nodeid 1 --setup-payload MT:-24J0AFN00KA0648G00 --discover-once 1 --use-only-onnetwork-discovery 0 -t 1000" \ + --factoryreset \ + ' + - name: Run Pairing ManualCode Test + timeout-minutes: 10 + run: | + scripts/run_in_build_env.sh \ + './scripts/tests/run_java_test.py \ + --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app \ + --app-args "--discriminator 3840 --interface-id -1" \ + --tool-path out/linux-x64-java-matter-controller \ + --tool-cluster "pairing" \ + --tool-args "code --nodeid 1 --setup-payload 34970112332 --discover-once 1 --use-only-onnetwork-discovery 0 -t 1000" \ + --factoryreset \ + ' - name: Uploading core files uses: actions/upload-artifact@v3 if: ${{ failure() && !env.ACT }} diff --git a/.gitmodules b/.gitmodules index d368b904833686..5478beda037473 100644 --- a/.gitmodules +++ b/.gitmodules @@ -58,7 +58,7 @@ path = third_party/freertos/repo url = https://github.com/FreeRTOS/FreeRTOS-Kernel.git branch = V10.3.1-kernel-only - platforms = ameba,cc13x2_26x2,bouffalolab,efr32,esp32,k32w0,infineon,qpg,cc32xx,silabs_docker + platforms = ameba,cc13xx_26xx,bouffalolab,efr32,esp32,k32w0,infineon,qpg,cc32xx,silabs_docker [submodule "simw-top-mini"] path = third_party/simw-top-mini/repo url = https://github.com/NXP/plug-and-trust.git @@ -224,12 +224,17 @@ path = third_party/ti_simplelink_sdk/repo_cc13xx_cc26xx url = https://github.com/TexasInstruments/cc13xx_cc26xx_sdk.git branch = main - platforms = cc13x2_26x2 + platforms = cc13xx_26xx [submodule "third_party/ti_simplelink_sdk/repo_cc32xx"] path = third_party/ti_simplelink_sdk/repo_cc32xx url = https://github.com/TexasInstruments/cc32xx_open_sdk.git branch = main platforms = cc32xx +[submodule "third_party/openthread/ot-ti"] + path = third_party/openthread/ot-ti + url = https://github.com/TexasInstruments/ot-ti.git + branch = main + platforms = cc13xx_26xx [submodule "third_party/nxp/mw320_sdk/repo"] path = third_party/nxp/mw320_sdk/repo url = https://github.com/nxptest/mw320_sdk @@ -293,3 +298,13 @@ path = third_party/imgui/repo url = https://github.com/ocornut/imgui platforms = linux +[submodule "third_party/asr/asr582x/asr_sdk"] + path = third_party/asr/asr582x/asr_sdk + url = https://github.com/asriot/ASR582X_Freertos.git + branch = matter + platforms = asr +[submodule "third_party/asr/asr595x/asr_sdk"] + path = third_party/asr/asr595x/asr_sdk + url = https://github.com/asriot/ASR595X_Freertos.git + branch = matter + platforms = asr diff --git a/.vscode/launch.json b/.vscode/launch.json index e68b78cbd4e57a..83ce3d5fe494bd 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -455,7 +455,13 @@ "armToolchainPath": "${env:PW_ENVIRONMENT_ROOT}/cipd/packages/arm/bin/", "servertype": "external", "gdbTarget": ":31627", //GDBserver port on FVP - "overrideLaunchCommands": ["-enable-pretty-printing"], + "overrideLaunchCommands": [ + "-enable-pretty-printing", + "add-symbol-file ./build/bl2.elf 0x10000000", + "add-symbol-file ./build/tfm_s.elf 0x38000400", + "add-symbol-file ./build/${input:openiotsdkUnittest}_ns.elf 0x28060400", + "break main_ns.cpp:main" + ], "runToEntryPoint": "main", "preLaunchTask": "Debug Open IoT SDK unit-tests", "showDevDebugOutput": "parsed" diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 2e495a9536fd2c..d0e5fbfae284c4 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -250,6 +250,7 @@ "args": [ "-Cbuild", "-d${input:openiotsdkDebugMode}", + "-l${input:openiotsdkLwipDebug}", "${input:openiotsdkExample}" ], "group": "build", @@ -266,7 +267,12 @@ "label": "Build Open IoT SDK unit-tests", "type": "shell", "command": "scripts/examples/openiotsdk_example.sh", - "args": ["-Cbuild", "-d${input:openiotsdkDebugMode}", "unit-tests"], + "args": [ + "-Cbuild", + "-d${input:openiotsdkDebugMode}", + "-l${input:openiotsdkLwipDebug}", + "unit-tests" + ], "group": "build", "problemMatcher": { "pattern": { @@ -334,6 +340,21 @@ } } }, + { + "label": "Test Open IoT SDK unit-tests", + "type": "shell", + "command": "scripts/examples/openiotsdk_example.sh", + "args": ["-Ctest", "unit-tests", "${input:openiotsdkUnitTest}"], + "group": "test", + "problemMatcher": { + "pattern": { + "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$", + "file": 1, + "line": 2, + "message": 5 + } + } + }, { "label": "Debug Open IoT SDK example", "type": "shell", @@ -439,6 +460,13 @@ "options": ["false", "true"], "default": "false" }, + { + "type": "pickString", + "id": "openiotsdkLwipDebug", + "description": "Do you want to use LwIP debug logs?", + "options": ["false", "true"], + "default": "false" + }, { "type": "pickString", "id": "openiotsdkExample", @@ -451,7 +479,6 @@ "id": "openiotsdkUnitTest", "description": "What unit test do you want to use?", "options": [ - "all", "accesstest", "AppTests", "ASN1Tests", @@ -478,7 +505,7 @@ "TransportLayerTests", "UserDirectedCommissioningTests" ], - "default": "all" + "default": "accesstest" }, { "type": "promptString", diff --git a/build_overrides/asr.gni b/build_overrides/asr.gni new file mode 100755 index 00000000000000..d012a516b2102f --- /dev/null +++ b/build_overrides/asr.gni @@ -0,0 +1,23 @@ +# 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. + +declare_args() { + asr_ic_family = "asr582x" + + # Root directory for ASR SDK build files. + asr_sdk_build_root = "//third_party/connectedhomeip/third_party/asr/asr582x" + + # Root directory for ASR toolchain. + asr_toolchain_root = "" +} diff --git a/config/asr/toolchain/BUILD.gn b/config/asr/toolchain/BUILD.gn new file mode 100755 index 00000000000000..d13d7e1888f07a --- /dev/null +++ b/config/asr/toolchain/BUILD.gn @@ -0,0 +1,47 @@ +# 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. + +import("//build_overrides/asr.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") + +assert(asr_ic_family == "asr582x" || asr_ic_family == "asr595x", + "Unsupported ASR IC: ${asr_ic_family}") + +if (asr_ic_family == "asr582x") { + import("${build_root}/toolchain/arm_gcc/arm_toolchain.gni") + _tool_name_root = "${asr_toolchain_root}arm-none-eabi-" +} + +if (asr_ic_family == "asr595x") { + import("${build_root}/toolchain/riscv_gcc/riscv_toolchain.gni") + _tool_name_root = "${asr_toolchain_root}riscv-asr-elf-" +} + +declare_args() { + asr_ar = _tool_name_root + "ar" + asr_cc = _tool_name_root + "gcc" + asr_cxx = _tool_name_root + "g++" +} + +gcc_toolchain("asrtoolchain") { + ar = asr_ar + cc = asr_cc + cxx = asr_cxx + + toolchain_args = { + current_os = "freertos" + is_clang = false + } +} diff --git a/config/nrfconnect/chip-module/generate_factory_data.cmake b/config/nrfconnect/chip-module/generate_factory_data.cmake index a754f22873c13d..491411cb6a3dd4 100644 --- a/config/nrfconnect/chip-module/generate_factory_data.cmake +++ b/config/nrfconnect/chip-module/generate_factory_data.cmake @@ -90,6 +90,11 @@ string(APPEND script_args "--discriminator ${CONFIG_CHIP_DEVICE_DISCRIMINATOR}\n string(APPEND script_args "--passcode ${CONFIG_CHIP_DEVICE_SPAKE2_PASSCODE}\n") string(APPEND script_args "--include_passcode\n") string(APPEND script_args "--overwrite\n") +string(APPEND script_args "--product_finish ${CONFIG_CHIP_DEVICE_PRODUCT_FINISH}\n") + +if(CONFIG_CHIP_DEVICE_PRODUCT_COLOR) + string(APPEND script_args "--product_color ${CONFIG_CHIP_DEVICE_PRODUCT_COLOR}\n") +endif() if(CONFIG_CHIP_FACTORY_DATA_GENERATE_ONBOARDING_CODES) string(APPEND script_args "--generate_onboarding\n") diff --git a/config/openiotsdk/cmake/linker.cmake b/config/openiotsdk/cmake/linker.cmake index 032b95f54afd60..fc3429ffd78656 100644 --- a/config/openiotsdk/cmake/linker.cmake +++ b/config/openiotsdk/cmake/linker.cmake @@ -27,12 +27,12 @@ function(set_target_link target) if (NOT LINKER_SCRIPT) set(LINKER_SCRIPT ${OPEN_IOT_SDK_CONFIG}/ld/cs300_gcc.ld) endif() - target_link_options(${APP_TARGET} PRIVATE -T ${LINKER_SCRIPT}) - set_target_properties(${APP_TARGET} PROPERTIES LINK_DEPENDS ${LINKER_SCRIPT}) + target_link_options(${target} PRIVATE -T ${LINKER_SCRIPT}) + set_target_properties(${target} PROPERTIES LINK_DEPENDS ${LINKER_SCRIPT}) target_link_options(${target} PRIVATE - "-Wl,-Map=${APP_TARGET}.map" + "-Wl,-Map=${target}.map" ) endfunction() diff --git a/config/openiotsdk/cmake/sdk.cmake b/config/openiotsdk/cmake/sdk.cmake index dbe54d4d122c37..7fbc7efa9561bc 100644 --- a/config/openiotsdk/cmake/sdk.cmake +++ b/config/openiotsdk/cmake/sdk.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) 2022 Project CHIP Authors +# 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. @@ -30,6 +30,12 @@ list(APPEND CONFIG_CHIP_EXTERNAL_TARGETS) # Additional Open IoT SDK build configuration set(TFM_SUPPORT NO CACHE BOOL "Add Trusted Firmware-M (TF-M) support to application") set(TFM_NS_APP_VERSION "0.0.0" CACHE STRING "TF-M non-secure application version (in the x.x.x format)") +set(CONFIG_CHIP_OPEN_IOT_SDK_LWIP_DEBUG NO CACHE BOOL "Enable LwIP debug logs") + +# Default LwIP options directory (should contain user_lwipopts.h file) +if (NOT LWIP_PROJECT_OPTS_DIR) + set(LWIP_PROJECT_OPTS_DIR ${OPEN_IOT_SDK_CONFIG}/lwip) +endif() # Overwrite versions of Open IoT SDK components @@ -76,11 +82,11 @@ if(TFM_SUPPORT) set(TFM_PLATFORM ${OPEN_IOT_SDK_EXAMPLE_COMMON}/tf-m/targets/an552) set(TFM_PSA_FIRMWARE_UPDATE ON) set(MCUBOOT_IMAGE_VERSION_NS ${TFM_NS_APP_VERSION}) - set(TFM_CMAKE_ARGS "-DCONFIG_TFM_ENABLE_FP=ON;-DTFM_PROFILE=profile_medium") + set(TFM_CMAKE_ARGS "-DCONFIG_TFM_ENABLE_FP=ON;-DTFM_PROFILE=profile_medium;-DTFM_EXCEPTION_INFO_DUMP=ON;-DCONFIG_TFM_HALT_ON_CORE_PANIC=ON;-DTFM_ISOLATION_LEVEL=1") if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") - set(TFM_CMAKE_ARGS "${TFM_CMAKE_ARGS};-DMCUBOOT_LOG_LEVEL=INFO;-DTFM_SPM_LOG_LEVEL=TFM_SPM_LOG_LEVEL_INFO;-DTFM_PARTITION_LOG_LEVEL=TFM_PARTITION_LOG_LEVEL_INFO") + set(TFM_CMAKE_ARGS "${TFM_CMAKE_ARGS};-DMCUBOOT_LOG_LEVEL=INFO;-DTFM_SPM_LOG_LEVEL=TFM_SPM_LOG_LEVEL_DEBUG;-DTFM_PARTITION_LOG_LEVEL=TFM_PARTITION_LOG_LEVEL_INFO") else() - set(TFM_CMAKE_ARGS "${TFM_CMAKE_ARGS};-DMCUBOOT_LOG_LEVEL=ERROR;-DTFM_SPM_LOG_LEVEL=TFM_SPM_LOG_LEVEL_ERROR;-DTFM_PARTITION_LOG_LEVEL=TFM_PARTITION_LOG_LEVEL_ERROR") + set(TFM_CMAKE_ARGS "${TFM_CMAKE_ARGS};-DMCUBOOT_LOG_LEVEL=ERROR;-DTFM_SPM_LOG_LEVEL=TFM_SPM_LOG_LEVEL_DEBUG;-DTFM_PARTITION_LOG_LEVEL=TFM_PARTITION_LOG_LEVEL_ERROR") endif() if(TFM_PROJECT_CONFIG_HEADER_FILE) set(TFM_CMAKE_ARGS "${TFM_CMAKE_ARGS};-DPROJECT_CONFIG_HEADER_FILE=${TFM_PROJECT_CONFIG_HEADER_FILE}") @@ -135,7 +141,6 @@ if(TARGET cmsis-rtos-api) target_link_libraries(cmsis-rtos-api PUBLIC freertos-cmsis-rtos - freertos-kernel-heap-3 ) target_compile_definitions(cmsis-rtos-api @@ -162,12 +167,17 @@ if(TARGET lwip-cmsis-port) target_compile_definitions(lwipopts INTERFACE DEBUG_PRINT=printf + $<$:LWIP_DEBUG> + $<$:CHIP_LIB_TESTS> ) - if(TARGET lwip-cmsis-port) - # Link the emac factory to LwIP port - target_link_libraries(lwip-cmsis-port PUBLIC iotsdk-emac-factory) - endif() + target_include_directories(lwipopts + INTERFACE + ${LWIP_PROJECT_OPTS_DIR} + ) + + # Link the emac factory to LwIP port + target_link_libraries(lwip-cmsis-port PUBLIC iotsdk-emac-factory) endif() # MDH configuration @@ -183,6 +193,15 @@ if(TARGET mcu-driver-hal) INTERFACE DOMAIN_NS=$,1,0> ) + + # Fixing the optimization issue for mcu-driver-hal target in the no-debug build. + # The default -Og optimization causes performance issues for the application. + # We need to replace it with -O2 which is suitable for performance. + # This fix can be removed in the future when the issue will be fixed in SDK directly. + if (NOT "${CMAKE_BUILD_TYPE}" STREQUAL "Debug") + target_compile_options(mcu-driver-hal INTERFACE $<$:-O2>) + target_compile_options(mcu-driver-hal INTERFACE $<$:-O2>) + endif() endif() # Mbedtls config @@ -279,66 +298,84 @@ list(APPEND CONFIG_CHIP_EXTERNAL_TARGETS ) function(sdk_post_build target) - string(REPLACE "_ns" "" APP_NAME ${APP_TARGET}) + string(REPLACE "_ns" "" APP_NAME ${target}) if(TFM_SUPPORT) include(ConvertElfToBin) include(SignTfmImage) - target_elf_to_bin(${APP_TARGET}) - iotsdk_tf_m_sign_image(${APP_TARGET}) - iotsdk_tf_m_merge_images(${APP_TARGET} 0x10000000 0x38000000 0x28060000) ExternalProject_Get_Property(trusted-firmware-m-build BINARY_DIR) + target_elf_to_bin(${target}) + add_custom_command( + TARGET + ${target} + POST_BUILD + DEPENDS + $/${target}.bin + COMMAND + # Sign the non-secure (application) image for TF-M bootloader (BL2)" + python3 ${BINARY_DIR}/install/image_signing/scripts/wrapper/wrapper.py + --layout ${BINARY_DIR}/install/image_signing/layout_files/signing_layout_ns.o + -v ${MCUBOOT_IMAGE_VERSION_NS} + -k ${BINARY_DIR}/install/image_signing/keys/root-RSA-3072_1.pem + --public-key-format full + --align 1 --pad --pad-header -H 0x400 -s auto -d "(0, 0.0.0+0)" + $/${target}.bin + --overwrite-only + --measured-boot-record + $/${target}_signed.bin + VERBATIM + ) + iotsdk_tf_m_merge_images(${target} 0x10000000 0x38000000 0x28060000) # Cleanup add_custom_command( TARGET - ${APP_TARGET} + ${target} POST_BUILD DEPENDS - $/tfm_s_signed.bin - $/${APP_TARGET}.bin - $/${APP_TARGET}_signed.bin - $/${APP_TARGET}_merged.hex - $/${APP_TARGET}_merged.elf + $/${target}.bin + $/${target}_signed.bin + $/${target}_merged.hex + $/${target}_merged.elf COMMAND - # Copy the TF-M secure elf image + # Copy the bootloader and TF-M secure image for debugging purposes ${CMAKE_COMMAND} -E copy + ${BINARY_DIR}/install/outputs/bl2.elf ${BINARY_DIR}/install/outputs/tfm_s.elf - $/ + $/ COMMAND # Rename output file ${CMAKE_COMMAND} -E copy - $/${APP_TARGET}_merged.elf - $/${APP_NAME}.elf + $/${target}_merged.elf + $/${APP_NAME}.elf COMMAND rm ARGS -Rf - $/tfm_s_signed.bin - $/${APP_TARGET}.bin - $/${APP_TARGET}_signed.bin - $/${APP_TARGET}_merged.hex - $/${APP_TARGET}_merged.elf + $/${target}.bin + $/${target}_signed.bin + $/${target}_merged.hex + $/${target}_merged.elf VERBATIM ) else() add_custom_command( TARGET - ${APP_TARGET} + ${target} POST_BUILD DEPENDS - $/${APP_TARGET}.elf - $/${APP_TARGET}.map + $/${target}.elf + $/${target}.map COMMAND # Rename output elf file ${CMAKE_COMMAND} -E copy - $/${APP_TARGET}.elf - $/${APP_NAME}.elf + $/${target}.elf + $/${APP_NAME}.elf COMMAND # Rename output map file ${CMAKE_COMMAND} -E copy - $/${APP_TARGET}.map - $/${APP_NAME}.map + $/${target}.map + $/${APP_NAME}.map COMMAND rm ARGS -Rf - $/${APP_TARGET}.elf - $/${APP_TARGET}.map + $/${target}.elf + $/${target}.map VERBATIM ) endif() #TFM_SUPPORT diff --git a/config/openiotsdk/ld/cs300_gcc_tfm.ld b/config/openiotsdk/ld/cs300_gcc_tfm.ld index 523c96e8efb77c..fd1d951258d917 100644 --- a/config/openiotsdk/ld/cs300_gcc_tfm.ld +++ b/config/openiotsdk/ld/cs300_gcc_tfm.ld @@ -18,7 +18,7 @@ MEMORY { FLASH (rx) : ORIGIN = ((0x28000000) + (0x60000) + (0x400)), LENGTH = ((0x200000) - (0x400) - (0x800)) - RAM (rwx) : ORIGIN = 0x21000000, LENGTH = 0x100000 + RAM (rwx) : ORIGIN = 0x21000000, LENGTH = 0x200000 } __stack_size__ = 0x1000; diff --git a/config/openiotsdk/lwip/user_lwipopts.h b/config/openiotsdk/lwip/user_lwipopts.h index 8bf38b1129fc56..48d8d4aee81b21 100644 --- a/config/openiotsdk/lwip/user_lwipopts.h +++ b/config/openiotsdk/lwip/user_lwipopts.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2022-2023 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,12 +19,35 @@ #ifndef USER_LWIPOPTS_H #define USER_LWIPOPTS_H +/** + * MEM_LIBC_MALLOC: use malloc/free/realloc provided by your C-library + * instead of the lwip internal allocator. + */ +#define MEM_LIBC_MALLOC (1) + +/** + * MEMP_NUM_NETBUF: the number of struct netbufs. + */ +#define MEMP_NUM_NETBUF 16 + +/** + * PBUF_POOL_SIZE: the number of buffers in the pbuf pool. + * + * Some unit tests required more pbuf buffers. + */ +#ifdef CHIP_LIB_TESTS +#define PBUF_POOL_SIZE (1001) +#endif // CHIP_LIB_TESTS + +/** + * LWIP_STATS : Turn off statistics gathering + */ #define LWIP_STATS (0) -#define LWIP_IGMP (1) -#define LWIP_RAW (1) -#define MEM_LIBC_MALLOC (1) -#define MEM_USE_POOLS (0) +/** + * LWIP_RAW: Enable application layer to hook into the IP layer itself. + */ +#define LWIP_RAW (1) #ifdef LWIP_DEBUG diff --git a/config/zephyr/Kconfig b/config/zephyr/Kconfig index b1edad054824c7..f0e8d9eddfcb66 100644 --- a/config/zephyr/Kconfig +++ b/config/zephyr/Kconfig @@ -201,6 +201,23 @@ config CHIP_DEVICE_ENABLE_KEY test action. This value is used during certification tests, and should not be present on devices in production environment. +config CHIP_DEVICE_PRODUCT_FINISH + string "Description of the product's external case finish method" + default "other" + help + provides a description of the product's external case finish method. + Possible values: + other; matte; satin; polished; rugged; fabric + +config CHIP_DEVICE_PRODUCT_COLOR + string "Description of the product's primary color" + help + provides a description of the product's primary color. + Possible values: + black; navy; green; teal; maroon; purple; olive; gray; blue; lime; + aqua; red; fuchsia; yellow; white; nickel; chrome; brass; cooper; + silver; gold. + # Matter optional features and parameters config CHIP_ENABLE_PAIRING_AUTOSTART diff --git a/docs/guides/nrfconnect_factory_data_configuration.md b/docs/guides/nrfconnect_factory_data_configuration.md index 16a9210c41fb8c..59eb99b50ad101 100644 --- a/docs/guides/nrfconnect_factory_data_configuration.md +++ b/docs/guides/nrfconnect_factory_data_configuration.md @@ -30,27 +30,29 @@ data secure by applying hardware write protection.
-- [Overview](#overview) - - [Factory data component table](#factory-data-component-table) - - [Factory data format](#factory-data-format) -- [Enabling factory data support](#enabling-factory-data-support) -- [Generating factory data](#generating-factory-data) - - [Creating the factory data JSON file with the first script](#creating-the-factory-data-json-file-with-the-first-script) - - [How to set user data](#how-to-set-user-data) - - [How to handle user data](#how-to-handle-user-data) - - [Verifying using the JSON Schema tool](#verifying-using-the-json-schema-tool) - - [Option 1: Using the php-json-schema tool](#option-1-using-the-php-json-schema-tool) - - [Option 2: Using a website validator](#option-2-using-a-website-validator) - - [Option 3: Using the nRF Connect Python script](#option-3-using-the-nrf-connect-python-script) - - [Generating onboarding codes](#generating-onboarding-codes) - - [Enabling onboarding codes generation within the build system](#enabling-onboarding-codes-generation-within-the-build-system) - - [Preparing factory data partition on a device](#preparing-factory-data-partition-on-a-device) - - [Creating a factory data partition with the second script](#creating-a-factory-data-partition-with-the-second-script) -- [Building an example with factory data](#building-an-example-with-factory-data) - - [Providing factory data parameters as a build argument list](#providing-factory-data-parameters-as-a-build-argument-list) - - [Setting factory data parameters using interactive Kconfig interfaces](#setting-factory-data-parameters-using-interactive-kconfig-interfaces) -- [Programming factory data](#programming-factory-data) -- [Using own factory data implementation](#using-own-factory-data-implementation) +- [Configuring factory data for the nRF Connect examples](#configuring-factory-data-for-the-nrf-connect-examples) + - [Overview](#overview) + - [Factory data component table](#factory-data-component-table) + - [Factory data format](#factory-data-format) + - [Appearance field description](#appearance-field-description) + - [Enabling factory data support](#enabling-factory-data-support) + - [Generating factory data](#generating-factory-data) + - [Creating the factory data JSON file with the first script](#creating-the-factory-data-json-file-with-the-first-script) + - [How to set user data](#how-to-set-user-data) + - [How to handle user data](#how-to-handle-user-data) + - [Verifying using the JSON Schema tool](#verifying-using-the-json-schema-tool) + - [Option 1: Using the php-json-schema tool](#option-1-using-the-php-json-schema-tool) + - [Option 2: Using a website validator](#option-2-using-a-website-validator) + - [Option 3: Using the nRF Connect Python script](#option-3-using-the-nrf-connect-python-script) + - [Generating onboarding codes](#generating-onboarding-codes) + - [Enabling onboarding codes generation within the build system](#enabling-onboarding-codes-generation-within-the-build-system) + - [Preparing factory data partition on a device](#preparing-factory-data-partition-on-a-device) + - [Creating a factory data partition with the second script](#creating-a-factory-data-partition-with-the-second-script) + - [Building an example with factory data](#building-an-example-with-factory-data) + - [Providing factory data parameters as a build argument list](#providing-factory-data-parameters-as-a-build-argument-list) + - [Setting factory data parameters using interactive Kconfig interfaces](#setting-factory-data-parameters-using-interactive-kconfig-interfaces) + - [Programming factory data](#programming-factory-data) + - [Using own factory data implementation](#using-own-factory-data-implementation)
@@ -87,27 +89,28 @@ about The following table lists the parameters of a factory data set: -| Key name | Full name | Length | Format | Conformance | Description | -| :---------------: | :----------------------------------: | :--------: | :----------: | :---------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | -| `version` | factory data version | 2 B | uint16 | mandatory | A version of the current factory data set. It cannot be changed by a user and it must be coherent with current version of the Factory Data Provider on device side. | -| `sn` | serial number | <1, 32> B | ASCII string | mandatory | A serial number parameter defines an unique number of manufactured device. The maximum length of the serial number is 32 characters. | -| `vendor_id` | vendor ID | 2 B | uint16 | mandatory | A CSA-assigned ID for the organization responsible for producing the device. | -| `product_id` | product ID | 2 B | uint16 | mandatory | A unique ID assigned by the device vendor to identify the product. It defaults to a CSA-assigned ID that designates a non-production or test product. | -| `vendor_name` | vendor name | <1, 32> B | ASCII string | mandatory | A human-readable vendor name that provides a simple string containing identification of device's vendor for the application and Matter stack purposes. | -| `product_name` | product name | <1, 32> B | ASCII string | mandatory | A human-readable product name that provides a simple string containing identification of the product for the application and the Matter stack purposes. | -| `date` | manufacturing date | <8, 10> B | ISO 8601 | mandatory | A manufacturing date specifies the date that the device was manufactured. The date format used is ISO 8601, for example `YYYY-MM-DD`. | -| `hw_ver` | hardware version | 2 B | uint16 | mandatory | A hardware version number that specifies the version number of the hardware of the device. The value meaning and the versioning scheme is defined by the vendor. | -| `hw_ver_str` | hardware version string | <1, 64> B | uint16 | mandatory | A hardware version string parameter that specifies the version of the hardware of the device as a more user-friendly value than that presented by the hardware version integer value. The value meaning and the versioning scheme is defined by the vendor. | -| `rd_uid` | rotating device ID unique ID | <16, 32> B | byte string | mandatory | The unique ID for rotating device ID, which consists of a randomly-generated 128-bit (or longer) octet string. This parameter should be protected against reading or writing over-the-air after initial introduction into the device, and stay fixed during the lifetime of the device. | -| `dac_cert` | (DAC) Device Attestation Certificate | <1, 602> B | byte string | mandatory | The Device Attestation Certificate (DAC) and the corresponding private key are unique to each Matter device. The DAC is used for the Device Attestation process and to perform commissioning into a fabric. The DAC is a DER-encoded X.509v3-compliant certificate, as defined in RFC 5280. | -| `dac_key` | DAC private key | 68 B | byte string | mandatory | The private key associated with the Device Attestation Certificate (DAC). This key should be encrypted and maximum security should be guaranteed while generating and providing it to factory data. | -| `pai_cert` | Product Attestation Intermediate | <1, 602> B | byte string | mandatory | An intermediate certificate is an X.509 certificate, which has been signed by the root certificate. The last intermediate certificate in a chain is used to sign the leaf (the Matter device) certificate. The PAI is a DER-encoded X.509v3-compliant certificate as defined in RFC 5280. | | -| `spake2_it` | SPAKE2+ iteration counter | 4 B | uint32 | mandatory | A SPAKE2+ iteration counter is the amount of PBKDF2 (a key derivation function) interactions in a cryptographic process used during SPAKE2+ Verifier generation. | -| `spake2_salt` | SPAKE2+ salt | <32, 64> B | byte string | mandatory | The SPAKE2+ salt is a random piece of data, at least 32 byte long. It is used as an additional input to a one-way function that performs the cryptographic operations. A new salt should be randomly generated for each password. | -| `spake2_verifier` | SPAKE2+ verifier | 97 B | byte string | mandatory | The SPAKE2+ verifier generated using SPAKE2+ salt, iteration counter, and passcode. | -| `discriminator` | Discriminator | 2 B | uint16 | mandatory | A 12-bit value matching the field of the same name in the setup code. The discriminator is used during the discovery process. | -| `passcode` | SPAKE passcode | 4 B | uint32 | optional | A pairing passcode is a 27-bit unsigned integer which serves as a proof of possession during the commissioning. Its value must be restricted to the values from `0x0000001` to `0x5F5E0FE` (`00000001` to `99999998` in decimal), excluding the following invalid passcode values: `00000000`, `11111111`, `22222222`, `33333333`, `44444444`, `55555555`, `66666666`, `77777777`, `88888888`, `99999999`, `12345678`, `87654321`. | -| `user` | User data | variable | JSON string | max 1024 B | The user data is provided in the JSON format. This parameter is optional and depends on device manufacturer's purpose. It is provided as a CBOR map type from persistent storage and should be parsed in the user application. This data is not used by the Matter stack. To learn how to work with user data, see [How to set user data](#how-to-set-user-data) section. | +| Key name | Full name | Length | Format | Conformance | Description | +| :------------------: | :----------------------------------: | :------------------: | :----------: | :---------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| `version` | factory data version | 2 B | uint16 | mandatory | A version of the current factory data set. It cannot be changed by a user and it must be coherent with current version of the Factory Data Provider on device side. | +| `sn` | serial number | <1, 32> B | ASCII string | mandatory | A serial number parameter defines an unique number of manufactured device. The maximum length of the serial number is 32 characters. | +| `vendor_id` | vendor ID | 2 B | uint16 | mandatory | A CSA-assigned ID for the organization responsible for producing the device. | +| `product_id` | product ID | 2 B | uint16 | mandatory | A unique ID assigned by the device vendor to identify the product. It defaults to a CSA-assigned ID that designates a non-production or test product. | +| `vendor_name` | vendor name | <1, 32> B | ASCII string | mandatory | A human-readable vendor name that provides a simple string containing identification of device's vendor for the application and Matter stack purposes. | +| `product_name` | product name | <1, 32> B | ASCII string | mandatory | A human-readable product name that provides a simple string containing identification of the product for the application and the Matter stack purposes. | +| `date` | manufacturing date | <8, 10> B | ISO 8601 | mandatory | A manufacturing date specifies the date that the device was manufactured. The date format used is ISO 8601, for example `YYYY-MM-DD`. | +| `hw_ver` | hardware version | 2 B | uint16 | mandatory | A hardware version number that specifies the version number of the hardware of the device. The value meaning and the versioning scheme is defined by the vendor. | +| `hw_ver_str` | hardware version string | <1, 64> B | uint16 | mandatory | A hardware version string parameter that specifies the version of the hardware of the device as a more user-friendly value than that presented by the hardware version integer value. The value meaning and the versioning scheme is defined by the vendor. | +| `rd_uid` | rotating device ID unique ID | <16, 32> B | byte string | mandatory | The unique ID for rotating device ID, which consists of a randomly-generated 128-bit (or longer) octet string. This parameter should be protected against reading or writing over-the-air after initial introduction into the device, and stay fixed during the lifetime of the device. | +| `dac_cert` | (DAC) Device Attestation Certificate | <1, 602> B | byte string | mandatory | The Device Attestation Certificate (DAC) and the corresponding private key are unique to each Matter device. The DAC is used for the Device Attestation process and to perform commissioning into a fabric. The DAC is a DER-encoded X.509v3-compliant certificate, as defined in RFC 5280. | +| `dac_key` | DAC private key | 68 B | byte string | mandatory | The private key associated with the Device Attestation Certificate (DAC). This key should be encrypted and maximum security should be guaranteed while generating and providing it to factory data. | +| `pai_cert` | Product Attestation Intermediate | <1, 602> B | byte string | mandatory | An intermediate certificate is an X.509 certificate, which has been signed by the root certificate. The last intermediate certificate in a chain is used to sign the leaf (the Matter device) certificate. The PAI is a DER-encoded X.509v3-compliant certificate as defined in RFC 5280. | | +| `spake2_it` | SPAKE2+ iteration counter | 4 B | uint32 | mandatory | A SPAKE2+ iteration counter is the amount of PBKDF2 (a key derivation function) interactions in a cryptographic process used during SPAKE2+ Verifier generation. | +| `spake2_salt` | SPAKE2+ salt | <32, 64> B | byte string | mandatory | The SPAKE2+ salt is a random piece of data, at least 32 byte long. It is used as an additional input to a one-way function that performs the cryptographic operations. A new salt should be randomly generated for each password. | +| `spake2_verifier` | SPAKE2+ verifier | 97 B | byte string | mandatory | The SPAKE2+ verifier generated using SPAKE2+ salt, iteration counter, and passcode. | +| `discriminator` | Discriminator | 2 B | uint16 | mandatory | A 12-bit value matching the field of the same name in the setup code. The discriminator is used during the discovery process. | +| `passcode` | SPAKE passcode | 4 B | uint32 | optional | A pairing passcode is a 27-bit unsigned integer which serves as a proof of possession during the commissioning. Its value must be restricted to the values from `0x0000001` to `0x5F5E0FE` (`00000001` to `99999998` in decimal), excluding the following invalid passcode values: `00000000`, `11111111`, `22222222`, `33333333`, `44444444`, `55555555`, `66666666`, `77777777`, `88888888`, `99999999`, `12345678`, `87654321`. | +| `product_appearance` | Product visible appearance | 2 B | CBOR map | optional | The appearance field is a structure that describes the visible appearance of the product. This field is provided in a CBOR map and consists of two attributes: `finish` (1 B), `primary_color` (1 B). See the [Appearance field description](#appearance-field-description) to learn how to set all attributes. | +| `user` | User data | variable, max 1024 B | CBOR map | optional | The user data is provided in the JSON format. This parameter is optional and depends on the device manufacturer's purpose. It is provided as a CBOR map type from persistent storage and should be parsed in the user application. This data is not used by the Matter stack. To learn how to work with user data, see the [How to set user data](#how-to-set-user-data) section. | ### Factory data format @@ -131,10 +134,10 @@ All parameters of the factory data set are either mandatory or optional: In the factory data set, the following formats are used: -- uint16 and uint32 -- These are the numeric formats representing, - respectively, two-bytes length unsigned integer and four-bytes length - unsigned integer. This value is stored in a HEX file in the big-endian - order. +- uint8, uint16, and uint32 -- These are the numeric formats representing, + respectively, one-byte length unsigned integer, two-bytes length unsigned + integer, and four-bytes length unsigned integer. This value is stored in a + HEX file in the big-endian order. - Byte string - This parameter represents the sequence of integers between `0` and `255`(inclusive), without any encoding. Because the JSON format does not allow to use of byte strings, the `hex:` prefix is added to a parameter, and @@ -150,6 +153,37 @@ In the factory data set, the following formats are used: - All certificates stored in factory data are provided in the [X.509](https://www.itu.int/rec/T-REC-X.509-201910-I/en) format. +#### Appearance field description + +The `appearance` field in the factory data set describes the device's visible +appearance. + +- `finish` - A string name that indicates the visible exterior finish of the + product. It refers to the `ProductFinishEnum` enum, and currently, you can + choose one of the following names: + +| Name | Enum value | +| :--------: | :--------: | +| `matte` | 0 | +| `satin` | 1 | +| `polished` | 2 | +| `rugged` | 3 | +| `fabric` | 4 | +| `other` | 255 | + +- `primary_color` - A string name that represents the RGB color space of the + device's case color, which is the most representative. It refers to the + `ColorEnum` enum, and currently, you can choose one of the following names: + +(Enum value) color name (`RGB value`) + +| (0) $$\color{black} \color{black}{black}$$ (`#000000`) | (1) $$\color{#000080}{navy}$$ (`#000080`) | (2) $$\color{#008000}{green}$$ (`#008000`) | (3) $$\color{#008080}{teal}$$ (`#008080`) | (4) $$\color{#800080}{maroon}$$ (`#800080`) | +| ------------------------------------------------------ | -------------------------------------------- | --------------------------------------------- | -------------------------------------------- | ------------------------------------------------------- | +| (5) $$\color{#800080}{purple}$$ (`#800080`) | (6) $$\color{#808000}{olive}$$ (`#800080`) | (7) $$\color{#808080}{gray}$$ (`#800080`) | (8) $$\color{blue}{blue}$$ (`#0000FF`) | (9) $$\color{lime}{lime}$$ (`#00FF00`) | +| (10) $$\color{aqua}{aqua}$$ (`#00FFFF`) | (11) $$\color{red}{red}$$ (`#FF0000`) | (12) $$\color{fuchsia}{fuchsia}$$ (`#FF00FF`) | (13) $$\color{yellow}{yellow}$$ (`#FFFF00`) | (14) $$\color{white} \color{white}{white}$$ (`#800080`) | +| (15) $$\color{#727472}{nickel}$$ (`#727472`) | (16) $$\color{#a8a9ad}{chrome}$$ (`#a8a9ad`) | (17) $$\color{#E1C16E}{brass}$$ (`#E1C16E`) | (18) $$\color{#B87333}{copper}$$ (`#B87333`) | (19) $$\color{#C0C0C0}{silver}$$ (`#C0C0C0`) | +| (20) $$\color{gold}{gold}$$ (`#FFD700`) | +
## Enabling factory data support @@ -287,6 +321,13 @@ To use this script, complete the following steps: --overwrite ``` + i. (optional) Add the appearance of the product: + + ``` + --product_finish + --product_color + ``` + 4. Run the script using the prepared list of arguments: ``` @@ -314,7 +355,9 @@ $ python scripts/tools/nrfconnect/generate_nrfconnect_chip_factory_data.py \ --discriminator 0xF00 \ --generate_rd_uid \ --passcode 20202021 \ ---out "build.json" \ +--product_finish "matte" \ +--product_color "black" \ +--out "build.json"' \ --schema "scripts/tools/nrfconnect/nrfconnect_factory_data.schema" ``` diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter index e57aaf1f464ec4..9d76c360803f43 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter @@ -2238,6 +2238,53 @@ server cluster BooleanState = 69 { readonly attribute int16u clusterRevision = 65533; } +/** Allows servers to ensure that listed clients are notified when a server is available for communication. */ +server cluster IcdManagement = 70 { + bitmap ICDManagementFeature : BITMAP32 { + kCheckInProtocolSupport = 0x1; + } + + fabric_scoped struct MonitoringRegistrationStruct { + fabric_sensitive node_id checkInNodeID = 1; + fabric_sensitive int64u monitoredSubject = 2; + fabric_sensitive octet_string<16> key = 3; + fabric_idx fabricIndex = 254; + } + + readonly attribute int32u idleModeInterval = 0; + readonly attribute int32u activeModeInterval = 1; + readonly attribute int16u activeModeThreshold = 2; + readonly attribute access(read: administer) MonitoringRegistrationStruct registeredClients[] = 3; + readonly attribute access(read: administer) int32u ICDCounter = 4; + readonly attribute int16u clientsSupportedPerFabric = 5; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct RegisterClientRequest { + node_id checkInNodeID = 0; + INT64U monitoredSubject = 1; + OCTET_STRING<16> key = 2; + optional OCTET_STRING<16> verificationKey = 3; + } + + request struct UnregisterClientRequest { + node_id checkInNodeID = 0; + optional OCTET_STRING<16> key = 1; + } + + response struct RegisterClientResponse = 1 { + INT32U ICDCounter = 0; + } + + fabric command access(invoke: manage) RegisterClient(RegisterClientRequest): RegisterClientResponse = 0; + fabric command access(invoke: manage) UnregisterClient(UnregisterClientRequest): DefaultSuccess = 2; + command access(invoke: manage) StayActiveRequest(): DefaultSuccess = 3; +} + /** Attributes and commands for selecting a mode from a list of supported options. */ server cluster ModeSelect = 80 { bitmap ModeSelectFeature : BITMAP32 { @@ -4908,6 +4955,21 @@ endpoint 0 { ram attribute clusterRevision default = 1; } + server cluster IcdManagement { + ram attribute idleModeInterval default = 500; + ram attribute activeModeInterval default = 300; + ram attribute activeModeThreshold default = 300; + callback attribute registeredClients; + ram attribute ICDCounter default = 0; + ram attribute clientsSupportedPerFabric default = 1; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute eventList; + callback attribute attributeList; + ram attribute featureMap default = 1; + ram attribute clusterRevision default = 1; + } + server cluster RelativeHumidityMeasurement { ram attribute measuredValue; ram attribute minMeasuredValue default = 0; diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap b/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap index 55a6cb9995e1e1..518a2fedd0f0a6 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.zap @@ -16,12 +16,6 @@ } ], "package": [ - { - "pathRelativity": "relativeToZap", - "path": "../../../src/app/zap-templates/app-templates.json", - "type": "gen-templates-json", - "version": "chip-v1" - }, { "pathRelativity": "relativeToZap", "path": "../../../src/app/zap-templates/zcl/zcl-with-test-extensions.json", @@ -29,6 +23,12 @@ "category": "matter", "version": 1, "description": "Matter SDK ZCL data with some extensions" + }, + { + "pathRelativity": "relativeToZap", + "path": "../../../src/app/zap-templates/app-templates.json", + "type": "gen-templates-json", + "version": "chip-v1" } ], "endpointTypes": [ @@ -6256,6 +6256,286 @@ } ] }, + { + "name": "ICD Management", + "code": 70, + "mfgCode": null, + "define": "ICD_MANAGEMENT_CLUSTER", + "side": "client", + "enabled": 0, + "commands": [ + { + "name": "RegisterClient", + "code": 0, + "mfgCode": null, + "source": "client", + "incoming": 1, + "outgoing": 0 + }, + { + "name": "UnregisterClient", + "code": 2, + "mfgCode": null, + "source": "client", + "incoming": 1, + "outgoing": 0 + }, + { + "name": "StayActiveRequest", + "code": 3, + "mfgCode": null, + "source": "client", + "incoming": 1, + "outgoing": 0 + } + ], + "attributes": [ + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "client", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "client", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "ICD Management", + "code": 70, + "mfgCode": null, + "define": "ICD_MANAGEMENT_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "RegisterClientResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "incoming": 1, + "outgoing": 1 + } + ], + "attributes": [ + { + "name": "IdleModeInterval", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "500", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveModeInterval", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "300", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveModeThreshold", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "300", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "RegisteredClients", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ICDCounter", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientsSupportedPerFabric", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "EventList", + "code": 65530, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, { "name": "Door Lock", "code": 257, diff --git a/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp b/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp index 8aff2a6f268bd3..cd16efd4a3f054 100644 --- a/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp +++ b/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp @@ -17,17 +17,17 @@ #include "binding-handler.h" -#include "app-common/zap-generated/ids/Clusters.h" -#include "app-common/zap-generated/ids/Commands.h" -#include "app/CommandSender.h" -#include "app/clusters/bindings/BindingManager.h" -#include "app/server/Server.h" -#include "controller/InvokeInteraction.h" -#include "lib/core/CHIPError.h" -#include "platform/CHIPDeviceLayer.h" +#include +#include +#include +#include +#include +#include +#include +#include #if defined(ENABLE_CHIP_SHELL) -#include "lib/shell/Engine.h" +#include // nogncheck using chip::Shell::Engine; using chip::Shell::shell_command_t; diff --git a/examples/all-clusters-app/ameba/main/CHIPDeviceManager.cpp b/examples/all-clusters-app/ameba/main/CHIPDeviceManager.cpp index d0db78341501a5..c9722c3e6fb8b2 100644 --- a/examples/all-clusters-app/ameba/main/CHIPDeviceManager.cpp +++ b/examples/all-clusters-app/ameba/main/CHIPDeviceManager.cpp @@ -68,17 +68,14 @@ CHIP_ERROR CHIPDeviceManager::Init(CHIPDeviceManagerCallbacks * cb) SuccessOrExit(err); err = mFactoryDataProvider.Init(); - if (err == CHIP_NO_ERROR) + if (err != CHIP_NO_ERROR) { - SetCommissionableDataProvider(&mFactoryDataProvider); - SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider); - SetDeviceInstanceInfoProvider(&mFactoryDataProvider); - } - else - { - ChipLogProgress(DeviceLayer, "Using example DAC provider"); - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); + ChipLogError(DeviceLayer, "Error initializing FactoryData!"); + ChipLogError(DeviceLayer, "Check if you have flashed it correctly!"); } + SetCommissionableDataProvider(&mFactoryDataProvider); + SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider); + SetDeviceInstanceInfoProvider(&mFactoryDataProvider); if (CONFIG_NETWORK_LAYER_BLE) { diff --git a/examples/all-clusters-app/esp32/main/CMakeLists.txt b/examples/all-clusters-app/esp32/main/CMakeLists.txt index c004e3f5dffb42..a2f72015840bae 100644 --- a/examples/all-clusters-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-app/esp32/main/CMakeLists.txt @@ -77,9 +77,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/group-key-mgmt-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/basic-information" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/bindings" - # Disable Client Monitoring cluster until update is done - # https://github.com/project-chip/connectedhomeip/issues/24425 - # "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/client-monitoring-server" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/icd-management-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/diagnostic-logs-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/door-lock-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/occupancy-sensor-server" diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/README.md b/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/README.md deleted file mode 100644 index 6f67dfa903ff0f..00000000000000 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/README.md +++ /dev/null @@ -1,244 +0,0 @@ -# Matter CC1352 CC2652 All-clusters Example Application - -An example application showing the use of [Matter][matter] on the Texas -Instruments CC13XX_26XX family of Wireless MCUs. - ---- - -- [Matter CC1352 CC2652 All Clusters Example Application](#matter-cc1352-cc2652-all-clusters-example-application) - - [Introduction](#introduction) - - [Device UI](#device-ui) - - [Building](#building) - - [Preparation](#preparation) - - [Compilation](#compilation) - - [Programming](#programming) - - [Code Composer Studio](#code-composer-studio) - - [UniFlash](#uniflash) - - [Viewing Logging Output](#viewing-logging-output) - - [Running the Example](#running-the-example) - - [Provisioning](#provisioning) - - [Bluetooth LE Advertising](#bluetooth-le-advertising) - - [Bluetooth LE Rendezvous](#bluetooth-le-rendezvous) - - [TI Support](#ti-support) - ---- - -## Introduction - -![CC1352R1_LAUNCHXL](../../pump-app/cc13x2x7_26x2x7/doc/images/cc1352r1_launchxl.jpg) - -The CC13XX_26XX all clusters example application provides the basis to query and -run commands for all currently implemented Matter clusters. This uses the -open-source Matter implementation and the Texas Instruments SimpleLinkâ„¢ CC13XX -and CC26XX software development kit. - -This example is enabled to build for CC2652R7 devices. - -The all-clusters example is intended to serve both as a means to explore the -workings of Matter, as well as a template for creating real products based on -the Texas Instruments devices. - -## Device UI - -This example application has a simple User Interface to depict the state of the -various Matter clusters and the attribute changes associated with them. The user -LEDs on the LaunchPad are used for the onoff, levelcontrol and identify clusters -to provide a working demonstration of the cluster attribute changes. The Green -LED is used to represent attribute changes to endpoint 1 while the Red LED is -used to represent changes to endpoint 2. - -Short presses (less than 1000ms) of the user buttons are used currently unused -in the all-clusters application, but stubs are provided. - -Long presses (greater than 1000ms) of the user buttons are used for controlling -BLE advertisements and resets. The left button (`BTN-1`) is used to perform a -factory reset of the device. The Right button (`BTN-2`) is used to disable BLE -advertisements (if enabled) or enable advertisements (if disabled). - -## Building - -### Preparation - -Some initial setup is necessary for preparing the build environment. This -section will need to be done when migrating to new versions of the SDK. This -guide assumes that the environment is linux based, and recommends Ubuntu 20.04. - -- Download and install [SysConfig][sysconfig] ([recommended - version][sysconfig_recommended]). This can be done simply with the following - commands. - - ``` - $ cd ~ - $ wget https://software-dl.ti.com/ccs/esd/sysconfig/sysconfig-1.11.0_2225-setup.run - $ chmod +x sysconfig-1.11.0_2225-setup.run - $ ./sysconfig-1.11.0_2225-setup.run - ``` - -- Run the bootstrap script to setup the build environment. - - ``` - $ cd ~/connectedhomeip - $ source ./scripts/bootstrap.sh - - ``` - -### Compilation - -It is necessary to activate the environment in every new shell. Then run GN and -Ninja to build the executable. - -- Activate the build environment with the repository activate script. - - ``` - $ cd ~/connectedhomeip - $ source ./scripts/activate.sh - - ``` - -- Run the build to produce a default executable. By default on Linux both the - TI SimpleLink SDK and Sysconfig are located in a `ti` folder in the user's - home directory, and you must provide the absolute path to them. For example - `/home/username/ti/sysconfig_1.11.0`. On Windows the default directory is - `C:\ti`. Take note of this install path, as it will be used in the next - step. - - ``` - $ cd ~/connectedhomeip/examples/all-clusters-minimal-app/cc13x2x7_26x2x7 - $ gn gen out/debug --args="ti_sysconfig_root=\"$HOME/ti/sysconfig_1.11.0\"" - $ ninja -C out/debug - - ``` - -## Programming - -Loading the built image onto a LaunchPad is supported through two methods; -Uniflash and Code Composer Studio (CCS). UniFlash can be used to load the image. -Code Composer Studio can be used to load the image and debug the source code. - -### Code Composer Studio - -Programming with CCS will allow for a full debug environment within the IDE. -This is accomplished by creating a target connection to the XDS110 debugger and -starting a project-less debug session. The CCS IDE will attempt to find the -source files on the local machine based on the debug information embedded within -the ELF. CCS may prompt you to find the source code if the image was built on -another machine or the source code is located in a different location than is -recorded within the ELF. - -Download and install [Code Composer Studio][ccs]. - -First open CCS and create a new workspace. - -Create a target connection (sometimes called the CCXML) for your target SoC and -debugger as described in the [Manual Method][ccs_manual_method] section of the -CCS User's Guide. - -Next initiate a project-less debug session as described in the [Manual -Launch][ccs_manual_launch] section of the CCS User's Guide. - -CCS should switch to the debug view described in the [After -Launch][ccs_after_launch] section of the User's Guide. The SoC core will likely -be disconnected and symbols will not be loaded. Connect to the core as described -in the [Debug View][ccs_debug_view] section of the User's Guide. Once the core -is connected, use the `Load` button on the toolbar to load the ELF image. - -Note that the default configuration of the CCXML uses 2-wire cJTAG instead of -the full 4-wire JTAG connection to match the default jumper configuration of the -LaunchPad. - -### UniFlash - -Uniflash is Texas Instrument's uniform programming tool for embedded processors. -This will allow you to erase, flash, and inspect the SoC without setting up a -debugging environment. - -Download and install [UniFlash][uniflash]. - -First open UniFlash. Debug probes connected to the computer will usually be -displayed under the Detected Devices due to the automatic device detection -feature. If your device does not show up in this view it my be disconnected, or -you may have to create a New Configuration. If you already have a CCXML for your -SoC and debug connection you can use that in the section at the bottom. Once -your device is selected, click the `Start` button within the section to launch -the session. - -Select the ELF image to load on the device with the `Browse` button. This file -is placed in the `out/debug` folder by this guide and ends with the `*.out` file -extension. - -Finally click the `Load Image` button to load the executable image onto the -device. You should be able to see the log output over the XDS110 User UART. - -Note that programming the device through JTAG sets the Halt-in-Boot flag and may -cause issues when performing a software reset. This flag can be reset by -power-cycling the LaunchPad. - -## Viewing Logging Output - -By default the log output will be sent to the Application/User UART. Open a -terminal emulator to that port to see the output with the following options: - -| Parameter | Value | -| ------------ | -------- | -| Speed (baud) | `115200` | -| Data bits | `8` | -| Stop bits | `1` | -| Parity | `None` | -| Flow control | `None` | - -## Running the Example - -Once a device has been flashed with this example, it can now join and operate in -an existing Thread network. The following sections assume that a Thread network -is already active, and has at least one [OpenThread Border -Router][ot_border_router_setup]. - -For insight into what other components are needed to run this example, please -refer to our [Matter Getting Started Guide][matter-e2e-faq]. - -### Provisioning - -Interacting with the application begins by enabling BLE advertisements and then -pairing the device into a Thread network. - -#### Bluetooth LE Advertising - -To provision this example onto a Thread network, the device must be discoverable -over Bluetooth LE. BLE advertising is started by long pressing the right button -(greater than 1000ms), labeled `BTN-2` on the silkscreen. Once the device is -fully provisioned, BLE advertising will stop. - -#### Bluetooth LE Rendezvous - -Pairing this application with `ble-thread` can be done with any of the enabled -[CHIP Controller](../../../src/controller/README.md) applications. Use the -information printed on the console to aide in pairing the device. The controller -application can also be used to control the example app with the cluster -commands. - -## TI Support - -For technical support, please consider creating a post on TI's [E2E forum][e2e]. -Additionally, we welcome any feedback. - -[matter]: https://github.com/project-chip/connectedhomeip -[ccs]: https://www.ti.com/tool/CCSTUDIO -[ccs_after_launch]: - https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#after-launch -[ccs_debug_view]: - https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#debug-view -[ccs_manual_launch]: - https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#manual-launch -[ccs_manual_method]: - https://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_debug-main.html?configuration#manual-method -[cc1352r1_launchxl]: https://www.ti.com/tool/LAUNCHXL-CC1352R1 -[e2e]: https://e2e.ti.com/support/wireless-connectivity/zigbee-and-thread -[matter-e2e-faq]: - https://e2e.ti.com/support/wireless-connectivity/zigbee-thread-group/zigbee-and-thread/f/zigbee-thread-forum/1082428/faq-cc2652r7-matter----getting-started-guide -[sysconfig]: https://www.ti.com/tool/SYSCONFIG -[sysconfig_recommended]: - https://software-dl.ti.com/ccs/esd/sysconfig/sysconfig-1.11.0_2225-setup.run -[ti_thread_dnd]: - https://www.ti.com/wireless-connectivity/thread/design-development.html -[ot_border_router_setup]: https://openthread.io/guides/border-router/build -[uniflash]: https://www.ti.com/tool/download/UNIFLASH diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ClusterManager.cpp b/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ClusterManager.cpp deleted file mode 100644 index b55ffa374e9788..00000000000000 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ClusterManager.cpp +++ /dev/null @@ -1,177 +0,0 @@ - -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "ClusterManager.h" -#include "Globals.h" -#include -#include -#include -#include -#include - -#ifdef AUTO_PRINT_METRICS -#include -#endif - -using namespace ::chip; -using namespace ::chip::Inet; -using namespace ::chip::System; -using namespace ::chip::DeviceLayer; - -constexpr uint32_t kIdentifyTimerDelayMS = 250; -constexpr uint32_t kIdentifyTimerDelayPerSec = 4; -ClusterManager ClusterManager::sCluster; - -#define ENDPOINT_ID_0 (0) -#define ENDPOINT_ID_1 (1) -#define ENDPOINT_ID_2 (2) - -void OnIdentifyTriggerEffect(Identify * identify) -{ - switch (identify->mCurrentEffectIdentifier) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - PLAT_LOG("EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - PLAT_LOG("EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - PLAT_LOG("EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - PLAT_LOG("EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - break; - default: - PLAT_LOG("No identifier effect"); - break; - } - return; -} - -Identify gIdentify0 = { - chip::EndpointId{ 0 }, - [](Identify *) { PLAT_LOG("onIdentifyStart"); }, - [](Identify *) { PLAT_LOG("onIdentifyStop"); }, - EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, - OnIdentifyTriggerEffect, -}; - -Identify gIdentify1 = { - chip::EndpointId{ 1 }, - [](Identify *) { PLAT_LOG("onIdentifyStart"); }, - [](Identify *) { PLAT_LOG("onIdentifyStop"); }, - EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, - OnIdentifyTriggerEffect, -}; - -void ClusterManager::OnOnOffPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) -{ - VerifyOrExit(attributeId == app::Clusters::OnOff::Attributes::OnOff::Id, - PLAT_LOG("Unhandled Attribute ID: '0x%04x", attributeId)); - VerifyOrExit(endpointId == ENDPOINT_ID_1 || endpointId == ENDPOINT_ID_2, - PLAT_LOG("Unexpected EndPoint ID: `0x%02x'", endpointId)); - - // At this point we can assume that value points to a bool value. - mEndpointOnOffState[endpointId - 1] = *value; - endpointId == ENDPOINT_ID_1 ? LED_write(sAppGreenHandle, *value) : LED_write(sAppRedHandle, *value); - -exit: - return; -} - -void ClusterManager::OnLevelControlAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) -{ - bool onOffState = mEndpointOnOffState[endpointId - 1]; - uint8_t brightness = onOffState ? *value : 0; - - VerifyOrExit(brightness > 0, PLAT_LOG("Brightness set to 0, ignoring")); - VerifyOrExit(attributeId == app::Clusters::LevelControl::Attributes::CurrentLevel::Id, - PLAT_LOG("Unhandled Attribute ID: '0x%04x", attributeId)); - VerifyOrExit(endpointId == ENDPOINT_ID_1 || endpointId == ENDPOINT_ID_2, - PLAT_LOG("Unexpected EndPoint ID: `0x%02x'", endpointId)); - - if (brightness > LED_BRIGHTNESS_MAX) - { - brightness = LED_BRIGHTNESS_MAX; - } - - endpointId == ENDPOINT_ID_1 ? LED_setOn(sAppGreenHandle, brightness) : LED_setOn(sAppRedHandle, brightness); - -exit: - return; -} - -void ClusterManager::OnColorControlAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) -{ - using namespace app::Clusters::ColorControl::Attributes; - - VerifyOrExit(attributeId == CurrentHue::Id || attributeId == CurrentSaturation::Id, - PLAT_LOG("Unhandled AttributeId ID: '0x%04x", attributeId)); - VerifyOrExit(endpointId == ENDPOINT_ID_1 || endpointId == ENDPOINT_ID_2, - PLAT_LOG("Unexpected EndPoint ID: `0x%02x'", endpointId)); - - if (endpointId == ENDPOINT_ID_1) - { - uint8_t hue, saturation; - if (attributeId == CurrentHue::Id) - { - hue = *value; - /* Read Current Saturation value when Attribute change callback for HUE Attribute */ - CurrentSaturation::Get(endpointId, &saturation); - } - else - { - saturation = *value; - /* Read Current Hue value when Attribute change callback for SATURATION Attribute */ - CurrentHue::Get(endpointId, &hue); - } - PLAT_LOG("Color Control triggered: Hue: %d Saturation: %d", hue, saturation); - } -exit: - return; -} - -void ClusterManager::OnIdentifyPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint16_t size, - uint8_t * value) -{ - if (attributeId == app::Clusters::Identify::Attributes::IdentifyTime::Id && size == 2) - { - uint16_t identifyTime; - memcpy(&identifyTime, value, size); - if (identifyTime) - { - // Currently we have no separate indicator LEDs on each endpoints. - // We are using LED1 for endpoint 0,1 and LED2 for endpoint 2 - if (endpointId == ENDPOINT_ID_2) - { - LED_startBlinking(sAppGreenHandle, kIdentifyTimerDelayMS, identifyTime * kIdentifyTimerDelayPerSec); - } - else - { - LED_startBlinking(sAppRedHandle, kIdentifyTimerDelayMS, identifyTime * kIdentifyTimerDelayPerSec); - } - } - else - { - bool onOffState; - endpointId == ENDPOINT_ID_0 ? onOffState = mEndpointOnOffState[0] : onOffState = mEndpointOnOffState[endpointId - 1]; - endpointId == ENDPOINT_ID_2 ? LED_write(sAppRedHandle, onOffState) : LED_write(sAppGreenHandle, onOffState); - } - } -} diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt index add408b7af9693..84a14de4714e13 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt @@ -61,7 +61,7 @@ object ChipClient { if (!this::androidPlatform.isInitialized && context != null) { //force ChipDeviceController load jni ChipDeviceController.loadJni() - androidPlatform = AndroidChipPlatform(AndroidBleManager(), PreferencesKeyValueStoreManager(context), PreferencesConfigurationManager(context), NsdManagerServiceResolver(context), NsdManagerServiceBrowser(context), ChipMdnsCallbackImpl(), DiagnosticDataProviderImpl(context)) + androidPlatform = AndroidChipPlatform(AndroidBleManager(context), PreferencesKeyValueStoreManager(context), PreferencesConfigurationManager(context), NsdManagerServiceResolver(context), NsdManagerServiceBrowser(context), ChipMdnsCallbackImpl(), DiagnosticDataProviderImpl(context)) } return androidPlatform diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt index c665adaeb97b47..4ceb3d2164147b 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/WildcardFragment.kt @@ -450,7 +450,7 @@ class WildcardFragment : Fragment() { private suspend fun readCurrentFabricIndex() : UInt { val context = requireContext() - val endpointId = 0L + val endpointId = 0 val clusterId = 62L // OperationalCredentials val attributeId = 5L // CurrentFabricIndex val deviceId = addressUpdateFragment.deviceId diff --git a/examples/build_overrides/asr.gni b/examples/build_overrides/asr.gni new file mode 100644 index 00000000000000..d012a516b2102f --- /dev/null +++ b/examples/build_overrides/asr.gni @@ -0,0 +1,23 @@ +# 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. + +declare_args() { + asr_ic_family = "asr582x" + + # Root directory for ASR SDK build files. + asr_sdk_build_root = "//third_party/connectedhomeip/third_party/asr/asr582x" + + # Root directory for ASR toolchain. + asr_toolchain_root = "" +} diff --git a/examples/chef/efr32/include/AppConfig.h b/examples/chef/efr32/include/AppConfig.h index a936fe1d8abaeb..e278e9439a437f 100644 --- a/examples/chef/efr32/include/AppConfig.h +++ b/examples/chef/efr32/include/AppConfig.h @@ -18,6 +18,7 @@ */ #pragma once +#include "silabs_utils.h" // ---- Lighting Example App Config ---- @@ -26,21 +27,3 @@ // Time it takes in ms for the simulated actuator to move from one // state to another. #define ACTUATOR_MOVEMENT_PERIOS_MS 10 - -// EFR Logging -#ifdef __cplusplus -extern "C" { -#endif - -void silabsInitLog(void); - -void efr32Log(const char * aFormat, ...); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); -void appError(int err); - -#ifdef __cplusplus -} - -#include -void appError(CHIP_ERROR error); -#endif diff --git a/examples/chef/efr32/src/AppTask.cpp b/examples/chef/efr32/src/AppTask.cpp index ee2e2921202fc6..d166243033cdd6 100644 --- a/examples/chef/efr32/src/AppTask.cpp +++ b/examples/chef/efr32/src/AppTask.cpp @@ -125,9 +125,7 @@ AppTask AppTask::sAppTask; CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); -#endif err = BaseApplication::Init(&gIdentify); if (err != CHIP_NO_ERROR) @@ -169,7 +167,6 @@ void AppTask::AppTaskMain(void * pvParameter) } } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) { AppEvent button_event = {}; @@ -182,4 +179,3 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) sAppTask.PostEvent(&button_event); } } -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT diff --git a/examples/chip-tool/templates/logging/DataModelLogger-src.zapt b/examples/chip-tool/templates/logging/DataModelLogger-src.zapt index d400874cf67ffb..167021f49577d2 100644 --- a/examples/chip-tool/templates/logging/DataModelLogger-src.zapt +++ b/examples/chip-tool/templates/logging/DataModelLogger-src.zapt @@ -40,7 +40,7 @@ CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, const {{ {{/zcl_events}} {{/zcl_clusters}} -{{#all_user_clusters side='client'}} +{{#zcl_clusters}} {{#zcl_commands_source_server}} CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, const {{asUpperCamelCase parent.name}}::Commands::{{asUpperCamelCase name}}::DecodableType & value) { @@ -52,7 +52,7 @@ CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, const {{ return CHIP_NO_ERROR; } {{/zcl_commands_source_server}} -{{/all_user_clusters}} +{{/zcl_clusters}} CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data) { @@ -61,7 +61,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP switch (path.mClusterId) { -{{#all_user_clusters side='client'}} +{{#zcl_clusters}} {{#zcl_attributes_server}} {{#first}} case {{asUpperCamelCase parent.name}}::Id: @@ -81,7 +81,7 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP } {{/last}} {{/zcl_attributes_server}} -{{/all_user_clusters}} +{{/zcl_clusters}} default: break; } @@ -96,7 +96,7 @@ CHIP_ERROR DataModelLogger::LogCommand(const chip::app::ConcreteCommandPath & pa switch (path.mClusterId) { -{{#all_user_clusters side='client'}} +{{#zcl_clusters}} {{#zcl_commands_source_server}} {{#first}} case {{asUpperCamelCase parent.name}}::Id: @@ -116,7 +116,7 @@ CHIP_ERROR DataModelLogger::LogCommand(const chip::app::ConcreteCommandPath & pa } {{/last}} {{/zcl_commands_source_server}} -{{/all_user_clusters}} +{{/zcl_clusters}} default: break; } @@ -152,7 +152,7 @@ CHIP_ERROR DataModelLogger::LogEvent(const chip::app::EventHeader & header, chip switch (header.mPath.mClusterId) { -{{#all_user_clusters side='client'}} +{{#zcl_clusters}} {{#zcl_events}} {{#first}} case {{asUpperCamelCase parent.name}}::Id: @@ -172,7 +172,7 @@ CHIP_ERROR DataModelLogger::LogEvent(const chip::app::EventHeader & header, chip } {{/last}} {{/zcl_events}} -{{/all_user_clusters}} +{{/zcl_clusters}} default: break; } diff --git a/examples/chip-tool/templates/logging/DataModelLogger.zapt b/examples/chip-tool/templates/logging/DataModelLogger.zapt index 222ab67dee0364..befe9d4210ce07 100644 --- a/examples/chip-tool/templates/logging/DataModelLogger.zapt +++ b/examples/chip-tool/templates/logging/DataModelLogger.zapt @@ -23,8 +23,8 @@ static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::C {{/zcl_events}} {{/zcl_clusters}} -{{#all_user_clusters side='client'}} +{{#zcl_clusters}} {{#zcl_commands_source_server}} static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::Clusters::{{asUpperCamelCase parent.name}}::Commands::{{asUpperCamelCase name}}::DecodableType & value); {{/zcl_commands_source_server}} -{{/all_user_clusters}} +{{/zcl_clusters}} diff --git a/examples/contact-sensor-app/contact-sensor-common/BUILD.gn b/examples/contact-sensor-app/contact-sensor-common/BUILD.gn index ddae4d2d0defc5..d95af40a21a3ff 100755 --- a/examples/contact-sensor-app/contact-sensor-common/BUILD.gn +++ b/examples/contact-sensor-app/contact-sensor-common/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("contact-sensor-common") { diff --git a/examples/dynamic-bridge-app/linux/include/data-model/DataModel.h b/examples/dynamic-bridge-app/linux/include/data-model/DataModel.h index cba8d3c9907129..053cd785aac472 100644 --- a/examples/dynamic-bridge-app/linux/include/data-model/DataModel.h +++ b/examples/dynamic-bridge-app/linux/include/data-model/DataModel.h @@ -201,7 +201,7 @@ CHIP_ERROR Encode(const ConcreteReadAttributePath & aPath, AttributeValueEncoder // CONFIG_BUILD_FOR_HOST_UNIT_TEST is true, so we can test how the other side // responds. #if !CONFIG_BUILD_FOR_HOST_UNIT_TEST - if (!x.HasValidValue()) + if (!x.ExistingValueInEncodableRange()) { return CHIP_IM_GLOBAL_STATUS(ConstraintError); } @@ -313,7 +313,7 @@ CHIP_ERROR Decode(const ConcreteDataAttributePath & aPath, AttributeValueDecoder // We have a value; decode it. ReturnErrorOnFailure(Decode(aPath, aDecoder, x.SetNonNull())); - if (!x.HasValidValue()) + if (!x.ExistingValueInEncodableRange()) { return CHIP_IM_GLOBAL_STATUS(ConstraintError); } diff --git a/examples/java-matter-controller/BUILD.gn b/examples/java-matter-controller/BUILD.gn index cdb67f1b8ed41d..92ae40df938568 100644 --- a/examples/java-matter-controller/BUILD.gn +++ b/examples/java-matter-controller/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Project CHIP Authors +# 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. @@ -38,6 +38,7 @@ kotlin_binary("java-matter-controller") { output_name = "java-matter-controller" deps = [ ":java", + "${chip_root}/src/controller/java:json_to_tlv_to_json_test", "${chip_root}/src/controller/java:tlv_read_write_test", "${chip_root}/src/controller/java:tlv_reader_test", "${chip_root}/src/controller/java:tlv_writer_test", diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Argument.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Argument.kt index 76e633a82a144a..77aa91a89aa31d 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Argument.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/common/Argument.kt @@ -141,6 +141,23 @@ class Argument { isValidArgument = numLong.toInt() >= minValue && numLong.toInt() <= maxValue } + ArgumentType.STRING -> { + val stringBuffer = this.value as StringBuffer + stringBuffer.append(value) + val str = stringBuffer.toString() + isValidArgument = value == str + } + + ArgumentType.BOOL -> { + val atomicBoolean = this.value as AtomicBoolean + try { + atomicBoolean.set(value.toBoolean()) + isValidArgument = true + } catch (e: Exception) { + isValidArgument = false + } + } + ArgumentType.ADDRESS -> isValidArgument = try { val ipAddress = this.value as IPAddress ipAddress.setAddress(InetAddress.getByName(value)) diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt index 7f2bc51e5ffb4a..4c4d191d83fcb0 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeCommand.kt @@ -22,5 +22,17 @@ import com.matter.controller.commands.common.CredentialsIssuer class PairCodeCommand(controller: ChipDeviceController, credsIssue: CredentialsIssuer?) : PairingCommand(controller, "code", credsIssue, PairingModeType.CODE, PairingNetworkType.NONE) { - override fun runCommand() {} + override fun runCommand() { + currentCommissioner() + .pairDeviceWithCode( + getNodeId(), + getOnboardingPayload(), + getDiscoverOnce(), + getUseOnlyOnNetworkDiscovery(), + null, + getWifiNetworkCredentials(), + ) + currentCommissioner().setCompletionListener(this) + waitCompleteMs(getTimeoutMillis()) + } } \ No newline at end of file diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt index 2cd822e32d467f..1168f7f93e30a2 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeThreadCommand.kt @@ -22,5 +22,17 @@ import com.matter.controller.commands.common.CredentialsIssuer class PairCodeThreadCommand(controller: ChipDeviceController, credsIssue: CredentialsIssuer?) : PairingCommand(controller, "code-thread", credsIssue, PairingModeType.CODE, PairingNetworkType.THREAD) { - override fun runCommand() {} + override fun runCommand() { + currentCommissioner() + .pairDeviceWithCode( + getNodeId(), + getOnboardingPayload(), + getDiscoverOnce(), + getUseOnlyOnNetworkDiscovery(), + null, + getThreadNetworkCredentials(), + ) + currentCommissioner().setCompletionListener(this) + waitCompleteMs(getTimeoutMillis()) + } } \ No newline at end of file diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt index 66f90fd7214cf9..09b639b1c251c1 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairCodeWifiCommand.kt @@ -22,5 +22,17 @@ import com.matter.controller.commands.common.CredentialsIssuer class PairCodeWifiCommand(controller: ChipDeviceController, credsIssue: CredentialsIssuer?) : PairingCommand(controller, "code-wifi", credsIssue, PairingModeType.CODE, PairingNetworkType.WIFI) { - override fun runCommand() {} + override fun runCommand() { + currentCommissioner() + .pairDeviceWithCode( + getNodeId(), + getOnboardingPayload(), + getDiscoverOnce(), + getUseOnlyOnNetworkDiscovery(), + null, + getWifiNetworkCredentials(), + ) + currentCommissioner().setCompletionListener(this) + waitCompleteMs(getTimeoutMillis()) + } } \ No newline at end of file diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImInvokeCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImInvokeCommand.kt index 7eb38a0d4f950a..f509ad32d38732 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImInvokeCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairOnNetworkLongImInvokeCommand.kt @@ -79,7 +79,7 @@ class PairOnNetworkLongImInvokeCommand( tlvWriter.endStructure() val element: InvokeElement = InvokeElement.newInstance( /* endpointId= */ - 0L, CLUSTER_ID_IDENTIFY, IDENTIFY_COMMAND, tlvWriter.getEncoded(), null + 0, CLUSTER_ID_IDENTIFY, IDENTIFY_COMMAND, tlvWriter.getEncoded(), null ) currentCommissioner() diff --git a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt index a6df1b0b450f6a..e2112c7486a9ba 100644 --- a/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt +++ b/examples/java-matter-controller/java/src/com/matter/controller/commands/pairing/PairingCommand.kt @@ -18,6 +18,7 @@ package com.matter.controller.commands.pairing import chip.devicecontroller.ChipDeviceController +import chip.devicecontroller.NetworkCredentials import com.matter.controller.commands.common.CredentialsIssuer import com.matter.controller.commands.common.IPAddress import com.matter.controller.commands.common.MatterCommand @@ -69,8 +70,8 @@ abstract class PairingCommand( PairingModeType.NONE -> {} PairingModeType.CODE, PairingModeType.CODE_PASE_ONLY -> { addArgument("payload", onboardingPayload, null, false) - addArgument("discover-once", discoverOnce, null, false) - addArgument("use-only-onnetwork-discovery", useOnlyOnNetworkDiscovery, null, false) + addArgument("discover-once", discoverOnce, null, true) + addArgument("use-only-onnetwork-discovery", useOnlyOnNetworkDiscovery, null, true) } PairingModeType.ADDRESS_PASE_ONLY -> { @@ -227,6 +228,30 @@ abstract class PairingCommand( return timeoutMillis.get() } + fun getOnboardingPayload(): String { + return onboardingPayload.toString() + } + + fun getWifiNetworkCredentials(): NetworkCredentials { + return NetworkCredentials.forWiFi(NetworkCredentials.WiFiCredentials(ssid.toString(), password.toString())) + } + + fun getThreadNetworkCredentials(): NetworkCredentials { + return NetworkCredentials.forThread(NetworkCredentials.ThreadCredentials(operationalDataset.toString().hexToByteArray())) + } + + private fun String.hexToByteArray(): ByteArray { + return chunked(2).map { byteStr -> byteStr.toUByte(16).toByte() }.toByteArray() + } + + fun getDiscoverOnce(): Boolean { + return discoverOnce.get() + } + + fun getUseOnlyOnNetworkDiscovery(): Boolean { + return useOnlyOnNetworkDiscovery.get() + } + companion object { private val logger = Logger.getLogger(PairingCommand::class.java.name) } diff --git a/examples/light-switch-app/ameba/main/CHIPDeviceManager.cpp b/examples/light-switch-app/ameba/main/CHIPDeviceManager.cpp index d0db78341501a5..c9722c3e6fb8b2 100644 --- a/examples/light-switch-app/ameba/main/CHIPDeviceManager.cpp +++ b/examples/light-switch-app/ameba/main/CHIPDeviceManager.cpp @@ -68,17 +68,14 @@ CHIP_ERROR CHIPDeviceManager::Init(CHIPDeviceManagerCallbacks * cb) SuccessOrExit(err); err = mFactoryDataProvider.Init(); - if (err == CHIP_NO_ERROR) + if (err != CHIP_NO_ERROR) { - SetCommissionableDataProvider(&mFactoryDataProvider); - SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider); - SetDeviceInstanceInfoProvider(&mFactoryDataProvider); - } - else - { - ChipLogProgress(DeviceLayer, "Using example DAC provider"); - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); + ChipLogError(DeviceLayer, "Error initializing FactoryData!"); + ChipLogError(DeviceLayer, "Check if you have flashed it correctly!"); } + SetCommissionableDataProvider(&mFactoryDataProvider); + SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider); + SetDeviceInstanceInfoProvider(&mFactoryDataProvider); if (CONFIG_NETWORK_LAYER_BLE) { diff --git a/examples/light-switch-app/light-switch-common/BUILD.gn b/examples/light-switch-app/light-switch-common/BUILD.gn index 15552d97dcad54..163e841678101a 100644 --- a/examples/light-switch-app/light-switch-common/BUILD.gn +++ b/examples/light-switch-app/light-switch-common/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("light-switch-common") { diff --git a/examples/light-switch-app/silabs/SiWx917/README.md b/examples/light-switch-app/silabs/SiWx917/README.md index 60f387b293bd04..a785640f5ec47f 100644 --- a/examples/light-switch-app/silabs/SiWx917/README.md +++ b/examples/light-switch-app/silabs/SiWx917/README.md @@ -1,6 +1,8 @@ # Matter SiWx917 Light Switch Example -An example showing the use of CHIP on the Silicon Labs SiWx917 SoC device. +An example showing the use of CHIP on the +[Silicon Labs SiWx917](https://www.silabs.com/wireless/wi-fi/siwx917-wireless-socs) +SoC device.
@@ -31,15 +33,17 @@ An example showing the use of CHIP on the Silicon Labs SiWx917 SoC device. ## Introduction -The SiWx917 light switch example provides a baseline demonstration of an on-off -light switch device, built using Matter, the Silicon Labs Gecko SDK, and the -Silicon Labs WiseMCU SDK. It can be controlled by a Chip controller over a Wi-Fi -network. +The [SiWx917](https://www.silabs.com/wireless/wi-fi/siwx917-wireless-socs) light +switch example provides a baseline demonstration of an on-off light switch +device, built using Matter, the Silicon Labs Gecko SDK, and the Silicon Labs +WiseMCU SDK. It can be controlled by a Chip controller over a Wi-Fi network. -The SiWx917 device can be commissioned over Bluetooth Low Energy where the -device and the Chip controller will exchange security information with the -rendezvous procedure. Wi-Fi Network credentials are then provided to the SiWx917 -device which will then join the Wi-Fi network. +The [SiWx917](https://www.silabs.com/wireless/wi-fi/siwx917-wireless-socs) +device can be commissioned over Bluetooth Low Energy where the device and the +Chip controller will exchange security information with the rendezvous +procedure. Wi-Fi Network credentials are then provided to the +[SiWx917](https://www.silabs.com/wireless/wi-fi/siwx917-wireless-socs) device +which will then join the Wi-Fi network. If the LCD is enabled, the LCD on the Silabs WSTK shows a QR Code containing the needed commissioning information for the BLE connection and starting the @@ -90,8 +94,10 @@ Silicon Labs platform. ## Flashing the Application -- Flashing requires the SiWx917 SoC device to be configured in the Ozone - Debugger. +- Flashing requires the + [SiWx917](https://www.silabs.com/wireless/wi-fi/siwx917-wireless-socs) SoC + device to be configured in the Ozone Debugger. + - Once it's configured, it can be run with the Ozone Debugger by loading the .out file. - > For detailed instructions, please refer to @@ -104,10 +110,11 @@ The example application's logging output can be viewed in the Ozone Debugger. ## Running the Complete Example -- For this example to work, it is necessary to have a second SiWx917 device - running the +- For this example to work, it is necessary to have a second + [SiWx917](https://www.silabs.com/wireless/wi-fi/siwx917-wireless-socs) + device running the [lighting app example](https://github.com/project-chip/connectedhomeip/blob/master/examples/lighting-app/silabs/SiWx917/README.md) - commissioned on the same Wi-Fi network + commissioned on the same Wi-Fi network. * You can provision and control the Chip device using the [chip-tool](https://github.com/project-chip/connectedhomeip/blob/master/examples/chip-tool/README.md) diff --git a/examples/light-switch-app/silabs/SiWx917/include/AppConfig.h b/examples/light-switch-app/silabs/SiWx917/include/AppConfig.h index b20cbf8fc20d55..0b6308b9f1eb61 100644 --- a/examples/light-switch-app/silabs/SiWx917/include/AppConfig.h +++ b/examples/light-switch-app/silabs/SiWx917/include/AppConfig.h @@ -19,6 +19,8 @@ #pragma once +#include "silabs_utils.h" + // ---- Lighting Example App Config ---- #define APP_TASK_NAME "Lit" @@ -28,21 +30,3 @@ // Time it takes in ms for the simulated actuator to move from one // state to another. #define ACTUATOR_MOVEMENT_PERIOS_MS 10 - -// EFR Logging -#ifdef __cplusplus -extern "C" { -#endif - -void silabsInitLog(void); - -void efr32Log(const char * aFormat, ...); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); -void appError(int err); - -#ifdef __cplusplus -} - -#include -void appError(CHIP_ERROR error); -#endif diff --git a/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp b/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp index 3cf6d9a034cae7..d76dc9de2526e4 100644 --- a/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp +++ b/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp @@ -69,6 +69,7 @@ constexpr chip::EndpointId kGenericSwitchEndpoint = 2; using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -239,7 +240,7 @@ void AppTask::SwitchActionEventHandler(AppEvent * aEvent) static bool mCurrentButtonState = false; - if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_PRESSED) + if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { mCurrentButtonState = !mCurrentButtonState; LightSwitchMgr::LightSwitchAction action = @@ -252,7 +253,7 @@ void AppTask::SwitchActionEventHandler(AppEvent * aEvent) sAppTask.GetLCD().WriteDemoUI(mCurrentButtonState); #endif } - else if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_RELEASED) + else if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonReleased)) { LightSwitchMgr::GetInstance().GenericSwitchOnShortRelease(); } @@ -268,7 +269,7 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) button_event.Handler = SwitchActionEventHandler; sAppTask.PostEvent(&button_event); } - else if (button == SIWx917_BTN0 && btnAction == SL_SIMPLE_BUTTON_PRESSED) + else if (button == SIWx917_BTN0 && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = BaseApplication::ButtonHandler; sAppTask.PostEvent(&button_event); diff --git a/examples/light-switch-app/silabs/efr32/include/AppConfig.h b/examples/light-switch-app/silabs/efr32/include/AppConfig.h index 6d61bd11840cb6..040aafc6912b25 100644 --- a/examples/light-switch-app/silabs/efr32/include/AppConfig.h +++ b/examples/light-switch-app/silabs/efr32/include/AppConfig.h @@ -19,6 +19,8 @@ #pragma once +#include "silabs_utils.h" + // ---- Lighting Example App Config ---- #define APP_TASK_NAME "Lit" @@ -85,21 +87,3 @@ 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, \ 0xFF, 0x01, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF - -// EFR Logging -#ifdef __cplusplus -extern "C" { -#endif - -void silabsInitLog(void); - -void efr32Log(const char * aFormat, ...); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); -void appError(int err); - -#ifdef __cplusplus -} - -#include -void appError(CHIP_ERROR error); -#endif diff --git a/examples/light-switch-app/silabs/efr32/src/AppTask.cpp b/examples/light-switch-app/silabs/efr32/src/AppTask.cpp index 81ba6afad54c0a..38dea28cc6abd8 100644 --- a/examples/light-switch-app/silabs/efr32/src/AppTask.cpp +++ b/examples/light-switch-app/silabs/efr32/src/AppTask.cpp @@ -68,6 +68,7 @@ constexpr chip::EndpointId kGenericSwitchEndpoint = 2; using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -153,9 +154,7 @@ AppTask AppTask::sAppTask; CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); -#endif #ifdef DISPLAY_ENABLED GetLCD().Init((uint8_t *) "Light Switch"); @@ -229,14 +228,13 @@ void AppTask::OnIdentifyStop(Identify * identify) #endif } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::SwitchActionEventHandler(AppEvent * aEvent) { VerifyOrReturn(aEvent->Type == AppEvent::kEventType_Button); static bool mCurrentButtonState = false; - if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_PRESSED) + if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { mCurrentButtonState = !mCurrentButtonState; LightSwitchMgr::LightSwitchAction action = @@ -249,7 +247,7 @@ void AppTask::SwitchActionEventHandler(AppEvent * aEvent) sAppTask.GetLCD().WriteDemoUI(mCurrentButtonState); #endif } - else if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_RELEASED) + else if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonReleased)) { LightSwitchMgr::GetInstance().GenericSwitchOnShortRelease(); } @@ -272,4 +270,3 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) sAppTask.PostEvent(&button_event); } } -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT diff --git a/examples/lighting-app/ameba/main/CHIPDeviceManager.cpp b/examples/lighting-app/ameba/main/CHIPDeviceManager.cpp index 01931850922b4c..5ec1473adf28cd 100644 --- a/examples/lighting-app/ameba/main/CHIPDeviceManager.cpp +++ b/examples/lighting-app/ameba/main/CHIPDeviceManager.cpp @@ -75,17 +75,14 @@ CHIP_ERROR CHIPDeviceManager::Init(CHIPDeviceManagerCallbacks * cb) SuccessOrExit(err); err = mFactoryDataProvider.Init(); - if (err == CHIP_NO_ERROR) + if (err != CHIP_NO_ERROR) { - SetCommissionableDataProvider(&mFactoryDataProvider); - SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider); - SetDeviceInstanceInfoProvider(&mFactoryDataProvider); - } - else - { - ChipLogProgress(DeviceLayer, "Using example DAC provider"); - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); + ChipLogError(DeviceLayer, "Error initializing FactoryData!"); + ChipLogError(DeviceLayer, "Check if you have flashed it correctly!"); } + SetCommissionableDataProvider(&mFactoryDataProvider); + SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider); + SetDeviceInstanceInfoProvider(&mFactoryDataProvider); if (CONFIG_NETWORK_LAYER_BLE) { diff --git a/examples/lighting-app/asr/.gn b/examples/lighting-app/asr/.gn new file mode 100755 index 00000000000000..8d75f1eafcdb89 --- /dev/null +++ b/examples/lighting-app/asr/.gn @@ -0,0 +1,29 @@ +# 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. + +import("//build_overrides/build.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 = "freertos" + + import("//args.gni") +} diff --git a/examples/lighting-app/asr/BUILD.gn b/examples/lighting-app/asr/BUILD.gn new file mode 100755 index 00000000000000..55b102fb25116f --- /dev/null +++ b/examples/lighting-app/asr/BUILD.gn @@ -0,0 +1,128 @@ +# 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. + +import("//build_overrides/asr.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("${asr_sdk_build_root}/asr_sdk.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/src/lib/lib.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/asr/asr_executable.gni") + +import("cfg.gni") + +assert(current_os == "freertos") + +asr_project_dir = "${chip_root}/examples/lighting-app/asr" +examples_plat_dir = "${chip_root}/examples/platform/asr" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + +asr_sdk_sources("lighting_app_sdk_sources") { + include_dirs = [ + "${chip_root}/src/platform/ASR", + "${asr_project_dir}/include", + "${examples_plat_dir}", + ] + + defines = [ + "ASR_LOG_ENABLED=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + ] + + if (chip_enable_factory_data) { + defines += [ + "CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER=1", + "CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER=1", + ] + } + + if (chip_lwip_ip6_hook) { + defines += [ + "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", + "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", + ] + } + + sources = [ "${asr_project_dir}/include/CHIPProjectConfig.h" ] + + public_configs = [ "${asr_sdk_build_root}:asr_sdk_config" ] +} + +asr_executable("lighting_app") { + include_dirs = [] + defines = [] + output_name = "chip-asr-lighting-example.out" + + sources = [ + "${examples_plat_dir}/CHIPDeviceManager.cpp", + "${examples_plat_dir}/LEDWidget.cpp", + "${examples_plat_dir}/init_Matter.cpp", + "${examples_plat_dir}/init_asrPlatform.cpp", + "${examples_plat_dir}/shell/matter_shell.cpp", + "src/AppTask.cpp", + "src/DeviceCallbacks.cpp", + "src/main.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${examples_plat_dir}/init_OTARequestor.cpp" ] + } + + deps = [ + ":lighting_app_sdk_sources", + "${chip_root}/examples/common/QRCode", + "${chip_root}/examples/lighting-app/lighting-common", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs += [ + "include", + "${examples_plat_dir}", + "${asr_project_dir}/include", + "${chip_root}/src/lib", + ] + + defines = [ "ASR_NETWORK_LAYER_BLE=${chip_config_network_layer_ble}" ] + + if (chip_build_libshell) { + defines += [ "CONFIG_ENABLE_CHIP_SHELL=1" ] + sources += [ "${examples_plat_dir}/shell/launch_shell.cpp" ] + include_dirs += [ "${examples_plat_dir}/shell" ] + } + + if (chip_print_memory_usage) { + ldflags += [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } + + output_dir = root_out_dir +} + +group("asr") { + deps = [ ":lighting_app" ] +} + +group("default") { + deps = [ ":asr" ] +} diff --git a/examples/lighting-app/asr/README.md b/examples/lighting-app/asr/README.md new file mode 100755 index 00000000000000..78755f02f9119a --- /dev/null +++ b/examples/lighting-app/asr/README.md @@ -0,0 +1,98 @@ +# CHIP ASR Lighting Example + +This example demonstrates the Matter Lighting application on ASR platform. + +--- + +- [CHIP ASR Lighting Example](#chip-asr-lighting-example) + - [Supported Chips](#supported-chips) + - [Building the Example Application](#building-the-example-application) + - [Commissioning](#commissioning) + - [BLE mode](#ble-mode) + - [IP mode](#ip-mode) + - [Cluster Control](#cluster-control) + +--- + +## Supported Chips + +The CHIP demo application is supported on: + +- ASR582X +- ASR595X + +## Building the Example Application + +- [Setup CHIP Environment](../../../docs/guides/BUILDING.md) + +- Setup toolchain for ASR582X,download gcc-arm-none-eabi-9-2019-q4-major,then + export `ASR_TOOLCHAIN_PATH`: + ``` + export ASR_TOOLCHAIN_PATH={path-to-toolchain}/gcc-arm-none-eabi-9-2019-q4-major/bin/ + ``` + for ASR595X,download asr_riscv_gnu_toolchain_10.2_ubuntu,then export + `ASR_TOOLCHAIN_PATH`: + ``` + export ASR_TOOLCHAIN_PATH={path-to-toolchain}/asr_riscv_gnu_toolchain_10.2_ubuntu-16.04/bin/ + ``` +- Setup Chip environment + - for ASR582X: + ``` + export ASR_BOARD=asr582x + ``` + - for ASR595X: + ``` + export ASR_BOARD=asr595x + ``` +- Building the Application + ``` + ./scripts/build/build_examples.py --target asr-$ASR_BOARD-lighting build + ``` +- The output image files are stored in the subdirectories under `out`, the + subdirectory name is the same as the argument specified after the option + `--target` when build the examples. + +- After building the application, `DOGO` tool is used to flash it to the + board. + +## Commissioning + +There are two commissioning modes supported by ASR platform: + +### BLE mode + +1. Build and Flash +2. The example will run automatically after booting the ASR board. +3. Restore factory settings using command `recovery` +4. Commissioning with + [Chip-Tool](https://github.com/project-chip/connectedhomeip/tree/master/examples/chip-tool) + +### IP mode + +1. Build and Flash +2. The example will run automatically after booting the ASR board. +3. Restore factory settings using command `recovery` +4. Connect to AP using command `wifi_open sta [ssid] [password]` +5. Commissioning with + [Chip-Tool](https://github.com/project-chip/connectedhomeip/tree/master/examples/chip-tool) + +## Cluster Control + +After successful commissioning, use `chip-tool` to control the board + +- OnOff Cluster + ``` + ./chip-tool onoff on 1 + ./chip-tool onoff off 1 + ./chip-tool onoff toggle 1 + ``` +- LevelControl Cluster + + ``` + ./chip-tool levelcontrol move-to-level 128 10 0 0 1 + ``` + +- ColorControl Cluster + ``` + ./chip-tool colorcontrol move-to-hue-and-saturation 240 100 0 0 0 1 + ``` diff --git a/examples/lighting-app/asr/args.gni b/examples/lighting-app/asr/args.gni new file mode 100755 index 00000000000000..aa2f74634e4d1b --- /dev/null +++ b/examples/lighting-app/asr/args.gni @@ -0,0 +1,27 @@ +# 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. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("//cfg.gni") +import("${chip_root}/src/platform/ASR/args.gni") + +asr_target_project = + get_label_info(":lighting_app_sdk_sources", "label_no_toolchain") + +declare_args() { + # Disable lock tracking, since our FreeRTOS configuration does not set + # INCLUDE_xSemaphoreGetMutexHolder + chip_stack_lock_tracking = "none" +} diff --git a/examples/lighting-app/asr/build_overrides b/examples/lighting-app/asr/build_overrides new file mode 120000 index 00000000000000..194ee0b812dc3d --- /dev/null +++ b/examples/lighting-app/asr/build_overrides @@ -0,0 +1 @@ +../../build_overrides/ \ No newline at end of file diff --git a/examples/lighting-app/asr/cfg.gni b/examples/lighting-app/asr/cfg.gni new file mode 100755 index 00000000000000..15fe50e79efb6d --- /dev/null +++ b/examples/lighting-app/asr/cfg.gni @@ -0,0 +1,23 @@ +# 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. + +declare_args() { + chip_enable_factory_data = false + + chip_lwip_ip6_hook = false + + setupPinCode = 20202021 + + setupDiscriminator = 3840 +} diff --git a/examples/platform/silabs/SiWx917/siwx917_utils.h b/examples/lighting-app/asr/include/AppConfig.h similarity index 68% rename from examples/platform/silabs/SiWx917/siwx917_utils.h rename to examples/lighting-app/asr/include/AppConfig.h index 2223275d841733..fd0622e3dae21e 100644 --- a/examples/platform/silabs/SiWx917/siwx917_utils.h +++ b/examples/lighting-app/asr/include/AppConfig.h @@ -1,7 +1,7 @@ /* * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2022 Silabs. + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,16 +19,26 @@ #pragma once -// SiWx917 Logging +// ---- Lighting Example App Config ---- + +#if (CFG_EASY_LOG_ENABLE == 1) +#include "elog.h" +#endif + +#define APP_TASK_NAME "APP" + +#define LIGHT_LED PWM_OUTPUT_CH4 + +#define APP_TASK_STACK_SIZE (1024 * 4) + +#define MATTER_DEVICE_NAME "ASR-Lighting" + #ifdef __cplusplus extern "C" { #endif -void silabsInitLog(void); - -void efr32Log(const char * aFormat, ...); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); void appError(int err); +void ASR_LOG(const char * aFormat, ...); #ifdef __cplusplus } diff --git a/examples/lighting-app/asr/include/AppTask.h b/examples/lighting-app/asr/include/AppTask.h new file mode 100644 index 00000000000000..de31a9cee6db47 --- /dev/null +++ b/examples/lighting-app/asr/include/AppTask.h @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2021 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. + */ + +#pragma once + +#include +#include + +#include +#include + +class AppTask +{ + +public: + CHIP_ERROR StartAppTask(); + static void AppTaskMain(void * pvParameter); + +private: + friend AppTask & GetAppTask(void); + + static AppTask sAppTask; +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/lighting-app/asr/include/CHIPProjectConfig.h b/examples/lighting-app/asr/include/CHIPProjectConfig.h new file mode 100755 index 00000000000000..4ff8cbed869e34 --- /dev/null +++ b/examples/lighting-app/asr/include/CHIPProjectConfig.h @@ -0,0 +1,112 @@ +/* + * + * Copyright (c) 2021 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 + +/** + * CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY + * + * Enables the use of a hard-coded default Chip device id and credentials if no device id + * is found in Chip NV storage. + * + * This option is for testing only and should be disabled in production releases. + */ +#define CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY 34 + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// define Device type based on the application +#define CHIP_DEVICE_CONFIG_DEVICE_TYPE 257 // 0x0101 Dimmable Bulb + +// 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_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds 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 versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 1 +#endif + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS + * + * Enable recording UTC timestamps. + */ +#define CHIP_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS 1 + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/ClusterManager.h b/examples/lighting-app/asr/include/DeviceCallbacks.h similarity index 51% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/ClusterManager.h rename to examples/lighting-app/asr/include/DeviceCallbacks.h index 1599ef1ef19264..02df92feb1f82a 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/ClusterManager.h +++ b/examples/lighting-app/asr/include/DeviceCallbacks.h @@ -1,7 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors - * Copyright 2021, Cypress Semiconductor Corporation (an Infineon company) + * Copyright (c) 2020 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,34 +17,31 @@ */ /** - * @file ClusterManager.h + * @file DeviceCallbacks.h * - * Declarations for the ClusterManager callbacks for this application + * Implementations for the DeviceManager callbacks for this application * **/ #pragma once +#include "CHIPDeviceManager.h" #include #include #include -class ClusterManager +class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks { public: - void OnOnOffPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); - void OnLevelControlAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); - void OnColorControlAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); - void OnIdentifyPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint16_t size, - uint8_t * value); + virtual void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value) override; private: - friend ClusterManager & ClusterMgr(void); - bool mEndpointOnOffState[2]; - static ClusterManager sCluster; + void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); + void OnOnOffPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); + void OnLevelPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint16_t size, + uint8_t * value); + void OnColorPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); + void OnIdentifyPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); }; - -inline ClusterManager & ClusterMgr(void) -{ - return ClusterManager::sCluster; -} diff --git a/examples/lighting-app/asr/src/AppTask.cpp b/examples/lighting-app/asr/src/AppTask.cpp new file mode 100644 index 00000000000000..619a71540c0759 --- /dev/null +++ b/examples/lighting-app/asr/src/AppTask.cpp @@ -0,0 +1,168 @@ +/* + * + * Copyright (c) 2021 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. + */ + +#include "AppTask.h" +#include "AppConfig.h" +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include "LEDWidget.h" +#include "qrcodegen.h" +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "init_Matter.h" +#if CONFIG_ENABLE_CHIP_SHELL +#include "matter_shell.h" +#endif +#include + +namespace { +lega_thread_t sAppTaskHandle; +} // namespace + +LEDWidget lightLED; + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; + +AppTask AppTask::sAppTask; + +namespace { +constexpr EndpointId kNetworkCommissioningEndpointMain = 0; +constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; + +app::Clusters::NetworkCommissioning::Instance + sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, + &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); +} // namespace + +void NetWorkCommissioningInstInit() +{ + sWiFiNetworkCommissioningInstance.Init(); + + // We only have network commissioning on endpoint 0. + emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); +} + +static DeviceCallbacks EchoCallbacks; + +CHIP_ERROR AppTask::StartAppTask() +{ + // Start App task. + OSStatus result = lega_rtos_create_thread(&sAppTaskHandle, 2, APP_TASK_NAME, (lega_thread_function_t) AppTaskMain, + APP_TASK_STACK_SIZE, (lega_thread_arg_t) this); + return (result == kNoErr) ? CHIP_NO_ERROR : CHIP_APPLICATION_ERROR(0x02); +} + +bool IsLightOn() +{ + EmberAfStatus status; + bool on = true; + status = app::Clusters::OnOff::Attributes::OnOff::Get(1, &on); + + if (status != EMBER_ZCL_STATUS_SUCCESS) + { + ASR_LOG("Error Read OnOff Attribute 0x%02x\n", status); + } + + return on != false; +} + +uint8_t GetLightLevel() +{ + EmberAfStatus status; + app::DataModel::Nullable currentLevel; + + status = app::Clusters::LevelControl::Attributes::CurrentLevel::Get(1, currentLevel); + + if (status != EMBER_ZCL_STATUS_SUCCESS) + { + ASR_LOG("Error Read CurrentLevel Attribute 0x%02x\n", status); + return -1; + } + + if (currentLevel.IsNull()) + { + ASR_LOG("Error currentLevel is null\n"); + return -1; + } + + return currentLevel.Value(); +} + +void led_startup_status() +{ + uint8_t currentLevel; + + if (IsLightOn() == true) + { + currentLevel = GetLightLevel(); + lightLED.Set(1); + lightLED.SetBrightness(currentLevel); + } +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + ASR_LOG("App Task started"); + + if (MatterInitializer::Init_Matter_Stack(MATTER_DEVICE_NAME) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); + + if (deviceMgr.Init(&EchoCallbacks) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + if (MatterInitializer::Init_Matter_Server() != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + NetWorkCommissioningInstInit(); + + ASR_LOG("Current Firmware Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + ConfigurationMgr().LogDeviceConfig(); + + // Print setup info + PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); + +#if (LIGHT_SELECT == LIGHT_SELECT_LED) + lightLED.Init(LIGHT_LED); // embedded board light +#elif (LIGHT_SELECT == LIGHT_SELECT_RGB) + lightLED.RGB_init(); +#endif + + /* get led onoff status and level value */ + led_startup_status(); +#if CONFIG_ENABLE_CHIP_SHELL + RegisterLightCommands(); +#endif + /* Delete task */ + lega_rtos_delete_thread(NULL); +} diff --git a/examples/lighting-app/asr/src/DeviceCallbacks.cpp b/examples/lighting-app/asr/src/DeviceCallbacks.cpp new file mode 100644 index 00000000000000..92c962f75702db --- /dev/null +++ b/examples/lighting-app/asr/src/DeviceCallbacks.cpp @@ -0,0 +1,248 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.cpp + * + * Implements all the callbacks to the application from the CHIP Stack + * + **/ +#include "DeviceCallbacks.h" +#include "AppConfig.h" +#include "CHIPDeviceManager.h" +#include "LEDWidget.h" +#include "init_OTARequestor.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT +#include "route_hook/asr_route_hook.h" +#endif + +static const char * TAG = "app-devicecallbacks"; + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::System; +using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceManager; +using namespace ::chip::Logging; + +uint32_t identifyTimerCount; +constexpr uint32_t kIdentifyTimerDelayMS = 250; +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +constexpr uint32_t kInitOTARequestorDelaySec = 3; + +void InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +{ + OTAInitializer::Instance().InitOTARequestor(); +} +#endif +void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + switch (event->Type) + { + case DeviceEventType::kInternetConnectivityChange: + OnInternetConnectivityChange(event); + break; + + case DeviceEventType::kInterfaceIpAddressChanged: + if ((event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned) || + (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned)) + { + // MDNS server restart on any ip assignment: if link local ipv6 is configured, that + // will not trigger a 'internet connectivity change' as there is no internet + // connectivity. MDNS still wants to refresh its listening interfaces to include the + // newly selected address. + chip::app::DnssdServer::Instance().StartServer(); + + if (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned) + { +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT + ChipLogProgress(NotSpecified, "Initializing route hook..."); + asr_route_hook_init(); +#endif + } + } + break; + } +} + +void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + static bool isOTAInitialized = false; +#endif + if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established) + { + ASR_LOG("IPv4 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); + } + else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost) + { + ASR_LOG("Lost IPv4 connectivity..."); + } + if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established) + { + ASR_LOG("IPv6 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Init OTA requestor only when we have gotten IPv6 address + if (!isOTAInitialized) + { + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec), + InitOTARequestorHandler, nullptr); + isOTAInitialized = true; + } +#endif + } + else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost) + { + ASR_LOG("Lost IPv6 connectivity..."); + } +} + +void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t type, + uint16_t size, uint8_t * value) +{ + switch (clusterId) + { + case app::Clusters::OnOff::Id: + OnOnOffPostAttributeChangeCallback(endpointId, attributeId, value); + break; + + case app::Clusters::Identify::Id: + OnIdentifyPostAttributeChangeCallback(endpointId, attributeId, value); + break; + + case app::Clusters::LevelControl::Id: + OnLevelPostAttributeChangeCallback(endpointId, attributeId, size, value); + break; + + case app::Clusters::ColorControl::Id: + OnColorPostAttributeChangeCallback(endpointId, attributeId, value); + break; + + default: + ChipLogProgress(Zcl, "Unknown cluster ID: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + break; + } +} + +void IdentifyTimerHandler(Layer * systemLayer, void * appState) +{ + if (identifyTimerCount) + { + systemLayer->StartTimer(Clock::Milliseconds32(kIdentifyTimerDelayMS), IdentifyTimerHandler, appState); + // Decrement the timer count. + identifyTimerCount--; + } +} + +extern LEDWidget lightLED; + +void DeviceCallbacks::OnOnOffPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) +{ + VerifyOrExit(attributeId == app::Clusters::OnOff::Attributes::OnOff::Id, + ChipLogError(DeviceLayer, TAG, "Unhandled Attribute ID: '0x%04x", attributeId)); + VerifyOrExit(endpointId == 1 || endpointId == 2, + ChipLogError(DeviceLayer, TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId)); + + lightLED.Set(*value); + +exit: + return; +} + +void DeviceCallbacks::OnLevelPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint16_t size, + uint8_t * value) +{ + VerifyOrExit(attributeId == app::Clusters::LevelControl::Attributes::CurrentLevel::Id, + ChipLogError(DeviceLayer, TAG, "Unhandled Attribute ID: '0x%04x", attributeId)); + VerifyOrExit(endpointId == 1 || endpointId == 2, + ChipLogError(DeviceLayer, TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId)); + + if (size == 1) + { + uint8_t tmp = *value; + ChipLogProgress(Zcl, "New level: %u ", tmp); + lightLED.SetBrightness(tmp); + } + else + { + ChipLogError(Zcl, "wrong length for level: %d\n", size); + } + +exit: + return; +} + +void DeviceCallbacks::OnColorPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) +{ + using namespace app::Clusters::ColorControl::Attributes; + + uint8_t hue, saturation; + + if ((attributeId != CurrentHue::Id) && (attributeId != CurrentSaturation::Id)) + { + ChipLogProgress(Zcl, "Unknown attribute ID: %" PRIx32, attributeId); + return; + } + + if (attributeId == CurrentHue::Id) + { + hue = *value; + CurrentSaturation::Get(endpointId, &saturation); + } + if (attributeId == CurrentSaturation::Id) + { + saturation = *value; + CurrentHue::Get(endpointId, &hue); + } + + ASR_LOG("New hue: %d, New saturation: %d\n", hue, saturation); + + lightLED.SetColor(hue, saturation); +} + +void DeviceCallbacks::OnIdentifyPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) +{ + VerifyOrExit(attributeId == app::Clusters::Identify::Attributes::IdentifyTime::Id, + ChipLogError(DeviceLayer, "[%s] Unhandled Attribute ID: '0x%04lx", TAG, attributeId)); + VerifyOrExit(endpointId == 1, ChipLogError(DeviceLayer, "[%s] Unexpected EndPoint ID: `0x%02x'", TAG, endpointId)); + + // timerCount represents the number of callback executions before we stop the timer. + // value is expressed in seconds and the timer is fired every 250ms, so just multiply value by 4. + // Also, we want timerCount to be odd number, so the ligth state ends in the same state it starts. + identifyTimerCount = (*value) * 4; + + DeviceLayer::SystemLayer().CancelTimer(IdentifyTimerHandler, this); + DeviceLayer::SystemLayer().StartTimer(Clock::Milliseconds32(kIdentifyTimerDelayMS), IdentifyTimerHandler, this); + +exit: + return; +} diff --git a/examples/lighting-app/asr/src/main.cpp b/examples/lighting-app/asr/src/main.cpp new file mode 100644 index 00000000000000..b697014484e13e --- /dev/null +++ b/examples/lighting-app/asr/src/main.cpp @@ -0,0 +1,93 @@ +/* + * + * Copyright (c) 2021 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. + */ + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "AppConfig.h" +#include "init_asrPlatform.h" +#include + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; + +volatile int apperror_cnt; +// ================================================================================ +// App Error +//================================================================================= +void appError(int err) +{ + ASR_LOG("!!!!!!!!!!!! App Critical Error: %d !!!!!!!!!!!", err); + lega_rtos_declare_critical(); + lega_rtos_enter_critical(); + while (1) + ; +} + +void appError(CHIP_ERROR error) +{ + appError(static_cast(error.AsInteger())); +} + +// ================================================================================ +// FreeRTOS Callbacks +// ================================================================================ +extern "C" void vApplicationIdleHook(void) +{ + // FreeRTOS Idle callback +} + +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + init_asrPlatform(); + + CHIP_ERROR ret = GetAppTask().StartAppTask(); + if (ret != CHIP_NO_ERROR) + { + ASR_LOG("GetAppTask().Init() failed"); + appError(ret); + } + /* Start the FreeRTOS scheduler */ + vTaskStartScheduler(); + + chip::Platform::MemoryShutdown(); + PlatformMgr().StopEventLoopTask(); + PlatformMgr().Shutdown(); + + // Should never get here. + ASR_LOG("vTaskStartScheduler() failed"); + appError(ret); +} diff --git a/examples/lighting-app/asr/third_party/connectedhomeip b/examples/lighting-app/asr/third_party/connectedhomeip new file mode 120000 index 00000000000000..11a54ed360106c --- /dev/null +++ b/examples/lighting-app/asr/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../ \ No newline at end of file diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/.gn b/examples/lighting-app/cc13x2x7_26x2x7/.gn similarity index 99% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/.gn rename to examples/lighting-app/cc13x2x7_26x2x7/.gn index 0adefc6ff99c6a..3d48789e30ab3d 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/.gn +++ b/examples/lighting-app/cc13x2x7_26x2x7/.gn @@ -23,5 +23,6 @@ check_system_includes = true default_args = { target_cpu = "arm" target_os = "freertos" + import("//args.gni") } diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/BUILD.gn b/examples/lighting-app/cc13x2x7_26x2x7/BUILD.gn similarity index 71% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/BUILD.gn rename to examples/lighting-app/cc13x2x7_26x2x7/BUILD.gn index 6c20ed346ec530..aec1e66b95939c 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/lighting-app/cc13x2x7_26x2x7/BUILD.gn @@ -26,18 +26,17 @@ import("${ti_simplelink_sdk_build_root}/ti_simplelink_sdk.gni") assert(current_os == "freertos") -project_dir = "${chip_root}/examples/all-clusters-minimal-app/cc13x2x7_26x2x7" +project_dir = "${chip_root}/examples/lighting-app/cc13x2x7_26x2x7" ti_simplelink_sdk("sdk") { - include_dirs = [ "${project_dir}/main/include" ] - public_configs = [ ":all-clusters-minimal-app_config" ] + include_dirs = [ "${project_dir}/include" ] + public_configs = [ ":lighting_app_config" ] } ti_sysconfig("sysconfig") { sources = [ "${project_dir}/chip.syscfg" ] outputs = [ - "ti_devices_config.c", "ti_radio_config.c", "ti_radio_config.h", "ti_drivers_config.c", @@ -71,25 +70,22 @@ ti_sysconfig("sysconfig") { ] } -ti_simplelink_executable("all-clusters-minimal-app") { - output_name = "chip-${ti_simplelink_board}-all-clusters-minimal-example.out" +ti_simplelink_executable("lighting_app") { + output_name = "chip-${ti_simplelink_board}-lighting-example.out" sources = [ - "${chip_root}/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp", - "${chip_root}/examples/all-clusters-app/all-clusters-common/src/bridged-actions-stub.cpp", - "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", "${chip_root}/examples/providers/DeviceInfoProviderImpl.cpp", - "${project_dir}/main/AppTask.cpp", - "${project_dir}/main/ClusterManager.cpp", - "${project_dir}/main/Globals.cpp", - "${project_dir}/main/ZclCallbacks.cpp", - "${project_dir}/main/main.cpp", + "${project_dir}/src/AppTask.cpp", + "${project_dir}/src/LightingManager.cpp", + "${project_dir}/src/ZclCallbacks.cpp", + "${project_dir}/src/main.cpp", ] deps = [ ":sdk", ":sysconfig", - "${chip_root}/examples/all-clusters-minimal-app/all-clusters-common", + "${chip_root}/examples/lighting-app/lighting-common", + "${chip_root}/examples/platform/cc13x2_26x2:cc13x2_26x2-attestation-credentials", "${chip_root}/src/lib", ] @@ -101,8 +97,6 @@ ti_simplelink_executable("all-clusters-minimal-app") { include_dirs = [ "${project_dir}", - "${project_dir}/main", - "${chip_root}/examples/all-clusters-app/all-clusters-common/include", "${chip_root}/examples/providers/", ] @@ -116,7 +110,7 @@ ti_simplelink_executable("all-clusters-minimal-app") { } group("cc13x2x7_26x2x7") { - deps = [ ":all-clusters-minimal-app" ] + deps = [ ":lighting_app" ] } group("default") { diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/args.gni b/examples/lighting-app/cc13x2x7_26x2x7/args.gni similarity index 83% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/args.gni rename to examples/lighting-app/cc13x2x7_26x2x7/args.gni index 9228f70c4a0f03..a6a8662c4d14cb 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/args.gni +++ b/examples/lighting-app/cc13x2x7_26x2x7/args.gni @@ -27,17 +27,15 @@ ti_simplelink_board = "LP_CC2652R7" optimize_debug_level = "s" lwip_debug = false -chip_enable_ota_requestor = false +chip_enable_ota_requestor = true -# Disable FTD Build for all-clusters app to save Flash chip_openthread_ftd = false +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2" # Disable CHIP Logging -chip_progress_logging = false - -# Dsiable verbose logs for all-clusters app to save Flash -chip_detail_logging = false -chip_automation_logging = false +#chip_progress_logging = false +#chip_detail_logging = false +#chip_automation_logging = false # BLE options chip_config_network_layer_ble = true @@ -47,6 +45,6 @@ chip_config_network_layer_ble = true chip_stack_lock_tracking = "none" matter_device_vid = "0xFFF1" -matter_device_pid = "0x8006" +matter_device_pid = "0x8005" matter_software_ver = "0x0001" matter_software_ver_str = "1.0d1" diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/build_overrides b/examples/lighting-app/cc13x2x7_26x2x7/build_overrides similarity index 100% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/build_overrides rename to examples/lighting-app/cc13x2x7_26x2x7/build_overrides diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/chip.syscfg b/examples/lighting-app/cc13x2x7_26x2x7/chip.syscfg similarity index 82% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/chip.syscfg rename to examples/lighting-app/cc13x2x7_26x2x7/chip.syscfg index 4f02a9fd40da9a..995ad22af6b435 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/lighting-app/cc13x2x7_26x2x7/chip.syscfg @@ -26,11 +26,10 @@ var LED = scripting.addModule("/ti/drivers/apps/LED"); var NVS = scripting.addModule("/ti/drivers/NVS"); var RF = scripting.addModule("/ti/drivers/RF"); var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); -var RTOS = scripting.addModule("/ti/drivers/RTOS"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); var TRNG = scripting.addModule("/ti/drivers/TRNG"); -var Thread = scripting.addModule("/ti/thread/thread"); var SHA2 = scripting.addModule("/ti/drivers/SHA2"); -var UART = scripting.addModule("/ti/drivers/UART"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); var ble = scripting.addModule("/ti/ble5stack/ble"); var dmm = scripting.addModule("/ti/dmm/dmm"); var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); @@ -50,12 +49,11 @@ var LED2 = LED.addInstance(); var TRNG1 = TRNG.addInstance(); var TRNG2 = TRNG.addInstance(); var TRNG3 = TRNG.addInstance(); -var UART1 = UART.addInstance(); +var UART2 = UART2.addInstance(); var AESCTRDRBG1 = AESCTRDRBG.addInstance(); var ECDH1 = ECDH.addInstance(); AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; -AESCTRDRBG1.aesctrObject.$name = "CONFIG_AESCTR_0"; AESCCM1.$name = "CONFIG_AESCCM0"; @@ -64,9 +62,6 @@ AESECB2.$name = "CONFIG_AESECB_1"; ECDH1.$name = "CONFIG_ECDH0"; -/* RTOS */ -RTOS.name = "FreeRTOS"; - /* Left Button */ Button1.$name = "CONFIG_BTN_LEFT"; Button1.$hardware = system.deviceData.board.components["BTN-1"]; @@ -89,11 +84,11 @@ for(var setting in ccfgSettings) CCFG[setting] = ccfgSettings[setting]; } -CCFG.enableCodeGeneration = true; +// Disable CCFG generation, this is added by the BIM project +CCFG.enableCodeGeneration = false; /* NVS */ NVS1.$name = "CONFIG_NVSINTERNAL"; - NVS1.internalFlash.regionBase = 0xAA000; NVS1.internalFlash.regionSize = 0x4000; @@ -113,6 +108,58 @@ for(var setting in rfDesignSettings) RFDesign[setting] = rfDesignSettings[setting]; } +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + /* Red LED */ LED1.$name = "CONFIG_LED_RED"; LED1.$hardware = system.deviceData.board.components.LED_RED; @@ -128,16 +175,14 @@ LED2.gpioPin.mode = "Output"; LED2.gpioPin.callbackFunction = ""; /* Debug UART */ -UART1.$hardware = system.deviceData.board.components.XDS110UART; -UART1.$name = "CONFIG_UART_DEBUG"; +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART2_DEBUG"; /* TRNG */ TRNG1.$name = "CONFIG_TRNG_0"; -TRNG2.$name = "CONFIG_TRNG_1"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; TRNG3.$name = "CONFIG_TRNG_APP"; -RTOS.name = "FreeRTOS"; - /* BLE */ ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; ble.maxConnNum = 1; @@ -145,11 +190,12 @@ ble.numOfAdvSets = 1; ble.lockProject = true; ble.oneLibSizeOpt = true; ble.maxPDUSize = 255; -ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param2"; ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; ble.connUpdateParamsPeripheral.reqMinConnInt = 30; ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; + ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h b/examples/lighting-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h similarity index 95% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h rename to examples/lighting-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h index 4d50a5a05c08d9..0f5090d7d9f320 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h +++ b/examples/lighting-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h @@ -55,7 +55,9 @@ * physical device, a change to its packaging, and/or a change to its marketing presentation. * This value is generally *not* incremented for device software versions. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION #define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 +#endif /** * Values set by args.gni: @@ -79,7 +81,7 @@ */ #define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) -#define MATTER_CC13X2_26X2_PLATFORM_LOG_ENABLED 1 +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 1 /** * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT @@ -108,13 +110,13 @@ * * @brief Defines the maximum number of CommandHandler, limits the number of active commands transactions on server. */ -#define CHIP_IM_MAX_NUM_COMMAND_HANDLER 1 +#define CHIP_IM_MAX_NUM_COMMAND_HANDLER 2 /** * @def CHIP_IM_MAX_NUM_WRITE_HANDLER * * @brief Defines the maximum number of WriteHandler, limits the number of active write transactions on server. */ -#define CHIP_IM_MAX_NUM_WRITE_HANDLER 1 +#define CHIP_IM_MAX_NUM_WRITE_HANDLER 2 #endif // CHIP_PROJECT_CONFIG_H diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/Globals.h b/examples/lighting-app/cc13x2x7_26x2x7/src/AppConfig.h similarity index 75% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/Globals.h rename to examples/lighting-app/cc13x2x7_26x2x7/src/AppConfig.h index 43f9362e0341b9..a818b21d641875 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/Globals.h +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/AppConfig.h @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2020 Project CHIP Authors * All rights reserved. * @@ -16,20 +15,21 @@ * limitations under the License. */ -#pragma once +#ifndef APP_CONFIG_H +#define APP_CONFIG_H -#include // Logging #ifdef __cplusplus extern "C" { #endif -int cc13x2_26x2LogInit(void); -void cc13x2_26x2Log(const char * aFormat, ...); -#define PLAT_LOG(...) cc13x2_26x2Log(__VA_ARGS__); +int cc13xx_26xxLogInit(void); +void cc13xx_26xxLog(const char * aFormat, ...); +#define PLAT_LOG(...) cc13xx_26xxLog(__VA_ARGS__); + +#define ACTUATOR_MOVEMENT_PERIOD_MS 1000 #ifdef __cplusplus } #endif -extern LED_Handle sAppRedHandle; -extern LED_Handle sAppGreenHandle; +#endif // APP_CONFIG_H diff --git a/examples/lighting-app/cc13x2x7_26x2x7/src/AppEvent.h b/examples/lighting-app/cc13x2x7_26x2x7/src/AppEvent.h new file mode 100644 index 00000000000000..9c55e1bf674531 --- /dev/null +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/AppEvent.h @@ -0,0 +1,84 @@ +/* + * + * 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. + */ +#ifndef APP_EVENT_H +#define APP_EVENT_H + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +struct AppEvent +{ + enum AppEventType + { + kEventType_None = 0, + kEventType_ButtonLeft, + kEventType_ButtonRight, + kEventType_AppEvent, + kEventType_IdentifyStart, + kEventType_IdentifyStop, + kEventType_Light, + kEventType_Timer, + }; + + enum AppEventButtonType + { + kAppEventButtonType_None = 0, + kAppEventButtonType_Clicked, + kAppEventButtonType_LongClicked, + }; + + enum AppEventIdentifyType + { + kAppEventIdentifyType_Blink = 0, + kAppEventIdentifyType_Breathe, + kAppEventIdentifyType_Okay, + kAppEventIdentifyType_Finish, + kAppEventIdentifyType_Stop, + }; + + enum AppEventType Type; + + union + { + struct + { + enum AppEventButtonType Type; + } ButtonEvent; + + struct + { + void * Context; + } TimerEvent; + + struct + { + uint8_t Action; + int32_t Actor; + void * Context; + } LightEvent; + + struct + { + enum AppEventIdentifyType Type; + } IdentifyEvent; + }; + + EventHandler Handler; +}; + +#endif // APP_EVENT_H diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.cpp similarity index 56% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/AppTask.cpp rename to examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.cpp index 871a5f71d6acc0..945679b5e1e853 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.cpp @@ -20,13 +20,12 @@ #include "AppTask.h" #include "AppConfig.h" #include "AppEvent.h" -#include -#include #include "FreeRTOS.h" -#include "Globals.h" + #include #include +#include #include #include @@ -36,15 +35,19 @@ #include #include #include -#include +#include #endif + #include #include -#ifdef AUTO_PRINT_METRICS -#include -#endif +#include + +#include +#include #include +#include +#include #include #include @@ -52,10 +55,19 @@ /* syscfg */ #include -#define APP_TASK_STACK_SIZE (5000) +#define APP_TASK_STACK_SIZE (4096) #define APP_TASK_PRIORITY 4 #define APP_EVENT_QUEUE_SIZE 10 +#define IDENTIFY_TRIGGER_EFFECT_BLINK 0 +#define IDENTIFY_TRIGGER_EFFECT_BREATHE 1 +#define IDENTIFY_TRIGGER_EFFECT_OKAY 2 +#define IDENTIFY_TRIGGER_EFFECT_FINISH_STOP 3 + +static uint32_t identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_FINISH_STOP; + +#define LIGHTING_APPLICATION_IDENTIFY_ENDPOINT 1 + using namespace ::chip; using namespace ::chip::Credentials; using namespace ::chip::DeviceLayer; @@ -63,14 +75,14 @@ using namespace ::chip::DeviceLayer; static TaskHandle_t sAppTaskHandle; static QueueHandle_t sAppEventQueue; +static LED_Handle sAppRedHandle; +static LED_Handle sAppGreenHandle; static Button_Handle sAppLeftHandle; static Button_Handle sAppRightHandle; static DeviceInfoProviderImpl sExampleDeviceInfoProvider; AppTask AppTask::sAppTask; -constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; - #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR static DefaultOTARequestor sRequestorCore; static DefaultOTARequestorStorage sRequestorStorage; @@ -91,54 +103,8 @@ void InitializeOTARequestor(void) } #endif -#ifdef AUTO_PRINT_METRICS -static void printMetrics(void) -{ - chip::DeviceLayer::ThreadMetrics *threadMetricsOut, *currThread; - uint64_t heapFree, heapUsed; - - DiagnosticDataProviderImpl::GetDefaultInstance().GetCurrentHeapUsed(heapUsed); - DiagnosticDataProviderImpl::GetDefaultInstance().GetCurrentHeapFree(heapFree); - DiagnosticDataProviderImpl::GetDefaultInstance().GetThreadMetrics(&threadMetricsOut); - - PLAT_LOG("Heap Metrics\n Heap Free: %d Heap Used: %d", (uint32_t) heapFree, (uint32_t) heapUsed); - - PLAT_LOG("Thread Metrics\n"); - - currThread = threadMetricsOut; - while (currThread) - { - PLAT_LOG("Task Name: %s ID: %d Stack Free Min: %d", currThread->name, (uint32_t) currThread->id, - (uint32_t) currThread->stackFreeMinimum); - - currThread = currThread->Next; - } - - DiagnosticDataProviderImpl::GetDefaultInstance().ReleaseThreadMetrics(threadMetricsOut); -} -#endif - -void DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEConnectionEstablished: - PLAT_LOG("CHIPoBLE connection established"); - break; - - case DeviceEventType::kCHIPoBLEConnectionClosed: - PLAT_LOG("CHIPoBLE disconnected"); - break; - - case DeviceEventType::kCommissioningComplete: - PLAT_LOG("Commissioning complete"); - break; - } - -#ifdef AUTO_PRINT_METRICS - printMetrics(); -#endif -} +::Identify stIdentify = { LIGHTING_APPLICATION_IDENTIFY_ENDPOINT, AppTask::IdentifyStartHandler, AppTask::IdentifyStopHandler, + EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, AppTask::TriggerIdentifyEffectHandler }; int AppTask::StartAppTask() { @@ -148,7 +114,7 @@ int AppTask::StartAppTask() if (sAppEventQueue == NULL) { PLAT_LOG("Failed to allocate app event queue"); - while (true) + while (1) ; } @@ -157,46 +123,50 @@ int AppTask::StartAppTask() pdPASS) { PLAT_LOG("Failed to create app task"); - while (true) + while (1) ; } return ret; } -int AppTask::Init() +// Action initiated callback +void uiTurnOn(void) { - LED_Params ledParams; - Button_Params buttonParams; + PLAT_LOG("Light On initiated"); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppRedHandle, 110 /* ms */, LED_BLINK_FOREVER); +} - cc13x2_26x2LogInit(); +// Action completed callback +void uiTurnedOn(void) +{ + PLAT_LOG("Light On completed"); + LED_stopBlinking(sAppRedHandle); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); +} - // Initialize LEDs - PLAT_LOG("Initialize LEDs"); - LED_init(); +// Action initiated callback +void uiTurnOff(void) +{ + PLAT_LOG("Light Off initiated"); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppRedHandle, 110 /* ms */, LED_BLINK_FOREVER); +} - LED_Params_init(&ledParams); // default PWM LED - sAppRedHandle = LED_open(CONFIG_LED_RED, &ledParams); +// Action completed callback +void uiTurnedOff(void) +{ + PLAT_LOG("Light Off completed"); + LED_stopBlinking(sAppRedHandle); LED_setOff(sAppRedHandle); +} - LED_Params_init(&ledParams); // default PWM LED - sAppGreenHandle = LED_open(CONFIG_LED_GREEN, &ledParams); - LED_setOff(sAppGreenHandle); - - // Initialize buttons - PLAT_LOG("Initialize buttons"); - Button_init(); +int AppTask::Init() +{ + LED_Params ledParams; + Button_Params buttonParams; - Button_Params_init(&buttonParams); - buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; - buttonParams.longPressDuration = 1000U; // ms - sAppLeftHandle = Button_open(CONFIG_BTN_LEFT, &buttonParams); - Button_setCallback(sAppLeftHandle, ButtonLeftEventHandler); - - Button_Params_init(&buttonParams); - buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; - buttonParams.longPressDuration = 1000U; // ms - sAppRightHandle = Button_open(CONFIG_BTN_RIGHT, &buttonParams); - Button_setCallback(sAppRightHandle, ButtonRightEventHandler); + cc13xx_26xxLogInit(); // Init Chip memory management before the stack Platform::MemoryInit(); @@ -205,7 +175,7 @@ int AppTask::Init() if (ret != CHIP_NO_ERROR) { PLAT_LOG("PlatformMgr().InitChipStack() failed"); - while (true) + while (1) ; } @@ -213,15 +183,18 @@ int AppTask::Init() if (ret != CHIP_NO_ERROR) { PLAT_LOG("ThreadStackMgr().InitThreadStack() failed"); - while (true) + while (1) ; } - +#if CHIP_DEVICE_CONFIG_THREAD_FTD + ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); +#else ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice); +#endif if (ret != CHIP_NO_ERROR) { PLAT_LOG("ConnectivityMgr().SetThreadDeviceType() failed"); - while (true) + while (1) ; } @@ -229,7 +202,7 @@ int AppTask::Init() if (ret != CHIP_NO_ERROR) { PLAT_LOG("PlatformMgr().StartEventLoopTask() failed"); - while (true) + while (1) ; } @@ -237,32 +210,68 @@ int AppTask::Init() if (ret != CHIP_NO_ERROR) { PLAT_LOG("ThreadStackMgr().StartThreadTask() failed"); - while (true) + while (1) ; } // Init ZCL Data Model and start server PLAT_LOG("Initialize Server"); - static chip::CommonCaseDeviceServerInitParams initParams; + static CommonCaseDeviceServerInitParams initParams; (void) initParams.InitializeStaticResourcesBeforeServerInit(); // Initialize info provider sExampleDeviceInfoProvider.SetStorageDelegate(initParams.persistentStorageDelegate); SetDeviceInfoProvider(&sExampleDeviceInfoProvider); - chip::Server::GetInstance().Init(initParams); - - ConfigurationMgr().LogDeviceConfig(); + Server::GetInstance().Init(initParams); // Initialize device attestation config +#ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS + SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); +#else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif + + // Initialize LEDs + PLAT_LOG("Initialize LEDs"); + LED_init(); + + LED_Params_init(&ledParams); // default PWM LED + sAppRedHandle = LED_open(CONFIG_LED_RED, &ledParams); + LED_setOff(sAppRedHandle); + + LED_Params_init(&ledParams); // default PWM LED + sAppGreenHandle = LED_open(CONFIG_LED_GREEN, &ledParams); + LED_setOff(sAppGreenHandle); - // We only have network commissioning on endpoint 0. - emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); + // Initialize buttons + PLAT_LOG("Initialize buttons"); + Button_init(); + + Button_Params_init(&buttonParams); + buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; + buttonParams.longPressDuration = 1000U; // ms + sAppLeftHandle = Button_open(CONFIG_BTN_LEFT, &buttonParams); + Button_setCallback(sAppLeftHandle, ButtonLeftEventHandler); + + Button_Params_init(&buttonParams); + buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; + buttonParams.longPressDuration = 1000U; // ms + sAppRightHandle = Button_open(CONFIG_BTN_RIGHT, &buttonParams); + Button_setCallback(sAppRightHandle, ButtonRightEventHandler); + + ret = LightMgr().Init(); + + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("LightMgr().Init() failed"); + while (1) + ; + } + + LightMgr().SetCallbacks(ActionInitiated, ActionCompleted); - // Register a function to receive events from the CHIP device layer. Note that calls to - // this function will happen on the CHIP event loop thread, not the app_main thread. - PlatformMgr().AddEventHandler(DeviceEventCallback, reinterpret_cast(nullptr)); + ConfigurationMgr().LogDeviceConfig(); #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR InitializeOTARequestor(); @@ -279,7 +288,7 @@ void AppTask::AppTaskMain(void * pvParameter) sAppTask.Init(); - while (true) + while (1) { /* Task pend until we have stuff to do */ if (xQueueReceive(sAppEventQueue, &event, portMAX_DELAY) == pdTRUE) @@ -289,14 +298,6 @@ void AppTask::AppTaskMain(void * pvParameter) } } -void AppTask::PostEvent(const AppEvent * aEvent) -{ - if (xQueueSend(sAppEventQueue, aEvent, 0) != pdPASS) - { - /* Failed to post the message */ - } -} - void AppTask::ButtonLeftEventHandler(Button_Handle handle, Button_EventMask events) { AppEvent event; @@ -337,13 +338,80 @@ void AppTask::ButtonRightEventHandler(Button_Handle handle, Button_EventMask eve } } +void AppTask::ActionInitiated(LightingManager::Action_t aAction, int32_t aActor) +{ + if (aAction == LightingManager::ON_ACTION) + { + uiTurnOn(); + } + else if (aAction == LightingManager::OFF_ACTION) + { + uiTurnOff(); + } +} + +void AppTask::ActionCompleted(LightingManager::Action_t aAction) +{ + if (aAction == LightingManager::ON_ACTION) + { + uiTurnedOn(); + } + else if (aAction == LightingManager::OFF_ACTION) + { + uiTurnedOff(); + } +} + +void AppTask::PostEvent(const AppEvent * aEvent) +{ + if (sAppEventQueue != NULL) + { + BaseType_t status; + if (xPortIsInsideInterrupt()) + { + BaseType_t higherPrioTaskWoken = pdFALSE; + status = xQueueSendFromISR(sAppEventQueue, aEvent, &higherPrioTaskWoken); + +#ifdef portYIELD_FROM_ISR + portYIELD_FROM_ISR(higherPrioTaskWoken); +#elif portEND_SWITCHING_ISR // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + portEND_SWITCHING_ISR(higherPrioTaskWoken); +#else // portYIELD_FROM_ISR or portEND_SWITCHING_ISR +#error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR" +#endif // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + } + else + { + status = xQueueSend(sAppEventQueue, aEvent, 1); + } + + if (status != pdTRUE) + { + PLAT_LOG("Failed to post event to app task event queue"); + } + } + else + { + PLAT_LOG("Event Queue is NULL should never happen"); + } +} + void AppTask::DispatchEvent(AppEvent * aEvent) { + int32_t actor; + switch (aEvent->Type) { + case AppEvent::kEventType_Light: { + actor = aEvent->LightEvent.Actor; + LightMgr().IsLightOn() ? LightMgr().InitiateAction(actor, LightingManager::OFF_ACTION) + : LightMgr().InitiateAction(actor, LightingManager::ON_ACTION); + } case AppEvent::kEventType_ButtonLeft: if (AppEvent::kAppEventButtonType_Clicked == aEvent->ButtonEvent.Type) { + actor = AppEvent::kEventType_ButtonLeft; + LightMgr().InitiateAction(actor, LightingManager::ON_ACTION); } else if (AppEvent::kAppEventButtonType_LongClicked == aEvent->ButtonEvent.Type) { @@ -354,6 +422,8 @@ void AppTask::DispatchEvent(AppEvent * aEvent) case AppEvent::kEventType_ButtonRight: if (AppEvent::kAppEventButtonType_Clicked == aEvent->ButtonEvent.Type) { + actor = AppEvent::kEventType_ButtonRight; + LightMgr().InitiateAction(actor, LightingManager::OFF_ACTION); } else if (AppEvent::kAppEventButtonType_LongClicked == aEvent->ButtonEvent.Type) { @@ -378,6 +448,33 @@ void AppTask::DispatchEvent(AppEvent * aEvent) } break; + case AppEvent::kEventType_IdentifyStart: + switch (identify_trigger_effect) + { + case IDENTIFY_TRIGGER_EFFECT_BLINK: + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 1000, LED_BLINK_FOREVER); + break; + case IDENTIFY_TRIGGER_EFFECT_BREATHE: + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 100, LED_BLINK_FOREVER); + break; + case IDENTIFY_TRIGGER_EFFECT_OKAY: + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 500, LED_BLINK_FOREVER); + break; + default: + break; + } + PLAT_LOG("Identify started"); + break; + + case AppEvent::kEventType_IdentifyStop: + LED_stopBlinking(sAppGreenHandle); + LED_setOff(sAppGreenHandle); + PLAT_LOG("Identify stopped"); + break; + case AppEvent::kEventType_AppEvent: if (NULL != aEvent->Handler) { @@ -390,3 +487,54 @@ void AppTask::DispatchEvent(AppEvent * aEvent) break; } } + +void AppTask::IdentifyStartHandler(::Identify *) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStart; + sAppTask.PostEvent(&event); +} + +void AppTask::IdentifyStopHandler(::Identify *) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStop; + sAppTask.PostEvent(&event); +} + +void AppTask::TriggerIdentifyEffectHandler(::Identify * identify) +{ + switch (identify->mCurrentEffectIdentifier) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + PLAT_LOG("Starting blink identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_BLINK; + IdentifyStartHandler(identify); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + PLAT_LOG("Starting breathe identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_BREATHE; + IdentifyStartHandler(identify); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + PLAT_LOG("Starting okay identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_OKAY; + IdentifyStartHandler(identify); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + PLAT_LOG("Channel Change identifier effect not implemented"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: + PLAT_LOG("Finish identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_FINISH_STOP; + IdentifyStopHandler(identify); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: + PLAT_LOG("Stop identifier effect"); + identify_trigger_effect = IDENTIFY_TRIGGER_EFFECT_FINISH_STOP; + IdentifyStopHandler(identify); + break; + default: + PLAT_LOG("No identifier effect"); + } +} diff --git a/examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.h b/examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.h new file mode 100644 index 00000000000000..3d305601bc12f7 --- /dev/null +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/AppTask.h @@ -0,0 +1,93 @@ +/* + * 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. + */ + +#pragma once + +#include +#include + +#include "FreeRTOS.h" +#include "semphr.h" +#include "task.h" + +#include "AppEvent.h" +#include "LightingManager.h" + +#include + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) +#define APP_ERROR_ALLOCATION_FAILED CHIP_APPLICATION_ERROR(0x07) +struct Identify; + +class AppTask +{ + +public: + int StartAppTask(); + static void AppTaskMain(void * pvParameter); + + static AppTask & GetAppTask() { return sAppTask; } + + void PostLightActionRequest(int32_t aActor, LightingManager::Action_t aAction); + void PostEvent(const AppEvent * event); + + static void IdentifyStartHandler(::Identify *); + static void IdentifyStopHandler(::Identify *); + static void TriggerIdentifyEffectHandler(::Identify * identify); + +private: + friend AppTask & GetAppTask(void); + + int Init(); + + static void ActionInitiated(LightingManager::Action_t aAction, int32_t aActor); + static void ActionCompleted(LightingManager::Action_t aAction); + + void DispatchEvent(AppEvent * event); + static void UpdateClusterState(intptr_t context); + static void SingleButtonEventHandler(AppEvent * aEvent); + static void ButtonTimerEventHandler(AppEvent * aEvent); + + static void ButtonLeftEventHandler(Button_Handle handle, Button_EventMask events); + static void ButtonRightEventHandler(Button_Handle handle, Button_EventMask events); + static void TimerEventHandler(void * p_context); + + enum Function_t + { + kFunction_NoneSelected = 0, + kFunction_SoftwareUpdate = 0, + kFunction_FactoryReset, + kFunction_Invalid + } Function; + + Function_t mFunction; + bool mFunctionTimerActive; + + static AppTask sAppTask; +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.cpp b/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.cpp new file mode 100644 index 00000000000000..ed5fc52e7e5638 --- /dev/null +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.cpp @@ -0,0 +1,176 @@ +/* + * + * 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. + */ + +#include "LightingManager.h" + +#include "AppConfig.h" +#include "AppTask.h" +#include + +using namespace chip; +using namespace ::chip::DeviceLayer; + +LightingManager LightingManager::sLight; + +TimerHandle_t sLightTimer; + +CHIP_ERROR LightingManager::Init() +{ + // Create FreeRTOS sw timer for light timer. + sLightTimer = xTimerCreate("lightTmr", // Just a text name, not used by the RTOS kernel + 1, // == default timer period (mS) + false, // no timer reload (==one-shot) + (void *) this, // init timer id = light obj context + TimerEventHandler // timer callback handler + ); + + if (sLightTimer == NULL) + { + PLAT_LOG("sLightTimer timer create failed"); + } + + bool currentLedState; + // read current on/off value on endpoint one. + OnOffServer::Instance().getOnOffValue(1, ¤tLedState); + + mState = currentLedState ? kState_OnCompleted : kState_OffCompleted; + + return CHIP_NO_ERROR; +} + +void LightingManager::SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB) +{ + mActionInitiated_CB = aActionInitiated_CB; + mActionCompleted_CB = aActionCompleted_CB; +} + +bool LightingManager::IsActionInProgress() +{ + return (mState == kState_OffInitiated || mState == kState_OnInitiated); +} + +bool LightingManager::IsLightOn() +{ + return (mState == kState_OnCompleted); +} + +bool LightingManager::InitiateAction(int32_t aActor, Action_t aAction) +{ + bool action_initiated = false; + State_t new_state; + + // Initiate Turn On/Off Action only when the previous one is complete. + if (mState == kState_OffCompleted && aAction == ON_ACTION) + { + action_initiated = true; + + new_state = kState_OnInitiated; + } + else if (mState == kState_OnCompleted && aAction == OFF_ACTION) + { + action_initiated = true; + + new_state = kState_OffInitiated; + } + + if (action_initiated) + { + StartTimer(ACTUATOR_MOVEMENT_PERIOD_MS); + + // Since the timer started successfully, update the state and trigger callback + mState = new_state; + + if (mActionInitiated_CB) + { + mActionInitiated_CB(aAction, aActor); + } + } + + return action_initiated; +} + +void LightingManager::StartTimer(uint32_t aTimeoutMs) +{ + if (xTimerIsTimerActive(sLightTimer)) + { + PLAT_LOG("app timer already started!"); + CancelTimer(); + } + + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(sLightTimer, pdMS_TO_TICKS(aTimeoutMs), 100) != pdPASS) + { + PLAT_LOG("sLightTimer timer start() failed"); + } +} + +void LightingManager::CancelTimer(void) +{ + if (xTimerStop(sLightTimer, 0) == pdFAIL) + { + PLAT_LOG("sLightTimer stop() failed"); + } +} + +void LightingManager::TimerEventHandler(TimerHandle_t xTimer) +{ + // Get light obj context from timer id. + LightingManager * light = static_cast(pvTimerGetTimerID(xTimer)); + + // The timer event handler will be called in the context of the timer task + // once sLightTimer expires. Post an event to apptask queue with the actual handler + // so that the event can be handled in the context of the apptask. + AppEvent event; + event.Type = AppEvent::kEventType_AppEvent; + event.LightEvent.Context = light; + + event.Handler = ActuatorMovementTimerEventHandler; + + AppTask::GetAppTask().PostEvent(&event); +} + +void LightingManager::ActuatorMovementTimerEventHandler(AppEvent * aEvent) +{ + Action_t actionCompleted = INVALID_ACTION; + + LightingManager * light = static_cast(aEvent->LightEvent.Context); + + if (light->mState == kState_OffInitiated) + { + light->mState = kState_OffCompleted; + actionCompleted = OFF_ACTION; + OnOffServer::Instance().setOnOffValue(1, 0, false); + } + else if (light->mState == kState_OnInitiated) + { + light->mState = kState_OnCompleted; + actionCompleted = ON_ACTION; + OnOffServer::Instance().setOnOffValue(1, 1, false); + } + + if (actionCompleted != INVALID_ACTION) + { + if (light->mActionCompleted_CB) + { + light->mActionCompleted_CB(actionCompleted); + } + } +} diff --git a/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.h b/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.h new file mode 100644 index 00000000000000..818feed45ee87a --- /dev/null +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/LightingManager.h @@ -0,0 +1,82 @@ +/* + * + * 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. + */ + +#pragma once + +#include +#include + +#include "AppEvent.h" + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include + +#include + +class LightingManager +{ +public: + enum Action_t + { + ON_ACTION = 0, + OFF_ACTION, + + INVALID_ACTION + } Action; + + enum State_t + { + kState_OffInitiated = 0, + kState_OffCompleted, + kState_OnInitiated, + kState_OnCompleted, + } State; + + CHIP_ERROR Init(); + bool IsLightOn(); + bool IsActionInProgress(); + bool InitiateAction(int32_t aActor, Action_t aAction); + + typedef void (*Callback_fn_initiated)(Action_t, int32_t aActor); + typedef void (*Callback_fn_completed)(Action_t); + void SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB); + + static void OnTriggerOffWithEffect(OnOffEffect * effect); + +private: + friend LightingManager & LightMgr(void); + State_t mState; + + Callback_fn_initiated mActionInitiated_CB; + Callback_fn_completed mActionCompleted_CB; + + void CancelTimer(void); + void StartTimer(uint32_t aTimeoutMs); + + static void TimerEventHandler(TimerHandle_t xTimer); + static void ActuatorMovementTimerEventHandler(AppEvent * aEvent); + static void OffEffectTimerEventHandler(AppEvent * aEvent); + + static LightingManager sLight; +}; + +inline LightingManager & LightMgr(void) +{ + return LightingManager::sLight; +} diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp b/examples/lighting-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp similarity index 57% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp rename to examples/lighting-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp index ba3f7bd1c205f8..7bb20a45944545 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp @@ -1,7 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors - * Copyright 2021, Cypress Semiconductor Corporation (an Infineon company) + * 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. @@ -22,17 +21,12 @@ */ #include "AppConfig.h" -#include "Globals.h" -#include - -#include "ClusterManager.h" +#include "LightingManager.h" #include #include -#include -#include -#include -#include +#include +#include using namespace ::chip; using namespace ::chip::app::Clusters; @@ -40,35 +34,26 @@ using namespace ::chip::app::Clusters; void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size, uint8_t * value) { - EndpointId endpoint = attributePath.mEndpointId; ClusterId clusterId = attributePath.mClusterId; AttributeId attributeId = attributePath.mAttributeId; - PLAT_LOG("MatterPostAttributeChangeCallback - Cluster ID: " ChipLogFormatMEI - ", EndPoint ID: '0x%02x', Attribute ID: " ChipLogFormatMEI, - ChipLogValueMEI(clusterId), endpoint, ChipLogValueMEI(attributeId)); + ChipLogProgress(Zcl, "Cluster callback: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); - switch (clusterId) + if (clusterId == OnOff::Id && attributeId == OnOff::Attributes::OnOff::Id) { - case OnOff::Id: - ClusterMgr().OnOnOffPostAttributeChangeCallback(endpoint, attributeId, value); - break; - - case Identify::Id: - ClusterMgr().OnIdentifyPostAttributeChangeCallback(endpoint, attributeId, size, value); - break; - - case LevelControl::Id: - ClusterMgr().OnLevelControlAttributeChangeCallback(endpoint, attributeId, value); - break; - - case ColorControl::Id: - ClusterMgr().OnColorControlAttributeChangeCallback(endpoint, attributeId, value); - break; - default: - PLAT_LOG("Unhandled cluster ID: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); - break; + LightMgr().InitiateAction(AppEvent::kEventType_Light, *value ? LightingManager::ON_ACTION : LightingManager::OFF_ACTION); + } + else if (clusterId == Identify::Id) + { + ChipLogProgress(Zcl, "Identify attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", + ChipLogValueMEI(attributeId), type, *value, size); + } + else if (clusterId == Groups::Id) + { + ChipLogProgress(Zcl, "Groups attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", + ChipLogValueMEI(attributeId), type, *value, size); } } + /** @brief OnOff Cluster Init * * This function is called when a specific cluster is initialized. It gives the @@ -76,6 +61,13 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & * It is called exactly once for each endpoint where cluster is present. * * @param endpoint Ver.: always + * + * TODO Issue #3841 + * emberAfOnOffClusterInitCallback happens before the stack initialize the cluster + * attributes to the default value. + * The logic here expects something similar to the deprecated Plugins callback + * emberAfPluginOnOffClusterServerPostInitCallback. + * */ void emberAfOnOffClusterInitCallback(EndpointId endpoint) { diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/main.cpp b/examples/lighting-app/cc13x2x7_26x2x7/src/main.cpp similarity index 79% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/main.cpp rename to examples/lighting-app/cc13x2x7_26x2x7/src/main.cpp index 8311c8990aa5c6..4fdb88703acab6 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/main.cpp +++ b/examples/lighting-app/cc13x2x7_26x2x7/src/main.cpp @@ -21,8 +21,8 @@ #include -#include -#include +#include "AppConfig.h" +#include "AppTask.h" #include @@ -30,7 +30,6 @@ #include #include #include -#include #include #include @@ -38,7 +37,7 @@ #include #include -#define TOTAL_ICALL_HEAP_SIZE (0xc800) +#define TOTAL_ICALL_HEAP_SIZE (0xc600) using namespace ::chip; using namespace ::chip::Inet; @@ -52,12 +51,23 @@ uint32_t heapSize = TOTAL_ICALL_HEAP_SIZE; // ================================================================================ extern "C" void vApplicationStackOverflowHook(void) { - while (true) + while (1) { ; } } +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + // ================================================================================ // Main Code // ================================================================================ @@ -70,8 +80,6 @@ int main(void) NVS_init(); - UART_init(); - ECDH_init(); ECDSA_init(); @@ -85,13 +93,13 @@ int main(void) { // can't log until the kernel is started // PLAT_LOG("GetAppTask().StartAppTask() failed"); - while (true) + while (1) ; } vTaskStartScheduler(); // Should never get here. - while (true) + while (1) ; } diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/third_party/connectedhomeip b/examples/lighting-app/cc13x2x7_26x2x7/third_party/connectedhomeip similarity index 100% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/third_party/connectedhomeip rename to examples/lighting-app/cc13x2x7_26x2x7/third_party/connectedhomeip diff --git a/examples/lighting-app/lighting-common/BUILD.gn b/examples/lighting-app/lighting-common/BUILD.gn index a7e00eabe34b56..e983b3e0e0f11c 100644 --- a/examples/lighting-app/lighting-common/BUILD.gn +++ b/examples/lighting-app/lighting-common/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") config("config") { diff --git a/examples/lighting-app/qpg/zap/BUILD.gn b/examples/lighting-app/qpg/zap/BUILD.gn index b62bf14bf03859..ec69db0b412a8c 100644 --- a/examples/lighting-app/qpg/zap/BUILD.gn +++ b/examples/lighting-app/qpg/zap/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("zap") { diff --git a/examples/lighting-app/silabs/SiWx917/include/AppConfig.h b/examples/lighting-app/silabs/SiWx917/include/AppConfig.h index 0b916a32f8452c..5352f6742a8e76 100644 --- a/examples/lighting-app/silabs/SiWx917/include/AppConfig.h +++ b/examples/lighting-app/silabs/SiWx917/include/AppConfig.h @@ -19,7 +19,7 @@ #pragma once -#include "siwx917_utils.h" +#include "silabs_utils.h" // ---- Lighting Example App Config ---- diff --git a/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp b/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp index 15474dc8527065..d57caba69674f0 100644 --- a/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp +++ b/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp @@ -43,6 +43,7 @@ using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -240,12 +241,12 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) AppEvent button_event = {}; button_event.Type = AppEvent::kEventType_Button; button_event.ButtonEvent.Action = btnAction; - if (button == SIWx917_BTN1 && btnAction == SL_SIMPLE_BUTTON_PRESSED) + if (button == SIWx917_BTN1 && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = LightActionEventHandler; sAppTask.PostEvent(&button_event); } - else if (button == SIWx917_BTN0 && btnAction == SL_SIMPLE_BUTTON_PRESSED) + else if (button == SIWx917_BTN0 && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = BaseApplication::ButtonHandler; sAppTask.PostEvent(&button_event); diff --git a/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.matter b/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.matter index 26d34db585312b..2bf7df26909899 100644 --- a/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.matter +++ b/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.matter @@ -1477,6 +1477,53 @@ server cluster UserLabel = 65 { readonly attribute int16u clusterRevision = 65533; } +/** Allows servers to ensure that listed clients are notified when a server is available for communication. */ +server cluster IcdManagement = 70 { + bitmap ICDManagementFeature : BITMAP32 { + kCheckInProtocolSupport = 0x1; + } + + fabric_scoped struct MonitoringRegistrationStruct { + fabric_sensitive node_id checkInNodeID = 1; + fabric_sensitive int64u monitoredSubject = 2; + fabric_sensitive octet_string<16> key = 3; + fabric_idx fabricIndex = 254; + } + + readonly attribute int32u idleModeInterval = 0; + readonly attribute int32u activeModeInterval = 1; + readonly attribute int16u activeModeThreshold = 2; + readonly attribute access(read: administer) MonitoringRegistrationStruct registeredClients[] = 3; + readonly attribute access(read: administer) int32u ICDCounter = 4; + readonly attribute int16u clientsSupportedPerFabric = 5; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct RegisterClientRequest { + node_id checkInNodeID = 0; + INT64U monitoredSubject = 1; + OCTET_STRING<16> key = 2; + optional OCTET_STRING<16> verificationKey = 3; + } + + request struct UnregisterClientRequest { + node_id checkInNodeID = 0; + optional OCTET_STRING<16> key = 1; + } + + response struct RegisterClientResponse = 1 { + INT32U ICDCounter = 0; + } + + fabric command access(invoke: manage) RegisterClient(RegisterClientRequest): RegisterClientResponse = 0; + fabric command access(invoke: manage) UnregisterClient(UnregisterClientRequest): DefaultSuccess = 2; + command access(invoke: manage) StayActiveRequest(): DefaultSuccess = 3; +} + /** Attributes and commands for controlling the color properties of a color-capable light. */ server cluster ColorControl = 768 { enum ColorLoopAction : ENUM8 { @@ -1975,6 +2022,21 @@ endpoint 0 { ram attribute featureMap default = 0; ram attribute clusterRevision default = 1; } + + server cluster IcdManagement { + ram attribute idleModeInterval default = 500; + ram attribute activeModeInterval default = 300; + ram attribute activeModeThreshold default = 300; + callback attribute registeredClients; + ram attribute ICDCounter; + ram attribute clientsSupportedPerFabric default = 1; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute eventList; + callback attribute attributeList; + ram attribute featureMap default = 1; + ram attribute clusterRevision default = 1; + } } endpoint 1 { device type dimmablelight = 257, version 1; diff --git a/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.zap b/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.zap index 60a5e50ba52621..a301ef4c0d33cf 100644 --- a/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.zap +++ b/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.zap @@ -16,6 +16,12 @@ } ], "package": [ + { + "pathRelativity": "relativeToZap", + "path": "../../../../../src/app/zap-templates/app-templates.json", + "type": "gen-templates-json", + "version": "chip-v1" + }, { "pathRelativity": "relativeToZap", "path": "../../../../../src/app/zap-templates/zcl/zcl.json", @@ -23,12 +29,6 @@ "category": "matter", "version": 1, "description": "Matter SDK ZCL data" - }, - { - "pathRelativity": "relativeToZap", - "path": "../../../../../src/app/zap-templates/app-templates.json", - "type": "gen-templates-json", - "version": "chip-v1" } ], "endpointTypes": [ @@ -5261,6 +5261,286 @@ "reportableChange": 0 } ] + }, + { + "name": "ICD Management", + "code": 70, + "mfgCode": null, + "define": "ICD_MANAGEMENT_CLUSTER", + "side": "client", + "enabled": 0, + "commands": [ + { + "name": "RegisterClient", + "code": 0, + "mfgCode": null, + "source": "client", + "incoming": 1, + "outgoing": 0 + }, + { + "name": "UnregisterClient", + "code": 2, + "mfgCode": null, + "source": "client", + "incoming": 1, + "outgoing": 0 + }, + { + "name": "StayActiveRequest", + "code": 3, + "mfgCode": null, + "source": "client", + "incoming": 1, + "outgoing": 0 + } + ], + "attributes": [ + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "client", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "client", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "ICD Management", + "code": 70, + "mfgCode": null, + "define": "ICD_MANAGEMENT_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "RegisterClientResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "incoming": 1, + "outgoing": 1 + } + ], + "attributes": [ + { + "name": "IdleModeInterval", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "500", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveModeInterval", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "300", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveModeThreshold", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "300", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "RegisteredClients", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ICDCounter", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientsSupportedPerFabric", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "EventList", + "code": 65530, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] } ] }, diff --git a/examples/lighting-app/silabs/efr32/include/AppConfig.h b/examples/lighting-app/silabs/efr32/include/AppConfig.h index 1cb27c78ae654c..4aee946506f022 100644 --- a/examples/lighting-app/silabs/efr32/include/AppConfig.h +++ b/examples/lighting-app/silabs/efr32/include/AppConfig.h @@ -19,7 +19,7 @@ #pragma once -#include "efr32_utils.h" +#include "silabs_utils.h" // ---- Lighting Example App Config ---- diff --git a/examples/lighting-app/silabs/efr32/include/AppTask.h b/examples/lighting-app/silabs/efr32/include/AppTask.h index f8ad1b45367a0b..9c988e9b3d8807 100644 --- a/examples/lighting-app/silabs/efr32/include/AppTask.h +++ b/examples/lighting-app/silabs/efr32/include/AppTask.h @@ -68,7 +68,7 @@ class AppTask : public BaseApplication static void AppTaskMain(void * pvParameter); CHIP_ERROR StartAppTask(); -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + /** * @brief Event handler when a button is pressed * Function posts an event for button processing @@ -78,7 +78,7 @@ class AppTask : public BaseApplication * SL_SIMPLE_BUTTON_RELEASED or SL_SIMPLE_BUTTON_DISABLED */ static void ButtonEventHandler(uint8_t button, uint8_t btnAction); -#endif + /** * @brief Callback called by the identify-server when an identify command is received * diff --git a/examples/lighting-app/silabs/efr32/src/AppTask.cpp b/examples/lighting-app/silabs/efr32/src/AppTask.cpp old mode 100755 new mode 100644 index a8c63c8e61b1d0..f40e13a7c01135 --- a/examples/lighting-app/silabs/efr32/src/AppTask.cpp +++ b/examples/lighting-app/silabs/efr32/src/AppTask.cpp @@ -46,14 +46,12 @@ #define LIGHT_LED 0 #endif -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT - #define APP_FUNCTION_BUTTON 0 #define APP_LIGHT_SWITCH 1 -#endif using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -132,9 +130,7 @@ AppTask AppTask::sAppTask; CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); -#endif #ifdef DISPLAY_ENABLED GetLCD().Init((uint8_t *) "Lighting-App"); @@ -241,13 +237,11 @@ void AppTask::LightActionEventHandler(AppEvent * aEvent) action = static_cast(aEvent->LightEvent.Action); actor = aEvent->LightEvent.Actor; } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT else if (aEvent->Type == AppEvent::kEventType_Button) { action = (LightMgr().IsLightOn()) ? LightingManager::OFF_ACTION : LightingManager::ON_ACTION; actor = AppEvent::kEventType_Button; } -#endif else { err = APP_ERROR_UNHANDLED_EVENT; @@ -263,14 +257,14 @@ void AppTask::LightActionEventHandler(AppEvent * aEvent) } } } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) { AppEvent button_event = {}; button_event.Type = AppEvent::kEventType_Button; button_event.ButtonEvent.Action = btnAction; - if (button == APP_LIGHT_SWITCH && btnAction == SL_SIMPLE_BUTTON_PRESSED) + if (button == APP_LIGHT_SWITCH && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = LightActionEventHandler; AppTask::GetAppTask().PostEvent(&button_event); @@ -281,7 +275,6 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) AppTask::GetAppTask().PostEvent(&button_event); } } -#endif void AppTask::ActionInitiated(LightingManager::Action_t aAction, int32_t aActor) { @@ -294,12 +287,11 @@ void AppTask::ActionInitiated(LightingManager::Action_t aAction, int32_t aActor) #ifdef DISPLAY_ENABLED sAppTask.GetLCD().WriteDemoUI(lightOn); #endif -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + if (aActor == AppEvent::kEventType_Button) { sAppTask.mSyncClusterToButtonAction = true; } -#endif } void AppTask::ActionCompleted(LightingManager::Action_t aAction) @@ -313,13 +305,12 @@ void AppTask::ActionCompleted(LightingManager::Action_t aAction) { SILABS_LOG("Light OFF") } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + if (sAppTask.mSyncClusterToButtonAction) { chip::DeviceLayer::PlatformMgr().ScheduleWork(UpdateClusterState, reinterpret_cast(nullptr)); sAppTask.mSyncClusterToButtonAction = false; } -#endif } void AppTask::PostLightActionRequest(int32_t aActor, LightingManager::Action_t aAction) diff --git a/examples/lock-app/cc13x2x7_26x2x7/BUILD.gn b/examples/lock-app/cc13x2x7_26x2x7/BUILD.gn index ba2b327339e516..0bd2dfef85d615 100644 --- a/examples/lock-app/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/lock-app/cc13x2x7_26x2x7/BUILD.gn @@ -29,7 +29,7 @@ assert(current_os == "freertos") project_dir = "${chip_root}/examples/lock-app/cc13x2x7_26x2x7" ti_simplelink_sdk("sdk") { - include_dirs = [ "${project_dir}/main/include" ] + include_dirs = [ "${project_dir}/include" ] public_configs = [ ":lock_app_config" ] } @@ -75,16 +75,17 @@ ti_simplelink_executable("lock_app") { sources = [ "${chip_root}/examples/providers/DeviceInfoProviderImpl.cpp", - "${project_dir}/main/AppTask.cpp", - "${project_dir}/main/BoltLockManager.cpp", - "${project_dir}/main/ZclCallbacks.cpp", - "${project_dir}/main/main.cpp", + "${project_dir}/src/AppTask.cpp", + "${project_dir}/src/LockManager.cpp", + "${project_dir}/src/ZclCallbacks.cpp", + "${project_dir}/src/main.cpp", ] deps = [ ":sdk", ":sysconfig", "${chip_root}/examples/lock-app/lock-common", + "${chip_root}/examples/platform/cc13x2_26x2:cc13x2_26x2-attestation-credentials", "${chip_root}/src/lib", ] @@ -96,7 +97,6 @@ ti_simplelink_executable("lock_app") { include_dirs = [ "${project_dir}", - "${project_dir}/main", "${chip_root}/examples/providers/", ] diff --git a/examples/lock-app/cc13x2x7_26x2x7/args.gni b/examples/lock-app/cc13x2x7_26x2x7/args.gni index 58a0bbbf2f366b..bd3e05a0055114 100644 --- a/examples/lock-app/cc13x2x7_26x2x7/args.gni +++ b/examples/lock-app/cc13x2x7_26x2x7/args.gni @@ -29,8 +29,11 @@ lwip_debug = false chip_enable_ota_requestor = true +chip_openthread_ftd = false +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2" + # Disable CHIP Logging -#chip_progress_logging = false +chip_progress_logging = false chip_detail_logging = false chip_automation_logging = false @@ -41,8 +44,6 @@ chip_config_network_layer_ble = true # INCLUDE_xSemaphoreGetMutexHolder chip_stack_lock_tracking = "none" -chip_openthread_ftd = false - matter_device_vid = "0xFFF1" matter_device_pid = "0x8006" matter_software_ver = "0x0001" diff --git a/examples/lock-app/cc13x2x7_26x2x7/chip.syscfg b/examples/lock-app/cc13x2x7_26x2x7/chip.syscfg index b55c57b9c364be..47cd09c1a31165 100644 --- a/examples/lock-app/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/lock-app/cc13x2x7_26x2x7/chip.syscfg @@ -133,8 +133,8 @@ UART1.$name = "CONFIG_UART_DEBUG"; /* TRNG */ TRNG1.$name = "CONFIG_TRNG_0"; -TRNG2.$name = "CONFIG_TRNG_1"; -TRNG3.$name = "CONFIG_TRNG_APP"; +TRNG2.$name = "CONFIG_TRNG_APP"; +TRNG3.$name = "CONFIG_TRNG_THREAD"; RTOS.name = "FreeRTOS"; @@ -152,6 +152,8 @@ ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; +ble.advSet1.advParam1.primIntMin = 100; +ble.advSet1.advParam1.primIntMax = 200; /* DMM */ dmm.project = "ti_thread_thermostat_remote_display"; diff --git a/examples/lock-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h b/examples/lock-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h new file mode 100644 index 00000000000000..a808f37a72d7b5 --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/include/CHIPProjectConfig.h @@ -0,0 +1,130 @@ +/* + * 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. + * + */ + +#ifndef CHIP_PROJECT_CONFIG_H +#define CHIP_PROJECT_CONFIG_H + +#if BUILD_RELEASE // release build +// Note: Default Pairing/PIN/Serial Numbers being used. These should not be enabled for production builds +#endif // BUILD_RELEASE + +// Use a default pairing code if one hasn't been provisioned in flash. +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 + +// Use a default pairing code if one hasn't been provisioned in flash. +#define CHIP_DEVICE_CONFIG_USE_TEST_PAIRING_CODE "CHIPUS" + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in CHIP NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds 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 versions. + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 +#endif + +/** + * Values set by args.gni: + * CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID + * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + */ + +/** + * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + * + * Enable support for CHIP-over-BLE (CHIPOBLE). + */ +#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 + +/** + * CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC + * + * Enables synchronizing the device's real time clock with a remote CHIP Time service + * using the CHIP Time Sync protocol. + */ +// #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) + +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 1 + +/** + * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT + * + * Enable the OpenThread SRP client to allow for CHIP device discovery. + */ +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 + +/** + * CHIP_CONFIG_EVENT_LOGGING_DEFAULT_IMPORTANCE + * + * For a development build, set the default importance of events to be logged as Debug. + * Since debug is the lowest importance level, this means all standard, critical, info and + * debug importance level vi events get logged. + */ +#if BUILD_RELEASE +#define CHIP_CONFIG_EVENT_LOGGING_DEFAULT_IMPORTANCE chip::Profiles::DataManagement::Production +#else +#define CHIP_CONFIG_EVENT_LOGGING_DEFAULT_IMPORTANCE chip::Profiles::DataManagement::Debug +#endif // BUILD_RELEASE + +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 + +/** + * @def CHIP_IM_MAX_NUM_COMMAND_HANDLER + * + * @brief Defines the maximum number of CommandHandler, limits the number of active commands transactions on server. + */ +#define CHIP_IM_MAX_NUM_COMMAND_HANDLER 2 + +/** + * @def CHIP_IM_MAX_NUM_WRITE_HANDLER + * + * @brief Defines the maximum number of WriteHandler, limits the number of active write transactions on server. + */ +#define CHIP_IM_MAX_NUM_WRITE_HANDLER 2 + +#endif // CHIP_PROJECT_CONFIG_H diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppConfig.h b/examples/lock-app/cc13x2x7_26x2x7/src/AppConfig.h similarity index 74% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppConfig.h rename to examples/lock-app/cc13x2x7_26x2x7/src/AppConfig.h index f7302b6efd10cd..a818b21d641875 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppConfig.h +++ b/examples/lock-app/cc13x2x7_26x2x7/src/AppConfig.h @@ -1,6 +1,5 @@ /* * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,4 +18,18 @@ #ifndef APP_CONFIG_H #define APP_CONFIG_H +// Logging +#ifdef __cplusplus +extern "C" { +#endif + +int cc13xx_26xxLogInit(void); +void cc13xx_26xxLog(const char * aFormat, ...); +#define PLAT_LOG(...) cc13xx_26xxLog(__VA_ARGS__); + +#define ACTUATOR_MOVEMENT_PERIOD_MS 1000 + +#ifdef __cplusplus +} +#endif #endif // APP_CONFIG_H diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppEvent.h b/examples/lock-app/cc13x2x7_26x2x7/src/AppEvent.h similarity index 86% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppEvent.h rename to examples/lock-app/cc13x2x7_26x2x7/src/AppEvent.h index ad9e93ee3ad1a5..dc4ce143338e1e 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppEvent.h +++ b/examples/lock-app/cc13x2x7_26x2x7/src/AppEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2018 Nest Labs, Inc. + * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -30,6 +30,8 @@ struct AppEvent kEventType_ButtonLeft, kEventType_ButtonRight, kEventType_AppEvent, + kEventType_IdentifyStart, + kEventType_IdentifyStop, }; enum AppEventButtonType @@ -52,6 +54,12 @@ struct AppEvent { void * Context; } BoltLockEvent; + + struct + { + uint8_t Action; + int32_t Actor; + } LockEvent; }; EventHandler Handler; diff --git a/examples/lock-app/cc13x2x7_26x2x7/src/AppTask.cpp b/examples/lock-app/cc13x2x7_26x2x7/src/AppTask.cpp new file mode 100644 index 00000000000000..772070fc7a0eab --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/src/AppTask.cpp @@ -0,0 +1,561 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020 Texas Instruments Incorporated + * 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 "FreeRTOS.h" + +#include +#include + +#include +#include + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +#include +#include +#include +#include +#include +#endif + +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include + +/* syscfg */ +#include + +#define APP_TASK_STACK_SIZE (4096) +#define APP_TASK_PRIORITY 4 +#define APP_EVENT_QUEUE_SIZE 10 + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; +using namespace ::chip::app::Clusters::DoorLock; + +static TaskHandle_t sAppTaskHandle; +static QueueHandle_t sAppEventQueue; + +static LED_Handle sAppRedHandle; +static LED_Handle sAppGreenHandle; +static Button_Handle sAppLeftHandle; +static Button_Handle sAppRightHandle; +static DeviceInfoProviderImpl sExampleDeviceInfoProvider; + +AppTask AppTask::sAppTask; + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +static DefaultOTARequestor sRequestorCore; +static DefaultOTARequestorStorage sRequestorStorage; +static DefaultOTARequestorDriver sRequestorUser; +static BDXDownloader sDownloader; +static OTAImageProcessorImpl sImageProcessor; + +void InitializeOTARequestor(void) +{ + // Initialize and interconnect the Requestor and Image Processor objects + SetRequestorInstance(&sRequestorCore); + + sRequestorStorage.Init(Server::GetInstance().GetPersistentStorage()); + sRequestorCore.Init(Server::GetInstance(), sRequestorStorage, sRequestorUser, sDownloader); + sImageProcessor.SetOTADownloader(&sDownloader); + sDownloader.SetImageProcessorDelegate(&sImageProcessor); + sRequestorUser.Init(&sRequestorCore, &sImageProcessor); +} +#endif + +::Identify stIdentify = { 0, AppTask::IdentifyStartHandler, AppTask::IdentifyStopHandler, + EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, AppTask::TriggerIdentifyEffectHandler }; + +int AppTask::StartAppTask() +{ + int ret = 0; + + sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); + if (sAppEventQueue == NULL) + { + PLAT_LOG("Failed to allocate app event queue"); + while (1) + ; + } + + // Start App task. + if (xTaskCreate(AppTaskMain, "APP", APP_TASK_STACK_SIZE / sizeof(StackType_t), NULL, APP_TASK_PRIORITY, &sAppTaskHandle) != + pdPASS) + { + PLAT_LOG("Failed to create app task"); + while (1) + ; + } + return ret; +} + +void uiLocking(void) +{ + PLAT_LOG("Lock initiated"); + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 50 /* ms */, LED_BLINK_FOREVER); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppRedHandle, 110 /* ms */, LED_BLINK_FOREVER); +} + +void uiLocked(void) +{ + PLAT_LOG("Lock completed"); + LED_stopBlinking(sAppGreenHandle); + LED_setOff(sAppGreenHandle); + LED_stopBlinking(sAppRedHandle); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); +} + +void uiUnlocking(void) +{ + PLAT_LOG("Unlock initiated"); + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 50 /* ms */, LED_BLINK_FOREVER); + LED_setOn(sAppRedHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppRedHandle, 110 /* ms */, LED_BLINK_FOREVER); +} + +void uiUnlocked(void) +{ + PLAT_LOG("Unlock completed"); + LED_stopBlinking(sAppGreenHandle); + LED_setOff(sAppGreenHandle); + LED_stopBlinking(sAppRedHandle); + LED_setOff(sAppRedHandle); +} + +int AppTask::Init() +{ + LED_Params ledParams; + Button_Params buttonParams; + + cc13xx_26xxLogInit(); + + // Init Chip memory management before the stack + Platform::MemoryInit(); + + CHIP_ERROR ret = PlatformMgr().InitChipStack(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("PlatformMgr().InitChipStack() failed"); + while (1) + ; + } + + ret = ThreadStackMgr().InitThreadStack(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("ThreadStackMgr().InitThreadStack() failed"); + while (1) + ; + } +#if CHIP_DEVICE_CONFIG_THREAD_FTD + ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); +#else + ret = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice); +#endif + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("ConnectivityMgr().SetThreadDeviceType() failed"); + while (1) + ; + } + + ret = PlatformMgr().StartEventLoopTask(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("PlatformMgr().StartEventLoopTask() failed"); + while (1) + ; + } + + ret = ThreadStackMgrImpl().StartThreadTask(); + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("ThreadStackMgr().StartThreadTask() failed"); + while (1) + ; + } + + // Init ZCL Data Model and start server + PLAT_LOG("Initialize Server"); + static CommonCaseDeviceServerInitParams initParams; + (void) initParams.InitializeStaticResourcesBeforeServerInit(); + + // Initialize info provider + sExampleDeviceInfoProvider.SetStorageDelegate(initParams.persistentStorageDelegate); + SetDeviceInfoProvider(&sExampleDeviceInfoProvider); + + Server::GetInstance().Init(initParams); + + // Initialize device attestation config +#ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS + SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); +#else + SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif + + // Initialize LEDs + PLAT_LOG("Initialize LEDs"); + LED_init(); + + LED_Params_init(&ledParams); // default PWM LED + sAppRedHandle = LED_open(CONFIG_LED_RED, &ledParams); + LED_setOff(sAppRedHandle); + + LED_Params_init(&ledParams); // default PWM LED + sAppGreenHandle = LED_open(CONFIG_LED_GREEN, &ledParams); + LED_setOff(sAppGreenHandle); + + // Initialize buttons + PLAT_LOG("Initialize buttons"); + Button_init(); + + Button_Params_init(&buttonParams); + buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; + buttonParams.longPressDuration = 1000U; // ms + sAppLeftHandle = Button_open(CONFIG_BTN_LEFT, &buttonParams); + Button_setCallback(sAppLeftHandle, ButtonLeftEventHandler); + + Button_Params_init(&buttonParams); + buttonParams.buttonEventMask = Button_EV_CLICKED | Button_EV_LONGCLICKED; + buttonParams.longPressDuration = 1000U; // ms + sAppRightHandle = Button_open(CONFIG_BTN_RIGHT, &buttonParams); + Button_setCallback(sAppRightHandle, ButtonRightEventHandler); + + PlatformMgr().LockChipStack(); + { + uint8_t numberOfCredentialsPerUser = 0; + uint16_t numberOfUsers = 0; + uint8_t numberOfWeekdaySchedulesPerUser = 0; + uint8_t numberOfYeardaySchedulesPerUser = 0; + uint8_t numberOfHolidaySchedules = 0; + chip::app::DataModel::Nullable state; + EndpointId endpointId{ 1 }; + + if (!DoorLockServer::Instance().GetNumberOfCredentialsSupportedPerUser(endpointId, numberOfCredentialsPerUser)) + { + numberOfCredentialsPerUser = 5; + } + + if (!DoorLockServer::Instance().GetNumberOfUserSupported(endpointId, numberOfUsers)) + { + numberOfUsers = 10; + } + + if (!DoorLockServer::Instance().GetNumberOfWeekDaySchedulesPerUserSupported(endpointId, numberOfWeekdaySchedulesPerUser)) + { + numberOfWeekdaySchedulesPerUser = 10; + } + + if (!DoorLockServer::Instance().GetNumberOfYearDaySchedulesPerUserSupported(endpointId, numberOfYeardaySchedulesPerUser)) + { + numberOfYeardaySchedulesPerUser = 10; + } + + if (!DoorLockServer::Instance().GetNumberOfHolidaySchedulesSupported(endpointId, numberOfHolidaySchedules)) + { + numberOfHolidaySchedules = 10; + } + + Attributes::LockState::Get(endpointId, state); + ret = LockMgr().Init(state, + CC13X2_26X2DoorLock::LockInitParams::ParamBuilder() + .SetNumberOfUsers(numberOfUsers) + .SetNumberOfCredentialsPerUser(numberOfCredentialsPerUser) + .SetNumberOfWeekdaySchedulesPerUser(numberOfWeekdaySchedulesPerUser) + .SetNumberOfYeardaySchedulesPerUser(numberOfYeardaySchedulesPerUser) + .SetNumberOfHolidaySchedules(numberOfHolidaySchedules) + .GetLockParam()); + + if (state.Value() == DlLockState::kLocked) + { + uiLocked(); + } + else + { + uiUnlocked(); + } + } + + PlatformMgr().UnlockChipStack(); + + if (ret != CHIP_NO_ERROR) + { + PLAT_LOG("LockMgr().Init() failed"); + while (1) + ; + } + + LockMgr().SetCallbacks(ActionInitiated, ActionCompleted); + + ConfigurationMgr().LogDeviceConfig(); + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + InitializeOTARequestor(); +#endif + // QR code will be used with CHIP Tool + PrintOnboardingCodes(RendezvousInformationFlags(RendezvousInformationFlag::kBLE)); + + return 0; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + AppEvent event; + + sAppTask.Init(); + + LockMgr().ReadConfigValues(); + + while (1) + { + /* Task pend until we have stuff to do */ + if (xQueueReceive(sAppEventQueue, &event, portMAX_DELAY) == pdTRUE) + { + sAppTask.DispatchEvent(&event); + } + } +} + +void AppTask::ButtonLeftEventHandler(Button_Handle handle, Button_EventMask events) +{ + AppEvent event; + event.Type = AppEvent::kEventType_ButtonLeft; + + if (events & Button_EV_CLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_Clicked; + } + else if (events & Button_EV_LONGCLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_LongClicked; + } + // button callbacks are in ISR context + if (xQueueSendFromISR(sAppEventQueue, &event, NULL) != pdPASS) + { + /* Failed to post the message */ + } +} + +void AppTask::ButtonRightEventHandler(Button_Handle handle, Button_EventMask events) +{ + AppEvent event; + event.Type = AppEvent::kEventType_ButtonRight; + + if (events & Button_EV_CLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_Clicked; + } + else if (events & Button_EV_LONGCLICKED) + { + event.ButtonEvent.Type = AppEvent::kAppEventButtonType_LongClicked; + } + // button callbacks are in ISR context + if (xQueueSendFromISR(sAppEventQueue, &event, NULL) != pdPASS) + { + /* Failed to post the message */ + } +} + +void AppTask::ActionInitiated(LockManager::Action_t aAction) +{ + if (aAction == LockManager::LOCK_ACTION) + { + uiLocking(); + } + else if (aAction == LockManager::UNLOCK_ACTION) + { + uiUnlocking(); + } +} + +void AppTask::ActionCompleted(LockManager::Action_t aAction) +{ + if (aAction == LockManager::LOCK_ACTION) + { + uiLocked(); + } + else if (aAction == LockManager::UNLOCK_ACTION) + { + uiUnlocked(); + } +} + +void AppTask::PostEvent(const AppEvent * aEvent) +{ + if (sAppEventQueue != NULL) + { + BaseType_t status; + if (xPortIsInsideInterrupt()) + { + BaseType_t higherPrioTaskWoken = pdFALSE; + status = xQueueSendFromISR(sAppEventQueue, aEvent, &higherPrioTaskWoken); + +#ifdef portYIELD_FROM_ISR + portYIELD_FROM_ISR(higherPrioTaskWoken); +#elif portEND_SWITCHING_ISR // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + portEND_SWITCHING_ISR(higherPrioTaskWoken); +#else // portYIELD_FROM_ISR or portEND_SWITCHING_ISR +#error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR" +#endif // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + } + else + { + status = xQueueSend(sAppEventQueue, aEvent, 1); + } + + if (status != pdTRUE) + { + PLAT_LOG("Failed to post event to app task event queue"); + } + } + else + { + PLAT_LOG("Event Queue is NULL should never happen"); + } +} + +void AppTask::DispatchEvent(AppEvent * aEvent) +{ + switch (aEvent->Type) + { + case AppEvent::kEventType_ButtonLeft: + if (AppEvent::kAppEventButtonType_Clicked == aEvent->ButtonEvent.Type) + { + LockMgr().InitiateAction(LockManager::UNLOCK_ACTION); + } + else if (AppEvent::kAppEventButtonType_LongClicked == aEvent->ButtonEvent.Type) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + break; + + case AppEvent::kEventType_ButtonRight: + if (AppEvent::kAppEventButtonType_Clicked == aEvent->ButtonEvent.Type) + { + LockMgr().InitiateAction(LockManager::LOCK_ACTION); + } + else if (AppEvent::kAppEventButtonType_LongClicked == aEvent->ButtonEvent.Type) + { + // Enable BLE advertisements + if (!ConnectivityMgr().IsBLEAdvertisingEnabled()) + { + if (Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() == CHIP_NO_ERROR) + { + PLAT_LOG("Enabled BLE Advertisements"); + } + else + { + PLAT_LOG("OpenBasicCommissioningWindow() failed"); + } + } + else + { + // Disable BLE advertisements + ConnectivityMgr().SetBLEAdvertisingEnabled(false); + PLAT_LOG("Disabled BLE Advertisements"); + } + } + break; + + case AppEvent::kEventType_IdentifyStart: + LED_setOn(sAppGreenHandle, LED_BRIGHTNESS_MAX); + LED_startBlinking(sAppGreenHandle, 500, LED_BLINK_FOREVER); + PLAT_LOG("Identify started"); + break; + + case AppEvent::kEventType_IdentifyStop: + LED_stopBlinking(sAppGreenHandle); + + LED_setOff(sAppGreenHandle); + PLAT_LOG("Identify stopped"); + break; + + case AppEvent::kEventType_AppEvent: + if (NULL != aEvent->Handler) + { + aEvent->Handler(aEvent); + } + break; + + case AppEvent::kEventType_None: + default: + break; + } +} + +void AppTask::IdentifyStartHandler(::Identify *) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStart; + sAppTask.PostEvent(&event); +} + +void AppTask::IdentifyStopHandler(::Identify *) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStop; + sAppTask.PostEvent(&event); +} + +void AppTask::TriggerIdentifyEffectHandler(::Identify * identify) +{ + switch (identify->mCurrentEffectIdentifier) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + PLAT_LOG("Starting blink identifier effect"); + IdentifyStartHandler(identify); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + PLAT_LOG("Breathe identifier effect not implemented"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + PLAT_LOG("Okay identifier effect not implemented"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + PLAT_LOG("Channel Change identifier effect not implemented"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: + PLAT_LOG("Finish identifier effect not implemented"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: + PLAT_LOG("Stop identifier effect"); + IdentifyStopHandler(identify); + break; + default: + PLAT_LOG("No identifier effect"); + } +} diff --git a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppTask.h b/examples/lock-app/cc13x2x7_26x2x7/src/AppTask.h similarity index 60% rename from examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppTask.h rename to examples/lock-app/cc13x2x7_26x2x7/src/AppTask.h index 002e1b3f70557c..15939e6581737b 100644 --- a/examples/all-clusters-minimal-app/cc13x2x7_26x2x7/main/include/AppTask.h +++ b/examples/lock-app/cc13x2x7_26x2x7/src/AppTask.h @@ -16,8 +16,7 @@ * limitations under the License. */ -#ifndef APP_TASK_H -#define APP_TASK_H +#pragma once #include #include @@ -27,22 +26,44 @@ #include "task.h" #include "AppEvent.h" +#include "LockManager.h" #include +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) +#define APP_ERROR_ALLOCATION_FAILED CHIP_APPLICATION_ERROR(0x07) + +struct Identify; + class AppTask { + public: int StartAppTask(); static void AppTaskMain(void * pvParameter); + void PostLockActionRequest(int32_t aActor, LockManager::Action_t aAction); void PostEvent(const AppEvent * event); + static void IdentifyStartHandler(::Identify *); + static void IdentifyStopHandler(::Identify *); + static void TriggerIdentifyEffectHandler(::Identify * identify); + private: friend AppTask & GetAppTask(void); int Init(); + // should this be done by BoltLock Manager? I don't want to unravel this spaghetti quite yet + static void ActionInitiated(LockManager::Action_t aAction); + static void ActionCompleted(LockManager::Action_t aAction); + void DispatchEvent(AppEvent * event); static void ButtonLeftEventHandler(Button_Handle handle, Button_EventMask events); @@ -60,6 +81,7 @@ class AppTask Function_t mFunction; bool mFunctionTimerActive; + bool mSyncClusterToButtonAction; static AppTask sAppTask; }; @@ -68,5 +90,3 @@ inline AppTask & GetAppTask(void) { return AppTask::sAppTask; } - -#endif // APP_TASK_H diff --git a/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.cpp b/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.cpp new file mode 100644 index 00000000000000..acd9c00b41c4d5 --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.cpp @@ -0,0 +1,703 @@ +/* + * + * 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. + */ + +#include "LockManager.h" + +#include "AppConfig.h" +#include "AppTask.h" +#include "platform/KeyValueStoreManager.h" +#include +#include +#include +#include + +LockManager LockManager::sLock; + +TimerHandle_t sLockTimer; + +using namespace CC13X2_26X2DoorLock::LockInitParams; +using namespace chip::DeviceLayer::PersistedStorage; + +// persisted storage keys +const char LockUser[] = "a/lu"; +const char Credential[] = "a/c"; +const char LockUserName[] = "a/lun"; +const char CredentialData[] = "a/cd"; +const char UserCredentials[] = "a/uc"; +const char WeekDaySchedules[] = "a/wds"; +const char YearDaySchedules[] = "a/yds"; +const char HolidaySchedules[] = "a/hs"; + +CHIP_ERROR LockManager::Init(chip::app::DataModel::Nullable state, LockParam lockParam) +{ + + LockParams = lockParam; + + if (LockParams.numberOfUsers > kMaxUsers) + { + PLAT_LOG("Max number of users is greater than %d, the maximum amount of users currently supported on this platform", + kMaxUsers); + return APP_ERROR_ALLOCATION_FAILED; + } + + if (LockParams.numberOfCredentialsPerUser > kMaxCredentialsPerUser) + { + PLAT_LOG("Max number of credentials per user is greater than %d, the maximum amount of users currently supported on this " + "platform", + kMaxCredentialsPerUser); + return APP_ERROR_ALLOCATION_FAILED; + } + + if (LockParams.numberOfWeekdaySchedulesPerUser > kMaxWeekdaySchedulesPerUser) + { + PLAT_LOG("Max number of schedules is greater than %d, the maximum amount of schedules currently supported on this platform", + kMaxWeekdaySchedulesPerUser); + return APP_ERROR_ALLOCATION_FAILED; + } + + if (LockParams.numberOfYeardaySchedulesPerUser > kMaxYeardaySchedulesPerUser) + { + PLAT_LOG("Max number of schedules is greater than %d, the maximum amount of schedules currently supported on this platform", + kMaxYeardaySchedulesPerUser); + return APP_ERROR_ALLOCATION_FAILED; + } + + if (LockParams.numberOfHolidaySchedules > kMaxHolidaySchedules) + { + PLAT_LOG("Max number of schedules is greater than %d, the maximum amount of schedules currently supported on this platform", + kMaxHolidaySchedules); + return APP_ERROR_ALLOCATION_FAILED; + } + + // Create FreeRTOS sw timer for lock timer. + sLockTimer = xTimerCreate("lockTmr", // Just a text name, not used by the RTOS kernel + 1, // == default timer period (mS) + false, // no timer reload (==one-shot) + (void *) this, // init timer id = lock obj context + TimerEventHandler // timer callback handler + ); + + if (sLockTimer == NULL) + { + PLAT_LOG("sLockTimer timer create failed"); + return APP_ERROR_CREATE_TIMER_FAILED; + } + + if (state.Value() == DlLockState::kUnlocked) + { + mState = kState_UnlockCompleted; + } + else + { + mState = kState_LockCompleted; + } + + return CHIP_NO_ERROR; +} + +bool LockManager::IsValidUserIndex(uint16_t userIndex) +{ + return (userIndex < kMaxUsers); +} + +bool LockManager::IsValidCredentialIndex(uint16_t credentialIndex, CredentialTypeEnum type) +{ + if (CredentialTypeEnum::kProgrammingPIN == type) + { + return (0 == credentialIndex); // 0 is required index for Programming PIN + } + return (credentialIndex < kMaxCredentialsPerUser); +} + +bool LockManager::IsValidWeekdayScheduleIndex(uint8_t scheduleIndex) +{ + return (scheduleIndex < kMaxWeekdaySchedulesPerUser); +} + +bool LockManager::IsValidYeardayScheduleIndex(uint8_t scheduleIndex) +{ + return (scheduleIndex < kMaxYeardaySchedulesPerUser); +} + +bool LockManager::IsValidHolidayScheduleIndex(uint8_t scheduleIndex) +{ + return (scheduleIndex < kMaxHolidaySchedules); +} + +bool LockManager::ReadConfigValues() +{ + size_t outLen; + KeyValueStoreMgr().Get(LockUser, reinterpret_cast(&mLockUsers), + sizeof(EmberAfPluginDoorLockUserInfo) * ArraySize(mLockUsers), &outLen); + + KeyValueStoreMgr().Get(Credential, reinterpret_cast(&mLockCredentials), + sizeof(EmberAfPluginDoorLockCredentialInfo) * ArraySize(mLockCredentials), &outLen); + + KeyValueStoreMgr().Get(LockUserName, reinterpret_cast(mUserNames), sizeof(mUserNames), &outLen); + + KeyValueStoreMgr().Get(CredentialData, reinterpret_cast(mCredentialData), sizeof(mCredentialData), &outLen); + + KeyValueStoreMgr().Get(UserCredentials, reinterpret_cast(mCredentials), + sizeof(CredentialStruct) * LockParams.numberOfUsers * LockParams.numberOfCredentialsPerUser, &outLen); + + KeyValueStoreMgr().Get(WeekDaySchedules, reinterpret_cast(mWeekdaySchedule), + sizeof(EmberAfPluginDoorLockWeekDaySchedule) * LockParams.numberOfWeekdaySchedulesPerUser * + LockParams.numberOfUsers, + &outLen); + + KeyValueStoreMgr().Get(YearDaySchedules, reinterpret_cast(mYeardaySchedule), + sizeof(EmberAfPluginDoorLockYearDaySchedule) * LockParams.numberOfYeardaySchedulesPerUser * + LockParams.numberOfUsers, + &outLen); + + KeyValueStoreMgr().Get(HolidaySchedules, reinterpret_cast(&(mHolidaySchedule)), + sizeof(EmberAfPluginDoorLockHolidaySchedule) * LockParams.numberOfHolidaySchedules, &outLen); + + return true; +} + +void LockManager::SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB) +{ + mActionInitiated_CB = aActionInitiated_CB; + mActionCompleted_CB = aActionCompleted_CB; +} + +bool LockManager::InitiateAction(Action_t aAction) +{ + bool action_initiated = false; + State_t new_state; + + // Initiate Turn Lock/Unlock Action only when the previous one is complete. + if (mState == kState_LockCompleted && aAction == UNLOCK_ACTION) + { + action_initiated = true; + + new_state = kState_UnlockInitiated; + } + else if (mState == kState_UnlockCompleted && aAction == LOCK_ACTION) + { + action_initiated = true; + + new_state = kState_LockInitiated; + } + + if (action_initiated) + { + + StartTimer(ACTUATOR_MOVEMENT_PERIOD_MS); + + // Since the timer started successfully, update the state and trigger callback + mState = new_state; + + if (mActionInitiated_CB) + { + mActionInitiated_CB(aAction); + } + } + + return action_initiated; +} + +void LockManager::StartTimer(uint32_t aTimeoutMs) +{ + if (xTimerIsTimerActive(sLockTimer)) + { + PLAT_LOG("app timer already started!"); + CancelTimer(); + } + + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(sLockTimer, pdMS_TO_TICKS(aTimeoutMs), 100) != pdPASS) + { + PLAT_LOG("sLockTimer timer start() failed"); + } +} + +void LockManager::CancelTimer(void) +{ + if (xTimerStop(sLockTimer, 0) == pdFAIL) + { + PLAT_LOG("sLockTimer stop() failed"); + } +} + +void LockManager::TimerEventHandler(TimerHandle_t xTimer) +{ + // Get lock obj context from timer id. + LockManager * lock = static_cast(pvTimerGetTimerID(xTimer)); + + // The timer event handler will be called in the context of the timer task + // once sLockTimer expires. Post an event to apptask queue with the actual handler + // so that the event can be handled in the context of the apptask. + AppEvent event; + event.Type = AppEvent::kEventType_AppEvent; + event.BoltLockEvent.Context = lock; + event.Handler = ActuatorMovementTimerEventHandler; + GetAppTask().PostEvent(&event); +} + +void LockManager::ActuatorMovementTimerEventHandler(AppEvent * aEvent) +{ + Action_t actionCompleted = INVALID_ACTION; + + LockManager * lock = static_cast(aEvent->BoltLockEvent.Context); + + if (lock->mState == kState_LockInitiated) + { + lock->mState = kState_LockCompleted; + actionCompleted = LOCK_ACTION; + DoorLockServer::Instance().SetLockState(1, DlLockState::kLocked); + } + else if (lock->mState == kState_UnlockInitiated) + { + lock->mState = kState_UnlockCompleted; + actionCompleted = UNLOCK_ACTION; + DoorLockServer::Instance().SetLockState(1, DlLockState::kUnlocked); + } + + if (actionCompleted != INVALID_ACTION) + { + if (lock->mActionCompleted_CB) + { + lock->mActionCompleted_CB(actionCompleted); + } + } +} + +bool LockManager::Lock(chip::EndpointId endpointId, const Optional & pin, OperationErrorEnum & err) +{ + return checkPin(endpointId, DlLockState::kLocked, pin, err); +} + +bool LockManager::Unlock(chip::EndpointId endpointId, const Optional & pin, OperationErrorEnum & err) +{ + return checkPin(endpointId, DlLockState::kUnlocked, pin, err); +} + +bool LockManager::GetUser(chip::EndpointId endpointId, uint16_t userIndex, EmberAfPluginDoorLockUserInfo & user) +{ + VerifyOrReturnValue(userIndex > 0, false); // indices are one-indexed + + userIndex--; + + VerifyOrReturnValue(IsValidUserIndex(userIndex), false); + + ChipLogProgress(Zcl, "Door Lock App: LockManager::GetUser [endpoint=%d,userIndex=%hu]", endpointId, userIndex); + + const auto & userInDb = mLockUsers[userIndex]; + + user.userStatus = userInDb.userStatus; + if (UserStatusEnum::kAvailable == user.userStatus) + { + ChipLogDetail(Zcl, "Found unoccupied user [endpoint=%d]", endpointId); + return true; + } + + user.userName = chip::CharSpan(userInDb.userName.data(), userInDb.userName.size()); + user.credentials = chip::Span(mCredentials[userIndex], userInDb.credentials.size()); + user.userUniqueId = userInDb.userUniqueId; + user.userType = userInDb.userType; + user.credentialRule = userInDb.credentialRule; + // So far there's no way to actually create the credential outside Matter, so here we always set the creation/modification + // source to Matter + user.creationSource = DlAssetSource::kMatterIM; + user.createdBy = userInDb.createdBy; + user.modificationSource = DlAssetSource::kMatterIM; + user.lastModifiedBy = userInDb.lastModifiedBy; + + ChipLogDetail(Zcl, + "Found occupied user " + "[endpoint=%d,name=\"%.*s\",credentialsCount=%u,uniqueId=%lx,type=%u,credentialRule=%u," + "createdBy=%d,lastModifiedBy=%d]", + endpointId, static_cast(user.userName.size()), user.userName.data(), user.credentials.size(), + user.userUniqueId, to_underlying(user.userType), to_underlying(user.credentialRule), user.createdBy, + user.lastModifiedBy); + + return true; +} + +bool LockManager::SetUser(chip::EndpointId endpointId, uint16_t userIndex, chip::FabricIndex creator, chip::FabricIndex modifier, + const chip::CharSpan & userName, uint32_t uniqueId, UserStatusEnum userStatus, UserTypeEnum usertype, + CredentialRuleEnum credentialRule, const CredentialStruct * credentials, size_t totalCredentials) +{ + ChipLogProgress(Zcl, + "Door Lock App: LockManager::SetUser " + "[endpoint=%d,userIndex=%d,creator=%d,modifier=%d,userName=%s,uniqueId=%ld " + "userStatus=%u,userType=%u,credentialRule=%u,credentials=%p,totalCredentials=%u]", + endpointId, userIndex, creator, modifier, userName.data(), uniqueId, to_underlying(userStatus), + to_underlying(usertype), to_underlying(credentialRule), credentials, totalCredentials); + + VerifyOrReturnValue(userIndex > 0, false); // indices are one-indexed + + userIndex--; + + VerifyOrReturnValue(IsValidUserIndex(userIndex), false); + + auto & userInStorage = mLockUsers[userIndex]; + + if (userName.size() > DOOR_LOCK_MAX_USER_NAME_SIZE) + { + ChipLogError(Zcl, "Cannot set user - user name is too long [endpoint=%d,index=%d]", endpointId, userIndex); + return false; + } + + if (totalCredentials > LockParams.numberOfCredentialsPerUser) + { + ChipLogError(Zcl, "Cannot set user - total number of credentials is too big [endpoint=%d,index=%d,totalCredentials=%u]", + endpointId, userIndex, totalCredentials); + return false; + } + + chip::Platform::CopyString(mUserNames[userIndex], userName); + userInStorage.userName = chip::CharSpan(mUserNames[userIndex], userName.size()); + userInStorage.userUniqueId = uniqueId; + userInStorage.userStatus = userStatus; + userInStorage.userType = usertype; + userInStorage.credentialRule = credentialRule; + userInStorage.lastModifiedBy = modifier; + userInStorage.createdBy = creator; + + for (size_t i = 0; i < totalCredentials; ++i) + { + mCredentials[userIndex][i] = credentials[i]; + mCredentials[userIndex][i].credentialType = CredentialTypeEnum::kPin; + mCredentials[userIndex][i].credentialIndex = i + 1; + } + + userInStorage.credentials = chip::Span(mCredentials[userIndex], totalCredentials); + + // Save user information in NVM flash + KeyValueStoreMgr().Put(LockUser, reinterpret_cast(&mLockUsers), + sizeof(EmberAfPluginDoorLockUserInfo) * LockParams.numberOfUsers); + + KeyValueStoreMgr().Put(UserCredentials, reinterpret_cast(mCredentials), + sizeof(CredentialStruct) * LockParams.numberOfUsers * LockParams.numberOfCredentialsPerUser); + + KeyValueStoreMgr().Put(LockUserName, reinterpret_cast(mUserNames), sizeof(mUserNames)); + + ChipLogProgress(Zcl, "Successfully set the user [mEndpointId=%d,index=%d]", endpointId, userIndex); + + return true; +} + +bool LockManager::GetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, CredentialTypeEnum credentialType, + EmberAfPluginDoorLockCredentialInfo & credential) +{ + + if (CredentialTypeEnum::kProgrammingPIN == credentialType) + { + VerifyOrReturnValue(IsValidCredentialIndex(credentialIndex, credentialType), + false); // programming pin index is only index allowed to contain 0 + } + else + { + VerifyOrReturnValue(IsValidCredentialIndex(--credentialIndex, credentialType), false); // otherwise, indices are one-indexed + } + + ChipLogProgress(Zcl, "Lock App: LockManager::GetCredential [credentialType=%u], credentialIndex=%d", + to_underlying(credentialType), credentialIndex); + + const auto & credentialInStorage = mLockCredentials[credentialIndex]; + + credential.status = credentialInStorage.status; + ChipLogDetail(Zcl, "CredentialStatus: %d, CredentialIndex: %d ", (int) credential.status, credentialIndex); + + if (DlCredentialStatus::kAvailable == credential.status) + { + ChipLogDetail(Zcl, "Found unoccupied credential "); + return true; + } + credential.credentialType = credentialInStorage.credentialType; + credential.credentialData = credentialInStorage.credentialData; + credential.createdBy = credentialInStorage.createdBy; + credential.lastModifiedBy = credentialInStorage.lastModifiedBy; + // So far there's no way to actually create the credential outside Matter, so here we always set the creation/modification + // source to Matter + credential.creationSource = DlAssetSource::kMatterIM; + credential.modificationSource = DlAssetSource::kMatterIM; + + ChipLogDetail(Zcl, "Found occupied credential [type=%u,dataSize=%u]", to_underlying(credential.credentialType), + credential.credentialData.size()); + + return true; +} + +bool LockManager::SetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, chip::FabricIndex creator, + chip::FabricIndex modifier, DlCredentialStatus credentialStatus, CredentialTypeEnum credentialType, + const chip::ByteSpan & credentialData) +{ + + if (CredentialTypeEnum::kProgrammingPIN == credentialType) + { + VerifyOrReturnValue(IsValidCredentialIndex(credentialIndex, credentialType), + false); // programming pin index is only index allowed to contain 0 + } + else + { + VerifyOrReturnValue(IsValidCredentialIndex(--credentialIndex, credentialType), false); // otherwise, indices are one-indexed + } + + ChipLogProgress(Zcl, + "Door Lock App: LockManager::SetCredential " + "[credentialStatus=%u,credentialType=%u,credentialDataSize=%u,creator=%d,modifier=%d]", + to_underlying(credentialStatus), to_underlying(credentialType), credentialData.size(), creator, modifier); + + auto & credentialInStorage = mLockCredentials[credentialIndex]; + + credentialInStorage.status = credentialStatus; + credentialInStorage.credentialType = credentialType; + credentialInStorage.createdBy = creator; + credentialInStorage.lastModifiedBy = modifier; + + memcpy(mCredentialData[credentialIndex], credentialData.data(), credentialData.size()); + credentialInStorage.credentialData = chip::ByteSpan{ mCredentialData[credentialIndex], credentialData.size() }; + + // Save credential information in NVM flash + KeyValueStoreMgr().Put(Credential, reinterpret_cast(&mLockCredentials), + sizeof(EmberAfPluginDoorLockCredentialInfo) * LockParams.numberOfCredentialsPerUser); + + KeyValueStoreMgr().Put(CredentialData, reinterpret_cast(&mCredentialData), sizeof(mCredentialData)); + + ChipLogProgress(Zcl, "Successfully set the credential [credentialType=%u]", to_underlying(credentialType)); + + return true; +} + +DlStatus LockManager::GetWeekdaySchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, + EmberAfPluginDoorLockWeekDaySchedule & schedule) +{ + + VerifyOrReturnValue(weekdayIndex > 0, DlStatus::kFailure); // indices are one-indexed + VerifyOrReturnValue(userIndex > 0, DlStatus::kFailure); // indices are one-indexed + + weekdayIndex--; + userIndex--; + + VerifyOrReturnValue(IsValidWeekdayScheduleIndex(weekdayIndex), DlStatus::kFailure); + VerifyOrReturnValue(IsValidUserIndex(userIndex), DlStatus::kFailure); + + const auto & scheduleInStorage = mWeekdaySchedule[userIndex][weekdayIndex]; + if (DlScheduleStatus::kAvailable == scheduleInStorage.status) + { + return DlStatus::kNotFound; + } + + schedule = scheduleInStorage.schedule; + + return DlStatus::kSuccess; +} + +DlStatus LockManager::SetWeekdaySchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, + DlScheduleStatus status, DaysMaskMap daysMask, uint8_t startHour, uint8_t startMinute, + uint8_t endHour, uint8_t endMinute) +{ + + VerifyOrReturnValue(weekdayIndex > 0, DlStatus::kFailure); // indices are one-indexed + VerifyOrReturnValue(userIndex > 0, DlStatus::kFailure); // indices are one-indexed + + weekdayIndex--; + userIndex--; + + VerifyOrReturnValue(IsValidWeekdayScheduleIndex(weekdayIndex), DlStatus::kFailure); + VerifyOrReturnValue(IsValidUserIndex(userIndex), DlStatus::kFailure); + + auto & scheduleInStorage = mWeekdaySchedule[userIndex][weekdayIndex]; + + scheduleInStorage.schedule.daysMask = daysMask; + scheduleInStorage.schedule.startHour = startHour; + scheduleInStorage.schedule.startMinute = startMinute; + scheduleInStorage.schedule.endHour = endHour; + scheduleInStorage.schedule.endMinute = endMinute; + scheduleInStorage.status = status; + + // Save schedule information in NVM flash + KeyValueStoreMgr().Put(WeekDaySchedules, reinterpret_cast(mWeekdaySchedule), + sizeof(EmberAfPluginDoorLockWeekDaySchedule) * LockParams.numberOfWeekdaySchedulesPerUser * + LockParams.numberOfUsers); + + return DlStatus::kSuccess; +} + +DlStatus LockManager::GetYeardaySchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, + EmberAfPluginDoorLockYearDaySchedule & schedule) +{ + VerifyOrReturnValue(yearDayIndex > 0, DlStatus::kFailure); // indices are one-indexed + VerifyOrReturnValue(userIndex > 0, DlStatus::kFailure); // indices are one-indexed + + yearDayIndex--; + userIndex--; + + VerifyOrReturnValue(IsValidYeardayScheduleIndex(yearDayIndex), DlStatus::kFailure); + VerifyOrReturnValue(IsValidUserIndex(userIndex), DlStatus::kFailure); + + const auto & scheduleInStorage = mYeardaySchedule[userIndex][yearDayIndex]; + if (DlScheduleStatus::kAvailable == scheduleInStorage.status) + { + return DlStatus::kNotFound; + } + + schedule = scheduleInStorage.schedule; + + return DlStatus::kSuccess; +} + +DlStatus LockManager::SetYeardaySchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, + DlScheduleStatus status, uint32_t localStartTime, uint32_t localEndTime) +{ + VerifyOrReturnValue(yearDayIndex > 0, DlStatus::kFailure); // indices are one-indexed + VerifyOrReturnValue(userIndex > 0, DlStatus::kFailure); // indices are one-indexed + + yearDayIndex--; + userIndex--; + + VerifyOrReturnValue(IsValidYeardayScheduleIndex(yearDayIndex), DlStatus::kFailure); + VerifyOrReturnValue(IsValidUserIndex(userIndex), DlStatus::kFailure); + + auto & scheduleInStorage = mYeardaySchedule[userIndex][yearDayIndex]; + + scheduleInStorage.schedule.localStartTime = localStartTime; + scheduleInStorage.schedule.localEndTime = localEndTime; + scheduleInStorage.status = status; + + // Save schedule information in NVM flash + KeyValueStoreMgr().Put(YearDaySchedules, reinterpret_cast(mYeardaySchedule), + sizeof(EmberAfPluginDoorLockYearDaySchedule) * LockParams.numberOfYeardaySchedulesPerUser * + LockParams.numberOfUsers); + + return DlStatus::kSuccess; +} + +DlStatus LockManager::GetHolidaySchedule(chip::EndpointId endpointId, uint8_t holidayIndex, + EmberAfPluginDoorLockHolidaySchedule & schedule) +{ + VerifyOrReturnValue(holidayIndex > 0, DlStatus::kFailure); // indices are one-indexed + + holidayIndex--; + + VerifyOrReturnValue(IsValidHolidayScheduleIndex(holidayIndex), DlStatus::kFailure); + + const auto & scheduleInStorage = mHolidaySchedule[holidayIndex]; + if (DlScheduleStatus::kAvailable == scheduleInStorage.status) + { + return DlStatus::kNotFound; + } + + schedule = scheduleInStorage.schedule; + + return DlStatus::kSuccess; +} + +DlStatus LockManager::SetHolidaySchedule(chip::EndpointId endpointId, uint8_t holidayIndex, DlScheduleStatus status, + uint32_t localStartTime, uint32_t localEndTime, OperatingModeEnum operatingMode) +{ + VerifyOrReturnValue(holidayIndex > 0, DlStatus::kFailure); // indices are one-indexed + + holidayIndex--; + + VerifyOrReturnValue(IsValidHolidayScheduleIndex(holidayIndex), DlStatus::kFailure); + + auto & scheduleInStorage = mHolidaySchedule[holidayIndex]; + + scheduleInStorage.schedule.localStartTime = localStartTime; + scheduleInStorage.schedule.localEndTime = localEndTime; + scheduleInStorage.schedule.operatingMode = operatingMode; + scheduleInStorage.status = status; + + // Save schedule information in NVM flash + KeyValueStoreMgr().Put(HolidaySchedules, reinterpret_cast(&(mHolidaySchedule)), + sizeof(EmberAfPluginDoorLockHolidaySchedule) * LockParams.numberOfHolidaySchedules); + + return DlStatus::kSuccess; +} + +const char * LockManager::lockStateToString(DlLockState lockState) const +{ + switch (lockState) + { + case DlLockState::kNotFullyLocked: + return "Not Fully Locked"; + case DlLockState::kLocked: + return "Locked"; + case DlLockState::kUnlocked: + return "Unlocked"; + case DlLockState::kUnknownEnumValue: + break; + } + + return "Unknown"; +} + +bool LockManager::checkPin(chip::EndpointId endpointId, DlLockState lockState, const Optional & pin, + OperationErrorEnum & err) +{ + // Assume pin is required until told otherwise + bool requirePin = true; + chip::app::Clusters::DoorLock::Attributes::RequirePINforRemoteOperation::Get(endpointId, &requirePin); + + // If a pin code is not given + if (!pin.HasValue()) + { + ChipLogDetail(Zcl, "Door Lock App: PIN code is not specified [endpointId=%d]", endpointId); + + // If a pin code is not required + if (!requirePin) + { + ChipLogDetail(Zcl, "Door Lock App: setting door lock state to \"%s\" [endpointId=%d]", lockStateToString(lockState), + endpointId); + + return true; + } + + ChipLogError(Zcl, "Door Lock App: PIN code is not specified, but it is required [endpointId=%d]", endpointId); + + err = OperationErrorEnum::kInvalidCredential; + DoorLockServer::Instance().HandleWrongCodeEntry(endpointId); + return false; + } + + // Check the PIN code + for (uint8_t i = 0; i < kMaxCredentials; i++) + { + if (mLockCredentials[i].credentialType != CredentialTypeEnum::kPin || + mLockCredentials[i].status == DlCredentialStatus::kAvailable) + { + continue; + } + + if (mLockCredentials[i].credentialData.data_equal(pin.Value())) + { + ChipLogDetail(Zcl, + "Lock App: specified PIN code was found in the database, setting lock state to \"%s\" [endpointId=%d]", + lockStateToString(lockState), endpointId); + + return true; + } + } + + ChipLogDetail(Zcl, + "Door Lock App: specified PIN code was not found in the database, ignoring command to set lock state to \"%s\" " + "[endpointId=%d]", + lockStateToString(lockState), endpointId); + + err = OperationErrorEnum::kInvalidCredential; + DoorLockServer::Instance().HandleWrongCodeEntry(endpointId); + return false; +} diff --git a/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.h b/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.h new file mode 100644 index 00000000000000..74129260bd9172 --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/src/LockManager.h @@ -0,0 +1,221 @@ +/* + * + * 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. + */ + +#pragma once + +#include + +#include +#include + +#include "AppEvent.h" + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support + +#include + +struct WeekDaysScheduleInfo +{ + DlScheduleStatus status; + EmberAfPluginDoorLockWeekDaySchedule schedule; +}; + +struct YearDayScheduleInfo +{ + DlScheduleStatus status; + EmberAfPluginDoorLockYearDaySchedule schedule; +}; + +struct HolidayScheduleInfo +{ + DlScheduleStatus status; + EmberAfPluginDoorLockHolidaySchedule schedule; +}; + +namespace CC13X2_26X2DoorLock { +namespace ResourceRanges { +// Used to size arrays +static constexpr uint16_t kMaxUsers = 10; +static constexpr uint8_t kMaxCredentialsPerUser = 10; +static constexpr uint8_t kMaxWeekdaySchedulesPerUser = 10; +static constexpr uint8_t kMaxYeardaySchedulesPerUser = 10; +static constexpr uint8_t kMaxHolidaySchedules = 10; +static constexpr uint8_t kMaxCredentialSize = 8; + +// Indices received for user/credential/schedules are 1-indexed +static constexpr uint8_t kStartIndexValue = 1; + +static constexpr uint8_t kMaxCredentials = kMaxUsers * kMaxCredentialsPerUser; +} // namespace ResourceRanges + +namespace LockInitParams { + +struct LockParam +{ + // Read from zap attributes + uint16_t numberOfUsers = 0; + uint8_t numberOfCredentialsPerUser = 0; + uint8_t numberOfWeekdaySchedulesPerUser = 0; + uint8_t numberOfYeardaySchedulesPerUser = 0; + uint8_t numberOfHolidaySchedules = 0; +}; + +class ParamBuilder +{ +public: + ParamBuilder & SetNumberOfUsers(uint16_t numberOfUsers) + { + lockParam_.numberOfUsers = numberOfUsers; + return *this; + } + ParamBuilder & SetNumberOfCredentialsPerUser(uint8_t numberOfCredentialsPerUser) + { + lockParam_.numberOfCredentialsPerUser = numberOfCredentialsPerUser; + return *this; + } + ParamBuilder & SetNumberOfWeekdaySchedulesPerUser(uint8_t numberOfWeekdaySchedulesPerUser) + { + lockParam_.numberOfWeekdaySchedulesPerUser = numberOfWeekdaySchedulesPerUser; + return *this; + } + ParamBuilder & SetNumberOfYeardaySchedulesPerUser(uint8_t numberOfYeardaySchedulesPerUser) + { + lockParam_.numberOfYeardaySchedulesPerUser = numberOfYeardaySchedulesPerUser; + return *this; + } + ParamBuilder & SetNumberOfHolidaySchedules(uint8_t numberOfHolidaySchedules) + { + lockParam_.numberOfHolidaySchedules = numberOfHolidaySchedules; + return *this; + } + LockParam GetLockParam() { return lockParam_; } + +private: + LockParam lockParam_; +}; + +} // namespace LockInitParams +} // namespace CC13X2_26X2DoorLock + +using namespace ::chip; +using namespace CC13X2_26X2DoorLock::ResourceRanges; + +class LockManager +{ +public: + enum Action_t + { + LOCK_ACTION = 0, + UNLOCK_ACTION, + + INVALID_ACTION + } Action; + + enum State_t + { + kState_LockInitiated = 0, + kState_LockCompleted, + kState_UnlockInitiated, + kState_UnlockCompleted, + } State; + + CHIP_ERROR Init(chip::app::DataModel::Nullable state, + CC13X2_26X2DoorLock::LockInitParams::LockParam lockParam); + bool InitiateAction(Action_t aAction); + + typedef void (*Callback_fn_initiated)(Action_t); + typedef void (*Callback_fn_completed)(Action_t); + void SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB); + + bool Lock(chip::EndpointId endpointId, const Optional & pin, OperationErrorEnum & err); + bool Unlock(chip::EndpointId endpointId, const Optional & pin, OperationErrorEnum & err); + + bool GetUser(chip::EndpointId endpointId, uint16_t userIndex, EmberAfPluginDoorLockUserInfo & user); + bool SetUser(chip::EndpointId endpointId, uint16_t userIndex, chip::FabricIndex creator, chip::FabricIndex modifier, + const chip::CharSpan & userName, uint32_t uniqueId, UserStatusEnum userStatus, UserTypeEnum usertype, + CredentialRuleEnum credentialRule, const CredentialStruct * credentials, size_t totalCredentials); + + bool GetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, CredentialTypeEnum credentialType, + EmberAfPluginDoorLockCredentialInfo & credential); + + bool SetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, chip::FabricIndex creator, chip::FabricIndex modifier, + DlCredentialStatus credentialStatus, CredentialTypeEnum credentialType, + const chip::ByteSpan & credentialData); + + DlStatus GetWeekdaySchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, + EmberAfPluginDoorLockWeekDaySchedule & schedule); + + DlStatus SetWeekdaySchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, DlScheduleStatus status, + DaysMaskMap daysMask, uint8_t startHour, uint8_t startMinute, uint8_t endHour, uint8_t endMinute); + + DlStatus GetYeardaySchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, + EmberAfPluginDoorLockYearDaySchedule & schedule); + + DlStatus SetYeardaySchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, DlScheduleStatus status, + uint32_t localStartTime, uint32_t localEndTime); + + DlStatus GetHolidaySchedule(chip::EndpointId endpointId, uint8_t holidayIndex, EmberAfPluginDoorLockHolidaySchedule & schedule); + + DlStatus SetHolidaySchedule(chip::EndpointId endpointId, uint8_t holidayIndex, DlScheduleStatus status, uint32_t localStartTime, + uint32_t localEndTime, OperatingModeEnum operatingMode); + + bool IsValidUserIndex(uint16_t userIndex); + bool IsValidCredentialIndex(uint16_t credentialIndex, CredentialTypeEnum type); + bool IsValidWeekdayScheduleIndex(uint8_t scheduleIndex); + bool IsValidYeardayScheduleIndex(uint8_t scheduleIndex); + bool IsValidHolidayScheduleIndex(uint8_t scheduleIndex); + + bool checkPin(chip::EndpointId endpointId, DlLockState lockState, const Optional & pin, + OperationErrorEnum & err); + const char * lockStateToString(DlLockState lockState) const; + + bool ReadConfigValues(); + +private: + friend LockManager & LockMgr(); + State_t mState; + + Callback_fn_initiated mActionInitiated_CB; + Callback_fn_completed mActionCompleted_CB; + + void CancelTimer(void); + void StartTimer(uint32_t aTimeoutMs); + + static void TimerEventHandler(TimerHandle_t xTimer); + static void AutoLockTimerEventHandler(AppEvent * aEvent); + static void ActuatorMovementTimerEventHandler(AppEvent * aEvent); + + EmberAfPluginDoorLockUserInfo mLockUsers[kMaxUsers]; + EmberAfPluginDoorLockCredentialInfo mLockCredentials[kMaxCredentials]; + WeekDaysScheduleInfo mWeekdaySchedule[kMaxUsers][kMaxWeekdaySchedulesPerUser]; + YearDayScheduleInfo mYeardaySchedule[kMaxUsers][kMaxYeardaySchedulesPerUser]; + HolidayScheduleInfo mHolidaySchedule[kMaxHolidaySchedules]; + + char mUserNames[ArraySize(mLockUsers)][DOOR_LOCK_MAX_USER_NAME_SIZE]; + uint8_t mCredentialData[kMaxCredentials][kMaxCredentialSize]; + CredentialStruct mCredentials[kMaxUsers][kMaxCredentialsPerUser]; + + static LockManager sLock; + CC13X2_26X2DoorLock::LockInitParams::LockParam LockParams; +}; + +inline LockManager & LockMgr() +{ + return LockManager::sLock; +} diff --git a/examples/lock-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp b/examples/lock-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp new file mode 100644 index 00000000000000..0fb673f020c5c5 --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/src/ZclCallbacks.cpp @@ -0,0 +1,149 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * This file implements the handler for data model messages. + */ + +#include "AppConfig.h" +#include "LockManager.h" +#include + +#include +#include +#include +#include + +using namespace ::chip::app::Clusters; +using namespace ::chip::DeviceLayer::Internal; + +void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size, + uint8_t * value) +{ + ClusterId clusterId = attributePath.mClusterId; + AttributeId attributeId = attributePath.mAttributeId; + ChipLogProgress(Zcl, "Cluster callback: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + + if (clusterId == DoorLock::Id && attributeId == DoorLock::Attributes::LockState::Id) + { + ChipLogProgress(Zcl, "Door lock cluster: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + } +} + +/** @brief DoorLock 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 emberAfDoorLockClusterInitCallback(EndpointId endpoint) {} + +bool emberAfPluginDoorLockOnDoorLockCommand(chip::EndpointId endpointId, const Optional & pinCode, + OperationErrorEnum & err) +{ + ChipLogProgress(Zcl, "Door Lock App: Lock Command endpoint=%d", endpointId); + bool status = LockMgr().Lock(endpointId, pinCode, err); + if (status == true) + { + LockMgr().InitiateAction(LockManager::LOCK_ACTION); + } + return status; +} + +bool emberAfPluginDoorLockOnDoorUnlockCommand(chip::EndpointId endpointId, const Optional & pinCode, + OperationErrorEnum & err) +{ + ChipLogProgress(Zcl, "Door Lock App: Unlock Command endpoint=%d", endpointId); + bool status = LockMgr().Unlock(endpointId, pinCode, err); + if (status == true) + { + LockMgr().InitiateAction(LockManager::UNLOCK_ACTION); + } + + return status; +} + +bool emberAfPluginDoorLockGetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, CredentialTypeEnum credentialType, + EmberAfPluginDoorLockCredentialInfo & credential) +{ + return LockMgr().GetCredential(endpointId, credentialIndex, credentialType, credential); +} + +bool emberAfPluginDoorLockSetCredential(chip::EndpointId endpointId, uint16_t credentialIndex, chip::FabricIndex creator, + chip::FabricIndex modifier, DlCredentialStatus credentialStatus, + CredentialTypeEnum credentialType, const chip::ByteSpan & credentialData) +{ + return LockMgr().SetCredential(endpointId, credentialIndex, creator, modifier, credentialStatus, credentialType, + credentialData); +} + +bool emberAfPluginDoorLockGetUser(chip::EndpointId endpointId, uint16_t userIndex, EmberAfPluginDoorLockUserInfo & user) +{ + return LockMgr().GetUser(endpointId, userIndex, user); +} + +bool emberAfPluginDoorLockSetUser(chip::EndpointId endpointId, uint16_t userIndex, chip::FabricIndex creator, + chip::FabricIndex modifier, const chip::CharSpan & userName, uint32_t uniqueId, + UserStatusEnum userStatus, UserTypeEnum usertype, CredentialRuleEnum credentialRule, + const CredentialStruct * credentials, size_t totalCredentials) +{ + + return LockMgr().SetUser(endpointId, userIndex, creator, modifier, userName, uniqueId, userStatus, usertype, credentialRule, + credentials, totalCredentials); +} + +DlStatus emberAfPluginDoorLockGetSchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, + EmberAfPluginDoorLockWeekDaySchedule & schedule) +{ + return LockMgr().GetWeekdaySchedule(endpointId, weekdayIndex, userIndex, schedule); +} + +DlStatus emberAfPluginDoorLockGetSchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, + EmberAfPluginDoorLockYearDaySchedule & schedule) +{ + return LockMgr().GetYeardaySchedule(endpointId, yearDayIndex, userIndex, schedule); +} + +DlStatus emberAfPluginDoorLockGetSchedule(chip::EndpointId endpointId, uint8_t holidayIndex, + EmberAfPluginDoorLockHolidaySchedule & holidaySchedule) +{ + return LockMgr().GetHolidaySchedule(endpointId, holidayIndex, holidaySchedule); +} + +DlStatus emberAfPluginDoorLockSetSchedule(chip::EndpointId endpointId, uint8_t weekdayIndex, uint16_t userIndex, + DlScheduleStatus status, DaysMaskMap daysMask, uint8_t startHour, uint8_t startMinute, + uint8_t endHour, uint8_t endMinute) +{ + return LockMgr().SetWeekdaySchedule(endpointId, weekdayIndex, userIndex, status, daysMask, startHour, startMinute, endHour, + endMinute); +} + +DlStatus emberAfPluginDoorLockSetSchedule(chip::EndpointId endpointId, uint8_t yearDayIndex, uint16_t userIndex, + DlScheduleStatus status, uint32_t localStartTime, uint32_t localEndTime) +{ + return LockMgr().SetYeardaySchedule(endpointId, yearDayIndex, userIndex, status, localStartTime, localEndTime); +} + +DlStatus emberAfPluginDoorLockSetSchedule(chip::EndpointId endpointId, uint8_t holidayIndex, DlScheduleStatus status, + uint32_t localStartTime, uint32_t localEndTime, OperatingModeEnum operatingMode) +{ + return LockMgr().SetHolidaySchedule(endpointId, holidayIndex, status, localStartTime, localEndTime, operatingMode); +} diff --git a/examples/lock-app/cc13x2x7_26x2x7/src/main.cpp b/examples/lock-app/cc13x2x7_26x2x7/src/main.cpp new file mode 100644 index 00000000000000..4fdb88703acab6 --- /dev/null +++ b/examples/lock-app/cc13x2x7_26x2x7/src/main.cpp @@ -0,0 +1,105 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020 Texas Instruments Incorporated + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include + +#include "AppConfig.h" +#include "AppTask.h" + +#include + +/* Driver Header files */ +#include +#include +#include + +#include +#include +#include +#include + +#include +#define TOTAL_ICALL_HEAP_SIZE (0xc600) + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; + +__attribute__((section(".heap"))) uint8_t GlobalHeapZoneBuffer[TOTAL_ICALL_HEAP_SIZE]; +uint32_t heapSize = TOTAL_ICALL_HEAP_SIZE; + +// ================================================================================ +// FreeRTOS Callbacks +// ================================================================================ +extern "C" void vApplicationStackOverflowHook(void) +{ + while (1) + { + ; + } +} + +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + Board_init(); + bpool((void *) GlobalHeapZoneBuffer, TOTAL_ICALL_HEAP_SIZE); + + GPIO_init(); + + NVS_init(); + + ECDH_init(); + + ECDSA_init(); + + AESECB_init(); + + SHA2_init(); + + int ret = GetAppTask().StartAppTask(); + if (ret != 0) + { + // can't log until the kernel is started + // PLAT_LOG("GetAppTask().StartAppTask() failed"); + while (1) + ; + } + + vTaskStartScheduler(); + + // Should never get here. + while (1) + ; +} diff --git a/examples/lock-app/lock-common/BUILD.gn b/examples/lock-app/lock-common/BUILD.gn index 4237883f3fb2b0..bb01a5185f80f7 100644 --- a/examples/lock-app/lock-common/BUILD.gn +++ b/examples/lock-app/lock-common/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("lock-common") { diff --git a/examples/lock-app/nxp/zap/BUILD.gn b/examples/lock-app/nxp/zap/BUILD.gn index ebb03aadd5a2ab..cc5fe9361c32a3 100644 --- a/examples/lock-app/nxp/zap/BUILD.gn +++ b/examples/lock-app/nxp/zap/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("zap") { diff --git a/examples/lock-app/openiotsdk/CMakeLists.txt b/examples/lock-app/openiotsdk/CMakeLists.txt index fca486fed81d09..289ecbc893fc54 100644 --- a/examples/lock-app/openiotsdk/CMakeLists.txt +++ b/examples/lock-app/openiotsdk/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) 2022 Project CHIP Authors +# 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. @@ -38,22 +38,6 @@ project(${APP_TARGET} LANGUAGES C CXX ASM) include(sdk) -# LwIP configuration -if(TARGET lwip-cmsis-port) - # lwip requires user_lwipopts.h, we use the custom settings - target_include_directories(lwipopts - INTERFACE - ${OPEN_IOT_SDK_CONFIG}/lwip - ) - - if (${CMAKE_BUILD_TYPE} STREQUAL "Debug") - target_compile_definitions(lwipopts - INTERFACE - LWIP_DEBUG - ) - endif() -endif() - add_executable(${APP_TARGET}) # Application CHIP build configuration @@ -80,6 +64,7 @@ target_sources(${APP_TARGET} ) target_link_libraries(${APP_TARGET} + openiotsdk-startup openiotsdk-app ) diff --git a/examples/lock-app/openiotsdk/main/main_ns.cpp b/examples/lock-app/openiotsdk/main/main_ns.cpp index 2b6484b05180c2..aea75e3c58ac7a 100644 --- a/examples/lock-app/openiotsdk/main/main_ns.cpp +++ b/examples/lock-app/openiotsdk/main/main_ns.cpp @@ -22,38 +22,8 @@ #include "openiotsdk_platform.h" -static void app_thread(void * argument) -{ - if (openiotsdk_network_init(true)) - { - ChipLogError(NotSpecified, "Network initialization failed"); - goto exit; - } - - if (openiotsdk_chip_run()) - { - ChipLogError(NotSpecified, "CHIP stack run failed"); - goto exit; - } - - ChipLogProgress(NotSpecified, "Open IoT SDK lock-app example application run"); - - while (true) - { - // Add forever delay to ensure proper workload for this thread - osDelay(osWaitForever); - } - - openiotsdk_chip_shutdown(); - -exit: - osThreadTerminate(osThreadGetId()); -} - int main() { - ChipLogProgress(NotSpecified, "Open IoT SDK lock-app example application start"); - if (openiotsdk_platform_init()) { ChipLogError(NotSpecified, "Open IoT SDK platform initialization failed"); @@ -66,22 +36,29 @@ int main() return EXIT_FAILURE; } - static const osThreadAttr_t thread_attr = { - .stack_size = 16 * 1024 // Allocate enough stack for app thread - }; + ChipLogProgress(NotSpecified, "Open IoT SDK lock-app example application start"); - osThreadId_t appThread = osThreadNew(app_thread, NULL, &thread_attr); - if (appThread == NULL) + if (openiotsdk_network_init(true)) { - ChipLogError(NotSpecified, "Failed to create app thread"); + ChipLogError(NotSpecified, "Network initialization failed"); return EXIT_FAILURE; } - if (openiotsdk_platform_run()) + if (openiotsdk_chip_run()) { - ChipLogError(NotSpecified, "Open IoT SDK platform run failed"); + ChipLogError(NotSpecified, "CHIP stack run failed"); return EXIT_FAILURE; } + ChipLogProgress(NotSpecified, "Open IoT SDK lock-app example application run"); + + while (true) + { + // Add forever delay to ensure proper workload for this thread + osDelay(osWaitForever); + } + + openiotsdk_chip_shutdown(); + return EXIT_SUCCESS; } diff --git a/examples/lock-app/qpg/zap/BUILD.gn b/examples/lock-app/qpg/zap/BUILD.gn index a0eb662971f4ed..67e29db5f3f249 100644 --- a/examples/lock-app/qpg/zap/BUILD.gn +++ b/examples/lock-app/qpg/zap/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/chip_data_model.gni") chip_data_model("zap") { diff --git a/examples/lock-app/silabs/SiWx917/include/AppConfig.h b/examples/lock-app/silabs/SiWx917/include/AppConfig.h index f6985596d8993e..62cff5df0aa336 100644 --- a/examples/lock-app/silabs/SiWx917/include/AppConfig.h +++ b/examples/lock-app/silabs/SiWx917/include/AppConfig.h @@ -19,6 +19,8 @@ #pragma once +#include "silabs_utils.h" + // ---- Door lock Example App Config ---- #define APP_TASK_NAME "Lock" @@ -28,21 +30,3 @@ // Time it takes in ms for the simulated actuator to move from one // state to another. #define ACTUATOR_MOVEMENT_PERIOS_MS 10 - -// EFR Logging -#ifdef __cplusplus -extern "C" { -#endif - -void silabsInitLog(void); - -void efr32Log(const char * aFormat, ...); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); -void appError(int err); - -#ifdef __cplusplus -} - -#include -void appError(CHIP_ERROR error); -#endif diff --git a/examples/lock-app/silabs/SiWx917/src/AppTask.cpp b/examples/lock-app/silabs/SiWx917/src/AppTask.cpp index fe1d267e465f02..006d81ef66d0b0 100644 --- a/examples/lock-app/silabs/SiWx917/src/AppTask.cpp +++ b/examples/lock-app/silabs/SiWx917/src/AppTask.cpp @@ -61,6 +61,7 @@ using chip::app::Clusters::DoorLock::OperationSourceEnum; using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; using namespace ::chip::DeviceLayer::Internal; using namespace SI917DoorLock::LockInitParams; @@ -348,12 +349,12 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) button_event.Type = AppEvent::kEventType_Button; button_event.ButtonEvent.Action = btnAction; - if (button == SIWx917_BTN1 && btnAction == SL_SIMPLE_BUTTON_PRESSED) + if (button == SIWx917_BTN1 && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = LockActionEventHandler; sAppTask.PostEvent(&button_event); } - else if (button == SIWx917_BTN0 && btnAction == SL_SIMPLE_BUTTON_PRESSED) + else if (button == SIWx917_BTN0 && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = BaseApplication::ButtonHandler; sAppTask.PostEvent(&button_event); diff --git a/examples/lock-app/silabs/efr32/include/AppConfig.h b/examples/lock-app/silabs/efr32/include/AppConfig.h index 405bb4691ad8e5..2045ce3ef4d947 100644 --- a/examples/lock-app/silabs/efr32/include/AppConfig.h +++ b/examples/lock-app/silabs/efr32/include/AppConfig.h @@ -19,6 +19,8 @@ #pragma once +#include "silabs_utils.h" + // ---- Door lock Example App Config ---- #define APP_TASK_NAME "Lock" @@ -84,21 +86,3 @@ 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF - -// EFR Logging -#ifdef __cplusplus -extern "C" { -#endif - -void silabsInitLog(void); - -void efr32Log(const char * aFormat, ...); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); -void appError(int err); - -#ifdef __cplusplus -} - -#include -void appError(CHIP_ERROR error); -#endif diff --git a/examples/lock-app/silabs/efr32/src/AppTask.cpp b/examples/lock-app/silabs/efr32/src/AppTask.cpp index 93226e14f28646..cf3d1f5e40cfcc 100644 --- a/examples/lock-app/silabs/efr32/src/AppTask.cpp +++ b/examples/lock-app/silabs/efr32/src/AppTask.cpp @@ -64,6 +64,7 @@ using chip::app::Clusters::DoorLock::OperationSourceEnum; using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; using namespace ::chip::DeviceLayer::Internal; using namespace EFR32DoorLock::LockInitParams; @@ -143,9 +144,7 @@ CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT #ifdef DISPLAY_ENABLED GetLCD().Init((uint8_t *) "Lock-App", true); @@ -361,14 +360,13 @@ void AppTask::LockActionEventHandler(AppEvent * aEvent) } } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) { AppEvent button_event = {}; button_event.Type = AppEvent::kEventType_Button; button_event.ButtonEvent.Action = btnAction; - if (button == APP_LOCK_SWITCH && btnAction == SL_SIMPLE_BUTTON_PRESSED) + if (button == APP_LOCK_SWITCH && btnAction == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { button_event.Handler = LockActionEventHandler; sAppTask.PostEvent(&button_event); @@ -379,7 +377,6 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) sAppTask.PostEvent(&button_event); } } -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::ActionInitiated(LockManager::Action_t aAction, int32_t aActor) { diff --git a/examples/ota-requestor-app/ameba/main/CHIPDeviceManager.cpp b/examples/ota-requestor-app/ameba/main/CHIPDeviceManager.cpp index d0db78341501a5..c9722c3e6fb8b2 100644 --- a/examples/ota-requestor-app/ameba/main/CHIPDeviceManager.cpp +++ b/examples/ota-requestor-app/ameba/main/CHIPDeviceManager.cpp @@ -68,17 +68,14 @@ CHIP_ERROR CHIPDeviceManager::Init(CHIPDeviceManagerCallbacks * cb) SuccessOrExit(err); err = mFactoryDataProvider.Init(); - if (err == CHIP_NO_ERROR) + if (err != CHIP_NO_ERROR) { - SetCommissionableDataProvider(&mFactoryDataProvider); - SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider); - SetDeviceInstanceInfoProvider(&mFactoryDataProvider); - } - else - { - ChipLogProgress(DeviceLayer, "Using example DAC provider"); - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); + ChipLogError(DeviceLayer, "Error initializing FactoryData!"); + ChipLogError(DeviceLayer, "Check if you have flashed it correctly!"); } + SetCommissionableDataProvider(&mFactoryDataProvider); + SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider); + SetDeviceInstanceInfoProvider(&mFactoryDataProvider); if (CONFIG_NETWORK_LAYER_BLE) { diff --git a/examples/persistent-storage/cc13x2x7_26x2x7/chip.syscfg b/examples/persistent-storage/cc13x2x7_26x2x7/chip.syscfg index b2409535110003..995ad22af6b435 100644 --- a/examples/persistent-storage/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/persistent-storage/cc13x2x7_26x2x7/chip.syscfg @@ -22,16 +22,14 @@ var AESCCM = scripting.addModule("/ti/drivers/AESCCM"); var AESECB = scripting.addModule("/ti/drivers/AESECB"); var Button = scripting.addModule("/ti/drivers/apps/Button"); -var ECJPAKE = scripting.addModule("/ti/drivers/ECJPAKE"); var LED = scripting.addModule("/ti/drivers/apps/LED"); var NVS = scripting.addModule("/ti/drivers/NVS"); var RF = scripting.addModule("/ti/drivers/RF"); var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); -var RTOS = scripting.addModule("/ti/drivers/RTOS"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); var TRNG = scripting.addModule("/ti/drivers/TRNG"); -var Thread = scripting.addModule("/ti/thread/thread"); var SHA2 = scripting.addModule("/ti/drivers/SHA2"); -var UART = scripting.addModule("/ti/drivers/UART"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); var ble = scripting.addModule("/ti/ble5stack/ble"); var dmm = scripting.addModule("/ti/dmm/dmm"); var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); @@ -43,20 +41,19 @@ var AESECB1 = AESECB.addInstance(); var AESECB2 = AESECB.addInstance(); var Button1 = Button.addInstance(); var Button2 = Button.addInstance(); -var ECJPAKE = ECJPAKE.addInstance(); var NVS1 = NVS.addInstance(); +var NVS2 = NVS.addInstance(); var SHA21 = SHA2.addInstance(); var LED1 = LED.addInstance(); var LED2 = LED.addInstance(); var TRNG1 = TRNG.addInstance(); var TRNG2 = TRNG.addInstance(); var TRNG3 = TRNG.addInstance(); -var UART1 = UART.addInstance(); +var UART2 = UART2.addInstance(); var AESCTRDRBG1 = AESCTRDRBG.addInstance(); var ECDH1 = ECDH.addInstance(); AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; -AESCTRDRBG1.aesctrObject.$name = "CONFIG_AESCTR_0"; AESCCM1.$name = "CONFIG_AESCCM0"; @@ -65,9 +62,6 @@ AESECB2.$name = "CONFIG_AESECB_1"; ECDH1.$name = "CONFIG_ECDH0"; -/* RTOS */ -RTOS.name = "FreeRTOS"; - /* Left Button */ Button1.$name = "CONFIG_BTN_LEFT"; Button1.$hardware = system.deviceData.board.components["BTN-1"]; @@ -84,23 +78,24 @@ Button2.gpioPin.interruptTrigger = "Falling Edge"; /* ======== CCFG ======== */ var CCFG = scripting.addModule("/ti/devices/CCFG"); -const deviceName = system.getScript("/ti/ti154stack/ti154stack_common.js").getLaunchPadFromDevice(); const ccfgSettings = system.getScript("/ti/common/lprf_ccfg_settings.js").ccfgSettings; for(var setting in ccfgSettings) { CCFG[setting] = ccfgSettings[setting]; } -// Update LF Clock Source for CC2652RB devices -if(deviceName.includes("RB")) -{ - CCFG.srcClkLF = "Derived from HF XOSC"; -} +// Disable CCFG generation, this is added by the BIM project +CCFG.enableCodeGeneration = false; + /* NVS */ NVS1.$name = "CONFIG_NVSINTERNAL"; NVS1.internalFlash.regionBase = 0xAA000; NVS1.internalFlash.regionSize = 0x4000; +NVS2.$name = "CONFIG_NVSEXTERNAL"; +NVS2.nvsType = "External"; // NVS Region Type +NVS2.$hardware = system.deviceData.board.components.MX25R8035F; + /* RF */ /* if an antenna component exists, assign it to the rf instance */ if (system.deviceData.board && system.deviceData.board.components.RF) { @@ -113,6 +108,58 @@ for(var setting in rfDesignSettings) RFDesign[setting] = rfDesignSettings[setting]; } +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + /* Red LED */ LED1.$name = "CONFIG_LED_RED"; LED1.$hardware = system.deviceData.board.components.LED_RED; @@ -128,16 +175,14 @@ LED2.gpioPin.mode = "Output"; LED2.gpioPin.callbackFunction = ""; /* Debug UART */ -UART1.$hardware = system.deviceData.board.components.XDS110UART; -UART1.$name = "CONFIG_UART_DEBUG"; +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART2_DEBUG"; /* TRNG */ TRNG1.$name = "CONFIG_TRNG_0"; -TRNG2.$name = "CONFIG_TRNG_1"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; TRNG3.$name = "CONFIG_TRNG_APP"; -RTOS.name = "FreeRTOS"; - /* BLE */ ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; ble.maxConnNum = 1; @@ -145,15 +190,14 @@ ble.numOfAdvSets = 1; ble.lockProject = true; ble.oneLibSizeOpt = true; ble.maxPDUSize = 255; -ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param2"; ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; ble.connUpdateParamsPeripheral.reqMinConnInt = 30; ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; + ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; -ble.advSet1.advParam1.primIntMin = 100; -ble.advSet1.advParam1.primIntMax = 200; /* DMM */ dmm.project = "ti_thread_thermostat_remote_display"; diff --git a/examples/persistent-storage/cc13x2x7_26x2x7/include/AppConfig.h b/examples/persistent-storage/cc13x2x7_26x2x7/include/AppConfig.h index 3cead418532caa..77f2cc37421d36 100644 --- a/examples/persistent-storage/cc13x2x7_26x2x7/include/AppConfig.h +++ b/examples/persistent-storage/cc13x2x7_26x2x7/include/AppConfig.h @@ -1,6 +1,5 @@ /* * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/examples/placeholder/linux/apps/app1/ciTests.json b/examples/placeholder/linux/apps/app1/ciTests.json index a54ee164a0d197..2a505b5fa74961 100644 --- a/examples/placeholder/linux/apps/app1/ciTests.json +++ b/examples/placeholder/linux/apps/app1/ciTests.json @@ -1,12 +1,20 @@ { "Test": [ "Test_TC_BINFO_2_3_Simulated", + "Test_TC_ACT_3_1_Simulated", + "Test_TC_BOOL_3_1_Simulated", "Test_TC_DESC_2_2_Simulated", "Test_TC_DGETH_3_1_Simulated", "Test_TC_DGSW_3_1_Simulated", "Test_TC_DGWIFI_3_1_Simulated", + "Test_TC_FLW_3_1_Simulated", "Test_TC_G_3_1_Simulated", + "Test_TC_I_3_1_Simulated", + "Test_TC_PRS_3_1_Simulated", + "Test_TC_PS_3_1_Simulated", + "Test_TC_PSCFG_3_1_Simulated", "Test_TC_RH_3_1_Simulated", + "Test_TC_SWTCH_3_1_Simulated", "Test_TC_WNCV_5_1_Simulated", "Test_TC_LCFG_3_1_Simulated", "Test_TC_LUNIT_1_1_Simulated", diff --git a/examples/platform/asr/BUILD.gn b/examples/platform/asr/BUILD.gn new file mode 100755 index 00000000000000..432d63cff64aa2 --- /dev/null +++ b/examples/platform/asr/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/asr.gni") +import("//build_overrides/chip.gni") + +import("${asr_sdk_build_root}/asr_sdk.gni") + +config("chip_examples_project_config") { + include_dirs = [ "project_include" ] +} diff --git a/examples/platform/asr/CHIPDeviceManager.cpp b/examples/platform/asr/CHIPDeviceManager.cpp new file mode 100644 index 00000000000000..8587b0b65abde2 --- /dev/null +++ b/examples/platform/asr/CHIPDeviceManager.cpp @@ -0,0 +1,76 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * This file implements the CHIP Device Interface that is used by + * applications to interact with the CHIP stack + * + */ + +#include + +#include "CHIPDeviceManager.h" +#include +#include +#include +#include +#include + +using namespace ::chip; + +namespace chip { + +namespace DeviceManager { + +using namespace ::chip::DeviceLayer; + +void CHIPDeviceManager::CommonDeviceEventHandler(const ChipDeviceEvent * event, intptr_t arg) +{ + CHIPDeviceManagerCallbacks * cb = reinterpret_cast(arg); + if (cb != nullptr) + { + cb->DeviceEventCallback(event, reinterpret_cast(cb)); + } +} + +CHIP_ERROR CHIPDeviceManager::Init(CHIPDeviceManagerCallbacks * cb) +{ + mCB = cb; + + PlatformMgr().AddEventHandler(CHIPDeviceManager::CommonDeviceEventHandler, reinterpret_cast(cb)); + + return CHIP_NO_ERROR; +} +} // namespace DeviceManager +} // namespace chip + +void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & path, uint8_t type, uint16_t size, uint8_t * value) +{ + chip::DeviceManager::CHIPDeviceManagerCallbacks * cb = + chip::DeviceManager::CHIPDeviceManager::GetInstance().GetCHIPDeviceManagerCallbacks(); + + ChipLogProgress(Zcl, + "MatterPostAttributeChangeCallback - Cluster ID: " ChipLogFormatMEI + ", EndPoint ID: '0x%02x', Attribute ID: " ChipLogFormatMEI, + ChipLogValueMEI(path.mClusterId), path.mEndpointId, ChipLogValueMEI(path.mAttributeId)); + + if (cb != nullptr) + { + cb->PostAttributeChangeCallback(path.mEndpointId, path.mClusterId, path.mAttributeId, type, size, value); + } +} diff --git a/examples/platform/asr/CHIPDeviceManager.h b/examples/platform/asr/CHIPDeviceManager.h new file mode 100644 index 00000000000000..0f4af78bc756b2 --- /dev/null +++ b/examples/platform/asr/CHIPDeviceManager.h @@ -0,0 +1,124 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * This file contains definitions for the CHIP DeviceManager Interface + * + * This object will co-ordinate multiple activities such as + * initialisation, rendezvous, session mgmt and other such + * activities within the CHIP stack. This is a singleton object. + */ + +#pragma once + +#include +#include +#include + +#include + +#include +#include + +#include + +namespace chip { +namespace DeviceManager { + +/** + * @brief + * This class provides a skeleton for all the callback functions. The functions will be + * called by other objects within the CHIP stack for specific events. + * Applications interested in receiving specific callbacks can specialize this class and handle + * these events in their implementation of this class. + */ +class CHIPDeviceManagerCallbacks +{ +public: + /** + * @brief + * Called when CHIP Device events (PublicEventTypes) are triggered. + * + * @param event ChipDeviceEvent that occurred + * @param arg arguments specific to the event, if any + */ + virtual void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg) {} + + /** + * @brief + * Called after an attribute has been changed + * + * @param endpoint endpoint id + * @param clusterID cluster id + * @param attributeId attribute id that was changed + * @param mask mask of the attribute + * @param manufacturerCode manufacturer code + * @param type attribute type + * @param size size of the attribute + * @param value pointer to the new value + */ + virtual void PostAttributeChangeCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value) + {} + virtual ~CHIPDeviceManagerCallbacks() {} +}; + +/** + * @brief + * A common class that drives other components of the CHIP stack + */ +class DLL_EXPORT CHIPDeviceManager +{ +public: + CHIPDeviceManager(const CHIPDeviceManager &) = delete; + CHIPDeviceManager(const CHIPDeviceManager &&) = delete; + CHIPDeviceManager & operator=(const CHIPDeviceManager &) = delete; + + static CHIPDeviceManager & GetInstance() + { + static CHIPDeviceManager instance; + return instance; + } + + /** + * @brief + * Initialise CHIPDeviceManager + * + * @param cb Application's instance of the CHIPDeviceManagerCallbacks for consuming events + */ + CHIP_ERROR Init(CHIPDeviceManagerCallbacks * cb); + + /** + * @brief + * Fetch a pointer to the registered CHIPDeviceManagerCallbacks object. + * + */ + CHIPDeviceManagerCallbacks * GetCHIPDeviceManagerCallbacks() { return mCB; } + + /** + * Use internally for registration of the ChipDeviceEvents + */ + static void CommonDeviceEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + +private: + CHIPDeviceManagerCallbacks * mCB = nullptr; + CHIPDeviceManager() {} +}; + +} // namespace DeviceManager +} // namespace chip diff --git a/examples/platform/asr/LEDWidget.cpp b/examples/platform/asr/LEDWidget.cpp new file mode 100644 index 00000000000000..f89f502f7ff62f --- /dev/null +++ b/examples/platform/asr/LEDWidget.cpp @@ -0,0 +1,280 @@ +/* + * + * 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 "LEDWidget.h" +#ifdef CFG_PLF_RV32 +#include "asr_gpio.h" +#include "asr_pinmux.h" +#include "asr_pwm.h" +#define duet_pwm_dev_t asr_pwm_dev_t +#define duet_pwm_config_t asr_pwm_config_t +#define duet_pwm_para_chg asr_pwm_para_chg +#define duet_pwm_init asr_pwm_init +#define duet_pwm_start asr_pwm_start +#else +#include "duet_gpio.h" +#include "duet_pinmux.h" +#include "duet_pwm.h" +#endif +#include "AppConfig.h" +#include + +/******************************************************************************* + * Macro Definitions + *******************************************************************************/ +/* Allowed TCPWM compare value for maximum brightness */ +#define LED_MAX_BRIGHTNESS (100u) + +/* Allowed TCPWM compare value for minimum brightness*/ +#define LED_MIN_BRIGHTNESS (0u) + +#define PWM_LED_FREQ_HZ (1000u) /* in Hz */ + +/* subtracting from 100 since the LED is connected in active low configuration */ +#define GET_DUTY_CYCLE(x) (100 - x) + +// PWM period in micro seconds +#define LED_PWM_PERIOD_US (255u) + +static void show_pwm(duet_pwm_dev_t * pwm_dev, uint8_t val) +{ + duet_pwm_config_t pwm_cfg; + + if (val < LED_MIN_BRIGHTNESS) + val = LED_MIN_BRIGHTNESS; + pwm_cfg.duty_cycle = (float) (val) / LED_PWM_PERIOD_US; + pwm_cfg.freq = PWM_LED_FREQ_HZ; + + duet_pwm_para_chg(pwm_dev, pwm_cfg); +} + +static void init_pwm(duet_pwm_dev_t * pwm_dev, uint8_t ledNum, uint8_t val) +{ + pwm_dev->port = ledNum; + pwm_dev->config.duty_cycle = val; + pwm_dev->config.freq = PWM_LED_FREQ_HZ; + pwm_dev->priv = NULL; + duet_pwm_init(pwm_dev); +} + +void LEDWidget::Init(uint8_t ledNum) +{ + mLastChangeTimeMS = 0; + mBlinkOnTimeMS = 0; + mBlinkOffTimeMS = 0; + mState = 0; + mbrightness = LED_MIN_BRIGHTNESS; + mHue = 0; + mSaturation = 0; + + if (ledNum == LIGHT_RGB_GREEN) + { +#ifdef CFG_PLF_RV32 + asr_pinmux_config(LIGHT_RGB_RED_PAD, PF_PWM); +#endif + init_pwm(&pwm_led_g, ledNum, LED_MIN_BRIGHTNESS); + } + else if (ledNum == LIGHT_RGB_BLUE) + { +#ifdef CFG_PLF_RV32 + asr_pinmux_config(LIGHT_RGB_BLUE_PAD, PF_PWM); +#endif + init_pwm(&pwm_led_b, ledNum, LED_MIN_BRIGHTNESS); + } + else + { +#ifdef CFG_PLF_RV32 + asr_pinmux_config(LIGHT_RGB_GREEN_PAD, PF_PWM); +#endif + init_pwm(&pwm_led, ledNum, LED_MIN_BRIGHTNESS); + } +} + +void LEDWidget::Invert(void) +{ + Set(!mState); +} + +void LEDWidget::Set(bool state) +{ + mLastChangeTimeMS = mBlinkOnTimeMS = mBlinkOffTimeMS = 0; + DoSet(state); +} + +bool LEDWidget::Get() +{ + return mState; +} + +void LEDWidget::Blink(uint32_t changeRateMS) +{ + Blink(changeRateMS, changeRateMS); +} + +void LEDWidget::Blink(uint32_t onTimeMS, uint32_t offTimeMS) +{ + mBlinkOnTimeMS = onTimeMS; + mBlinkOffTimeMS = offTimeMS; + Animate(); +} + +void LEDWidget::Animate() +{ + if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0) + { + uint64_t nowMS = chip::System::SystemClock().GetMonotonicMilliseconds64().count(); + uint64_t stateDurMS = ((mState) ? mBlinkOnTimeMS : mBlinkOffTimeMS); + uint64_t nextChangeTimeMS = mLastChangeTimeMS + stateDurMS; + + if (nextChangeTimeMS < nowMS) + { + DoSet(!mState); + mLastChangeTimeMS = nowMS; + } + } +} + +void LEDWidget::DoSet(bool state) +{ + if (mState != state) + { + (state) ? PWM_start() : PWM_stop(); + } + mState = state; +} + +void LEDWidget::RGB_init() +{ + Init(LIGHT_RGB_RED); // red light of RGB + Init(LIGHT_RGB_GREEN); // green light of RGB + Init(LIGHT_RGB_BLUE); // blue light of RGB +} + +void LEDWidget::PWM_start() +{ + if (!mState) + { + /* Start PWM to turn the LED on */ + if (0 != duet_pwm_start(&pwm_led)) + { + ASR_LOG("PWM failed to start!"); + } + +#if (LIGHT_SELECT == LIGHT_SELECT_RGB) + /* Start PWM to turn the LED on */ + if (0 != duet_pwm_start(&pwm_led_g)) + { + ASR_LOG("PWM failed to start!"); + } + + /* Start PWM to turn the LED on */ + if (0 != duet_pwm_start(&pwm_led_b)) + { + ASR_LOG("PWM failed to start!"); + } +#endif + mState = 1; + } +} + +void LEDWidget::PWM_stop() +{ + SetBrightness(LED_MIN_BRIGHTNESS); + mbrightness = LED_MIN_BRIGHTNESS; + mState = 0; +} + +void LEDWidget::SetBrightness(uint8_t brightness) +{ + mbrightness = brightness; + SetColor(mHue, mSaturation); +} + +void LEDWidget::SetColor(uint8_t Hue, uint8_t Saturation) +{ + uint8_t red, green, blue; + uint8_t sSaturation, sbrightness; + uint16_t sHue; + + sbrightness = (mState) ? mbrightness : 0; + + sHue = static_cast(Hue) * 360 / 254; // sHue [0, 360] + sSaturation = static_cast(Saturation) * 100 / 254; // sSaturation [0 , 100] + + HSB2rgb(sHue, sSaturation, sbrightness, red, green, blue); + ASR_LOG("brightness: %d, red: %d, green: %d, blue: %d", sbrightness, red, green, blue); + + mHue = Hue; + mSaturation = Saturation; + + showRGB(red, green, blue); +} + +void LEDWidget::HSB2rgb(uint16_t Hue, uint8_t Saturation, uint8_t brightness, uint8_t & red, uint8_t & green, uint8_t & blue) +{ + uint16_t i = Hue / 60; + uint16_t rgb_max = brightness; + uint16_t rgb_min = rgb_max * (100 - Saturation) / 100; + uint16_t diff = Hue % 60; + uint16_t rgb_adj = (rgb_max - rgb_min) * diff / 60; + + switch (i) + { + case 0: + red = rgb_max; + green = rgb_min + rgb_adj; + blue = rgb_min; + break; + case 1: + red = rgb_max - rgb_adj; + green = rgb_max; + blue = rgb_min; + break; + case 2: + red = rgb_min; + green = rgb_max; + blue = rgb_min + rgb_adj; + break; + case 3: + red = rgb_min; + green = rgb_max - rgb_adj; + blue = rgb_max; + break; + case 4: + red = rgb_min + rgb_adj; + green = rgb_min; + blue = rgb_max; + break; + default: + red = rgb_max; + green = rgb_min; + blue = rgb_max - rgb_adj; + break; + } +} + +void LEDWidget::showRGB(uint8_t red, uint8_t green, uint8_t blue) +{ + show_pwm(&pwm_led, red); + +#if (LIGHT_SELECT == LIGHT_SELECT_RGB) + show_pwm(&pwm_led_g, green); + + show_pwm(&pwm_led_b, blue); +#endif +} diff --git a/examples/platform/asr/LEDWidget.h b/examples/platform/asr/LEDWidget.h new file mode 100644 index 00000000000000..028a852fba1933 --- /dev/null +++ b/examples/platform/asr/LEDWidget.h @@ -0,0 +1,80 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#ifdef CFG_PLF_RV32 +#include "asr_pwm.h" +#define duet_pwm_dev_t asr_pwm_dev_t +#else +#include "duet_pwm.h" +#endif +#ifdef __cplusplus +extern "C" { +#endif +void RGB_setup_HSB(uint8_t Hue, uint8_t Saturation); +#ifdef __cplusplus +} +#endif + +#define LIGHT_SELECT_LED 1 +#define LIGHT_SELECT_RGB 2 +#define LIGHT_SELECT LIGHT_SELECT_RGB + +#define LIGHT_RGB_RED PWM_OUTPUT_CH6 +#define LIGHT_RGB_GREEN PWM_OUTPUT_CH4 +#define LIGHT_RGB_BLUE PWM_OUTPUT_CH1 + +#define LIGHT_RGB_RED_PAD PAD7 +#define LIGHT_RGB_GREEN_PAD PAD6 +#define LIGHT_RGB_BLUE_PAD PAD10 + +class LEDWidget +{ +public: + static void InitGpio(void); + void Init(uint8_t port); + void Set(bool state); + bool Get(void); + void Invert(void); + void Blink(uint32_t changeRateMS); + void Blink(uint32_t onTimeMS, uint32_t offTimeMS); + void Animate(); + void PWM_start(); + void PWM_stop(); + void RGB_init(); + void SetBrightness(uint8_t brightness); + void SetColor(uint8_t Hue, uint8_t Saturation); + void HSB2rgb(uint16_t Hue, uint8_t Saturation, uint8_t brightness, uint8_t & red, uint8_t & green, uint8_t & blue); + void showRGB(uint8_t red, uint8_t green, uint8_t blue); + +private: + uint64_t mLastChangeTimeMS = 0; + uint32_t mBlinkOnTimeMS = 0; + uint32_t mBlinkOffTimeMS = 0; + bool mState = 0; + uint8_t mbrightness = 0; + + uint8_t mHue; + uint8_t mSaturation; + duet_pwm_dev_t pwm_led; + duet_pwm_dev_t pwm_led_g; + duet_pwm_dev_t pwm_led_b; + void DoSet(bool state); +}; diff --git a/examples/platform/asr/args.gni b/examples/platform/asr/args.gni new file mode 100755 index 00000000000000..53604116cd174f --- /dev/null +++ b/examples/platform/asr/args.gni @@ -0,0 +1,21 @@ +# 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. + +import("//build_overrides/chip.gni") + +chip_ble_project_config_include = "" +chip_device_project_config_include = "" +chip_project_config_include = "" +chip_inet_project_config_include = "" +chip_system_project_config_include = "" diff --git a/examples/platform/asr/init_Matter.cpp b/examples/platform/asr/init_Matter.cpp new file mode 100644 index 00000000000000..8f46ac4f9ed423 --- /dev/null +++ b/examples/platform/asr/init_Matter.cpp @@ -0,0 +1,121 @@ +/* + * + * 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 "AppConfig.h" +#include +#include +#include +#include +#include +#include +#include +#include +#if CONFIG_ENABLE_CHIP_SHELL +#include +#endif +#include + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; +using namespace ::chip::Credentials; +using namespace ::chip::System; + +namespace { +ASRFactoryDataProvider sFactoryDataProvider; +} // namespace + +chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; + +CHIP_ERROR MatterInitializer::Matter_Task_Config(lega_task_config_t * cfg) +{ + lega_rtos_get_chip_task_cfg(cfg); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR MatterInitializer::Init_Matter_Stack(const char * appName) +{ + // mbedtls_platform_set_calloc_free(CHIPPlatformMemoryCalloc, CHIPPlatformMemoryFree); + + ASR_LOG("==================================================\r\n"); + ASR_LOG("%s starting\r\n", appName); + ASR_LOG("==================================================\r\n"); + + CHIP_ERROR err = CHIP_NO_ERROR; + + err = chip::DeviceLayer::PersistedStorage::KeyValueStoreMgrImpl().Init(); + if (err != CHIP_NO_ERROR) + { + ASR_LOG("PersistedStorage::KeyValueStoreMgrImpl().Init() failed"); + appError(err); + } + + SetCommissionableDataProvider(&sFactoryDataProvider); + //============================================== + // Init Matter Stack + //============================================== + ASR_LOG("Init CHIP Stack"); + // Init Chip memory management before the stack + err = chip::Platform::MemoryInit(); + ReturnErrorOnFailure(err); + + err = PlatformMgr().InitChipStack(); + ReturnErrorOnFailure(err); + + err = sFactoryDataProvider.Init(); + ReturnErrorOnFailure(err); + + SetDeviceInstanceInfoProvider(&sFactoryDataProvider); + + chip::DeviceLayer::ConnectivityMgr().SetBLEDeviceName(appName); + + if (CONFIG_NETWORK_LAYER_BLE) + { + ConnectivityMgr().SetBLEAdvertisingEnabled(true); + } + return CHIP_NO_ERROR; +} + +CHIP_ERROR MatterInitializer::Init_Matter_Server(void) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + // Init Matter Server and Start Event Loop + chip::DeviceLayer::PlatformMgr().LockChipStack(); + static chip::CommonCaseDeviceServerInitParams initParams; + (void) initParams.InitializeStaticResourcesBeforeServerInit(); + + chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); + chip::Server::GetInstance().Init(initParams); + chip::DeviceLayer::PlatformMgr().UnlockChipStack(); + + // Initialize device attestation config + SetDeviceAttestationCredentialsProvider(&sFactoryDataProvider); + + ASR_LOG("Starting Platform Manager Event Loop"); + // // Start a task to run the CHIP Device event loop. + err = PlatformMgr().StartEventLoopTask(); + ReturnErrorOnFailure(err); + +#if CONFIG_ENABLE_CHIP_SHELL + chip::LaunchShell(); +#endif + + return CHIP_NO_ERROR; +} diff --git a/examples/platform/silabs/SiWx917/siwx917_utils.cpp b/examples/platform/asr/init_Matter.h similarity index 58% rename from examples/platform/silabs/SiWx917/siwx917_utils.cpp rename to examples/platform/asr/init_Matter.h index 49a23255cd93c5..d6bea07bee8036 100644 --- a/examples/platform/silabs/SiWx917/siwx917_utils.cpp +++ b/examples/platform/asr/init_Matter.h @@ -1,7 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2022 Silabs. + * Copyright (c) 2022 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,21 +15,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include +#include +#include +#include +#include -#include "siwx917_utils.h" -#include "init_ccpPlatform.h" - -#include - -void appError(int err) -{ - SILABS_LOG("!!!!!!!!!!!! App Critical Error: %d !!!!!!!!!!!", err); - portDISABLE_INTERRUPTS(); - while (true) - ; -} - -void appError(CHIP_ERROR error) +class MatterInitializer { - appError(static_cast(error.AsInteger())); -} +public: + static CHIP_ERROR Init_Matter_Stack(const char * appName); + static CHIP_ERROR Init_Matter_Server(void); + static CHIP_ERROR Matter_Task_Config(lega_task_config_t * cfg); +}; diff --git a/examples/platform/asr/init_OTARequestor.cpp b/examples/platform/asr/init_OTARequestor.cpp new file mode 100644 index 00000000000000..3bcad294bd162f --- /dev/null +++ b/examples/platform/asr/init_OTARequestor.cpp @@ -0,0 +1,84 @@ +/* + * + * 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 "init_OTARequestor.h" +#include "app/clusters/ota-requestor/DefaultOTARequestorStorage.h" +#include +#include +#include +#include +#include +#include + +using namespace chip; +using namespace chip::DeviceLayer; + +namespace { +DefaultOTARequestor gRequestorCore; +DefaultOTARequestorStorage gRequestorStorage; +ExtendedOTARequestorDriver gRequestorUser; +BDXDownloader gDownloader; +ASROTAImageProcessor gImageProcessor; +chip::ota::DefaultOTARequestorUserConsent gUserConsentProvider; +static chip::ota::UserConsentState gUserConsentState = chip::ota::UserConsentState::kGranted; +} // namespace + +#define OTA_PERIODIC_TIMEOUT 86400 // 24 * 60 * 60 + +extern "C" void asrQueryImageCmdHandler() +{ + ChipLogProgress(DeviceLayer, "Calling asrQueryImageCmdHandler"); + PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->TriggerImmediateQuery(); }); +} + +extern "C" void asrApplyUpdateCmdHandler() +{ + ChipLogProgress(DeviceLayer, "Calling asrApplyUpdateCmdHandler"); + PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->ApplyUpdate(); }); +} + +void OTAInitializer::InitOTARequestor(void) +{ + SetRequestorInstance(&gRequestorCore); + ConfigurationMgr().StoreSoftwareVersion(CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION); + gRequestorStorage.Init(chip::Server::GetInstance().GetPersistentStorage()); + // Set server instance used for session establishment + gRequestorCore.Init(chip::Server::GetInstance(), gRequestorStorage, gRequestorUser, gDownloader); + gImageProcessor.SetOTADownloader(&gDownloader); + // Connect the Downloader and Image Processor objects + gDownloader.SetImageProcessorDelegate(&gImageProcessor); + + gRequestorUser.SetPeriodicQueryTimeout(OTA_PERIODIC_TIMEOUT); + gRequestorUser.Init(&gRequestorCore, &gImageProcessor); + if (gUserConsentState != chip::ota::UserConsentState::kUnknown) + { + gUserConsentProvider.SetUserConsentState(gUserConsentState); + gRequestorUser.SetUserConsentDelegate(&gUserConsentProvider); + } + ChipLogProgress(DeviceLayer, "Current Software Version: %u", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION); + ChipLogProgress(DeviceLayer, "Current Software Version String: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); +} + +void OTAInitializer::ReloadQueryTimeout(uint32_t timeout) +{ + if (timeout > 0) + { + gRequestorUser.SetPeriodicQueryTimeout(timeout); + gRequestorUser.RekickPeriodicQueryTimer(); + } +} diff --git a/examples/platform/asr/init_OTARequestor.h b/examples/platform/asr/init_OTARequestor.h new file mode 100755 index 00000000000000..6975da8fb1a12d --- /dev/null +++ b/examples/platform/asr/init_OTARequestor.h @@ -0,0 +1,30 @@ +/* + * + * 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 "stdint.h" + +class OTAInitializer +{ +public: + static OTAInitializer & Instance(void) + { + static OTAInitializer sInitOTA; + return sInitOTA; + } + void InitOTARequestor(void); + void ReloadQueryTimeout(uint32_t timeout); +}; diff --git a/examples/platform/asr/init_asrPlatform.cpp b/examples/platform/asr/init_asrPlatform.cpp new file mode 100644 index 00000000000000..b91419812b88a9 --- /dev/null +++ b/examples/platform/asr/init_asrPlatform.cpp @@ -0,0 +1,163 @@ +/* + * + * 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. + */ + +/** + * @file + * This file provides the function to initialize the ASR platform. + */ + +#include "AppConfig.h" +#include +#include + +#include +#include +#include + +#include "lega_wlan_api.h" +#include "soc_init.h" +#ifdef CFG_PLF_RV32 +#include "asr_flash_kv.h" +#include "asr_pinmux.h" +#include "asr_sec_hw_common.h" +#include "asr_uart.h" +#else +#include "duet_flash_kv.h" +#include "duet_pinmux.h" +#include "duet_uart.h" +#include "duet_version.h" +#endif +#include "lega_ota_utils.h" +#include "lega_rtos_api.h" +#include "printf_uart.h" +#include "tcpip.h" +#if (CFG_EASY_LOG_ENABLE == 1) +#include "elog.h" +#include "elog_cfg.h" +#endif + +#ifdef CFG_PLF_RV32 +#define LEGA_UART0_INDEX UART0_INDEX +#define LEGA_UART1_INDEX UART1_INDEX +#define LEGA_UART2_INDEX UART2_INDEX +#define duet_pinmux_config asr_pinmux_config +#define duet_uart_init printf_uart_init +#define duet_flash_kv_init alto_flash_kv_init +#else +#define LEGA_UART0_INDEX DUET_UART0_INDEX +#define LEGA_UART1_INDEX DUET_UART1_INDEX +#define LEGA_UART2_INDEX DUET_UART2_INDEX +#endif + +#define UART1_TX_PIN PAD2 +#define UART1_RX_PIN PAD3 + +#ifdef CFG_PLF_RV32 +extern asr_uart_dev_t lega_at_uart; +#else +extern duet_uart_dev_t lega_at_uart; +#endif + +#ifdef __cplusplus +extern "C" { +#endif +void lega_sram_rf_pta_init(void); +void lega_recovery_phy_fsm_config(void); +void lega_wlan_efuse_read(void); +int lega_wlan_init(void); +void ota_roll_back_pro(void); +int32_t duet_flash_kv_init(void); +void lega_at_cmd_register_all(void); +int lega_at_init(void); +void at_handle_uartirq(char ch); +int asr_security_engine_init(); +void at_uart_init(void); +#ifdef __cplusplus +} +#endif + +void at_uart_init(void) +{ + memset(&lega_at_uart, 0, sizeof(lega_at_uart)); + + lega_at_uart.config.baud_rate = UART_BAUDRATE_115200; + lega_at_uart.config.data_width = DATA_8BIT; + lega_at_uart.config.flow_control = FLOW_CTRL_DISABLED; + lega_at_uart.config.parity = PARITY_NO; + lega_at_uart.config.stop_bits = STOP_1BIT; + lega_at_uart.config.mode = TX_RX_MODE; + lega_at_uart.port = UART1_INDEX; + + duet_pinmux_config(UART1_TX_PIN, PF_UART1); + duet_pinmux_config(UART1_RX_PIN, PF_UART1); + + // register uart callback func for receiving at command + lega_at_uart.priv = (void *) (at_handle_uartirq); + duet_uart_init(&lega_at_uart); +} + +void init_asrPlatform(void) +{ + // don't run any code before soc_pre_init. + soc_pre_init(); + + soc_init(); + + duet_flash_kv_init(); + + // uart init and register uart for receiving at command + at_uart_init(); + + // ota roll back,just for flash_remapping + ota_roll_back_pro(); + + // register uart for printf log, the used uart should be init before. + printf_uart_register(LEGA_UART1_INDEX); + // register uart for at log, the used uart should be init before. + printf2_uart_register(LEGA_UART1_INDEX); + + // printf("\napp version: %s\n",LEGA_VERSION_STR); + + /* set EasyLogger log format */ +#if (CFG_EASY_LOG_ENABLE == 1) + elog_init(); + elog_set_fmt(ELOG_LVL_ASSERT, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME); + elog_set_fmt(ELOG_LVL_ERROR, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME); + elog_set_fmt(ELOG_LVL_WARN, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME); + elog_set_fmt(ELOG_LVL_INFO, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME); + elog_set_fmt(ELOG_LVL_DEBUG, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME); + elog_set_fmt(ELOG_LVL_VERBOSE, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME); + elog_start(); +#endif + + lega_wlan_efuse_read(); + + lega_sram_rf_pta_init(); + + lega_recovery_phy_fsm_config(); + + asr_security_engine_init(); +#if !CONFIG_ENABLE_CHIP_SHELL + lega_at_init(); +#endif + lega_at_cmd_register_all(); + + lega_wlan_init(); + + tcpip_init(NULL, NULL); +} diff --git a/src/test_driver/openiotsdk/unit-tests/lwip-config/user_lwipopts.h b/examples/platform/asr/init_asrPlatform.h old mode 100644 new mode 100755 similarity index 83% rename from src/test_driver/openiotsdk/unit-tests/lwip-config/user_lwipopts.h rename to examples/platform/asr/init_asrPlatform.h index 59ed1720c7e36c..33dc6337dda189 --- a/src/test_driver/openiotsdk/unit-tests/lwip-config/user_lwipopts.h +++ b/examples/platform/asr/init_asrPlatform.h @@ -16,10 +16,11 @@ * limitations under the License. */ -#ifndef USER_LWIPOPTS_H -#define USER_LWIPOPTS_H +/** + * @file + * This file provides the function to initialize the ASR platform. + */ -#define LWIP_STATS (0) -#define PBUF_POOL_SIZE (1001) +#pragma once -#endif /* USER_LWIPOPTS_H */ +void init_asrPlatform(void); diff --git a/examples/platform/asr/shell/launch_shell.cpp b/examples/platform/asr/shell/launch_shell.cpp new file mode 100644 index 00000000000000..a937d1ea48ddbe --- /dev/null +++ b/examples/platform/asr/shell/launch_shell.cpp @@ -0,0 +1,42 @@ +/* + * + * 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 "launch_shell.h" + +#include "lega_rtos_api.h" + +#include + +namespace { + +void MatterShellTask(void * args) +{ + chip::Shell::Engine::Root().RunMainLoop(); +} + +} // namespace + +namespace chip { + +void LaunchShell() +{ + chip::Shell::Engine::Root().Init(); + + lega_rtos_create_thread(NULL, 1, "matter_shell", (lega_thread_function_t) MatterShellTask, 2048, 0); +} + +} // namespace chip diff --git a/src/transport/SessionHandle.h b/examples/platform/asr/shell/launch_shell.h old mode 100644 new mode 100755 similarity index 87% rename from src/transport/SessionHandle.h rename to examples/platform/asr/shell/launch_shell.h index c1b0aeeee0cb40..604584b58982bd --- a/src/transport/SessionHandle.h +++ b/examples/platform/asr/shell/launch_shell.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * 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. @@ -17,4 +17,8 @@ #pragma once -#include +namespace chip { + +void LaunchShell(); + +} diff --git a/examples/platform/asr/shell/matter_shell.cpp b/examples/platform/asr/shell/matter_shell.cpp new file mode 100644 index 00000000000000..55a66b31cf0eaf --- /dev/null +++ b/examples/platform/asr/shell/matter_shell.cpp @@ -0,0 +1,142 @@ +/* + * + * 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. + */ + +/** + * @file + * This file provides the Shell implementation of Matter. + * It can be also used in ASR AT Command implementation. + */ + +#include "matter_shell.h" +#include "AppConfig.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; + +#if CONFIG_ENABLE_CHIP_SHELL +#include "lib/shell/Engine.h" + +using chip::Shell::Engine; +using chip::Shell::shell_command_t; +using chip::Shell::streamer_get; +using chip::Shell::streamer_printf; +#endif + +void asr_matter_reset(Reset_t type) +{ + if (type == WIFI_RESET) + { + ConnectivityMgr().ClearWiFiStationProvision(); + chip::Server::GetInstance().GetFabricTable().DeleteAllFabrics(); + chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow(); + } + else if (type == FACTORY_RESET) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + else if (type == COMMISSIONING_RESET) + { + chip::Server::GetInstance().GetFabricTable().DeleteAllFabrics(); + auto & commissionMgr = chip::Server::GetInstance().GetCommissioningWindowManager(); + commissionMgr.OpenBasicCommissioningWindow(commissionMgr.MaxCommissioningTimeout(), + CommissioningWindowAdvertisement::kDnssdOnly); + } +} + +void ShutdownChip() +{ + Server::GetInstance().Shutdown(); + PlatformMgr().StopEventLoopTask(); + PlatformMgr().Shutdown(); +} + +void asr_matter_onoff(int value) +{ + ChipLogProgress(Zcl, "updating on/off = %d", value); + + EmberAfStatus status = chip::app::Clusters::OnOff::Attributes::OnOff::Set( + /* endpoint ID */ 1, (uint8_t *) &value); + + if (status != EMBER_ZCL_STATUS_SUCCESS) + { + ChipLogProgress(Zcl, "ERR: updating on/off %x", status); + } +} + +void asr_matter_sensors(bool enable, int temp, int humi, int pressure) +{ +#if ASR_BOARD_ENABLE_SENSORS + if (enable) + { + chip::app::Clusters::TemperatureMeasurement::Attributes::MeasuredValue::Set( + /* endpoint ID */ 1, static_cast(temp)); + + chip::app::Clusters::RelativeHumidityMeasurement::Attributes::MeasuredValue::Set( + /* endpoint ID */ 1, static_cast(humi)); + + chip::app::Clusters::PressureMeasurement::Attributes::MeasuredValue::Set( + /* endpoint ID */ 1, static_cast(pressure)); + } +#else + ChipLogProgress(Zcl, "Sensor is not supported!"); +#endif +} + +void asr_matter_ota(uint32_t timeout) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + OTAInitializer::Instance().ReloadQueryTimeout(timeout); +#else + ChipLogProgress(Zcl, "OTA is not supported!"); +#endif +} + +#if CONFIG_ENABLE_CHIP_SHELL +static CHIP_ERROR sLightCommandHandler(int argc, char ** argv) +{ + if (argc == 1 && strcmp(argv[0], "on") == 0) + { + asr_matter_onoff(1); + return CHIP_NO_ERROR; + } + if (argc == 1 && strcmp(argv[0], "off") == 0) + { + asr_matter_onoff(0); + return CHIP_NO_ERROR; + } + streamer_printf(streamer_get(), "Usage: OnOff [on|off]"); + return CHIP_NO_ERROR; +} + +void RegisterLightCommands() +{ + static const shell_command_t sLightCommand = { sLightCommandHandler, "OnOff", "OnOff commands. Usage: OnOff [on|off]" }; + Engine::Root().RegisterCommands(&sLightCommand, 1); +} +#endif diff --git a/examples/platform/asr/shell/matter_shell.h b/examples/platform/asr/shell/matter_shell.h new file mode 100644 index 00000000000000..e0f2c86f2818aa --- /dev/null +++ b/examples/platform/asr/shell/matter_shell.h @@ -0,0 +1,52 @@ +/* + * + * 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. + */ + +/** + * @file + * This file provides the Shell implementation of Matter. + * It can be also used in ASR AT Command implementation. + */ + +#ifndef __MATTER_SHELL_H__ +#define __MATTER_SHELL_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum +{ + WIFI_RESET = 0, + FACTORY_RESET, + COMMISSIONING_RESET, +} Reset_t; + +void ShutdownChip(); +void asr_matter_reset(Reset_t type); +void asr_matter_onoff(int value); +void asr_matter_sensors(bool enable, int temp, int humi, int pressure); +void asr_matter_ota(uint32_t timeout); +#if CONFIG_ENABLE_CHIP_SHELL +void RegisterLightCommands(); +#endif +#ifdef __cplusplus +} +#endif +#endif // __MATTER_SHELL_H__ diff --git a/examples/platform/cc13x2_26x2/BUILD.gn b/examples/platform/cc13x2_26x2/BUILD.gn index 619ecdfa446dc5..06beceb9d75d01 100644 --- a/examples/platform/cc13x2_26x2/BUILD.gn +++ b/examples/platform/cc13x2_26x2/BUILD.gn @@ -14,6 +14,15 @@ import("//build_overrides/chip.gni") +config("chip_examples_project_config") { + include_dirs = [ "project_include" ] +} + +source_set("openthread_core_config_cc13x2_26x2_chip_examples") { + sources = [ "project_include/OpenThreadConfig.h" ] + public_configs = [ ":chip_examples_project_config" ] +} + config("attestation-credentials-config") { include_dirs = [ "${chip_root}" ] diff --git a/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp b/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp index 9e39a54c263668..ddde42c932d590 100644 --- a/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp +++ b/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp @@ -15,8 +15,6 @@ * limitations under the License. */ #include "CC13X2_26X2DeviceAttestationCreds.h" -#include -#include #include #include #include @@ -30,6 +28,10 @@ namespace CC13X2_26X2 { namespace { +extern "C" { + +extern void cc13x2_26x2Log(const char * aFormat, ...); + typedef struct { const uint32_t len; @@ -127,6 +129,8 @@ const factoryData gFactoryData = { }, }; +} // extern "C" + CHIP_ERROR LoadKeypairFromRaw(ByteSpan private_key, ByteSpan public_key, Crypto::P256Keypair & keypair) { Crypto::P256SerializedKeypair serialized_keypair; diff --git a/examples/platform/cc13x2_26x2/args.gni b/examples/platform/cc13x2_26x2/args.gni index 7d18cc869d4831..ff1f8159857fc6 100644 --- a/examples/platform/cc13x2_26x2/args.gni +++ b/examples/platform/cc13x2_26x2/args.gni @@ -14,10 +14,10 @@ import("//build_overrides/chip.gni") -import("${chip_root}/src/platform/cc13x2_26x2/args.gni") +import("${chip_root}/src/platform/cc13xx_26xx/cc13x2_26x2/args.gni") openthread_config_file = "" -openthread_core_config_deps = [] +openthread_core_config_deps = [ "${chip_root}/examples/platform/cc13x2_26x2:openthread_core_config_cc13x2_26x2_chip_examples" ] chip_ble_project_config_include = "" chip_device_project_config_include = "" diff --git a/examples/platform/cc13x2_26x2/project_include/OpenThreadConfig.h b/examples/platform/cc13x2_26x2/project_include/OpenThreadConfig.h new file mode 100644 index 00000000000000..7747508d80bfdb --- /dev/null +++ b/examples/platform/cc13x2_26x2/project_include/OpenThreadConfig.h @@ -0,0 +1,98 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Overrides to default OpenThread configuration. + * + */ + +#pragma once + +#ifdef DeviceFamily_CC13X2_CC26X2 + +/* Number of message buffers reduced to fit into CC26x2x3 RAM */ +#define OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS 22 + +#endif // DeviceFamily_CC13X2_CC26X2 + +#define OPENTHREAD_CONFIG_LOG_OUTPUT OPENTHREAD_CONFIG_LOG_OUTPUT_APP + +// When operating in a less than ideal RF environment, having a more forgiving configuration +// of OpenThread makes thread a great deal more reliable. +#define OPENTHREAD_CONFIG_TMF_ADDRESS_QUERY_MAX_RETRY_DELAY 120 // default is 28800 +#define OPENTHREAD_CONFIG_MAC_DEFAULT_MAX_FRAME_RETRIES_DIRECT 15 // default is 3 +#define OPENTHREAD_CONFIG_MAC_DEFAULT_MAX_FRAME_RETRIES_INDIRECT 1 // default is 0 +#define OPENTHREAD_CONFIG_MAC_MAX_TX_ATTEMPTS_INDIRECT_POLLS 16 // default is 4 + +// Enable periodic parent search to speed up finding a better parent. +#define OPENTHREAD_CONFIG_PARENT_SEARCH_ENABLE 1 // default is 0 +#define OPENTHREAD_CONFIG_PARENT_SEARCH_RSS_THRESHOLD -45 // default is -65 +#define OPENTHREAD_CONFIG_MLE_INFORM_PREVIOUS_PARENT_ON_REATTACH 1 // default is 0 + +// Use smaller maximum interval to speed up reattaching. +#define OPENTHREAD_CONFIG_MLE_ATTACH_BACKOFF_MAXIMUM_INTERVAL (60 * 10 * 1000) // default 1200000 ms + +#define OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE 1 +//#define OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE 0 +#define UART_AS_SERIAL_TRANSPORT 1 +#define OPENTHREAD_CONFIG_PLATFORM_USEC_TIMER_ENABLE 1 + +#define OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE 1 +#define OPENTHREAD_CONFIG_ECDSA_ENABLE 1 +#define OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_DNS_CLIENT_SERVICE_DISCOVERY_ENABLE 1 + +#define OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE 0 +#define OPENTHREAD_CONFIG_BORDER_AGENT_ENABLE 0 +#define OPENTHREAD_CONFIG_COMMISSIONER_ENABLE 0 +#define OPENTHREAD_CONFIG_JOINER_ENABLE 0 + +#define OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS 0 +// TCP disabled until OpenThread has a GN/Ninja build for the tcplp library +#define OPENTHREAD_CONFIG_TCP_ENABLE 0 + +#define OPENTHREAD_CONFIG_THREAD_VERSION OT_THREAD_VERSION_1_3 + +//#define OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE 1 +//#define OPENTHREAD_CONFIG_COAP_API_ENABLE 1 +#define OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE 0 +#define OPENTHREAD_CONFIG_COAP_API_ENABLE 0 +#define OPENTHREAD_CONFIG_DHCP6_CLIENT_ENABLE 0 +#define OPENTHREAD_CONFIG_DHCP6_SERVER_ENABLE 0 +#define OPENTHREAD_CONFIG_DIAG_ENABLE 0 +#define OPENTHREAD_CONFIG_DNSSD_SERVER_ENABLE 0 +#define OPENTHREAD_CONFIG_DUA_ENABLE 1 +#define OPENTHREAD_CONFIG_LINK_RAW_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_CSL_TRANSMITTER_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_FILTER_ENABLE 0 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_ACK_TIMEOUT_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_CSMA_BACKOFF_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_RETRANSMIT_ENABLE 1 +#define OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE 1 +#define OPENTHREAD_CONFIG_MLE_LINK_METRICS_SUBJECT_ENABLE 1 +#define OPENTHREAD_CONFIG_MLR_ENABLE 1 +#define OPENTHREAD_CONFIG_NETDATA_PUBLISHER_ENABLE 1 +#define OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_DEFAULT_MODE 1 +#define OPENTHREAD_CONFIG_SRP_SERVER_ENABLE 0 +#define OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE 1 + +// Use the TI-supplied default platform configuration for remainder +#include "openthread-core-cc13xx_cc26xx-config.h" diff --git a/examples/platform/linux/AppMain.cpp b/examples/platform/linux/AppMain.cpp index d9bdbd5f87bdb2..bdfa8eba2f428e 100644 --- a/examples/platform/linux/AppMain.cpp +++ b/examples/platform/linux/AppMain.cpp @@ -19,7 +19,6 @@ #include #include -#include #include #include #include @@ -53,12 +52,12 @@ #if defined(ENABLE_CHIP_SHELL) #include -#include +#include // nogncheck #include #endif #if defined(PW_RPC_ENABLED) -#include +#include #endif #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED diff --git a/examples/platform/linux/BUILD.gn b/examples/platform/linux/BUILD.gn index 08580aad33c1f5..284a6c6116c579 100644 --- a/examples/platform/linux/BUILD.gn +++ b/examples/platform/linux/BUILD.gn @@ -35,12 +35,8 @@ source_set("app-main") { "AppMain.h", "CommissionableInit.cpp", "CommissionableInit.h", - "CommissioneeShellCommands.cpp", - "CommissioneeShellCommands.h", "CommissionerMain.cpp", "CommissionerMain.h", - "ControllerShellCommands.cpp", - "ControllerShellCommands.h", "LinuxCommissionableDataProvider.cpp", "LinuxCommissionableDataProvider.h", "NamedPipeCommands.cpp", @@ -53,29 +49,32 @@ source_set("app-main") { "testing/CustomCSRResponseOperationalKeyStore.h", ] - defines = [] + public_deps = [ + "${chip_root}/src/lib", + "${chip_root}/src/platform/logging:force_stdio", + ] + deps = [ + ":ota-test-event-trigger", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/app/server", + ] if (chip_enable_pw_rpc) { defines += [ "PW_RPC_ENABLED" ] } + if (chip_build_libshell) { defines += [ "ENABLE_CHIP_SHELL" ] + sources += [ + "CommissioneeShellCommands.cpp", + "CommissioneeShellCommands.h", + "ControllerShellCommands.cpp", + "ControllerShellCommands.h", + ] } - public_deps = [ - ":ota-test-event-trigger", - "${chip_root}/examples/providers:device_info_provider", - "${chip_root}/src/app/server", - "${chip_root}/src/credentials:default_attestation_verifier", - "${chip_root}/src/lib", - "${chip_root}/src/lib/shell", - "${chip_root}/src/lib/shell:shell_core", - "${chip_root}/src/platform/logging:force_stdio", - ] - if (chip_enable_transport_trace) { - public_deps += - [ "${chip_root}/examples/common/tracing:trace_handlers_decoder" ] + deps += [ "${chip_root}/examples/common/tracing:trace_handlers_decoder" ] } public_configs = [ ":app-main-config" ] @@ -88,25 +87,15 @@ source_set("commissioner-main") { "CommissionerMain.h", ] - defines = [] - - if (chip_enable_pw_rpc) { - defines += [ "PW_RPC_ENABLED" ] - } if (chip_build_libshell) { defines += [ "ENABLE_CHIP_SHELL" ] } - public_deps = [ - "${chip_root}/src/app/server", - "${chip_root}/src/credentials:default_attestation_verifier", - "${chip_root}/src/lib", - "${chip_root}/src/lib/shell", - "${chip_root}/src/lib/shell:shell_core", - ] + public_deps = [ "${chip_root}/src/lib" ] + deps = [ "${chip_root}/src/app/server" ] if (chip_enable_transport_trace) { - public_deps += [ "${chip_root}/examples/common/tracing:trace_handlers" ] + deps += [ "${chip_root}/examples/common/tracing:trace_handlers" ] } public_configs = [ ":app-main-config" ] diff --git a/examples/platform/linux/CommissionerMain.cpp b/examples/platform/linux/CommissionerMain.cpp index c2a4e8292455a8..d9c1b5557ebd50 100644 --- a/examples/platform/linux/CommissionerMain.cpp +++ b/examples/platform/linux/CommissionerMain.cpp @@ -55,10 +55,6 @@ #include #include -#if defined(PW_RPC_ENABLED) -#include -#endif - #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED #include "TraceHandlers.h" #endif // CHIP_CONFIG_TRANSPORT_TRACE_ENABLED diff --git a/examples/platform/nxp/se05x/linux/AppMain.cpp b/examples/platform/nxp/se05x/linux/AppMain.cpp index 1ecf8052100a54..5ae726604a4c8a 100644 --- a/examples/platform/nxp/se05x/linux/AppMain.cpp +++ b/examples/platform/nxp/se05x/linux/AppMain.cpp @@ -60,7 +60,7 @@ #endif #if defined(PW_RPC_ENABLED) -#include +#include #endif #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED diff --git a/examples/platform/nxp/se05x/linux/BUILD.gn b/examples/platform/nxp/se05x/linux/BUILD.gn index 4956883bcec584..52ce3d417617e5 100644 --- a/examples/platform/nxp/se05x/linux/BUILD.gn +++ b/examples/platform/nxp/se05x/linux/BUILD.gn @@ -108,8 +108,6 @@ source_set("commissioner-main") { "${chip_root}/src/app/server", "${chip_root}/src/credentials:default_attestation_verifier", "${chip_root}/src/lib", - "${chip_root}/src/lib/shell", - "${chip_root}/src/lib/shell:shell_core", ] if (chip_enable_transport_trace) { diff --git a/examples/platform/openiotsdk/app/CMakeLists.txt b/examples/platform/openiotsdk/app/CMakeLists.txt index 4d566fa2e37cd6..c9939ea6a74fcd 100644 --- a/examples/platform/openiotsdk/app/CMakeLists.txt +++ b/examples/platform/openiotsdk/app/CMakeLists.txt @@ -16,6 +16,38 @@ cmake_minimum_required(VERSION 3.21) +# Declare Open IoT SDK startup target +add_library(openiotsdk-startup + OBJECT + openiotsdk_startup_gcc.cpp +) + +target_link_libraries(openiotsdk-startup + PUBLIC + # iotsdk-serial-retarget contains the UART but we don't need the retarget part + $,EXCLUDE,.*gcc_retarget.*> + cmsis-rtos-api + mcu-driver-hal +) + +target_link_options(openiotsdk-startup + PUBLIC + "-Wl,--wrap,__malloc_lock" + "-Wl,--wrap,__malloc_unlock" +) + +if(TFM_SUPPORT) + target_compile_definitions(openiotsdk-startup + PUBLIC + TFM_SUPPORT + ) + + target_link_libraries(openiotsdk-startup + PUBLIC + tfm-ns-interface + ) +endif() + # Declare Open IoT SDK app interface target add_library(openiotsdk-app openiotsdk_platform.cpp @@ -31,7 +63,6 @@ target_include_directories(openiotsdk-app target_link_libraries(openiotsdk-app PUBLIC chip - $ ) if(TFM_SUPPORT) diff --git a/examples/platform/openiotsdk/app/openiotsdk_platform.cpp b/examples/platform/openiotsdk/app/openiotsdk_platform.cpp index 829980d31f2392..28b6da91f5c176 100644 --- a/examples/platform/openiotsdk/app/openiotsdk_platform.cpp +++ b/examples/platform/openiotsdk/app/openiotsdk_platform.cpp @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2022 Project CHIP Authors * All rights reserved. * @@ -31,6 +30,7 @@ #include #include #include +#include #include #include @@ -53,6 +53,7 @@ using namespace ::chip; using namespace ::chip::Platform; using namespace ::chip::DeviceLayer; +using namespace ::chip::Logging::Platform; constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; @@ -168,7 +169,8 @@ static int get_psa_images_details() int openiotsdk_platform_init(void) { int ret; - osKernelState_t state; + + ois_logging_init(); ret = mbedtls_platform_setup(NULL); if (ret) @@ -178,13 +180,6 @@ int openiotsdk_platform_init(void) } #ifdef TFM_SUPPORT - ret = tfm_ns_interface_init(); - if (ret != 0) - { - ChipLogError(NotSpecified, "TF-M initialization failed: %d", ret); - return EXIT_FAILURE; - } - ret = get_psa_images_details(); if (ret != 0) { @@ -193,20 +188,6 @@ int openiotsdk_platform_init(void) } #endif // TFM_SUPPORT - ret = osKernelInitialize(); - if (ret != osOK) - { - ChipLogError(NotSpecified, "osKernelInitialize failed: %d", ret); - return EXIT_FAILURE; - } - - state = osKernelGetState(); - if (state != osKernelReady) - { - ChipLogError(NotSpecified, "Kernel not ready: %d", state); - return EXIT_FAILURE; - } - return EXIT_SUCCESS; } @@ -214,10 +195,6 @@ int openiotsdk_chip_init(void) { CHIP_ERROR err; -#if NDEBUG - chip::Logging::SetLogFilter(chip::Logging::LogCategory::kLogCategory_Progress); -#endif - err = MemoryInit(); if (err != CHIP_NO_ERROR) { @@ -244,18 +221,6 @@ int openiotsdk_chip_init(void) return EXIT_SUCCESS; } -int openiotsdk_platform_run(void) -{ - int ret = osKernelStart(); - if (ret != osOK) - { - ChipLogError(NotSpecified, "Failed to start kernel: %d", ret); - return EXIT_FAILURE; - } - - return EXIT_SUCCESS; -} - int openiotsdk_network_init(bool wait) { int ret; @@ -289,12 +254,10 @@ int openiotsdk_network_init(bool wait) int openiotsdk_chip_run(void) { - CHIP_ERROR err; - #ifdef USE_CHIP_DATA_MODEL // Init ZCL Data Model and start server static chip::CommonCaseDeviceServerInitParams initParams; - err = initParams.InitializeStaticResourcesBeforeServerInit(); + CHIP_ERROR err = initParams.InitializeStaticResourcesBeforeServerInit(); if (err != CHIP_NO_ERROR) { ChipLogError(NotSpecified, "Initialize static resources before server init failed: %s", err.AsString()); diff --git a/examples/platform/openiotsdk/app/openiotsdk_startup_gcc.cpp b/examples/platform/openiotsdk/app/openiotsdk_startup_gcc.cpp new file mode 100644 index 00000000000000..bf143db5d32877 --- /dev/null +++ b/examples/platform/openiotsdk/app/openiotsdk_startup_gcc.cpp @@ -0,0 +1,573 @@ +/* + * Copyright (c) 2006-2022 ARM Limited + * Copyright (c) 2023 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bootstrap/mbed_critical.h" +#include "cmsis_os2.h" +extern "C" { +#include "hal/serial_api.h" +} + +#ifdef TFM_SUPPORT +extern "C" uint32_t tfm_ns_interface_init(void); +#endif // TFM_SUPPORT + +#define CALLER_ADDR() __builtin_extract_return_addr(__builtin_return_address(0)) + +// Consider reducing the baudrate if the serial is used as input and characters are lost +extern "C" mdh_serial_t * get_example_serial(); +#ifndef IOT_SDK_APP_SERIAL_BAUDRATE +#define IOT_SDK_APP_SERIAL_BAUDRATE 921600 +#endif + +// main thread declaration +// The thread object and associated stack are statically allocated +#ifndef IOT_SDK_APP_MAIN_STACK_SIZE +#define IOT_SDK_APP_MAIN_STACK_SIZE 16 * 1024 +#endif +static void main_thread(void * argument); +alignas(8) static char main_thread_stack[IOT_SDK_APP_MAIN_STACK_SIZE]; +alignas(8) static uint8_t main_thread_storage[100] __attribute__((section(".bss.os.thread.cb"))); + +// malloc mutex declaration +static osMutexId_t malloc_mutex; +alignas(8) static uint8_t malloc_mutex_obj[80]; + +// C runtime import: constructor initialization and main +extern "C" void __libc_init_array(void); +extern "C" int main(void); + +// IOT SDK serial declarations +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +static mdh_serial_t * serial; + +// stdout tx mutex declaration +static osMutexId_t tx_mutex; +alignas(8) static uint8_t tx_mutex_obj[80]; + +static int serial_out(const char * str, size_t len) +{ + if (str == NULL) + { + return -1; + } + + if (len == 0) + { + return 0; + } + + size_t written = 0; + while (written++ < len) + { + mdh_serial_put_data(serial, *str++); + } + + return len; +} + +// prints while printf is not usable yet +static void bare_metal_print(const char * str) +{ + serial_out(str, strlen(str)); +} + +static void serial_irq_cb(void * p_instance, mdh_serial_irq_type_t event); + +struct CriticalSection +{ + CriticalSection() { core_util_critical_section_enter(); } + CriticalSection(const CriticalSection &) = delete; + CriticalSection & operator=(const CriticalSection &) = delete; + ~CriticalSection() { core_util_critical_section_exit(); } +}; + +// RX buffer +template +struct RingBuffer +{ + static_assert(Size > 0); + RingBuffer() : head_(0), tail_(0), full_(false) {} + void put(uint8_t data); + bool get(uint8_t * data); + size_t get(uint8_t * data, size_t size); + bool empty() const; + bool full() const; + size_t size() const; + +private: + uint8_t buffer_[Size]; + size_t head_ = 0; + size_t tail_ = 0; + bool full_ = false; + + void increment(size_t & val); + void increment(size_t & val, size_t incr); + bool empty_() const; + size_t size_() const; +}; + +// Buffer that receive data from serial +static RingBuffer<128> rx_buffer; + +/* + * This function override startup sequence. Instead of releasing control to the C runtime + * the following operations are performed: + * + * - initialize the serial (low level) + * - initialize RTOS + * - Start the RTOS with the main thread + */ +extern "C" void mbed_sdk_init(void) +{ + serial = get_example_serial(); + mdh_serial_set_baud(serial, IOT_SDK_APP_SERIAL_BAUDRATE); + + int ret = osKernelInitialize(); + if (ret != osOK) + { + bare_metal_print("osKernelInitialize failed\r\n"); + abort(); + } + + // Create main thread used to run the application + { + osThreadAttr_t main_thread_attr = { + .name = "main", + .cb_mem = &main_thread_storage, + .cb_size = sizeof(main_thread_storage), + .stack_mem = main_thread_stack, + .stack_size = sizeof(main_thread_stack), + .priority = osPriorityNormal, + }; + + osThreadId_t main_thread_id = osThreadNew(main_thread, NULL, &main_thread_attr); + if (main_thread_id == NULL) + { + bare_metal_print("Main thread creation failed\r\n"); + abort(); + } + } + + ret = osKernelStart(); + // Note osKernelStart should never return + bare_metal_print("Kernel failed to start\r\n"); + abort(); +} + +/** + * Main thread + * - Initialize TF-M + * - Initialize the toolchain: + * - Setup mutexes for malloc and environment + * - Construct global objects + * - Run the main + */ +static void main_thread(void * argument) +{ + // Create Malloc mutex + { + osMutexAttr_t malloc_mutex_attr = { .name = "malloc_mutex", + .attr_bits = osMutexRecursive | osMutexPrioInherit, + .cb_mem = &malloc_mutex_obj, + .cb_size = sizeof(malloc_mutex_obj) }; + + malloc_mutex = osMutexNew(&malloc_mutex_attr); + if (malloc_mutex == NULL) + { + bare_metal_print("Failed to initialize malloc mutex\r\n"); + abort(); + } + } + + // Create stdout TX mutex + { + osMutexAttr_t tx_mutex_attr = { + .name = "tx_mutex", .attr_bits = osMutexPrioInherit, .cb_mem = &tx_mutex_obj, .cb_size = sizeof(tx_mutex_obj) + }; + + tx_mutex = osMutexNew(&tx_mutex_attr); + if (tx_mutex == NULL) + { + bare_metal_print("Failed to initialize tx mutex\r\n"); + abort(); + } + } + + // Disable buffering to let write and fwrite call straight into _write + setvbuf(stdout, /* buffer */ NULL, _IONBF, /* size */ 0); + setvbuf(stderr, /* buffer */ NULL, _IONBF, /* size */ 0); + setvbuf(stdin, /* buffer */ NULL, _IONBF, /* size */ 0); + + // It is safe to use printf from this point + +#ifdef TFM_SUPPORT + { + int ret = tfm_ns_interface_init(); + if (ret != 0) + { + bare_metal_print("TF-M initialization failed\r\n"); + abort(); + } + } +#endif + + /* Run the C++ global object constructors */ + __libc_init_array(); + + // Note: Reception on the serial port is buffered to mitigate bytes lost + mdh_serial_set_irq_callback(serial, serial_irq_cb, serial); + mdh_serial_set_irq_availability(serial, MDH_SERIAL_IRQ_TYPE_RX, true); + + // It is safe to receive data on serial from this point + + int return_code = main(); + + exit(return_code); +} + +/* + * Override of lock/unlock functions for malloc. + */ +extern "C" void __wrap___malloc_lock(struct _reent * reent) +{ + osMutexAcquire(malloc_mutex, osWaitForever); +} + +extern "C" void __wrap___malloc_unlock(struct _reent * reent) +{ + osMutexRelease(malloc_mutex); +} + +/* + * Override of new/delete operators. + * The override add a trace when a non-throwing new fails. + */ + +void * operator new(std::size_t count) +{ + void * buffer = malloc(count); + if (!buffer) + { + printf("operator new failure from %p\r\n", CALLER_ADDR()); + abort(); + } + return buffer; +} + +void * operator new[](std::size_t count) +{ + void * buffer = malloc(count); + if (!buffer) + { + printf("operator new[] failure from %p\r\n", CALLER_ADDR()); + abort(); + } + return buffer; +} + +void * operator new(std::size_t count, const std::nothrow_t & tag) +{ + return malloc(count); +} + +void * operator new[](std::size_t count, const std::nothrow_t & tag) +{ + return malloc(count); +} + +void operator delete(void * ptr) +{ + free(ptr); +} + +void operator delete(void * ptr, std::size_t) +{ + free(ptr); +} + +void operator delete[](void * ptr) +{ + free(ptr); +} + +void operator delete[](void * ptr, std::size_t) +{ + free(ptr); +} + +/* + * Override of _sbrk + * It prints an error when the system runs out of memory in the heap segment. + */ + +#undef errno +extern "C" int errno; + +extern "C" char __end__; +extern "C" char __HeapLimit; + +extern "C" void * _sbrk(int incr) +{ + static uint32_t heap = (uint32_t) &__end__; + uint32_t prev_heap = heap; + uint32_t new_heap = heap + incr; + + /* __HeapLimit is end of heap section */ + if (new_heap > (uint32_t) &__HeapLimit) + { + printf("_sbrk failure, incr = %d, new_heap = 0x%08lX\r\n", incr, new_heap); + errno = ENOMEM; + return (void *) -1; + } + + heap = new_heap; + return (void *) prev_heap; +} + +// Override exit +extern "C" void _exit(int return_code) +{ + // display exit reason + if (return_code) + { + printf("Application exited with %d\r\n", return_code); + } + + // flush stdio + fflush(stdout); + fflush(stderr); + + // lock the kernel and go to sleep forever + osKernelLock(); + while (1) + { + __WFE(); + } +} + +// Calling a FreeRTOS API is illegal while scheduler is suspended. +// Therefore we provide this custom implementation which relies on underlying +// safety of malloc. +extern "C" void * pvPortMalloc(size_t size) +{ + return malloc(size); +} + +extern "C" void vPortFree(void * ptr) +{ + free(ptr); +} + +// Retarget of low level read and write + +extern "C" int _write(int fd, const char * str, size_t len) +{ + if (fd != STDOUT_FILENO && fd != STDERR_FILENO) + { + return -1; + } + + osMutexAcquire(tx_mutex, osWaitForever); + int len_written = serial_out(str, len); + osMutexRelease(tx_mutex); + + return len_written; +} + +extern "C" int _read(int fd, char * str, size_t len) +{ + if (fd != STDIN_FILENO) + { + return -1; + } + + return rx_buffer.get((uint8_t *) str, len); +} + +static void serial_irq_cb(void * p_instance, mdh_serial_irq_type_t event) +{ + if ((event != MDH_SERIAL_IRQ_TYPE_RX) || !p_instance) + { + return; + } + + mdh_serial_t * serial = reinterpret_cast(p_instance); + + if (event == MDH_SERIAL_IRQ_TYPE_RX) + { + while (mdh_serial_is_readable(serial)) + { + // Gather as much as possible data bytes + rx_buffer.put(mdh_serial_get_data(serial)); + } + } +} + +// Ring buffer implementation +template +void RingBuffer::put(uint8_t data) +{ + CriticalSection _; + buffer_[head_] = data; + increment(head_); + + if (full_) + { + tail_ = head_; + } + else if (head_ == tail_) + { + full_ = true; + } +} + +template +bool RingBuffer::get(uint8_t * data) +{ + CriticalSection _; + if (empty_()) + { + return false; + } + + *data = buffer_[tail_]; + increment(tail_); + full_ = false; + + return true; +} + +template +size_t RingBuffer::get(uint8_t * data, size_t size) +{ + if (size == 0) + { + return 0; + } + + if (size == 1) + { + return get(data) ? 1 : 0; + } + + CriticalSection _; + if (empty_()) + { + return 0; + } + + // resize dest to fit with available data + size = std::min(size_(), size); + + if (tail_ + size > Size) + { + auto it = std::copy(buffer_ + tail_, buffer_ + Size, data); + // set to the future tail + tail_ = size - (Size - tail_); + std::copy(buffer_, buffer_ + tail_, it); + } + else + { + std::copy(buffer_ + tail_, buffer_ + size, data); + increment(tail_, size); + } + + full_ = false; + + return size; +} + +template +bool RingBuffer::empty() const +{ + CriticalSection _; + return empty_(); +} + +template +bool RingBuffer::full() const +{ + CriticalSection _; + return bool(full_); +} + +template +size_t RingBuffer::size() const +{ + CriticalSection _; + return size_(); +} + +template +void RingBuffer::increment(size_t & val) +{ + ++val; + assert(val <= Size); + + if (val == Size) + { + val = 0; + } +} + +template +void RingBuffer::increment(size_t & val, size_t incr) +{ + val += incr; + + if (val >= Size) + { + val = val - Size; + } +} + +template +bool RingBuffer::empty_() const +{ + return head_ == tail_ && !bool(full_); +} + +template +size_t RingBuffer::size_() const +{ + if (full_) + { + return Size; + } + else if (head_ < tail_) + { + return Size - (tail_ - head_); + } + else + { + return head_ - tail_; + }; +} diff --git a/examples/platform/openiotsdk/tf-m/targets/an552/partition/region_defs.h b/examples/platform/openiotsdk/tf-m/targets/an552/partition/region_defs.h index d124a00450785e..682f0f50747373 100755 --- a/examples/platform/openiotsdk/tf-m/targets/an552/partition/region_defs.h +++ b/examples/platform/openiotsdk/tf-m/targets/an552/partition/region_defs.h @@ -101,9 +101,9 @@ #define NS_CODE_SIZE (IMAGE_NS_CODE_SIZE) #define NS_CODE_LIMIT (NS_CODE_START + NS_CODE_SIZE - 1) -/* Non-Secure Data stored in ISRAM0 */ +/* Non-Secure Data stored in ISRAM0 + ISRAM1 */ #define NS_DATA_START (ISRAM0_BASE_NS) -#define NS_DATA_SIZE (ISRAM0_SIZE) +#define NS_DATA_SIZE (ISRAM0_SIZE + ISRAM1_SIZE) #define NS_DATA_LIMIT (NS_DATA_START + NS_DATA_SIZE - 1) /* NS partition information is used for MPC and SAU configuration */ diff --git a/examples/platform/openiotsdk/tf-m/targets/an552/target_cfg.c b/examples/platform/openiotsdk/tf-m/targets/an552/target_cfg.c index 9b0338b38c8532..0358426779cafc 100755 --- a/examples/platform/openiotsdk/tf-m/targets/an552/target_cfg.c +++ b/examples/platform/openiotsdk/tf-m/targets/an552/target_cfg.c @@ -171,6 +171,13 @@ enum tfm_plat_err_t nvic_interrupt_enable(void) return TFM_PLAT_ERR_SYSTEM_ERR; } + ret = Driver_ISRAM1_MPC.EnableInterrupt(); + if (ret != ARM_DRIVER_OK) + { + ERROR_MSG("Failed to Enable MPC interrupt for ISRAM1!"); + return TFM_PLAT_ERR_SYSTEM_ERR; + } + ret = Driver_SRAM_MPC.EnableInterrupt(); if (ret != ARM_DRIVER_OK) { @@ -302,6 +309,21 @@ enum tfm_plat_err_t mpc_init_cfg(void) return TFM_PLAT_ERR_SYSTEM_ERR; } + /* ISRAM1 is allocated for NS data, so whole range is set to non-secure + * accesible. */ + ret = Driver_ISRAM1_MPC.Initialize(); + if (ret != ARM_DRIVER_OK) + { + ERROR_MSG("Failed to Initialize MPC for ISRAM1!"); + return TFM_PLAT_ERR_SYSTEM_ERR; + } + ret = Driver_ISRAM1_MPC.ConfigRegion(MPC_ISRAM1_RANGE_BASE_NS, MPC_ISRAM1_RANGE_LIMIT_NS, ARM_MPC_ATTR_NONSECURE); + if (ret != ARM_DRIVER_OK) + { + ERROR_MSG("Failed to Configure MPC for ISRAM1!"); + return TFM_PLAT_ERR_SYSTEM_ERR; + } + /* Configuring additional flash partition. */ ret = Driver_SRAM_MPC.Initialize(); if (ret != ARM_DRIVER_OK) @@ -331,10 +353,7 @@ enum tfm_plat_err_t mpc_init_cfg(void) return TFM_PLAT_ERR_SYSTEM_ERR; } - /* Lock down not used MPC's */ - Driver_ISRAM1_MPC.LockDown(); - - /* SRAM and ISRAM0 MPCs left unlocked as they are not reset if NVIC system + /* SRAM, ISRAM0 and ISRAM1 MPCs left unlocked as they are not reset if NVIC system * reset asserted. */ @@ -351,6 +370,8 @@ void mpc_revert_non_secure_to_secure_cfg(void) { Driver_ISRAM0_MPC.ConfigRegion(MPC_ISRAM0_RANGE_BASE_S, MPC_ISRAM0_RANGE_LIMIT_S, ARM_MPC_ATTR_SECURE); + Driver_ISRAM1_MPC.ConfigRegion(MPC_ISRAM1_RANGE_BASE_S, MPC_ISRAM1_RANGE_LIMIT_S, ARM_MPC_ATTR_SECURE); + Driver_SRAM_MPC.ConfigRegion(MPC_SRAM_RANGE_BASE_S, MPC_SRAM_RANGE_LIMIT_S, ARM_MPC_ATTR_SECURE); Driver_QSPI_MPC.ConfigRegion(MPC_QSPI_RANGE_BASE_S, MPC_QSPI_RANGE_LIMIT_S, ARM_MPC_ATTR_SECURE); @@ -365,6 +386,7 @@ void mpc_revert_non_secure_to_secure_cfg(void) void mpc_clear_irq(void) { Driver_ISRAM0_MPC.ClearInterrupt(); + Driver_ISRAM1_MPC.ClearInterrupt(); Driver_SRAM_MPC.ClearInterrupt(); Driver_QSPI_MPC.ClearInterrupt(); } diff --git a/examples/platform/silabs/SiWx917/BUILD.gn b/examples/platform/silabs/SiWx917/BUILD.gn index ad3775845f3efa..3233ea7e88dd98 100644 --- a/examples/platform/silabs/SiWx917/BUILD.gn +++ b/examples/platform/silabs/SiWx917/BUILD.gn @@ -240,6 +240,7 @@ source_set("siwx917-common") { sources = [ "${silabs_common_plat_dir}/LEDWidget.cpp", "${silabs_common_plat_dir}/heap_4_silabs.c", + "${silabs_common_plat_dir}/silabs_utils.cpp", "${silabs_common_plat_dir}/syscalls_stubs.cpp", "${wifi_sdk_dir}/dhcp_client.cpp", "${wifi_sdk_dir}/ethernetif.cpp", @@ -249,7 +250,6 @@ source_set("siwx917-common") { "SiWx917/wfx_rsi_host.c", "init_ccpPlatform.cpp", "matter_config.cpp", - "siwx917_utils.cpp", ] if (use_base_app) { diff --git a/examples/platform/silabs/SiWx917/BaseApplication.cpp b/examples/platform/silabs/SiWx917/BaseApplication.cpp index 62b5f4cc1bc361..7b0bae137b2ecd 100644 --- a/examples/platform/silabs/SiWx917/BaseApplication.cpp +++ b/examples/platform/silabs/SiWx917/BaseApplication.cpp @@ -37,7 +37,7 @@ #include "SilabsDeviceDataProvider.h" #include "rsi_board.h" #include "rsi_chip.h" -#include "siwx917_utils.h" +#include "silabs_utils.h" #include #include #include @@ -47,6 +47,8 @@ #include #include +#include + #ifdef SL_WIFI #include "wfx_host_events.h" #include @@ -70,6 +72,7 @@ using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -355,7 +358,7 @@ void BaseApplication::ButtonHandler(AppEvent * aEvent) // FACTORY_RESET_TRIGGER_TIMEOUT to signal factory reset has been initiated. // To cancel factory reset: release the APP_FUNCTION_BUTTON once all LEDs // start blinking within the FACTORY_RESET_CANCEL_WINDOW_TIMEOUT - if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_PRESSED) + if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { if ((!mFunctionTimerActive) && (mFunction == kFunction_NoneSelected)) { diff --git a/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_platform_init.c b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_platform_init.c index 453954795f6556..3801ebd30a4603 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_platform_init.c +++ b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_platform_init.c @@ -21,7 +21,7 @@ #include "rsi_board.h" #include "rsi_pll.h" #include "rsi_rom_clks.h" -#include "siwx917_utils.h" +#include "silabs_utils.h" #include "system_RS1xxxx.h" #define SOC_PLL_REF_FREQUENCY 32000000 /* PLL input REFERENCE clock 32MHZ */ diff --git a/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h index cb1279590926c7..51555534613d78 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h +++ b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h @@ -81,7 +81,6 @@ extern "C" { #endif void wfx_rsidev_init(void); void wfx_rsi_task(void * arg); -void efr32Log(const char * aFormat, ...); #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 void wfx_ip_changed_notify(int got_ip); #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ @@ -90,7 +89,6 @@ int32_t wfx_rsi_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); int32_t wfx_rsi_reset_count(); int32_t wfx_rsi_disconnect(); int32_t wfx_rsi_init_platform(); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); #ifdef __cplusplus } diff --git a/examples/platform/silabs/SiWx917/uart.cpp b/examples/platform/silabs/SiWx917/uart.cpp index 74e77f43f11ad4..966fe44d7efd25 100644 --- a/examples/platform/silabs/SiWx917/uart.cpp +++ b/examples/platform/silabs/SiWx917/uart.cpp @@ -19,7 +19,7 @@ #include "USART.h" #include "matter_shell.h" #include "rsi_rom_egpio.h" -#include "siwx917_utils.h" +#include "silabs_utils.h" #ifdef __cplusplus extern "C" { #endif diff --git a/examples/platform/silabs/SilabsDeviceDataProvider.cpp b/examples/platform/silabs/SilabsDeviceDataProvider.cpp index 585699785937bd..53e3e5fa3da259 100644 --- a/examples/platform/silabs/SilabsDeviceDataProvider.cpp +++ b/examples/platform/silabs/SilabsDeviceDataProvider.cpp @@ -24,7 +24,7 @@ #ifdef SIWX917_USE_COMISSIONABLE_DATA #include "DeviceConfig.h" -#include "siwx917_utils.h" +#include "silabs_utils.h" #include #include #endif // SIWX917_USE_COMISSIONABLE_DATA diff --git a/examples/platform/silabs/efr32/BUILD.gn b/examples/platform/silabs/efr32/BUILD.gn index d74792a1cba233..549b2aeec9da5a 100644 --- a/examples/platform/silabs/efr32/BUILD.gn +++ b/examples/platform/silabs/efr32/BUILD.gn @@ -282,8 +282,8 @@ source_set("efr32-common") { sources = [ "${silabs_common_plat_dir}/LEDWidget.cpp", "${silabs_common_plat_dir}/heap_4_silabs.c", + "${silabs_common_plat_dir}/silabs_utils.cpp", "${silabs_common_plat_dir}/syscalls_stubs.cpp", - "efr32_utils.cpp", "init_efrPlatform.cpp", "matter_config.cpp", ] diff --git a/examples/platform/silabs/efr32/BaseApplication.cpp b/examples/platform/silabs/efr32/BaseApplication.cpp index 9d096f23353cab..baf16e78cc2510 100644 --- a/examples/platform/silabs/efr32/BaseApplication.cpp +++ b/examples/platform/silabs/efr32/BaseApplication.cpp @@ -53,6 +53,8 @@ #include #endif // CHIP_ENABLE_OPENTHREAD +#include + #ifdef SL_WIFI #include "wfx_host_events.h" #include @@ -75,12 +77,11 @@ #if defined(ENABLE_WSTK_LEDS) && defined(SL_CATALOG_SIMPLE_LED_LED1_PRESENT) #define SYSTEM_STATE_LED 0 #endif // ENABLE_WSTK_LEDS -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT #define APP_FUNCTION_BUTTON 0 -#endif using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; namespace { @@ -397,7 +398,7 @@ void BaseApplication::LightEventHandler() sStatusLED.Animate(); #endif // ENABLE_WSTK_LEDS } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + void BaseApplication::ButtonHandler(AppEvent * aEvent) { // To trigger software update: press the APP_FUNCTION_BUTTON button briefly (< @@ -407,7 +408,7 @@ void BaseApplication::ButtonHandler(AppEvent * aEvent) // FACTORY_RESET_TRIGGER_TIMEOUT to signal factory reset has been initiated. // To cancel factory reset: release the APP_FUNCTION_BUTTON once all LEDs // start blinking within the FACTORY_RESET_CANCEL_WINDOW_TIMEOUT - if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_PRESSED) + if (aEvent->ButtonEvent.Action == static_cast(SilabsPlatform::ButtonAction::ButtonPressed)) { if (!mFunctionTimerActive && mFunction == kFunction_NoneSelected) { @@ -444,10 +445,7 @@ void BaseApplication::ButtonHandler(AppEvent * aEvent) SILABS_LOG("Failed to open the Basic Commissioning Window"); } } - else - { - SILABS_LOG("Network is already provisioned, Ble advertissement not enabled"); - } + else { SILABS_LOG("Network is already provisioned, Ble advertissement not enabled"); } } else if (mFunctionTimerActive && mFunction == kFunction_FactoryReset) { @@ -464,7 +462,7 @@ void BaseApplication::ButtonHandler(AppEvent * aEvent) } } } -#endif + void BaseApplication::CancelFunctionTimer() { if (xTimerStop(sFunctionTimer, pdMS_TO_TICKS(0)) == pdFAIL) diff --git a/examples/platform/silabs/efr32/BaseApplication.h b/examples/platform/silabs/efr32/BaseApplication.h index 191fcba4aaf3f3..d8bd8e9a6a7502 100644 --- a/examples/platform/silabs/efr32/BaseApplication.h +++ b/examples/platform/silabs/efr32/BaseApplication.h @@ -28,9 +28,6 @@ #include "AppEvent.h" #include "FreeRTOS.h" -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT -#include "sl_simple_button_instances.h" -#endif #include "timers.h" // provides FreeRTOS timer support #include #include @@ -153,7 +150,7 @@ class BaseApplication * @param aEvent post event being processed */ static void FunctionEventHandler(AppEvent * aEvent); -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + /** * @brief PB0 Button event processing function * Press and hold will trigger a factory reset timer start @@ -162,7 +159,7 @@ class BaseApplication * @param aEvent button event being processed */ static void ButtonHandler(AppEvent * aEvent); -#endif + /** * @brief Light Timer finished callback function * Calls LED processing function diff --git a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c index 02ae9b2cba9b17..507523a2f6e03e 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c +++ b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c @@ -36,6 +36,8 @@ #endif #include "spidrv.h" +#include "silabs_utils.h" + #include "gpiointerrupt.h" #include "sl_device_init_clocks.h" #include "sl_status.h" @@ -140,13 +142,10 @@ void rsi_hal_board_init(void) xSemaphoreGive(spiTransferLock); /* GPIO INIT of MG12 & MG24 : Reset, Wakeup, Interrupt */ - SILABS_LOG("RSI_HAL: init GPIO"); sl_wfx_host_gpio_init(); /* Reset of Wifi chip */ - SILABS_LOG("RSI_HAL: Reset Wifi"); sl_wfx_host_reset_chip(); - SILABS_LOG("RSI_HAL: Init done"); } /***************************************************************************** diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c index cb802e32948839..b8edbd71cace76 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c @@ -70,7 +70,6 @@ void rsi_gpio_irq_cb(uint8_t irqnum) void rsi_hal_intr_config(void (*rsi_interrupt_handler)(void)) { call_back = rsi_interrupt_handler; - SILABS_LOG("RSI:Set SPI intr CB to=%x", (uint32_t) call_back); } /*===================================================*/ diff --git a/examples/platform/silabs/efr32/rs911x/rsi_if.c b/examples/platform/silabs/efr32/rs911x/rsi_if.c index dae7b0cd4f762e..86238374ef175f 100644 --- a/examples/platform/silabs/efr32/rs911x/rsi_if.c +++ b/examples/platform/silabs/efr32/rs911x/rsi_if.c @@ -31,6 +31,8 @@ #include "event_groups.h" #include "task.h" +#include "silabs_utils.h" + #include "wfx_host_events.h" #include "rsi_driver.h" diff --git a/examples/platform/silabs/efr32/rs911x/wfx_rsi.h b/examples/platform/silabs/efr32/rs911x/wfx_rsi.h index 7292970a11c011..cd18672faf42ba 100644 --- a/examples/platform/silabs/efr32/rs911x/wfx_rsi.h +++ b/examples/platform/silabs/efr32/rs911x/wfx_rsi.h @@ -83,7 +83,6 @@ extern "C" { #endif void wfx_rsidev_init(void); void wfx_rsi_task(void * arg); -void efr32Log(const char * aFormat, ...); #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 void wfx_ip_changed_notify(int got_ip); #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ @@ -94,7 +93,6 @@ int32_t wfx_rsi_disconnect(); #if CHIP_DEVICE_CONFIG_ENABLE_SED int32_t wfx_rsi_power_save(); #endif /* CHIP_DEVICE_CONFIG_ENABLE_SED */ -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); #ifdef __cplusplus } diff --git a/examples/platform/silabs/efr32/rs911x/wfx_rsi_host.c b/examples/platform/silabs/efr32/rs911x/wfx_rsi_host.c index 0691c21670518a..80368c1b66734b 100644 --- a/examples/platform/silabs/efr32/rs911x/wfx_rsi_host.c +++ b/examples/platform/silabs/efr32/rs911x/wfx_rsi_host.c @@ -26,6 +26,8 @@ #include "em_usart.h" #include "sl_status.h" +#include "silabs_utils.h" + #include "FreeRTOS.h" #include "event_groups.h" #include "task.h" @@ -53,11 +55,9 @@ sl_status_t wfx_wifi_start(void) { if (wfx_rsi.dev_state & WFX_RSI_ST_STARTED) { - SILABS_LOG("%s: already started.", __func__); return SL_STATUS_OK; } wfx_rsi.dev_state |= WFX_RSI_ST_STARTED; - SILABS_LOG("%s: starting..", __func__); /* * Create the Wifi driver task */ @@ -66,7 +66,6 @@ sl_status_t wfx_wifi_start(void) if (NULL == wfx_rsi.wlan_task) { - SILABS_LOG("%s: error: failed to create task.", __func__); return SL_STATUS_FAIL; } return SL_STATUS_OK; @@ -95,7 +94,6 @@ bool wfx_is_sta_mode_enabled(void) { bool mode; mode = !!(wfx_rsi.dev_state & WFX_RSI_ST_STA_MODE); - // SILABS_LOG("%s: %d", __func__, (mode ? "yes" : "no")); return mode; } @@ -170,7 +168,6 @@ void wfx_clear_wifi_provision(void) { memset(&wfx_rsi.sec, 0, sizeof(wfx_rsi.sec)); wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_PROVISIONED; - SILABS_LOG("%s: completed.", __func__); } /************************************************************************* @@ -228,7 +225,6 @@ void wfx_setup_ip6_link_local(sl_wfx_interface_t whichif) * TODO: Implement IPV6 setup, currently in wfx_rsi_task() * This is hooked with MATTER code. */ - SILABS_LOG("%s: warning: not implemented.", __func__); } /********************************************************************* @@ -243,7 +239,6 @@ bool wfx_is_sta_connected(void) { bool status; status = (wfx_rsi.dev_state & WFX_RSI_ST_STA_CONNECTED) ? true : false; - SILABS_LOG("%s: status: %s", __func__, (status ? "connected" : "not connected")); return status; } @@ -272,11 +267,9 @@ wifi_mode_t wfx_get_wifi_mode() ***********************************************************************/ sl_status_t wfx_sta_discon(void) { - SILABS_LOG("%s: started.", __func__); int32_t status; status = wfx_rsi_disconnect(); wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTED; - SILABS_LOG("%s: completed.", __func__); return status; } #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 @@ -299,7 +292,6 @@ bool wfx_have_ipv4_addr(sl_wfx_interface_t which_if) { status = false; /* TODO */ } - SILABS_LOG("%s: status: %d", __func__, status); return status; } #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ @@ -323,7 +315,6 @@ bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) { status = false; /* TODO */ } - SILABS_LOG("%s: status: %d", __func__, status); return status; } @@ -420,6 +411,5 @@ bool wfx_start_scan(char * ssid, void (*callback)(wfx_wifi_scan_result_t *)) void wfx_cancel_scan(void) { /* Not possible */ - SILABS_LOG("%s: cannot cancel scan", __func__); } #endif /* SL_WFX_CONFIG_SCAN */ diff --git a/examples/platform/silabs/efr32/wf200/efr_spi.c b/examples/platform/silabs/efr32/wf200/efr_spi.c index 927b9a5fb892fa..5c97a294321648 100644 --- a/examples/platform/silabs/efr32/wf200/efr_spi.c +++ b/examples/platform/silabs/efr32/wf200/efr_spi.c @@ -417,7 +417,6 @@ static void sl_wfx_spi_wakeup_irq_callback(uint8_t irqNumber) *****************************************************************************/ void sl_wfx_host_gpio_init(void) { - SILABS_LOG("WIFI: GPIO Init:IRQ=%d", wirq_irq_nb); // Enable GPIO clock. CMU_ClockEnable(cmuClock_GPIO, true); diff --git a/examples/platform/silabs/efr32/efr32_utils.cpp b/examples/platform/silabs/silabs_utils.cpp similarity index 97% rename from examples/platform/silabs/efr32/efr32_utils.cpp rename to examples/platform/silabs/silabs_utils.cpp index bd2bf771c60152..2e8a83bdf5be2b 100644 --- a/examples/platform/silabs/efr32/efr32_utils.cpp +++ b/examples/platform/silabs/silabs_utils.cpp @@ -17,7 +17,7 @@ * limitations under the License. */ -#include "efr32_utils.h" +#include "silabs_utils.h" #include "init_efrPlatform.h" #include "sl_system_kernel.h" diff --git a/examples/platform/silabs/efr32/efr32_utils.h b/examples/platform/silabs/silabs_utils.h similarity index 91% rename from examples/platform/silabs/efr32/efr32_utils.h rename to examples/platform/silabs/silabs_utils.h index 04cf773fc49eff..93941fbf9c668e 100644 --- a/examples/platform/silabs/efr32/efr32_utils.h +++ b/examples/platform/silabs/silabs_utils.h @@ -26,8 +26,8 @@ extern "C" { void silabsInitLog(void); -void efr32Log(const char * aFormat, ...); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); +void silabsLog(const char * aFormat, ...); +#define SILABS_LOG(...) silabsLog(__VA_ARGS__); void appError(int err); #ifdef __cplusplus diff --git a/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn b/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn index 7eadbc73e8c4a9..5a9aed051d28fc 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn @@ -36,7 +36,6 @@ ti_sysconfig("sysconfig") { sources = [ "${project_dir}/chip.syscfg" ] outputs = [ - "ti_devices_config.c", "ti_radio_config.c", "ti_radio_config.h", "ti_drivers_config.c", diff --git a/examples/pump-app/cc13x2x7_26x2x7/args.gni b/examples/pump-app/cc13x2x7_26x2x7/args.gni index 8baf8977c88bb2..aeeb0708a235e7 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/args.gni +++ b/examples/pump-app/cc13x2x7_26x2x7/args.gni @@ -29,10 +29,12 @@ lwip_debug = false chip_enable_ota_requestor = true +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2" + # Disable CHIP Logging #chip_progress_logging = false -#chip_detail_logging = false -#chip_automation_logging = false +chip_detail_logging = false +chip_automation_logging = false # BLE options chip_config_network_layer_ble = true diff --git a/examples/pump-app/cc13x2x7_26x2x7/chip.syscfg b/examples/pump-app/cc13x2x7_26x2x7/chip.syscfg index 6bbd36becbf9cc..995ad22af6b435 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/pump-app/cc13x2x7_26x2x7/chip.syscfg @@ -17,159 +17,51 @@ * limitations under the License. */ -/** - * These arguments were used when this file was generated. They will be automatically applied on subsequent loads - * via the GUI or CLI. Run CLI with '--help' for additional information on how to override these arguments. - * @cliArgs --board "/ti/boards/CC26X2R1_LAUNCHXL" --product "simplelink_cc13x2_26x2_sdk@4.40.05.02_eng" - * @versions {"tool":"1.9.0+2015","templates":null} - */ - -/** - * Import the modules used in this configuration. - */ -const ble = scripting.addModule("/ti/ble5stack/ble"); -const CCFG = scripting.addModule("/ti/devices/CCFG"); -const rfdesign = scripting.addModule("/ti/devices/radioconfig/rfdesign"); -const dmm = scripting.addModule("/ti/dmm/dmm"); -const AESCCM = scripting.addModule("/ti/drivers/AESCCM"); -const AESCCM1 = AESCCM.addInstance(); -const AESCCM2 = AESCCM.addInstance(); -const AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); -const AESCTRDRBG1 = AESCTRDRBG.addInstance(); -const AESECB = scripting.addModule("/ti/drivers/AESECB"); -const AESECB1 = AESECB.addInstance(); -const AESECB2 = AESECB.addInstance(); -const ECDH = scripting.addModule("/ti/drivers/ECDH"); -const ECDH1 = ECDH.addInstance(); -const ECDH2 = ECDH.addInstance(); -const NVS = scripting.addModule("/ti/drivers/NVS"); -const NVS1 = NVS.addInstance(); -const NVS2 = NVS.addInstance(); -const RF = scripting.addModule("/ti/drivers/RF"); -const RTOS = scripting.addModule("/ti/drivers/RTOS"); -const SHA2 = scripting.addModule("/ti/drivers/SHA2"); -const SHA21 = SHA2.addInstance(); -const TRNG = scripting.addModule("/ti/drivers/TRNG"); -const TRNG1 = TRNG.addInstance(); -const TRNG2 = TRNG.addInstance(); -const TRNG3 = TRNG.addInstance(); -const UART = scripting.addModule("/ti/drivers/UART"); -const UART1 = UART.addInstance(); -const UART2 = UART.addInstance(); -const Button = scripting.addModule("/ti/drivers/apps/Button"); -const Button1 = Button.addInstance(); -const Button2 = Button.addInstance(); -const LED = scripting.addModule("/ti/drivers/apps/LED"); -const LED1 = LED.addInstance(); -const LED2 = LED.addInstance(); -const thread = scripting.addModule("/ti/thread/thread"); - -/** - * Write custom configuration values to the imported modules. - */ -ble.maxConnNum = 1; -ble.numOfAdvSets = 1; -ble.lockProject = true; -ble.maxPDUSize = 255; -ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; -ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; -ble.connUpdateParamsPeripheral.reqMinConnInt = 30; -ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; -ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; -ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; -ble.advSet1.advData1.$name = "ti_ble5stack_broadcaster_advertisement_data0"; -ble.advSet1.scanRes1.$name = "ti_ble5stack_broadcaster_advertisement_data1"; - -CCFG.enableBootloader = true; -CCFG.enableBootloaderBackdoor = true; -CCFG.dioBootloaderBackdoor = 13; -CCFG.levelBootloaderBackdoor = "Active low"; -CCFG.srcClkLF = "Derived from HF XOSC"; -CCFG.ccfgTemplate.$name = "ti_devices_CCFGTemplate0"; - -dmm.project = "ti_thread_thermostat_remote_display"; -dmm.stackRoles = ["blePeripheral","threadFTD"]; -dmm.lockStackRoles = true; -dmm.numApplicationStates = 10; -dmm.applicationState0 = "ANY"; -dmm.applicationState1 = "DMMPOLICY_BLE_IDLE"; -dmm.applicationState2 = "DMMPOLICY_BLE_ADV"; -dmm.applicationState3 = "DMMPOLICY_BLE_CONNECTING"; -dmm.applicationState4 = "DMMPOLICY_BLE_HIGH_BANDWIDTH"; -dmm.applicationState5 = "DMMPOLICY_BLE_CONNECTED"; -dmm.applicationState6 = "DMMPOLICY_BLE_OAD"; -dmm.applicationState7 = "DMMPOLICY_THREAD_IDLE"; -dmm.applicationState8 = "DMMPOLICY_THREAD_LINK_EST"; -dmm.applicationState9 = "DMMPOLICY_THREAD_DATA"; -dmm.policyArray.create(4); -dmm.policyArray[0].$name = "ti_dmm_policy_dmm_policy0"; -dmm.policyArray[0].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble0"; -dmm.policyArray[0].blePeripheral.applicationStates = ["applicationState6"]; -dmm.policyArray[0].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread0"; -dmm.policyArray[0].threadFTD.pause = "DMMPOLICY_PAUSED"; -dmm.policyArray[1].$name = "ti_dmm_policy_dmm_policy1"; -dmm.policyArray[1].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble1"; -dmm.policyArray[1].blePeripheral.applicationStates = ["applicationState3","applicationState4"]; -dmm.policyArray[1].blePeripheral.weight = 25; -dmm.policyArray[1].blePeripheral.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_BLE_CONNECTION"]; -dmm.policyArray[1].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread1"; -dmm.policyArray[2].$name = "ti_dmm_policy_dmm_policy2"; -dmm.policyArray[2].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble2"; -dmm.policyArray[2].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread2"; -dmm.policyArray[2].threadFTD.weight = 30; -dmm.policyArray[2].threadFTD.applicationStates = ["applicationState8"]; -dmm.policyArray[2].threadFTD.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_ALL"]; -dmm.policyArray[3].$name = "ti_dmm_policy_dmm_policy3"; -dmm.policyArray[3].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble3"; -dmm.policyArray[3].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread3"; -dmm.policyArray[3].threadFTD.weight = 1; -AESCCM1.$name = "CONFIG_AESCCM0"; - -AESCCM2.$name = "CONFIG_AESCCM_1"; +/* Modules */ +var AESCCM = scripting.addModule("/ti/drivers/AESCCM"); +var AESECB = scripting.addModule("/ti/drivers/AESECB"); +var Button = scripting.addModule("/ti/drivers/apps/Button"); +var LED = scripting.addModule("/ti/drivers/apps/LED"); +var NVS = scripting.addModule("/ti/drivers/NVS"); +var RF = scripting.addModule("/ti/drivers/RF"); +var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); +var TRNG = scripting.addModule("/ti/drivers/TRNG"); +var SHA2 = scripting.addModule("/ti/drivers/SHA2"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); +var ble = scripting.addModule("/ti/ble5stack/ble"); +var dmm = scripting.addModule("/ti/dmm/dmm"); +var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); +var ECDH = scripting.addModule("/ti/drivers/ECDH"); + +/* Instances */ +var AESCCM1 = AESCCM.addInstance(); +var AESECB1 = AESECB.addInstance(); +var AESECB2 = AESECB.addInstance(); +var Button1 = Button.addInstance(); +var Button2 = Button.addInstance(); +var NVS1 = NVS.addInstance(); +var NVS2 = NVS.addInstance(); +var SHA21 = SHA2.addInstance(); +var LED1 = LED.addInstance(); +var LED2 = LED.addInstance(); +var TRNG1 = TRNG.addInstance(); +var TRNG2 = TRNG.addInstance(); +var TRNG3 = TRNG.addInstance(); +var UART2 = UART2.addInstance(); +var AESCTRDRBG1 = AESCTRDRBG.addInstance(); +var ECDH1 = ECDH.addInstance(); AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; -AESCTRDRBG1.aesctrObject.$name = "CONFIG_AESCTR_0"; -AESECB1.$name = "CONFIG_AESECB0"; +AESCCM1.$name = "CONFIG_AESCCM0"; +AESECB1.$name = "CONFIG_AESECB0"; AESECB2.$name = "CONFIG_AESECB_1"; ECDH1.$name = "CONFIG_ECDH0"; -ECDH2.$name = "CONFIG_ECDH_1"; - -NVS1.$name = "CONFIG_NVSINTERNAL"; -NVS1.internalFlash.$name = "ti_drivers_nvs_NVSCC26XX0"; -NVS1.internalFlash.regionBase = 0xAA000; -NVS1.internalFlash.regionSize = 0x4000; - -NVS2.$name = "CONFIG_NVSEXTERNAL"; -NVS2.nvsType = "External"; // NVS Region Type -NVS2.$hardware = system.deviceData.board.components.MX25R8035F; - -RTOS.name = "FreeRTOS"; - -SHA21.$name = "CONFIG_SHA2_0"; - -TRNG1.$name = "CONFIG_TRNG_0"; - -TRNG2.$name = "CONFIG_TRNG_1"; - -TRNG3.$name = "CONFIG_TRNG_APP"; - -UART1.$name = "CONFIG_UART_DEBUG"; -UART1.uart.$assign = "UART1"; -UART1.uart.txPin.$assign = "boosterpack.4"; -UART1.uart.rxPin.$assign = "boosterpack.3"; -UART1.txPinInstance.$name = "CONFIG_PIN_4"; -UART1.rxPinInstance.$name = "CONFIG_PIN_5"; - -UART2.$name = "CONFIG_DISPLAY_UART"; -UART2.txPinInstance.$name = "CONFIG_PIN_6"; -UART2.rxPinInstance.$name = "CONFIG_PIN_7"; - - /* Left Button */ Button1.$name = "CONFIG_BTN_LEFT"; Button1.$hardware = system.deviceData.board.components["BTN-1"]; @@ -184,6 +76,90 @@ Button2.gpioPin.$name = "CONFIG_GPIO_BTN2"; Button2.gpioPin.pull = "Pull Up"; Button2.gpioPin.interruptTrigger = "Falling Edge"; +/* ======== CCFG ======== */ +var CCFG = scripting.addModule("/ti/devices/CCFG"); +const ccfgSettings = system.getScript("/ti/common/lprf_ccfg_settings.js").ccfgSettings; +for(var setting in ccfgSettings) +{ + CCFG[setting] = ccfgSettings[setting]; +} + +// Disable CCFG generation, this is added by the BIM project +CCFG.enableCodeGeneration = false; + +/* NVS */ +NVS1.$name = "CONFIG_NVSINTERNAL"; +NVS1.internalFlash.regionBase = 0xAA000; +NVS1.internalFlash.regionSize = 0x4000; + +NVS2.$name = "CONFIG_NVSEXTERNAL"; +NVS2.nvsType = "External"; // NVS Region Type +NVS2.$hardware = system.deviceData.board.components.MX25R8035F; + +/* RF */ +/* if an antenna component exists, assign it to the rf instance */ +if (system.deviceData.board && system.deviceData.board.components.RF) { + RF.$hardware = system.deviceData.board.components.RF; +} + +const rfDesignSettings = system.getScript("/ti/common/lprf_rf_design_settings.js").rfDesignSettings; +for(var setting in rfDesignSettings) +{ + RFDesign[setting] = rfDesignSettings[setting]; +} + +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + /* Red LED */ LED1.$name = "CONFIG_LED_RED"; LED1.$hardware = system.deviceData.board.components.LED_RED; @@ -198,19 +174,65 @@ LED2.gpioPin.$name = "CONFIG_GPIO_GLED"; LED2.gpioPin.mode = "Output"; LED2.gpioPin.callbackFunction = ""; -thread.deviceTypeReadOnly = true; -thread.pm.$name = "ti_thread_pm_thread_pm0"; -thread.rf.$name = "ti_thread_rf_thread_rf0"; -thread.rf.radioConfig.$name = "ti_devices_radioconfig_settings_ieee_15_40"; -thread.rf.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param0"; -thread.network.$name = "ti_thread_network_thread_network0"; -thread.security.$name = "ti_thread_security_thread_security0"; - -/** - * Pinmux solution for unlocked pins/peripherals. This ensures that minor changes to the automatic solver in a future - * version of the tool will not impact the pinmux you originally saw. These lines can be completely deleted in order to - * re-solve from scratch. - */ -UART2.uart.$suggestSolution = "UART0"; -UART2.uart.txPin.$suggestSolution = "boosterpack.30"; -UART2.uart.rxPin.$suggestSolution = "boosterpack.29"; +/* Debug UART */ +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART2_DEBUG"; + +/* TRNG */ +TRNG1.$name = "CONFIG_TRNG_0"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; +TRNG3.$name = "CONFIG_TRNG_APP"; + +/* BLE */ +ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; +ble.maxConnNum = 1; +ble.numOfAdvSets = 1; +ble.lockProject = true; +ble.oneLibSizeOpt = true; +ble.maxPDUSize = 255; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param2"; +ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; +ble.connUpdateParamsPeripheral.reqMinConnInt = 30; +ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; + + +ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; +ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; + +/* DMM */ +dmm.project = "ti_thread_thermostat_remote_display"; +dmm.stackRoles = ["blePeripheral","threadFTD"]; +dmm.lockStackRoles = true; +dmm.numApplicationStates = 10; +dmm.applicationState0 = "ANY"; +dmm.applicationState1 = "DMMPOLICY_BLE_IDLE"; +dmm.applicationState2 = "DMMPOLICY_BLE_ADV"; +dmm.applicationState3 = "DMMPOLICY_BLE_CONNECTING"; +dmm.applicationState4 = "DMMPOLICY_BLE_HIGH_BANDWIDTH"; +dmm.applicationState5 = "DMMPOLICY_BLE_CONNECTED"; +dmm.applicationState6 = "DMMPOLICY_BLE_OAD"; +dmm.applicationState7 = "DMMPOLICY_THREAD_IDLE"; +dmm.applicationState8 = "DMMPOLICY_THREAD_LINK_EST"; +dmm.applicationState9 = "DMMPOLICY_THREAD_DATA"; +dmm.policyArray.create(4); +dmm.policyArray[0].$name = "ti_dmm_policy_dmm_policy0"; +dmm.policyArray[0].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble0"; +dmm.policyArray[0].blePeripheral.applicationStates = ["applicationState6"]; +dmm.policyArray[0].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread0"; +dmm.policyArray[0].threadFTD.pause = "DMMPOLICY_PAUSED"; +dmm.policyArray[1].$name = "ti_dmm_policy_dmm_policy1"; +dmm.policyArray[1].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble1"; +dmm.policyArray[1].blePeripheral.applicationStates = ["applicationState3","applicationState4"]; +dmm.policyArray[1].blePeripheral.weight = 25; +dmm.policyArray[1].blePeripheral.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_BLE_CONNECTION"]; +dmm.policyArray[1].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread1"; +dmm.policyArray[2].$name = "ti_dmm_policy_dmm_policy2"; +dmm.policyArray[2].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble2"; +dmm.policyArray[2].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread2"; +dmm.policyArray[2].threadFTD.weight = 30; +dmm.policyArray[2].threadFTD.applicationStates = ["applicationState8"]; +dmm.policyArray[2].threadFTD.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_ALL"]; +dmm.policyArray[3].$name = "ti_dmm_policy_dmm_policy3"; +dmm.policyArray[3].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble3"; +dmm.policyArray[3].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread3"; +dmm.policyArray[3].threadFTD.weight = 1; diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp index 5eb903e6ca0688..4514cd7cd8b8d8 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -38,7 +38,7 @@ #include #include #include -#include +#include #endif #include #include @@ -135,7 +135,7 @@ int AppTask::Init() LED_Params ledParams; Button_Params buttonParams; - cc13x2_26x2LogInit(); + cc13xx_26xxLogInit(); // Init Chip memory management before the stack Platform::MemoryInit(); @@ -221,7 +221,7 @@ int AppTask::Init() (void) initParams.InitializeStaticResourcesBeforeServerInit(); chip::Server::GetInstance().Init(initParams); -// Initialize device attestation config + // Initialize device attestation config #ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); #else diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp b/examples/pump-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp index a66a9e1a7ba1b4..54faa0db6e7314 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp +++ b/examples/pump-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp @@ -7,7 +7,7 @@ * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 - *BoltLockManager + * * 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. diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/include/AppConfig.h b/examples/pump-app/cc13x2x7_26x2x7/main/include/AppConfig.h index 3cead418532caa..b925344ddb4c9a 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/include/AppConfig.h +++ b/examples/pump-app/cc13x2x7_26x2x7/main/include/AppConfig.h @@ -1,6 +1,5 @@ /* * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,9 +23,9 @@ extern "C" { #endif -int cc13x2_26x2LogInit(void); -void cc13x2_26x2Log(const char * aFormat, ...); -#define PLAT_LOG(...) cc13x2_26x2Log(__VA_ARGS__); +int cc13xx_26xxLogInit(void); +void cc13xx_26xxLog(const char * aFormat, ...); +#define PLAT_LOG(...) cc13xx_26xxLog(__VA_ARGS__); #ifdef __cplusplus } diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/include/AppEvent.h b/examples/pump-app/cc13x2x7_26x2x7/main/include/AppEvent.h index 0f501990b2ab76..3a9c606e95c330 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/include/AppEvent.h +++ b/examples/pump-app/cc13x2x7_26x2x7/main/include/AppEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2018 Nest Labs, Inc. + * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h b/examples/pump-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h index 5cb1c4369f9dd7..f99523c278db0c 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h +++ b/examples/pump-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h @@ -74,7 +74,7 @@ */ #define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) -#define MATTER_CC13X2_26X2_PLATFORM_LOG_ENABLED 1 +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 1 /** * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/main.cpp b/examples/pump-app/cc13x2x7_26x2x7/main/main.cpp index 6137478fc2ffcc..2b4be76e9c33da 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/main.cpp +++ b/examples/pump-app/cc13x2x7_26x2x7/main/main.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include @@ -38,7 +37,7 @@ #include #include -#define TOTAL_ICALL_HEAP_SIZE (0xCB00) +#define TOTAL_ICALL_HEAP_SIZE (0xC700) using namespace ::chip; using namespace ::chip::Inet; @@ -58,6 +57,17 @@ extern "C" void vApplicationStackOverflowHook(void) } } +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + // ================================================================================ // Main Code // ================================================================================ @@ -70,8 +80,6 @@ int main(void) NVS_init(); - UART_init(); - ECDH_init(); ECDSA_init(); diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/BUILD.gn b/examples/pump-controller-app/cc13x2x7_26x2x7/BUILD.gn index d3031712c04a58..0155ff6461ddd9 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/BUILD.gn @@ -37,7 +37,6 @@ ti_sysconfig("sysconfig") { sources = [ "${project_dir}/chip.syscfg" ] outputs = [ - "ti_devices_config.c", "ti_radio_config.c", "ti_radio_config.h", "ti_drivers_config.c", @@ -84,6 +83,7 @@ ti_simplelink_executable("pump_controller_app") { deps = [ ":sdk", ":sysconfig", + "${chip_root}/examples/platform/cc13x2_26x2:cc13x2_26x2-attestation-credentials", "${chip_root}/examples/pump-controller-app/pump-controller-common", "${chip_root}/src/lib", ] diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/args.gni b/examples/pump-controller-app/cc13x2x7_26x2x7/args.gni index 7d386dc216df2f..fb13057bc99474 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/args.gni +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/args.gni @@ -29,10 +29,12 @@ lwip_debug = false chip_enable_ota_requestor = true +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2" + # Disable CHIP Logging #chip_progress_logging = false -#chip_detail_logging = false -#chip_automation_logging = false +chip_detail_logging = false +chip_automation_logging = false # BLE options chip_config_network_layer_ble = true diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/chip.syscfg b/examples/pump-controller-app/cc13x2x7_26x2x7/chip.syscfg index 47c7ded81c1b56..995ad22af6b435 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/chip.syscfg @@ -17,158 +17,51 @@ * limitations under the License. */ -/** - * These arguments were used when this file was generated. They will be automatically applied on subsequent loads - * via the GUI or CLI. Run CLI with '--help' for additional information on how to override these arguments. - * @cliArgs --board "/ti/boards/CC26X2R1_LAUNCHXL" --product "simplelink_cc13x2_26x2_sdk@4.40.05.02_eng" - * @versions {"tool":"1.9.0+2015","templates":null} - */ - -/** - * Import the modules used in this configuration. - */ -const ble = scripting.addModule("/ti/ble5stack/ble"); -const CCFG = scripting.addModule("/ti/devices/CCFG"); -const rfdesign = scripting.addModule("/ti/devices/radioconfig/rfdesign"); -const dmm = scripting.addModule("/ti/dmm/dmm"); -const AESCCM = scripting.addModule("/ti/drivers/AESCCM"); -const AESCCM1 = AESCCM.addInstance(); -const AESCCM2 = AESCCM.addInstance(); -const AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); -const AESCTRDRBG1 = AESCTRDRBG.addInstance(); -const AESECB = scripting.addModule("/ti/drivers/AESECB"); -const AESECB1 = AESECB.addInstance(); -const AESECB2 = AESECB.addInstance(); -const ECDH = scripting.addModule("/ti/drivers/ECDH"); -const ECDH1 = ECDH.addInstance(); -const ECDH2 = ECDH.addInstance(); -const NVS = scripting.addModule("/ti/drivers/NVS"); -const NVS1 = NVS.addInstance(); -const NVS2 = NVS.addInstance(); -const RF = scripting.addModule("/ti/drivers/RF"); -const RTOS = scripting.addModule("/ti/drivers/RTOS"); -const SHA2 = scripting.addModule("/ti/drivers/SHA2"); -const SHA21 = SHA2.addInstance(); -const TRNG = scripting.addModule("/ti/drivers/TRNG"); -const TRNG1 = TRNG.addInstance(); -const TRNG2 = TRNG.addInstance(); -const TRNG3 = TRNG.addInstance(); -const UART = scripting.addModule("/ti/drivers/UART"); -const UART1 = UART.addInstance(); -const UART2 = UART.addInstance(); -const Button = scripting.addModule("/ti/drivers/apps/Button"); -const Button1 = Button.addInstance(); -const Button2 = Button.addInstance(); -const LED = scripting.addModule("/ti/drivers/apps/LED"); -const LED1 = LED.addInstance(); -const LED2 = LED.addInstance(); -const thread = scripting.addModule("/ti/thread/thread"); - -/** - * Write custom configuration values to the imported modules. - */ -ble.maxConnNum = 1; -ble.numOfAdvSets = 1; -ble.lockProject = true; -ble.maxPDUSize = 255; -ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; -ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; -ble.connUpdateParamsPeripheral.reqMinConnInt = 30; -ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; -ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; -ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; -ble.advSet1.advData1.$name = "ti_ble5stack_broadcaster_advertisement_data0"; -ble.advSet1.scanRes1.$name = "ti_ble5stack_broadcaster_advertisement_data1"; - -CCFG.enableBootloader = true; -CCFG.enableBootloaderBackdoor = true; -CCFG.dioBootloaderBackdoor = 13; -CCFG.levelBootloaderBackdoor = "Active low"; -CCFG.srcClkLF = "Derived from HF XOSC"; -CCFG.ccfgTemplate.$name = "ti_devices_CCFGTemplate0"; - -dmm.project = "ti_thread_thermostat_remote_display"; -dmm.stackRoles = ["blePeripheral","threadFTD"]; -dmm.lockStackRoles = true; -dmm.numApplicationStates = 10; -dmm.applicationState0 = "ANY"; -dmm.applicationState1 = "DMMPOLICY_BLE_IDLE"; -dmm.applicationState2 = "DMMPOLICY_BLE_ADV"; -dmm.applicationState3 = "DMMPOLICY_BLE_CONNECTING"; -dmm.applicationState4 = "DMMPOLICY_BLE_HIGH_BANDWIDTH"; -dmm.applicationState5 = "DMMPOLICY_BLE_CONNECTED"; -dmm.applicationState6 = "DMMPOLICY_BLE_OAD"; -dmm.applicationState7 = "DMMPOLICY_THREAD_IDLE"; -dmm.applicationState8 = "DMMPOLICY_THREAD_LINK_EST"; -dmm.applicationState9 = "DMMPOLICY_THREAD_DATA"; -dmm.policyArray.create(4); -dmm.policyArray[0].$name = "ti_dmm_policy_dmm_policy0"; -dmm.policyArray[0].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble0"; -dmm.policyArray[0].blePeripheral.applicationStates = ["applicationState6"]; -dmm.policyArray[0].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread0"; -dmm.policyArray[0].threadFTD.pause = "DMMPOLICY_PAUSED"; -dmm.policyArray[1].$name = "ti_dmm_policy_dmm_policy1"; -dmm.policyArray[1].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble1"; -dmm.policyArray[1].blePeripheral.applicationStates = ["applicationState3","applicationState4"]; -dmm.policyArray[1].blePeripheral.weight = 25; -dmm.policyArray[1].blePeripheral.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_BLE_CONNECTION"]; -dmm.policyArray[1].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread1"; -dmm.policyArray[2].$name = "ti_dmm_policy_dmm_policy2"; -dmm.policyArray[2].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble2"; -dmm.policyArray[2].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread2"; -dmm.policyArray[2].threadFTD.weight = 30; -dmm.policyArray[2].threadFTD.applicationStates = ["applicationState8"]; -dmm.policyArray[2].threadFTD.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_ALL"]; -dmm.policyArray[3].$name = "ti_dmm_policy_dmm_policy3"; -dmm.policyArray[3].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble3"; -dmm.policyArray[3].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread3"; -dmm.policyArray[3].threadFTD.weight = 1; -AESCCM1.$name = "CONFIG_AESCCM0"; - -AESCCM2.$name = "CONFIG_AESCCM_1"; +/* Modules */ +var AESCCM = scripting.addModule("/ti/drivers/AESCCM"); +var AESECB = scripting.addModule("/ti/drivers/AESECB"); +var Button = scripting.addModule("/ti/drivers/apps/Button"); +var LED = scripting.addModule("/ti/drivers/apps/LED"); +var NVS = scripting.addModule("/ti/drivers/NVS"); +var RF = scripting.addModule("/ti/drivers/RF"); +var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); +var TRNG = scripting.addModule("/ti/drivers/TRNG"); +var SHA2 = scripting.addModule("/ti/drivers/SHA2"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); +var ble = scripting.addModule("/ti/ble5stack/ble"); +var dmm = scripting.addModule("/ti/dmm/dmm"); +var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); +var ECDH = scripting.addModule("/ti/drivers/ECDH"); + +/* Instances */ +var AESCCM1 = AESCCM.addInstance(); +var AESECB1 = AESECB.addInstance(); +var AESECB2 = AESECB.addInstance(); +var Button1 = Button.addInstance(); +var Button2 = Button.addInstance(); +var NVS1 = NVS.addInstance(); +var NVS2 = NVS.addInstance(); +var SHA21 = SHA2.addInstance(); +var LED1 = LED.addInstance(); +var LED2 = LED.addInstance(); +var TRNG1 = TRNG.addInstance(); +var TRNG2 = TRNG.addInstance(); +var TRNG3 = TRNG.addInstance(); +var UART2 = UART2.addInstance(); +var AESCTRDRBG1 = AESCTRDRBG.addInstance(); +var ECDH1 = ECDH.addInstance(); AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; -AESCTRDRBG1.aesctrObject.$name = "CONFIG_AESCTR_0"; -AESECB1.$name = "CONFIG_AESECB0"; +AESCCM1.$name = "CONFIG_AESCCM0"; +AESECB1.$name = "CONFIG_AESECB0"; AESECB2.$name = "CONFIG_AESECB_1"; ECDH1.$name = "CONFIG_ECDH0"; -ECDH2.$name = "CONFIG_ECDH_1"; - -NVS1.$name = "CONFIG_NVSINTERNAL"; -NVS1.internalFlash.$name = "ti_drivers_nvs_NVSCC26XX0"; -NVS1.internalFlash.regionBase = 0xAA000; -NVS1.internalFlash.regionSize = 0x4000; - -NVS2.$name = "CONFIG_NVSEXTERNAL"; -NVS2.nvsType = "External"; // NVS Region Type -NVS2.$hardware = system.deviceData.board.components.MX25R8035F; - -RTOS.name = "FreeRTOS"; - -SHA21.$name = "CONFIG_SHA2_0"; - -TRNG1.$name = "CONFIG_TRNG_0"; - -TRNG2.$name = "CONFIG_TRNG_1"; - -TRNG3.$name = "CONFIG_TRNG_APP"; - -UART1.$name = "CONFIG_UART_DEBUG"; -UART1.uart.$assign = "UART1"; -UART1.uart.txPin.$assign = "boosterpack.4"; -UART1.uart.rxPin.$assign = "boosterpack.3"; -UART1.txPinInstance.$name = "CONFIG_PIN_4"; -UART1.rxPinInstance.$name = "CONFIG_PIN_5"; - -UART2.$name = "CONFIG_DISPLAY_UART"; -UART2.txPinInstance.$name = "CONFIG_PIN_6"; -UART2.rxPinInstance.$name = "CONFIG_PIN_7"; - /* Left Button */ Button1.$name = "CONFIG_BTN_LEFT"; Button1.$hardware = system.deviceData.board.components["BTN-1"]; @@ -183,6 +76,90 @@ Button2.gpioPin.$name = "CONFIG_GPIO_BTN2"; Button2.gpioPin.pull = "Pull Up"; Button2.gpioPin.interruptTrigger = "Falling Edge"; +/* ======== CCFG ======== */ +var CCFG = scripting.addModule("/ti/devices/CCFG"); +const ccfgSettings = system.getScript("/ti/common/lprf_ccfg_settings.js").ccfgSettings; +for(var setting in ccfgSettings) +{ + CCFG[setting] = ccfgSettings[setting]; +} + +// Disable CCFG generation, this is added by the BIM project +CCFG.enableCodeGeneration = false; + +/* NVS */ +NVS1.$name = "CONFIG_NVSINTERNAL"; +NVS1.internalFlash.regionBase = 0xAA000; +NVS1.internalFlash.regionSize = 0x4000; + +NVS2.$name = "CONFIG_NVSEXTERNAL"; +NVS2.nvsType = "External"; // NVS Region Type +NVS2.$hardware = system.deviceData.board.components.MX25R8035F; + +/* RF */ +/* if an antenna component exists, assign it to the rf instance */ +if (system.deviceData.board && system.deviceData.board.components.RF) { + RF.$hardware = system.deviceData.board.components.RF; +} + +const rfDesignSettings = system.getScript("/ti/common/lprf_rf_design_settings.js").rfDesignSettings; +for(var setting in rfDesignSettings) +{ + RFDesign[setting] = rfDesignSettings[setting]; +} + +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + /* Red LED */ LED1.$name = "CONFIG_LED_RED"; LED1.$hardware = system.deviceData.board.components.LED_RED; @@ -197,19 +174,65 @@ LED2.gpioPin.$name = "CONFIG_GPIO_GLED"; LED2.gpioPin.mode = "Output"; LED2.gpioPin.callbackFunction = ""; -thread.deviceTypeReadOnly = true; -thread.pm.$name = "ti_thread_pm_thread_pm0"; -thread.rf.$name = "ti_thread_rf_thread_rf0"; -thread.rf.radioConfig.$name = "ti_devices_radioconfig_settings_ieee_15_40"; -thread.rf.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param0"; -thread.network.$name = "ti_thread_network_thread_network0"; -thread.security.$name = "ti_thread_security_thread_security0"; - -/** - * Pinmux solution for unlocked pins/peripherals. This ensures that minor changes to the automatic solver in a future - * version of the tool will not impact the pinmux you originally saw. These lines can be completely deleted in order to - * re-solve from scratch. - */ -UART2.uart.$suggestSolution = "UART0"; -UART2.uart.txPin.$suggestSolution = "boosterpack.30"; -UART2.uart.rxPin.$suggestSolution = "boosterpack.29"; +/* Debug UART */ +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART2_DEBUG"; + +/* TRNG */ +TRNG1.$name = "CONFIG_TRNG_0"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; +TRNG3.$name = "CONFIG_TRNG_APP"; + +/* BLE */ +ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; +ble.maxConnNum = 1; +ble.numOfAdvSets = 1; +ble.lockProject = true; +ble.oneLibSizeOpt = true; +ble.maxPDUSize = 255; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param2"; +ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; +ble.connUpdateParamsPeripheral.reqMinConnInt = 30; +ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; + + +ble.advSet1.$name = "ti_ble5stack_broadcaster_advertisement_set0"; +ble.advSet1.advParam1.$name = "ti_ble5stack_broadcaster_advertisement_params0"; + +/* DMM */ +dmm.project = "ti_thread_thermostat_remote_display"; +dmm.stackRoles = ["blePeripheral","threadFTD"]; +dmm.lockStackRoles = true; +dmm.numApplicationStates = 10; +dmm.applicationState0 = "ANY"; +dmm.applicationState1 = "DMMPOLICY_BLE_IDLE"; +dmm.applicationState2 = "DMMPOLICY_BLE_ADV"; +dmm.applicationState3 = "DMMPOLICY_BLE_CONNECTING"; +dmm.applicationState4 = "DMMPOLICY_BLE_HIGH_BANDWIDTH"; +dmm.applicationState5 = "DMMPOLICY_BLE_CONNECTED"; +dmm.applicationState6 = "DMMPOLICY_BLE_OAD"; +dmm.applicationState7 = "DMMPOLICY_THREAD_IDLE"; +dmm.applicationState8 = "DMMPOLICY_THREAD_LINK_EST"; +dmm.applicationState9 = "DMMPOLICY_THREAD_DATA"; +dmm.policyArray.create(4); +dmm.policyArray[0].$name = "ti_dmm_policy_dmm_policy0"; +dmm.policyArray[0].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble0"; +dmm.policyArray[0].blePeripheral.applicationStates = ["applicationState6"]; +dmm.policyArray[0].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread0"; +dmm.policyArray[0].threadFTD.pause = "DMMPOLICY_PAUSED"; +dmm.policyArray[1].$name = "ti_dmm_policy_dmm_policy1"; +dmm.policyArray[1].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble1"; +dmm.policyArray[1].blePeripheral.applicationStates = ["applicationState3","applicationState4"]; +dmm.policyArray[1].blePeripheral.weight = 25; +dmm.policyArray[1].blePeripheral.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_BLE_CONNECTION"]; +dmm.policyArray[1].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread1"; +dmm.policyArray[2].$name = "ti_dmm_policy_dmm_policy2"; +dmm.policyArray[2].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble2"; +dmm.policyArray[2].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread2"; +dmm.policyArray[2].threadFTD.weight = 30; +dmm.policyArray[2].threadFTD.applicationStates = ["applicationState8"]; +dmm.policyArray[2].threadFTD.appliedActivity = ["DMMPOLICY_APPLIED_ACTIVITY_ALL"]; +dmm.policyArray[3].$name = "ti_dmm_policy_dmm_policy3"; +dmm.policyArray[3].blePeripheral.$name = "ti_dmm_policy_stack_dmm_stack_ble3"; +dmm.policyArray[3].threadFTD.$name = "ti_dmm_policy_stack_dmm_stack_thread3"; +dmm.policyArray[3].threadFTD.weight = 1; diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp index e8611622fc28dd..8c4e51f44431fd 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -24,7 +24,8 @@ #include "FreeRTOS.h" #include -#include + +#include #include #include @@ -34,7 +35,7 @@ #include #include #include -#include +#include #endif #include #include @@ -122,7 +123,7 @@ int AppTask::Init() LED_Params ledParams; Button_Params buttonParams; - cc13x2_26x2LogInit(); + cc13xx_26xxLogInit(); // Init Chip memory management before the stack chip::Platform::MemoryInit(); @@ -174,7 +175,11 @@ int AppTask::Init() chip::Server::GetInstance().Init(initParams); // Initialize device attestation config +#ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS + SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); +#else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif // Initialize LEDs PLAT_LOG("Initialize LEDs"); diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp b/examples/pump-controller-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp index 9dfc7e22e76687..e450a4b233eddb 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/ZclCallbacks.cpp @@ -7,7 +7,7 @@ * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 - *BoltLockManager + * * 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. diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppConfig.h b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppConfig.h index 3cead418532caa..b925344ddb4c9a 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppConfig.h +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppConfig.h @@ -1,6 +1,5 @@ /* * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,9 +23,9 @@ extern "C" { #endif -int cc13x2_26x2LogInit(void); -void cc13x2_26x2Log(const char * aFormat, ...); -#define PLAT_LOG(...) cc13x2_26x2Log(__VA_ARGS__); +int cc13xx_26xxLogInit(void); +void cc13xx_26xxLog(const char * aFormat, ...); +#define PLAT_LOG(...) cc13xx_26xxLog(__VA_ARGS__); #ifdef __cplusplus } diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppEvent.h b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppEvent.h index 0f501990b2ab76..3a9c606e95c330 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppEvent.h +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/AppEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2018 Nest Labs, Inc. + * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h index aca4a63dc9798f..97dac7bf1fe313 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/include/CHIPProjectConfig.h @@ -74,7 +74,7 @@ */ #define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) -#define MATTER_CC13X2_26X2_PLATFORM_LOG_ENABLED 1 +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 1 /** * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT diff --git a/examples/pump-controller-app/cc13x2x7_26x2x7/main/main.cpp b/examples/pump-controller-app/cc13x2x7_26x2x7/main/main.cpp index 6137478fc2ffcc..2b4be76e9c33da 100644 --- a/examples/pump-controller-app/cc13x2x7_26x2x7/main/main.cpp +++ b/examples/pump-controller-app/cc13x2x7_26x2x7/main/main.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include @@ -38,7 +37,7 @@ #include #include -#define TOTAL_ICALL_HEAP_SIZE (0xCB00) +#define TOTAL_ICALL_HEAP_SIZE (0xC700) using namespace ::chip; using namespace ::chip::Inet; @@ -58,6 +57,17 @@ extern "C" void vApplicationStackOverflowHook(void) } } +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + // ================================================================================ // Main Code // ================================================================================ @@ -70,8 +80,6 @@ int main(void) NVS_init(); - UART_init(); - ECDH_init(); ECDSA_init(); diff --git a/examples/shell/cc13x2x7_26x2x7/BUILD.gn b/examples/shell/cc13x2x7_26x2x7/BUILD.gn index 1b4716017365b7..691853a6f8ebc8 100644 --- a/examples/shell/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/shell/cc13x2x7_26x2x7/BUILD.gn @@ -85,6 +85,7 @@ ti_simplelink_executable("shell_app") { ":sdk", ":sysconfig", "${chip_root}/examples/all-clusters-app/all-clusters-common", + "${chip_root}/examples/platform/cc13x2_26x2:cc13x2_26x2-attestation-credentials", "${chip_root}/examples/shell/shell_common:shell_common", "${chip_root}/src/lib", "${chip_root}/src/lib/shell:shell", diff --git a/examples/shell/cc13x2x7_26x2x7/args.gni b/examples/shell/cc13x2x7_26x2x7/args.gni index 58ec5edf1dbb5a..92dd1dcdfdd0b2 100644 --- a/examples/shell/cc13x2x7_26x2x7/args.gni +++ b/examples/shell/cc13x2x7_26x2x7/args.gni @@ -30,6 +30,7 @@ chip_enable_ota_requestor = false # Disable FTD Build for all-clusters app to save Flash chip_openthread_ftd = false +openthread_external_platform = "${chip_root}/third_party/openthread/platforms/cc13x2_26x2:libopenthread-cc13x2_cc26x2" # Disable CHIP Logging chip_progress_logging = false diff --git a/examples/shell/cc13x2x7_26x2x7/chip.syscfg b/examples/shell/cc13x2x7_26x2x7/chip.syscfg index 738502f344e309..ed0e4a5c8d5fd6 100644 --- a/examples/shell/cc13x2x7_26x2x7/chip.syscfg +++ b/examples/shell/cc13x2x7_26x2x7/chip.syscfg @@ -18,19 +18,16 @@ */ - /* Modules */ var AESCCM = scripting.addModule("/ti/drivers/AESCCM"); var AESECB = scripting.addModule("/ti/drivers/AESECB"); -var ECJPAKE = scripting.addModule("/ti/drivers/ECJPAKE"); var NVS = scripting.addModule("/ti/drivers/NVS"); var RF = scripting.addModule("/ti/drivers/RF"); var RFDesign = scripting.addModule("ti/devices/radioconfig/rfdesign"); -var RTOS = scripting.addModule("/ti/drivers/RTOS"); +var RFCustom = scripting.addModule("/ti/devices/radioconfig/custom"); var TRNG = scripting.addModule("/ti/drivers/TRNG"); -var Thread = scripting.addModule("/ti/thread/thread"); var SHA2 = scripting.addModule("/ti/drivers/SHA2"); -var UART = scripting.addModule("/ti/drivers/UART"); +var UART2 = scripting.addModule("/ti/drivers/UART2"); var ble = scripting.addModule("/ti/ble5stack/ble"); var dmm = scripting.addModule("/ti/dmm/dmm"); var AESCTRDRBG = scripting.addModule("/ti/drivers/AESCTRDRBG"); @@ -40,19 +37,17 @@ var ECDH = scripting.addModule("/ti/drivers/ECDH"); var AESCCM1 = AESCCM.addInstance(); var AESECB1 = AESECB.addInstance(); var AESECB2 = AESECB.addInstance(); -var ECJPAKE = ECJPAKE.addInstance(); var NVS1 = NVS.addInstance(); var NVS2 = NVS.addInstance(); var SHA21 = SHA2.addInstance(); var TRNG1 = TRNG.addInstance(); var TRNG2 = TRNG.addInstance(); var TRNG3 = TRNG.addInstance(); -var UART1 = UART.addInstance(); +var UART2 = UART2.addInstance(); var AESCTRDRBG1 = AESCTRDRBG.addInstance(); var ECDH1 = ECDH.addInstance(); AESCTRDRBG1.$name = "CONFIG_AESCTRDRBG_0"; -AESCTRDRBG1.aesctrObject.$name = "CONFIG_AESCTR_0"; AESCCM1.$name = "CONFIG_AESCCM0"; @@ -92,17 +87,68 @@ for(var setting in rfDesignSettings) RFDesign[setting] = rfDesignSettings[setting]; } -/* Streamer UART */ -UART1.$hardware = system.deviceData.board.components.XDS110UART; -UART1.$name = "CONFIG_UART_STREAMER"; + +/* Handling for RF frontend characterization */ +if(RFDesign.rfDesign.match(/LP_CC2652PSIP/)) +{ + RFCustom.ieee = ["ieee154p10"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154p10.codeExportConfig +} +else +{ + RFCustom.ieee = ["ieee154"]; + var rfCodeExportConfig = RFCustom.radioConfigieee154.codeExportConfig +} + +var cmdList = [ + "cmdIeeeTx", + "cmdIeeeRx", + "cmdIeeeCsma", + "cmdIeeeEdScan", + "cmdIeeeRxAck", + "cmdTxTest" +]; + +rfCodeExportConfig.useConst = true; +rfCodeExportConfig.useMulti = true; +rfCodeExportConfig.symGenMethod = "Custom"; + +const deviceId = system.deviceData.deviceId; + +// Add high PA options if present +if(deviceId.match(/CC(265[12]R|2674R|1352R1|1354R)/)) +{ + cmdList.push("cmdRadioSetup"); + rfCodeExportConfig.cmdRadioSetup = "RF_cmdIeeeRadioSetup"; +} +else if(deviceId.match(/CC(265[12]P|2674P|1352P)/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + rfCodeExportConfig.paExport = "combined"; +} +else if(deviceId.match(/CC(265[34]|1354)P/)) +{ + cmdList.push("cmdRadioSetupPa"); + rfCodeExportConfig.cmdRadioSetupPa = "RF_cmdIeeeRadioSetup"; + // currently not characterized for high PA +} +else +{ + throw new Error("Could not match platform to any known platform types"); +} + +rfCodeExportConfig.cmdList_ieee_15_4 = cmdList; + +/* Debug UART */ +UART2.$hardware = system.deviceData.board.components.XDS110UART; +UART2.$name = "CONFIG_UART_STREAMER"; /* TRNG */ TRNG1.$name = "CONFIG_TRNG_0"; -TRNG2.$name = "CONFIG_TRNG_1"; +TRNG2.$name = "CONFIG_TRNG_THREAD"; TRNG3.$name = "CONFIG_TRNG_APP"; -RTOS.name = "FreeRTOS"; - /* BLE */ ble.addressMode = "ADDRMODE_RP_WITH_PUBLIC_ID"; ble.maxConnNum = 1; @@ -110,7 +156,7 @@ ble.numOfAdvSets = 1; ble.lockProject = true; ble.oneLibSizeOpt = true; ble.maxPDUSize = 255; -ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param1"; +ble.radioConfig.codeExportConfig.$name = "ti_devices_radioconfig_code_export_param2"; ble.connUpdateParamsPeripheral.$name = "ti_ble5stack_general_ble_conn_update_params0"; ble.connUpdateParamsPeripheral.reqMinConnInt = 30; ble.connUpdateParamsPeripheral.reqMaxConnInt = 50; diff --git a/examples/shell/cc13x2x7_26x2x7/include/CHIPProjectConfig.h b/examples/shell/cc13x2x7_26x2x7/include/CHIPProjectConfig.h index 969a02acb089ca..1e8f718031e90f 100644 --- a/examples/shell/cc13x2x7_26x2x7/include/CHIPProjectConfig.h +++ b/examples/shell/cc13x2x7_26x2x7/include/CHIPProjectConfig.h @@ -75,7 +75,7 @@ */ #define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (256) -#define MATTER_CC13X2_26X2_PLATFORM_LOG_ENABLED 0 +#define MATTER_CC13XX_26XX_PLATFORM_LOG_ENABLED 0 /** * CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT diff --git a/examples/shell/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/shell/cc13x2x7_26x2x7/main/AppTask.cpp index 8e29789d2639cd..dda97f4e566ef5 100644 --- a/examples/shell/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/shell/cc13x2x7_26x2x7/main/AppTask.cpp @@ -25,17 +25,18 @@ #include #include -#include #include #include #include +#include + #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR #include #include #include #include -#include +#include #endif #include #include @@ -60,7 +61,7 @@ static TaskHandle_t sAppTaskHandle; // Logging extern "C" { -int cc13x2_26x2LogInit(void); +int cc13xx_26xxLogInit(void); } #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR @@ -102,7 +103,7 @@ CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; - cc13x2_26x2LogInit(); + cc13xx_26xxLogInit(); // Init Chip memory management before the stack Platform::MemoryInit(); @@ -150,7 +151,12 @@ CHIP_ERROR AppTask::Init() chip::Server::GetInstance().Init(initParams); // Initialize device attestation config +#ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS + SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); +#else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif + #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR InitializeOTARequestor(); #endif diff --git a/examples/shell/cc13x2x7_26x2x7/main/main.cpp b/examples/shell/cc13x2x7_26x2x7/main/main.cpp index 198e5c906b3f94..884744230dfc56 100644 --- a/examples/shell/cc13x2x7_26x2x7/main/main.cpp +++ b/examples/shell/cc13x2x7_26x2x7/main/main.cpp @@ -29,7 +29,6 @@ #include #include #include -#include #include #include @@ -38,7 +37,7 @@ #include #include -#define TOTAL_ICALL_HEAP_SIZE (0xc800) +#define TOTAL_ICALL_HEAP_SIZE (0xc700) using namespace ::chip; using namespace ::chip::Inet; @@ -58,6 +57,17 @@ extern "C" void vApplicationStackOverflowHook(void) } } +/* Wrapper functions for using the queue registry regardless of whether it is enabled or disabled */ +extern "C" void vQueueAddToRegistryWrapper(QueueHandle_t xQueue, const char * pcQueueName) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + +extern "C" void vQueueUnregisterQueueWrapper(QueueHandle_t xQueue) +{ + /* This function is intentionally left empty as the Queue Registry is disabled */ +} + // ================================================================================ // Main Code // ================================================================================ @@ -72,8 +82,6 @@ int main(void) NVS_init(); - UART_init(); - ECDH_init(); ECDSA_init(); diff --git a/examples/shell/openiotsdk/CMakeLists.txt b/examples/shell/openiotsdk/CMakeLists.txt index d17908bf6021e7..13ea384b261ff6 100644 --- a/examples/shell/openiotsdk/CMakeLists.txt +++ b/examples/shell/openiotsdk/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) 2022 Project CHIP Authors +# 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. @@ -35,22 +35,6 @@ project(${APP_TARGET} LANGUAGES C CXX ASM) include(sdk) -# LwIP configuration -if(TARGET lwip-cmsis-port) - # lwip requires user_lwipopts.h, we use the custom settings - target_include_directories(lwipopts - INTERFACE - ${OPEN_IOT_SDK_CONFIG}/lwip - ) - - if (${CMAKE_BUILD_TYPE} STREQUAL "Debug") - target_compile_definitions(lwipopts - INTERFACE - LWIP_DEBUG - ) - endif() -endif() - add_executable(${APP_TARGET}) # Application CHIP build configuration @@ -59,6 +43,16 @@ include(chip) add_subdirectory(${OPEN_IOT_SDK_EXAMPLE_COMMON}/app ./app_build) +target_compile_definitions(openiotsdk-startup + PRIVATE + IOT_SDK_APP_SERIAL_BAUDRATE=9600 +) + +target_compile_definitions(openiotsdk-startup + PRIVATE + IOT_SDK_APP_MAIN_STACK_SIZE=8192 +) + target_include_directories(${APP_TARGET} PRIVATE main/include @@ -73,6 +67,7 @@ target_sources(${APP_TARGET} ) target_link_libraries(${APP_TARGET} + openiotsdk-startup openiotsdk-app ) diff --git a/examples/shell/openiotsdk/main/include/CHIPProjectConfig.h b/examples/shell/openiotsdk/main/include/CHIPProjectConfig.h index 7089ae47a8038f..1d5b781c19e7ef 100644 --- a/examples/shell/openiotsdk/main/include/CHIPProjectConfig.h +++ b/examples/shell/openiotsdk/main/include/CHIPProjectConfig.h @@ -28,3 +28,5 @@ #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 #define CHIP_DISPATCH_EVENT_LONG_DISPATCH_TIME_WARNING_THRESHOLD_MS 500 + +#define CHIP_SHELL_PROMPT "Enter command:\r\n" diff --git a/examples/shell/openiotsdk/main/main_ns.cpp b/examples/shell/openiotsdk/main/main_ns.cpp index c832b2df4e49cf..056ab2c66f62ff 100644 --- a/examples/shell/openiotsdk/main/main_ns.cpp +++ b/examples/shell/openiotsdk/main/main_ns.cpp @@ -29,41 +29,19 @@ using namespace ::chip; using namespace ::chip::Shell; -static void app_thread(void * argument) +int main() { - int ret; - - if (openiotsdk_network_init(true)) - { - ChipLogError(Shell, "Network initialization failed"); - goto exit; - } - - // Initialize the default streamer that was linked. - ret = Engine::Root().Init(); - if (ret) + if (openiotsdk_platform_init()) { - ChipLogError(Shell, "Streamer initialization failed [%d]", ret); - goto exit; + ChipLogError(Shell, "Open IoT SDK platform initialization failed"); + return EXIT_FAILURE; } - cmd_misc_init(); - - ChipLogProgress(Shell, "Open IoT SDK shell example application run"); - - Engine::Root().RunMainLoop(); - -exit: - osThreadTerminate(osThreadGetId()); -} - -int main() -{ ChipLogProgress(Shell, "Open IoT SDK shell example application start"); - if (openiotsdk_platform_init()) + if (openiotsdk_network_init(true)) { - ChipLogError(Shell, "Open IoT SDK platform initialization failed"); + ChipLogError(Shell, "Network initialization failed"); return EXIT_FAILURE; } @@ -73,22 +51,19 @@ int main() return EXIT_FAILURE; } - static const osThreadAttr_t thread_attr = { - .stack_size = 8 * 1024 // Allocate enough stack for app thread - }; - - osThreadId_t appThread = osThreadNew(app_thread, NULL, &thread_attr); - if (appThread == NULL) + // Initialize the default streamer that was linked. + int ret = Engine::Root().Init(); + if (ret) { - ChipLogError(Shell, "Failed to create app thread"); + ChipLogError(Shell, "Streamer initialization failed [%d]", ret); return EXIT_FAILURE; } - if (openiotsdk_platform_run()) - { - ChipLogError(Shell, "Open IoT SDK platform run failed"); - return EXIT_FAILURE; - } + cmd_misc_init(); + + ChipLogProgress(Shell, "Open IoT SDK shell example application run"); + + Engine::Root().RunMainLoop(); return EXIT_SUCCESS; } diff --git a/examples/thermostat/silabs/efr32/include/AppConfig.h b/examples/thermostat/silabs/efr32/include/AppConfig.h index a1561de487da01..edba77c5fc078c 100644 --- a/examples/thermostat/silabs/efr32/include/AppConfig.h +++ b/examples/thermostat/silabs/efr32/include/AppConfig.h @@ -19,6 +19,8 @@ #pragma once +#include "silabs_utils.h" + // ---- Lighting Example App Config ---- #define APP_TASK_NAME "Lit" @@ -58,21 +60,3 @@ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF #define OFF_DEMO_BITMAP ON_DEMO_BITMAP - -// EFR Logging -#ifdef __cplusplus -extern "C" { -#endif - -void silabsInitLog(void); - -void efr32Log(const char * aFormat, ...); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); -void appError(int err); - -#ifdef __cplusplus -} - -#include -void appError(CHIP_ERROR error); -#endif diff --git a/examples/thermostat/silabs/efr32/src/AppTask.cpp b/examples/thermostat/silabs/efr32/src/AppTask.cpp index ef7204cbfd4b82..2e506d1658223c 100644 --- a/examples/thermostat/silabs/efr32/src/AppTask.cpp +++ b/examples/thermostat/silabs/efr32/src/AppTask.cpp @@ -142,9 +142,7 @@ AppTask AppTask::sAppTask; CHIP_ERROR AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT chip::DeviceLayer::Silabs::GetPlatform().SetButtonsCb(AppTask::ButtonEventHandler); -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT #ifdef DISPLAY_ENABLED GetLCD().Init((uint8_t *) "Thermostat-App"); @@ -246,7 +244,6 @@ void AppTask::UpdateThermoStatUI() #endif // DISPLAY_ENABLED } -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) { AppEvent aEvent = {}; @@ -259,4 +256,3 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) sAppTask.PostEvent(&aEvent); } } -#endif // SL_CATALOG_SIMPLE_BUTTON_PRESENT diff --git a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/handlers/ContentAppEndpointManagerImpl.java b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/handlers/ContentAppEndpointManagerImpl.java index 6f4e6eb98c52e2..f93897f2d2a582 100644 --- a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/handlers/ContentAppEndpointManagerImpl.java +++ b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/handlers/ContentAppEndpointManagerImpl.java @@ -18,7 +18,7 @@ public ContentAppEndpointManagerImpl(Context context) { this.context = context; } - public String sendCommand(int endpointId, int clusterId, int commandId, String commandPayload) { + public String sendCommand(int endpointId, long clusterId, long commandId, String commandPayload) { Log.d(TAG, "Received a command for endpointId " + endpointId + ". Message " + commandPayload); ContentApp discoveredApp = @@ -54,7 +54,7 @@ public String sendCommand(int endpointId, int clusterId, int commandId, String c return "Success"; } - public String readAttribute(int endpointId, int clusterId, int attributeId) { + public String readAttribute(int endpointId, long clusterId, long attributeId) { Log.d( TAG, "Received a attribute read request for endpointId " diff --git a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/ContentAppAgentService.java b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/ContentAppAgentService.java index cc311b9481e194..542e8e4f93f33c 100644 --- a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/ContentAppAgentService.java +++ b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/ContentAppAgentService.java @@ -107,12 +107,12 @@ public IBinder onBind(final Intent intent) { } public static String sendCommand( - Context context, String packageName, int clusterId, int commandId, String payload) { + Context context, String packageName, long clusterId, long commandId, String payload) { Intent in = new Intent(MatterIntentConstants.ACTION_MATTER_COMMAND); Bundle extras = new Bundle(); extras.putByteArray(MatterIntentConstants.EXTRA_COMMAND_PAYLOAD, payload.getBytes()); - extras.putInt(MatterIntentConstants.EXTRA_COMMAND_ID, commandId); - extras.putInt(MatterIntentConstants.EXTRA_CLUSTER_ID, clusterId); + extras.putLong(MatterIntentConstants.EXTRA_COMMAND_ID, commandId); + extras.putLong(MatterIntentConstants.EXTRA_CLUSTER_ID, clusterId); in.putExtras(extras); in.setPackage(packageName); int flags = Intent.FLAG_INCLUDE_STOPPED_PACKAGES; @@ -127,13 +127,13 @@ public static String sendCommand( } public static String sendAttributeReadRequest( - Context context, String packageName, int clusterId, int attributeId) { + Context context, String packageName, long clusterId, long attributeId) { Intent in = new Intent(MatterIntentConstants.ACTION_MATTER_COMMAND); Bundle extras = new Bundle(); extras.putString( MatterIntentConstants.EXTRA_ATTRIBUTE_ACTION, MatterIntentConstants.ATTRIBUTE_ACTION_READ); - extras.putInt(MatterIntentConstants.EXTRA_ATTRIBUTE_ID, attributeId); - extras.putInt(MatterIntentConstants.EXTRA_CLUSTER_ID, clusterId); + extras.putLong(MatterIntentConstants.EXTRA_ATTRIBUTE_ID, attributeId); + extras.putLong(MatterIntentConstants.EXTRA_CLUSTER_ID, clusterId); in.putExtras(extras); in.setPackage(packageName); int flags = Intent.FLAG_INCLUDE_STOPPED_PACKAGES; diff --git a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/MatterServant.java b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/MatterServant.java index 00963fa1f7e2ae..79b02f01386769 100644 --- a/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/MatterServant.java +++ b/examples/tv-app/android/App/platform-app/src/main/java/com/matter/tv/server/service/MatterServant.java @@ -82,36 +82,26 @@ public void init(@NonNull Context context) { mTvApp = new TvApp( (app, clusterId, endpoint) -> { - switch (clusterId) { - case Clusters.ClusterId_KeypadInput: - app.setKeypadInputManager(endpoint, new KeypadInputManagerStub(endpoint)); - break; - case Clusters.ClusterId_WakeOnLan: - app.setWakeOnLanManager(endpoint, new WakeOnLanManagerStub(endpoint)); - break; - case Clusters.ClusterId_MediaInput: - app.setMediaInputManager(endpoint, new MediaInputManagerStub(endpoint)); - break; - case Clusters.ClusterId_ContentLauncher: - app.setContentLaunchManager(endpoint, new ContentLaunchManagerStub(endpoint)); - break; - case Clusters.ClusterId_LowPower: - app.setLowPowerManager(endpoint, new LowPowerManagerStub(endpoint)); - break; - case Clusters.ClusterId_MediaPlayback: - app.setMediaPlaybackManager(endpoint, new MediaPlaybackManagerStub(endpoint)); - break; - case Clusters.ClusterId_Channel: - app.setChannelManager(endpoint, new ChannelManagerStub(endpoint)); - break; - case Clusters.ClusterId_OnOff: - mOnOffEndpoint = endpoint; - app.setOnOffManager(endpoint, new OnOffManagerStub(endpoint)); - break; - case Clusters.ClusterId_LevelControl: - mLevelEndpoint = endpoint; - app.setLevelManager(endpoint, new LevelManagerStub(endpoint)); - break; + if (clusterId == Clusters.ClusterId_KeypadInput) { + app.setKeypadInputManager(endpoint, new KeypadInputManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_WakeOnLan) { + app.setWakeOnLanManager(endpoint, new WakeOnLanManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_MediaInput) { + app.setMediaInputManager(endpoint, new MediaInputManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_ContentLauncher) { + app.setContentLaunchManager(endpoint, new ContentLaunchManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_LowPower) { + app.setLowPowerManager(endpoint, new LowPowerManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_MediaPlayback) { + app.setMediaPlaybackManager(endpoint, new MediaPlaybackManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_Channel) { + app.setChannelManager(endpoint, new ChannelManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_OnOff) { + mOnOffEndpoint = endpoint; + app.setOnOffManager(endpoint, new OnOffManagerStub(endpoint)); + } else if (clusterId == Clusters.ClusterId_LevelControl) { + mLevelEndpoint = endpoint; + app.setLevelManager(endpoint, new LevelManagerStub(endpoint)); } }); mTvApp.setDACProvider(new DACProviderStub()); diff --git a/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp b/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp index 0565d364e2719f..54e4ee633ce7d9 100644 --- a/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp +++ b/examples/tv-app/android/java/ContentAppAttributeDelegate.cpp @@ -49,7 +49,7 @@ std::string ContentAppAttributeDelegate::Read(const chip::app::ConcreteReadAttri jstring resp = (jstring) env->CallObjectMethod(mContentAppEndpointManager, mReadAttributeMethod, static_cast(aPath.mEndpointId), - static_cast(aPath.mClusterId), static_cast(aPath.mAttributeId)); + static_cast(aPath.mClusterId), static_cast(aPath.mAttributeId)); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in ContentAppAttributeDelegate::Read"); diff --git a/examples/tv-app/android/java/ContentAppAttributeDelegate.h b/examples/tv-app/android/java/ContentAppAttributeDelegate.h index 4ec02712201d7b..9d22bbc5fff7aa 100644 --- a/examples/tv-app/android/java/ContentAppAttributeDelegate.h +++ b/examples/tv-app/android/java/ContentAppAttributeDelegate.h @@ -67,7 +67,7 @@ class ContentAppAttributeDelegate VerifyOrReturn(ContentAppEndpointManagerClass != nullptr, ChipLogError(Zcl, "Failed to get ContentAppEndpointManager Java class")); - mReadAttributeMethod = env->GetMethodID(ContentAppEndpointManagerClass, "readAttribute", "(III)Ljava/lang/String;"); + mReadAttributeMethod = env->GetMethodID(ContentAppEndpointManagerClass, "readAttribute", "(IJJ)Ljava/lang/String;"); if (mReadAttributeMethod == nullptr) { ChipLogError(Zcl, "Failed to access ContentAppEndpointManager 'readAttribute' method"); diff --git a/examples/tv-app/android/java/ContentAppCommandDelegate.cpp b/examples/tv-app/android/java/ContentAppCommandDelegate.cpp index b477b75333866b..1ad6ef2fa40311 100644 --- a/examples/tv-app/android/java/ContentAppCommandDelegate.cpp +++ b/examples/tv-app/android/java/ContentAppCommandDelegate.cpp @@ -73,7 +73,7 @@ void ContentAppCommandDelegate::InvokeCommand(CommandHandlerInterface::HandlerCo jstring resp = (jstring) env->CallObjectMethod( mContentAppEndpointManager, mSendCommandMethod, static_cast(handlerContext.mRequestPath.mEndpointId), - static_cast(handlerContext.mRequestPath.mClusterId), static_cast(handlerContext.mRequestPath.mCommandId), + static_cast(handlerContext.mRequestPath.mClusterId), static_cast(handlerContext.mRequestPath.mCommandId), jsonString.jniValue()); if (env->ExceptionCheck()) { @@ -108,7 +108,7 @@ Status ContentAppCommandDelegate::InvokeCommand(EndpointId epId, ClusterId clust jstring resp = (jstring) env->CallObjectMethod(mContentAppEndpointManager, mSendCommandMethod, static_cast(epId), - static_cast(clusterId), static_cast(commandId), jsonString.jniValue()); + static_cast(clusterId), static_cast(commandId), jsonString.jniValue()); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Java exception in ContentAppCommandDelegate::sendCommand"); diff --git a/examples/tv-app/android/java/ContentAppCommandDelegate.h b/examples/tv-app/android/java/ContentAppCommandDelegate.h index 610a2c7069f29d..156fa287f2ef9a 100644 --- a/examples/tv-app/android/java/ContentAppCommandDelegate.h +++ b/examples/tv-app/android/java/ContentAppCommandDelegate.h @@ -96,7 +96,7 @@ class ContentAppCommandDelegate : public CommandHandlerInterface ChipLogError(Zcl, "Failed to get ContentAppEndpointManager Java class")); mSendCommandMethod = - env->GetMethodID(ContentAppEndpointManagerClass, "sendCommand", "(IIILjava/lang/String;)Ljava/lang/String;"); + env->GetMethodID(ContentAppEndpointManagerClass, "sendCommand", "(IJJLjava/lang/String;)Ljava/lang/String;"); if (mSendCommandMethod == nullptr) { ChipLogError(Zcl, "Failed to access ContentAppEndpointManager 'sendCommand' method"); diff --git a/examples/tv-app/android/java/TVApp-JNI.cpp b/examples/tv-app/android/java/TVApp-JNI.cpp index a8eeba37344923..d7081419c0c645 100644 --- a/examples/tv-app/android/java/TVApp-JNI.cpp +++ b/examples/tv-app/android/java/TVApp-JNI.cpp @@ -64,7 +64,7 @@ void TvAppJNI::InitializeWithObjects(jobject app) jclass managerClass = env->GetObjectClass(mTvAppObject); VerifyOrReturn(managerClass != nullptr, ChipLogError(Zcl, "Failed to get TvAppJNI Java class")); - mPostClusterInitMethod = env->GetMethodID(managerClass, "postClusterInit", "(II)V"); + mPostClusterInitMethod = env->GetMethodID(managerClass, "postClusterInit", "(JI)V"); if (mPostClusterInitMethod == nullptr) { ChipLogError(Zcl, "Failed to access ChannelManager 'postClusterInit' method"); @@ -79,7 +79,7 @@ void TvAppJNI::PostClusterInit(int clusterId, int endpoint) VerifyOrReturn(mTvAppObject != nullptr, ChipLogError(Zcl, "TvAppJNI::mTvAppObject null")); VerifyOrReturn(mPostClusterInitMethod != nullptr, ChipLogError(Zcl, "TvAppJNI::mPostClusterInitMethod null")); - env->CallVoidMethod(mTvAppObject, mPostClusterInitMethod, static_cast(clusterId), static_cast(endpoint)); + env->CallVoidMethod(mTvAppObject, mPostClusterInitMethod, static_cast(clusterId), static_cast(endpoint)); if (env->ExceptionCheck()) { ChipLogError(Zcl, "Failed to call TvAppJNI 'postClusterInit' method"); diff --git a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/Clusters.java b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/Clusters.java index 7d7761a7b2050b..5322af22c97ae5 100644 --- a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/Clusters.java +++ b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/Clusters.java @@ -18,121 +18,121 @@ public class Clusters { - public static final int ClusterId_PowerConfiguration = 0x00000001; - public static final int ClusterId_DeviceTemperatureConfiguration = 0x00000002; - public static final int ClusterId_Identify = 0x00000003; - public static final int ClusterId_Groups = 0x00000004; - public static final int ClusterId_Scenes = 0x00000005; - public static final int ClusterId_OnOff = 0x00000006; - public static final int ClusterId_OnOffSwitchConfiguration = 0x00000007; - public static final int ClusterId_LevelControl = 0x00000008; - public static final int ClusterId_Alarms = 0x00000009; - public static final int ClusterId_Time = 0x0000000A; - public static final int ClusterId_BinaryInputBasic = 0x0000000F; - public static final int ClusterId_PowerProfile = 0x0000001A; - public static final int ClusterId_ApplianceControl = 0x0000001B; - public static final int ClusterId_PulseWidthModulation = 0x0000001C; - public static final int ClusterId_Descriptor = 0x0000001D; - public static final int ClusterId_Binding = 0x0000001E; - public static final int ClusterId_AccessControl = 0x0000001F; - public static final int ClusterId_PollControl = 0x00000020; - public static final int ClusterId_Actions = 0x00000025; - public static final int ClusterId_Basic = 0x00000028; - public static final int ClusterId_OtaSoftwareUpdateProvider = 0x00000029; - public static final int ClusterId_OtaSoftwareUpdateRequestor = 0x0000002A; - public static final int ClusterId_LocalizationConfiguration = 0x0000002B; - public static final int ClusterId_LocalizationTimeFormat = 0x0000002C; - public static final int ClusterId_LocalizationUnit = 0x0000002D; - public static final int ClusterId_PowerSourceConfiguration = 0x0000002E; - public static final int ClusterId_PowerSource = 0x0000002F; - public static final int ClusterId_GeneralCommissioning = 0x00000030; - public static final int ClusterId_NetworkCommissioning = 0x00000031; - public static final int ClusterId_DiagnosticLogs = 0x00000032; - public static final int ClusterId_GeneralDiagnostics = 0x00000033; - public static final int ClusterId_SoftwareDiagnostics = 0x00000034; - public static final int ClusterId_ThreadNetworkDiagnostics = 0x00000035; - public static final int ClusterId_WiFiNetworkDiagnostics = 0x00000036; - public static final int ClusterId_EthernetNetworkDiagnostics = 0x00000037; - public static final int ClusterId_TimeSynchronization = 0x00000038; - public static final int ClusterId_BridgedDeviceBasic = 0x00000039; - public static final int ClusterId_Switch = 0x0000003B; - public static final int ClusterId_AdministratorCommissioning = 0x0000003C; - public static final int ClusterId_OperationalCredentials = 0x0000003E; - public static final int ClusterId_GroupKeyManagement = 0x0000003F; - public static final int ClusterId_FixedLabel = 0x00000040; - public static final int ClusterId_UserLabel = 0x00000041; - public static final int ClusterId_ProxyConfiguration = 0x00000042; - public static final int ClusterId_ProxyDiscovery = 0x00000043; - public static final int ClusterId_ProxyValid = 0x00000044; - public static final int ClusterId_BooleanState = 0x00000045; - public static final int ClusterId_ModeSelect = 0x00000050; - public static final int ClusterId_ShadeConfiguration = 0x00000100; - public static final int ClusterId_DoorLock = 0x00000101; - public static final int ClusterId_WindowCovering = 0x00000102; - public static final int ClusterId_BarrierControl = 0x00000103; - public static final int ClusterId_PumpConfigurationAndControl = 0x00000200; - public static final int ClusterId_Thermostat = 0x00000201; - public static final int ClusterId_FanControl = 0x00000202; - public static final int ClusterId_DehumidificationControl = 0x00000203; - public static final int ClusterId_ThermostatUserInterfaceConfiguration = 0x00000204; - public static final int ClusterId_ColorControl = 0x00000300; - public static final int ClusterId_BallastConfiguration = 0x00000301; - public static final int ClusterId_IlluminanceMeasurement = 0x00000400; - public static final int ClusterId_TemperatureMeasurement = 0x00000402; - public static final int ClusterId_PressureMeasurement = 0x00000403; - public static final int ClusterId_FlowMeasurement = 0x00000404; - public static final int ClusterId_RelativeHumidityMeasurement = 0x00000405; - public static final int ClusterId_OccupancySensing = 0x00000406; - public static final int ClusterId_CarbonMonoxideConcentrationMeasurement = 0x0000040C; - public static final int ClusterId_CarbonDioxideConcentrationMeasurement = 0x0000040D; - public static final int ClusterId_EthyleneConcentrationMeasurement = 0x0000040E; - public static final int ClusterId_EthyleneOxideConcentrationMeasurement = 0x0000040F; - public static final int ClusterId_HydrogenConcentrationMeasurement = 0x00000410; - public static final int ClusterId_HydrogenSulphideConcentrationMeasurement = 0x00000411; - public static final int ClusterId_NitricOxideConcentrationMeasurement = 0x00000412; - public static final int ClusterId_NitrogenDioxideConcentrationMeasurement = 0x00000413; - public static final int ClusterId_OxygenConcentrationMeasurement = 0x00000414; - public static final int ClusterId_OzoneConcentrationMeasurement = 0x00000415; - public static final int ClusterId_SulfurDioxideConcentrationMeasurement = 0x00000416; - public static final int ClusterId_DissolvedOxygenConcentrationMeasurement = 0x00000417; - public static final int ClusterId_BromateConcentrationMeasurement = 0x00000418; - public static final int ClusterId_ChloraminesConcentrationMeasurement = 0x00000419; - public static final int ClusterId_ChlorineConcentrationMeasurement = 0x0000041A; - public static final int ClusterId_FecalColiformAndEColiConcentrationMeasurement = 0x0000041B; - public static final int ClusterId_FluorideConcentrationMeasurement = 0x0000041C; - public static final int ClusterId_HaloaceticAcidsConcentrationMeasurement = 0x0000041D; - public static final int ClusterId_TotalTrihalomethanesConcentrationMeasurement = 0x0000041E; - public static final int ClusterId_TotalColiformBacteriaConcentrationMeasurement = 0x0000041F; - public static final int ClusterId_TurbidityConcentrationMeasurement = 0x00000420; - public static final int ClusterId_CopperConcentrationMeasurement = 0x00000421; - public static final int ClusterId_LeadConcentrationMeasurement = 0x00000422; - public static final int ClusterId_ManganeseConcentrationMeasurement = 0x00000423; - public static final int ClusterId_SulfateConcentrationMeasurement = 0x00000424; - public static final int ClusterId_BromodichloromethaneConcentrationMeasurement = 0x00000425; - public static final int ClusterId_BromoformConcentrationMeasurement = 0x00000426; - public static final int ClusterId_ChlorodibromomethaneConcentrationMeasurement = 0x00000427; - public static final int ClusterId_ChloroformConcentrationMeasurement = 0x00000428; - public static final int ClusterId_SodiumConcentrationMeasurement = 0x00000429; - public static final int ClusterId_IasZone = 0x00000500; - public static final int ClusterId_IasAce = 0x00000501; - public static final int ClusterId_IasWd = 0x00000502; - public static final int ClusterId_WakeOnLan = 0x00000503; - public static final int ClusterId_Channel = 0x00000504; - public static final int ClusterId_TargetNavigator = 0x00000505; - public static final int ClusterId_MediaPlayback = 0x00000506; - public static final int ClusterId_MediaInput = 0x00000507; - public static final int ClusterId_LowPower = 0x00000508; - public static final int ClusterId_KeypadInput = 0x00000509; - public static final int ClusterId_ContentLauncher = 0x0000050A; - public static final int ClusterId_AudioOutput = 0x0000050B; - public static final int ClusterId_ApplicationLauncher = 0x0000050C; - public static final int ClusterId_ApplicationBasic = 0x0000050D; - public static final int ClusterId_AccountLogin = 0x0000050E; - public static final int ClusterId_TestCluster = 0xFFF1FC05; - public static final int ClusterId_Messaging = 0x00000703; - public static final int ClusterId_ApplianceIdentification = 0x00000B00; - public static final int ClusterId_MeterIdentification = 0x00000B01; - public static final int ClusterId_ApplianceEventsAndAlert = 0x00000B02; - public static final int ClusterId_ApplianceStatistics = 0x00000B03; - public static final int ClusterId_ElectricalMeasurement = 0x00000B04; + public static final long ClusterId_PowerConfiguration = 0x00000001; + public static final long ClusterId_DeviceTemperatureConfiguration = 0x00000002; + public static final long ClusterId_Identify = 0x00000003; + public static final long ClusterId_Groups = 0x00000004; + public static final long ClusterId_Scenes = 0x00000005; + public static final long ClusterId_OnOff = 0x00000006; + public static final long ClusterId_OnOffSwitchConfiguration = 0x00000007; + public static final long ClusterId_LevelControl = 0x00000008; + public static final long ClusterId_Alarms = 0x00000009; + public static final long ClusterId_Time = 0x0000000A; + public static final long ClusterId_BinaryInputBasic = 0x0000000F; + public static final long ClusterId_PowerProfile = 0x0000001A; + public static final long ClusterId_ApplianceControl = 0x0000001B; + public static final long ClusterId_PulseWidthModulation = 0x0000001C; + public static final long ClusterId_Descriptor = 0x0000001D; + public static final long ClusterId_Binding = 0x0000001E; + public static final long ClusterId_AccessControl = 0x0000001F; + public static final long ClusterId_PollControl = 0x00000020; + public static final long ClusterId_Actions = 0x00000025; + public static final long ClusterId_Basic = 0x00000028; + public static final long ClusterId_OtaSoftwareUpdateProvider = 0x00000029; + public static final long ClusterId_OtaSoftwareUpdateRequestor = 0x0000002A; + public static final long ClusterId_LocalizationConfiguration = 0x0000002B; + public static final long ClusterId_LocalizationTimeFormat = 0x0000002C; + public static final long ClusterId_LocalizationUnit = 0x0000002D; + public static final long ClusterId_PowerSourceConfiguration = 0x0000002E; + public static final long ClusterId_PowerSource = 0x0000002F; + public static final long ClusterId_GeneralCommissioning = 0x00000030; + public static final long ClusterId_NetworkCommissioning = 0x00000031; + public static final long ClusterId_DiagnosticLogs = 0x00000032; + public static final long ClusterId_GeneralDiagnostics = 0x00000033; + public static final long ClusterId_SoftwareDiagnostics = 0x00000034; + public static final long ClusterId_ThreadNetworkDiagnostics = 0x00000035; + public static final long ClusterId_WiFiNetworkDiagnostics = 0x00000036; + public static final long ClusterId_EthernetNetworkDiagnostics = 0x00000037; + public static final long ClusterId_TimeSynchronization = 0x00000038; + public static final long ClusterId_BridgedDeviceBasic = 0x00000039; + public static final long ClusterId_Switch = 0x0000003B; + public static final long ClusterId_AdministratorCommissioning = 0x0000003C; + public static final long ClusterId_OperationalCredentials = 0x0000003E; + public static final long ClusterId_GroupKeyManagement = 0x0000003F; + public static final long ClusterId_FixedLabel = 0x00000040; + public static final long ClusterId_UserLabel = 0x00000041; + public static final long ClusterId_ProxyConfiguration = 0x00000042; + public static final long ClusterId_ProxyDiscovery = 0x00000043; + public static final long ClusterId_ProxyValid = 0x00000044; + public static final long ClusterId_BooleanState = 0x00000045; + public static final long ClusterId_ModeSelect = 0x00000050; + public static final long ClusterId_ShadeConfiguration = 0x00000100; + public static final long ClusterId_DoorLock = 0x00000101; + public static final long ClusterId_WindowCovering = 0x00000102; + public static final long ClusterId_BarrierControl = 0x00000103; + public static final long ClusterId_PumpConfigurationAndControl = 0x00000200; + public static final long ClusterId_Thermostat = 0x00000201; + public static final long ClusterId_FanControl = 0x00000202; + public static final long ClusterId_DehumidificationControl = 0x00000203; + public static final long ClusterId_ThermostatUserInterfaceConfiguration = 0x00000204; + public static final long ClusterId_ColorControl = 0x00000300; + public static final long ClusterId_BallastConfiguration = 0x00000301; + public static final long ClusterId_IlluminanceMeasurement = 0x00000400; + public static final long ClusterId_TemperatureMeasurement = 0x00000402; + public static final long ClusterId_PressureMeasurement = 0x00000403; + public static final long ClusterId_FlowMeasurement = 0x00000404; + public static final long ClusterId_RelativeHumidityMeasurement = 0x00000405; + public static final long ClusterId_OccupancySensing = 0x00000406; + public static final long ClusterId_CarbonMonoxideConcentrationMeasurement = 0x0000040C; + public static final long ClusterId_CarbonDioxideConcentrationMeasurement = 0x0000040D; + public static final long ClusterId_EthyleneConcentrationMeasurement = 0x0000040E; + public static final long ClusterId_EthyleneOxideConcentrationMeasurement = 0x0000040F; + public static final long ClusterId_HydrogenConcentrationMeasurement = 0x00000410; + public static final long ClusterId_HydrogenSulphideConcentrationMeasurement = 0x00000411; + public static final long ClusterId_NitricOxideConcentrationMeasurement = 0x00000412; + public static final long ClusterId_NitrogenDioxideConcentrationMeasurement = 0x00000413; + public static final long ClusterId_OxygenConcentrationMeasurement = 0x00000414; + public static final long ClusterId_OzoneConcentrationMeasurement = 0x00000415; + public static final long ClusterId_SulfurDioxideConcentrationMeasurement = 0x00000416; + public static final long ClusterId_DissolvedOxygenConcentrationMeasurement = 0x00000417; + public static final long ClusterId_BromateConcentrationMeasurement = 0x00000418; + public static final long ClusterId_ChloraminesConcentrationMeasurement = 0x00000419; + public static final long ClusterId_ChlorineConcentrationMeasurement = 0x0000041A; + public static final long ClusterId_FecalColiformAndEColiConcentrationMeasurement = 0x0000041B; + public static final long ClusterId_FluorideConcentrationMeasurement = 0x0000041C; + public static final long ClusterId_HaloaceticAcidsConcentrationMeasurement = 0x0000041D; + public static final long ClusterId_TotalTrihalomethanesConcentrationMeasurement = 0x0000041E; + public static final long ClusterId_TotalColiformBacteriaConcentrationMeasurement = 0x0000041F; + public static final long ClusterId_TurbidityConcentrationMeasurement = 0x00000420; + public static final long ClusterId_CopperConcentrationMeasurement = 0x00000421; + public static final long ClusterId_LeadConcentrationMeasurement = 0x00000422; + public static final long ClusterId_ManganeseConcentrationMeasurement = 0x00000423; + public static final long ClusterId_SulfateConcentrationMeasurement = 0x00000424; + public static final long ClusterId_BromodichloromethaneConcentrationMeasurement = 0x00000425; + public static final long ClusterId_BromoformConcentrationMeasurement = 0x00000426; + public static final long ClusterId_ChlorodibromomethaneConcentrationMeasurement = 0x00000427; + public static final long ClusterId_ChloroformConcentrationMeasurement = 0x00000428; + public static final long ClusterId_SodiumConcentrationMeasurement = 0x00000429; + public static final long ClusterId_IasZone = 0x00000500; + public static final long ClusterId_IasAce = 0x00000501; + public static final long ClusterId_IasWd = 0x00000502; + public static final long ClusterId_WakeOnLan = 0x00000503; + public static final long ClusterId_Channel = 0x00000504; + public static final long ClusterId_TargetNavigator = 0x00000505; + public static final long ClusterId_MediaPlayback = 0x00000506; + public static final long ClusterId_MediaInput = 0x00000507; + public static final long ClusterId_LowPower = 0x00000508; + public static final long ClusterId_KeypadInput = 0x00000509; + public static final long ClusterId_ContentLauncher = 0x0000050A; + public static final long ClusterId_AudioOutput = 0x0000050B; + public static final long ClusterId_ApplicationLauncher = 0x0000050C; + public static final long ClusterId_ApplicationBasic = 0x0000050D; + public static final long ClusterId_AccountLogin = 0x0000050E; + public static final long ClusterId_TestCluster = 0xFFF1FC05; + public static final long ClusterId_Messaging = 0x00000703; + public static final long ClusterId_ApplianceIdentification = 0x00000B00; + public static final long ClusterId_MeterIdentification = 0x00000B01; + public static final long ClusterId_ApplianceEventsAndAlert = 0x00000B02; + public static final long ClusterId_ApplianceStatistics = 0x00000B03; + public static final long ClusterId_ElectricalMeasurement = 0x00000B04; } diff --git a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/ContentAppEndpointManager.java b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/ContentAppEndpointManager.java index 92c5e5243b85ad..ed6253fd446ed9 100644 --- a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/ContentAppEndpointManager.java +++ b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/ContentAppEndpointManager.java @@ -2,7 +2,7 @@ public interface ContentAppEndpointManager { - public String sendCommand(int endpointId, int clusterId, int commandId, String commandPayload); + public String sendCommand(int endpointId, long clusterId, long commandId, String commandPayload); - public String readAttribute(int endpointId, int clusterId, int attributeId); + public String readAttribute(int endpointId, long clusterId, long attributeId); } diff --git a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvApp.java b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvApp.java index 92c41fdebc7e6f..d8bb564370afa4 100644 --- a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvApp.java +++ b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvApp.java @@ -28,7 +28,7 @@ public TvApp(TvAppCallback callback) { nativeInit(); } - private void postClusterInit(int clusterId, int endpoint) { + private void postClusterInit(long clusterId, int endpoint) { Log.d(TAG, "postClusterInit for " + clusterId + " at " + endpoint); if (mCallback != null) { mCallback.onClusterInit(this, clusterId, endpoint); diff --git a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvAppCallback.java b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvAppCallback.java index 27d2c7e1aa1e2b..d5bf7a090bc0de 100644 --- a/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvAppCallback.java +++ b/examples/tv-app/android/java/src/com/matter/tv/server/tvapp/TvAppCallback.java @@ -17,5 +17,5 @@ package com.matter.tv.server.tvapp; public interface TvAppCallback { - void onClusterInit(TvApp app, int clusterId, int endpoint); + void onClusterInit(TvApp app, long clusterId, int endpoint); } diff --git a/examples/tv-app/linux/AppImpl.cpp b/examples/tv-app/linux/AppImpl.cpp index 9ecb9bcb39d0c4..a07eeadaeb029a 100644 --- a/examples/tv-app/linux/AppImpl.cpp +++ b/examples/tv-app/linux/AppImpl.cpp @@ -32,9 +32,6 @@ #include #include #include -#include -#include -#include #include #include #include diff --git a/examples/tv-app/linux/BUILD.gn b/examples/tv-app/linux/BUILD.gn index 35f4af6c4542d7..c77a4feb75407d 100644 --- a/examples/tv-app/linux/BUILD.gn +++ b/examples/tv-app/linux/BUILD.gn @@ -14,28 +14,16 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("args.gni") - import("${chip_root}/build/chip/tools.gni") +import("${chip_root}/src/lib/lib.gni") assert(chip_build_tools) -config("config") { - include_dirs = [ - ".", - "${chip_root}/zzz_generated/chip-tv-app", - "${chip_root}/src/lib", - ] - - cflags = [ "-Wconversion" ] -} - executable("chip-tv-app") { sources = [ "${chip_root}/examples/tv-app/tv-common/include/CHIPProjectAppConfig.h", "AppImpl.cpp", "AppImpl.h", - "AppPlatformShellCommands.cpp", "ZclCallbacks.cpp", "include/account-login/AccountLoginManager.cpp", "include/account-login/AccountLoginManager.h", @@ -74,11 +62,16 @@ executable("chip-tv-app") { ] cflags = [ "-Wconversion" ] - - public_configs = [ ":config" ] + defines = [] + include_dirs = [ + ".", + "${chip_root}/zzz_generated/chip-tv-app", + "${chip_root}/src/lib", + ] if (chip_build_libshell) { - cflags += [ "-DENABLE_CHIP_SHELL" ] + defines += [ "ENABLE_CHIP_SHELL" ] + sources += [ "AppPlatformShellCommands.cpp" ] } output_dir = root_out_dir diff --git a/examples/tv-app/linux/main.cpp b/examples/tv-app/linux/main.cpp index 31d15a41a8421e..2609d9a2f3c6f4 100644 --- a/examples/tv-app/linux/main.cpp +++ b/examples/tv-app/linux/main.cpp @@ -41,7 +41,7 @@ #include "include/wake-on-lan/WakeOnLanManager.h" #if defined(ENABLE_CHIP_SHELL) -#include +#include // nogncheck #endif using namespace chip; diff --git a/examples/tv-casting-app/linux/BUILD.gn b/examples/tv-casting-app/linux/BUILD.gn index 0f6f12c50dd022..52d8f77cca6f65 100644 --- a/examples/tv-casting-app/linux/BUILD.gn +++ b/examples/tv-casting-app/linux/BUILD.gn @@ -14,17 +14,14 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("args.gni") - import("${chip_root}/build/chip/tools.gni") +import("${chip_root}/src/lib/lib.gni") assert(chip_build_tools) executable("chip-tv-casting-app") { sources = [ "${chip_root}/examples/tv-casting-app/tv-casting-common/include/CHIPProjectAppConfig.h", - "CastingShellCommands.cpp", - "CastingShellCommands.h", "CastingUtils.cpp", "CastingUtils.h", "main.cpp", @@ -39,13 +36,18 @@ executable("chip-tv-casting-app") { "${chip_root}/third_party/jsoncpp", ] + defines = [] include_dirs = [ "${chip_root}/examples/tv-casting-app/tv-casting-common/include" ] cflags = [ "-Wconversion" ] if (chip_build_libshell) { - cflags += [ "-DENABLE_CHIP_SHELL" ] + defines += [ "ENABLE_CHIP_SHELL" ] + sources += [ + "CastingShellCommands.cpp", + "CastingShellCommands.h", + ] } output_dir = root_out_dir diff --git a/examples/tv-casting-app/linux/main.cpp b/examples/tv-casting-app/linux/main.cpp index 6fa224518bedd1..45c53c842568f8 100644 --- a/examples/tv-casting-app/linux/main.cpp +++ b/examples/tv-casting-app/linux/main.cpp @@ -25,7 +25,7 @@ #include "CastingUtils.h" #if defined(ENABLE_CHIP_SHELL) #include "CastingShellCommands.h" -#include +#include // nogncheck #include #endif diff --git a/examples/window-app/silabs/SiWx917/include/AppConfig.h b/examples/window-app/silabs/SiWx917/include/AppConfig.h index 7a3f809ac217c5..19c64320bf6e7a 100644 --- a/examples/window-app/silabs/SiWx917/include/AppConfig.h +++ b/examples/window-app/silabs/SiWx917/include/AppConfig.h @@ -19,14 +19,11 @@ #pragma once +#include "silabs_utils.h" + // ---- Window Example App Config ---- #define APP_TASK_NAME "APP" -// EFR Logging -#ifdef __cplusplus -extern "C" { -#endif - #define LCD_SIZE 128 #define LCD_MARGIN_SIZE 1 #define LCD_BORDER_SIZE 2 @@ -56,15 +53,3 @@ extern "C" { #ifndef COVER_LIFT_TILT_TIMEOUT #define COVER_LIFT_TILT_TIMEOUT 500 #endif - -void silabsInitLog(void); - -void efr32Log(const char * aFormat, ...); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); - -#ifdef __cplusplus -} - -#include -void appError(CHIP_ERROR error); -#endif diff --git a/examples/window-app/silabs/efr32/include/AppConfig.h b/examples/window-app/silabs/efr32/include/AppConfig.h index 7a3f809ac217c5..19c64320bf6e7a 100644 --- a/examples/window-app/silabs/efr32/include/AppConfig.h +++ b/examples/window-app/silabs/efr32/include/AppConfig.h @@ -19,14 +19,11 @@ #pragma once +#include "silabs_utils.h" + // ---- Window Example App Config ---- #define APP_TASK_NAME "APP" -// EFR Logging -#ifdef __cplusplus -extern "C" { -#endif - #define LCD_SIZE 128 #define LCD_MARGIN_SIZE 1 #define LCD_BORDER_SIZE 2 @@ -56,15 +53,3 @@ extern "C" { #ifndef COVER_LIFT_TILT_TIMEOUT #define COVER_LIFT_TILT_TIMEOUT 500 #endif - -void silabsInitLog(void); - -void efr32Log(const char * aFormat, ...); -#define SILABS_LOG(...) efr32Log(__VA_ARGS__); - -#ifdef __cplusplus -} - -#include -void appError(CHIP_ERROR error); -#endif diff --git a/examples/window-app/silabs/efr32/src/WindowAppImpl.cpp b/examples/window-app/silabs/efr32/src/WindowAppImpl.cpp index 51c6652c6da149..c4e48212e56e42 100644 --- a/examples/window-app/silabs/efr32/src/WindowAppImpl.cpp +++ b/examples/window-app/silabs/efr32/src/WindowAppImpl.cpp @@ -31,9 +31,6 @@ #include #include #endif // QR_CODE_ENABLED -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT -#include -#endif #include @@ -60,6 +57,7 @@ SilabsLCD slLCD; using namespace chip::app::Clusters::WindowCovering; using namespace chip; using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceLayer::Silabs; #define APP_STATE_LED 0 #define APP_ACTION_LED 1 @@ -518,9 +516,9 @@ WindowAppImpl::Button::Button(WindowApp::Button::Id id, const char * name) : Win void WindowAppImpl::OnButtonChange(uint8_t button, uint8_t btnAction) { -#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT WindowApp::Button * btn = static_cast