diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index aecc5372bcc41c..838e19e75a5c64 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -17,7 +17,7 @@ "build": { "dockerfile": "Dockerfile", "args": { - "BUILD_VERSION": "0.6.30" + "BUILD_VERSION": "0.6.35" } }, "remoteUser": "vscode", diff --git a/.github/.wordlist.txt b/.github/.wordlist.txt index b1f04c1a849bf4..f7d6f3995dc039 100644 --- a/.github/.wordlist.txt +++ b/.github/.wordlist.txt @@ -416,6 +416,7 @@ diffsyms dimmable dirname dirs +disableNotifyUpdateApplied disambiguated discoverable DispatchEvent diff --git a/.github/workflows/bloat_check.yaml b/.github/workflows/bloat_check.yaml index 1df105da65301d..494a0f42ec2acf 100644 --- a/.github/workflows/bloat_check.yaml +++ b/.github/workflows/bloat_check.yaml @@ -27,10 +27,13 @@ jobs: pull_request_update: name: Report on pull requests + # Don't run on forked repos + if: github.repository_owner == 'project-chip' + runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 steps: - uses: Wandalen/wretry.action@v1.0.36 diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 66f2035df7f874..8a847a3e034df6 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 volumes: - "/tmp/log_output:/tmp/test_logs" options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 @@ -138,7 +138,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 volumes: - "/tmp/log_output:/tmp/test_logs" options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 @@ -298,7 +298,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 volumes: - "/tmp/log_output:/tmp/test_logs" options: --sysctl "net.ipv6.conf.all.disable_ipv6=0 @@ -352,12 +352,6 @@ jobs: timeout-minutes: 200 runs-on: macos-latest if: github.actor != 'restyled-io[bot]' - - env: - # NOTE: Generally kept in sync within the repo using - # scripts/tools/zap/version_update.py - ZAP_VERSION: v2023.01.19-nightly - ZAP_INSTALL_PATH: /usr/local/zap/zap-v2023.01.19-nightly steps: - uses: Wandalen/wretry.action@v1.0.36 @@ -388,16 +382,6 @@ jobs: ls -la /usr/local/Cellar/openssl@1.1 OPEN_SSL_VERSION=`ls -la /usr/local/Cellar/openssl@1.1 | cat | tail -n1 | awk '{print $NF}'` ln -s /usr/local/Cellar/openssl@1.1/$OPEN_SSL_VERSION/lib/pkgconfig/* . - - name: Install zap - run: | - sudo mkdir -p $ZAP_INSTALL_PATH - sudo chown `whoami` $ZAP_INSTALL_PATH - curl -L https://github.com/project-chip/zap/releases/download/${ZAP_VERSION}/zap-mac.zip \ - --output $ZAP_INSTALL_PATH/zap-mac.zip - cd $ZAP_INSTALL_PATH - unzip zap-mac.zip zap-cli - rm zap-mac.zip - ./zap-cli --version - name: Bootstrap timeout-minutes: 25 run: scripts/build/gn_bootstrap.sh @@ -471,7 +455,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 volumes: - "/tmp/log_output:/tmp/test_logs" options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 diff --git a/.github/workflows/chef.yaml b/.github/workflows/chef.yaml index 40a11908b4b072..e3f9709180380a 100644 --- a/.github/workflows/chef.yaml +++ b/.github/workflows/chef.yaml @@ -29,7 +29,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 options: --user root steps: @@ -57,7 +57,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32:0.6.34 + image: connectedhomeip/chip-build-esp32:0.6.35 options: --user root steps: @@ -85,7 +85,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-nrf-platform:0.6.34 + image: connectedhomeip/chip-build-nrf-platform:0.6.35 options: --user root steps: diff --git a/.github/workflows/cirque.yaml b/.github/workflows/cirque.yaml index 5cc48487c6ae97..ec999e2170b7e8 100644 --- a/.github/workflows/cirque.yaml +++ b/.github/workflows/cirque.yaml @@ -29,7 +29,7 @@ jobs: timeout-minutes: 90 env: - DOCKER_RUN_VERSION: 0.6.34 + DOCKER_RUN_VERSION: 0.6.35 GITHUB_CACHE_PATH: /tmp/cirque-cache/ runs-on: ubuntu-latest @@ -38,7 +38,7 @@ jobs: # need to run with privilege, which isn't supported by job.XXX.contaner # https://github.com/actions/container-action/issues/2 # container: - # image: connectedhomeip/chip-build-cirque:0.6.34 + # image: connectedhomeip/chip-build-cirque:0.6.35 # volumes: # - "/tmp:/tmp" # - "/dev/pts:/dev/pts" diff --git a/.github/workflows/darwin-tests.yaml b/.github/workflows/darwin-tests.yaml index d9e70b82503984..7d1db5f479dc6c 100644 --- a/.github/workflows/darwin-tests.yaml +++ b/.github/workflows/darwin-tests.yaml @@ -39,10 +39,6 @@ jobs: env: BUILD_VARIANT: ${{matrix.build_variant}} LSAN_OPTIONS: detect_leaks=1 malloc_context_size=40 suppressions=scripts/tests/chiptest/lsan-mac-suppressions.txt - # NOTE: Generally kept in sync within the repo using - # scripts/tools/zap/version_update.py - ZAP_VERSION: v2023.01.19-nightly - ZAP_INSTALL_PATH: /usr/local/zap/zap-v2023.01.19-nightly if: github.actor != 'restyled-io[bot]' runs-on: macos-latest @@ -76,16 +72,6 @@ jobs: ls -la /usr/local/Cellar/openssl@1.1 OPEN_SSL_VERSION=`ls -la /usr/local/Cellar/openssl@1.1 | cat | tail -n1 | awk '{print $NF}'` ln -s /usr/local/Cellar/openssl@1.1/$OPEN_SSL_VERSION/lib/pkgconfig/* . - - name: Install zap - run: | - sudo mkdir -p $ZAP_INSTALL_PATH - sudo chown `whoami` $ZAP_INSTALL_PATH - curl -L https://github.com/project-chip/zap/releases/download/${ZAP_VERSION}/zap-mac.zip \ - --output $ZAP_INSTALL_PATH/zap-mac.zip - cd $ZAP_INSTALL_PATH - unzip zap-mac.zip zap-cli - rm zap-mac.zip - ./zap-cli --version - name: Bootstrap timeout-minutes: 25 run: scripts/build/gn_bootstrap.sh diff --git a/.github/workflows/darwin.yaml b/.github/workflows/darwin.yaml index 447c16fe8eb88a..fb29e67cd0ce98 100644 --- a/.github/workflows/darwin.yaml +++ b/.github/workflows/darwin.yaml @@ -52,22 +52,6 @@ jobs: ls -la /usr/local/Cellar/openssl@1.1 OPEN_SSL_VERSION=`ls -la /usr/local/Cellar/openssl@1.1 | cat | tail -n1 | awk '{print $NF}'` ln -s /usr/local/Cellar/openssl@1.1/$OPEN_SSL_VERSION/lib/pkgconfig/* . - - name: Install zap - run: | - sudo mkdir -p $ZAP_INSTALL_PATH - sudo chown `whoami` $ZAP_INSTALL_PATH - curl -L https://github.com/project-chip/zap/releases/download/${ZAP_VERSION}/zap-mac.zip \ - --output $ZAP_INSTALL_PATH/zap-mac.zip - cd $ZAP_INSTALL_PATH - unzip zap-mac.zip zap-cli - rm zap-mac.zip - ./zap-cli --version - env: - # NOTE: Generally kept in sync within the repo using - # scripts/tools/zap/version_update.py - # This is scoped to only the steps that don't use xcodebuild. - ZAP_VERSION: v2023.01.19-nightly - ZAP_INSTALL_PATH: /usr/local/zap/zap-v2023.01.19-nightly - name: Bootstrap timeout-minutes: 25 run: scripts/build/gn_bootstrap.sh @@ -79,6 +63,12 @@ jobs: path: | .environment/gn_out/.ninja_log .environment/pigweed-venv/*.log + - name: Block zap-cli from being used + # xcodebuild is NOT expected to require zap-cli + run: scripts/run_in_build_env.sh 'mv $PW_ENVIRONMENT_ROOT/cipd/packages/zap/zap-cli $PW_ENVIRONMENT_ROOT/cipd/packages/zap/zap-cli.moved' + - name: Validate zap-cli is NOT available + # run_in_build_env.sh is used to ensure PATH is set to something that would otherwise find zap-cli + run: scripts/run_in_build_env.sh '(zap-cli --version && exit 1) || exit 0' - name: Run iOS Build Debug timeout-minutes: 50 working-directory: src/darwin/Framework @@ -118,36 +108,22 @@ jobs: - name: Clean Build run: xcodebuild clean working-directory: src/darwin/Framework + - name: Make zap-cli work again + run: scripts/run_in_build_env.sh 'mv $PW_ENVIRONMENT_ROOT/cipd/packages/zap/zap-cli.moved $PW_ENVIRONMENT_ROOT/cipd/packages/zap/zap-cli' + - name: Validate zap-cli is again available + run: scripts/run_in_build_env.sh 'zap-cli --version' - name: Build example All Clusters Server timeout-minutes: 15 run: | scripts/examples/gn_build_example.sh examples/all-clusters-app/linux out/debug chip_config_network_layer_ble=false - env: - # NOTE: Generally kept in sync within the repo using - # scripts/tools/zap/version_update.py - # This is scoped to only the steps that don't use xcodebuild. - ZAP_VERSION: v2023.01.19-nightly - ZAP_INSTALL_PATH: /usr/local/zap/zap-v2023.01.19-nightly - name: Build example OTA Provider timeout-minutes: 10 run: | scripts/examples/gn_build_example.sh examples/ota-provider-app/linux out/debug chip_config_network_layer_ble=false - env: - # NOTE: Generally kept in sync within the repo using - # scripts/tools/zap/version_update.py - # This is scoped to only the steps that don't use xcodebuild. - ZAP_VERSION: v2023.01.19-nightly - ZAP_INSTALL_PATH: /usr/local/zap/zap-v2023.01.19-nightly - name: Build example OTA Requestor timeout-minutes: 10 run: | scripts/examples/gn_build_example.sh examples/ota-requestor-app/linux out/debug chip_config_network_layer_ble=false - env: - # NOTE: Generally kept in sync within the repo using - # scripts/tools/zap/version_update.py - # This is scoped to only the steps that don't use xcodebuild. - ZAP_VERSION: v2023.01.19-nightly - ZAP_INSTALL_PATH: /usr/local/zap/zap-v2023.01.19-nightly - name: Delete Defaults run: defaults delete com.apple.dt.xctest.tool continue-on-error: true diff --git a/.github/workflows/doxygen.yaml b/.github/workflows/doxygen.yaml index 9ac5d34d6f8504..53975923422d84 100644 --- a/.github/workflows/doxygen.yaml +++ b/.github/workflows/doxygen.yaml @@ -82,7 +82,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build-doxygen:0.6.34 + image: connectedhomeip/chip-build-doxygen:0.6.35 if: github.actor != 'restyled-io[bot]' diff --git a/.github/workflows/examples-ameba.yaml b/.github/workflows/examples-ameba.yaml index 422c1819472cd7..23c52d94fe0bf6 100644 --- a/.github/workflows/examples-ameba.yaml +++ b/.github/workflows/examples-ameba.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-ameba:0.6.34 + image: connectedhomeip/chip-build-ameba:0.6.35 options: --user root steps: diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index 1453b4d4d4bf40..f18f9b933b310e 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-bouffalolab:0.6.34 + image: connectedhomeip/chip-build-bouffalolab:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-cc13x2x7_26x2x7.yaml b/.github/workflows/examples-cc13x2x7_26x2x7.yaml index 91ccd55f848360..c95d076834e0c9 100644 --- a/.github/workflows/examples-cc13x2x7_26x2x7.yaml +++ b/.github/workflows/examples-cc13x2x7_26x2x7.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-ti:0.6.34 + image: connectedhomeip/chip-build-ti:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-efr32.yaml b/.github/workflows/examples-efr32.yaml index 105e75ad731f30..10344c5c099151 100644 --- a/.github/workflows/examples-efr32.yaml +++ b/.github/workflows/examples-efr32.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-efr32:0.6.34 + image: connectedhomeip/chip-build-efr32:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-esp32.yaml b/.github/workflows/examples-esp32.yaml index f621be81617cc6..d28ba2d1c4657e 100644 --- a/.github/workflows/examples-esp32.yaml +++ b/.github/workflows/examples-esp32.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32:0.6.34 + image: connectedhomeip/chip-build-esp32:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -148,7 +148,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32:0.6.34 + image: connectedhomeip/chip-build-esp32:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-infineon.yaml b/.github/workflows/examples-infineon.yaml index e0b745fdd27365..503312465b9d56 100644 --- a/.github/workflows/examples-infineon.yaml +++ b/.github/workflows/examples-infineon.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-infineon:0.6.34 + image: connectedhomeip/chip-build-infineon:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-k32w.yaml b/.github/workflows/examples-k32w.yaml index 03867d3afd39e8..43d72b2f26cef7 100644 --- a/.github/workflows/examples-k32w.yaml +++ b/.github/workflows/examples-k32w.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-k32w:0.6.34 + image: connectedhomeip/chip-build-k32w:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-linux-arm.yaml b/.github/workflows/examples-linux-arm.yaml index 6b4fcfc8c2ec07..0d3c6af18258e7 100644 --- a/.github/workflows/examples-linux-arm.yaml +++ b/.github/workflows/examples-linux-arm.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-crosscompile:0.6.34 + image: connectedhomeip/chip-build-crosscompile:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -73,7 +73,7 @@ jobs: run: | ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ - --target linux-arm64-chip-cert \ + --target linux-arm64-chip-cert-clang \ --target linux-arm64-all-clusters-clang \ --target linux-arm64-chip-tool-ipv6only-clang \ --target linux-arm64-lock-clang \ diff --git a/.github/workflows/examples-linux-imx.yaml b/.github/workflows/examples-linux-imx.yaml index 9bda08530bf2df..5fb3d8a17a35ff 100644 --- a/.github/workflows/examples-linux-imx.yaml +++ b/.github/workflows/examples-linux-imx.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-imx:0.6.34 + image: connectedhomeip/chip-build-imx:0.6.35 steps: - uses: Wandalen/wretry.action@v1.0.36 diff --git a/.github/workflows/examples-linux-standalone.yaml b/.github/workflows/examples-linux-standalone.yaml index 2e7016880da510..9cb447501b9c18 100644 --- a/.github/workflows/examples-linux-standalone.yaml +++ b/.github/workflows/examples-linux-standalone.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-mbed.yaml b/.github/workflows/examples-mbed.yaml index a5b6c2e299b9b1..6f24da71558367 100644 --- a/.github/workflows/examples-mbed.yaml +++ b/.github/workflows/examples-mbed.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-mbed-os:0.6.34 + image: connectedhomeip/chip-build-mbed-os:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-mw320.yaml b/.github/workflows/examples-mw320.yaml index 0d646e0442a7be..69f6e23ae06b85 100755 --- a/.github/workflows/examples-mw320.yaml +++ b/.github/workflows/examples-mw320.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-nrfconnect.yaml b/.github/workflows/examples-nrfconnect.yaml index a88c4ac01702a3..1d84e4629db0b8 100644 --- a/.github/workflows/examples-nrfconnect.yaml +++ b/.github/workflows/examples-nrfconnect.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-nrf-platform:0.6.34 + image: connectedhomeip/chip-build-nrf-platform:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-openiotsdk.yaml b/.github/workflows/examples-openiotsdk.yaml index c3fb39cf441bf8..975ebce2e9510b 100644 --- a/.github/workflows/examples-openiotsdk.yaml +++ b/.github/workflows/examples-openiotsdk.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-openiotsdk:0.6.34 + image: connectedhomeip/chip-build-openiotsdk:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" options: --privileged diff --git a/.github/workflows/examples-qpg.yaml b/.github/workflows/examples-qpg.yaml index 2e45bc73131d01..67f4db03565fbc 100644 --- a/.github/workflows/examples-qpg.yaml +++ b/.github/workflows/examples-qpg.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-telink.yaml b/.github/workflows/examples-telink.yaml index 6aca1ff4caddf4..4e025b0917f900 100644 --- a/.github/workflows/examples-telink.yaml +++ b/.github/workflows/examples-telink.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-telink:0.6.34 + image: connectedhomeip/chip-build-telink:0.6.35 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-tizen.yaml b/.github/workflows/examples-tizen.yaml index 528323915f6cd4..a4ed8444b01c90 100644 --- a/.github/workflows/examples-tizen.yaml +++ b/.github/workflows/examples-tizen.yaml @@ -33,7 +33,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-tizen:0.6.34 + image: connectedhomeip/chip-build-tizen:0.6.35 options: --user root volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -61,9 +61,9 @@ jobs: --enable-flashbundle \ --target tizen-arm-all-clusters \ --target tizen-arm-all-clusters-minimal-no-wifi \ - --target chip-tool-ubsan \ - --target light \ - --target light-no-ble-no-wifi \ + --target tizen-arm-chip-tool-ubsan \ + --target tizen-arm-light \ + --target tizen-arm-light-no-ble-no-wifi \ build \ --copy-artifacts-to out/artifacts \ " diff --git a/.github/workflows/full-android.yaml b/.github/workflows/full-android.yaml index ff7c0c6983ddd2..d8a5a13396c386 100644 --- a/.github/workflows/full-android.yaml +++ b/.github/workflows/full-android.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-android:0.6.34 + image: connectedhomeip/chip-build-android:0.6.35 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/fuzzing-build.yaml b/.github/workflows/fuzzing-build.yaml index c947ff5807a581..3f8e0424010bf5 100644 --- a/.github/workflows/fuzzing-build.yaml +++ b/.github/workflows/fuzzing-build.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 volumes: - "/tmp/log_output:/tmp/test_logs" @@ -88,12 +88,6 @@ jobs: runs-on: macos-latest if: github.actor != 'restyled-io[bot]' - env: - # NOTE: Generally kept in sync within the repo using - # scripts/tools/zap/version_update.py - ZAP_VERSION: v2023.01.19-nightly - ZAP_INSTALL_PATH: /usr/local/zap/zap-v2023.01.19-nightly - steps: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout @@ -117,16 +111,6 @@ jobs: ls -la /usr/local/Cellar/openssl@1.1 OPEN_SSL_VERSION=`ls -la /usr/local/Cellar/openssl@1.1 | cat | tail -n1 | awk '{print $NF}'` ln -s /usr/local/Cellar/openssl@1.1/$OPEN_SSL_VERSION/lib/pkgconfig/* . - - name: Install zap - run: | - sudo mkdir -p $ZAP_INSTALL_PATH - sudo chown `whoami` $ZAP_INSTALL_PATH - curl -L https://github.com/project-chip/zap/releases/download/${ZAP_VERSION}/zap-mac.zip \ - --output $ZAP_INSTALL_PATH/zap-mac.zip - cd $ZAP_INSTALL_PATH - unzip zap-mac.zip zap-cli - rm zap-mac.zip - ./zap-cli --version - name: Bootstrap timeout-minutes: 25 run: scripts/build/gn_bootstrap.sh diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 00e6f7cb060fe2..dc6ceed574b3a4 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -28,7 +28,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 steps: - uses: Wandalen/wretry.action@v1.0.36 @@ -116,7 +116,7 @@ jobs: uses: gaurav-nelson/github-action-markdown-link-check@v1 # git grep exits with 0 if it finds a match, but we want - # to fail (exit nonzero) on match. And we wasnt to exclude this file, + # to fail (exit nonzero) on match. And we want to exclude this file, # to avoid our grep regexp matching itself. - name: Check for incorrect error use in VerifyOrExit if: always() @@ -124,7 +124,7 @@ jobs: git grep -n "VerifyOrExit(.*, [A-Za-z]*_ERROR" -- './*' ':(exclude).github/workflows/lint.yml' && exit 1 || exit 0 # git grep exits with 0 if it finds a match, but we want - # to fail (exit nonzero) on match. And we wasnt to exclude this file, + # to fail (exit nonzero) on match. And we want to exclude this file, # to avoid our grep regexp matching itself. - name: Check for use of PRI*8, which are not supported on some libcs. if: always() @@ -132,7 +132,7 @@ jobs: git grep -n "PRI.8" -- './*' ':(exclude).github/workflows/lint.yml' ':(exclude)third_party/lwip/repo/lwip/src/include/lwip/arch.h' && exit 1 || exit 0 # git grep exits with 0 if it finds a match, but we want - # to fail (exit nonzero) on match. And we wasnt to exclude this file, + # to fail (exit nonzero) on match. And we want to exclude this file, # to avoid our grep regexp matching itself. - name: Check for use of PRI*16, which are not supported on some libcs. if: always() @@ -140,7 +140,7 @@ jobs: git grep -n "PRI.16" -- './*' ':(exclude).github/workflows/lint.yml' ':(exclude)third_party/lwip/repo/lwip/src/include/lwip/arch.h' && exit 1 || exit 0 # git grep exits with 0 if it finds a match, but we want - # to fail (exit nonzero) on match. And we wasnt to exclude this file, + # to fail (exit nonzero) on match. And we want to exclude this file, # to avoid our grep regexp matching itself. - name: Check for use of %zu, which are not supported on some libcs. if: always() @@ -167,7 +167,7 @@ jobs: scripts/tools/check_test_pics.py src/app/tests/suites/certification/ci-pics-values src/app/tests/suites/certification/PICS.yaml # git grep exits with 0 if it finds a match, but we want - # to fail (exit nonzero) on match. And we wasnt to exclude this file, + # to fail (exit nonzero) on match. And we want to exclude this file, # to avoid our grep regexp matching itself. - name: Check for use of 0x%u and the like, which lead to misleading output. if: always() @@ -175,9 +175,17 @@ jobs: git grep -n '0x%[0-9l.-]*[^0-9lxX".-]' -- './*' ':(exclude).github/workflows/lint.yml' && exit 1 || exit 0 # git grep exits with 0 if it finds a match, but we want - # to fail (exit nonzero) on match. And we wasnt to exclude this file, + # to fail (exit nonzero) on match. And we want to exclude this file, # to avoid our grep regexp matching itself. - name: Check for use of '"0x" PRIu*' and the like, which lead to misleading output. if: always() run: | git grep -n '0x%[0-9-]*" *PRI[^xX]' -- './*' ':(exclude).github/workflows/lint.yml' && exit 1 || exit 0 + + # git grep exits with 0 if it finds a match, but we want + # to fail (exit nonzero) on match. And we want to exclude this file, + # to avoid our grep regexp matching itself. + - name: Check for use of legacy non-namespaced attribute ids. + if: always() + run: | + git grep -n '_ATTRIBUTE_ID' -- src ':(exclude)src/app/zap-templates/templates/app/attribute-id.zapt' && exit 1 || exit 0 diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index 66c3b6a576088e..293ee31f955c64 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32-qemu:0.6.34 + image: connectedhomeip/chip-build-esp32-qemu:0.6.35 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/release_artifacts.yaml b/.github/workflows/release_artifacts.yaml index f53931717c01ea..1b773d8c28d52c 100644 --- a/.github/workflows/release_artifacts.yaml +++ b/.github/workflows/release_artifacts.yaml @@ -29,7 +29,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build-esp32:0.6.34 + image: connectedhomeip/chip-build-esp32:0.6.35 steps: - uses: Wandalen/wretry.action@v1.0.36 @@ -75,7 +75,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build-efr32:0.6.34 + image: connectedhomeip/chip-build-efr32:0.6.35 steps: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout diff --git a/.github/workflows/smoketest-android.yaml b/.github/workflows/smoketest-android.yaml index 44f1defff5cf11..1007d93e99f7ea 100644 --- a/.github/workflows/smoketest-android.yaml +++ b/.github/workflows/smoketest-android.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-android:0.6.34 + image: connectedhomeip/chip-build-android:0.6.35 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index e002203160cd00..a0370261e34ccb 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -47,7 +47,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" @@ -136,10 +136,12 @@ jobs: src/app/zap-templates/zcl/data-model/chip/general-commissioning-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/general-diagnostics-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/global-attributes.xml \ + src/app/zap-templates/zcl/data-model/chip/groups-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/group-key-mgmt-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/identify-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/illuminance-measurement-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/keypad-input-cluster.xml \ + src/app/zap-templates/zcl/data-model/chip/level-control-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/localization-configuration-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/low-power-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/media-input-cluster.xml \ @@ -173,11 +175,12 @@ jobs: src/app/zap-templates/zcl/data-model/chip/wifi-network-diagnostics-cluster.xml \ src/app/zap-templates/zcl/data-model/chip/window-covering.xml \ src/app/zap-templates/zcl/data-model/chip/matter-devices.xml \ + src/app/zap-templates/zcl/data-model/draft/barrier-control-cluster.xml \ src/app/zap-templates/zcl/data-model/silabs/general.xml \ src/app/zap-templates/zcl/data-model/silabs/ha-devices.xml \ src/app/zap-templates/zcl/data-model/silabs/ha.xml \ src/app/zap-templates/zcl/data-model/silabs/lo-devices.xml \ - src/app/zap-templates/zcl/data-model/silabs/types.xml \ + src/app/zap-templates/zcl/data-model/silabs/types-silabs.xml \ src/app/zap-templates/zcl/data-model/silabs/zll-devices.xml \ src/app/zap-templates/zcl/data-model/silabs/zll.xml \ " @@ -214,11 +217,10 @@ jobs: --bridge-app ./out/linux-x64-bridge-${BUILD_VARIANT}/chip-bridge-app \ " - name: Run Tests using chip-repl - timeout-minutes: 5 + timeout-minutes: 45 run: | ./scripts/run_in_build_env.sh \ "./scripts/tests/run_test_suite.py \ - --chip-tool ./out/linux-x64-chip-tool${CHIP_TOOL_VARIANT}-${BUILD_VARIANT}/chip-tool \ --run-yamltests-with-chip-repl \ run \ --iterations 1 \ @@ -260,10 +262,6 @@ jobs: CHIP_TOOL_VARIANT: ${{matrix.chip_tool}} TSAN_OPTIONS: "halt_on_error=1" LSAN_OPTIONS: detect_leaks=1 suppressions=scripts/tests/chiptest/lsan-mac-suppressions.txt - # NOTE: Generally kept in sync within the repo using - # scripts/tools/zap/version_update.py - ZAP_VERSION: v2023.01.19-nightly - ZAP_INSTALL_PATH: /usr/local/zap/zap-v2023.01.19-nightly if: github.actor != 'restyled-io[bot]' runs-on: macos-latest @@ -297,15 +295,6 @@ jobs: ls -la /usr/local/Cellar/openssl@1.1 OPEN_SSL_VERSION=`ls -la /usr/local/Cellar/openssl@1.1 | cat | tail -n1 | awk '{print $NF}'` ln -s /usr/local/Cellar/openssl@1.1/$OPEN_SSL_VERSION/lib/pkgconfig/* . - - name: Install zap - run: | - sudo mkdir -p $ZAP_INSTALL_PATH - sudo chown `whoami` $ZAP_INSTALL_PATH - curl -L https://github.com/project-chip/zap/releases/download/${ZAP_VERSION}/zap-mac.zip \ - --output $ZAP_INSTALL_PATH/zap-mac.zip - cd $ZAP_INSTALL_PATH - unzip zap-mac.zip zap-cli - rm zap-mac.zip - name: Bootstrap timeout-minutes: 25 run: scripts/build/gn_bootstrap.sh @@ -383,7 +372,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" @@ -428,6 +417,7 @@ jobs: scripts/run_in_build_env.sh './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_decode 1" --script "src/python_testing/TC_SC_3_6.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021"' scripts/run_in_build_env.sh './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_decode 1" --script "src/python_testing/TC_DA_1_7.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --bool-arg allow_sdk_dac:true"' scripts/run_in_build_env.sh './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_decode 1 --enable-key 000102030405060708090a0b0c0d0e0f" --script "src/python_testing/TC_TestEventTrigger.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --bool-arg allow_sdk_dac:true"' + scripts/run_in_build_env.sh './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_decode 1" --script "src/python_testing/TC_ACE_1_4.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021 --int-arg PIXIT.ACE.APPENDPOINT:1 PIXIT.ACE.APPDEVTYPEID:0x0100 --string-arg PIXIT.ACE.APPCLUSTER:OnOff PIXIT.ACE.APPATTRIBUTE:OnOff"' scripts/run_in_build_env.sh './scripts/tests/run_python_test.py --app out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app --factoryreset --app-args "--discriminator 1234 --KVS kvs1 --trace_decode 1" --script "src/python_testing/TC_ACE_1_3.py" --script-args "--storage-path admin_storage.json --commissioning-method on-network --discriminator 1234 --passcode 20202021"' - name: Uploading core files uses: actions/upload-artifact@v3 @@ -458,7 +448,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" @@ -545,10 +535,6 @@ jobs: env: BUILD_VARIANT: ${{matrix.build_variant}} TSAN_OPTIONS: "halt_on_error=1" - # NOTE: Generally kept in sync within the repo using - # scripts/tools/zap/version_update.py - ZAP_VERSION: v2023.01.19-nightly - ZAP_INSTALL_PATH: /usr/local/zap/zap-v2023.01.19-nightly if: github.actor != 'restyled-io[bot]' && false runs-on: macos-latest @@ -576,15 +562,6 @@ jobs: ls -la /usr/local/Cellar/openssl@1.1 OPEN_SSL_VERSION=`ls -la /usr/local/Cellar/openssl@1.1 | cat | tail -n1 | awk '{print $NF}'` ln -s /usr/local/Cellar/openssl@1.1/$OPEN_SSL_VERSION/lib/pkgconfig/* . - - name: Install zap - run: | - sudo mkdir -p $ZAP_INSTALL_PATH - sudo chown `whoami` $ZAP_INSTALL_PATH - curl -L https://github.com/project-chip/zap/releases/download/${ZAP_VERSION}/zap-mac.zip \ - --output $ZAP_INSTALL_PATH/zap-mac.zip - cd $ZAP_INSTALL_PATH - unzip zap-mac.zip zap-cli - rm zap-mac.zip - name: Bootstrap timeout-minutes: 25 run: scripts/build/gn_bootstrap.sh diff --git a/.github/workflows/unit_integration_test.yaml b/.github/workflows/unit_integration_test.yaml index c339a84510921c..d01552761f847e 100644 --- a/.github/workflows/unit_integration_test.yaml +++ b/.github/workflows/unit_integration_test.yaml @@ -37,7 +37,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 volumes: - "/tmp/log_output:/tmp/test_logs" options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" diff --git a/.github/workflows/zap_regeneration.yaml b/.github/workflows/zap_regeneration.yaml index 740dc62b49d0a8..35a48203405047 100644 --- a/.github/workflows/zap_regeneration.yaml +++ b/.github/workflows/zap_regeneration.yaml @@ -28,7 +28,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 defaults: run: shell: sh diff --git a/.github/workflows/zap_templates.yaml b/.github/workflows/zap_templates.yaml index dadb560e0a29fd..7a49bde308a9ad 100644 --- a/.github/workflows/zap_templates.yaml +++ b/.github/workflows/zap_templates.yaml @@ -29,7 +29,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build:0.6.34 + image: connectedhomeip/chip-build:0.6.35 defaults: run: shell: sh diff --git a/.gitignore b/.gitignore index 8d4ea014d762c6..5c9f408a1cb968 100644 --- a/.gitignore +++ b/.gitignore @@ -71,3 +71,6 @@ compile_commands.json # log files *.log examples/thermostat/ameba/build + +# Downloaded zap without a pigweed root (via zap_download.py) +.zap diff --git a/.gitmodules b/.gitmodules index 74addf59b3d0d7..048d1f48b7734b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -293,4 +293,4 @@ [submodule "third_party/libwebsockets/repo"] path = third_party/libwebsockets/repo url = https://github.com/warmcat/libwebsockets - platforms = linux,darwin + platforms = linux,darwin,tizen diff --git a/.vscode/launch.json b/.vscode/launch.json index bf83cc0d85d6e4..5a8cfbce9c8682 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -435,7 +435,13 @@ "armToolchainPath": "${env:ARM_GCC_TOOLCHAIN_PATH}/bin", "servertype": "external", "gdbTarget": "${input:openiotsdkRemoteHost}: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/chip-openiotsdk-${input:openiotsdkApp}-example_ns.elf 0x28060400", + "break main_ns.cpp:main" + ], "runToEntryPoint": "main", "preLaunchTask": "Debug Open IoT SDK example", "showDevDebugOutput": "parsed" diff --git a/config/esp32/components/chip/CMakeLists.txt b/config/esp32/components/chip/CMakeLists.txt index d7cb69a6a8fa34..fcd62b8757a36c 100644 --- a/config/esp32/components/chip/CMakeLists.txt +++ b/config/esp32/components/chip/CMakeLists.txt @@ -31,10 +31,10 @@ endif() include(${CMAKE_CURRENT_LIST_DIR}/ota-image.cmake) -set(CHIP_REQURIE_COMPONENTS freertos lwip bt mbedtls fatfs app_update console openthread nvs_flash) +set(CHIP_REQUIRE_COMPONENTS freertos lwip bt mbedtls fatfs app_update console openthread nvs_flash spi_flash) if((NOT "${IDF_TARGET}" STREQUAL "esp32h2") AND (NOT "${IDF_TARGET}" STREQUAL "esp32c2")) - list(APPEND CHIP_REQURIE_COMPONENTS mdns) + list(APPEND CHIP_REQUIRE_COMPONENTS mdns) endif() if (NOT CMAKE_BUILD_EARLY_EXPANSION) @@ -49,7 +49,7 @@ if (NOT CMAKE_BUILD_EARLY_EXPANSION) endif() idf_component_register(SRCS chip.c chip.cpp - PRIV_REQUIRES ${CHIP_REQURIE_COMPONENTS}) + PRIV_REQUIRES ${CHIP_REQUIRE_COMPONENTS}) # Prepare initial args file (lacking compile flags) # This will be saved as args.gn.in diff --git a/config/esp32/components/chip/Kconfig b/config/esp32/components/chip/Kconfig index dea6109649232f..34b2e0fb043345 100644 --- a/config/esp32/components/chip/Kconfig +++ b/config/esp32/components/chip/Kconfig @@ -673,7 +673,7 @@ menu "CHIP Device Layer" config ENABLE_ESP32_LOCATIONCAPABILITY depends on ENABLE_ESP32_FACTORY_DATA_PROVIDER - bool "Enable ESP32 Device LocationCapability " + bool "Enable ESP32 Device LocationCapability" default n help Enable ESP32 Device LocationCapability diff --git a/config/esp32/components/chip/idf_component.yml b/config/esp32/components/chip/idf_component.yml new file mode 100644 index 00000000000000..e47917975ce13d --- /dev/null +++ b/config/esp32/components/chip/idf_component.yml @@ -0,0 +1,6 @@ +## IDF Component Manager Manifest File +dependencies: + espressif/mdns: + version: "^1.0.3" + rules: + - if: "idf_version >=5.0" diff --git a/config/openiotsdk/CMakeLists.txt b/config/openiotsdk/CMakeLists.txt index 414f591095f1dc..1e7a77a0f21615 100644 --- a/config/openiotsdk/CMakeLists.txt +++ b/config/openiotsdk/CMakeLists.txt @@ -97,20 +97,10 @@ endif() set(GN_ROOT_TARGET ${CHIP_ROOT}/config/openiotsdk/chip-gn) # Prepare compiler flags -# All Open IoT SDK targets -list(APPEND ALL_SDK_TARGETS) - -foreach(source_dir ${SDK_SOURCES_BINARY_DIRS}) - get_all_cmake_targets(SDK_TARGETS ${source_dir}) - list(APPEND ALL_SDK_TARGETS ${SDK_TARGETS}) -endforeach() - -# Exclude unnecessary targets -list(FILTER ALL_SDK_TARGETS EXCLUDE REGEX "^.*linker.*|.*example.*|.*apps.*|.*doc.*|dist|lib$") - -foreach(target ${ALL_SDK_TARGETS}) - get_target_common_compile_flags(SDK_TARGET_CFLAGS ${target}) - list(APPEND CHIP_CFLAGS ${SDK_TARGET_CFLAGS}) +# Get compiler flags from external targets +foreach(target ${EXTERNAL_TARGETS}) + get_target_common_compile_flags(EXTERNAL_TARGET_CFLAGS ${target}) + list(APPEND CHIP_CFLAGS ${EXTERNAL_TARGET_CFLAGS}) endforeach() # Remove duplicated flags @@ -200,6 +190,8 @@ chip_gn_arg_bool ("chip_detail_logging" CONFIG_CHIP_DETAIL_LOG chip_gn_arg_bool ("chip_progress_logging" CONFIG_CHIP_PROGRESS_LOGGING) chip_gn_arg_bool ("chip_automation_logging" CONFIG_CHIP_AUTOMATION_LOGGING) chip_gn_arg_bool ("chip_error_logging" CONFIG_CHIP_ERROR_LOGGING) +chip_gn_arg_bool ("chip_openiotsdk_use_tfm" TFM_SUPPORT) +chip_gn_arg_bool ("chip_openiotsdk_use_psa_ps" CONFIG_CHIP_OPEN_IOT_SDK_USE_PSA_PS) if (TARGET cmsis-rtos-api) chip_gn_arg_string("target_os" "cmsis-rtos") endif() @@ -249,22 +241,10 @@ target_include_directories(openiotsdk-chip INTERFACE target_link_directories(openiotsdk-chip INTERFACE ${CMAKE_CURRENT_BINARY_DIR}/lib) target_link_libraries(openiotsdk-chip INTERFACE -Wl,--start-group ${CHIP_LIBRARIES} -Wl,--end-group) target_link_libraries(openiotsdk-chip INTERFACE - $<$:mcu-driver-hal> - $<$:mcu-driver-bootstrap> - $<$:mdh-reference-platforms-for-arm> - $<$:mbedtls> - $<$:lwipcore> - $<$:iotsdk-ip-network-api> - $<$:iotsdk-tdbstore> - $<$:iotsdk-blockdevice> - $<$:$> + ${EXTERNAL_TARGETS} ) add_dependencies(openiotsdk-chip chip-gn) -target_include_directories(openiotsdk-chip INTERFACE - ${CHIP_ROOT}/config/openiotsdk/mbedtls -) - if (NOT ${CMAKE_BUILD_TYPE} STREQUAL "Debug") target_compile_definitions(openiotsdk-chip INTERFACE NDEBUG diff --git a/config/openiotsdk/cmake/chip.cmake b/config/openiotsdk/cmake/chip.cmake index 985d7f05bf74db..9a7dcf629e3a06 100644 --- a/config/openiotsdk/cmake/chip.cmake +++ b/config/openiotsdk/cmake/chip.cmake @@ -19,6 +19,8 @@ # CMake for CHIP library configuration # +get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH) + # Default CHIP build configuration set(CONFIG_CHIP_PROJECT_CONFIG "main/include/CHIPProjectConfig.h" CACHE STRING "") set(CONFIG_CHIP_LIB_TESTS NO CACHE BOOL "") @@ -29,5 +31,38 @@ set(CONFIG_CHIP_PROGRESS_LOGGING YES CACHE BOOL "Enable logging at progress leve set(CONFIG_CHIP_AUTOMATION_LOGGING YES CACHE BOOL "Enable logging at automation level") set(CONFIG_CHIP_ERROR_LOGGING YES CACHE BOOL "Enable logging at error level") +set(CONFIG_CHIP_OPEN_IOT_SDK_USE_PSA_PS NO CACHE BOOL "Enable using PSA Protected Storage") + +if(CONFIG_CHIP_OPEN_IOT_SDK_USE_PSA_PS AND NOT TFM_SUPPORT) + message( FATAL_ERROR "You can not use PSA Protected Storage without TF-M support" ) +endif() + # Add CHIP sources add_subdirectory(${OPEN_IOT_SDK_CONFIG} ./chip_build) + +# Additional openiotsdk-chip target configuration + +# TF-M support requires the right order of generating targets +if(TFM_SUPPORT) + add_dependencies(chip-gn tfm-ns-interface) +endif() + +function(chip_add_data_model target scope model_name) + target_include_directories(${target} + PUBLIC + ${GEN_DIR}/app-common + ${GEN_DIR}/${model_name}-app + ) + + target_compile_definitions(${target} + PUBLIC + USE_CHIP_DATA_MODEL + ) + + include(${CHIP_ROOT}/src/app/chip_data_model.cmake) + chip_configure_data_model(${target} + SCOPE ${scope} + INCLUDE_SERVER + ZAP_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../${model_name}-common/${model_name}-app.zap + ) +endfunction() diff --git a/config/openiotsdk/cmake/sdk.cmake b/config/openiotsdk/cmake/sdk.cmake index c87dad8412579d..52055cacdfc49a 100644 --- a/config/openiotsdk/cmake/sdk.cmake +++ b/config/openiotsdk/cmake/sdk.cmake @@ -24,41 +24,67 @@ include(FetchContent) get_filename_component(OPEN_IOT_SDK_SOURCE ${CHIP_ROOT}/third_party/open-iot-sdk/sdk REALPATH) get_filename_component(OPEN_IOT_SDK_STORAGE_SOURCE ${CHIP_ROOT}/third_party/open-iot-sdk/storage REALPATH) -# List of binary directories to Open IoT SDK sources -list(APPEND SDK_SOURCES_BINARY_DIRS) +# Open IoT SDK targets passed to CHIP build +list(APPEND 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)") + +# Overwrite versions of Open IoT SDK components + +# Add a Matter specific version of Mbedtls +FetchContent_Declare( + mbedtls + GIT_REPOSITORY https://github.com/ARMmbed/mbedtls + GIT_TAG v3.2.1 + GIT_SHALLOW ON + GIT_PROGRESS ON +) # Open IoT SDK configuration -set(IOTSDK_MDH_ARM ON) -set(MDH_PLATFORM "ARM_AN552_MPS3") -set(MDH_ARM_BUILD_EXAMPLES OFF) -set(IOTSDK_CMSIS_RTOS_API ON) -set(IOTSDK_FREERTOS ON) -set(IOTSDK_MBEDTLS ON) -set(IOTSDK_LWIP ON) -set(FETCHCONTENT_QUIET OFF) -set(IOTSDK_EXAMPLES OFF) -set(BUILD_TESTING NO) +set(IOTSDK_FETCH_LIST + mcu-driver-reference-platforms-for-arm + cmsis-5 + cmsis-freertos + mbedtls + lwip + cmsis-sockets-api +) + +set(MDH_PLATFORM ARM_AN552_MPS3) set(VARIANT "FVP") +set(FETCHCONTENT_QUIET OFF) +if(TFM_SUPPORT) + list(APPEND IOTSDK_FETCH_LIST trusted-firmware-m) + 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") + 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") + 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") + endif() + if(TFM_PROJECT_CONFIG_HEADER_FILE) + set(TFM_CMAKE_ARGS "${TFM_CMAKE_ARGS};-DPROJECT_CONFIG_HEADER_FILE=${TFM_PROJECT_CONFIG_HEADER_FILE}") + endif() + set(LINKER_SCRIPT ${OPEN_IOT_SDK_CONFIG}/ld/cs300_gcc_tfm.ld) +endif() # Add Open IoT SDK source add_subdirectory(${OPEN_IOT_SDK_SOURCE} ./sdk_build) -list(APPEND SDK_SOURCES_BINARY_DIRS ${CMAKE_CURRENT_BINARY_DIR}/sdk_build) # Add Open IoT SDK modules to path list(APPEND CMAKE_MODULE_PATH ${open-iot-sdk_SOURCE_DIR}/cmake) +list(APPEND CMAKE_MODULE_PATH ${open-iot-sdk_SOURCE_DIR}/components/trusted-firmware-m) + +# Configure component properties -# CMSIS-RTOS configuration # CMSIS 5 require projects to provide configuration macros via RTE_Components.h # and CMSIS_device_header. The macro CMSIS_device_header is not automatically set # based on CMAKE_SYSTEM_PROCESSOR in the place where cmsis-core is first defined, # because a project may want to provide its own device header. -if(TARGET cmsis-rtos-api) - target_include_directories(cmsis-rtos-api - PUBLIC - cmsis-config - ) -endif() - if(TARGET cmsis-core) target_compile_definitions(cmsis-core INTERFACE @@ -66,6 +92,48 @@ if(TARGET cmsis-core) ) endif() +# Add RTOS configuration headers +# Link cmsis-rtos-api against a concrete implementation +if(TARGET cmsis-rtos-api) + target_include_directories(cmsis-core + INTERFACE + cmsis-config + ) + + target_compile_definitions(cmsis-rtos-api + PUBLIC + DOMAIN_NS=$,1,0> + ) + + if(TARGET freertos-kernel) + target_include_directories(freertos-kernel + PUBLIC + freertos-config + ) + + target_link_libraries(freertos-kernel + PUBLIC + cmsis-core + ) + + target_link_libraries(cmsis-rtos-api + PUBLIC + freertos-cmsis-rtos + freertos-kernel-heap-3 + ) + + target_compile_definitions(cmsis-rtos-api + INTERFACE + CONFIG_RUN_FREERTOS_SECURE_ONLY=$,0,1> + ) + elseif(TARGET cmsis-rtx) + target_link_libraries(cmsis-rtos-api + INTERFACE + cmsis-rtx + ) + endif() +endif() + # LwIP configuration if(TARGET lwip-cmsis-port) # lwipcore requires the config defined by lwip-cmsis-port @@ -94,6 +162,13 @@ if(TARGET ethernet-lan91c111) ) endif() +if(TARGET mcu-driver-hal) + target_compile_definitions(mcu-driver-hal + INTERFACE + DOMAIN_NS=$,1,0> + ) +endif() + # Mbedtls config if(TARGET mbedtls-config) target_include_directories(mbedtls-config @@ -101,14 +176,14 @@ if(TARGET mbedtls-config) ${OPEN_IOT_SDK_CONFIG}/mbedtls ) - target_sources(mbedtls-config + target_sources(mbedtls-config INTERFACE ${OPEN_IOT_SDK_CONFIG}/mbedtls/platform_alt.cpp ) target_compile_definitions(mbedtls-config INTERFACE - MBEDTLS_CONFIG_FILE="mbedtls_config.h" + MBEDTLS_CONFIG_FILE="${OPEN_IOT_SDK_CONFIG}/mbedtls/mbedtls_config.h" ) target_link_libraries(mbedtls-config @@ -117,28 +192,138 @@ if(TARGET mbedtls-config) ) endif() -# Declare RTOS interface target -add_library(cmsis-rtos-implementation INTERFACE) +if("mcu-driver-reference-platforms-for-arm" IN_LIST IOTSDK_FETCH_LIST) + list(APPEND EXTERNAL_TARGETS + mcu-driver-bootstrap + mcu-driver-hal + mdh-arm-corstone-300-common + target-interface + ) +endif() -if(TARGET freertos-kernel) - target_link_libraries(cmsis-rtos-implementation - INTERFACE - freertos-cmsis-rtos - freertos-kernel-heap-3 +if("cmsis-5" IN_LIST IOTSDK_FETCH_LIST) + list(APPEND EXTERNAL_TARGETS + cmsis-core + cmsis-rtos-api + iotsdk-ip-network-api ) - target_include_directories(cmsis-rtos-implementation - INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}/freertos-config +endif() + +if("cmsis-freertos" IN_LIST IOTSDK_FETCH_LIST) + list(APPEND EXTERNAL_TARGETS + freertos-cmsis-rtos ) -elseif(TARGET cmsis-rtx) - target_link_libraries(cmsis-rtos-implementation - INTERFACE - cmsis-rtx - cmsis-rtos-api - cmsis-rtx-freertos-alloc-wrapper +endif() + +if("mbedtls" IN_LIST IOTSDK_FETCH_LIST) + list(APPEND EXTERNAL_TARGETS + mbedtls + mbedtls-config + mbedtls-threading-cmsis-rtos ) endif() +if("lwip" IN_LIST IOTSDK_FETCH_LIST) + list(APPEND EXTERNAL_TARGETS + lwipcore + lwip-cmsis-port + lwip-cmsis-sys + lwip-cmsis-port-low-input-latency + lwipopts + ) +endif() + +if("cmsis-sockets-api" IN_LIST IOTSDK_FETCH_LIST) + list(APPEND EXTERNAL_TARGETS + cmsis-sockets-api + lwip-sockets + ) +endif() + +if("trusted-firmware-m" IN_LIST IOTSDK_FETCH_LIST) + list(APPEND EXTERNAL_TARGETS + tfm-ns-interface + tfm-ns-interface-cmsis-rtos + ) +endif() + +# Additional Open IoT SDK port components + # Add Open IoT SDK storage source add_subdirectory(${OPEN_IOT_SDK_STORAGE_SOURCE} ./sdk_storage_build) -list(APPEND SDK_SOURCES_BINARY_DIRS ${CMAKE_CURRENT_BINARY_DIR}/sdk_storage_build) +list(APPEND EXTERNAL_TARGETS + iotsdk-blockdevice + iotsdk-tdbstore +) + +# Add custom storage library +add_subdirectory(${OPEN_IOT_SDK_CONFIG}/storage storage_build) +list(APPEND EXTERNAL_TARGETS + openiotsdk-storage +) + +function(sdk_post_build target) + string(REPLACE "_ns" "" APP_NAME ${APP_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) + # Cleanup + add_custom_command( + TARGET + ${APP_TARGET} + POST_BUILD + DEPENDS + $/tfm_s_signed.bin + $/${APP_TARGET}.bin + $/${APP_TARGET}_signed.bin + $/${APP_TARGET}_merged.hex + $/${APP_TARGET}_merged.elf + COMMAND + # Copy the TF-M secure elf image + ${CMAKE_COMMAND} -E copy + ${BINARY_DIR}/install/outputs/tfm_s.elf + $/ + COMMAND + # Rename output file + ${CMAKE_COMMAND} -E copy + $/${APP_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 + VERBATIM + ) +else() + add_custom_command( + TARGET + ${APP_TARGET} + POST_BUILD + DEPENDS + $/${APP_TARGET}.elf + $/${APP_TARGET}.map + COMMAND + # Rename output elf file + ${CMAKE_COMMAND} -E copy + $/${APP_TARGET}.elf + $/${APP_NAME}.elf + COMMAND + # Rename output map file + ${CMAKE_COMMAND} -E copy + $/${APP_TARGET}.map + $/${APP_NAME}.map + COMMAND rm + ARGS -Rf + $/${APP_TARGET}.elf + $/${APP_TARGET}.map + VERBATIM + ) +endif() #TFM_SUPPORT +endfunction() diff --git a/config/openiotsdk/ld/cs300_gcc.ld b/config/openiotsdk/ld/cs300_gcc.ld index 850e91200bc0d5..97ec041ff09ed6 100644 --- a/config/openiotsdk/ld/cs300_gcc.ld +++ b/config/openiotsdk/ld/cs300_gcc.ld @@ -1,4 +1,20 @@ -; +/* + * + * 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. + */ + MEMORY { ITCM (rx) : ORIGIN = 0x00000000, LENGTH = 32K diff --git a/config/openiotsdk/ld/cs300_gcc_tfm.ld b/config/openiotsdk/ld/cs300_gcc_tfm.ld new file mode 100644 index 00000000000000..523c96e8efb77c --- /dev/null +++ b/config/openiotsdk/ld/cs300_gcc_tfm.ld @@ -0,0 +1,172 @@ +/* + * + * 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. + */ + +MEMORY +{ + FLASH (rx) : ORIGIN = ((0x28000000) + (0x60000) + (0x400)), LENGTH = ((0x200000) - (0x400) - (0x800)) + RAM (rwx) : ORIGIN = 0x21000000, LENGTH = 0x100000 +} + +__stack_size__ = 0x1000; + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a libnosys.a) + +SECTIONS +{ + .text : + { + KEEP(*(.vectors)) + __Vectors_End = .; + __Vectors_Size = __Vectors_End - __Vectors; + __end__ = .; + + *(.text*) + + KEEP(*(.init)) + KEEP(*(.fini)) + + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + + KEEP(*(.eh_frame*)) + } > FLASH + + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > FLASH + + __exidx_start = .; + + .ARM.exidx : + { + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } > FLASH + + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * define etext2/data2_start/data2_end */ + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (DEFINED(__etext2) ? __etext2 : 0) + LONG (DEFINED(__data2_start__) ? __data2_start__ : 0) + LONG (DEFINED(__data2_start__) ? __data2_end__ - __data2_start__ : 0) + __copy_table_end__ = .; + } > FLASH + + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (DEFINED(__bss2_start__) ? __bss2_start__ : 0) + LONG (DEFINED(__bss2_start__) ? __bss2_end__ - __bss2_start__ : 0) + __zero_table_end__ = .; + } > FLASH + + __etext = .; + + .data : AT (__etext) + { + __data_start__ = .; + *(vtable) + *(.data*) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + . = ALIGN(4); + /* All data end */ + __data_end__ = .; + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + bss_size = __bss_end__ - __bss_start__; + + .stack : + { + . = ALIGN(8); + __StackLimit = .; + KEEP(*(.stack*)) + . += __stack_size__; + __StackTop = .; + } > RAM + PROVIDE(__stack = __StackTop); + + .heap (COPY): + { + . = ALIGN(8); + __HeapBase = .; + __end__ = .; + end = __end__; + KEEP(*(.heap*)) + . += (ORIGIN(RAM) + LENGTH(RAM) - .); + __HeapLimit = .; + __heap_limit = .; + } > RAM + + ASSERT(__HeapLimit <= (ORIGIN(RAM) + LENGTH(RAM)), "RAM region overflowed") +} diff --git a/config/openiotsdk/mbedtls/mbedtls_config.h b/config/openiotsdk/mbedtls/mbedtls_config.h index e12878adf14986..316d43c67940d0 100644 --- a/config/openiotsdk/mbedtls/mbedtls_config.h +++ b/config/openiotsdk/mbedtls/mbedtls_config.h @@ -24,12 +24,14 @@ * limitations under the License. */ -#ifndef MBEDTLS_CONFIG_H -#define MBEDTLS_CONFIG_H - -#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) -#define _CRT_SECURE_NO_DEPRECATE 1 -#endif +/** + * This is an optional version symbol that enables compatibility handling of + * config files. + * + * It is equal to the #MBEDTLS_VERSION_NUMBER of the Mbed TLS version that + * introduced the config format we want to be compatible with. + */ +//#define MBEDTLS_CONFIG_VERSION 0x03000000 /** * \name SECTION: System support @@ -47,8 +49,7 @@ * * Used in: * library/aria.c - * library/timing.c - * include/mbedtls/bn_mul.h + * library/bn_mul.h * * Required by: * MBEDTLS_AESNI_C @@ -128,7 +129,12 @@ * MBEDTLS_PLATFORM_TIME_MACRO, MBEDTLS_PLATFORM_TIME_TYPE_MACRO and * MBEDTLS_PLATFORM_STD_TIME. * - * Comment if your system does not support time functions + * Comment if your system does not support time functions. + * + * \note If MBEDTLS_TIMING_C is set - to enable the semi-portable timing + * interface - timing.c will include time.h on suitable platforms + * regardless of the setting of MBEDTLS_HAVE_TIME, unless + * MBEDTLS_TIMING_ALT is used. See timing.c for more information. */ #define MBEDTLS_HAVE_TIME @@ -219,6 +225,7 @@ * Uncomment a macro to enable alternate implementation of specific base * platform function */ +//#define MBEDTLS_PLATFORM_SETBUF_ALT //#define MBEDTLS_PLATFORM_EXIT_ALT //#define MBEDTLS_PLATFORM_TIME_ALT //#define MBEDTLS_PLATFORM_FPRINTF_ALT @@ -255,73 +262,7 @@ */ //#define MBEDTLS_DEPRECATED_REMOVED -/** - * \def MBEDTLS_CHECK_PARAMS - * - * This configuration option controls whether the library validates more of - * the parameters passed to it. - * - * When this flag is not defined, the library only attempts to validate an - * input parameter if: (1) they may come from the outside world (such as the - * network, the filesystem, etc.) or (2) not validating them could result in - * internal memory errors such as overflowing a buffer controlled by the - * library. On the other hand, it doesn't attempt to validate parameters whose - * values are fully controlled by the application (such as pointers). - * - * When this flag is defined, the library additionally attempts to validate - * parameters that are fully controlled by the application, and should always - * be valid if the application code is fully correct and trusted. - * - * For example, when a function accepts as input a pointer to a buffer that may - * contain untrusted data, and its documentation mentions that this pointer - * must not be NULL: - * - The pointer is checked to be non-NULL only if this option is enabled. - * - The content of the buffer is always validated. - * - * When this flag is defined, if a library function receives a parameter that - * is invalid: - * 1. The function will invoke the macro MBEDTLS_PARAM_FAILED(). - * 2. If MBEDTLS_PARAM_FAILED() did not terminate the program, the function - * will immediately return. If the function returns an Mbed TLS error code, - * the error code in this case is MBEDTLS_ERR_xxx_BAD_INPUT_DATA. - * - * When defining this flag, you also need to arrange a definition for - * MBEDTLS_PARAM_FAILED(). You can do this by any of the following methods: - * - By default, the library defines MBEDTLS_PARAM_FAILED() to call a - * function mbedtls_param_failed(), but the library does not define this - * function. If you do not make any other arrangements, you must provide - * the function mbedtls_param_failed() in your application. - * See `platform_util.h` for its prototype. - * - If you enable the macro #MBEDTLS_CHECK_PARAMS_ASSERT, then the - * library defines MBEDTLS_PARAM_FAILED(\c cond) to be `assert(cond)`. - * You can still supply an alternative definition of - * MBEDTLS_PARAM_FAILED(), which may call `assert`. - * - If you define a macro MBEDTLS_PARAM_FAILED() before including `config.h` - * or you uncomment the definition of MBEDTLS_PARAM_FAILED() in `config.h`, - * the library will call the macro that you defined and will not supply - * its own version. Note that if MBEDTLS_PARAM_FAILED() calls `assert`, - * you need to enable #MBEDTLS_CHECK_PARAMS_ASSERT so that library source - * files include ``. - * - * Uncomment to enable validation of application-controlled parameters. - */ -//#define MBEDTLS_CHECK_PARAMS - -/** - * \def MBEDTLS_CHECK_PARAMS_ASSERT - * - * Allow MBEDTLS_PARAM_FAILED() to call `assert`, and make it default to - * `assert`. This macro is only used if #MBEDTLS_CHECK_PARAMS is defined. - * - * If this macro is not defined, then MBEDTLS_PARAM_FAILED() defaults to - * calling a function mbedtls_param_failed(). See the documentation of - * #MBEDTLS_CHECK_PARAMS for details. - * - * Uncomment to allow MBEDTLS_PARAM_FAILED() to call `assert`. - */ -//#define MBEDTLS_CHECK_PARAMS_ASSERT - -/* \} name SECTION: System support */ +/** \} name SECTION: System support */ /** * \name SECTION: mbed TLS feature support @@ -334,7 +275,7 @@ /** * \def MBEDTLS_TIMING_ALT * - * Uncomment to provide your own alternate implementation for mbedtls_timing_hardclock(), + * Uncomment to provide your own alternate implementation for * mbedtls_timing_get_timer(), mbedtls_set_alarm(), mbedtls_set/get_delay() * * Only works if you have MBEDTLS_TIMING_C enabled. @@ -363,16 +304,14 @@ * Uncomment a macro to enable alternate implementation of the corresponding * module. * - * \warning MD2, MD4, MD5, ARC4, DES and SHA-1 are considered weak and their + * \warning MD5, DES and SHA-1 are considered weak and their * use constitutes a security risk. If possible, we recommend * avoiding dependencies on them, and considering stronger message * digests and ciphers instead. * */ //#define MBEDTLS_AES_ALT -//#define MBEDTLS_ARC4_ALT //#define MBEDTLS_ARIA_ALT -//#define MBEDTLS_BLOWFISH_ALT //#define MBEDTLS_CAMELLIA_ALT //#define MBEDTLS_CCM_ALT //#define MBEDTLS_CHACHA20_ALT @@ -383,8 +322,6 @@ //#define MBEDTLS_ECJPAKE_ALT //#define MBEDTLS_GCM_ALT //#define MBEDTLS_NIST_KW_ALT -//#define MBEDTLS_MD2_ALT -//#define MBEDTLS_MD4_ALT //#define MBEDTLS_MD5_ALT //#define MBEDTLS_POLY1305_ALT //#define MBEDTLS_RIPEMD160_ALT @@ -392,10 +329,9 @@ //#define MBEDTLS_SHA1_ALT //#define MBEDTLS_SHA256_ALT //#define MBEDTLS_SHA512_ALT -//#define MBEDTLS_XTEA_ALT /* - * When replacing the elliptic curve module, pleace consider, that it is + * When replacing the elliptic curve module, please consider, that it is * implemented with two .c files: * - ecp.c * - ecp_curves.c @@ -406,7 +342,7 @@ //#define MBEDTLS_ECP_ALT /** - * \def MBEDTLS_MD2_PROCESS_ALT + * \def MBEDTLS_SHA256_PROCESS_ALT * * MBEDTLS__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use you * alternate core implementation of symmetric crypto or hash function. Keep in @@ -421,20 +357,14 @@ * of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible * with this definition. * - * \note Because of a signature change, the core AES encryption and decryption routines are - * currently named mbedtls_aes_internal_encrypt and mbedtls_aes_internal_decrypt, - * respectively. When setting up alternative implementations, these functions should - * be overridden, but the wrapper functions mbedtls_aes_decrypt and mbedtls_aes_encrypt - * must stay untouched. - * - * \note If you use the AES_xxx_ALT macros, then is is recommended to also set + * \note If you use the AES_xxx_ALT macros, then it is recommended to also set * MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES * tables. * * Uncomment a macro to enable alternate implementation of the corresponding * function. * - * \warning MD2, MD4, MD5, DES and SHA-1 are considered weak and their use + * \warning MD5, DES and SHA-1 are considered weak and their use * constitutes a security risk. If possible, we recommend avoiding * dependencies on them, and considering stronger message digests * and ciphers instead. @@ -445,13 +375,9 @@ * alternative implementations should use the RNG only for generating * the ephemeral key and nothing else. If this is not possible, then * MBEDTLS_ECDSA_DETERMINISTIC should be disabled and an alternative - * implementation should be provided for mbedtls_ecdsa_sign_det_ext() - * (and for mbedtls_ecdsa_sign_det() too if backward compatibility is - * desirable). + * implementation should be provided for mbedtls_ecdsa_sign_det_ext(). * */ -//#define MBEDTLS_MD2_PROCESS_ALT -//#define MBEDTLS_MD4_PROCESS_ALT //#define MBEDTLS_MD5_PROCESS_ALT //#define MBEDTLS_RIPEMD160_PROCESS_ALT //#define MBEDTLS_SHA1_PROCESS_ALT @@ -535,23 +461,6 @@ //#define MBEDTLS_ECP_RANDOMIZE_MXZ_ALT //#define MBEDTLS_ECP_NORMALIZE_MXZ_ALT -/** - * \def MBEDTLS_TEST_NULL_ENTROPY - * - * Enables testing and use of mbed TLS without any configured entropy sources. - * This permits use of the library on platforms before an entropy source has - * been integrated (see for example the MBEDTLS_ENTROPY_HARDWARE_ALT or the - * MBEDTLS_ENTROPY_NV_SEED switches). - * - * WARNING! This switch MUST be disabled in production builds, and is suitable - * only for development. - * Enabling the switch negates any security provided by the library. - * - * Requires MBEDTLS_ENTROPY_C, MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES - * - */ -//#define MBEDTLS_TEST_NULL_ENTROPY - /** * \def MBEDTLS_ENTROPY_HARDWARE_ALT * @@ -559,7 +468,8 @@ * hardware entropy collector. * * Your function must be called \c mbedtls_hardware_poll(), have the same - * prototype as declared in entropy_poll.h, and accept NULL as first argument. + * prototype as declared in library/entropy_poll.h, and accept NULL as first + * argument. * * Uncomment to use your own hardware entropy collector. */ @@ -616,6 +526,29 @@ */ //#define MBEDTLS_CAMELLIA_SMALL_MEMORY +/** + * \def MBEDTLS_CHECK_RETURN_WARNING + * + * If this macro is defined, emit a compile-time warning if application code + * calls a function without checking its return value, but the return value + * should generally be checked in portable applications. + * + * This is only supported on platforms where #MBEDTLS_CHECK_RETURN is + * implemented. Otherwise this option has no effect. + * + * Uncomment to get warnings on using fallible functions without checking + * their return value. + * + * \note This feature is a work in progress. + * Warnings will be added to more functions in the future. + * + * \note A few functions are considered critical, and ignoring the return + * value of these functions will trigger a warning even if this + * macro is not defined. To completely disable return value check + * warnings, define #MBEDTLS_CHECK_RETURN with an empty expansion. + */ +//#define MBEDTLS_CHECK_RETURN_WARNING + /** * \def MBEDTLS_CIPHER_MODE_CBC * @@ -658,8 +591,7 @@ * Warning: Only do so when you know what you are doing. This allows for * encryption or channels without any security! * - * Requires MBEDTLS_ENABLE_WEAK_CIPHERSUITES as well to enable - * the following ciphersuites: + * To enable the following ciphersuites: * MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA * MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA @@ -707,57 +639,6 @@ */ //#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY -/** - * \def MBEDTLS_ENABLE_WEAK_CIPHERSUITES - * - * Enable weak ciphersuites in SSL / TLS. - * Warning: Only do so when you know what you are doing. This allows for - * channels with virtually no security at all! - * - * This enables the following ciphersuites: - * MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA - * MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA - * - * Uncomment this macro to enable weak ciphersuites - * - * \warning DES is considered a weak cipher and its use constitutes a - * security risk. We recommend considering stronger ciphers instead. - */ -//#define MBEDTLS_ENABLE_WEAK_CIPHERSUITES - -/** - * \def MBEDTLS_REMOVE_ARC4_CIPHERSUITES - * - * Remove RC4 ciphersuites by default in SSL / TLS. - * This flag removes the ciphersuites based on RC4 from the default list as - * returned by mbedtls_ssl_list_ciphersuites(). However, it is still possible to - * enable (some of) them with mbedtls_ssl_conf_ciphersuites() by including them - * explicitly. - * - * Uncomment this macro to remove RC4 ciphersuites by default. - */ -#define MBEDTLS_REMOVE_ARC4_CIPHERSUITES - -/** - * \def MBEDTLS_REMOVE_3DES_CIPHERSUITES - * - * Remove 3DES ciphersuites by default in SSL / TLS. - * This flag removes the ciphersuites based on 3DES from the default list as - * returned by mbedtls_ssl_list_ciphersuites(). However, it is still possible - * to enable (some of) them with mbedtls_ssl_conf_ciphersuites() by including - * them explicitly. - * - * A man-in-the-browser attacker can recover authentication tokens sent through - * a TLS connection using a 3DES based cipher suite (see "On the Practical - * (In-)Security of 64-bit Block Ciphers" by Karthikeyan Bhargavan and Gaëtan - * Leurent, see https://sweet32.info/SWEET32_CCS16.pdf). If this attack falls - * in your threat model or you are unsure, then you should keep this option - * enabled to remove 3DES based cipher suites. - * - * Comment this macro to keep 3DES in the default ciphersuite list. - */ -#define MBEDTLS_REMOVE_3DES_CIPHERSUITES - /** * \def MBEDTLS_ECP_DP_SECP192R1_ENABLED * @@ -793,28 +674,6 @@ */ #define MBEDTLS_ECP_NIST_OPTIM -/** - * \def MBEDTLS_ECP_NO_INTERNAL_RNG - * - * When this option is disabled, mbedtls_ecp_mul() will make use of an - * internal RNG when called with a NULL \c f_rng argument, in order to protect - * against some side-channel attacks. - * - * This protection introduces a dependency of the ECP module on one of the - * DRBG modules. For very constrained implementations that don't require this - * protection (for example, because you're only doing signature verification, - * so not manipulating any secret, or because local/physical side-channel - * attacks are outside your threat model), it might be desirable to get rid of - * that dependency. - * - * \warning Enabling this option makes some uses of ECP vulnerable to some - * side-channel attacks. Only enable it if you know that's not a problem for - * your use case. - * - * Uncomment this macro to disable some counter-measures in ECP. - */ -//#define MBEDTLS_ECP_NO_INTERNAL_RNG - /** * \def MBEDTLS_ECP_RESTARTABLE * @@ -835,39 +694,10 @@ * * \note This option only works with the default software implementation of * elliptic curve functionality. It is incompatible with - * MBEDTLS_ECP_ALT, MBEDTLS_ECDH_XXX_ALT, MBEDTLS_ECDSA_XXX_ALT - * and MBEDTLS_ECDH_LEGACY_CONTEXT. + * MBEDTLS_ECP_ALT, MBEDTLS_ECDH_XXX_ALT, MBEDTLS_ECDSA_XXX_ALT. */ //#define MBEDTLS_ECP_RESTARTABLE -/** - * \def MBEDTLS_ECDH_LEGACY_CONTEXT - * - * Use a backward compatible ECDH context. - * - * Mbed TLS supports two formats for ECDH contexts (#mbedtls_ecdh_context - * defined in `ecdh.h`). For most applications, the choice of format makes - * no difference, since all library functions can work with either format, - * except that the new format is incompatible with MBEDTLS_ECP_RESTARTABLE. - - * The new format used when this option is disabled is smaller - * (56 bytes on a 32-bit platform). In future versions of the library, it - * will support alternative implementations of ECDH operations. - * The new format is incompatible with applications that access - * context fields directly and with restartable ECP operations. - * - * Define this macro if you enable MBEDTLS_ECP_RESTARTABLE or if you - * want to access ECDH context fields directly. Otherwise you should - * comment out this macro definition. - * - * This option has no effect if #MBEDTLS_ECDH_C is not enabled. - * - * \note This configuration option is experimental. Future versions of the - * library may modify the way the ECDH context layout is configured - * and may modify the layout of the new context type. - */ -//#define MBEDTLS_ECDH_LEGACY_CONTEXT - /** * \def MBEDTLS_ECDSA_DETERMINISTIC * @@ -899,8 +729,6 @@ * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 - * MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_PSK_WITH_RC4_128_SHA */ //#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED @@ -923,8 +751,6 @@ * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 - * MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA * * \warning Using DHE constitutes a security risk as it * is not possible to validate custom DH parameters. @@ -950,8 +776,6 @@ * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 - * MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA */ //#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED @@ -975,8 +799,6 @@ * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 - * MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA */ //#define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED @@ -1002,9 +824,6 @@ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - * MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_RSA_WITH_RC4_128_SHA - * MBEDTLS_TLS_RSA_WITH_RC4_128_MD5 */ //#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED @@ -1030,7 +849,6 @@ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA - * MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA * * \warning Using DHE constitutes a security risk as it * is not possible to validate custom DH parameters. @@ -1061,8 +879,6 @@ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 - * MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA */ #define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED @@ -1085,8 +901,6 @@ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 - * MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA */ #define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED @@ -1099,8 +913,6 @@ * * This enables the following ciphersuites (if other requisites are * enabled as well): - * MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA - * MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 @@ -1123,8 +935,6 @@ * * This enables the following ciphersuites (if other requisites are * enabled as well): - * MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA - * MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 @@ -1205,8 +1015,7 @@ /** * \def MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES * - * Do not add default entropy sources. These are the platform specific, - * mbedtls_timing_hardclock and HAVEGE based poll functions. + * Do not add default entropy sources in mbedtls_entropy_init(). * * This is useful to have more control over the added entropy sources in an * application. @@ -1278,7 +1087,7 @@ * which is currently hard-coded to be int32_t. * * Note that this option is meant for internal use only and may be removed - * without notice. It is incompatible with MBEDTLS_USE_PSA_CRYPTO. + * without notice. */ //#define MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER @@ -1321,7 +1130,7 @@ * * Enable support for PKCS#1 v1.5 encoding. * - * Requires: MBEDTLS_RSA_C + * Requires: MBEDTLS_MD_C, MBEDTLS_RSA_C * * This enables support for PKCS#1 v1.5 operations. */ @@ -1338,6 +1147,22 @@ */ //#define MBEDTLS_PKCS1_V21 +/** \def MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS + * + * Enable support for platform built-in keys. If you enable this feature, + * you must implement the function mbedtls_psa_platform_get_builtin_key(). + * See the documentation of that function for more information. + * + * Built-in keys are typically derived from a hardware unique key or + * stored in a secure element. + * + * Requires: MBEDTLS_PSA_CRYPTO_C. + * + * \warning This interface is experimental and may change or be removed + * without notice. + */ +//#define MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS + /** \def MBEDTLS_PSA_CRYPTO_CLIENT * * Enable support for PSA crypto client. @@ -1360,8 +1185,9 @@ * * Requires: MBEDTLS_PSA_CRYPTO_C * - * \warning This interface is experimental and may change or be removed - * without notice. + * \warning This interface is experimental. We intend to maintain backward + * compatibility with application code that relies on drivers, + * but the driver interfaces may change without notice. */ //#define MBEDTLS_PSA_CRYPTO_DRIVERS @@ -1454,7 +1280,7 @@ * Enable an implementation of SHA-256 that has lower ROM footprint but also * lower performance. * - * The default implementation is meant to be a reasonnable compromise between + * The default implementation is meant to be a reasonable compromise between * performance and size. This version optimizes more aggressively for size at * the expense of performance. Eg on Cortex-M4 it reduces the size of * mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about @@ -1474,18 +1300,6 @@ */ //#define MBEDTLS_SHA512_SMALLER -/** - * \def MBEDTLS_SHA512_NO_SHA384 - * - * Disable the SHA-384 option of the SHA-512 module. Use this to save some - * code size on devices that don't use SHA-384. - * - * Requires: MBEDTLS_SHA512_C - * - * Uncomment to disable SHA-384 - */ -//#define MBEDTLS_SHA512_NO_SHA384 - /** * \def MBEDTLS_SSL_ALL_ALERT_MESSAGES * @@ -1500,20 +1314,6 @@ */ #define MBEDTLS_SSL_ALL_ALERT_MESSAGES -/** - * \def MBEDTLS_SSL_RECORD_CHECKING - * - * Enable the function mbedtls_ssl_check_record() which can be used to check - * the validity and authenticity of an incoming record, to verify that it has - * not been seen before. These checks are performed without modifying the - * externally visible state of the SSL context. - * - * See mbedtls_ssl_check_record() for more information. - * - * Uncomment to enable support for record checking. - */ -//#define MBEDTLS_SSL_RECORD_CHECKING - /** * \def MBEDTLS_SSL_DTLS_CONNECTION_ID * @@ -1524,8 +1324,9 @@ * in the underlying transport. * * Setting this option enables the SSL APIs `mbedtls_ssl_set_cid()`, - * `mbedtls_ssl_get_peer_cid()` and `mbedtls_ssl_conf_cid()`. - * See the corresponding documentation for more information. + * mbedtls_ssl_get_own_cid()`, `mbedtls_ssl_get_peer_cid()` and + * `mbedtls_ssl_conf_cid()`. See the corresponding documentation for + * more information. * * \warning The Connection ID extension is still in draft state. * We make no stability promises for the availability @@ -1606,9 +1407,7 @@ * * This only affects CBC ciphersuites, and is useless if none is defined. * - * Requires: MBEDTLS_SSL_PROTO_TLS1 or - * MBEDTLS_SSL_PROTO_TLS1_1 or - * MBEDTLS_SSL_PROTO_TLS1_2 + * Requires: MBEDTLS_SSL_PROTO_TLS1_2 * * Comment this macro to disable support for Encrypt-then-MAC */ @@ -1619,37 +1418,17 @@ * Enable support for RFC 7627: Session Hash and Extended Master Secret * Extension. * - * This was introduced as "the proper fix" to the Triple Handshake familiy of + * This was introduced as "the proper fix" to the Triple Handshake family of * attacks, but it is recommended to always use it (even if you disable * renegotiation), since it actually fixes a more fundamental issue in the * original SSL/TLS design, and has implications beyond Triple Handshake. * - * Requires: MBEDTLS_SSL_PROTO_TLS1 or - * MBEDTLS_SSL_PROTO_TLS1_1 or - * MBEDTLS_SSL_PROTO_TLS1_2 + * Requires: MBEDTLS_SSL_PROTO_TLS1_2 * * Comment this macro to disable support for Extended Master Secret. */ #define MBEDTLS_SSL_EXTENDED_MASTER_SECRET -/** - * \def MBEDTLS_SSL_FALLBACK_SCSV - * - * Enable support for RFC 7507: Fallback Signaling Cipher Suite Value (SCSV) - * for Preventing Protocol Downgrade Attacks. - * - * For servers, it is recommended to always enable this, unless you support - * only one version of TLS, or know for sure that none of your clients - * implements a fallback strategy. - * - * For clients, you only need this if you're using a fallback strategy, which - * is not recommended in the first place, unless you absolutely need it to - * interoperate with buggy (version-intolerant) servers. - * - * Comment this macro to disable support for FALLBACK_SCSV - */ -//#define MBEDTLS_SSL_FALLBACK_SCSV - /** * \def MBEDTLS_SSL_KEEP_PEER_CERTIFICATE * @@ -1665,38 +1444,15 @@ * \note This option has no influence on the protection against the * triple handshake attack. Even if it is disabled, Mbed TLS will * still ensure that certificates do not change during renegotiation, - * for exaple by keeping a hash of the peer's certificate. + * for example by keeping a hash of the peer's certificate. + * + * \note This option is required if MBEDTLS_SSL_PROTO_TLS1_3 is set. * * Comment this macro to disable storing the peer's certificate * after the handshake. */ //#define MBEDTLS_SSL_KEEP_PEER_CERTIFICATE -/** - * \def MBEDTLS_SSL_HW_RECORD_ACCEL - * - * Enable hooking functions in SSL module for hardware acceleration of - * individual records. - * - * \deprecated This option is deprecated and will be removed in a future - * version of Mbed TLS. - * - * Uncomment this macro to enable hooking functions. - */ -//#define MBEDTLS_SSL_HW_RECORD_ACCEL - -/** - * \def MBEDTLS_SSL_CBC_RECORD_SPLITTING - * - * Enable 1/n-1 record splitting for CBC mode in SSLv3 and TLS 1.0. - * - * This is a countermeasure to the BEAST attack, which also minimizes the risk - * of interoperability issues compared to sending 0-length records. - * - * Comment this macro to disable 1/n-1 record splitting. - */ -//#define MBEDTLS_SSL_CBC_RECORD_SPLITTING - /** * \def MBEDTLS_SSL_RENEGOTIATION * @@ -1719,29 +1475,6 @@ */ //#define MBEDTLS_SSL_RENEGOTIATION -/** - * \def MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO - * - * Enable support for receiving and parsing SSLv2 Client Hello messages for the - * SSL Server module (MBEDTLS_SSL_SRV_C). - * - * \deprecated This option is deprecated and will be removed in a future - * version of Mbed TLS. - * - * Uncomment this macro to enable support for SSLv2 Client Hello messages. - */ -//#define MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO - -/** - * \def MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE - * - * Pick the ciphersuite according to the client's preferences rather than ours - * in the SSL Server module (MBEDTLS_SSL_SRV_C). - * - * Uncomment this macro to respect client's ciphersuite order - */ -//#define MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE - /** * \def MBEDTLS_SSL_MAX_FRAGMENT_LENGTH * @@ -1752,85 +1485,70 @@ #define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH /** - * \def MBEDTLS_SSL_PROTO_SSL3 - * - * Enable support for SSL 3.0. + * \def MBEDTLS_SSL_PROTO_TLS1_2 * - * Requires: MBEDTLS_MD5_C - * MBEDTLS_SHA1_C + * Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled). * - * \deprecated This option is deprecated and will be removed in a future - * version of Mbed TLS. + * Requires: MBEDTLS_SHA1_C or MBEDTLS_SHA256_C or MBEDTLS_SHA512_C + * (Depends on ciphersuites) * - * Comment this macro to disable support for SSL 3.0 + * Comment this macro to disable support for TLS 1.2 / DTLS 1.2 */ -//#define MBEDTLS_SSL_PROTO_SSL3 +#define MBEDTLS_SSL_PROTO_TLS1_2 /** - * \def MBEDTLS_SSL_PROTO_TLS1 - * - * Enable support for TLS 1.0. + * \def MBEDTLS_SSL_PROTO_TLS1_3 * - * Requires: MBEDTLS_MD5_C - * MBEDTLS_SHA1_C + * Enable support for TLS 1.3. * - * Comment this macro to disable support for TLS 1.0 - */ -//#define MBEDTLS_SSL_PROTO_TLS1 - -/** - * \def MBEDTLS_SSL_PROTO_TLS1_1 + * \note The support for TLS 1.3 is not comprehensive yet, in particular + * pre-shared keys are not supported. + * See docs/architecture/tls13-support.md for a description of the TLS + * 1.3 support that this option enables. * - * Enable support for TLS 1.1 (and DTLS 1.0 if DTLS is enabled). + * Requires: MBEDTLS_SSL_KEEP_PEER_CERTIFICATE + * Requires: MBEDTLS_PSA_CRYPTO_C * - * Requires: MBEDTLS_MD5_C - * MBEDTLS_SHA1_C + * Note: even though TLS 1.3 depends on PSA Crypto, if you want it to only use + * PSA for all crypto operations, you need to also enable + * MBEDTLS_USE_PSA_CRYPTO; otherwise X.509 operations, and functions that are + * common with TLS 1.2 (record protection, running handshake hash) will still + * use non-PSA crypto. * - * Comment this macro to disable support for TLS 1.1 / DTLS 1.0 + * Uncomment this macro to enable the support for TLS 1.3. */ -//#define MBEDTLS_SSL_PROTO_TLS1_1 +//#define MBEDTLS_SSL_PROTO_TLS1_3 /** - * \def MBEDTLS_SSL_PROTO_TLS1_2 - * - * Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled). + * \def MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE * - * Requires: MBEDTLS_SHA1_C or MBEDTLS_SHA256_C or MBEDTLS_SHA512_C - * (Depends on ciphersuites) + * Enable TLS 1.3 middlebox compatibility mode. * - * Comment this macro to disable support for TLS 1.2 / DTLS 1.2 - */ -#define MBEDTLS_SSL_PROTO_TLS1_2 - -/** - * \def MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL + * As specified in Section D.4 of RFC 8446, TLS 1.3 offers a compatibility + * mode to make a TLS 1.3 connection more likely to pass through middle boxes + * expecting TLS 1.2 traffic. * - * This macro is used to selectively enable experimental parts - * of the code that contribute to the ongoing development of - * the prototype TLS 1.3 and DTLS 1.3 implementation, and provide - * no other purpose. + * Turning on the compatibility mode comes at the cost of a few added bytes + * on the wire, but it doesn't affect compatibility with TLS 1.3 implementations + * that don't use it. Therefore, unless transmission bandwidth is critical and + * you know that middlebox compatibility issues won't occur, it is therefore + * recommended to set this option. * - * \warning TLS 1.3 and DTLS 1.3 aren't yet supported in Mbed TLS, - * and no feature exposed through this macro is part of the - * public API. In particular, features under the control - * of this macro are experimental and don't come with any - * stability guarantees. + * Comment to disable compatibility mode for TLS 1.3. If + * MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not have any + * effect on the build. * - * Uncomment this macro to enable experimental and partial - * functionality specific to TLS 1.3. */ -//#define MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL +//#define MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE /** * \def MBEDTLS_SSL_PROTO_DTLS * * Enable support for DTLS (all available versions). * - * Enable this and MBEDTLS_SSL_PROTO_TLS1_1 to enable DTLS 1.0, - * and/or this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2. + * Enable this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2. * - * Requires: MBEDTLS_SSL_PROTO_TLS1_1 - * or MBEDTLS_SSL_PROTO_TLS1_2 + * Requires: MBEDTLS_SSL_PROTO_TLS1_2 * * Comment this macro to disable support for DTLS */ @@ -1870,7 +1588,7 @@ * unless you know for sure amplification cannot be a problem in the * environment in which your server operates. * - * \warning Disabling this can ba a security risk! (see above) + * \warning Disabling this can be a security risk! (see above) * * Requires: MBEDTLS_SSL_PROTO_DTLS * @@ -1892,7 +1610,7 @@ * (see Section 5 of RFC 5764), are not handled by this feature. * Instead, after successful completion of a handshake negotiating * the use of DTLS-SRTP, the extended key exporter API - * mbedtls_ssl_conf_export_keys_ext_cb() should be used to implement + * mbedtls_ssl_conf_export_keys_cb() should be used to implement * the key exporter described in Section 4.2 of RFC 5764 and RFC 5705 * (this is implemented in the SSL example programs). * The resulting key should then be passed to an SRTP stack. @@ -1925,17 +1643,6 @@ */ //#define MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE -/** - * \def MBEDTLS_SSL_DTLS_BADMAC_LIMIT - * - * Enable support for a limit of records with bad MAC. - * - * See mbedtls_ssl_conf_dtls_badmac_limit(). - * - * Requires: MBEDTLS_SSL_PROTO_DTLS - */ -//#define MBEDTLS_SSL_DTLS_BADMAC_LIMIT - /** * \def MBEDTLS_SSL_SESSION_TICKETS * @@ -1950,16 +1657,6 @@ */ //#define MBEDTLS_SSL_SESSION_TICKETS -/** - * \def MBEDTLS_SSL_EXPORT_KEYS - * - * Enable support for exporting key block and master secret. - * This is required for certain users of TLS, e.g. EAP-TLS. - * - * Comment this macro to disable support for key export - */ -//#define MBEDTLS_SSL_EXPORT_KEYS - /** * \def MBEDTLS_SSL_SERVER_NAME_INDICATION * @@ -1971,39 +1668,6 @@ */ #define MBEDTLS_SSL_SERVER_NAME_INDICATION -/** - * \def MBEDTLS_SSL_TRUNCATED_HMAC - * - * Enable support for RFC 6066 truncated HMAC in SSL. - * - * Comment this macro to disable support for truncated HMAC in SSL - */ -//#define MBEDTLS_SSL_TRUNCATED_HMAC - -/** - * \def MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT - * - * Fallback to old (pre-2.7), non-conforming implementation of the truncated - * HMAC extension which also truncates the HMAC key. Note that this option is - * only meant for a transitory upgrade period and will be removed in a future - * version of the library. - * - * \warning The old implementation is non-compliant and has a security weakness - * (2^80 brute force attack on the HMAC key used for a single, - * uninterrupted connection). This should only be enabled temporarily - * when (1) the use of truncated HMAC is essential in order to save - * bandwidth, and (2) the peer is an Mbed TLS stack that doesn't use - * the fixed implementation yet (pre-2.7). - * - * \deprecated This option is deprecated and will be removed in a - * future version of Mbed TLS. - * - * Uncomment to fallback to old, non-compliant truncated HMAC implementation. - * - * Requires: MBEDTLS_SSL_TRUNCATED_HMAC - */ -//#define MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT - /** * \def MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH * @@ -2103,17 +1767,14 @@ * will still continue to work as usual, so enabling this option should not * break backwards compatibility. * - * \warning The PSA Crypto API is in beta stage. While you're welcome to - * experiment using it, incompatible API changes are still possible, and some - * parts may not have reached the same quality as the rest of Mbed TLS yet. + * \note See docs/use-psa-crypto.md for a complete description of what this + * option currently does, and of parts that are not affected by it so far. * - * \warning This option enables new Mbed TLS APIs that are dependent on the - * PSA Crypto API, so can't come with the same stability guarantees as the - * rest of the Mbed TLS APIs. You're welcome to experiment with them, but for - * now, access to these APIs is opt-in (via enabling the present option), in - * order to clearly differentiate them from the stable Mbed TLS APIs. + * \warning If you enable this option, you need to call `psa_crypto_init()` + * before calling any function from the SSL/TLS, X.509 or PK modules. * * Requires: MBEDTLS_PSA_CRYPTO_C. + * Conflicts with: MBEDTLS_ECP_RESTARTABLE * * Uncomment this to enable internal use of PSA Crypto and new associated APIs. */ @@ -2125,12 +1786,19 @@ * This setting allows support for cryptographic mechanisms through the PSA * API to be configured separately from support through the mbedtls API. * - * Uncomment this to enable use of PSA Crypto configuration settings which - * can be found in include/psa/crypto_config.h. + * When this option is disabled, the PSA API exposes the cryptographic + * mechanisms that can be implemented on top of the `mbedtls_xxx` API + * configured with `MBEDTLS_XXX` symbols. + * + * When this option is enabled, the PSA API exposes the cryptographic + * mechanisms requested by the `PSA_WANT_XXX` symbols defined in + * include/psa/crypto_config.h. The corresponding `MBEDTLS_XXX` settings are + * automatically enabled if required (i.e. if no PSA driver provides the + * mechanism). You may still freely enable additional `MBEDTLS_XXX` symbols + * in mbedtls_config.h. * - * If you enable this option and write your own configuration file, you must - * include mbedtls/config_psa.h in your configuration file. The default - * provided mbedtls/config.h contains the necessary inclusion. + * If the symbol #MBEDTLS_PSA_CRYPTO_CONFIG_FILE is defined, it specifies + * an alternative header to include instead of include/psa/crypto_config.h. * * This feature is still experimental and is not ready for production since * it is not completed. @@ -2150,28 +1818,6 @@ */ //#define MBEDTLS_VERSION_FEATURES -/** - * \def MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 - * - * If set, the X509 parser will not break-off when parsing an X509 certificate - * and encountering an extension in a v1 or v2 certificate. - * - * Uncomment to prevent an error. - */ -//#define MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 - -/** - * \def MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION - * - * If set, the X509 parser will not break-off when parsing an X509 certificate - * and encountering an unknown critical extension. - * - * \warning Depending on your PKI use, enabling this can be a security risk! - * - * Uncomment to prevent an error. - */ -//#define MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION - /** * \def MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK * @@ -2192,31 +1838,15 @@ //#define MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK /** - * \def MBEDTLS_X509_CHECK_KEY_USAGE + * \def MBEDTLS_X509_REMOVE_INFO * - * Enable verification of the keyUsage extension (CA and leaf certificates). + * Disable mbedtls_x509_*_info() and related APIs. * - * Disabling this avoids problems with mis-issued and/or misused - * (intermediate) CA and leaf certificates. - * - * \warning Depending on your PKI use, disabling this can be a security risk! - * - * Comment to skip keyUsage checking for both CA and leaf certificates. - */ -#define MBEDTLS_X509_CHECK_KEY_USAGE - -/** - * \def MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE - * - * Enable verification of the extendedKeyUsage extension (leaf certificates). - * - * Disabling this avoids problems with mis-issued and/or misused certificates. - * - * \warning Depending on your PKI use, disabling this can be a security risk! - * - * Comment to skip extendedKeyUsage checking for certificates. + * Uncomment to omit mbedtls_x509_*_info(), as well as mbedtls_debug_print_crt() + * and other functions/constants only used by these functions, thus reducing + * the code footprint by several KB. */ -#define MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE +//#define MBEDTLS_X509_REMOVE_INFO /** * \def MBEDTLS_X509_RSASSA_PSS_SUPPORT @@ -2227,32 +1857,7 @@ * Comment this macro to disallow using RSASSA-PSS in certificates. */ //#define MBEDTLS_X509_RSASSA_PSS_SUPPORT - -/** - * \def MBEDTLS_ZLIB_SUPPORT - * - * If set, the SSL/TLS module uses ZLIB to support compression and - * decompression of packet data. - * - * \warning TLS-level compression MAY REDUCE SECURITY! See for example the - * CRIME attack. Before enabling this option, you should examine with care if - * CRIME or similar exploits may be applicable to your use case. - * - * \note Currently compression can't be used with DTLS. - * - * \deprecated This feature is deprecated and will be removed - * in the next major revision of the library. - * - * Used in: library/ssl_tls.c - * library/ssl_cli.c - * library/ssl_srv.c - * - * This feature requires zlib library and headers to be present. - * - * Uncomment to enable use of ZLIB - */ -//#define MBEDTLS_ZLIB_SUPPORT -/* \} name SECTION: mbed TLS feature support */ +/** \} name SECTION: mbed TLS feature support */ /** * \name SECTION: mbed TLS modules @@ -2350,34 +1955,6 @@ */ #define MBEDTLS_AES_C -/** - * \def MBEDTLS_ARC4_C - * - * Enable the ARCFOUR stream cipher. - * - * Module: library/arc4.c - * Caller: library/cipher.c - * - * This module enables the following ciphersuites (if other requisites are - * enabled as well): - * MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA - * MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA - * MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA - * MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA - * MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA - * MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA - * MBEDTLS_TLS_RSA_WITH_RC4_128_SHA - * MBEDTLS_TLS_RSA_WITH_RC4_128_MD5 - * MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA - * MBEDTLS_TLS_PSK_WITH_RC4_128_SHA - * - * \warning ARC4 is considered a weak cipher and its use constitutes a - * security risk. If possible, we recommend avoidng dependencies on - * it, and considering stronger ciphers instead. - * - */ -//#define MBEDTLS_ARC4_C - /** * \def MBEDTLS_ASN1_PARSE_C * @@ -2428,22 +2005,13 @@ * library/ecp.c * library/ecdsa.c * library/rsa.c - * library/rsa_internal.c + * library/rsa_alt_helpers.c * library/ssl_tls.c * * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support. */ #define MBEDTLS_BIGNUM_C -/** - * \def MBEDTLS_BLOWFISH_C - * - * Enable the Blowfish block cipher. - * - * Module: library/blowfish.c - */ -//#define MBEDTLS_BLOWFISH_C - /** * \def MBEDTLS_CAMELLIA_C * @@ -2558,25 +2126,14 @@ * * Module: library/ccm.c * - * Requires: MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C + * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C or + * MBEDTLS_ARIA_C * * This module enables the AES-CCM ciphersuites, if other requisites are * enabled as well. */ #define MBEDTLS_CCM_C -/** - * \def MBEDTLS_CERTS_C - * - * Enable the test certificates. - * - * Module: library/certs.c - * Caller: - * - * This module is used for testing (ssl_client/server). - */ -//#define MBEDTLS_CERTS_C - /** * \def MBEDTLS_CHACHA20_C * @@ -2603,7 +2160,17 @@ * Enable the generic cipher layer. * * Module: library/cipher.c - * Caller: library/ssl_tls.c + * Caller: library/ccm.c + * library/cmac.c + * library/gcm.c + * library/nist_kw.c + * library/pkcs12.c + * library/pkcs5.c + * library/psa_crypto_aead.c + * library/psa_crypto_mac.c + * library/ssl_ciphersuites.c + * library/ssl_msg.c + * library/ssl_ticket.c (unless MBEDTLS_USE_PSA_CRYPTO is enabled) * * Uncomment to enable generic cipher wrappers. */ @@ -2615,9 +2182,14 @@ * Enable the CMAC (Cipher-based Message Authentication Code) mode for block * ciphers. * + * \note When #MBEDTLS_CMAC_ALT is active, meaning that the underlying + * implementation of the CMAC algorithm is provided by an alternate + * implementation, that alternate implementation may opt to not support + * AES-192 or 3DES as underlying block ciphers for the CMAC operation. + * * Module: library/cmac.c * - * Requires: MBEDTLS_AES_C or MBEDTLS_DES_C + * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_DES_C * */ //#define MBEDTLS_CMAC_C @@ -2648,9 +2220,10 @@ * Enable the debug functions. * * Module: library/debug.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c + * Caller: library/ssl_msg.c * library/ssl_tls.c + * library/ssl_tls12_*.c + * library/ssl_tls13_*.c * * This module provides debugging functions. */ @@ -2665,19 +2238,6 @@ * Caller: library/pem.c * library/cipher.c * - * This module enables the following ciphersuites (if other requisites are - * enabled as well): - * MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA - * MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA - * * PEM_PARSE uses DES/3DES for decrypting encrypted keys. * * \warning DES is considered a weak cipher and its use constitutes a @@ -2691,8 +2251,9 @@ * Enable the Diffie-Hellman-Merkle module. * * Module: library/dhm.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c + * Caller: library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c * * This module is used by the following key exchanges: * DHE-RSA, DHE-PSK @@ -2712,8 +2273,10 @@ * Enable the elliptic curve Diffie-Hellman library. * * Module: library/ecdh.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c + * Caller: library/psa_crypto.c + * library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c * * This module is used by the following key exchanges: * ECDHE-ECDSA, ECDHE-RSA, DHE-PSK @@ -2744,9 +2307,9 @@ * * Enable the elliptic curve J-PAKE library. * - * \warning This is currently experimental. EC J-PAKE support is based on the - * Thread v1.0.0 specification; incompatible changes to the specification - * might still happen. For this reason, this is disabled by default. + * \note EC J-PAKE support is based on the Thread v1.0.0 specification. + * It has not been reviewed for compliance with newer standards such as + * Thread v1.1 or RFC 8236. * * Module: library/ecjpake.c * Caller: @@ -2805,36 +2368,14 @@ * * Module: library/gcm.c * - * Requires: MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C or MBEDTLS_ARIA_C + * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C or + * MBEDTLS_ARIA_C * * This module enables the AES-GCM and CAMELLIA-GCM ciphersuites, if other * requisites are enabled as well. */ #define MBEDTLS_GCM_C -/** - * \def MBEDTLS_HAVEGE_C - * - * Enable the HAVEGE random generator. - * - * Warning: the HAVEGE random generator is not suitable for virtualized - * environments - * - * Warning: the HAVEGE random generator is dependent on timing and specific - * processor traits. It is therefore not advised to use HAVEGE as - * your applications primary random generator or primary entropy pool - * input. As a secondary input to your entropy pool, it IS able add - * the (limited) extra entropy it provides. - * - * Module: library/havege.c - * Caller: - * - * Requires: MBEDTLS_TIMING_C - * - * Uncomment to enable the HAVEGE random generator. - */ -//#define MBEDTLS_HAVEGE_C - /** * \def MBEDTLS_HKDF_C * @@ -2860,7 +2401,7 @@ * * Requires: MBEDTLS_MD_C * - * Uncomment to enable the HMAC_DRBG random number geerator. + * Uncomment to enable the HMAC_DRBG random number generator. */ //#define MBEDTLS_HMAC_DRBG_C @@ -2883,46 +2424,29 @@ * Enable the generic message digest layer. * * Module: library/md.c - * Caller: + * Caller: library/constant_time.c + * library/ecdsa.c + * library/ecjpake.c + * library/hkdf.c + * library/hmac_drbg.c + * library/pk.c + * library/pkcs5.c + * library/pkcs12.c + * library/psa_crypto_ecp.c + * library/psa_crypto_rsa.c + * library/rsa.c + * library/ssl_cookie.c + * library/ssl_msg.c + * library/ssl_tls.c + * library/x509.c + * library/x509_crt.c + * library/x509write_crt.c + * library/x509write_csr.c * * Uncomment to enable generic message digest wrappers. */ #define MBEDTLS_MD_C -/** - * \def MBEDTLS_MD2_C - * - * Enable the MD2 hash algorithm. - * - * Module: library/md2.c - * Caller: - * - * Uncomment to enable support for (rare) MD2-signed X.509 certs. - * - * \warning MD2 is considered a weak message digest and its use constitutes a - * security risk. If possible, we recommend avoiding dependencies on - * it, and considering stronger message digests instead. - * - */ -//#define MBEDTLS_MD2_C - -/** - * \def MBEDTLS_MD4_C - * - * Enable the MD4 hash algorithm. - * - * Module: library/md4.c - * Caller: - * - * Uncomment to enable support for (rare) MD4-signed X.509 certs. - * - * \warning MD4 is considered a weak message digest and its use constitutes a - * security risk. If possible, we recommend avoiding dependencies on - * it, and considering stronger message digests instead. - * - */ -//#define MBEDTLS_MD4_C - /** * \def MBEDTLS_MD5_C * @@ -2933,10 +2457,9 @@ * library/pem.c * library/ssl_tls.c * - * This module is required for SSL/TLS up to version 1.1, and for TLS 1.2 - * depending on the handshake parameters. Further, it is used for checking - * MD5-signed certificates, and for PBKDF1 when decrypting PEM-encoded - * encrypted keys. + * This module is required for TLS 1.2 depending on the handshake parameters. + * Further, it is used for checking MD5-signed certificates, and for PBKDF1 + * when decrypting PEM-encoded encrypted keys. * * \warning MD5 is considered a weak message digest and its use constitutes a * security risk. If possible, we recommend avoiding dependencies on @@ -3054,14 +2577,16 @@ /** * \def MBEDTLS_PK_C * - * Enable the generic public (asymetric) key layer. + * Enable the generic public (asymmetric) key layer. * * Module: library/pk.c - * Caller: library/ssl_tls.c - * library/ssl_cli.c - * library/ssl_srv.c + * Caller: library/psa_crypto_rsa.c + * library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c + * library/x509.c * - * Requires: MBEDTLS_RSA_C or MBEDTLS_ECP_C + * Requires: MBEDTLS_MD_C, MBEDTLS_RSA_C or MBEDTLS_ECP_C * * Uncomment to enable generic public key wrappers. */ @@ -3070,7 +2595,7 @@ /** * \def MBEDTLS_PK_PARSE_C * - * Enable the generic public (asymetric) key parser. + * Enable the generic public (asymmetric) key parser. * * Module: library/pkparse.c * Caller: library/x509_crt.c @@ -3085,7 +2610,7 @@ /** * \def MBEDTLS_PK_WRITE_C * - * Enable the generic public (asymetric) key writer. + * Enable the generic public (asymmetric) key writer. * * Module: library/pkwrite.c * Caller: library/x509write.c @@ -3103,30 +2628,12 @@ * * Module: library/pkcs5.c * - * Requires: MBEDTLS_MD_C + * Requires: MBEDTLS_CIPHER_C, MBEDTLS_MD_C * * This module adds support for the PKCS#5 functions. */ #define MBEDTLS_PKCS5_C -/** - * \def MBEDTLS_PKCS11_C - * - * Enable wrapper for PKCS#11 smartcard support via the pkcs11-helper library. - * - * \deprecated This option is deprecated and will be removed in a future - * version of Mbed TLS. - * - * Module: library/pkcs11.c - * Caller: library/pk.c - * - * Requires: MBEDTLS_PK_C - * - * This module enables SSL/TLS PKCS #11 smartcard support. - * Requires the presence of the PKCS#11 helper library (libpkcs11-helper) - */ -//#define MBEDTLS_PKCS11_C - /** * \def MBEDTLS_PKCS12_C * @@ -3137,7 +2644,6 @@ * Caller: library/pkparse.c * * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_CIPHER_C, MBEDTLS_MD_C - * Can use: MBEDTLS_ARC4_C * * This module enables PKCS#12 functions. */ @@ -3178,27 +2684,24 @@ * * Enable the Platform Security Architecture cryptography API. * - * \warning The PSA Crypto API is still beta status. While you're welcome to - * experiment using it, incompatible API changes are still possible, and some - * parts may not have reached the same quality as the rest of Mbed TLS yet. - * * Module: library/psa_crypto.c * - * Requires: either MBEDTLS_CTR_DRBG_C and MBEDTLS_ENTROPY_C, + * Requires: MBEDTLS_CIPHER_C, + * either MBEDTLS_CTR_DRBG_C and MBEDTLS_ENTROPY_C, * or MBEDTLS_HMAC_DRBG_C and MBEDTLS_ENTROPY_C, * or MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG. * */ -//#define MBEDTLS_PSA_CRYPTO_C +#define MBEDTLS_PSA_CRYPTO_C /** * \def MBEDTLS_PSA_CRYPTO_SE_C * - * Enable secure element support in the Platform Security Architecture + * Enable dynamic secure element support in the Platform Security Architecture * cryptography API. * - * \warning This feature is not yet suitable for production. It is provided - * for API evaluation and testing purposes only. + * \deprecated This feature is deprecated. Please switch to the driver + * interface enabled by #MBEDTLS_PSA_CRYPTO_DRIVERS. * * Module: library/psa_crypto_se.c * @@ -3249,11 +2752,12 @@ * Enable the RSA public-key cryptosystem. * * Module: library/rsa.c - * library/rsa_internal.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c + * library/rsa_alt_helpers.c + * Caller: library/pk.c + * library/psa_crypto.c * library/ssl_tls.c - * library/x509.c + * library/ssl*_client.c + * library/ssl*_server.c * * This module is used by the following key exchanges: * RSA, DHE-RSA, ECDHE-RSA, RSA-PSK @@ -3269,13 +2773,10 @@ * * Module: library/sha1.c * Caller: library/md.c - * library/ssl_cli.c - * library/ssl_srv.c - * library/ssl_tls.c - * library/x509write_crt.c + * library/psa_crypto_hash.c * - * This module is required for SSL/TLS up to version 1.1, for TLS 1.2 - * depending on the handshake parameters, and for SHA1-signed certificates. + * This module is required for TLS 1.2 depending on the handshake parameters, + * and for SHA1-signed certificates. * * \warning SHA-1 is considered a weak message digest and its use constitutes * a security risk. If possible, we recommend avoiding dependencies @@ -3284,37 +2785,177 @@ */ #define MBEDTLS_SHA1_C +/** + * \def MBEDTLS_SHA224_C + * + * Enable the SHA-224 cryptographic hash algorithm. + * + * Requires: MBEDTLS_SHA256_C. The library does not currently support enabling + * SHA-224 without SHA-256. + * + * Module: library/sha256.c + * Caller: library/md.c + * library/ssl_cookie.c + * + * This module adds support for SHA-224. + */ +#define MBEDTLS_SHA224_C + /** * \def MBEDTLS_SHA256_C * - * Enable the SHA-224 and SHA-256 cryptographic hash algorithms. + * Enable the SHA-256 cryptographic hash algorithm. + * + * Requires: MBEDTLS_SHA224_C. The library does not currently support enabling + * SHA-256 without SHA-224. * * Module: library/sha256.c * Caller: library/entropy.c * library/md.c - * library/ssl_cli.c - * library/ssl_srv.c * library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c * - * This module adds support for SHA-224 and SHA-256. + * This module adds support for SHA-256. * This module is required for the SSL/TLS 1.2 PRF function. */ #define MBEDTLS_SHA256_C +/** + * \def MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT + * + * Enable acceleration of the SHA-256 and SHA-224 cryptographic hash algorithms + * with the ARMv8 cryptographic extensions if they are available at runtime. + * If not, the library will fall back to the C implementation. + * + * \note If MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT is defined when building + * for a non-Aarch64 build it will be silently ignored. + * + * \note The code uses Neon intrinsics, so \c CFLAGS must be set to a minimum + * of \c -march=armv8-a+crypto. + * + * \warning MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT cannot be defined at the + * same time as MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY. + * + * Requires: MBEDTLS_SHA256_C. + * + * Module: library/sha256.c + * + * Uncomment to have the library check for the A64 SHA-256 crypto extensions + * and use them if available. + */ +//#define MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT + +/** + * \def MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY + * + * Enable acceleration of the SHA-256 and SHA-224 cryptographic hash algorithms + * with the ARMv8 cryptographic extensions, which must be available at runtime + * or else an illegal instruction fault will occur. + * + * \note This allows builds with a smaller code size than with + * MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT + * + * \note The code uses Neon intrinsics, so \c CFLAGS must be set to a minimum + * of \c -march=armv8-a+crypto. + * + * \warning MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY cannot be defined at the same + * time as MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT. + * + * Requires: MBEDTLS_SHA256_C. + * + * Module: library/sha256.c + * + * Uncomment to have the library use the A64 SHA-256 crypto extensions + * unconditionally. + */ +//#define MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY + +/** + * \def MBEDTLS_SHA384_C + * + * Enable the SHA-384 cryptographic hash algorithm. + * + * Requires: MBEDTLS_SHA512_C + * + * Module: library/sha512.c + * Caller: library/md.c + * library/psa_crypto_hash.c + * library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c + * + * Comment to disable SHA-384 + */ +//#define MBEDTLS_SHA384_C + /** * \def MBEDTLS_SHA512_C * - * Enable the SHA-384 and SHA-512 cryptographic hash algorithms. + * Enable SHA-512 cryptographic hash algorithms. * * Module: library/sha512.c * Caller: library/entropy.c * library/md.c - * library/ssl_cli.c - * library/ssl_srv.c + * library/ssl_tls.c + * library/ssl_cookie.c * - * This module adds support for SHA-384 and SHA-512. + * This module adds support for SHA-512. */ //#define MBEDTLS_SHA512_C +/** + * \def MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT + * + * Enable acceleration of the SHA-512 and SHA-384 cryptographic hash algorithms + * with the ARMv8 cryptographic extensions if they are available at runtime. + * If not, the library will fall back to the C implementation. + * + * \note If MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT is defined when building + * for a non-Aarch64 build it will be silently ignored. + * + * \note The code uses the SHA-512 Neon intrinsics, so requires GCC >= 8 or + * Clang >= 7, and \c CFLAGS must be set to a minimum of + * \c -march=armv8.2-a+sha3. An optimisation level of \c -O3 generates the + * fastest code. + * + * \warning MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT cannot be defined at the + * same time as MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY. + * + * Requires: MBEDTLS_SHA512_C. + * + * Module: library/sha512.c + * + * Uncomment to have the library check for the A64 SHA-512 crypto extensions + * and use them if available. + */ +//#define MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT + +/** + * \def MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY + * + * Enable acceleration of the SHA-512 and SHA-384 cryptographic hash algorithms + * with the ARMv8 cryptographic extensions, which must be available at runtime + * or else an illegal instruction fault will occur. + * + * \note This allows builds with a smaller code size than with + * MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT + * + * \note The code uses the SHA-512 Neon intrinsics, so requires GCC >= 8 or + * Clang >= 7, and \c CFLAGS must be set to a minimum of + * \c -march=armv8.2-a+sha3. An optimisation level of \c -O3 generates the + * fastest code. + * + * \warning MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY cannot be defined at the same + * time as MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT. + * + * Requires: MBEDTLS_SHA512_C. + * + * Module: library/sha512.c + * + * Uncomment to have the library use the A64 SHA-512 crypto extensions + * unconditionally. + */ +//#define MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY /** * \def MBEDTLS_SSL_CACHE_C @@ -3346,7 +2987,7 @@ * Module: library/ssl_ticket.c * Caller: * - * Requires: MBEDTLS_CIPHER_C + * Requires: MBEDTLS_CIPHER_C || MBEDTLS_USE_PSA_CRYPTO */ //#define MBEDTLS_SSL_TICKET_C @@ -3355,7 +2996,7 @@ * * Enable the SSL/TLS client code. * - * Module: library/ssl_cli.c + * Module: library/ssl*_client.c * Caller: * * Requires: MBEDTLS_SSL_TLS_C @@ -3369,7 +3010,7 @@ * * Enable the SSL/TLS server code. * - * Module: library/ssl_srv.c + * Module: library/ssl*_server.c * Caller: * * Requires: MBEDTLS_SSL_TLS_C @@ -3384,8 +3025,8 @@ * Enable the generic SSL/TLS code. * * Module: library/ssl_tls.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c + * Caller: library/ssl*_client.c + * library/ssl*_server.c * * Requires: MBEDTLS_CIPHER_C, MBEDTLS_MD_C * and at least one of the MBEDTLS_SSL_PROTO_XXX defines @@ -3428,14 +3069,15 @@ * your own implementation of the whole module by setting * \c MBEDTLS_TIMING_ALT in the current file. * + * \note The timing module will include time.h on suitable platforms + * regardless of the setting of MBEDTLS_HAVE_TIME, unless + * MBEDTLS_TIMING_ALT is used. See timing.c for more information. + * * \note See also our Knowledge Base article about porting to a new * environment: * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS * * Module: library/timing.c - * Caller: library/havege.c - * - * This module is used by the HAVEGE random number generator. */ //#define MBEDTLS_TIMING_C @@ -3473,9 +3115,9 @@ * Enable X.509 certificate parsing. * * Module: library/x509_crt.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c - * library/ssl_tls.c + * Caller: library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c * * Requires: MBEDTLS_X509_USE_C * @@ -3550,17 +3192,89 @@ */ #define MBEDTLS_X509_CSR_WRITE_C +/** \} name SECTION: mbed TLS modules */ + /** - * \def MBEDTLS_XTEA_C + * \name SECTION: General configuration options * - * Enable the XTEA block cipher. + * This section contains Mbed TLS build settings that are not associated + * with a particular module. * - * Module: library/xtea.c - * Caller: + * \{ */ -//#define MBEDTLS_XTEA_C -/* \} name SECTION: mbed TLS modules */ +/** + * \def MBEDTLS_CONFIG_FILE + * + * If defined, this is a header which will be included instead of + * `"mbedtls/mbedtls_config.h"`. + * This header file specifies the compile-time configuration of Mbed TLS. + * Unlike other configuration options, this one must be defined on the + * compiler command line: a definition in `mbedtls_config.h` would have + * no effect. + * + * This macro is expanded after an \#include directive. This is a popular but + * non-standard feature of the C language, so this feature is only available + * with compilers that perform macro expansion on an \#include line. + * + * The value of this symbol is typically a path in double quotes, either + * absolute or relative to a directory on the include search path. + */ +//#define MBEDTLS_CONFIG_FILE "mbedtls/mbedtls_config.h" + +/** + * \def MBEDTLS_USER_CONFIG_FILE + * + * If defined, this is a header which will be included after + * `"mbedtls/mbedtls_config.h"` or #MBEDTLS_CONFIG_FILE. + * This allows you to modify the default configuration, including the ability + * to undefine options that are enabled by default. + * + * This macro is expanded after an \#include directive. This is a popular but + * non-standard feature of the C language, so this feature is only available + * with compilers that perform macro expansion on an \#include line. + * + * The value of this symbol is typically a path in double quotes, either + * absolute or relative to a directory on the include search path. + */ +//#define MBEDTLS_USER_CONFIG_FILE "/dev/null" + +/** + * \def MBEDTLS_PSA_CRYPTO_CONFIG_FILE + * + * If defined, this is a header which will be included instead of + * `"psa/crypto_config.h"`. + * This header file specifies which cryptographic mechanisms are available + * through the PSA API when #MBEDTLS_PSA_CRYPTO_CONFIG is enabled, and + * is not used when #MBEDTLS_PSA_CRYPTO_CONFIG is disabled. + * + * This macro is expanded after an \#include directive. This is a popular but + * non-standard feature of the C language, so this feature is only available + * with compilers that perform macro expansion on an \#include line. + * + * The value of this symbol is typically a path in double quotes, either + * absolute or relative to a directory on the include search path. + */ +//#define MBEDTLS_PSA_CRYPTO_CONFIG_FILE "psa/crypto_config.h" + +/** + * \def MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE + * + * If defined, this is a header which will be included after + * `"psa/crypto_config.h"` or #MBEDTLS_PSA_CRYPTO_CONFIG_FILE. + * This allows you to modify the default configuration, including the ability + * to undefine options that are enabled by default. + * + * This macro is expanded after an \#include directive. This is a popular but + * non-standard feature of the C language, so this feature is only available + * with compilers that perform macro expansion on an \#include line. + * + * The value of this symbol is typically a path in double quotes, either + * absolute or relative to a directory on the include search path. + */ +//#define MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE "/dev/null" + +/** \} name SECTION: General configuration options */ /** * \name SECTION: Module configuration options @@ -3571,22 +3285,26 @@ * * Our advice is to enable options and change their values here * only if you have a good reason and know the consequences. - * - * Please check the respective header file for documentation on these - * parameters (to prevent duplicate documentation). * \{ */ +/* The Doxygen documentation here is used when a user comments out a + * setting and runs doxygen themselves. On the other hand, when we typeset + * the full documentation including disabled settings, the documentation + * in specific modules' header files is used if present. When editing this + * file, make sure that each option is documented in exactly one place, + * plus optionally a same-line Doxygen comment here if there is a Doxygen + * comment in the specific module. */ /* MPI / BIGNUM options */ //#define MBEDTLS_MPI_WINDOW_SIZE 6 /**< Maximum window size used. */ //#define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */ /* CTR_DRBG options */ -//#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default (48 with -// SHA-512, 32 with SHA-256) */ #define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is -// performed by default */ #define MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input -// bytes */ #define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ -//#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ +//#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with +// SHA-256) */ #define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ #define +// MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ #define +// MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ #define +// MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ /* HMAC_DRBG options */ //#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ @@ -3595,88 +3313,74 @@ //#define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ /* ECP options */ -//#define MBEDTLS_ECP_MAX_BITS 521 /**< Maximum bit size of groups */ -//#define MBEDTLS_ECP_WINDOW_SIZE 6 /**< Maximum window size used */ +//#define MBEDTLS_ECP_WINDOW_SIZE 4 /**< Maximum window size used */ //#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up */ /* Entropy options */ //#define MBEDTLS_ENTROPY_MAX_SOURCES 20 /**< Maximum number of sources supported */ //#define MBEDTLS_ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */ -//#define MBEDTLS_ENTROPY_MIN_HARDWARE 32 /**< Default minimum number of bytes required for the hardware -// entropy source mbedtls_hardware_poll() before entropy is released */ +//#define MBEDTLS_ENTROPY_MIN_HARDWARE 32 /**< Default minimum number of bytes required for the hardware entropy +// source mbedtls_hardware_poll() before entropy is released */ /* Memory buffer allocator options */ //#define MBEDTLS_MEMORY_ALIGN_MULTIPLE 4 /**< Align on multiples of this value */ /* Platform options */ -//#define MBEDTLS_PLATFORM_STD_MEM_HDR /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is -// defined. Don't define if no header is needed. */ #define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< Default -// allocator to use, can be undefined */ #define MBEDTLS_PLATFORM_STD_FREE free /**< Default free to use, can -// be undefined */ #define MBEDTLS_PLATFORM_STD_EXIT exit /**< Default exit to use, can be undefined */ -//#define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use, can be undefined. MBEDTLS_HAVE_TIME must -// be enabled */ #define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use, can be undefined */ -//#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< Default printf to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_MEM_HDR /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is defined. Don't +// define if no header is needed. */ #define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< Default allocator to use, can be +// undefined */ #define MBEDTLS_PLATFORM_STD_FREE free /**< Default free to use, can be undefined */ #define +// MBEDTLS_PLATFORM_STD_SETBUF setbuf /**< Default setbuf to use, can be undefined */ #define MBEDTLS_PLATFORM_STD_EXIT exit +///**< Default exit to use, can be undefined */ #define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use, can be +// undefined. MBEDTLS_HAVE_TIME must be enabled */ #define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use, +// can be undefined */ #define MBEDTLS_PLATFORM_STD_PRINTF printf /**< Default printf to use, can be undefined */ /* Note: your snprintf must correctly zero-terminate the buffer! */ //#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< Default snprintf to use, can be undefined */ //#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS 0 /**< Default exit value to use, can be undefined */ //#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE 1 /**< Default exit value to use, can be undefined */ -//#define MBEDTLS_PLATFORM_STD_NV_SEED_READ mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to -// use, can be undefined */ #define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE mbedtls_platform_std_nv_seed_write /**< Default -// nv_seed_write function to use, can be undefined */ #define MBEDTLS_PLATFORM_STD_NV_SEED_FILE "seedfile" /**< Seed -// file to read/write with default implementation */ +//#define MBEDTLS_PLATFORM_STD_NV_SEED_READ mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be +// undefined */ #define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function +// to use, can be undefined */ #define MBEDTLS_PLATFORM_STD_NV_SEED_FILE "seedfile" /**< Seed file to read/write with default +// implementation */ /* To Use Function Macros MBEDTLS_PLATFORM_C must be enabled */ /* MBEDTLS_PLATFORM_XXX_MACRO and MBEDTLS_PLATFORM_XXX_ALT cannot both be defined */ //#define MBEDTLS_PLATFORM_CALLOC_MACRO calloc /**< Default allocator macro to use, can be undefined */ //#define MBEDTLS_PLATFORM_FREE_MACRO free /**< Default free macro to use, can be undefined */ //#define MBEDTLS_PLATFORM_EXIT_MACRO exit /**< Default exit macro to use, can be undefined */ -//#define MBEDTLS_PLATFORM_TIME_MACRO time /**< Default time macro to use, can be undefined. -// MBEDTLS_HAVE_TIME must be enabled */ #define MBEDTLS_PLATFORM_TIME_TYPE_MACRO time_t /**< Default time macro to -// use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */ #define MBEDTLS_PLATFORM_FPRINTF_MACRO fprintf /**< -// Default fprintf macro to use, can be undefined */ #define MBEDTLS_PLATFORM_PRINTF_MACRO printf /**< Default -// printf macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_SETBUF_MACRO setbuf /**< Default setbuf macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_TIME_MACRO time /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be +// enabled */ #define MBEDTLS_PLATFORM_TIME_TYPE_MACRO time_t /**< Default time macro to use, can be undefined. +// MBEDTLS_HAVE_TIME must be enabled */ #define MBEDTLS_PLATFORM_FPRINTF_MACRO fprintf /**< Default fprintf macro to use, can +// be undefined */ #define MBEDTLS_PLATFORM_PRINTF_MACRO printf /**< Default printf macro to use, can be undefined */ /* Note: your snprintf must correctly zero-terminate the buffer! */ //#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf /**< Default snprintf macro to use, can be undefined */ //#define MBEDTLS_PLATFORM_VSNPRINTF_MACRO vsnprintf /**< Default vsnprintf macro to use, can be undefined */ -//#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to -// use, can be undefined */ #define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO mbedtls_platform_std_nv_seed_write /**< -// Default nv_seed_write function to use, can be undefined */ - -/** - * \brief This macro is invoked by the library when an invalid parameter - * is detected that is only checked with #MBEDTLS_CHECK_PARAMS - * (see the documentation of that option for context). - * - * When you leave this undefined here, the library provides - * a default definition. If the macro #MBEDTLS_CHECK_PARAMS_ASSERT - * is defined, the default definition is `assert(cond)`, - * otherwise the default definition calls a function - * mbedtls_param_failed(). This function is declared in - * `platform_util.h` for the benefit of the library, but - * you need to define in your application. - * - * When you define this here, this replaces the default - * definition in platform_util.h (which no longer declares the - * function mbedtls_param_failed()) and it is your responsibility - * to make sure this macro expands to something suitable (in - * particular, that all the necessary declarations are visible - * from within the library - you can ensure that by providing - * them in this file next to the macro definition). - * If you define this macro to call `assert`, also define - * #MBEDTLS_CHECK_PARAMS_ASSERT so that library source files - * include ``. - * - * Note that you may define this macro to expand to nothing, in - * which case you don't have to worry about declarations or - * definitions. However, you will then be notified about invalid - * parameters only in non-void functions, and void function will - * just silently return early on invalid parameters, which - * partially negates the benefits of enabling - * #MBEDTLS_CHECK_PARAMS in the first place, so is discouraged. - * - * \param cond The expression that should evaluate to true, but doesn't. - */ -//#define MBEDTLS_PARAM_FAILED( cond ) assert( cond ) +//#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be +// undefined */ #define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function +// to use, can be undefined */ + +/** \def MBEDTLS_CHECK_RETURN + * + * This macro is used at the beginning of the declaration of a function + * to indicate that its return value should be checked. It should + * instruct the compiler to emit a warning or an error if the function + * is called without checking its return value. + * + * There is a default implementation for popular compilers in platform_util.h. + * You can override the default implementation by defining your own here. + * + * If the implementation here is empty, this will effectively disable the + * checking of functions' return values. + */ +//#define MBEDTLS_CHECK_RETURN __attribute__((__warn_unused_result__)) + +/** \def MBEDTLS_IGNORE_RETURN + * + * This macro requires one argument, which should be a C function call. + * If that function call would cause a #MBEDTLS_CHECK_RETURN warning, this + * warning is suppressed. + */ +//#define MBEDTLS_IGNORE_RETURN( result ) ((void) !(result)) /* PSA options */ /** @@ -3708,32 +3412,6 @@ /* SSL options */ -/** \def MBEDTLS_SSL_MAX_CONTENT_LEN - * - * Maximum length (in bytes) of incoming and outgoing plaintext fragments. - * - * This determines the size of both the incoming and outgoing TLS I/O buffers - * in such a way that both are capable of holding the specified amount of - * plaintext data, regardless of the protection mechanism used. - * - * To configure incoming and outgoing I/O buffers separately, use - * #MBEDTLS_SSL_IN_CONTENT_LEN and #MBEDTLS_SSL_OUT_CONTENT_LEN, - * which overwrite the value set by this option. - * - * \note When using a value less than the default of 16KB on the client, it is - * recommended to use the Maximum Fragment Length (MFL) extension to - * inform the server about this limitation. On the server, there - * is no supported, standardized way of informing the client about - * restriction on the maximum size of incoming messages, and unless - * the limitation has been communicated by other means, it is recommended - * to only change the outgoing buffer size #MBEDTLS_SSL_OUT_CONTENT_LEN - * while keeping the default value of 16KB for the incoming buffer. - * - * Uncomment to set the maximum plaintext size of both - * incoming and outgoing I/O buffers. - */ -#define MBEDTLS_SSL_MAX_CONTENT_LEN 8192 - /** \def MBEDTLS_SSL_IN_CONTENT_LEN * * Maximum length (in bytes) of incoming plaintext fragments. @@ -3742,9 +3420,6 @@ * that it is capable of holding the specified amount of plaintext data, * regardless of the protection mechanism used. * - * If this option is undefined, it inherits its value from - * #MBEDTLS_SSL_MAX_CONTENT_LEN. - * * \note When using a value less than the default of 16KB on the client, it is * recommended to use the Maximum Fragment Length (MFL) extension to * inform the server about this limitation. On the server, there @@ -3754,8 +3429,7 @@ * to only change the outgoing buffer size #MBEDTLS_SSL_OUT_CONTENT_LEN * while keeping the default value of 16KB for the incoming buffer. * - * Uncomment to set the maximum plaintext size of the incoming I/O buffer - * independently of the outgoing I/O buffer. + * Uncomment to set the maximum plaintext size of the incoming I/O buffer. */ //#define MBEDTLS_SSL_IN_CONTENT_LEN 16384 @@ -3773,27 +3447,10 @@ */ //#define MBEDTLS_SSL_CID_OUT_LEN_MAX 32 -/** \def MBEDTLS_SSL_CID_PADDING_GRANULARITY - * - * This option controls the use of record plaintext padding - * when using the Connection ID extension in DTLS 1.2. - * - * The padding will always be chosen so that the length of the - * padded plaintext is a multiple of the value of this option. - * - * Note: A value of \c 1 means that no padding will be used - * for outgoing records. - * - * Note: On systems lacking division instructions, - * a power of two should be preferred. - * - */ -//#define MBEDTLS_SSL_CID_PADDING_GRANULARITY 16 - -/** \def MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY +/** \def MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY * * This option controls the use of record plaintext padding - * in TLS 1.3. + * in TLS 1.3 and when using the Connection ID extension in DTLS 1.2. * * The padding will always be chosen so that the length of the * padded plaintext is a multiple of the value of this option. @@ -3804,7 +3461,7 @@ * Note: On systems lacking division instructions, * a power of two should be preferred. */ -//#define MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY 1 +//#define MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY 16 /** \def MBEDTLS_SSL_OUT_CONTENT_LEN * @@ -3814,9 +3471,6 @@ * that it is capable of holding the specified amount of plaintext data, * regardless of the protection mechanism used. * - * If this option undefined, it inherits its value from - * #MBEDTLS_SSL_MAX_CONTENT_LEN. - * * It is possible to save RAM by setting a smaller outward buffer, while keeping * the default inward 16384 byte buffer to conform to the TLS specification. * @@ -3825,8 +3479,7 @@ * The specific size requirement depends on the configured ciphers and any * certificate data which is sent during the handshake. * - * Uncomment to set the maximum plaintext size of the outgoing I/O buffer - * independently of the incoming I/O buffer. + * Uncomment to set the maximum plaintext size of the outgoing I/O buffer. */ //#define MBEDTLS_SSL_OUT_CONTENT_LEN 16384 @@ -3835,7 +3488,7 @@ * Maximum number of heap-allocated bytes for the purpose of * DTLS handshake message reassembly and future message buffering. * - * This should be at least 9/8 * MBEDTLSSL_IN_CONTENT_LEN + * This should be at least 9/8 * MBEDTLS_SSL_IN_CONTENT_LEN * to account for a reassembled handshake message of maximum size, * together with its reassembly bitmap. * @@ -3847,10 +3500,20 @@ */ //#define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768 -//#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME 86400 /**< Lifetime of session tickets (if enabled) */ //#define MBEDTLS_PSK_MAX_LEN 32 /**< Max size of TLS pre-shared keys, in bytes (default 256 bits) */ -//#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, -// or in number of cookies issued */ +//#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number +// of cookies issued */ + +/** \def MBEDTLS_TLS_EXT_CID + * + * At the time of writing, the CID extension has not been assigned its + * final value. Set this configuration option to make Mbed TLS use a + * different value. + * + * A future minor revision of Mbed TLS may change the default value of + * this option to match evolving standards and usage. + */ +//#define MBEDTLS_TLS_EXT_CID 254 /** * Complete list of ciphersuites to use, in order of preference. @@ -3864,44 +3527,12 @@ * * The value below is only an example, not the default. */ -//#define MBEDTLS_SSL_CIPHERSUITES -// MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 +//#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 /* X509 options */ //#define MBEDTLS_X509_MAX_INTERMEDIATE_CA 8 /**< Maximum number of intermediate CAs in a verification chain. */ -//#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512 /**< Maximum length of a path/filename string in bytes including the -// null terminator character ('\0'). */ - -/** - * Allow SHA-1 in the default TLS configuration for certificate signing. - * Without this build-time option, SHA-1 support must be activated explicitly - * through mbedtls_ssl_conf_cert_profile. Turning on this option is not - * recommended because of it is possible to generate SHA-1 collisions, however - * this may be safe for legacy infrastructure where additional controls apply. - * - * \warning SHA-1 is considered a weak message digest and its use constitutes - * a security risk. If possible, we recommend avoiding dependencies - * on it, and considering stronger message digests instead. - * - */ -//#define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES - -/** - * Allow SHA-1 in the default TLS configuration for TLS 1.2 handshake - * signature and ciphersuite selection. Without this build-time option, SHA-1 - * support must be activated explicitly through mbedtls_ssl_conf_sig_hashes. - * The use of SHA-1 in TLS <= 1.1 and in HMAC-SHA-1 is always allowed by - * default. At the time of writing, there is no practical attack on the use - * of SHA-1 in handshake signatures, hence this option is turned on by default - * to preserve compatibility with existing peers, but the general - * warning applies nonetheless: - * - * \warning SHA-1 is considered a weak message digest and its use constitutes - * a security risk. If possible, we recommend avoiding dependencies - * on it, and considering stronger message digests instead. - * - */ -//#define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE +//#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512 /**< Maximum length of a path/filename string in bytes including the null +// terminator character ('\0'). */ /** * Uncomment the macro to let mbed TLS use your alternate implementation of @@ -3951,10 +3582,4 @@ */ //#define MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED -#if defined(MBEDTLS_PSA_CRYPTO_CONFIG) -#include "mbedtls/config_psa.h" -#endif - -#include "mbedtls/check_config.h" - -#endif /* MBEDTLS_CONFIG_H */ +/** \} name SECTION: Module configuration options */ diff --git a/config/openiotsdk/storage/CMakeLists.txt b/config/openiotsdk/storage/CMakeLists.txt new file mode 100644 index 00000000000000..a7f1e0b53f0e4a --- /dev/null +++ b/config/openiotsdk/storage/CMakeLists.txt @@ -0,0 +1,34 @@ +# +# Copyright (c) 2022 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +cmake_minimum_required(VERSION 3.21) + +# Declare Open IoT SDK app interface target +add_library(openiotsdk-storage + FlashBlockDevice.cpp +) + +target_include_directories(openiotsdk-storage + PUBLIC + . + ${CHIP_ROOT}/src/platform/openiotsdk +) + +target_link_libraries(openiotsdk-storage + PUBLIC + mcu-driver-hal + iotsdk-blockdevice +) diff --git a/config/openiotsdk/storage/FlashBlockDevice.cpp b/config/openiotsdk/storage/FlashBlockDevice.cpp new file mode 100644 index 00000000000000..e876dec9eaed19 --- /dev/null +++ b/config/openiotsdk/storage/FlashBlockDevice.cpp @@ -0,0 +1,287 @@ +/* + * + * 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. + */ + +/** + * @file + * Utilities for interacting with the the Open IoT SDK key-value storage. + */ + +#include + +#include "FlashBlockDevice.h" +#include + +extern "C" { +#include +} + +#define FLASH_BASE_ADDRESS (SRAM_BASE_NS) /* 0x01000000 */ +#define FLASH_TOTAL_SIZE (SRAM_SIZE) /* 2 MB */ +#define FLASH_AREA_IMAGE_SECTOR_SIZE (0x1000) /* 4 KB */ +#define FLASH_PAGE_SIZE 256 +#define FLASH_END_ADDRESS (FLASH_BASE_ADDRESS + FLASH_TOTAL_SIZE) +#define FLASH_READ_SIZE 1 +#define FLASH_ERASE_VALUE 0xFFU + +namespace iotsdk { +namespace storage { + +FlashBlockDevice::FlashBlockDevice(uint32_t address, uint32_t size) : _base(address), _size(size), _is_initialized(false) {} + +FlashBlockDevice::~FlashBlockDevice() {} + +bd_status FlashBlockDevice::init() +{ + if (!_base) + { + _base = FLASH_BASE_ADDRESS; + } + + if (!_size) + { + _size = FLASH_TOTAL_SIZE - (_base - FLASH_BASE_ADDRESS); + } + + if (_size + _base > FLASH_TOTAL_SIZE + FLASH_BASE_ADDRESS) + { + return bd_status::INCORRECT_SIZE; + } + + if (_base < FLASH_BASE_ADDRESS) + { + return bd_status::INCORRECT_ADDRESS; + } + + _is_initialized = true; + return bd_status::OK; +} + +bd_status FlashBlockDevice::deinit() +{ + if (!_is_initialized) + { + return bd_status::OK; + } + + _is_initialized = false; + + return bd_status::OK; +} + +bd_status FlashBlockDevice::read(void * buffer, bd_addr_t virtual_address, bd_size_t size) +{ + if (!_is_initialized) + { + return bd_status::DEVICE_NOT_INITIALIZED; + } + + /* Check that the address and size are properly aligned and fit. */ + bd_status status = is_valid_read(virtual_address, size); + if (status != bd_status::OK) + { + return status; + } + + /* Convert virtual address to the physical address for the device. */ + const auto physical_address = static_cast(_base + virtual_address); + + /* Read data */ + memcpy(static_cast(buffer), (void *) physical_address, static_cast(size)); + + return bd_status::OK; +} + +bd_status FlashBlockDevice::program(const void * buffer, bd_addr_t virtual_address, bd_size_t size) +{ + if (!_is_initialized) + { + return bd_status::DEVICE_NOT_INITIALIZED; + } + + /* Check that the address and size are properly aligned and fit. */ + bd_status status = is_valid_program(virtual_address, size); + if (status != bd_status::OK) + { + return status; + } + + /* Convert virtual address to the physical address for the device. */ + auto physical_address = static_cast(_base + virtual_address); + auto remaining_size = static_cast(size); + const auto * buf = static_cast(buffer); + + while (remaining_size > 0) + { + /* Multiple pages can be programmed at once but cannot cross sector boundaries */ + const auto sector_size = FLASH_AREA_IMAGE_SECTOR_SIZE; + const auto sector_end = (physical_address / sector_size + 1) * sector_size; + const auto chunk = (physical_address + remaining_size > sector_end) ? (sector_end - physical_address) : remaining_size; + /* Write data */ + memcpy((void *) physical_address, buf, chunk); + physical_address += chunk; + remaining_size -= chunk; + buf += chunk; + } + + return bd_status::OK; +} + +bd_status FlashBlockDevice::erase(bd_addr_t virtual_address, bd_size_t size) +{ + if (!_is_initialized) + { + return bd_status::DEVICE_NOT_INITIALIZED; + } + + /* Check that the address and size are properly aligned and fit. */ + const bd_status status = is_valid_erase(virtual_address, size); + if (status != bd_status::OK) + { + return status; + } + + /* Convert virtual address to the physical address for the device. */ + auto physical_address = static_cast(_base + virtual_address); + const auto sector_size = FLASH_AREA_IMAGE_SECTOR_SIZE; + const auto erase_region = (physical_address + size) - sector_size; + + while (physical_address <= erase_region) + { + memset((void *) physical_address, FLASH_ERASE_VALUE, FLASH_AREA_IMAGE_SECTOR_SIZE); + physical_address += sector_size; + } + + return bd_status::OK; +} + +bd_size_t FlashBlockDevice::get_read_size() const +{ + return FLASH_READ_SIZE; +} + +bd_size_t FlashBlockDevice::get_program_size() const +{ + if (!_is_initialized) + { + return 0; + } + + return FLASH_PAGE_SIZE; +} + +bd_size_t FlashBlockDevice::get_erase_size() const +{ + return 0; +} + +bd_size_t FlashBlockDevice::get_erase_size(bd_addr_t addr) const +{ + if (!_is_initialized) + { + return 0; + } + + if (static_cast(_base) + addr > UINT32_MAX) + { + return 0; + } + + return FLASH_AREA_IMAGE_SECTOR_SIZE; +} + +int FlashBlockDevice::get_erase_value() const +{ + if (!_is_initialized) + { + return -1; + } + + return FLASH_ERASE_VALUE; +} + +bd_size_t FlashBlockDevice::size() const +{ + return _size; +} + +const char * FlashBlockDevice::get_type() const +{ + return "FLASH_BD"; +} + +bd_status FlashBlockDevice::is_valid_read(bd_addr_t addr, bd_size_t size) const +{ + if (static_cast(_base) + addr > UINT32_MAX) + { + return bd_status::INCORRECT_ADDRESS; + } + + if (size > UINT32_MAX) + { + return bd_status::INCORRECT_SIZE; + } + + return BlockDevice::is_valid_read(addr, size); +} + +bd_status FlashBlockDevice::is_valid_program(bd_addr_t addr, bd_size_t size) const +{ + if (static_cast(_base) + addr > UINT32_MAX) + { + return bd_status::INCORRECT_ADDRESS; + } + + if (size > UINT32_MAX) + { + return bd_status::INCORRECT_SIZE; + } + + return BlockDevice::is_valid_program(addr, size); +} + +bd_status FlashBlockDevice::is_valid_erase(bd_addr_t addr, bd_size_t size) const +{ + if (static_cast(_base) + addr > UINT32_MAX) + { + return bd_status::INCORRECT_ADDRESS; + } + + if (size > UINT32_MAX) + { + return bd_status::INCORRECT_SIZE; + } + + return BlockDevice::is_valid_erase(addr, size); +} + +} // namespace storage +} // namespace iotsdk + +namespace chip { +namespace DeviceLayer { +namespace Internal { + +static iotsdk::storage::FlashBlockDevice gBlockDevice(0, 0); + +iotsdk::storage::BlockDevice * GetBlockDevice() +{ + return &gBlockDevice; +} + +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip diff --git a/config/openiotsdk/storage/FlashBlockDevice.h b/config/openiotsdk/storage/FlashBlockDevice.h new file mode 100644 index 00000000000000..95ba8375e7c9db --- /dev/null +++ b/config/openiotsdk/storage/FlashBlockDevice.h @@ -0,0 +1,185 @@ +/* + * + * 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 + */ + +#ifndef IOTSDK_FLASH_BLOCKDEVICE_H +#define IOTSDK_FLASH_BLOCKDEVICE_H + +#include "iotsdk/BlockDevice.h" + +#include + +namespace iotsdk { +namespace storage { +/** BlockDevice using the flash memory for TF-M application + * + */ +class FlashBlockDevice final : public BlockDevice +{ +public: + /** Creates a FlashBlockDevice + * @param address Physical address where the block device start + * @param size The block device size + */ + FlashBlockDevice(uint32_t address, uint32_t size); + + ~FlashBlockDevice(); + + /** Initialize a block device + * + * This method must be called before attempting any further block device operations. + * + * @return bd_status::OK on success or an error status on failure + */ + bd_status init() override; + + /** Deinitialize a block device + * + * @return bd_status::OK on success or an error status on failure + */ + bd_status deinit() override; + + /** Read blocks from a block device + * + * If a failure occurs, it is not possible to determine how many bytes succeeded. + * + * @param buffer Buffer to write blocks to + * @param addr Address of block to begin reading from + * @param size Size to read in bytes, must be a multiple of the read block size + * @return bd_status::OK on success or an error status on failure + */ + bd_status read(void * buffer, bd_addr_t addr, bd_size_t size) override; + + /** Program blocks to a block device + * + * The blocks must have been erased prior to being programmed. + * + * If a failure occurs, it is not possible to determine how many bytes succeeded. + * + * @param buffer Buffer of data to write to blocks + * @param addr Address of block to begin writing to + * @param size Size to write in bytes, must be a multiple of the program block size + * @return bd_status::OK on success or an error status on failure + */ + bd_status program(const void * buffer, bd_addr_t addr, bd_size_t size) override; + + /** Erase blocks on a block device + * + * The state of an erased block is undefined until it has been programmed, + * unless get_erase_value returns a non-negative byte value. + * + * @param addr Address of block to begin erasing + * @param size Size to erase in bytes, must be a multiple of the erase block size + * @return bd_status::OK on success or an error status on failure + */ + bd_status erase(bd_addr_t addr, bd_size_t size) override; + + /** Get the size of a readable block + * + * @return Size of a readable block in bytes + */ + bd_size_t get_read_size() const override; + + /** Get the size of a programmable block + * + * @return Size of a programmable block in bytes + * @note Must be a multiple of the read size + */ + bd_size_t get_program_size() const override; + + /** Get the size of an erasable block for the whole device + * + * @return Size of an erasable block in bytes for the whole device + * @note Must be a multiple of the program size, or 0 if no common erase size exists + * across all regions or the underlying implementation does not provide this + * information in which case you need to call get_erase_size(bd_addr_t) instead + * @note For FlashBlockDevice, this always returns 0 because the underlying + * MCU-Driver-HAL flash API does not indicate whether all sectors have the same + * size + */ + bd_size_t get_erase_size() const override; + + /** Get the size of an erasable block given address + * + * @param addr Address within the erasable block + * @return Size of an erasable block in bytes + * @note Must be a multiple of the program size + */ + bd_size_t get_erase_size(bd_addr_t addr) const override; + + /** Get the value of storage when erased + * + * If get_erase_value returns a non-negative byte value, the underlying + * storage is set to that value when erased, and storage containing + * that value can be programmed without another erase. + * + * @return The value of storage when erased, or -1 if you can't + * rely on the value of the erased storage + */ + int get_erase_value() const override; + + /** Get the total size of the underlying device + * + * @return Size of the underlying device in bytes + */ + bd_size_t size() const override; + + /** Convenience function for checking block read validity + * + * @param addr Address of block to begin reading from + * @param size Size to read in bytes + * @return bd_status::OK if read is valid for underlying block device + */ + bd_status is_valid_read(bd_addr_t addr, bd_size_t size) const override; + + /** Convenience function for checking block program validity + * + * @param addr Address of block to begin writing to + * @param size Size to write in bytes + * @return bd_status::OK if program is valid for underlying block device + */ + bd_status is_valid_program(bd_addr_t addr, bd_size_t size) const override; + + /** Convenience function for checking block erase validity + * + * @param addr Address of block to begin erasing + * @param size Size to erase in bytes + * @return bd_status::OK if erase is valid for underlying block device + */ + bd_status is_valid_erase(bd_addr_t addr, bd_size_t size) const override; + + /** Get the BlockDevice class type. + * + * @return A string represent the BlockDevice class type. + */ + const char * get_type() const override; + +private: + // Device configuration + uint32_t _base; + uint32_t _size; + bool _is_initialized; +}; + +} // namespace storage +} // namespace iotsdk + +#endif /* IOTSDK_FLASH_BLOCKDEVICE_H */ diff --git a/config/openiotsdk/util.cmake b/config/openiotsdk/util.cmake index 23e0aabe662ee3..cfa34725f781fa 100644 --- a/config/openiotsdk/util.cmake +++ b/config/openiotsdk/util.cmake @@ -137,16 +137,3 @@ function(convert_list_of_flags_to_string_of_flags ptr_list_of_flags string_of_fl # Set the output variable in the parent scope set(${string_of_flags} ${locally_scoped_string_of_flags} PARENT_SCOPE) endfunction() - - -function (get_all_cmake_targets out_var current_dir) - get_property(targets DIRECTORY ${current_dir} PROPERTY BUILDSYSTEM_TARGETS) - get_property(subdirs DIRECTORY ${current_dir} PROPERTY SUBDIRECTORIES) - - foreach(subdir ${subdirs}) - get_all_cmake_targets(subdir_targets ${subdir}) - list(APPEND targets ${subdir_targets}) - endforeach() - - set(${out_var} ${targets} PARENT_SCOPE) -endfunction() \ No newline at end of file diff --git a/config/telink/chip-module/Kconfig b/config/telink/chip-module/Kconfig index aa58ad3c58a8cb..894986b2bf69ec 100644 --- a/config/telink/chip-module/Kconfig +++ b/config/telink/chip-module/Kconfig @@ -1,5 +1,5 @@ # -# Copyright (c) 2022 Project CHIP Authors +# 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. @@ -20,6 +20,16 @@ rsource "../../zephyr/Kconfig" config CHIP_DEVICE_VENDOR_NAME default "Telink semiconductor" +config CHIP_APP_LOG_LEVEL + int "Logging level in application" + default LOG_DEFAULT_LEVEL + depends on LOG + help + Sets the logging level in the Matter application. Use this configuration + option only within the application. To set the logging level for the + Matter stack, use the MATTER_LOG_LEVEL configuration option. + + # See config/zephyr/Kconfig for full definition config CHIP_OTA_REQUESTOR bool @@ -130,3 +140,12 @@ endif #CHIP_FACTORY_DATA_BUILD config CHIP_FACTORY_RESET_ERASE_NVS bool default y + +config CHIP_LOG_SIZE_OPTIMIZATION + bool "Disable some detailed logs to decrease flash usage" + default y + help + Disables some log levels for specific Matter log modules that provide + information that is too detailed to be used in most cases. You can find + full configuration enabled by this option in the + platform/telink/CHIPPlatformConfig.h file. diff --git a/docs/examples/openiotsdk_examples.md b/docs/examples/openiotsdk_examples.md index 36e12236c62172..6cdca9c5a8fdf1 100644 --- a/docs/examples/openiotsdk_examples.md +++ b/docs/examples/openiotsdk_examples.md @@ -140,6 +140,51 @@ Then add the GDB plugin to your development environment: arguments with `docker run` command. Remember add GDB plugin path to environment variable as FAST_MODEL_PLUGINS_PATH inside container. +## Configuration + +### Trusted Firmware-M + +To add [TF-M](https://tf-m-user-guide.trustedfirmware.org) support to Matter +example you need to set `TFM_SUPPORT` variable inside main application +`CMakeLists.txt` file. + +``` +set(TFM_SUPPORT YES) +``` + +This causes the Matter example to be built as non-secure application in +Non-secure Processing Environment (`NSPE`). The bootloader and the secure part +are also built from `TF-M` sources. All components are merged into a single +executable file at the end of the building process. + +You can also provide the own version of Matter example by setting +`TFM_NS_APP_VERSION` variable. + +``` +set(TFM_NS_APP_VERSION "0.0.1") +``` + +### Trusted Firmware-M Protected Storage + +There is an option to add +[TF-M Protected Storage Service](https://tf-m-user-guide.trustedfirmware.org/integration_guide/services/tfm_ps_integration_guide.html) +support for `key-value` storage component in Matter examples. You need to set +`CONFIG_CHIP_OPEN_IOT_SDK_USE_PSA_PS` variable inside main application +`CMakeLists.txt` fi + +``` +set(CONFIG_CHIP_OPEN_IOT_SDK_USE_PSA_PS YES) +``` + +This option causes `key-value` objects will be stored in a secure part of flash +memory and the Protected Storage Service takes care of their encryption and +authentication. + +**NOTE** + +The `TF-M Protected Storage` option requires enabling +[TF-M](#trusted-firmware-m) support. + ## Building You build using a vscode task or call the script directly from the command line. diff --git a/docs/guides/openiotsdk_platform_overview.md b/docs/guides/openiotsdk_platform_overview.md index 2c4d04754dcc4a..211cd1af852179 100644 --- a/docs/guides/openiotsdk_platform_overview.md +++ b/docs/guides/openiotsdk_platform_overview.md @@ -93,3 +93,23 @@ This becomes the lower bound for timers. Drivers are provided by [Reference MCU-Driver-HAL driver implementation for Arm platforms](https://gitlab.arm.com/iot/open-iot-sdk/mcu-driver-hal/mcu-driver-reference-platforms-for-arm) which is provided by Open IoT SDK. + +## Trusted Firmware-M + +[Trusted Firmware-M](https://tf-m-user-guide.trustedfirmware.org) (`TF-M`) +implements the Secure Processing Environment (`SPE`) for `Armv8-M`, `Armv8.1-M` +architectures and dual-core platforms. It is the platform security architecture +reference implementation aligning with `PSA` Certified guidelines, enabling +chips, Real Time Operating Systems and devices to become `PSA` Certified. `TF-M` +relies on an isolation boundary between the Non-secure Processing Environment +(`NSPE`) and the Secure Processing Environment (`SPE`). + +`TF-M` consists of: + +- Secure Boot to authenticate `NSPE` and `SPE` images + +- `TF-M Core` for controlling the isolation, communication and execution + within `SPE` and with `NSPE` + +- Crypto, Internal Trusted Storage (`ITS`), Protected Storage (`PS`), Firmware + Update and Attestation secure services 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 c465f8d350b3b5..3872956148de0d 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 @@ -108,17 +108,21 @@ server cluster Groups = 4 { } server cluster Scenes = 5 { + bitmap SceneFeatures : BITMAP32 { + kSceneNames = 0x1; + } + bitmap ScenesCopyMode : BITMAP8 { kCopyAllScenes = 0x1; } struct ExtensionFieldSet { - cluster_id clusterId = 0; + cluster_id clusterID = 0; AttributeValuePair attributeValueList[] = 1; } struct AttributeValuePair { - optional attrib_id attributeId = 0; + optional attrib_id attributeID = 0; int8u attributeValue[] = 1; } @@ -131,52 +135,52 @@ server cluster Scenes = 5 { readonly attribute int16u clusterRevision = 65533; request struct AddSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; INT16U transitionTime = 2; CHAR_STRING sceneName = 3; ExtensionFieldSet extensionFieldSets[] = 4; } request struct ViewSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; } request struct RemoveSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; } request struct RemoveAllScenesRequest { - group_id groupId = 0; + group_id groupID = 0; } request struct StoreSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; } request struct RecallSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; optional nullable INT16U transitionTime = 2; } request struct GetSceneMembershipRequest { - group_id groupId = 0; + group_id groupID = 0; } response struct AddSceneResponse = 0 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; } response struct ViewSceneResponse = 1 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; optional INT16U transitionTime = 3; optional CHAR_STRING sceneName = 4; optional ExtensionFieldSet extensionFieldSets[] = 5; @@ -184,25 +188,25 @@ server cluster Scenes = 5 { response struct RemoveSceneResponse = 2 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; } response struct RemoveAllScenesResponse = 3 { ENUM8 status = 0; - group_id groupId = 1; + group_id groupID = 1; } response struct StoreSceneResponse = 4 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; } response struct GetSceneMembershipResponse = 6 { ENUM8 status = 0; nullable INT8U capacity = 1; - group_id groupId = 2; + group_id groupID = 2; optional INT8U sceneList[] = 3; } @@ -245,10 +249,6 @@ client cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; @@ -292,10 +292,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; @@ -845,7 +841,7 @@ server cluster PowerSourceConfiguration = 46 { server cluster PowerSource = 47 { enum BatChargeFault : ENUM8 { - kUnspecfied = 0; + kUnspecified = 0; kAmbientTooHot = 1; kAmbientTooCold = 2; kBatteryTooHot = 3; @@ -885,7 +881,7 @@ server cluster PowerSource = 47 { } enum PowerSourceStatus : ENUM8 { - kUnspecfied = 0; + kUnspecified = 0; kActive = 1; kStandby = 2; kUnavailable = 3; @@ -1480,6 +1476,11 @@ server cluster WiFiNetworkDiagnostics = 54 { kAx = 5; } + bitmap WiFiNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + info event Disconnection = 0 { INT16U reasonCode = 0; } @@ -1526,6 +1527,11 @@ server cluster EthernetNetworkDiagnostics = 55 { kRate400G = 9; } + bitmap EthernetNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + readonly attribute nullable PHYRateEnum PHYRate = 0; readonly attribute nullable boolean fullDuplex = 1; readonly attribute int64u packetRxCount = 2; @@ -2665,9 +2671,9 @@ server cluster PumpConfigurationAndControl = 512 { server cluster Thermostat = 513 { enum SetpointAdjustMode : ENUM8 { - kHeatSetpoint = 0; - kCoolSetpoint = 1; - kHeatAndCoolSetpoints = 2; + kHeat = 0; + kCool = 1; + kBoth = 2; } enum ThermostatControlSequence : ENUM8 { @@ -2690,9 +2696,11 @@ server cluster Thermostat = 513 { kAuto = 1; kCool = 3; kHeat = 4; - kEmergencyHeating = 5; + kEmergencyHeat = 5; kPrecooling = 6; kFanOnly = 7; + kDry = 8; + kSleep = 9; } bitmap DayOfWeek : BITMAP8 { @@ -2703,21 +2711,21 @@ server cluster Thermostat = 513 { kThursday = 0x10; kFriday = 0x20; kSaturday = 0x40; - kAwayOrVacation = 0x80; + kAway = 0x80; } bitmap ModeForSequence : BITMAP8 { - kHeatSetpointFieldPresent = 0x1; - kCoolSetpointFieldPresent = 0x2; + kHeatSetpointPresent = 0x1; + kCoolSetpointPresent = 0x2; } bitmap ThermostatFeature : BITMAP32 { kHeating = 0x1; kCooling = 0x2; kOccupancy = 0x4; - kSchedule = 0x8; + kScheduleConfiguration = 0x8; kSetback = 0x10; - kAutomode = 0x20; + kAutoMode = 0x20; } struct ThermostatScheduleTransition { @@ -3583,9 +3591,9 @@ server cluster ApplicationLauncher = 1292 { kApplicationPlatform = 0x1; } - struct Application { - int16u catalogVendorId = 0; - char_string applicationId = 1; + struct ApplicationStruct { + int16u catalogVendorID = 0; + char_string applicationID = 1; } readonly attribute INT16U catalogList[] = 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 eb9b669469f49f..727730b6b6045a 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 @@ -16819,7 +16819,7 @@ "reportableChange": 0 }, { - "name": "IntrinsicBalanceFactor", + "name": "IntrinsicBallastFactor", "code": 20, "mfgCode": null, "side": "server", @@ -18311,7 +18311,7 @@ "outgoing": 1 }, { - "name": "StopPlayback", + "name": "Stop", "code": 2, "mfgCode": null, "source": "client", @@ -18455,7 +18455,7 @@ "code": 3, "mfgCode": null, "side": "server", - "type": "PlaybackPosition", + "type": "PlaybackPositionStruct", "included": 0, "storageOption": "External", "singleton": 0, @@ -19181,7 +19181,7 @@ "code": 1, "mfgCode": null, "side": "server", - "type": "ApplicationEP", + "type": "ApplicationEPStruct", "included": 0, "storageOption": "External", "singleton": 0, diff --git a/examples/all-clusters-app/ameba/main/include/ThermostatCommands.h b/examples/all-clusters-app/ameba/main/include/ThermostatCommands.h index c1444bf332c0ab..31ff5098869680 100644 --- a/examples/all-clusters-app/ameba/main/include/ThermostatCommands.h +++ b/examples/all-clusters-app/ameba/main/include/ThermostatCommands.h @@ -154,7 +154,7 @@ void ProcessThermostatUnicastBindingCommand(BindingCommandData * data, const Emb switch (data->commandId) { case Clusters::Thermostat::Commands::SetpointRaiseLower::Id: - setpointRaiseLowerCommand.mode = static_cast(data->args[0]); + setpointRaiseLowerCommand.mode = static_cast(data->args[0]); setpointRaiseLowerCommand.amount = static_cast(data->args[1]); Controller::InvokeCommandRequest(peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, setpointRaiseLowerCommand, onSuccess, onFailure); @@ -171,7 +171,7 @@ void ProcessThermostatGroupBindingCommand(BindingCommandData * data, const Ember switch (data->commandId) { case Clusters::Thermostat::Commands::SetpointRaiseLower::Id: - setpointRaiseLowerCommand.mode = static_cast(data->args[0]); + setpointRaiseLowerCommand.mode = static_cast(data->args[0]); setpointRaiseLowerCommand.amount = static_cast(data->args[1]); Controller::InvokeGroupCommandRequest(&exchangeMgr, binding.fabricIndex, binding.groupId, setpointRaiseLowerCommand); break; diff --git a/examples/all-clusters-app/esp32/main/AppTask.cpp b/examples/all-clusters-app/esp32/main/AppTask.cpp index 2111d7cb32df47..9a04b23c689d4c 100644 --- a/examples/all-clusters-app/esp32/main/AppTask.cpp +++ b/examples/all-clusters-app/esp32/main/AppTask.cpp @@ -161,6 +161,13 @@ void AppTask::ActionCompleted(BoltLockManager::Action_t aAction) } } +CHIP_ERROR AppTask::LockInit() +{ + ReturnErrorOnFailure(BoltLockMgr().InitLockState()); + BoltLockMgr().SetCallbacks(ActionInitiated, ActionCompleted); + return CHIP_NO_ERROR; +} + CHIP_ERROR AppTask::Init() { /* Print chip information */ @@ -179,10 +186,7 @@ CHIP_ERROR AppTask::Init() (void *) this, // init timer id = app task obj context TimerEventHandler // timer callback handler ); - - CHIP_ERROR err = BoltLockMgr().InitLockState(); - - BoltLockMgr().SetCallbacks(ActionInitiated, ActionCompleted); + VerifyOrReturnError(sFunctionTimer != NULL, CHIP_ERROR_NO_MEMORY, ESP_LOGE(TAG, "Failed to create function selection timer")); statusLED1.Init(STATUS_LED_GPIO_NUM); // Our second LED doesn't map to any physical LEDs so far, just to virtual @@ -199,7 +203,7 @@ CHIP_ERROR AppTask::Init() InitDeviceDisplay(); #endif - return err; + return CHIP_NO_ERROR; } void AppTask::AppTaskMain(void * pvParameter) diff --git a/examples/all-clusters-app/esp32/main/CMakeLists.txt b/examples/all-clusters-app/esp32/main/CMakeLists.txt index cb096a8c1e3262..e642a04553d7c0 100644 --- a/examples/all-clusters-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-app/esp32/main/CMakeLists.txt @@ -26,7 +26,6 @@ set(PRIV_INCLUDE_DIRS_LIST ) set(SRC_DIRS_LIST "${CMAKE_CURRENT_LIST_DIR}" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/all-clusters-app/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" diff --git a/examples/all-clusters-app/esp32/main/include/AppTask.h b/examples/all-clusters-app/esp32/main/include/AppTask.h index 8a72b2d47e5777..779e7e990c12a7 100644 --- a/examples/all-clusters-app/esp32/main/include/AppTask.h +++ b/examples/all-clusters-app/esp32/main/include/AppTask.h @@ -39,6 +39,7 @@ class AppTask void PostEvent(const AppEvent * event); void ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction); static void ButtonPressedAction(AppEvent * aEvent); + CHIP_ERROR LockInit(); private: CHIP_ERROR Init(); diff --git a/examples/all-clusters-app/esp32/main/main.cpp b/examples/all-clusters-app/esp32/main/main.cpp index 1447638bcce0b1..62563025279cbf 100644 --- a/examples/all-clusters-app/esp32/main/main.cpp +++ b/examples/all-clusters-app/esp32/main/main.cpp @@ -115,6 +115,13 @@ static void InitServer(intptr_t context) emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); InitBindingHandlers(); + + CHIP_ERROR err = GetAppTask().LockInit(); + if (err != CHIP_NO_ERROR) + { + ESP_LOGE(TAG, "Failed to initialize app task lock, err:%" CHIP_ERROR_FORMAT, err.Format()); + } + #if CONFIG_DEVICE_TYPE_M5STACK SetupPretendDevices(); #endif diff --git a/examples/all-clusters-app/telink/CMakeLists.txt b/examples/all-clusters-app/telink/CMakeLists.txt index 9b981dfc1766f9..afe18d1cb7c95d 100644 --- a/examples/all-clusters-app/telink/CMakeLists.txt +++ b/examples/all-clusters-app/telink/CMakeLists.txt @@ -55,7 +55,8 @@ target_sources(app PRIVATE ${ALL_CLUSTERS_COMMON_DIR}/src/binding-handler.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp - ${TELINK_COMMON}/util/src/ThreadUtil.cpp) + ${TELINK_COMMON}/util/src/ThreadUtil.cpp + ${TELINK_COMMON}/util/src/PWMDevice.cpp) chip_configure_data_model(app INCLUDE_SERVER diff --git a/examples/all-clusters-app/telink/Readme.md b/examples/all-clusters-app/telink/Readme.md index f436507f9684b6..719656cbcb8484 100644 --- a/examples/all-clusters-app/telink/Readme.md +++ b/examples/all-clusters-app/telink/Readme.md @@ -66,14 +66,31 @@ The following buttons are available on **tlsr9518adk80d** board: ### LEDs -**Red** LED indicates current state of Thread network. It ables to be in +#### Indicate current state of Thread network + +**Red** LED indicates current state of Thread network. It is able to be in following states: | State | Description | | :-------------------------- | :--------------------------------------------------------------------------- | | Blinks with short pulses | Device is not commissioned to Thread, Thread is disabled | -| Blinls with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | -| Blinks with whde pulses | Device commissioned and joined to thread network as CHILD | +| Blinks with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | +| Blinks with wide pulses | Device commissioned and joined to thread network as CHILD | + +#### Indicate identify of device + +**Green** LED used to identify the device. The LED starts blinking when the +Identify command of the Identify cluster is received. The command's argument can +be used to specify the the effect. It is able to be in following effects: + +| Effect | Description | +| :------------------------------ | :------------------------------------------------------------------- | +| Blinks (200 ms on/200 ms off) | Blink (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK) | +| Breathe (during 1000 ms) | Breathe (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE) | +| Blinks (50 ms on/950 ms off) | Okay (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY) | +| Blinks (1000 ms on/1000 ms off) | Channel Change (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE) | +| Blinks (950 ms on/50 ms off) | Finish (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT) | +| LED off | Stop (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT) | ### CHIP tool commands diff --git a/examples/all-clusters-app/telink/include/AppConfig.h b/examples/all-clusters-app/telink/include/AppConfig.h index 27d2cc072c03fc..8eb990230520e6 100644 --- a/examples/all-clusters-app/telink/include/AppConfig.h +++ b/examples/all-clusters-app/telink/include/AppConfig.h @@ -29,6 +29,6 @@ #define BUTTON_PIN_2 0 // LEDs config -// System led config -#define SYSTEM_STATE_LED_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED_PIN 7 +#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) +#define SYSTEM_STATE_LED 7 +#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) diff --git a/examples/all-clusters-app/telink/include/AppEvent.h b/examples/all-clusters-app/telink/include/AppEvent.h index 54250995e06ca8..b6e45d7d1526c8 100644 --- a/examples/all-clusters-app/telink/include/AppEvent.h +++ b/examples/all-clusters-app/telink/include/AppEvent.h @@ -32,6 +32,8 @@ struct AppEvent kEventType_Button = 0, kEventType_Timer, kEventType_UpdateLedState, + kEventType_IdentifyStart, + kEventType_IdentifyStop, }; uint16_t Type; diff --git a/examples/all-clusters-app/telink/include/AppTask.h b/examples/all-clusters-app/telink/include/AppTask.h index 7787968458b867..69e5d61669752b 100644 --- a/examples/all-clusters-app/telink/include/AppTask.h +++ b/examples/all-clusters-app/telink/include/AppTask.h @@ -20,6 +20,7 @@ #include "AppEvent.h" #include "LEDWidget.h" +#include "PWMDevice.h" #include @@ -28,22 +29,25 @@ #include struct k_timer; +struct Identify; class AppTask { public: - CHIP_ERROR StartApp(); + CHIP_ERROR StartApp(void); void PostEvent(AppEvent * event); + static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); private: friend AppTask & GetAppTask(void); + CHIP_ERROR Init(void); - CHIP_ERROR Init(); + static void ActionIdentifyStateUpdateHandler(k_timer * timer); void DispatchEvent(AppEvent * event); - static void UpdateStatusLED(); + static void UpdateStatusLED(void); static void LEDStateUpdateHandler(LEDWidget * ledWidget); static void FactoryResetButtonEventHandler(void); static void StartThreadButtonEventHandler(void); @@ -58,12 +62,14 @@ class AppTask static void StartThreadHandler(AppEvent * aEvent); static void StartBleAdvHandler(AppEvent * aEvent); static void UpdateLedStateEventHandler(AppEvent * aEvent); + static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); static void InitButtons(void); static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); static AppTask sAppTask; + PWMDevice mPwmIdentifyLed; }; inline AppTask & GetAppTask(void) diff --git a/examples/all-clusters-app/telink/prj.conf b/examples/all-clusters-app/telink/prj.conf index 6c7821f2c87ec7..be2598cb6ade52 100644 --- a/examples/all-clusters-app/telink/prj.conf +++ b/examples/all-clusters-app/telink/prj.conf @@ -21,6 +21,9 @@ # enable GPIO CONFIG_GPIO=y +# enable PWM +CONFIG_PWM=y + # OpenThread configs CONFIG_OPENTHREAD_MTD=y CONFIG_OPENTHREAD_FTD=n diff --git a/examples/all-clusters-app/telink/src/AppTask.cpp b/examples/all-clusters-app/telink/src/AppTask.cpp index bc05a343618354..376b0d80b6bc40 100644 --- a/examples/all-clusters-app/telink/src/AppTask.cpp +++ b/examples/all-clusters-app/telink/src/AppTask.cpp @@ -61,13 +61,30 @@ SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); #endif // CONFIG_CHIP_LIB_SHELL -LOG_MODULE_DECLARE(app); +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); + +using namespace ::chip; +using namespace ::chip::app; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; namespace { -constexpr int kFactoryResetTriggerTimeout = 2000; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; +constexpr EndpointId kEndpointId = 1; +constexpr uint8_t kDefaultMinLevel = 0; +constexpr uint8_t kDefaultMaxLevel = 254; +constexpr uint32_t kIdentifyBlinkRateMs = 200; +constexpr uint32_t kIdentifyOkayOnRateMs = 50; +constexpr uint32_t kIdentifyOkayOffRateMs = 950; +constexpr uint32_t kIdentifyFinishOnRateMs = 950; +constexpr uint32_t kIdentifyFinishOffRateMs = 50; +constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; +constexpr uint32_t kIdentifyBreatheRateMs = 1000; + +const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); k_timer sFactoryResetTimer; @@ -88,29 +105,11 @@ chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; void OnIdentifyTriggerEffect(Identify * identify) { - switch (identify->mCurrentEffectIdentifier) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - break; - } - return; + AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); } Identify sIdentify = { - chip::EndpointId{ 1 }, + kEndpointId, [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStart"); }, [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStop"); }, EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, @@ -119,11 +118,6 @@ Identify sIdentify = { } // namespace -using namespace ::chip; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; -using namespace ::chip::DeviceLayer::Internal; - AppTask AppTask::sAppTask; class AppFabricTableDelegate : public FabricTable::Delegate @@ -139,16 +133,14 @@ class AppFabricTableDelegate : public FabricTable::Delegate constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; -CHIP_ERROR AppTask::Init() +CHIP_ERROR AppTask::Init(void) { - CHIP_ERROR ret; - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); // Initialize status LED - LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + LEDWidget::InitGpio(LEDS_PORT); LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED_PIN); + sStatusLED.Init(SYSTEM_STATE_LED); UpdateStatusLED(); @@ -163,6 +155,16 @@ CHIP_ERROR AppTask::Init() (void) initParams.InitializeStaticResourcesBeforeServerInit(); chip::Server::GetInstance().Init(initParams); + // Initialize PWM Identify led + CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("Green IDENTIFY PWM Device Init fail"); + return err; + } + + sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); + // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -181,11 +183,11 @@ CHIP_ERROR AppTask::Init() ConfigurationMgr().LogDeviceConfig(); // Configure Bindings - ret = InitBindingHandlers(); - if (ret != CHIP_NO_ERROR) + err = InitBindingHandlers(); + if (err != CHIP_NO_ERROR) { LOG_ERR("InitBindingHandlers fail"); - return ret; + return err; } PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); @@ -195,24 +197,24 @@ CHIP_ERROR AppTask::Init() // between the main and the CHIP threads. PlatformMgr().AddEventHandler(ChipEventHandler, 0); - ret = ConnectivityMgr().SetBLEDeviceName("TelinkApp"); - if (ret != CHIP_NO_ERROR) + err = ConnectivityMgr().SetBLEDeviceName("TelinkApp"); + if (err != CHIP_NO_ERROR) { LOG_ERR("SetBLEDeviceName fail"); - return ret; + return err; } - ret = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); - if (ret != CHIP_NO_ERROR) + err = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); + if (err != CHIP_NO_ERROR) { LOG_ERR("AppFabricTableDelegate fail"); - return ret; + return err; } return CHIP_NO_ERROR; } -CHIP_ERROR AppTask::StartApp() +CHIP_ERROR AppTask::StartApp(void) { CHIP_ERROR err = Init(); @@ -236,6 +238,56 @@ CHIP_ERROR AppTask::StartApp() } } +void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStart; + + switch (aEffect) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); + event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; + event.Type = AppEvent::kEventType_IdentifyStop; + break; + default: + ChipLogProgress(Zcl, "No identifier effect"); + return; + } + + sAppTask.PostEvent(&event); +} + void AppTask::FactoryResetButtonEventHandler(void) { AppEvent event; @@ -276,7 +328,7 @@ void AppTask::StartThreadHandler(AppEvent * aEvent) if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) { // Switch context from BLE to Thread - BLEManagerImpl sInstance; + Internal::BLEManagerImpl sInstance; sInstance.SwitchToIeee802154(); StartDefaultThreadNetwork(); } @@ -336,7 +388,7 @@ void AppTask::LEDStateUpdateHandler(LEDWidget * ledWidget) sAppTask.PostEvent(&event); } -void AppTask::UpdateStatusLED() +void AppTask::UpdateStatusLED(void) { if (sIsThreadProvisioned && sIsThreadEnabled) { @@ -382,10 +434,21 @@ void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */ } } +void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateIdentifyStateEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) +{ + sAppTask.mPwmIdentifyLed.UpdateAction(); +} + void AppTask::PostEvent(AppEvent * aEvent) { - if (!aEvent) - return; if (k_msgq_put(&sAppEventQueue, aEvent, K_NO_WAIT) != 0) { LOG_INF("PostEvent fail"); @@ -394,8 +457,6 @@ void AppTask::PostEvent(AppEvent * aEvent) void AppTask::DispatchEvent(AppEvent * aEvent) { - if (!aEvent) - return; if (aEvent->Handler) { aEvent->Handler(aEvent); diff --git a/examples/all-clusters-app/telink/src/ZclDoorLockCallbacks.cpp b/examples/all-clusters-app/telink/src/ZclDoorLockCallbacks.cpp index ddf996bfc48f2c..068b990444b4f5 100644 --- a/examples/all-clusters-app/telink/src/ZclDoorLockCallbacks.cpp +++ b/examples/all-clusters-app/telink/src/ZclDoorLockCallbacks.cpp @@ -26,7 +26,7 @@ using namespace ::chip; using namespace ::chip::app::Clusters; using namespace ::chip::app::Clusters::DoorLock; -LOG_MODULE_DECLARE(app, CONFIG_MATTER_LOG_LEVEL); +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); // Provided some empty callbacks and replaced feature map // to simulate DoorLock endpoint for All-Clusters-App example diff --git a/examples/all-clusters-app/telink/src/main.cpp b/examples/all-clusters-app/telink/src/main.cpp index dd1480f6677e45..4061e239ee8fbc 100644 --- a/examples/all-clusters-app/telink/src/main.cpp +++ b/examples/all-clusters-app/telink/src/main.cpp @@ -23,7 +23,7 @@ #include -LOG_MODULE_REGISTER(app); +LOG_MODULE_REGISTER(app, CONFIG_CHIP_APP_LOG_LEVEL); using namespace ::chip; using namespace ::chip::Inet; diff --git a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter index be2a9057302f06..35157a1c70dd3b 100644 --- a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter +++ b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter @@ -6,6 +6,11 @@ struct LabelStruct { char_string<16> value = 1; } +struct ApplicationStruct { + int16u catalogVendorID = 0; + char_string applicationID = 1; +} + server cluster Identify = 3 { enum IdentifyEffectIdentifier : ENUM8 { kBlink = 0; @@ -102,17 +107,21 @@ server cluster Groups = 4 { } server cluster Scenes = 5 { + bitmap SceneFeatures : BITMAP32 { + kSceneNames = 0x1; + } + bitmap ScenesCopyMode : BITMAP8 { kCopyAllScenes = 0x1; } struct ExtensionFieldSet { - cluster_id clusterId = 0; + cluster_id clusterID = 0; AttributeValuePair attributeValueList[] = 1; } struct AttributeValuePair { - optional attrib_id attributeId = 0; + optional attrib_id attributeID = 0; int8u attributeValue[] = 1; } @@ -125,52 +134,52 @@ server cluster Scenes = 5 { readonly attribute int16u clusterRevision = 65533; request struct AddSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; INT16U transitionTime = 2; CHAR_STRING sceneName = 3; ExtensionFieldSet extensionFieldSets[] = 4; } request struct ViewSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; } request struct RemoveSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; } request struct RemoveAllScenesRequest { - group_id groupId = 0; + group_id groupID = 0; } request struct StoreSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; } request struct RecallSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; optional nullable INT16U transitionTime = 2; } request struct GetSceneMembershipRequest { - group_id groupId = 0; + group_id groupID = 0; } response struct AddSceneResponse = 0 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; } response struct ViewSceneResponse = 1 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; optional INT16U transitionTime = 3; optional CHAR_STRING sceneName = 4; optional ExtensionFieldSet extensionFieldSets[] = 5; @@ -178,25 +187,25 @@ server cluster Scenes = 5 { response struct RemoveSceneResponse = 2 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; } response struct RemoveAllScenesResponse = 3 { ENUM8 status = 0; - group_id groupId = 1; + group_id groupID = 1; } response struct StoreSceneResponse = 4 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; } response struct GetSceneMembershipResponse = 6 { ENUM8 status = 0; nullable INT8U capacity = 1; - group_id groupId = 2; + group_id groupID = 2; optional INT8U sceneList[] = 3; } @@ -239,10 +248,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute bitmap32 featureMap = 65532; readonly attribute int16u clusterRevision = 65533; @@ -730,7 +735,7 @@ server cluster PowerSourceConfiguration = 46 { server cluster PowerSource = 47 { enum BatChargeFault : ENUM8 { - kUnspecfied = 0; + kUnspecified = 0; kAmbientTooHot = 1; kAmbientTooCold = 2; kBatteryTooHot = 3; @@ -770,7 +775,7 @@ server cluster PowerSource = 47 { } enum PowerSourceStatus : ENUM8 { - kUnspecfied = 0; + kUnspecified = 0; kActive = 1; kStandby = 2; kUnavailable = 3; @@ -1294,6 +1299,11 @@ server cluster WiFiNetworkDiagnostics = 54 { kAx = 5; } + bitmap WiFiNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + info event Disconnection = 0 { INT16U reasonCode = 0; } @@ -1330,6 +1340,11 @@ server cluster EthernetNetworkDiagnostics = 55 { kRate400G = 9; } + bitmap EthernetNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + readonly attribute nullable PHYRateEnum PHYRate = 0; readonly attribute nullable boolean fullDuplex = 1; readonly attribute int64u packetRxCount = 2; @@ -2257,9 +2272,9 @@ server cluster PumpConfigurationAndControl = 512 { server cluster Thermostat = 513 { enum SetpointAdjustMode : ENUM8 { - kHeatSetpoint = 0; - kCoolSetpoint = 1; - kHeatAndCoolSetpoints = 2; + kHeat = 0; + kCool = 1; + kBoth = 2; } enum ThermostatControlSequence : ENUM8 { @@ -2282,9 +2297,11 @@ server cluster Thermostat = 513 { kAuto = 1; kCool = 3; kHeat = 4; - kEmergencyHeating = 5; + kEmergencyHeat = 5; kPrecooling = 6; kFanOnly = 7; + kDry = 8; + kSleep = 9; } bitmap DayOfWeek : BITMAP8 { @@ -2295,21 +2312,21 @@ server cluster Thermostat = 513 { kThursday = 0x10; kFriday = 0x20; kSaturday = 0x40; - kAwayOrVacation = 0x80; + kAway = 0x80; } bitmap ModeForSequence : BITMAP8 { - kHeatSetpointFieldPresent = 0x1; - kCoolSetpointFieldPresent = 0x2; + kHeatSetpointPresent = 0x1; + kCoolSetpointPresent = 0x2; } bitmap ThermostatFeature : BITMAP32 { kHeating = 0x1; kCooling = 0x2; kOccupancy = 0x4; - kSchedule = 0x8; + kScheduleConfiguration = 0x8; kSetback = 0x10; - kAutomode = 0x20; + kAutoMode = 0x20; } struct ThermostatScheduleTransition { @@ -2639,7 +2656,7 @@ server cluster MediaPlayback = 1286 { command Play(): PlaybackResponse = 0; command Pause(): PlaybackResponse = 1; - command StopPlayback(): PlaybackResponse = 2; + command Stop(): PlaybackResponse = 2; } server cluster MediaInput = 1287 { @@ -2928,30 +2945,25 @@ server cluster ApplicationLauncher = 1292 { kApplicationPlatform = 0x1; } - struct Application { - int16u catalogVendorId = 0; - char_string applicationId = 1; - } - readonly attribute bitmap32 featureMap = 65532; readonly attribute int16u clusterRevision = 65533; request struct LaunchAppRequest { - Application application = 0; + optional ApplicationStruct application = 0; optional OCTET_STRING data = 1; } request struct StopAppRequest { - Application application = 0; + optional ApplicationStruct application = 0; } request struct HideAppRequest { - Application application = 0; + optional ApplicationStruct application = 0; } response struct LauncherResponse = 3 { ApplicationLauncherStatusEnum status = 0; - OCTET_STRING data = 1; + optional OCTET_STRING data = 1; } command LaunchApp(LaunchAppRequest): LauncherResponse = 0; @@ -2967,13 +2979,8 @@ server cluster ApplicationBasic = 1293 { kActiveVisibleNotFocus = 3; } - struct ApplicationBasicApplication { - int16u catalogVendorId = 0; - char_string applicationId = 1; - } - readonly attribute char_string<32> applicationName = 2; - readonly attribute ApplicationBasicApplication application = 4; + readonly attribute ApplicationStruct application = 4; readonly attribute ApplicationStatusEnum status = 5; readonly attribute char_string<32> applicationVersion = 6; readonly attribute vendor_id allowedVendorList[] = 7; diff --git a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap index eab740cb31a262..ef03195bd8b49b 100644 --- a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap +++ b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.zap @@ -16311,7 +16311,7 @@ "reportableChange": 0 }, { - "name": "IntrinsicBalanceFactor", + "name": "IntrinsicBallastFactor", "code": 20, "mfgCode": null, "side": "server", @@ -16461,7 +16461,7 @@ "side": "server", "type": "array", "included": 1, - "storageOption": "RAM", + "storageOption": "External", "singleton": 0, "bounded": 0, "defaultValue": "", @@ -16477,7 +16477,7 @@ "side": "server", "type": "array", "included": 1, - "storageOption": "RAM", + "storageOption": "External", "singleton": 0, "bounded": 0, "defaultValue": "", @@ -16493,7 +16493,7 @@ "side": "server", "type": "array", "included": 1, - "storageOption": "RAM", + "storageOption": "External", "singleton": 0, "bounded": 0, "defaultValue": "", @@ -17811,7 +17811,7 @@ "outgoing": 1 }, { - "name": "StopPlayback", + "name": "Stop", "code": 2, "mfgCode": null, "source": "client", @@ -17965,7 +17965,7 @@ "code": 3, "mfgCode": null, "side": "server", - "type": "PlaybackPosition", + "type": "PlaybackPositionStruct", "included": 0, "storageOption": "External", "singleton": 0, @@ -18717,7 +18717,7 @@ "code": 1, "mfgCode": null, "side": "server", - "type": "ApplicationEP", + "type": "ApplicationEPStruct", "included": 0, "storageOption": "External", "singleton": 0, @@ -18865,7 +18865,7 @@ "code": 4, "mfgCode": null, "side": "server", - "type": "ApplicationBasicApplication", + "type": "ApplicationStruct", "included": 1, "storageOption": "External", "singleton": 0, diff --git a/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt b/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt index 4994beed15155e..b6528fb48e36e5 100644 --- a/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt @@ -26,7 +26,6 @@ set(PRIV_INCLUDE_DIRS_LIST ) set(SRC_DIRS_LIST "${CMAKE_CURRENT_LIST_DIR}" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/all-clusters-minimal-app/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/ota" diff --git a/examples/all-clusters-minimal-app/telink/src/AppTask.cpp b/examples/all-clusters-minimal-app/telink/src/AppTask.cpp index 2b5a51b524f879..1a8c1e08ff2f60 100644 --- a/examples/all-clusters-minimal-app/telink/src/AppTask.cpp +++ b/examples/all-clusters-minimal-app/telink/src/AppTask.cpp @@ -59,7 +59,7 @@ SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); #endif // CONFIG_CHIP_LIB_SHELL -LOG_MODULE_DECLARE(app); +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); namespace { constexpr int kFactoryResetTriggerTimeout = 2000; diff --git a/examples/all-clusters-minimal-app/telink/src/main.cpp b/examples/all-clusters-minimal-app/telink/src/main.cpp index dd1480f6677e45..4061e239ee8fbc 100644 --- a/examples/all-clusters-minimal-app/telink/src/main.cpp +++ b/examples/all-clusters-minimal-app/telink/src/main.cpp @@ -23,7 +23,7 @@ #include -LOG_MODULE_REGISTER(app); +LOG_MODULE_REGISTER(app, CONFIG_CHIP_APP_LOG_LEVEL); using namespace ::chip; using namespace ::chip::Inet; diff --git a/examples/bridge-app/bridge-common/bridge-app.matter b/examples/bridge-app/bridge-common/bridge-app.matter index 9ad049a62dd53c..18cdac8cf27d1c 100644 --- a/examples/bridge-app/bridge-common/bridge-app.matter +++ b/examples/bridge-app/bridge-common/bridge-app.matter @@ -75,10 +75,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute bitmap32 featureMap = 65532; readonly attribute int16u clusterRevision = 65533; @@ -1107,6 +1103,11 @@ server cluster WiFiNetworkDiagnostics = 54 { kAx = 5; } + bitmap WiFiNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + info event Disconnection = 0 { INT16U reasonCode = 0; } @@ -1151,6 +1152,11 @@ server cluster EthernetNetworkDiagnostics = 55 { kRate400G = 9; } + bitmap EthernetNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + readonly attribute nullable PHYRateEnum PHYRate = 0; readonly attribute nullable boolean fullDuplex = 1; readonly attribute int64u packetRxCount = 2; diff --git a/examples/bridge-app/esp32/main/CMakeLists.txt b/examples/bridge-app/esp32/main/CMakeLists.txt index 62b57d8d3fb2e7..407037a0066d5c 100644 --- a/examples/bridge-app/esp32/main/CMakeLists.txt +++ b/examples/bridge-app/esp32/main/CMakeLists.txt @@ -20,7 +20,6 @@ idf_component_register(PRIV_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" SRC_DIRS "${CMAKE_CURRENT_LIST_DIR}" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/bridge-app/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/server" diff --git a/examples/chef/devices/noip_rootnode_dimmablelight_bCwGYSDpoe.matter b/examples/chef/devices/noip_rootnode_dimmablelight_bCwGYSDpoe.matter index 050a119036d258..55066d37b26292 100644 --- a/examples/chef/devices/noip_rootnode_dimmablelight_bCwGYSDpoe.matter +++ b/examples/chef/devices/noip_rootnode_dimmablelight_bCwGYSDpoe.matter @@ -132,10 +132,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; @@ -963,6 +959,11 @@ server cluster WiFiNetworkDiagnostics = 54 { kAx = 5; } + bitmap WiFiNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + info event Disconnection = 0 { INT16U reasonCode = 0; } @@ -1009,6 +1010,11 @@ server cluster EthernetNetworkDiagnostics = 55 { kRate400G = 9; } + bitmap EthernetNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + readonly attribute nullable PHYRateEnum PHYRate = 0; readonly attribute nullable boolean fullDuplex = 1; readonly attribute int64u packetRxCount = 2; diff --git a/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter b/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter index a73febd35b22ab..37ddc92e299bcd 100644 --- a/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter +++ b/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter @@ -138,10 +138,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly nosubscribe attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; diff --git a/examples/chef/devices/rootnode_dimmablelight_bCwGYSDpoe.matter b/examples/chef/devices/rootnode_dimmablelight_bCwGYSDpoe.matter index 5f2806abc28224..45473a2e4140b3 100644 --- a/examples/chef/devices/rootnode_dimmablelight_bCwGYSDpoe.matter +++ b/examples/chef/devices/rootnode_dimmablelight_bCwGYSDpoe.matter @@ -132,10 +132,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; diff --git a/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter b/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter index 29a4b8ca37a86c..a2520e905c4478 100644 --- a/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter +++ b/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter @@ -132,10 +132,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; diff --git a/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter b/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter index b97b9c5f6ba28a..f2d7633500a71d 100644 --- a/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter +++ b/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter @@ -132,10 +132,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute command_id generatedCommandList[] = 65528; readonly attribute command_id acceptedCommandList[] = 65529; @@ -1171,9 +1167,9 @@ server cluster FixedLabel = 64 { client cluster Thermostat = 513 { enum SetpointAdjustMode : ENUM8 { - kHeatSetpoint = 0; - kCoolSetpoint = 1; - kHeatAndCoolSetpoints = 2; + kHeat = 0; + kCool = 1; + kBoth = 2; } enum ThermostatControlSequence : ENUM8 { @@ -1196,9 +1192,11 @@ client cluster Thermostat = 513 { kAuto = 1; kCool = 3; kHeat = 4; - kEmergencyHeating = 5; + kEmergencyHeat = 5; kPrecooling = 6; kFanOnly = 7; + kDry = 8; + kSleep = 9; } bitmap DayOfWeek : BITMAP8 { @@ -1209,21 +1207,21 @@ client cluster Thermostat = 513 { kThursday = 0x10; kFriday = 0x20; kSaturday = 0x40; - kAwayOrVacation = 0x80; + kAway = 0x80; } bitmap ModeForSequence : BITMAP8 { - kHeatSetpointFieldPresent = 0x1; - kCoolSetpointFieldPresent = 0x2; + kHeatSetpointPresent = 0x1; + kCoolSetpointPresent = 0x2; } bitmap ThermostatFeature : BITMAP32 { kHeating = 0x1; kCooling = 0x2; kOccupancy = 0x4; - kSchedule = 0x8; + kScheduleConfiguration = 0x8; kSetback = 0x10; - kAutomode = 0x20; + kAutoMode = 0x20; } readonly attribute nullable int16s localTemperature = 0; diff --git a/examples/chef/devices/rootnode_onofflight_bbs1b7IaOV.matter b/examples/chef/devices/rootnode_onofflight_bbs1b7IaOV.matter index 580ace00aef332..4a2bf2810685a4 100644 --- a/examples/chef/devices/rootnode_onofflight_bbs1b7IaOV.matter +++ b/examples/chef/devices/rootnode_onofflight_bbs1b7IaOV.matter @@ -132,10 +132,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; diff --git a/examples/chef/devices/rootnode_onofflightswitch_FsPlMr090Q.matter b/examples/chef/devices/rootnode_onofflightswitch_FsPlMr090Q.matter index 277af201cfc145..861c60deef8bef 100644 --- a/examples/chef/devices/rootnode_onofflightswitch_FsPlMr090Q.matter +++ b/examples/chef/devices/rootnode_onofflightswitch_FsPlMr090Q.matter @@ -132,10 +132,6 @@ client cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute command_id generatedCommandList[] = 65528; readonly attribute command_id acceptedCommandList[] = 65529; @@ -178,10 +174,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute command_id generatedCommandList[] = 65528; readonly attribute command_id acceptedCommandList[] = 65529; diff --git a/examples/chef/devices/rootnode_onoffpluginunit_Wtf8ss5EBY.matter b/examples/chef/devices/rootnode_onoffpluginunit_Wtf8ss5EBY.matter index 22a24464488aa5..237b62a61af864 100644 --- a/examples/chef/devices/rootnode_onoffpluginunit_Wtf8ss5EBY.matter +++ b/examples/chef/devices/rootnode_onoffpluginunit_Wtf8ss5EBY.matter @@ -132,10 +132,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; diff --git a/examples/chef/devices/rootnode_speaker_RpzeXdimqA.matter b/examples/chef/devices/rootnode_speaker_RpzeXdimqA.matter index 23b37a6390cf72..71a51a8ad27c61 100644 --- a/examples/chef/devices/rootnode_speaker_RpzeXdimqA.matter +++ b/examples/chef/devices/rootnode_speaker_RpzeXdimqA.matter @@ -129,10 +129,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute command_id generatedCommandList[] = 65528; readonly attribute command_id acceptedCommandList[] = 65529; diff --git a/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter b/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter index 3ffcc2edca87a6..5c255f0f39dfff 100644 --- a/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter +++ b/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter @@ -1029,9 +1029,9 @@ server cluster FixedLabel = 64 { server cluster Thermostat = 513 { enum SetpointAdjustMode : ENUM8 { - kHeatSetpoint = 0; - kCoolSetpoint = 1; - kHeatAndCoolSetpoints = 2; + kHeat = 0; + kCool = 1; + kBoth = 2; } enum ThermostatControlSequence : ENUM8 { @@ -1054,9 +1054,11 @@ server cluster Thermostat = 513 { kAuto = 1; kCool = 3; kHeat = 4; - kEmergencyHeating = 5; + kEmergencyHeat = 5; kPrecooling = 6; kFanOnly = 7; + kDry = 8; + kSleep = 9; } bitmap DayOfWeek : BITMAP8 { @@ -1067,21 +1069,21 @@ server cluster Thermostat = 513 { kThursday = 0x10; kFriday = 0x20; kSaturday = 0x40; - kAwayOrVacation = 0x80; + kAway = 0x80; } bitmap ModeForSequence : BITMAP8 { - kHeatSetpointFieldPresent = 0x1; - kCoolSetpointFieldPresent = 0x2; + kHeatSetpointPresent = 0x1; + kCoolSetpointPresent = 0x2; } bitmap ThermostatFeature : BITMAP32 { kHeating = 0x1; kCooling = 0x2; kOccupancy = 0x4; - kSchedule = 0x8; + kScheduleConfiguration = 0x8; kSetback = 0x10; - kAutomode = 0x20; + kAutoMode = 0x20; } readonly attribute nullable int16s localTemperature = 0; diff --git a/examples/chip-tool/BUILD.gn b/examples/chip-tool/BUILD.gn index 1ca148ceeb1246..97df8a48b5051d 100644 --- a/examples/chip-tool/BUILD.gn +++ b/examples/chip-tool/BUILD.gn @@ -28,6 +28,7 @@ assert(chip_build_tools) config("config") { include_dirs = [ ".", + "${chip_root}/examples/common", "${chip_root}/zzz_generated/app-common/app-common", "${chip_root}/zzz_generated/chip-tool", "${chip_root}/src/lib", @@ -59,6 +60,8 @@ static_library("chip-tool-utils") { "commands/common/Commands.h", "commands/common/CredentialIssuerCommands.h", "commands/common/HexConversion.h", + "commands/common/RemoteDataModelLogger.cpp", + "commands/common/RemoteDataModelLogger.h", "commands/delay/SleepCommand.cpp", "commands/delay/WaitForCommissioneeCommand.cpp", "commands/discover/DiscoverCommand.cpp", @@ -85,13 +88,11 @@ static_library("chip-tool-utils") { deps = [] if (config_use_interactive_mode) { - sources += [ - "commands/interactive/InteractiveCommands.cpp", - "commands/interactive/WebSocketServer.cpp", - "commands/interactive/WebSocketServer.h", - "commands/interactive/WebSocketServerDelegate.h", + sources += [ "commands/interactive/InteractiveCommands.cpp" ] + deps += [ + "${chip_root}/examples/common/websocket-server", + "${editline_root}:editline", ] - deps += [ "${editline_root}:editline" ] } if (config_enable_yaml_tests) { @@ -110,10 +111,10 @@ static_library("chip-tool-utils") { "${chip_root}/src/controller/data_model", "${chip_root}/src/credentials:file_attestation_trust_store", "${chip_root}/src/lib", + "${chip_root}/src/lib/support/jsontlv", "${chip_root}/src/platform", "${chip_root}/third_party/inipp", "${chip_root}/third_party/jsoncpp", - "${chip_root}/third_party/libwebsockets", ] public_configs = [ ":config" ] diff --git a/examples/chip-tool/commands/clusters/ClusterCommand.h b/examples/chip-tool/commands/clusters/ClusterCommand.h index c2562843e024a8..eb9a7167948bf5 100644 --- a/examples/chip-tool/commands/clusters/ClusterCommand.h +++ b/examples/chip-tool/commands/clusters/ClusterCommand.h @@ -74,6 +74,8 @@ class ClusterCommand : public InteractionModelCommands, public ModelCommand, pub CHIP_ERROR error = status.ToChipError(); if (CHIP_NO_ERROR != error) { + ReturnOnFailure(RemoteDataModelLogger::LogErrorAsJSON(path, status)); + ChipLogError(chipTool, "Response Failure: %s", chip::ErrorStr(error)); mError = error; return; @@ -81,6 +83,8 @@ class ClusterCommand : public InteractionModelCommands, public ModelCommand, pub if (data != nullptr) { + ReturnOnFailure(RemoteDataModelLogger::LogCommandAsJSON(path, data)); + error = DataModelLogger::LogCommand(path, data); if (CHIP_NO_ERROR != error) { @@ -93,6 +97,8 @@ class ClusterCommand : public InteractionModelCommands, public ModelCommand, pub virtual void OnError(const chip::app::CommandSender * client, CHIP_ERROR error) override { + ReturnOnFailure(RemoteDataModelLogger::LogErrorAsJSON(error)); + ChipLogProgress(chipTool, "Error: %s", chip::ErrorStr(error)); mError = error; } diff --git a/examples/chip-tool/commands/clusters/DataModelLogger.h b/examples/chip-tool/commands/clusters/DataModelLogger.h index 38a2fb1812f3f4..5ffb775d0bf01a 100644 --- a/examples/chip-tool/commands/clusters/DataModelLogger.h +++ b/examples/chip-tool/commands/clusters/DataModelLogger.h @@ -24,7 +24,9 @@ #include #include #include +#include #include +#include #include class DataModelLogger diff --git a/examples/chip-tool/commands/clusters/ReportCommand.h b/examples/chip-tool/commands/clusters/ReportCommand.h index eae5fa8ee51054..98a51cd7232e93 100644 --- a/examples/chip-tool/commands/clusters/ReportCommand.h +++ b/examples/chip-tool/commands/clusters/ReportCommand.h @@ -37,6 +37,8 @@ class ReportCommand : public InteractionModelReports, public ModelCommand, publi CHIP_ERROR error = status.ToChipError(); if (CHIP_NO_ERROR != error) { + ReturnOnFailure(RemoteDataModelLogger::LogErrorAsJSON(path, status)); + ChipLogError(chipTool, "Response Failure: %s", chip::ErrorStr(error)); mError = error; return; @@ -49,6 +51,8 @@ class ReportCommand : public InteractionModelReports, public ModelCommand, publi return; } + ReturnOnFailure(RemoteDataModelLogger::LogAttributeAsJSON(path, data)); + error = DataModelLogger::LogAttribute(path, data); if (CHIP_NO_ERROR != error) { @@ -66,6 +70,8 @@ class ReportCommand : public InteractionModelReports, public ModelCommand, publi CHIP_ERROR error = status->ToChipError(); if (CHIP_NO_ERROR != error) { + ReturnOnFailure(RemoteDataModelLogger::LogErrorAsJSON(eventHeader, *status)); + ChipLogError(chipTool, "Response Failure: %s", chip::ErrorStr(error)); mError = error; return; diff --git a/examples/chip-tool/commands/clusters/WriteAttributeCommand.h b/examples/chip-tool/commands/clusters/WriteAttributeCommand.h index 9b5e8f3ef70728..1b92da403d3dab 100644 --- a/examples/chip-tool/commands/clusters/WriteAttributeCommand.h +++ b/examples/chip-tool/commands/clusters/WriteAttributeCommand.h @@ -109,6 +109,8 @@ class WriteAttribute : public InteractionModelWriter, public ModelCommand, publi CHIP_ERROR error = status.ToChipError(); if (CHIP_NO_ERROR != error) { + ReturnOnFailure(RemoteDataModelLogger::LogErrorAsJSON(path, status)); + ChipLogError(chipTool, "Response Failure: %s", chip::ErrorStr(error)); mError = error; } @@ -116,6 +118,8 @@ class WriteAttribute : public InteractionModelWriter, public ModelCommand, publi void OnError(const chip::app::WriteClient * client, CHIP_ERROR error) override { + ReturnOnFailure(RemoteDataModelLogger::LogErrorAsJSON(error)); + ChipLogProgress(chipTool, "Error: %s", chip::ErrorStr(error)); mError = error; } diff --git a/examples/chip-tool/commands/common/Commands.cpp b/examples/chip-tool/commands/common/Commands.cpp index 4e9c508f0fb4f8..fb675ee96acb4d 100644 --- a/examples/chip-tool/commands/common/Commands.cpp +++ b/examples/chip-tool/commands/common/Commands.cpp @@ -21,11 +21,59 @@ #include "Command.h" #include +#include +#include #include +#include #include #include +#include "../clusters/JsonParser.h" + +namespace { + +char kInteractiveModeName[] = ""; +constexpr size_t kInteractiveModeArgumentsMaxLength = 32; +constexpr const char * kOptionalArgumentPrefix = "--"; +constexpr const char * kJsonClusterKey = "cluster"; +constexpr const char * kJsonCommandKey = "command"; +constexpr const char * kJsonCommandSpecifierKey = "command_specifier"; +constexpr const char * kJsonArgumentsKey = "arguments"; + +std::vector GetArgumentsFromJson(Command * command, Json::Value & value, bool optional) +{ + std::vector args; + for (size_t i = 0; i < command->GetArgumentsCount(); i++) + { + auto argName = command->GetArgumentName(i); + for (auto const & memberName : value.getMemberNames()) + { + if (strcasecmp(argName, memberName.c_str()) != 0) + { + continue; + } + + if (command->GetArgumentIsOptional(i) != optional) + { + continue; + } + + if (optional) + { + args.push_back(std::string(kOptionalArgumentPrefix) + argName); + } + + auto argValue = value[memberName].asString(); + args.push_back(std::move(argValue)); + break; + } + } + return args; +}; + +} // namespace + void Commands::Register(const char * clusterName, commands_list commandsList) { for (auto & command : commandsList) @@ -55,15 +103,42 @@ int Commands::Run(int argc, char ** argv) return (err == CHIP_NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE; } -int Commands::RunInteractive(int argc, char ** argv) +int Commands::RunInteractive(const char * command) { - CHIP_ERROR err = RunCommand(argc, argv, true); - if (err == CHIP_NO_ERROR) + std::vector arguments; + VerifyOrReturnValue(DecodeArgumentsFromInteractiveMode(command, arguments), EXIT_FAILURE); + + if (arguments.size() > (kInteractiveModeArgumentsMaxLength - 1 /* for interactive mode name */)) + { + ChipLogError(chipTool, "Too many arguments. Ignoring."); + arguments.resize(kInteractiveModeArgumentsMaxLength - 1); + } + + int argc = 0; + char * argv[kInteractiveModeArgumentsMaxLength] = {}; + argv[argc++] = kInteractiveModeName; + + std::string commandStr; + for (auto & arg : arguments) + { + argv[argc] = new char[arg.size() + 1]; + strcpy(argv[argc++], arg.c_str()); + commandStr += arg; + commandStr += " "; + } + + ChipLogProgress(chipTool, "Command: %s", commandStr.c_str()); + auto err = RunCommand(argc, argv, true); + + // Do not delete arg[0] + for (auto i = 1; i < argc; i++) { - return EXIT_SUCCESS; + delete[] argv[i]; } - ChipLogError(chipTool, "Run command failure: %s", chip::ErrorStr(err)); - return EXIT_FAILURE; + + VerifyOrReturnValue(CHIP_NO_ERROR == err, EXIT_FAILURE, ChipLogError(chipTool, "Run command failure: %s", chip::ErrorStr(err))); + + return EXIT_SUCCESS; } CHIP_ERROR Commands::RunCommand(int argc, char ** argv, bool interactive) @@ -368,3 +443,90 @@ void Commands::ShowCommand(std::string executable, std::string clusterName, Comm fprintf(stderr, "%s\n", description.c_str()); } } + +bool Commands::DecodeArgumentsFromInteractiveMode(const char * command, std::vector & args) +{ + // Remote clients may not know the ordering of arguments, so instead of a strict ordering arguments can + // be passed in as a json payload encoded in base64 and are reordered on the fly. + return IsJsonString(command) ? DecodeArgumentsFromBase64EncodedJson(command, args) + : DecodeArgumentsFromStringStream(command, args); +} + +bool Commands::DecodeArgumentsFromBase64EncodedJson(const char * json, std::vector & args) +{ + Json::Value jsonValue; + bool parsed = JsonParser::ParseCustomArgument(json, json + kJsonStringPrefixLen, jsonValue); + VerifyOrReturnValue(parsed, false, ChipLogError(chipTool, "Error while parsing json.")); + VerifyOrReturnValue(jsonValue.isObject(), false, ChipLogError(chipTool, "Unexpected json type.")); + VerifyOrReturnValue(jsonValue.isMember(kJsonClusterKey), false, + ChipLogError(chipTool, "'%s' key not found in json.", kJsonClusterKey)); + VerifyOrReturnValue(jsonValue.isMember(kJsonCommandKey), false, + ChipLogError(chipTool, "'%s' key not found in json.", kJsonCommandKey)); + VerifyOrReturnValue(jsonValue.isMember(kJsonArgumentsKey), false, + ChipLogError(chipTool, "'%s' key not found in json.", kJsonArgumentsKey)); + VerifyOrReturnValue(IsBase64String(jsonValue[kJsonArgumentsKey].asString().c_str()), false, + ChipLogError(chipTool, "'arguments' is not a base64 string.")); + + auto clusterName = jsonValue[kJsonClusterKey].asString(); + auto commandName = jsonValue[kJsonCommandKey].asString(); + auto arguments = jsonValue[kJsonArgumentsKey].asString(); + + auto cluster = GetCluster(clusterName); + VerifyOrReturnValue(cluster != mClusters.end(), false, + ChipLogError(chipTool, "Cluster '%s' is not supported.", clusterName.c_str())); + + auto command = GetCommand(cluster->second, commandName); + + if (jsonValue.isMember(kJsonCommandSpecifierKey) && IsGlobalCommand(commandName)) + { + auto commandSpecifierName = jsonValue[kJsonCommandSpecifierKey].asString(); + command = GetGlobalCommand(cluster->second, commandName, commandSpecifierName); + } + VerifyOrReturnValue(nullptr != command, false, ChipLogError(chipTool, "Unknown command.")); + + auto encodedData = arguments.c_str(); + encodedData += kBase64StringPrefixLen; + + size_t encodedDataSize = strlen(encodedData); + size_t expectedMaxDecodedSize = BASE64_MAX_DECODED_LEN(encodedDataSize); + + chip::Platform::ScopedMemoryBuffer decodedData; + VerifyOrReturnValue(decodedData.Calloc(expectedMaxDecodedSize + 1 /* for null */), false); + + size_t decodedDataSize = chip::Base64Decode(encodedData, static_cast(encodedDataSize), decodedData.Get()); + VerifyOrReturnValue(decodedDataSize != 0, false, ChipLogError(chipTool, "Error while decoding base64 data.")); + + decodedData.Get()[decodedDataSize] = '\0'; + + Json::Value jsonArguments; + bool parsedArguments = JsonParser::ParseCustomArgument(encodedData, chip::Uint8::to_char(decodedData.Get()), jsonArguments); + VerifyOrReturnValue(parsedArguments, false, ChipLogError(chipTool, "Error while parsing json.")); + VerifyOrReturnValue(jsonArguments.isObject(), false, ChipLogError(chipTool, "Unexpected json type, expects and object.")); + + auto mandatoryArguments = GetArgumentsFromJson(command, jsonArguments, false /* addOptional */); + auto optionalArguments = GetArgumentsFromJson(command, jsonArguments, true /* addOptional */); + + args.push_back(std::move(clusterName)); + args.push_back(std::move(commandName)); + if (jsonValue.isMember(kJsonCommandSpecifierKey)) + { + auto commandSpecifierName = jsonValue[kJsonCommandSpecifierKey].asString(); + args.push_back(std::move(commandSpecifierName)); + } + args.insert(args.end(), mandatoryArguments.begin(), mandatoryArguments.end()); + args.insert(args.end(), optionalArguments.begin(), optionalArguments.end()); + + return true; +} + +bool Commands::DecodeArgumentsFromStringStream(const char * command, std::vector & args) +{ + std::string arg; + std::stringstream ss(command); + while (ss >> std::quoted(arg, '\'')) + { + args.push_back(std::move(arg)); + } + + return true; +} diff --git a/examples/chip-tool/commands/common/Commands.h b/examples/chip-tool/commands/common/Commands.h index 57475b1c027087..80f585931f65db 100644 --- a/examples/chip-tool/commands/common/Commands.h +++ b/examples/chip-tool/commands/common/Commands.h @@ -32,7 +32,7 @@ class Commands void Register(const char * clusterName, commands_list commandsList); int Run(int argc, char ** argv); - int RunInteractive(int argc, char ** argv); + int RunInteractive(const char * command); private: CHIP_ERROR RunCommand(int argc, char ** argv, bool interactive = false); @@ -50,6 +50,10 @@ class Commands void ShowClusterEvents(std::string executable, std::string clusterName, std::string commandName, CommandsVector & commands); void ShowCommand(std::string executable, std::string clusterName, Command * command); + bool DecodeArgumentsFromInteractiveMode(const char * command, std::vector & args); + bool DecodeArgumentsFromBase64EncodedJson(const char * encodedData, std::vector & args); + bool DecodeArgumentsFromStringStream(const char * command, std::vector & args); + std::map mClusters; #ifdef CONFIG_USE_LOCAL_STORAGE PersistentStorage mStorage; diff --git a/examples/chip-tool/commands/common/CustomStringPrefix.h b/examples/chip-tool/commands/common/CustomStringPrefix.h index a3133b3876b393..b761a358f5850c 100644 --- a/examples/chip-tool/commands/common/CustomStringPrefix.h +++ b/examples/chip-tool/commands/common/CustomStringPrefix.h @@ -18,12 +18,28 @@ #pragma once +static constexpr char kJsonStringPrefix[] = "json:"; +constexpr size_t kJsonStringPrefixLen = ArraySize(kJsonStringPrefix) - 1; // Don't count the null + +static constexpr char kBase64StringPrefix[] = "base64:"; +constexpr size_t kBase64StringPrefixLen = ArraySize(kBase64StringPrefix) - 1; // Don't count the null + static constexpr char kHexStringPrefix[] = "hex:"; constexpr size_t kHexStringPrefixLen = ArraySize(kHexStringPrefix) - 1; // Don't count the null static constexpr char kStrStringPrefix[] = "str:"; constexpr size_t kStrStringPrefixLen = ArraySize(kStrStringPrefix) - 1; // Don't count the null +inline bool IsJsonString(const char * str) +{ + return strncmp(str, kJsonStringPrefix, kJsonStringPrefixLen) == 0; +} + +inline bool IsBase64String(const char * str) +{ + return strncmp(str, kBase64StringPrefix, kBase64StringPrefixLen) == 0; +} + inline bool IsHexString(const char * str) { return strncmp(str, kHexStringPrefix, kHexStringPrefixLen) == 0; diff --git a/examples/chip-tool/commands/common/RemoteDataModelLogger.cpp b/examples/chip-tool/commands/common/RemoteDataModelLogger.cpp new file mode 100644 index 00000000000000..512a28e5ae80c9 --- /dev/null +++ b/examples/chip-tool/commands/common/RemoteDataModelLogger.cpp @@ -0,0 +1,155 @@ +/* + * 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 "RemoteDataModelLogger.h" + +#include + +constexpr const char * kClusterIdKey = "clusterId"; +constexpr const char * kEndpointIdKey = "endpointId"; +constexpr const char * kAttributeIdKey = "attributeId"; +constexpr const char * kEventIdKey = "eventId"; +constexpr const char * kCommandIdKey = "commandId"; +constexpr const char * kErrorIdKey = "error"; +constexpr const char * kClusterErrorIdKey = "clusterError"; + +namespace { +RemoteDataModelLoggerDelegate * gDelegate; + +CHIP_ERROR LogError(Json::Value & value, const chip::app::StatusIB & status) +{ + if (status.mClusterStatus.HasValue()) + { + auto statusValue = status.mClusterStatus.Value(); + value[kClusterErrorIdKey] = statusValue; + } + +#if CHIP_CONFIG_IM_STATUS_CODE_VERBOSE_FORMAT + auto statusName = chip::Protocols::InteractionModel::StatusName(status.mStatus); + value[kErrorIdKey] = statusName; +#else + auto statusName = status.mStatus; + value[kErrorIdKey] = chip::to_underlying(statusName); +#endif // CHIP_CONFIG_IM_STATUS_CODE_VERBOSE_FORMAT + + auto valueStr = chip::JsonToString(value); + return gDelegate->LogJSON(valueStr.c_str()); +} +} // namespace + +namespace RemoteDataModelLogger { +CHIP_ERROR LogAttributeAsJSON(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data) +{ + VerifyOrReturnError(gDelegate != nullptr, CHIP_NO_ERROR); + + Json::Value value; + value[kClusterIdKey] = path.mClusterId; + value[kEndpointIdKey] = path.mEndpointId; + value[kAttributeIdKey] = path.mAttributeId; + + chip::TLV::TLVReader reader; + reader.Init(*data); + ReturnErrorOnFailure(chip::TlvToJson(reader, value)); + + auto valueStr = chip::JsonToString(value); + return gDelegate->LogJSON(valueStr.c_str()); +} + +CHIP_ERROR LogErrorAsJSON(const chip::app::ConcreteDataAttributePath & path, const chip::app::StatusIB & status) +{ + VerifyOrReturnError(gDelegate != nullptr, CHIP_NO_ERROR); + + Json::Value value; + value[kClusterIdKey] = path.mClusterId; + value[kEndpointIdKey] = path.mEndpointId; + value[kAttributeIdKey] = path.mAttributeId; + + return LogError(value, status); +} + +CHIP_ERROR LogCommandAsJSON(const chip::app::ConcreteCommandPath & path, chip::TLV::TLVReader * data) +{ + VerifyOrReturnError(gDelegate != nullptr, CHIP_NO_ERROR); + + Json::Value value; + value[kClusterIdKey] = path.mClusterId; + value[kEndpointIdKey] = path.mEndpointId; + value[kCommandIdKey] = path.mCommandId; + + chip::TLV::TLVReader reader; + reader.Init(*data); + ReturnErrorOnFailure(chip::TlvToJson(reader, value)); + + auto valueStr = chip::JsonToString(value); + return gDelegate->LogJSON(valueStr.c_str()); +} + +CHIP_ERROR LogErrorAsJSON(const chip::app::ConcreteCommandPath & path, const chip::app::StatusIB & status) +{ + VerifyOrReturnError(gDelegate != nullptr, CHIP_NO_ERROR); + + Json::Value value; + value[kClusterIdKey] = path.mClusterId; + value[kEndpointIdKey] = path.mEndpointId; + value[kCommandIdKey] = path.mCommandId; + + return LogError(value, status); +} + +CHIP_ERROR LogEventAsJSON(const chip::app::EventHeader & header, chip::TLV::TLVReader * data) +{ + VerifyOrReturnError(gDelegate != nullptr, CHIP_NO_ERROR); + + Json::Value value; + value[kClusterIdKey] = header.mPath.mClusterId; + value[kEndpointIdKey] = header.mPath.mEndpointId; + value[kEventIdKey] = header.mPath.mEventId; + + chip::TLV::TLVReader reader; + reader.Init(*data); + ReturnErrorOnFailure(chip::TlvToJson(reader, value)); + + auto valueStr = chip::JsonToString(value); + return gDelegate->LogJSON(valueStr.c_str()); +} + +CHIP_ERROR LogErrorAsJSON(const chip::app::EventHeader & header, const chip::app::StatusIB & status) +{ + VerifyOrReturnError(gDelegate != nullptr, CHIP_NO_ERROR); + + Json::Value value; + value[kClusterIdKey] = header.mPath.mClusterId; + value[kEndpointIdKey] = header.mPath.mEndpointId; + value[kEventIdKey] = header.mPath.mEventId; + + return LogError(value, status); +} + +CHIP_ERROR LogErrorAsJSON(const CHIP_ERROR & error) +{ + Json::Value value; + chip::app::StatusIB status; + status.InitFromChipError(error); + return LogError(value, status); +} + +void SetDelegate(RemoteDataModelLoggerDelegate * delegate) +{ + gDelegate = delegate; +} +}; // namespace RemoteDataModelLogger diff --git a/examples/chip-tool/commands/common/RemoteDataModelLogger.h b/examples/chip-tool/commands/common/RemoteDataModelLogger.h new file mode 100644 index 00000000000000..ed9cb1fe09b52d --- /dev/null +++ b/examples/chip-tool/commands/common/RemoteDataModelLogger.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2023 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#pragma once + +#include +#include +#include +#include + +class RemoteDataModelLoggerDelegate +{ +public: + CHIP_ERROR virtual LogJSON(const char *) = 0; + virtual ~RemoteDataModelLoggerDelegate(){}; +}; + +namespace RemoteDataModelLogger { +CHIP_ERROR LogAttributeAsJSON(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data); +CHIP_ERROR LogErrorAsJSON(const chip::app::ConcreteDataAttributePath & path, const chip::app::StatusIB & status); +CHIP_ERROR LogCommandAsJSON(const chip::app::ConcreteCommandPath & path, chip::TLV::TLVReader * data); +CHIP_ERROR LogErrorAsJSON(const chip::app::ConcreteCommandPath & path, const chip::app::StatusIB & status); +CHIP_ERROR LogEventAsJSON(const chip::app::EventHeader & header, chip::TLV::TLVReader * data); +CHIP_ERROR LogErrorAsJSON(const chip::app::EventHeader & header, const chip::app::StatusIB & status); +CHIP_ERROR LogErrorAsJSON(const CHIP_ERROR & error); +void SetDelegate(RemoteDataModelLoggerDelegate * delegate); +}; // namespace RemoteDataModelLogger diff --git a/examples/chip-tool/commands/interactive/InteractiveCommands.cpp b/examples/chip-tool/commands/interactive/InteractiveCommands.cpp index e887391a12031a..f3c76c28881fb1 100644 --- a/examples/chip-tool/commands/interactive/InteractiveCommands.cpp +++ b/examples/chip-tool/commands/interactive/InteractiveCommands.cpp @@ -21,14 +21,13 @@ #include #include -#include -#include -char kInteractiveModeName[] = ""; constexpr const char * kInteractiveModePrompt = ">>> "; -constexpr uint8_t kInteractiveModeArgumentsMaxLength = 32; constexpr const char * kInteractiveModeHistoryFilePath = "/tmp/chip_tool_history"; constexpr const char * kInteractiveModeStopCommand = "quit()"; +constexpr const char * kCategoryError = "Error"; +constexpr const char * kCategoryProgress = "Info"; +constexpr const char * kCategoryDetail = "Debug"; namespace { @@ -44,6 +43,133 @@ void ENFORCE_FORMAT(3, 0) LoggingCallback(const char * module, uint8_t category, ClearLine(); } +struct InteractiveServerResultLog +{ + std::string module; + std::string message; + std::string messageType; +}; + +struct InteractiveServerResult +{ + bool mEnabled = false; + bool mIsAsyncReport = false; + int mStatus = EXIT_SUCCESS; + std::vector mResults; + std::vector mLogs; + + void Setup(bool isAsyncReport) + { + mEnabled = true; + mIsAsyncReport = isAsyncReport; + } + + void Reset() + { + mEnabled = false; + mIsAsyncReport = false; + mStatus = EXIT_SUCCESS; + mResults.clear(); + mLogs.clear(); + } + + bool IsAsyncReport() const { return mIsAsyncReport; } + + void MaybeAddLog(const char * module, uint8_t category, const char * base64Message) + { + VerifyOrReturn(mEnabled); + + const char * messageType = nullptr; + switch (category) + { + case chip::Logging::kLogCategory_Error: + messageType = kCategoryError; + break; + case chip::Logging::kLogCategory_Progress: + messageType = kCategoryProgress; + break; + case chip::Logging::kLogCategory_Detail: + messageType = kCategoryDetail; + break; + } + + mLogs.push_back(InteractiveServerResultLog({ module, base64Message, messageType })); + } + + void MaybeAddResult(const char * result) + { + VerifyOrReturn(mEnabled); + mResults.push_back(result); + } + + std::string AsJsonString() const + { + std::string resultsStr; + if (mResults.size()) + { + for (const auto & result : mResults) + { + resultsStr = resultsStr + result + ","; + } + + // Remove last comma. + resultsStr.pop_back(); + } + + if (mStatus != EXIT_SUCCESS) + { + if (resultsStr.size()) + { + resultsStr = resultsStr + ","; + } + resultsStr = resultsStr + "{ \"error\": \"FAILURE\" }"; + } + + std::string logsStr; + if (mLogs.size()) + { + for (const auto & log : mLogs) + { + logsStr = logsStr + "{"; + logsStr = logsStr + " \"module\": \"" + log.module + "\","; + logsStr = logsStr + " \"category\": \"" + log.messageType + "\","; + logsStr = logsStr + " \"message\": \"" + log.message + "\""; + logsStr = logsStr + "},"; + } + + // Remove last comma. + logsStr.pop_back(); + } + + std::string jsonLog; + jsonLog = jsonLog + "{"; + jsonLog = jsonLog + " \"results\": [" + resultsStr + "],"; + jsonLog = jsonLog + " \"logs\": [" + logsStr + "]"; + jsonLog = jsonLog + "}"; + + return jsonLog; + } +}; + +InteractiveServerResult gInteractiveServerResult; + +void ENFORCE_FORMAT(3, 0) InteractiveServerLoggingCallback(const char * module, uint8_t category, const char * msg, va_list args) +{ + va_list args_copy; + va_copy(args_copy, args); + + chip::Logging::Platform::LogV(module, category, msg, args); + + char message[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; + vsnprintf(message, sizeof(message), msg, args_copy); + va_end(args_copy); + + char base64Message[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE * 2] = {}; + chip::Base64Encode(chip::Uint8::from_char(message), static_cast(strlen(message)), base64Message); + + gInteractiveServerResult.MaybeAddLog(module, category, base64Message); +} + char * GetCommand(char * command) { if (command != nullptr) @@ -67,15 +193,44 @@ char * GetCommand(char * command) CHIP_ERROR InteractiveServerCommand::RunCommand() { + // Logs needs to be redirected in order to refresh the screen appropriately when something + // is dumped to stdout while the user is typing a command. + chip::Logging::SetLogRedirectCallback(InteractiveServerLoggingCallback); + + RemoteDataModelLogger::SetDelegate(this); ReturnErrorOnFailure(mWebSocketServer.Run(mPort, this)); + gInteractiveServerResult.Reset(); SetCommandExitStatus(CHIP_NO_ERROR); return CHIP_NO_ERROR; } +void SendOverWebSocket(intptr_t context) +{ + auto server = reinterpret_cast(context); + server->Send(gInteractiveServerResult.AsJsonString().c_str()); + gInteractiveServerResult.Reset(); +} + bool InteractiveServerCommand::OnWebSocketMessageReceived(char * msg) { - return ParseCommand(msg); + bool isAsyncReport = strlen(msg) == 0; + gInteractiveServerResult.Setup(isAsyncReport); + VerifyOrReturnValue(!isAsyncReport, true); + + auto shouldStop = ParseCommand(msg, &gInteractiveServerResult.mStatus); + chip::DeviceLayer::PlatformMgr().ScheduleWork(SendOverWebSocket, reinterpret_cast(&mWebSocketServer)); + return shouldStop; +} + +CHIP_ERROR InteractiveServerCommand::LogJSON(const char * json) +{ + gInteractiveServerResult.MaybeAddResult(json); + if (gInteractiveServerResult.IsAsyncReport()) + { + chip::DeviceLayer::PlatformMgr().ScheduleWork(SendOverWebSocket, reinterpret_cast(&mWebSocketServer)); + } + return CHIP_NO_ERROR; } CHIP_ERROR InteractiveStartCommand::RunCommand() @@ -87,10 +242,11 @@ CHIP_ERROR InteractiveStartCommand::RunCommand() chip::Logging::SetLogRedirectCallback(LoggingCallback); char * command = nullptr; + int status; while (true) { command = GetCommand(command); - if (command != nullptr && !ParseCommand(command)) + if (command != nullptr && !ParseCommand(command, &status)) { break; } @@ -106,7 +262,7 @@ CHIP_ERROR InteractiveStartCommand::RunCommand() return CHIP_NO_ERROR; } -bool InteractiveCommand::ParseCommand(char * command) +bool InteractiveCommand::ParseCommand(char * command, int * status) { if (strcmp(command, kInteractiveModeStopCommand) == 0) { @@ -114,31 +270,9 @@ bool InteractiveCommand::ParseCommand(char * command) return false; } - char * args[kInteractiveModeArgumentsMaxLength]; - args[0] = kInteractiveModeName; - int argsCount = 1; - std::string arg; - - std::stringstream ss(command); - while (ss >> std::quoted(arg, '\'')) - { - if (argsCount == kInteractiveModeArgumentsMaxLength) - { - ChipLogError(chipTool, "Too many arguments. Ignoring."); - return true; - } - - char * carg = new char[arg.size() + 1]; - strcpy(carg, arg.c_str()); - args[argsCount++] = carg; - } - ClearLine(); - mHandler->RunInteractive(argsCount, args); - // Do not delete arg[0] - while (--argsCount) - delete[] args[argsCount]; + *status = mHandler->RunInteractive(command); return true; } diff --git a/examples/chip-tool/commands/interactive/InteractiveCommands.h b/examples/chip-tool/commands/interactive/InteractiveCommands.h index 830c9d5fd408f2..49e6432ccb7f01 100644 --- a/examples/chip-tool/commands/interactive/InteractiveCommands.h +++ b/examples/chip-tool/commands/interactive/InteractiveCommands.h @@ -18,10 +18,11 @@ #pragma once +#include "../clusters/DataModelLogger.h" #include "../common/CHIPCommand.h" #include "../common/Commands.h" -#include "WebSocketServer.h" +#include class Commands; @@ -35,7 +36,7 @@ class InteractiveCommand : public CHIPCommand /////////// CHIPCommand Interface ///////// chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(0); } - bool ParseCommand(char * command); + bool ParseCommand(char * command, int * status); private: Commands * mHandler = nullptr; @@ -52,7 +53,7 @@ class InteractiveStartCommand : public InteractiveCommand CHIP_ERROR RunCommand() override; }; -class InteractiveServerCommand : public InteractiveCommand, public WebSocketServerDelegate +class InteractiveServerCommand : public InteractiveCommand, public WebSocketServerDelegate, public RemoteDataModelLoggerDelegate { public: InteractiveServerCommand(Commands * commandsHandler, CredentialIssuerCommands * credsIssuerConfig) : @@ -67,6 +68,9 @@ class InteractiveServerCommand : public InteractiveCommand, public WebSocketServ /////////// WebSocketServerDelegate Interface ///////// bool OnWebSocketMessageReceived(char * msg) override; + /////////// RemoteDataModelLoggerDelegate interface ///////// + CHIP_ERROR LogJSON(const char * json) override; + private: WebSocketServer mWebSocketServer; chip::Optional mPort; diff --git a/examples/chip-tool/commands/pairing/PairingCommand.cpp b/examples/chip-tool/commands/pairing/PairingCommand.cpp index 9c185024ad2075..ec8deb76a6081f 100644 --- a/examples/chip-tool/commands/pairing/PairingCommand.cpp +++ b/examples/chip-tool/commands/pairing/PairingCommand.cpp @@ -72,6 +72,10 @@ CommissioningParameters PairingCommand::GetCommissioningParameters() { auto params = CommissioningParameters(); params.SetSkipCommissioningComplete(mSkipCommissioningComplete.ValueOr(false)); + if (mBypassAttestationVerifier.ValueOr(false)) + { + params.SetDeviceAttestationDelegate(this); + } switch (mNetworkType) { @@ -281,3 +285,19 @@ void PairingCommand::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E command->SetCommandExitStatus(err); } + +chip::Optional PairingCommand::FailSafeExpiryTimeoutSecs() const +{ + // We don't need to set additional failsafe timeout as we don't ask the final user if he wants to continue + return chip::Optional(); +} + +void PairingCommand::OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, + chip::DeviceProxy * device, + const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, + chip::Credentials::AttestationVerificationResult attestationResult) +{ + // Bypass attestation verification, continue with success + deviceCommissioner->ContinueCommissioningAfterDeviceAttestation(device, + chip::Credentials::AttestationVerificationResult::kSuccess); +} diff --git a/examples/chip-tool/commands/pairing/PairingCommand.h b/examples/chip-tool/commands/pairing/PairingCommand.h index 4919ec89de8ad1..142a09013806af 100644 --- a/examples/chip-tool/commands/pairing/PairingCommand.h +++ b/examples/chip-tool/commands/pairing/PairingCommand.h @@ -48,7 +48,8 @@ enum class PairingNetworkType class PairingCommand : public CHIPCommand, public chip::Controller::DevicePairingDelegate, - public chip::Controller::DeviceDiscoveryDelegate + public chip::Controller::DeviceDiscoveryDelegate, + public chip::Credentials::DeviceAttestationDelegate { public: PairingCommand(const char * commandName, PairingMode mode, PairingNetworkType networkType, @@ -60,6 +61,9 @@ class PairingCommand : public CHIPCommand, mCurrentFabricRemoveCallback(OnCurrentFabricRemove, this) { AddArgument("node-id", 0, UINT64_MAX, &mNodeId); + AddArgument("bypass-attestation-verifier", 0, 1, &mBypassAttestationVerifier, + "Bypass the attestation verifier. If not provided or false, the attestation verifier is not bypassed." + " If true, the commissioning will continue in case of attestation verification failure."); switch (networkType) { @@ -158,6 +162,12 @@ class PairingCommand : public CHIPCommand, void OnDiscoveredDevice(const chip::Dnssd::DiscoveredNodeData & nodeData) override; bool IsDiscoverOnce() { return mDiscoverOnce.ValueOr(false); } + /////////// DeviceAttestationDelegate ///////// + chip::Optional FailSafeExpiryTimeoutSecs() const override; + void OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, chip::DeviceProxy * device, + const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, + chip::Credentials::AttestationVerificationResult attestationResult) override; + private: CHIP_ERROR RunInternal(NodeId remoteId); CHIP_ERROR Pair(NodeId remoteId, PeerAddress address); @@ -177,6 +187,7 @@ class PairingCommand : public CHIPCommand, chip::Optional mUseOnlyOnNetworkDiscovery; chip::Optional mPaseOnly; chip::Optional mSkipCommissioningComplete; + chip::Optional mBypassAttestationVerifier; uint16_t mRemotePort; uint16_t mDiscriminator; uint32_t mSetupPINCode; diff --git a/src/app/tests/suites/certification/Test_TC_DGSW_3_2_Simulated.yaml b/examples/common/websocket-server/BUILD.gn similarity index 55% rename from src/app/tests/suites/certification/Test_TC_DGSW_3_2_Simulated.yaml rename to examples/common/websocket-server/BUILD.gn index 221e0a80ab17a1..fdd17300cecd06 100644 --- a/src/app/tests/suites/certification/Test_TC_DGSW_3_2_Simulated.yaml +++ b/examples/common/websocket-server/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Project CHIP Authors +# 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. @@ -12,21 +12,20 @@ # See the License for the specific language governing permissions and # limitations under the License. -name: 44.3.2. [TC-DGSW-3.2] Commands Generated [DUT as Client] +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") -PICS: - - DGSW.C +static_library("websocket-server") { + output_name = "libWebSocketServer" -config: - nodeId: 0x12344321 - cluster: "Software Diagnostics" - endpoint: 0 + sources = [ + "WebSocketServer.cpp", + "WebSocketServer.h", + "WebSocketServerDelegate.h", + ] -tests: - - label: "Wait for the device to be commissioned" - cluster: "DelayCommands" - command: "WaitForCommissioning" - - - label: "DUT sends ResetWatermarks to TH" - PICS: DGSW.C.C00.Tx - wait: "ResetWatermarks" + public_deps = [ + "${chip_root}/src/lib/support", + "${chip_root}/third_party/libwebsockets", + ] +} diff --git a/examples/chip-tool/commands/interactive/WebSocketServer.cpp b/examples/common/websocket-server/WebSocketServer.cpp similarity index 87% rename from examples/chip-tool/commands/interactive/WebSocketServer.cpp rename to examples/common/websocket-server/WebSocketServer.cpp index c7269b38af538f..867180b976c012 100644 --- a/examples/chip-tool/commands/interactive/WebSocketServer.cpp +++ b/examples/common/websocket-server/WebSocketServer.cpp @@ -18,10 +18,15 @@ #include "WebSocketServer.h" +#include +#include + constexpr uint16_t kDefaultWebSocketServerPort = 9002; constexpr uint16_t kMaxMessageBufferLen = 8192; namespace { +lws * gWebSocketInstance = nullptr; + void LogWebSocketCallbackReason(lws_callback_reasons reason) { #if CHIP_DETAIL_LOGGING @@ -121,6 +126,14 @@ static int OnWebSocketCallback(lws * wsi, lws_callback_reasons reason, void * us { lws_callback_on_writable(wsi); } + else if (LWS_CALLBACK_ESTABLISHED == reason) + { + gWebSocketInstance = wsi; + } + else if (LWS_CALLBACK_WSI_DESTROY == reason) + { + gWebSocketInstance = nullptr; + } return 0; } @@ -145,3 +158,15 @@ CHIP_ERROR WebSocketServer::Run(chip::Optional port, WebSocketServerDe lws_context_default_loop_run_destroy(context); return CHIP_NO_ERROR; } + +CHIP_ERROR WebSocketServer::Send(const char * msg) +{ + VerifyOrReturnError(nullptr != gWebSocketInstance, CHIP_ERROR_INCORRECT_STATE); + + chip::Platform::ScopedMemoryBuffer buffer; + VerifyOrReturnError(buffer.Calloc(LWS_PRE + strlen(msg)), CHIP_ERROR_NO_MEMORY); + memcpy(&buffer[LWS_PRE], (void *) msg, strlen(msg)); + lws_write(gWebSocketInstance, &buffer[LWS_PRE], strlen(msg), LWS_WRITE_TEXT); + + return CHIP_NO_ERROR; +} diff --git a/examples/chip-tool/commands/interactive/WebSocketServer.h b/examples/common/websocket-server/WebSocketServer.h similarity index 95% rename from examples/chip-tool/commands/interactive/WebSocketServer.h rename to examples/common/websocket-server/WebSocketServer.h index d24ab07f88f217..712cf185d8f4a0 100644 --- a/examples/chip-tool/commands/interactive/WebSocketServer.h +++ b/examples/common/websocket-server/WebSocketServer.h @@ -22,10 +22,10 @@ #include #include -#include class WebSocketServer { public: CHIP_ERROR Run(chip::Optional port, WebSocketServerDelegate * delegate); + CHIP_ERROR Send(const char * msg); }; diff --git a/examples/chip-tool/commands/interactive/WebSocketServerDelegate.h b/examples/common/websocket-server/WebSocketServerDelegate.h similarity index 100% rename from examples/chip-tool/commands/interactive/WebSocketServerDelegate.h rename to examples/common/websocket-server/WebSocketServerDelegate.h diff --git a/examples/contact-sensor-app/contact-sensor-common/contact-sensor-app.matter b/examples/contact-sensor-app/contact-sensor-common/contact-sensor-app.matter index 45e8e9e93c221c..99a39ebfebd41b 100644 --- a/examples/contact-sensor-app/contact-sensor-common/contact-sensor-app.matter +++ b/examples/contact-sensor-app/contact-sensor-common/contact-sensor-app.matter @@ -951,6 +951,11 @@ server cluster WiFiNetworkDiagnostics = 54 { kAx = 5; } + bitmap WiFiNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + info event Disconnection = 0 { INT16U reasonCode = 0; } @@ -997,6 +1002,11 @@ server cluster EthernetNetworkDiagnostics = 55 { kRate400G = 9; } + bitmap EthernetNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + readonly attribute nullable PHYRateEnum PHYRate = 0; readonly attribute nullable boolean fullDuplex = 1; readonly attribute int64u packetRxCount = 2; diff --git a/examples/contact-sensor-app/telink/CMakeLists.txt b/examples/contact-sensor-app/telink/CMakeLists.txt index a2ddd3d332163f..144d1eaab34f88 100755 --- a/examples/contact-sensor-app/telink/CMakeLists.txt +++ b/examples/contact-sensor-app/telink/CMakeLists.txt @@ -51,7 +51,8 @@ target_sources(app PRIVATE src/ZclCallbacks.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp - ${TELINK_COMMON}/util/src/ThreadUtil.cpp) + ${TELINK_COMMON}/util/src/ThreadUtil.cpp + ${TELINK_COMMON}/util/src/PWMDevice.cpp) chip_configure_data_model(app INCLUDE_SERVER diff --git a/examples/contact-sensor-app/telink/README.md b/examples/contact-sensor-app/telink/README.md index 31b004dd7aaa5b..a41fadcc3bacb8 100755 --- a/examples/contact-sensor-app/telink/README.md +++ b/examples/contact-sensor-app/telink/README.md @@ -64,14 +64,33 @@ The following buttons are available on **tlsr9518adk80d** board: ### LEDs -**Red** LED indicates current state of Thread network. It ables to be in +#### Indicate current state of Thread network + +**Red** LED indicates current state of Thread network. It is able to be in following states: | State | Description | | :-------------------------- | :--------------------------------------------------------------------------- | | Blinks with short pulses | Device is not commissioned to Thread, Thread is disabled | -| Blinls with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | -| Blinks with whde pulses | Device commissioned and joined to thread network as CHILD | +| Blinks with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | +| Blinks with wide pulses | Device commissioned and joined to thread network as CHILD | + +#### Indicate identify of device + +**Green** LED used to identify the device. The LED starts blinking when the +Identify command of the Identify cluster is received. The command's argument can +be used to specify the the effect. It is able to be in following effects: + +| Effect | Description | +| :------------------------------ | :------------------------------------------------------------------- | +| Blinks (200 ms on/200 ms off) | Blink (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK) | +| Breathe (during 1000 ms) | Breathe (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE) | +| Blinks (50 ms on/950 ms off) | Okay (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY) | +| Blinks (1000 ms on/1000 ms off) | Channel Change (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE) | +| Blinks (950 ms on/50 ms off) | Finish (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT) | +| LED off | Stop (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT) | + +#### Indicate current state of Contact Sensor **Blue** LED shows current state of Contact Sensor diff --git a/examples/contact-sensor-app/telink/include/AppConfig.h b/examples/contact-sensor-app/telink/include/AppConfig.h index 01128b76e4d929..4e4f556036bcfa 100755 --- a/examples/contact-sensor-app/telink/include/AppConfig.h +++ b/examples/contact-sensor-app/telink/include/AppConfig.h @@ -29,9 +29,7 @@ #define BUTTON_PIN_2 0 // LEDs config -// System led config -#define SYSTEM_STATE_LED_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED_PIN 7 - -// Contact state led -#define CONTACT_STATE_LED_PIN 4 +#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) +#define SYSTEM_STATE_LED 7 +#define CONTACT_STATE_LED 4 +#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) diff --git a/examples/contact-sensor-app/telink/include/AppEvent.h b/examples/contact-sensor-app/telink/include/AppEvent.h index 4051ba31cbb465..5306a8076d0804 100755 --- a/examples/contact-sensor-app/telink/include/AppEvent.h +++ b/examples/contact-sensor-app/telink/include/AppEvent.h @@ -32,6 +32,8 @@ struct AppEvent kEventType_Button = 0, kEventType_Timer, kEventType_UpdateLedState, + kEventType_IdentifyStart, + kEventType_IdentifyStop, kEventType_Contact, }; diff --git a/examples/contact-sensor-app/telink/include/AppTask.h b/examples/contact-sensor-app/telink/include/AppTask.h index ad6f98c7c2cf66..0cf75d63696004 100644 --- a/examples/contact-sensor-app/telink/include/AppTask.h +++ b/examples/contact-sensor-app/telink/include/AppTask.h @@ -21,6 +21,7 @@ #include "AppEvent.h" #include "ContactSensorManager.h" #include "LEDWidget.h" +#include "PWMDevice.h" #include @@ -36,14 +37,17 @@ #define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) struct k_timer; +struct Identify; class AppTask { public: CHIP_ERROR StartApp(void); - void PostContactActionRequest(ContactSensorManager::Action aAction); void PostEvent(AppEvent * event); + static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); + + void PostContactActionRequest(ContactSensorManager::Action aAction); void UpdateClusterState(void); void UpdateDeviceState(void); @@ -54,6 +58,8 @@ class AppTask friend AppTask & GetAppTask(void); CHIP_ERROR Init(void); + static void ActionIdentifyStateUpdateHandler(k_timer * timer); + void DispatchEvent(AppEvent * event); static void OnStateChanged(ContactSensorManager::State aState); @@ -76,6 +82,7 @@ class AppTask static void StartBleAdvHandler(AppEvent * aEvent); static void ContactActionEventHandler(AppEvent * aEvent); static void UpdateLedStateEventHandler(AppEvent * aEvent); + static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); static void InitButtons(void); @@ -84,6 +91,7 @@ class AppTask bool mSyncClusterToButtonAction = false; static AppTask sAppTask; + PWMDevice mPwmIdentifyLed; #if CONFIG_CHIP_FACTORY_DATA // chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; diff --git a/examples/contact-sensor-app/telink/prj.conf b/examples/contact-sensor-app/telink/prj.conf index 6c4ad9d8975f05..3c582145b38a29 100755 --- a/examples/contact-sensor-app/telink/prj.conf +++ b/examples/contact-sensor-app/telink/prj.conf @@ -21,6 +21,9 @@ # enable GPIO CONFIG_GPIO=y +# enable PWM +CONFIG_PWM=y + # OpenThread configs CONFIG_OPENTHREAD_MTD=y CONFIG_OPENTHREAD_FTD=n diff --git a/examples/contact-sensor-app/telink/src/AppTask.cpp b/examples/contact-sensor-app/telink/src/AppTask.cpp index a2dc322fcc50de..d237054a062794 100644 --- a/examples/contact-sensor-app/telink/src/AppTask.cpp +++ b/examples/contact-sensor-app/telink/src/AppTask.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include #include #include @@ -43,7 +42,7 @@ #include #include -LOG_MODULE_DECLARE(app); +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); using namespace ::chip; using namespace ::chip::app; @@ -51,16 +50,28 @@ using namespace ::chip::Credentials; using namespace ::chip::DeviceLayer; namespace { +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; +constexpr EndpointId kEndpointId = 1; +constexpr uint8_t kDefaultMinLevel = 0; +constexpr uint8_t kDefaultMaxLevel = 254; +constexpr uint32_t kIdentifyBlinkRateMs = 200; +constexpr uint32_t kIdentifyOkayOnRateMs = 50; +constexpr uint32_t kIdentifyOkayOffRateMs = 950; +constexpr uint32_t kIdentifyFinishOnRateMs = 950; +constexpr uint32_t kIdentifyFinishOffRateMs = 50; +constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; +constexpr uint32_t kIdentifyBreatheRateMs = 1000; + +const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; -constexpr int kFactoryResetTriggerTimeout = 2000; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; - +#if CONFIG_CHIP_FACTORY_DATA // NOTE! This key is for test/certification only and should not be available in production devices! -// If CONFIG_CHIP_FACTORY_DATA is enabled, this value is read from the factory data. uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; +#endif K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); k_timer sFactoryResetTimer; @@ -82,29 +93,11 @@ chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; void OnIdentifyTriggerEffect(Identify * identify) { - switch (identify->mCurrentEffectIdentifier) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - break; - } - return; + AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); } Identify sIdentify = { - chip::EndpointId{ 1 }, + kEndpointId, [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStart"); }, [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStop"); }, EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, @@ -126,20 +119,18 @@ class AppFabricTableDelegate : public FabricTable::Delegate } }; -CHIP_ERROR AppTask::Init() +CHIP_ERROR AppTask::Init(void) { - CHIP_ERROR err; - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); // Initialize status LED - LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + LEDWidget::InitGpio(LEDS_PORT); LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED_PIN); + sStatusLED.Init(SYSTEM_STATE_LED); UpdateStatusLED(); - sContactSensorLED.Init(CONTACT_STATE_LED_PIN); + sContactSensorLED.Init(CONTACT_STATE_LED); sContactSensorLED.Set(ContactSensorMgr().IsContactClosed()); UpdateDeviceState(); @@ -150,6 +141,16 @@ CHIP_ERROR AppTask::Init() k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); k_timer_user_data_set(&sFactoryResetTimer, this); + // Initialize PWM Identify led + CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("Green IDENTIFY PWM Device Init fail"); + return err; + } + + sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); + // Initialize CHIP server #if CONFIG_CHIP_FACTORY_DATA ReturnErrorOnFailure(mFactoryDataProvider.Init()); @@ -254,6 +255,56 @@ CHIP_ERROR AppTask::StartApp(void) } } +void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStart; + + switch (aEffect) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); + event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; + event.Type = AppEvent::kEventType_IdentifyStop; + break; + default: + ChipLogProgress(Zcl, "No identifier effect"); + return; + } + + sAppTask.PostEvent(&event); +} + void AppTask::PostContactActionRequest(ContactSensorManager::Action aAction) { AppEvent event; @@ -306,8 +357,8 @@ void AppTask::UpdateClusterStateInternal(intptr_t arg) ChipLogProgress(NotSpecified, "emberAfWriteAttribute : %d", newValue); // write the new boolean state value - EmberAfStatus status = emberAfWriteAttribute(1, ZCL_BOOLEAN_STATE_CLUSTER_ID, ZCL_STATE_VALUE_ATTRIBUTE_ID, - (uint8_t *) &newValue, ZCL_BOOLEAN_ATTRIBUTE_TYPE); + EmberAfStatus status = emberAfWriteAttribute(1, Clusters::BooleanState::Id, ZCL_STATE_VALUE_ATTRIBUTE_ID, (uint8_t *) &newValue, + ZCL_BOOLEAN_ATTRIBUTE_TYPE); if (status != EMBER_ZCL_STATUS_SUCCESS) { ChipLogError(NotSpecified, "ERR: updating boolean status value %x", status); @@ -446,6 +497,19 @@ void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */ } } +void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateIdentifyStateEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) +{ + sAppTask.mPwmIdentifyLed.UpdateAction(); +} + void AppTask::PostEvent(AppEvent * aEvent) { if (k_msgq_put(&sAppEventQueue, aEvent, K_NO_WAIT) != 0) @@ -517,7 +581,7 @@ void AppTask::UpdateDeviceStateInternal(intptr_t arg) bool stateValueAttrValue = 0; /* get boolean state attribute value */ - (void) emberAfReadAttribute(1, ZCL_BOOLEAN_STATE_CLUSTER_ID, ZCL_STATE_VALUE_ATTRIBUTE_ID, (uint8_t *) &stateValueAttrValue, 1); + (void) emberAfReadAttribute(1, Clusters::BooleanState::Id, ZCL_STATE_VALUE_ATTRIBUTE_ID, (uint8_t *) &stateValueAttrValue, 1); ChipLogProgress(NotSpecified, "emberAfReadAttribute : %d", stateValueAttrValue); sContactSensorLED.Set(stateValueAttrValue); diff --git a/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp b/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp index b555e4e0a2c958..c0a7612084d000 100644 --- a/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp +++ b/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp @@ -27,7 +27,7 @@ #include #include -LOG_MODULE_DECLARE(app); +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); ContactSensorManager ContactSensorManager::sContactSensor; diff --git a/examples/contact-sensor-app/telink/src/ZclCallbacks.cpp b/examples/contact-sensor-app/telink/src/ZclCallbacks.cpp index 89d6aed77f16d2..1b8424eeb1e90c 100644 --- a/examples/contact-sensor-app/telink/src/ZclCallbacks.cpp +++ b/examples/contact-sensor-app/telink/src/ZclCallbacks.cpp @@ -26,6 +26,8 @@ using namespace chip; using namespace chip::app::Clusters; +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); + void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size, uint8_t * value) { diff --git a/examples/contact-sensor-app/telink/src/main.cpp b/examples/contact-sensor-app/telink/src/main.cpp index e71632de12fddb..9dd145f55ba0c9 100755 --- a/examples/contact-sensor-app/telink/src/main.cpp +++ b/examples/contact-sensor-app/telink/src/main.cpp @@ -23,7 +23,7 @@ #include -LOG_MODULE_REGISTER(app); +LOG_MODULE_REGISTER(app, CONFIG_CHIP_APP_LOG_LEVEL); using namespace ::chip; using namespace ::chip::Inet; diff --git a/examples/darwin-framework-tool/commands/clusters/ReportCommandBridge.h b/examples/darwin-framework-tool/commands/clusters/ReportCommandBridge.h index 9b88ce50514724..97e480ac974844 100644 --- a/examples/darwin-framework-tool/commands/clusters/ReportCommandBridge.h +++ b/examples/darwin-framework-tool/commands/clusters/ReportCommandBridge.h @@ -1,5 +1,5 @@ /* - * 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"); @@ -134,7 +134,7 @@ class SubscribeAttribute : public ModelCommand { params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); } if (mAutoResubscribe.HasValue()) { - params.resubscribeIfLost = mAutoResubscribe.Value(); + params.resubscribeAutomatically = mAutoResubscribe.Value(); } [device subscribeToAttributesWithEndpointID:[NSNumber numberWithUnsignedShort:endpointId] @@ -184,6 +184,24 @@ class SubscribeEvent : public ModelCommand { public: SubscribeEvent() : ModelCommand("subscribe-all-events") + { + AddCommonArguments(); + } + + SubscribeEvent(chip::ClusterId clusterId, bool isClusterAny = false) + : ModelCommand("subscribe-event-by-id") + , mClusterId(clusterId) + { + if (isClusterAny == true) { + AddArgument("cluster-id", 0, UINT32_MAX, &mClusterId); + } + AddArgument("event-id", 0, UINT32_MAX, &mEventId); + AddArgument("event-min", 0, UINT64_MAX, &mEventNumber); + AddArgument("is-urgent", 0, 1, &mIsUrgent); + AddCommonArguments(); + } + + void AddCommonArguments() { AddArgument("min-interval", 0, UINT16_MAX, &mMinInterval); AddArgument("max-interval", 0, UINT16_MAX, &mMaxInterval); @@ -199,34 +217,61 @@ class SubscribeEvent : public ModelCommand { dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL); MTRSubscribeParams * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; + if (mEventNumber.HasValue()) { + params.minEventNumber = [NSNumber numberWithUnsignedLongLong:mEventNumber.Value()]; + } if (mKeepSubscriptions.HasValue()) { params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); } + if (mIsUrgent.HasValue()) { + params.reportEventsUrgently = mIsUrgent.Value(); + } if (mAutoResubscribe.HasValue()) { - params.resubscribeIfLost = mAutoResubscribe.Value(); + params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [device subscribeWithQueue:callbackQueue - params:params - clusterStateCacheContainer:nil - attributeReportHandler:^(NSArray * value) { - SetCommandExitStatus(CHIP_NO_ERROR); - } - eventReportHandler:^(NSArray * value) { - for (id item in value) { - NSLog(@"Response Item: %@", [item description]); + if (strcmp(GetName(), "subscribe-event-by-id") == 0) { + [device subscribeToEventsWithEndpointID:(endpointId == chip::kInvalidEndpointId) + ? nil + : [NSNumber numberWithUnsignedShort:endpointId] + clusterID:(mClusterId == chip::kInvalidClusterId) ? nil : [NSNumber numberWithUnsignedInteger:mClusterId] + eventID:(mEventId == chip::kInvalidEventId) ? nil : [NSNumber numberWithUnsignedInteger:mEventId] + params:params + queue:callbackQueue + reportHandler:^(NSArray *> * _Nullable values, NSError * _Nullable error) { + if (values) { + for (id item in values) { + NSLog(@"Response Item: %@", [item description]); + } + } + SetCommandExitStatus(error); } - SetCommandExitStatus(CHIP_NO_ERROR); - } - errorHandler:^(NSError * error) { - SetCommandExitStatus(error); - } - subscriptionEstablished:^() { - mSubscriptionEstablished = YES; - } - resubscriptionScheduled:^(NSError * error, NSNumber * resubscriptionDelay) { - NSLog(@"Subscription dropped with error %@. Resubscription in %@ms", error, resubscriptionDelay); - }]; + subscriptionEstablished:^() { + mSubscriptionEstablished = YES; + }]; + } else { + [device subscribeWithQueue:callbackQueue + params:params + clusterStateCacheContainer:nil + attributeReportHandler:^(NSArray * value) { + SetCommandExitStatus(CHIP_NO_ERROR); + } + eventReportHandler:^(NSArray * value) { + for (id item in value) { + NSLog(@"Response Item: %@", [item description]); + } + SetCommandExitStatus(CHIP_NO_ERROR); + } + errorHandler:^(NSError * error) { + SetCommandExitStatus(error); + } + subscriptionEstablished:^() { + mSubscriptionEstablished = YES; + } + resubscriptionScheduled:^(NSError * error, NSNumber * resubscriptionDelay) { + NSLog(@"Subscription dropped with error %@. Resubscription in %@ms", error, resubscriptionDelay); + }]; + } return CHIP_NO_ERROR; } @@ -237,7 +282,82 @@ class SubscribeEvent : public ModelCommand { chip::Optional mKeepSubscriptions; chip::Optional mAutoResubscribe; chip::Optional mEventNumber; + chip::Optional mIsUrgent; bool mSubscriptionEstablished = NO; uint16_t mMinInterval; uint16_t mMaxInterval; + + void Shutdown() override + { + mSubscriptionEstablished = NO; + ModelCommand::Shutdown(); + } + + bool DeferInteractiveCleanup() override { return mSubscriptionEstablished; } + +private: + chip::ClusterId mClusterId; + chip::EventId mEventId; +}; + +class ReadEvent : public ModelCommand { +public: + ReadEvent() + : ModelCommand("read-event-by-id") + { + AddArgument("cluster-id", 0, UINT32_MAX, &mClusterId); + AddArgument("event-id", 0, UINT32_MAX, &mEventId); + AddArgument("event-min", 0, UINT64_MAX, &mEventNumber); + ModelCommand::AddArguments(); + } + + ReadEvent(chip::ClusterId clusterId) + : ModelCommand("read-event-by-id") + , mClusterId(clusterId) + { + AddArgument("event-id", 0, UINT32_MAX, &mEventId); + AddArgument("event-min", 0, UINT64_MAX, &mEventNumber); + ModelCommand::AddArguments(); + } + + ~ReadEvent() {} + + CHIP_ERROR SendCommand(MTRBaseDevice * _Nonnull device, chip::EndpointId endpointId) override + { + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL); + MTRReadParams * params = [[MTRReadParams alloc] init]; + if (mFabricFiltered.HasValue()) { + params.filterByFabric = mFabricFiltered.Value(); + } + if (mEventNumber.HasValue()) { + params.minEventNumber = [NSNumber numberWithUnsignedLongLong:mEventNumber.Value()]; + } + + [device + readEventsWithEndpointID:(endpointId == chip::kInvalidEndpointId) ? nil : [NSNumber numberWithUnsignedShort:endpointId] + clusterID:(mClusterId == chip::kInvalidClusterId) ? nil : [NSNumber numberWithUnsignedInteger:mClusterId] + eventID:(mEventId == chip::kInvalidEventId) ? nil : [NSNumber numberWithUnsignedInteger:mEventId] + params:params + queue:callbackQueue + completion:^(NSArray *> * _Nullable values, NSError * _Nullable error) { + if (error != nil) { + LogNSError("Error reading event", error); + } + if (values) { + for (id item in values) { + NSLog(@"Response Item: %@", [item description]); + } + } + SetCommandExitStatus(error); + }]; + return CHIP_NO_ERROR; + } + +protected: + chip::Optional mFabricFiltered; + chip::Optional mEventNumber; + +private: + chip::ClusterId mClusterId; + chip::AttributeId mEventId; }; diff --git a/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm b/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm index a251d517e6b83e..4188da365574c5 100644 --- a/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm +++ b/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm @@ -21,12 +21,8 @@ #include #include -#include -#include -char kInteractiveModeName[] = ""; constexpr const char * kInteractiveModePrompt = ">>> "; -constexpr uint8_t kInteractiveModeArgumentsMaxLength = 32; constexpr const char * kInteractiveModeHistoryFilePath = "/tmp/darwin_framework_tool_history"; constexpr const char * kInteractiveModeStopCommand = "quit()"; @@ -144,29 +140,7 @@ el_status_t StopFunction() return NO; } - char * args[kInteractiveModeArgumentsMaxLength]; - args[0] = kInteractiveModeName; - int argsCount = 1; - std::string arg; - - std::stringstream ss(command); - while (ss >> std::quoted(arg, '\'')) { - if (argsCount == kInteractiveModeArgumentsMaxLength) { - ChipLogError(chipTool, "Too many arguments. Ignoring."); - return YES; - } - - char * carg = new char[arg.size() + 1]; - strcpy(carg, arg.c_str()); - args[argsCount++] = carg; - } - ClearLine(); - mHandler->RunInteractive(argsCount, args); - - // Do not delete arg[0] - while (--argsCount) - delete[] args[argsCount]; - + mHandler->RunInteractive(command); return YES; } diff --git a/examples/darwin-framework-tool/commands/pairing/Commands.h b/examples/darwin-framework-tool/commands/pairing/Commands.h index 16c57b5d4ddd0f..23242355ffaa3f 100644 --- a/examples/darwin-framework-tool/commands/pairing/Commands.h +++ b/examples/darwin-framework-tool/commands/pairing/Commands.h @@ -1,5 +1,5 @@ /* - * 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"); @@ -22,7 +22,7 @@ #include "OpenCommissioningWindowCommand.h" #include "PairingCommandBridge.h" -#include "PrepareCommissioningCommand.h" +#include "PreWarmCommissioningCommand.h" class PairCode : public PairingCommandBridge { @@ -72,7 +72,7 @@ void registerCommandsPairing(Commands & commands) make_unique(), make_unique(), make_unique(), - make_unique(), + make_unique(), }; commands.Register(clusterName, clusterCommands); diff --git a/examples/darwin-framework-tool/commands/pairing/PrepareCommissioningCommand.h b/examples/darwin-framework-tool/commands/pairing/PreWarmCommissioningCommand.h similarity index 75% rename from examples/darwin-framework-tool/commands/pairing/PrepareCommissioningCommand.h rename to examples/darwin-framework-tool/commands/pairing/PreWarmCommissioningCommand.h index c1fd777cf1146a..f3508b8040296c 100644 --- a/examples/darwin-framework-tool/commands/pairing/PrepareCommissioningCommand.h +++ b/examples/darwin-framework-tool/commands/pairing/PreWarmCommissioningCommand.h @@ -1,5 +1,5 @@ /* - * 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"); @@ -23,10 +23,10 @@ #import "MTRError_Utils.h" -class PrepareCommissioningCommand : public CHIPCommandBridge { +class PreWarmCommissioningCommand : public CHIPCommandBridge { public: - PrepareCommissioningCommand() - : CHIPCommandBridge("prepare-commissioning") + PreWarmCommissioningCommand() + : CHIPCommandBridge("pre-warm-commissioning") { } @@ -35,12 +35,7 @@ class PrepareCommissioningCommand : public CHIPCommandBridge { CHIP_ERROR RunCommand() override { auto * controller = CurrentCommissioner(); - NSError * error; - if (![controller prepareCommissioningSession:&error]) { - auto err = MTRErrorToCHIPErrorCode(error); - SetCommandExitStatus(err); - return err; - } + [controller preWarmCommissioningSession]; // In interactive mode, we don't want to block the UI until the end of `GetWaitDuration`. So returns early. if (IsInteractive()) { diff --git a/examples/darwin-framework-tool/commands/provider/OTASoftwareUpdateInteractive.mm b/examples/darwin-framework-tool/commands/provider/OTASoftwareUpdateInteractive.mm index 77ca8d51a022a5..b2f2b3b0731988 100644 --- a/examples/darwin-framework-tool/commands/provider/OTASoftwareUpdateInteractive.mm +++ b/examples/darwin-framework-tool/commands/provider/OTASoftwareUpdateInteractive.mm @@ -1,6 +1,6 @@ /* * - * 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,8 +38,7 @@ return nil; } - NSError * error; - return [MTROTAHeader headerFromData:[NSData dataWithBytes:buffer.data() length:buffer.size()] error:&error]; + return [[MTROTAHeader alloc] initWithData:[NSData dataWithBytes:buffer.data() length:buffer.size()]]; } // Parses the JSON filepath and extracts DeviceSoftwareVersionModel parameters diff --git a/examples/darwin-framework-tool/templates/commands.zapt b/examples/darwin-framework-tool/templates/commands.zapt index 0b6f7367cb3d98..9db578ce5a1134 100644 --- a/examples/darwin-framework-tool/templates/commands.zapt +++ b/examples/darwin-framework-tool/templates/commands.zapt @@ -231,7 +231,7 @@ public: params.filterByFabric = mFabricFiltered.Value(); } if (mAutoResubscribe.HasValue()) { - params.resubscribeIfLost = mAutoResubscribe.Value(); + params.resubscribeAutomatically = mAutoResubscribe.Value(); } [cluster subscribe{{>attribute}}WithParams:params subscriptionEstablished:^(){ mSubscriptionEstablished=YES; } @@ -292,6 +292,12 @@ void registerCluster{{asUpperCamelCase name}}(Commands & commands) {{/if}} {{/unless}} {{/chip_server_cluster_attributes}} + {{#zcl_events}} + {{#first}} + make_unique(Id), // + make_unique(Id), // + {{/first}} + {{/zcl_events}} }; commands.Register(clusterName, clusterCommands); @@ -308,6 +314,8 @@ void registerClusterAny(Commands & commands) make_unique(), // make_unique(), // make_unique(), // + make_unique(), // + make_unique(chip::kInvalidClusterId, true), // make_unique(), // }; diff --git a/examples/darwin-framework-tool/templates/tests/ciTests.json b/examples/darwin-framework-tool/templates/tests/ciTests.json index 77f97d3ce7e0a3..98bff77d169c2f 100644 --- a/examples/darwin-framework-tool/templates/tests/ciTests.json +++ b/examples/darwin-framework-tool/templates/tests/ciTests.json @@ -27,6 +27,8 @@ "Test_TC_TSTAT_2_2", "Test_TC_ACL_2_4", "Test_TC_ACL_2_7", - "Test_TC_ACL_2_9" + "Test_TC_ACL_2_8", + "Test_TC_ACL_2_9", + "Test_TC_ACL_2_10" ] } diff --git a/examples/dynamic-bridge-app/bridge-common/bridge-app.matter b/examples/dynamic-bridge-app/bridge-common/bridge-app.matter index 9ad049a62dd53c..18cdac8cf27d1c 100644 --- a/examples/dynamic-bridge-app/bridge-common/bridge-app.matter +++ b/examples/dynamic-bridge-app/bridge-common/bridge-app.matter @@ -75,10 +75,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute bitmap32 featureMap = 65532; readonly attribute int16u clusterRevision = 65533; @@ -1107,6 +1103,11 @@ server cluster WiFiNetworkDiagnostics = 54 { kAx = 5; } + bitmap WiFiNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + info event Disconnection = 0 { INT16U reasonCode = 0; } @@ -1151,6 +1152,11 @@ server cluster EthernetNetworkDiagnostics = 55 { kRate400G = 9; } + bitmap EthernetNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + readonly attribute nullable PHYRateEnum PHYRate = 0; readonly attribute nullable boolean fullDuplex = 1; readonly attribute int64u packetRxCount = 2; diff --git a/examples/light-switch-app/esp32/main/CMakeLists.txt b/examples/light-switch-app/esp32/main/CMakeLists.txt index 9fecd318807163..8a5bd77d21c740 100644 --- a/examples/light-switch-app/esp32/main/CMakeLists.txt +++ b/examples/light-switch-app/esp32/main/CMakeLists.txt @@ -25,7 +25,6 @@ idf_component_register(PRIV_INCLUDE_DIRS "${CMAKE_CURRENT_LIST_DIR}" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/light-switch-app/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/ota" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/common" diff --git a/examples/light-switch-app/light-switch-common/light-switch-app.matter b/examples/light-switch-app/light-switch-common/light-switch-app.matter index 5809b1a6b1ca41..ba452d17d77e20 100644 --- a/examples/light-switch-app/light-switch-common/light-switch-app.matter +++ b/examples/light-switch-app/light-switch-common/light-switch-app.matter @@ -143,17 +143,21 @@ server cluster Groups = 4 { } client cluster Scenes = 5 { + bitmap SceneFeatures : BITMAP32 { + kSceneNames = 0x1; + } + bitmap ScenesCopyMode : BITMAP8 { kCopyAllScenes = 0x1; } struct ExtensionFieldSet { - cluster_id clusterId = 0; + cluster_id clusterID = 0; AttributeValuePair attributeValueList[] = 1; } struct AttributeValuePair { - optional attrib_id attributeId = 0; + optional attrib_id attributeID = 0; int8u attributeValue[] = 1; } @@ -166,52 +170,52 @@ client cluster Scenes = 5 { readonly attribute int16u clusterRevision = 65533; request struct AddSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; INT16U transitionTime = 2; CHAR_STRING sceneName = 3; ExtensionFieldSet extensionFieldSets[] = 4; } request struct ViewSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; } request struct RemoveSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; } request struct RemoveAllScenesRequest { - group_id groupId = 0; + group_id groupID = 0; } request struct StoreSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; } request struct RecallSceneRequest { - group_id groupId = 0; - INT8U sceneId = 1; + group_id groupID = 0; + INT8U sceneID = 1; optional nullable INT16U transitionTime = 2; } request struct GetSceneMembershipRequest { - group_id groupId = 0; + group_id groupID = 0; } response struct AddSceneResponse = 0 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; } response struct ViewSceneResponse = 1 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; optional INT16U transitionTime = 3; optional CHAR_STRING sceneName = 4; optional ExtensionFieldSet extensionFieldSets[] = 5; @@ -219,25 +223,25 @@ client cluster Scenes = 5 { response struct RemoveSceneResponse = 2 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; } response struct RemoveAllScenesResponse = 3 { ENUM8 status = 0; - group_id groupId = 1; + group_id groupID = 1; } response struct StoreSceneResponse = 4 { ENUM8 status = 0; - group_id groupId = 1; - INT8U sceneId = 2; + group_id groupID = 1; + INT8U sceneID = 2; } response struct GetSceneMembershipResponse = 6 { ENUM8 status = 0; nullable INT8U capacity = 1; - group_id groupId = 2; + group_id groupID = 2; optional INT8U sceneList[] = 3; } @@ -280,10 +284,6 @@ client cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; @@ -1153,6 +1153,11 @@ server cluster WiFiNetworkDiagnostics = 54 { kAx = 5; } + bitmap WiFiNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + info event Disconnection = 0 { INT16U reasonCode = 0; } @@ -1199,6 +1204,11 @@ server cluster EthernetNetworkDiagnostics = 55 { kRate400G = 9; } + bitmap EthernetNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + readonly attribute nullable PHYRateEnum PHYRate = 0; readonly attribute nullable boolean fullDuplex = 1; readonly attribute int64u packetRxCount = 2; diff --git a/examples/light-switch-app/telink/CMakeLists.txt b/examples/light-switch-app/telink/CMakeLists.txt index 3f67e533375932..af48b2eb688c3e 100755 --- a/examples/light-switch-app/telink/CMakeLists.txt +++ b/examples/light-switch-app/telink/CMakeLists.txt @@ -52,7 +52,8 @@ target_sources(app PRIVATE src/binding-handler.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp - ${TELINK_COMMON}/util/src/ThreadUtil.cpp) + ${TELINK_COMMON}/util/src/ThreadUtil.cpp + ${TELINK_COMMON}/util/src/PWMDevice.cpp) chip_configure_data_model(app INCLUDE_SERVER diff --git a/examples/light-switch-app/telink/README.md b/examples/light-switch-app/telink/README.md index 2c5aa4a940f687..a150047a5ec4d0 100755 --- a/examples/light-switch-app/telink/README.md +++ b/examples/light-switch-app/telink/README.md @@ -69,14 +69,31 @@ The following buttons are available on **tlsr9518adk80d** board: ### LEDs -**Red** LED indicates current state of Thread network. It ables to be in +#### Indicate current state of Thread network + +**Red** LED indicates current state of Thread network. It is able to be in following states: | State | Description | | :-------------------------- | :--------------------------------------------------------------------------- | | Blinks with short pulses | Device is not commissioned to Thread, Thread is disabled | -| Blinls with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | -| Blinks with whde pulses | Device commissioned and joined to thread network as CHILD | +| Blinks with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | +| Blinks with wide pulses | Device commissioned and joined to thread network as CHILD | + +#### Indicate identify of device + +**Green** LED used to identify the device. The LED starts blinking when the +Identify command of the Identify cluster is received. The command's argument can +be used to specify the the effect. It is able to be in following effects: + +| Effect | Description | +| :------------------------------ | :------------------------------------------------------------------- | +| Blinks (200 ms on/200 ms off) | Blink (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK) | +| Breathe (during 1000 ms) | Breathe (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE) | +| Blinks (50 ms on/950 ms off) | Okay (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY) | +| Blinks (1000 ms on/1000 ms off) | Channel Change (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE) | +| Blinks (950 ms on/50 ms off) | Finish (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT) | +| LED off | Stop (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT) | ### CHIP tool commands diff --git a/examples/light-switch-app/telink/include/AppConfig.h b/examples/light-switch-app/telink/include/AppConfig.h index 6155133e1d0278..688d848ea520ae 100755 --- a/examples/light-switch-app/telink/include/AppConfig.h +++ b/examples/light-switch-app/telink/include/AppConfig.h @@ -29,10 +29,6 @@ #define BUTTON_PIN_2 0 // LEDs config -// System led config -#define SYSTEM_STATE_LED_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED_PIN 7 - -// Lighting LED config -#define LIGHTING_PWM_DEVICE DEVICE_DT_GET(DT_PWMS_CTLR(DT_ALIAS(pwm_led0))) -#define LIGHTING_PWM_CHANNEL DT_PWMS_CHANNEL(DT_ALIAS(pwm_led0)) +#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) +#define SYSTEM_STATE_LED 7 +#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) diff --git a/examples/light-switch-app/telink/include/AppEvent.h b/examples/light-switch-app/telink/include/AppEvent.h index 9a6fd3060c1685..72554b4bb54b5a 100755 --- a/examples/light-switch-app/telink/include/AppEvent.h +++ b/examples/light-switch-app/telink/include/AppEvent.h @@ -32,6 +32,8 @@ struct AppEvent kEventType_Button = 0, kEventType_Timer, kEventType_UpdateLedState, + kEventType_IdentifyStart, + kEventType_IdentifyStop, kEventType_Lighting, kEventType_Install, }; diff --git a/examples/light-switch-app/telink/include/AppTask.h b/examples/light-switch-app/telink/include/AppTask.h old mode 100755 new mode 100644 index 6509613e3741b8..8226505fcc2ccc --- a/examples/light-switch-app/telink/include/AppTask.h +++ b/examples/light-switch-app/telink/include/AppTask.h @@ -20,6 +20,7 @@ #include "AppEvent.h" #include "LEDWidget.h" +#include "PWMDevice.h" #include @@ -32,6 +33,7 @@ #include struct k_timer; +struct Identify; class AppTask { @@ -50,13 +52,16 @@ class AppTask void PostLightingActionRequest(Action_t aAction); void PostEvent(AppEvent * event); void UpdateClusterState(); + static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); private: friend AppTask & GetAppTask(void); - CHIP_ERROR Init(); + + CHIP_ERROR Init(void); static void ActionInitiated(AppTask::Action_t aAction, int32_t aActor); static void ActionCompleted(AppTask::Action_t aAction, int32_t aActor); + static void ActionIdentifyStateUpdateHandler(k_timer * timer); void DispatchEvent(AppEvent * event); @@ -77,12 +82,14 @@ class AppTask static void SwitchActionEventHandler(AppEvent * aEvent); static void StartBleAdvHandler(AppEvent * aEvent); static void UpdateLedStateEventHandler(AppEvent * aEvent); + static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); static void InitButtons(void); static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); static AppTask sAppTask; + PWMDevice mPwmIdentifyLed; #if CONFIG_CHIP_FACTORY_DATA // chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; diff --git a/examples/light-switch-app/telink/src/AppTask.cpp b/examples/light-switch-app/telink/src/AppTask.cpp index 0c8013067fc9d7..e3fc414277bf22 100644 --- a/examples/light-switch-app/telink/src/AppTask.cpp +++ b/examples/light-switch-app/telink/src/AppTask.cpp @@ -63,7 +63,7 @@ SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); #endif // CONFIG_CHIP_LIB_SHELL -LOG_MODULE_DECLARE(app); +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); using namespace ::chip; using namespace ::chip::app; @@ -71,15 +71,28 @@ using namespace ::chip::Credentials; using namespace ::chip::DeviceLayer; namespace { -constexpr int kFactoryResetTriggerTimeout = 2000; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; +constexpr EndpointId kEndpointId = 1; +constexpr uint8_t kDefaultMinLevel = 0; +constexpr uint8_t kDefaultMaxLevel = 254; +constexpr uint32_t kIdentifyBlinkRateMs = 200; +constexpr uint32_t kIdentifyOkayOnRateMs = 50; +constexpr uint32_t kIdentifyOkayOffRateMs = 950; +constexpr uint32_t kIdentifyFinishOnRateMs = 950; +constexpr uint32_t kIdentifyFinishOffRateMs = 50; +constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; +constexpr uint32_t kIdentifyBreatheRateMs = 1000; + +const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; +#if CONFIG_CHIP_FACTORY_DATA // NOTE! This key is for test/certification only and should not be available in production devices! -// If CONFIG_CHIP_FACTORY_DATA is enabled, this value is read from the factory data. uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; +#endif K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); k_timer sFactoryResetTimer; @@ -101,29 +114,11 @@ chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; void OnIdentifyTriggerEffect(Identify * identify) { - switch (identify->mCurrentEffectIdentifier) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - break; - } - return; + AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); } Identify sIdentify = { - chip::EndpointId{ 1 }, + kEndpointId, [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStart"); }, [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStop"); }, EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, @@ -145,16 +140,14 @@ class AppFabricTableDelegate : public FabricTable::Delegate } }; -CHIP_ERROR AppTask::Init() +CHIP_ERROR AppTask::Init(void) { - CHIP_ERROR err; - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); // Initialize status LED - LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + LEDWidget::InitGpio(LEDS_PORT); LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED_PIN); + sStatusLED.Init(SYSTEM_STATE_LED); UpdateStatusLED(); @@ -164,6 +157,16 @@ CHIP_ERROR AppTask::Init() k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); k_timer_user_data_set(&sFactoryResetTimer, this); + // Initialize PWM Identify led + CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("Green IDENTIFY PWM Device Init fail"); + return err; + } + + sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); + // Initialize CHIP server #if CONFIG_CHIP_FACTORY_DATA ReturnErrorOnFailure(mFactoryDataProvider.Init()); @@ -228,7 +231,7 @@ CHIP_ERROR AppTask::Init() return CHIP_NO_ERROR; } -CHIP_ERROR AppTask::StartApp() +CHIP_ERROR AppTask::StartApp(void) { CHIP_ERROR err = Init(); @@ -252,6 +255,56 @@ CHIP_ERROR AppTask::StartApp() } } +void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStart; + + switch (aEffect) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); + event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; + event.Type = AppEvent::kEventType_IdentifyStop; + break; + default: + ChipLogProgress(Zcl, "No identifier effect"); + return; + } + + sAppTask.PostEvent(&event); +} + void AppTask::SwitchActionButtonEventHandler(void) { AppEvent event; @@ -374,7 +427,7 @@ void AppTask::LEDStateUpdateHandler(LEDWidget * ledWidget) sAppTask.PostEvent(&event); } -void AppTask::UpdateStatusLED() +void AppTask::UpdateStatusLED(void) { if (sIsThreadProvisioned && sIsThreadEnabled) { @@ -420,6 +473,19 @@ void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */ } } +void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateIdentifyStateEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) +{ + sAppTask.mPwmIdentifyLed.UpdateAction(); +} + void AppTask::ActionInitiated(AppTask::Action_t aAction, int32_t aActor) {} void AppTask::ActionCompleted(AppTask::Action_t aAction, int32_t aActor) diff --git a/examples/light-switch-app/telink/src/ZclCallbacks.cpp b/examples/light-switch-app/telink/src/ZclCallbacks.cpp index cb2b2ab490b48a..e7edb8514e7a18 100644 --- a/examples/light-switch-app/telink/src/ZclCallbacks.cpp +++ b/examples/light-switch-app/telink/src/ZclCallbacks.cpp @@ -23,6 +23,8 @@ #include #include +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); + using namespace chip; using namespace chip::app::Clusters; diff --git a/examples/light-switch-app/telink/src/binding-handler.cpp b/examples/light-switch-app/telink/src/binding-handler.cpp index 60efbcf8857f5c..f982266828c583 100755 --- a/examples/light-switch-app/telink/src/binding-handler.cpp +++ b/examples/light-switch-app/telink/src/binding-handler.cpp @@ -31,6 +31,8 @@ #include "lib/shell/commands/Help.h" #endif // CONFIG_CHIP_LIB_SHELL +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); + using namespace chip; using namespace chip::app; diff --git a/examples/light-switch-app/telink/src/main.cpp b/examples/light-switch-app/telink/src/main.cpp index e71632de12fddb..9dd145f55ba0c9 100755 --- a/examples/light-switch-app/telink/src/main.cpp +++ b/examples/light-switch-app/telink/src/main.cpp @@ -23,7 +23,7 @@ #include -LOG_MODULE_REGISTER(app); +LOG_MODULE_REGISTER(app, CONFIG_CHIP_APP_LOG_LEVEL); using namespace ::chip; using namespace ::chip::Inet; diff --git a/examples/lighting-app/esp32/CMakeLists.txt b/examples/lighting-app/esp32/CMakeLists.txt index 746f70379ef1c1..92f2a10fec2f0b 100644 --- a/examples/lighting-app/esp32/CMakeLists.txt +++ b/examples/lighting-app/esp32/CMakeLists.txt @@ -27,7 +27,6 @@ include(${CMAKE_CURRENT_LIST_DIR}/third_party/connectedhomeip/examples/common/cm set(EXTRA_COMPONENT_DIRS "${CMAKE_CURRENT_LIST_DIR}/third_party/connectedhomeip/config/esp32/components" "${CMAKE_CURRENT_LIST_DIR}/third_party/connectedhomeip/examples/common/QRCode" - "${IDF_PATH}/examples/common_components/led_strip" ) project(chip-lighting-app) diff --git a/examples/lighting-app/esp32/main/CMakeLists.txt b/examples/lighting-app/esp32/main/CMakeLists.txt index c1f1e30767e455..8b7a6e916f38a5 100644 --- a/examples/lighting-app/esp32/main/CMakeLists.txt +++ b/examples/lighting-app/esp32/main/CMakeLists.txt @@ -28,7 +28,6 @@ set(SRC_DIRS_LIST "${CMAKE_CURRENT_LIST_DIR}" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/lighting-app/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/lighting-app/lighting-common/src" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/ota" @@ -68,7 +67,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/group-key-mgmt-server" ) -set(PRIV_REQUIRES_LIST chip QRCode bt led_strip app_update openthread driver nvs_flash) +set(PRIV_REQUIRES_LIST chip QRCode bt led_strip app_update openthread driver nvs_flash spi_flash) if (CONFIG_ENABLE_PW_RPC) # Append additional directories for RPC build diff --git a/examples/lighting-app/esp32/main/DeviceCallbacks.cpp b/examples/lighting-app/esp32/main/DeviceCallbacks.cpp index bc1174f4676358..c61c3d3d5054b5 100644 --- a/examples/lighting-app/esp32/main/DeviceCallbacks.cpp +++ b/examples/lighting-app/esp32/main/DeviceCallbacks.cpp @@ -47,8 +47,9 @@ using namespace chip::app::Clusters; void AppDeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t type, uint16_t size, uint8_t * value) { - ESP_LOGI(TAG, "PostAttributeChangeCallback - Cluster ID: '0x%04x', EndPoint ID: '0x%02x', Attribute ID: '0x%04x'", clusterId, - endpointId, attributeId); + ESP_LOGI(TAG, + "PostAttributeChangeCallback - Cluster ID: '0x%04" PRIx32 "', EndPoint ID: '0x%02x', Attribute ID: '0x%04" PRIx32 "'", + clusterId, endpointId, attributeId); switch (clusterId) { @@ -67,7 +68,7 @@ void AppDeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, Clus #endif default: - ESP_LOGI(TAG, "Unhandled cluster ID: %d", clusterId); + ESP_LOGI(TAG, "Unhandled cluster ID: %" PRIu32, clusterId); break; } @@ -76,7 +77,8 @@ void AppDeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, Clus void AppDeviceCallbacks::OnOnOffPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) { - VerifyOrExit(attributeId == OnOff::Attributes::OnOff::Id, ESP_LOGI(TAG, "Unhandled Attribute ID: '0x%04x", attributeId)); + VerifyOrExit(attributeId == OnOff::Attributes::OnOff::Id, + ESP_LOGI(TAG, "Unhandled Attribute ID: '0x%04" PRIx32 "'", attributeId)); VerifyOrExit(endpointId == 1, ESP_LOGE(TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId)); AppLED.Set(*value); @@ -88,7 +90,7 @@ void AppDeviceCallbacks::OnOnOffPostAttributeChangeCallback(EndpointId endpointI void AppDeviceCallbacks::OnLevelControlAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) { VerifyOrExit(attributeId == LevelControl::Attributes::CurrentLevel::Id, - ESP_LOGI(TAG, "Unhandled Attribute ID: '0x%04x", attributeId)); + ESP_LOGI(TAG, "Unhandled Attribute ID: '0x%04" PRIx32 "'", attributeId)); VerifyOrExit(endpointId == 1, ESP_LOGE(TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId)); AppLED.SetBrightness(*value); @@ -105,7 +107,7 @@ void AppDeviceCallbacks::OnColorControlAttributeChangeCallback(EndpointId endpoi VerifyOrExit(attributeId == ColorControl::Attributes::CurrentHue::Id || attributeId == ColorControl::Attributes::CurrentSaturation::Id, - ESP_LOGI(TAG, "Unhandled AttributeId ID: '0x%04x", attributeId)); + ESP_LOGI(TAG, "Unhandled AttributeId ID: '0x%04" PRIx32 "'", attributeId)); VerifyOrExit(endpointId == 1, ESP_LOGE(TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId)); if (attributeId == ColorControl::Attributes::CurrentHue::Id) diff --git a/examples/lighting-app/esp32/main/Kconfig.projbuild b/examples/lighting-app/esp32/main/Kconfig.projbuild index 43d7d9f0e75381..b41b4ef0e4fb81 100644 --- a/examples/lighting-app/esp32/main/Kconfig.projbuild +++ b/examples/lighting-app/esp32/main/Kconfig.projbuild @@ -25,6 +25,7 @@ menu "Demo" default DEVICE_TYPE_ESP32_DEVKITC if IDF_TARGET_ESP32 default DEVICE_TYPE_ESP32_C3_DEVKITM if IDF_TARGET_ESP32C3 default DEVICE_TYPE_ESP32_S3_DEVKITM if IDF_TARGET_ESP32S3 + default DEVICE_TYPE_ESP32_C2_DEVKITM if IDF_TARGET_ESP32C2 help Specifies the type of ESP32 device. @@ -46,6 +47,9 @@ menu "Demo" config DEVICE_TYPE_ESP32H2_DEVKITC bool "ESP32H2-DevKitC" depends on IDF_TARGET_ESP32H2 + config DEVICE_TYPE_ESP32_C2_DEVKITM + bool "ESP32C2-DevKitM" + depends on IDF_TARGET_ESP32C2 endchoice choice LED_TYPE @@ -76,7 +80,7 @@ menu "Demo" int "LED GPIO number" range 0 48 default 26 if DEVICE_TYPE_ESP32_WROVER_KIT - default 8 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32H2_DEVKITC + default 8 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32H2_DEVKITC || DEVICE_TYPE_ESP32_C2_DEVKITM default 48 if DEVICE_TYPE_ESP32_S3_DEVKITM default 5 help diff --git a/examples/lighting-app/esp32/main/LEDWidget.cpp b/examples/lighting-app/esp32/main/LEDWidget.cpp index bf2221b26446c9..6e65bec7c0c1e5 100644 --- a/examples/lighting-app/esp32/main/LEDWidget.cpp +++ b/examples/lighting-app/esp32/main/LEDWidget.cpp @@ -27,14 +27,6 @@ void LEDWidget::Init(void) mBrightness = UINT8_MAX; #if CONFIG_LED_TYPE_RMT -#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) - led_strip_config_t strip_config = { - .strip_gpio_num = CONFIG_LED_GPIO, - .max_leds = 1, - }; - - led_strip_new_rmt_device(&strip_config, &mStrip); -#else rmt_config_t config = RMT_DEFAULT_CONFIG_TX((gpio_num_t) CONFIG_LED_GPIO, (rmt_channel_t) CONFIG_LED_RMT_CHANNEL); led_strip_config_t strip_config = LED_STRIP_DEFAULT_CONFIG(1, (led_strip_dev_t) config.channel); @@ -42,8 +34,7 @@ void LEDWidget::Init(void) rmt_config(&config); rmt_driver_install(config.channel, 0, 0); - mStrip = led_strip_new_rmt_ws2812(&strip_config); -#endif + mStrip = led_strip_new_rmt_ws2812(&strip_config); mHue = 0; mSaturation = 0; #else @@ -131,13 +122,8 @@ void LEDWidget::DoSet(void) { HsvColor_t hsv = { mHue, mSaturation, brightness }; RgbColor_t rgb = HsvToRgb(hsv); -#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) - led_strip_set_pixel(mStrip, 0, rgb.r, rgb.g, rgb.b); - led_strip_refresh(mStrip); -#else mStrip->set_pixel(mStrip, 0, rgb.r, rgb.g, rgb.b); mStrip->refresh(mStrip, 100); -#endif } #else ESP_LOGI(TAG, "DoSet to GPIO number %d", mGPIONum); diff --git a/examples/lighting-app/esp32/main/idf_component.yml b/examples/lighting-app/esp32/main/idf_component.yml new file mode 100644 index 00000000000000..1c539b8eb57668 --- /dev/null +++ b/examples/lighting-app/esp32/main/idf_component.yml @@ -0,0 +1,2 @@ +dependencies: + espressif/led_strip: "^1.0.0-alpha" diff --git a/examples/lighting-app/esp32/main/include/LEDWidget.h b/examples/lighting-app/esp32/main/include/LEDWidget.h index f9d00a2b6882a9..c390d63ac1024f 100644 --- a/examples/lighting-app/esp32/main/include/LEDWidget.h +++ b/examples/lighting-app/esp32/main/include/LEDWidget.h @@ -50,11 +50,7 @@ class LEDWidget #if CONFIG_LED_TYPE_RMT uint8_t mHue; uint8_t mSaturation; -#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) - led_strip_handle_t mStrip; -#else led_strip_t * mStrip; -#endif #else gpio_num_t mGPIONum; #endif diff --git a/examples/lighting-app/esp32/sdkconfig.defaults b/examples/lighting-app/esp32/sdkconfig.defaults index 64623b292bfdd3..bb74fc99f423d7 100644 --- a/examples/lighting-app/esp32/sdkconfig.defaults +++ b/examples/lighting-app/esp32/sdkconfig.defaults @@ -52,3 +52,6 @@ CONFIG_ESPTOOLPY_FLASHSIZE="4MB" # Disable softap support by default CONFIG_ESP_WIFI_SOFTAP_SUPPORT=n +# This example uses the older version of RMT driver to work with both +# idf-v4.4.3 and idf-v5.0, so supressing the warnings by setting below option +CONFIG_RMT_SUPPRESS_DEPRECATE_WARN=y diff --git a/examples/lighting-app/esp32/sdkconfig.defaults.esp32c2 b/examples/lighting-app/esp32/sdkconfig.defaults.esp32c2 new file mode 100644 index 00000000000000..6cb90db4f55b9d --- /dev/null +++ b/examples/lighting-app/esp32/sdkconfig.defaults.esp32c2 @@ -0,0 +1,19 @@ +# Disable chip shell +CONFIG_ENABLE_CHIP_SHELL=n + +# CONFIG_ESP32_WIFI_IRAM_OPT is not set +# CONFIG_ESP32_WIFI_RX_IRAM_OPT is not set +CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH=y +CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y + +CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE=y + +CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=16 +CONFIG_LWIP_TCP_RECVMBOX_SIZE=8 + +CONFIG_BT_NIMBLE_ROLE_CENTRAL=n +CONFIG_BT_NIMBLE_ROLE_OBSERVER=n + +CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=4 +CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=8 +CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=16 diff --git a/examples/lighting-app/lighting-common/lighting-app.matter b/examples/lighting-app/lighting-common/lighting-app.matter index 08d65c1210d1bd..2568988fa5ae56 100644 --- a/examples/lighting-app/lighting-common/lighting-app.matter +++ b/examples/lighting-app/lighting-common/lighting-app.matter @@ -137,10 +137,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; @@ -1109,6 +1105,11 @@ server cluster WiFiNetworkDiagnostics = 54 { kAx = 5; } + bitmap WiFiNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + info event Disconnection = 0 { INT16U reasonCode = 0; } @@ -1155,6 +1156,11 @@ server cluster EthernetNetworkDiagnostics = 55 { kRate400G = 9; } + bitmap EthernetNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + readonly attribute nullable PHYRateEnum PHYRate = 0; readonly attribute nullable boolean fullDuplex = 1; readonly attribute int64u packetRxCount = 2; diff --git a/examples/lighting-app/nxp/zap/lighting-on-off.matter b/examples/lighting-app/nxp/zap/lighting-on-off.matter index 9cb8188a05df26..6114c82e64eaa2 100644 --- a/examples/lighting-app/nxp/zap/lighting-on-off.matter +++ b/examples/lighting-app/nxp/zap/lighting-on-off.matter @@ -138,10 +138,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly nosubscribe attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; diff --git a/examples/lighting-app/silabs/efr32/BUILD.gn b/examples/lighting-app/silabs/efr32/BUILD.gn index fdcadf1feb5732..dcda82dc8d9dea 100644 --- a/examples/lighting-app/silabs/efr32/BUILD.gn +++ b/examples/lighting-app/silabs/efr32/BUILD.gn @@ -91,7 +91,8 @@ if (chip_enable_wifi) { # ThunderBoards, Explorer Kit and MGM240L do not support LCD (No LCD) if (silabs_board == "BRD4166A" || silabs_board == "BRD2601B" || - silabs_board == "BRD2703A" || silabs_board == "BRD4319A") { + silabs_board == "BRD2703A" || silabs_board == "BRD4319A" || + silabs_board == "BRD2704A") { show_qr_code = false disable_lcd = true } @@ -208,6 +209,10 @@ efr32_executable("lighting_app") { include_dirs = [ "include" ] defines = [] + if (silabs_board == "BRD2704A") { + defines += [ "SL_STATUS_LED=0" ] + } + sources = [ "${examples_common_plat_dir}/heap_4_silabs.c", "${examples_plat_dir}/BaseApplication.cpp", diff --git a/examples/lighting-app/silabs/efr32/include/AppTask.h b/examples/lighting-app/silabs/efr32/include/AppTask.h index df80995592fd95..cc76b02e8b293d 100644 --- a/examples/lighting-app/silabs/efr32/include/AppTask.h +++ b/examples/lighting-app/silabs/efr32/include/AppTask.h @@ -30,7 +30,9 @@ #include "BaseApplication.h" #include "FreeRTOS.h" #include "LightingManager.h" +#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT #include "sl_simple_button_instances.h" +#endif #include "timers.h" // provides FreeRTOS timer support #include #include @@ -69,7 +71,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 @@ -79,7 +81,7 @@ class AppTask : public BaseApplication * SL_SIMPLE_BUTTON_RELEASED or SL_SIMPLE_BUTTON_DISABLED */ void ButtonEventHandler(const sl_button_t * buttonHandle, uint8_t btnAction) override; - +#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 100644 new mode 100755 index ccd77060e755d1..458ae51d797865 --- a/examples/lighting-app/silabs/efr32/src/AppTask.cpp +++ b/examples/lighting-app/silabs/efr32/src/AppTask.cpp @@ -44,12 +44,18 @@ #include #ifdef ENABLE_WSTK_LEDS -#define SYSTEM_STATE_LED &sl_led_led0 +#if defined(SL_CATALOG_SIMPLE_LED_LED1_PRESENT) #define LIGHT_LED &sl_led_led1 +#else +#define LIGHT_LED &sl_led_led0 +#endif #endif // ENABLE_WSTK_LEDS +#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT + #define APP_FUNCTION_BUTTON &sl_button_btn0 #define APP_LIGHT_SWITCH &sl_button_btn1 +#endif using namespace chip; using namespace ::chip::DeviceLayer; @@ -158,6 +164,21 @@ CHIP_ERROR AppTask::Init() sLightLED.Set(LightMgr().IsLightOn()); #endif // ENABLE_WSTK_LEDS +// Update the LCD with the Stored value. Show QR Code if not provisioned +#ifdef DISPLAY_ENABLED + GetLCD().WriteDemoUI(LightMgr().IsLightOn()); +#ifdef QR_CODE_ENABLED +#ifdef SL_WIFI + if (!ConnectivityMgr().IsWiFiStationProvisioned()) +#else + if (!ConnectivityMgr().IsThreadProvisioned()) +#endif /* !SL_WIFI */ + { + GetLCD().ShowQRCode(true, true); + } +#endif // QR_CODE_ENABLED +#endif + return err; } @@ -225,11 +246,13 @@ 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; @@ -245,7 +268,7 @@ void AppTask::LightActionEventHandler(AppEvent * aEvent) } } } - +#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT void AppTask::ButtonEventHandler(const sl_button_t * buttonHandle, uint8_t btnAction) { if (buttonHandle == NULL) @@ -269,6 +292,8 @@ void AppTask::ButtonEventHandler(const sl_button_t * buttonHandle, uint8_t btnAc } } +#endif + void AppTask::ActionInitiated(LightingManager::Action_t aAction, int32_t aActor) { // Action initiated, update the light led @@ -282,11 +307,12 @@ 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) @@ -300,12 +326,13 @@ 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/lighting-app/silabs/efr32/src/main.cpp b/examples/lighting-app/silabs/efr32/src/main.cpp index 2594f6f9216e78..9f447b972678b6 100644 --- a/examples/lighting-app/silabs/efr32/src/main.cpp +++ b/examples/lighting-app/silabs/efr32/src/main.cpp @@ -21,7 +21,9 @@ #include "AppConfig.h" #include "init_efrPlatform.h" +#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT #include "sl_simple_button_instances.h" +#endif #include "sl_system_kernel.h" #include #include @@ -78,7 +80,9 @@ int main(void) appError(CHIP_ERROR_INTERNAL); } +#ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT void sl_button_on_change(const sl_button_t * handle) { AppTask::GetAppTask().ButtonEventHandler(handle, sl_button_get_state(handle)); } +#endif diff --git a/examples/lighting-app/telink/README.md b/examples/lighting-app/telink/README.md index d6ace813c0df75..11594c9091855e 100644 --- a/examples/lighting-app/telink/README.md +++ b/examples/lighting-app/telink/README.md @@ -67,16 +67,55 @@ The following buttons are available on **tlsr9518adk80d** board: ### LEDs -**Red** LED indicates current state of Thread network. It ables to be in +#### Indicate current state of Thread network + +**Red** LED indicates current state of Thread network. It is able to be in following states: | State | Description | | :-------------------------- | :--------------------------------------------------------------------------- | | Blinks with short pulses | Device is not commissioned to Thread, Thread is disabled | -| Blinls with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | -| Blinks with whde pulses | Device commissioned and joined to thread network as CHILD | +| Blinks with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | +| Blinks with wide pulses | Device commissioned and joined to thread network as CHILD | + +#### Indicate identify of device + +**Green** LED used to identify the device. The LED starts blinking when the +Identify command of the Identify cluster is received. The command's argument can +be used to specify the the effect. It is able to be in following effects: + +| Effect | Description | +| :------------------------------ | :------------------------------------------------------------------- | +| Blinks (200 ms on/200 ms off) | Blink (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK) | +| Breathe (during 1000 ms) | Breathe (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE) | +| Blinks (50 ms on/950 ms off) | Okay (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY) | +| Blinks (1000 ms on/1000 ms off) | Channel Change (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE) | +| Blinks (950 ms on/50 ms off) | Finish (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT) | +| LED off | Stop (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT) | + +#### Indicate current state of lightbulb + +By default, only **Blue** LED is used to show current state of lightbulb (only +for lightning-app). + +To enable RGB functionality in Your application set this config: + +In Matter examples/lighting-app/telink/include/**AppConfig.h**, set the define +`USE_RGB_PWM`: + +```bash + define USE_RGB_PWM 1 +``` + +To get current state of lightbulb in RGB mode, connect 3-color LED module to +following pins: -**Blue** LED shows current state of lightbulb +| Name | Pin | +| :---: | :-----------------: | +| Red | PE2 (pin 8 of J34) | +| Green | PE0 (pin 5 of J34) | +| Blue | PB4 (pin 20 of J34) | +| GND | GND (pin 24 of J50) | ### CHIP tool commands diff --git a/examples/lighting-app/telink/include/AppConfig.h b/examples/lighting-app/telink/include/AppConfig.h index 3c2430643eb2ee..531cca82215120 100644 --- a/examples/lighting-app/telink/include/AppConfig.h +++ b/examples/lighting-app/telink/include/AppConfig.h @@ -29,15 +29,15 @@ #define BUTTON_PIN_2 0 // LEDs config -// System led config -#define SYSTEM_STATE_LED_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED_PIN 7 +#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) +#define SYSTEM_STATE_LED 7 // Lighting LED config #define USE_RGB_PWM 0 -#define LIGHTING_PWM_SPEC_BLUE PWM_DT_SPEC_GET(DT_ALIAS(pwm_led0)) +#define LIGHTING_PWM_SPEC_RGB_BLUE PWM_DT_SPEC_GET(DT_ALIAS(pwm_led0)) #if USE_RGB_PWM -#define LIGHTING_PWM_SPEC_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led1)) -#define LIGHTING_PWM_SPEC_RED PWM_DT_SPEC_GET(DT_ALIAS(pwm_led2)) +#define LIGHTING_PWM_SPEC_RGB_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led1)) +#define LIGHTING_PWM_SPEC_RGB_RED PWM_DT_SPEC_GET(DT_ALIAS(pwm_led2)) #endif +#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) diff --git a/examples/lighting-app/telink/include/AppEvent.h b/examples/lighting-app/telink/include/AppEvent.h index 1766b5d77577a1..72554b4bb54b5a 100644 --- a/examples/lighting-app/telink/include/AppEvent.h +++ b/examples/lighting-app/telink/include/AppEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -32,6 +32,8 @@ struct AppEvent kEventType_Button = 0, kEventType_Timer, kEventType_UpdateLedState, + kEventType_IdentifyStart, + kEventType_IdentifyStop, kEventType_Lighting, kEventType_Install, }; diff --git a/examples/lighting-app/telink/include/AppTask.h b/examples/lighting-app/telink/include/AppTask.h index e0b37739915d4e..f0a175a4d9f9c1 100644 --- a/examples/lighting-app/telink/include/AppTask.h +++ b/examples/lighting-app/telink/include/AppTask.h @@ -18,6 +18,7 @@ #pragma once +#include "AppConfig.h" #include "AppEvent.h" #include "LEDWidget.h" #include "PWMDevice.h" @@ -34,16 +35,17 @@ #include struct k_timer; +struct Identify; class AppTask { public: - CHIP_ERROR StartApp(); + CHIP_ERROR StartApp(void); void SetInitiateAction(PWMDevice::Action_t aAction, int32_t aActor, uint8_t * value); void PostEvent(AppEvent * aEvent); - void UpdateClusterState(); - PWMDevice & GetPWMDevice() { return mBluePwmLed; } + void UpdateClusterState(void); + PWMDevice & GetPWMDevice(void) { return mPwmRgbBlueLed; } enum ButtonId_t { @@ -53,19 +55,22 @@ class AppTask kButtonId_StartBleAdv } ButtonId; + static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); + private: #ifdef CONFIG_CHIP_PW_RPC friend class chip::rpc::TelinkButton; #endif friend AppTask & GetAppTask(void); - CHIP_ERROR Init(); + CHIP_ERROR Init(void); static void ActionInitiated(PWMDevice::Action_t aAction, int32_t aActor); static void ActionCompleted(PWMDevice::Action_t aAction, int32_t aActor); + static void ActionIdentifyStateUpdateHandler(k_timer * timer); void DispatchEvent(AppEvent * event); - static void UpdateStatusLED(); + static void UpdateStatusLED(void); static void LEDStateUpdateHandler(LEDWidget * ledWidget); static void LightingActionButtonEventHandler(void); static void FactoryResetButtonEventHandler(void); @@ -82,6 +87,7 @@ class AppTask static void LightingActionEventHandler(AppEvent * aEvent); static void StartBleAdvHandler(AppEvent * aEvent); static void UpdateLedStateEventHandler(AppEvent * aEvent); + static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); static void ButtonEventHandler(ButtonId_t btnId, bool btnPressed); static void InitButtons(void); @@ -89,11 +95,12 @@ class AppTask static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); static AppTask sAppTask; - PWMDevice mBluePwmLed; + PWMDevice mPwmRgbBlueLed; #if USE_RGB_PWM - PWMDevice mGreenPwmLed; - PWMDevice mRedPwmLed; + PWMDevice mPwmRgbGreenLed; + PWMDevice mPwmRgbRedLed; #endif + PWMDevice mPwmIdentifyLed; #if CONFIG_CHIP_FACTORY_DATA // chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; diff --git a/examples/lighting-app/telink/src/AppTask.cpp b/examples/lighting-app/telink/src/AppTask.cpp index 0dd80c267c668e..3578f005f5434a 100644 --- a/examples/lighting-app/telink/src/AppTask.cpp +++ b/examples/lighting-app/telink/src/AppTask.cpp @@ -64,7 +64,7 @@ SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); #endif // CONFIG_CHIP_LIB_SHELL -LOG_MODULE_DECLARE(app); +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); using namespace ::chip; using namespace ::chip::app; @@ -72,18 +72,27 @@ using namespace ::chip::Credentials; using namespace ::chip::DeviceLayer; namespace { -constexpr int kFactoryResetTriggerTimeout = 2000; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; - -const struct pwm_dt_spec sBluePwmLed = LIGHTING_PWM_SPEC_BLUE; +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; +constexpr EndpointId kLightEndpointId = 1; +constexpr uint8_t kDefaultMinLevel = 0; +constexpr uint8_t kDefaultMaxLevel = 254; +constexpr uint32_t kIdentifyBlinkRateMs = 200; +constexpr uint32_t kIdentifyOkayOnRateMs = 50; +constexpr uint32_t kIdentifyOkayOffRateMs = 950; +constexpr uint32_t kIdentifyFinishOnRateMs = 950; +constexpr uint32_t kIdentifyFinishOffRateMs = 50; +constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; +constexpr uint32_t kIdentifyBreatheRateMs = 1000; + +const struct pwm_dt_spec sPwmRgbSpecBlueLed = LIGHTING_PWM_SPEC_RGB_BLUE; #if USE_RGB_PWM -const struct pwm_dt_spec sGreenPwmLed = LIGHTING_PWM_SPEC_GREEN; -const struct pwm_dt_spec sRedPwmLed = LIGHTING_PWM_SPEC_RED; +const struct pwm_dt_spec sPwmRgbSpecGreenLed = LIGHTING_PWM_SPEC_RGB_GREEN; +const struct pwm_dt_spec sPwmRgbSpecRedLed = LIGHTING_PWM_SPEC_RGB_RED; #endif +const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; #if CONFIG_CHIP_FACTORY_DATA // NOTE! This key is for test/certification only and should not be available in production devices! @@ -118,29 +127,11 @@ chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; void OnIdentifyTriggerEffect(Identify * identify) { - switch (identify->mCurrentEffectIdentifier) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - break; - } - return; + AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); } Identify sIdentify = { - chip::EndpointId{ 1 }, + kLightEndpointId, [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStart"); }, [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStop"); }, EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, @@ -162,14 +153,15 @@ class AppFabricTableDelegate : public FabricTable::Delegate } }; -CHIP_ERROR AppTask::Init() +CHIP_ERROR AppTask::Init(void) { LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); - // Initialize status LED - LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + // Initialize LEDs + LEDWidget::InitGpio(LEDS_PORT); LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED_PIN); + + sStatusLED.Init(SYSTEM_STATE_LED); UpdateStatusLED(); @@ -181,33 +173,42 @@ CHIP_ERROR AppTask::Init() // Init lighting manager uint8_t minLightLevel = kDefaultMinLevel; - Clusters::LevelControl::Attributes::MinLevel::Get(1, &minLightLevel); + Clusters::LevelControl::Attributes::MinLevel::Get(kLightEndpointId, &minLightLevel); uint8_t maxLightLevel = kDefaultMaxLevel; - Clusters::LevelControl::Attributes::MaxLevel::Get(1, &maxLightLevel); + Clusters::LevelControl::Attributes::MaxLevel::Get(kLightEndpointId, &maxLightLevel); + + // Initialize PWM LEDs + CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("Green IDENTIFY PWM Device Init fail"); + return err; + } - CHIP_ERROR err = sAppTask.mBluePwmLed.Init(&sBluePwmLed, minLightLevel, maxLightLevel, maxLightLevel); + err = sAppTask.mPwmRgbBlueLed.Init(&sPwmRgbSpecBlueLed, minLightLevel, maxLightLevel, maxLightLevel); if (err != CHIP_NO_ERROR) { - LOG_ERR("Blue PWM Device Init fail"); + LOG_ERR("Blue RGB PWM Device Init fail"); return err; } #if USE_RGB_PWM - err = sAppTask.mRedPwmLed.Init(&sRedPwmLed, minLightLevel, maxLightLevel, maxLightLevel); + err = sAppTask.mPwmRgbRedLed.Init(&sPwmRgbSpecRedLed, minLightLevel, maxLightLevel, maxLightLevel); if (err != CHIP_NO_ERROR) { - LOG_ERR("Red PWM Device Init fail"); + LOG_ERR("Red RGB PWM Device Init fail"); return err; } - err = sAppTask.mGreenPwmLed.Init(&sGreenPwmLed, minLightLevel, maxLightLevel, maxLightLevel); + err = sAppTask.mPwmRgbGreenLed.Init(&sPwmRgbSpecGreenLed, minLightLevel, maxLightLevel, maxLightLevel); if (err != CHIP_NO_ERROR) { - LOG_ERR("Green PWM Device Init fail"); + LOG_ERR("Green RGB PWM Device Init fail"); return err; } #endif - sAppTask.mBluePwmLed.SetCallbacks(ActionInitiated, ActionCompleted); + sAppTask.mPwmRgbBlueLed.SetCallbacks(ActionInitiated, ActionCompleted, nullptr); + sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); // Initialize CHIP server #if CONFIG_CHIP_FACTORY_DATA @@ -265,7 +266,7 @@ CHIP_ERROR AppTask::Init() return CHIP_NO_ERROR; } -CHIP_ERROR AppTask::StartApp() +CHIP_ERROR AppTask::StartApp(void) { CHIP_ERROR err = Init(); @@ -312,7 +313,7 @@ void AppTask::LightingActionEventHandler(AppEvent * aEvent) else if (aEvent->Type == AppEvent::kEventType_Button) { #if USE_RGB_PWM - if (sAppTask.mRedPwmLed.IsTurnedOn() || sAppTask.mGreenPwmLed.IsTurnedOn() || sAppTask.mBluePwmLed.IsTurnedOn()) + if (sAppTask.mPwmRgbRedLed.IsTurnedOn() || sAppTask.mPwmRgbGreenLed.IsTurnedOn() || sAppTask.mPwmRgbBlueLed.IsTurnedOn()) { action = PWMDevice::OFF_ACTION; } @@ -321,7 +322,7 @@ void AppTask::LightingActionEventHandler(AppEvent * aEvent) action = PWMDevice::ON_ACTION; } #else - action = sAppTask.mBluePwmLed.IsTurnedOn() ? PWMDevice::OFF_ACTION : PWMDevice::ON_ACTION; + action = sAppTask.mPwmRgbBlueLed.IsTurnedOn() ? PWMDevice::OFF_ACTION : PWMDevice::ON_ACTION; #endif actor = AppEvent::kEventType_Button; } @@ -329,15 +330,65 @@ void AppTask::LightingActionEventHandler(AppEvent * aEvent) if (action != PWMDevice::INVALID_ACTION && ( #if USE_RGB_PWM - !sAppTask.mRedPwmLed.InitiateAction(action, actor, NULL) || - !sAppTask.mGreenPwmLed.InitiateAction(action, actor, NULL) || + !sAppTask.mPwmRgbRedLed.InitiateAction(action, actor, NULL) || + !sAppTask.mPwmRgbGreenLed.InitiateAction(action, actor, NULL) || #endif - !sAppTask.mBluePwmLed.InitiateAction(action, actor, NULL))) + !sAppTask.mPwmRgbBlueLed.InitiateAction(action, actor, NULL))) { LOG_INF("Action is in progress or active"); } } +void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStart; + + switch (aEffect) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); + event.Handler = [](AppEvent *) { + sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); + event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; + event.Type = AppEvent::kEventType_IdentifyStop; + break; + default: + ChipLogProgress(Zcl, "No identifier effect"); + return; + } + + sAppTask.PostEvent(&event); +} + void AppTask::FactoryResetButtonEventHandler(void) { AppEvent event; @@ -438,7 +489,7 @@ void AppTask::LEDStateUpdateHandler(LEDWidget * ledWidget) sAppTask.PostEvent(&event); } -void AppTask::UpdateStatusLED() +void AppTask::UpdateStatusLED(void) { if (sIsThreadProvisioned && sIsThreadEnabled) { @@ -484,19 +535,32 @@ void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */ } } +void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateIdentifyStateEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) +{ + sAppTask.mPwmIdentifyLed.UpdateAction(); +} + void AppTask::ActionInitiated(PWMDevice::Action_t aAction, int32_t aActor) { if (aAction == PWMDevice::ON_ACTION) { - LOG_INF("ON_ACTION initiated"); + LOG_DBG("ON_ACTION initiated"); } else if (aAction == PWMDevice::OFF_ACTION) { - LOG_INF("OFF_ACTION initiated"); + LOG_DBG("OFF_ACTION initiated"); } else if (aAction == PWMDevice::LEVEL_ACTION) { - LOG_INF("LEVEL_ACTION initiated"); + LOG_DBG("LEVEL_ACTION initiated"); } } @@ -504,15 +568,15 @@ void AppTask::ActionCompleted(PWMDevice::Action_t aAction, int32_t aActor) { if (aAction == PWMDevice::ON_ACTION) { - LOG_INF("ON_ACTION completed"); + LOG_DBG("ON_ACTION completed"); } else if (aAction == PWMDevice::OFF_ACTION) { - LOG_INF("OFF_ACTION completed"); + LOG_DBG("OFF_ACTION completed"); } else if (aAction == PWMDevice::LEVEL_ACTION) { - LOG_INF("LEVEL_ACTION completed"); + LOG_DBG("LEVEL_ACTION completed"); } if (aActor == AppEvent::kEventType_Button) @@ -541,15 +605,16 @@ void AppTask::DispatchEvent(AppEvent * aEvent) } } -void AppTask::UpdateClusterState() +void AppTask::UpdateClusterState(void) { #if USE_RGB_PWM - bool isTurnedOn = sAppTask.mRedPwmLed.IsTurnedOn() || sAppTask.mGreenPwmLed.IsTurnedOn() || sAppTask.mBluePwmLed.IsTurnedOn(); + bool isTurnedOn = + sAppTask.mPwmRgbRedLed.IsTurnedOn() || sAppTask.mPwmRgbGreenLed.IsTurnedOn() || sAppTask.mPwmRgbBlueLed.IsTurnedOn(); #else - bool isTurnedOn = sAppTask.mBluePwmLed.IsTurnedOn(); + bool isTurnedOn = sAppTask.mPwmRgbBlueLed.IsTurnedOn(); #endif // write the new on/off value - EmberAfStatus status = Clusters::OnOff::Attributes::OnOff::Set(1, isTurnedOn); + EmberAfStatus status = Clusters::OnOff::Attributes::OnOff::Set(kLightEndpointId, isTurnedOn); if (status != EMBER_ZCL_STATUS_SUCCESS) { @@ -565,12 +630,12 @@ void AppTask::UpdateClusterState() } else { - setLevel = sAppTask.mBluePwmLed.GetLevel(); + setLevel = sAppTask.mPwmRgbBlueLed.GetLevel(); } #else - uint8_t setLevel = sAppTask.mBluePwmLed.GetLevel(); + uint8_t setLevel = sAppTask.mPwmRgbBlueLed.GetLevel(); #endif - status = Clusters::LevelControl::Attributes::CurrentLevel::Set(1, setLevel); + status = Clusters::LevelControl::Attributes::CurrentLevel::Set(kLightEndpointId, setLevel); if (status != EMBER_ZCL_STATUS_SUCCESS) { LOG_ERR("Update CurrentLevel fail: %x", status); @@ -648,10 +713,10 @@ void AppTask::SetInitiateAction(PWMDevice::Action_t aAction, int32_t aActor, uin if (aAction == PWMDevice::ON_ACTION || aAction == PWMDevice::OFF_ACTION) { - sAppTask.mBluePwmLed.InitiateAction(aAction, aActor, value); + sAppTask.mPwmRgbBlueLed.InitiateAction(aAction, aActor, value); #if USE_RGB_PWM - sAppTask.mRedPwmLed.InitiateAction(aAction, aActor, value); - sAppTask.mGreenPwmLed.InitiateAction(aAction, aActor, value); + sAppTask.mPwmRgbRedLed.InitiateAction(aAction, aActor, value); + sAppTask.mPwmRgbGreenLed.InitiateAction(aAction, aActor, value); #endif } else if (aAction == PWMDevice::LEVEL_ACTION) @@ -679,7 +744,7 @@ void AppTask::SetInitiateAction(PWMDevice::Action_t aAction, int32_t aActor, uin ChipLogProgress(Zcl, "New brightness: %u | R: %u, G: %u, B: %u", sBrightness, rgb.r, rgb.g, rgb.b); setRgbAction = true; #else - sAppTask.mBluePwmLed.InitiateAction(aAction, aActor, value); + sAppTask.mPwmRgbBlueLed.InitiateAction(aAction, aActor, value); #endif } @@ -716,9 +781,9 @@ void AppTask::SetInitiateAction(PWMDevice::Action_t aAction, int32_t aActor, uin if (setRgbAction) { - sAppTask.mRedPwmLed.InitiateAction(aAction, aActor, &rgb.r); - sAppTask.mGreenPwmLed.InitiateAction(aAction, aActor, &rgb.g); - sAppTask.mBluePwmLed.InitiateAction(aAction, aActor, &rgb.b); + sAppTask.mPwmRgbRedLed.InitiateAction(aAction, aActor, &rgb.r); + sAppTask.mPwmRgbGreenLed.InitiateAction(aAction, aActor, &rgb.g); + sAppTask.mPwmRgbBlueLed.InitiateAction(aAction, aActor, &rgb.b); } #endif } diff --git a/examples/lighting-app/telink/src/ZclCallbacks.cpp b/examples/lighting-app/telink/src/ZclCallbacks.cpp index 5a0a6dbec4c07f..f25ae759db8150 100644 --- a/examples/lighting-app/telink/src/ZclCallbacks.cpp +++ b/examples/lighting-app/telink/src/ZclCallbacks.cpp @@ -26,6 +26,8 @@ #include #include +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); + using namespace chip; using namespace chip::app::Clusters; using namespace chip::app::Clusters::OnOff; @@ -40,7 +42,7 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & if (clusterId == OnOff::Id && attributeId == OnOff::Attributes::OnOff::Id) { - ChipLogProgress(Zcl, "Cluster OnOff: attribute OnOff set to %u", *value); + ChipLogDetail(Zcl, "Cluster OnOff: attribute OnOff set to %u", *value); GetAppTask().SetInitiateAction(*value ? PWMDevice::ON_ACTION : PWMDevice::OFF_ACTION, static_cast(AppEvent::kEventType_Lighting), value); } @@ -48,7 +50,7 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & { if (GetAppTask().GetPWMDevice().IsTurnedOn()) { - ChipLogProgress(Zcl, "Cluster LevelControl: attribute CurrentLevel set to %u", *value); + ChipLogDetail(Zcl, "Cluster LevelControl: attribute CurrentLevel set to %u", *value); GetAppTask().SetInitiateAction(PWMDevice::LEVEL_ACTION, static_cast(AppEvent::kEventType_Lighting), value); } else @@ -78,7 +80,7 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & xy.y = *reinterpret_cast(value); } - ChipLogProgress(Zcl, "New XY color: %u|%u", xy.x, xy.y); + ChipLogDetail(Zcl, "New XY color: %u|%u", xy.x, xy.y); GetAppTask().SetInitiateAction(PWMDevice::COLOR_ACTION_XY, static_cast(AppEvent::kEventType_Lighting), (uint8_t *) &xy); } @@ -100,19 +102,19 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & { hsv.s = *value; } - ChipLogProgress(Zcl, "New HSV color: hue = %u| saturation = %u", hsv.h, hsv.s); + ChipLogDetail(Zcl, "New HSV color: hue = %u| saturation = %u", hsv.h, hsv.s); GetAppTask().SetInitiateAction(PWMDevice::COLOR_ACTION_HSV, static_cast(AppEvent::kEventType_Lighting), (uint8_t *) &hsv); } /* Temperature Mireds color space */ else if (attributeId == ColorControl::Attributes::ColorTemperatureMireds::Id) { - ChipLogProgress(Zcl, "New Temperature Mireds color = %u", *(uint16_t *) value); + ChipLogDetail(Zcl, "New Temperature Mireds color = %u", *(uint16_t *) value); GetAppTask().SetInitiateAction(PWMDevice::COLOR_ACTION_CT, static_cast(AppEvent::kEventType_Lighting), value); } else { - ChipLogProgress(Zcl, "Ignore ColorControl attribute (%u) that is not currently processed!", attributeId); + ChipLogDetail(Zcl, "Ignore ColorControl attribute (%u) that is not currently processed!", attributeId); } } } diff --git a/examples/lighting-app/telink/src/main.cpp b/examples/lighting-app/telink/src/main.cpp index 2e30e3cc52b6f9..ca6d59cbc9eae8 100644 --- a/examples/lighting-app/telink/src/main.cpp +++ b/examples/lighting-app/telink/src/main.cpp @@ -27,7 +27,7 @@ #include "Rpc.h" #endif -LOG_MODULE_REGISTER(app); +LOG_MODULE_REGISTER(app, CONFIG_CHIP_APP_LOG_LEVEL); using namespace ::chip; using namespace ::chip::Inet; diff --git a/examples/lock-app/esp32/main/CMakeLists.txt b/examples/lock-app/esp32/main/CMakeLists.txt index 8947b92a95c617..e15ee62a79f53b 100644 --- a/examples/lock-app/esp32/main/CMakeLists.txt +++ b/examples/lock-app/esp32/main/CMakeLists.txt @@ -41,7 +41,6 @@ idf_component_register(INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/common/pigweed/esp32" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/lock-app/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/util" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" @@ -152,7 +151,6 @@ idf_component_register(PRIV_INCLUDE_DIRS "${CMAKE_CURRENT_LIST_DIR}" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/lock-app/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/shell_extension" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/common" diff --git a/examples/lock-app/linux/include/LockEndpoint.h b/examples/lock-app/linux/include/LockEndpoint.h index 0e0b32fd3b775b..7ba34d10d6c3cd 100644 --- a/examples/lock-app/linux/include/LockEndpoint.h +++ b/examples/lock-app/linux/include/LockEndpoint.h @@ -39,6 +39,7 @@ struct YearDayScheduleInfo; struct HolidayScheduleInfo; static constexpr size_t DOOR_LOCK_CREDENTIAL_INFO_MAX_DATA_SIZE = 20; +static constexpr size_t DOOR_LOCK_CREDENTIAL_INFO_MAX_TYPES = 6; class LockEndpoint { @@ -48,7 +49,7 @@ class LockEndpoint uint8_t numberOfHolidaySchedules) : mEndpointId{ endpointId }, mLockState{ DlLockState::kLocked }, mDoorState{ DoorStateEnum::kDoorClosed }, mLockUsers(numberOfLockUsersSupported), - mLockCredentials(numberOfCredentialsSupported + 1), + mLockCredentials(DOOR_LOCK_CREDENTIAL_INFO_MAX_TYPES, std::vector(numberOfCredentialsSupported + 1)), mWeekDaySchedules(numberOfLockUsersSupported, std::vector(weekDaySchedulesPerUser)), mYearDaySchedules(numberOfLockUsersSupported, std::vector(yearDaySchedulesPerUser)), mHolidaySchedules(numberOfHolidaySchedules) @@ -109,7 +110,7 @@ class LockEndpoint // This is very naive implementation of users/credentials/schedules database and by no means the best practice. Proper storage // of those items is out of scope of this example. std::vector mLockUsers; - std::vector mLockCredentials; + std::vector> mLockCredentials; std::vector> mWeekDaySchedules; std::vector> mYearDaySchedules; std::vector mHolidaySchedules; diff --git a/examples/lock-app/linux/src/LockEndpoint.cpp b/examples/lock-app/linux/src/LockEndpoint.cpp index 6ed9592df0c0f9..672b2f32f9fb75 100644 --- a/examples/lock-app/linux/src/LockEndpoint.cpp +++ b/examples/lock-app/linux/src/LockEndpoint.cpp @@ -164,14 +164,20 @@ bool LockEndpoint::GetCredential(uint16_t credentialIndex, CredentialTypeEnum cr ChipLogProgress(Zcl, "Lock App: LockEndpoint::GetCredential [endpoint=%d,credentialIndex=%u,credentialType=%u]", mEndpointId, credentialIndex, to_underlying(credentialType)); - if (credentialIndex >= mLockCredentials.size() || + if (to_underlying(credentialType) >= mLockCredentials.size()) + { + ChipLogError(Zcl, "Cannot get the credential - index out of range [endpoint=%d,index=%d]", mEndpointId, credentialIndex); + return false; + } + + if (credentialIndex >= mLockCredentials.at(to_underlying(credentialType)).size() || (0 == credentialIndex && CredentialTypeEnum::kProgrammingPIN != credentialType)) { ChipLogError(Zcl, "Cannot get the credential - index out of range [endpoint=%d,index=%d]", mEndpointId, credentialIndex); return false; } - const auto & credentialInStorage = mLockCredentials[credentialIndex]; + const auto & credentialInStorage = mLockCredentials[to_underlying(credentialType)][credentialIndex]; credential.status = credentialInStorage.status; if (DlCredentialStatus::kAvailable == credential.status) @@ -206,14 +212,21 @@ bool LockEndpoint::SetCredential(uint16_t credentialIndex, chip::FabricIndex cre mEndpointId, credentialIndex, to_underlying(credentialStatus), to_underlying(credentialType), static_cast(credentialData.size()), creator, modifier); - if (credentialIndex >= mLockCredentials.size() || + if (to_underlying(credentialType) >= mLockCredentials.capacity()) + { + ChipLogError(Zcl, "Cannot set the credential - type out of range [endpoint=%d,type=%d]", mEndpointId, + to_underlying(credentialType)); + return false; + } + + if (credentialIndex >= mLockCredentials.at(to_underlying(credentialType)).size() || (0 == credentialIndex && CredentialTypeEnum::kProgrammingPIN != credentialType)) { ChipLogError(Zcl, "Cannot set the credential - index out of range [endpoint=%d,index=%d]", mEndpointId, credentialIndex); return false; } - auto & credentialInStorage = mLockCredentials[credentialIndex]; + auto & credentialInStorage = mLockCredentials[to_underlying(credentialType)][credentialIndex]; if (credentialData.size() > DOOR_LOCK_CREDENTIAL_INFO_MAX_DATA_SIZE) { ChipLogError(Zcl, @@ -391,11 +404,12 @@ bool LockEndpoint::setLockState(DlLockState lockState, const Optional(credential - mLockCredentials.begin()); + auto credentialIndex = static_cast(credential - pinCredentials.begin()); auto user = std::find_if(mLockUsers.begin(), mLockUsers.end(), [credential, credentialIndex](const LockUserInfo & u) { return std::any_of(u.credentials.begin(), u.credentials.end(), [&credential, credentialIndex](const CredentialStruct & c) { return c.CredentialIndex == credentialIndex && c.CredentialType == to_underlying(credential->credentialType); diff --git a/examples/lock-app/lock-common/lock-app.matter b/examples/lock-app/lock-common/lock-app.matter index 236536d36f27ff..3c5c2dc494f7c0 100644 --- a/examples/lock-app/lock-common/lock-app.matter +++ b/examples/lock-app/lock-common/lock-app.matter @@ -71,10 +71,6 @@ server cluster OnOff = 6 { kLighting = 0x1; } - bitmap SceneFeatures : BITMAP32 { - kSceneNames = 0x1; - } - readonly attribute boolean onOff = 0; readonly attribute boolean globalSceneControl = 16384; attribute int16u onTime = 16385; @@ -391,7 +387,7 @@ server cluster PowerSourceConfiguration = 46 { server cluster PowerSource = 47 { enum BatChargeFault : ENUM8 { - kUnspecfied = 0; + kUnspecified = 0; kAmbientTooHot = 1; kAmbientTooCold = 2; kBatteryTooHot = 3; @@ -431,7 +427,7 @@ server cluster PowerSource = 47 { } enum PowerSourceStatus : ENUM8 { - kUnspecfied = 0; + kUnspecified = 0; kActive = 1; kStandby = 2; kUnavailable = 3; @@ -1025,6 +1021,11 @@ server cluster WiFiNetworkDiagnostics = 54 { kAx = 5; } + bitmap WiFiNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + info event Disconnection = 0 { INT16U reasonCode = 0; } @@ -1071,6 +1072,11 @@ server cluster EthernetNetworkDiagnostics = 55 { kRate400G = 9; } + bitmap EthernetNetworkDiagnosticsFeature : BITMAP32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + } + readonly attribute nullable PHYRateEnum PHYRate = 0; readonly attribute nullable boolean fullDuplex = 1; readonly attribute int64u packetRxCount = 2; diff --git a/examples/lock-app/openiotsdk/CMakeLists.txt b/examples/lock-app/openiotsdk/CMakeLists.txt index 1e0125b99c0497..ec75b81afdf3d2 100644 --- a/examples/lock-app/openiotsdk/CMakeLists.txt +++ b/examples/lock-app/openiotsdk/CMakeLists.txt @@ -19,11 +19,15 @@ cmake_minimum_required(VERSION 3.21) get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../../.. REALPATH) get_filename_component(OPEN_IOT_SDK_CONFIG ${CHIP_ROOT}/config/openiotsdk REALPATH) get_filename_component(OPEN_IOT_SDK_EXAMPLE_COMMON ${CHIP_ROOT}/examples/platform/openiotsdk REALPATH) -get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH) list(APPEND CMAKE_MODULE_PATH ${OPEN_IOT_SDK_CONFIG}/cmake) -set(APP_TARGET chip-openiotsdk-lock-app-example) +set(APP_TARGET chip-openiotsdk-lock-app-example_ns) + +set(TFM_SUPPORT YES) +set(TFM_PROJECT_CONFIG_HEADER_FILE "${CMAKE_CURRENT_SOURCE_DIR}/tf-m-config/TfmProjectConfig.h") +set(TFM_NS_APP_VERSION "0.0.1") +set(CONFIG_CHIP_OPEN_IOT_SDK_USE_PSA_PS YES) # Toolchain files need to exist before first call to project include(toolchain) @@ -55,16 +59,16 @@ include(chip) add_subdirectory(${OPEN_IOT_SDK_EXAMPLE_COMMON}/app ./app_build) -target_include_directories(${APP_TARGET} +chip_add_data_model(openiotsdk-app PUBLIC lock) + +target_include_directories(${APP_TARGET} PRIVATE main/include - ${GEN_DIR}/app-common - ${GEN_DIR}/lock-app ) -target_sources(${APP_TARGET} +target_sources(${APP_TARGET} PRIVATE - main/main.cpp + main/main_ns.cpp main/ZclCallbacks.cpp main/LockManager.cpp main/LockEndpoint.cpp @@ -74,11 +78,7 @@ target_link_libraries(${APP_TARGET} openiotsdk-app ) -include(${CHIP_ROOT}/src/app/chip_data_model.cmake) -chip_configure_data_model(${APP_TARGET} - INCLUDE_SERVER - ZAP_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../lock-common/lock-app.zap -) - include(linker) set_target_link(${APP_TARGET}) + +sdk_post_build(${APP_TARGET}) diff --git a/examples/lock-app/openiotsdk/cmsis-config/RTE_Components.h b/examples/lock-app/openiotsdk/cmsis-config/RTE_Components.h index 3921500daecafb..e86df2b4e44e06 100644 --- a/examples/lock-app/openiotsdk/cmsis-config/RTE_Components.h +++ b/examples/lock-app/openiotsdk/cmsis-config/RTE_Components.h @@ -19,6 +19,4 @@ #ifndef RTE_COMPONENTS_H #define RTE_COMPONENTS_H -#define OS_STACK_SIZE (4 * 1024) - #endif // RTE_COMPONENTS_H diff --git a/examples/lock-app/openiotsdk/freertos-config/FreeRTOSConfig.h b/examples/lock-app/openiotsdk/freertos-config/FreeRTOSConfig.h index c95af61db3c84d..bfcd8f09e9b4aa 100644 --- a/examples/lock-app/openiotsdk/freertos-config/FreeRTOSConfig.h +++ b/examples/lock-app/openiotsdk/freertos-config/FreeRTOSConfig.h @@ -190,7 +190,7 @@ extern uint32_t SystemCoreClock; // Use TrustZone Secure Side Only // This settings prevents FreeRTOS contex switch to Non-Secure side. // Enable this setting when FreeRTOS runs on the Secure side only. -#define configRUN_FREERTOS_SECURE_ONLY 1 +#define configRUN_FREERTOS_SECURE_ONLY CONFIG_RUN_FREERTOS_SECURE_ONLY // Use TrustZone Security Extension // Using TrustZone affects context handling. diff --git a/examples/lock-app/openiotsdk/main/main.cpp b/examples/lock-app/openiotsdk/main/main_ns.cpp similarity index 63% rename from examples/lock-app/openiotsdk/main/main.cpp rename to examples/lock-app/openiotsdk/main/main_ns.cpp index fbd72e0542fc85..2b6484b05180c2 100644 --- a/examples/lock-app/openiotsdk/main/main.cpp +++ b/examples/lock-app/openiotsdk/main/main_ns.cpp @@ -18,48 +18,23 @@ #include #include -#include #include -#include - -#include -#include -#include -#include #include "openiotsdk_platform.h" -using namespace ::chip; -using namespace ::chip::DeviceLayer; - static void app_thread(void * argument) { - CHIP_ERROR error; - if (openiotsdk_network_init(true)) { ChipLogError(NotSpecified, "Network initialization failed"); goto exit; } - // Init ZCL Data Model and start server - static chip::CommonCaseDeviceServerInitParams initParams; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - initParams.operationalServicePort = CHIP_PORT; - initParams.userDirectedCommissioningPort = CHIP_UDC_PORT; - - error = Server::GetInstance().Init(initParams); - SuccessOrExit(error); - - // Now that the server has started and we are done with our startup logging, - // log our discovery/onboarding information again so it's not lost in the - // noise. - ConfigurationMgr().LogDeviceConfig(); - - PrintOnboardingCodes(RendezvousInformationFlags(RendezvousInformationFlag::kOnNetwork)); - - // Initialize device attestation config - SetDeviceAttestationCredentialsProvider(Credentials::Examples::GetExampleDACProvider()); + if (openiotsdk_chip_run()) + { + ChipLogError(NotSpecified, "CHIP stack run failed"); + goto exit; + } ChipLogProgress(NotSpecified, "Open IoT SDK lock-app example application run"); @@ -69,7 +44,7 @@ static void app_thread(void * argument) osDelay(osWaitForever); } - Server::GetInstance().Shutdown(); + openiotsdk_chip_shutdown(); exit: osThreadTerminate(osThreadGetId()); diff --git a/examples/lock-app/openiotsdk/tf-m-config/TfmProjectConfig.h b/examples/lock-app/openiotsdk/tf-m-config/TfmProjectConfig.h new file mode 100644 index 00000000000000..a792f400bd2660 --- /dev/null +++ b/examples/lock-app/openiotsdk/tf-m-config/TfmProjectConfig.h @@ -0,0 +1,165 @@ +/* + * + * 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. + */ + +#ifndef TFM_PROJECT_CONFIG_H +#define TFM_PROJECT_CONFIG_H + +/* Platform Partition Configs */ + +/* Size of input buffer in platform service */ +#define PLATFORM_SERVICE_INPUT_BUFFER_SIZE 64 + +/* Size of output buffer in platform service */ +#define PLATFORM_SERVICE_OUTPUT_BUFFER_SIZE 64 + +/* The stack size of the Platform Secure Partition */ +#define PLATFORM_SP_STACK_SIZE 0x500 + +/* Disable Non-volatile counter module */ +#define PLATFORM_NV_COUNTER_MODULE_DISABLED 0 + +/* Crypto Partition Configs */ + +/* + * Heap size for the crypto backend + * CRYPTO_ENGINE_BUF_SIZE needs to be >8KB for EC signing by attest module. + */ +#define CRYPTO_ENGINE_BUF_SIZE 0x2080 + +/* The max number of concurrent operations that can be active (allocated) at any time in Crypto */ +#define CRYPTO_CONC_OPER_NUM 8 + +/* Enable PSA Crypto random number generator module */ +#define CRYPTO_RNG_MODULE_ENABLED 1 + +/* Enable PSA Crypto Key module */ +#define CRYPTO_KEY_MODULE_ENABLED 1 + +/* Enable PSA Crypto AEAD module */ +#define CRYPTO_AEAD_MODULE_ENABLED 1 + +/* Enable PSA Crypto MAC module */ +#define CRYPTO_MAC_MODULE_ENABLED 1 + +/* Enable PSA Crypto Hash module */ +#define CRYPTO_HASH_MODULE_ENABLED 1 + +/* Enable PSA Crypto Cipher module */ +#define CRYPTO_CIPHER_MODULE_ENABLED 1 + +/* Enable PSA Crypto asymmetric key signature module */ +#define CRYPTO_ASYM_SIGN_MODULE_ENABLED 1 + +/* Enable PSA Crypto asymmetric key encryption module */ +#define CRYPTO_ASYM_ENCRYPT_MODULE_ENABLED 0 + +/* Enable PSA Crypto key derivation module */ +#define CRYPTO_KEY_DERIVATION_MODULE_ENABLED 1 + +/* Default size of the internal scratch buffer used for PSA FF IOVec allocations */ +#define CRYPTO_IOVEC_BUFFER_SIZE 5120 + +/* Use stored NV seed to provide entropy */ +#define CRYPTO_NV_SEED 1 + +/* + * Only enable multi-part operations in Hash, MAC, AEAD and symmetric ciphers, + * to optimize memory footprint in resource-constrained devices. + */ +#define CRYPTO_SINGLE_PART_FUNCS_DISABLED 0 + +/* The stack size of the Crypto Secure Partition */ +#define CRYPTO_STACK_SIZE 0x1B00 + +/* FWU Partition Configs */ + +/* Size of the FWU internal data transfer buffer */ +#define TFM_FWU_BUF_SIZE PSA_FWU_MAX_WRITE_SIZE + +/* The stack size of the Firmware Update Secure Partition */ +#define FWU_STACK_SIZE 0x600 + +/* Attest Partition Configs */ + +/* Include optional claims in initial attestation token */ +#define ATTEST_INCLUDE_OPTIONAL_CLAIMS 1 + +/* Include COSE key-id in initial attestation token */ +#define ATTEST_INCLUDE_COSE_KEY_ID 0 + +/* The stack size of the Initial Attestation Secure Partition */ +#define ATTEST_STACK_SIZE 0x700 + +/* Set the initial attestation token profile */ +#define ATTEST_TOKEN_PROFILE_PSA_IOT_1 1 + +/* ITS Partition Configs */ + +/* Create flash FS if it doesn't exist for Internal Trusted Storage partition */ +#define ITS_CREATE_FLASH_LAYOUT 1 + +/* Enable emulated RAM FS for platforms that don't have flash for Internal Trusted Storage partition */ +#define ITS_RAM_FS 0 + +/* Validate filesystem metadata every time it is read from flash */ +#define ITS_VALIDATE_METADATA_FROM_FLASH 1 + +/* The maximum asset size to be stored in the Internal Trusted Storage */ +#define ITS_MAX_ASSET_SIZE 512 + +/* Size of the ITS internal data transfer buffer */ +#define ITS_BUF_SIZE 32 + +/* The maximum number of assets to be stored in the Internal Trusted Storage */ +#define ITS_NUM_ASSETS 10 + +/* The stack size of the Internal Trusted Storage Secure Partition */ +#define ITS_STACK_SIZE 0x720 + +/* PS Partition Configs */ + +/* Create flash FS if it doesn't exist for Protected Storage partition */ +#define PS_CREATE_FLASH_LAYOUT 1 + +/* Enable emulated RAM FS for platforms that don't have flash for Protected Storage partition */ +#define PS_RAM_FS 0 + +/* Enable rollback protection for Protected Storage partition */ +#define PS_ROLLBACK_PROTECTION 1 + +/* Validate filesystem metadata every time it is read from flash */ +#define PS_VALIDATE_METADATA_FROM_FLASH 1 + +/* The maximum asset size to be stored in the Protected Storage */ +#define PS_MAX_ASSET_SIZE 2048 + +/* The maximum number of assets to be stored in the Protected Storage */ +#define PS_NUM_ASSETS 30 + +/* The stack size of the Protected Storage Secure Partition */ +#define PS_STACK_SIZE 0x700 + +/* SPM Partition Configs */ + +/* The maximal number of secure services that are connected or requested at the same time */ +#define CONFIG_TFM_CONN_HANDLE_MAX_NUM 8 + +/* Enable the doorbell APIs */ +#define CONFIG_TFM_DOORBELL_API 1 + +#endif /* TFM_PROJECT_CONFIG_H */ diff --git a/examples/lock-app/silabs/efr32/src/AppTask.cpp b/examples/lock-app/silabs/efr32/src/AppTask.cpp index 241c49319fa01b..142991bbe5be3e 100644 --- a/examples/lock-app/silabs/efr32/src/AppTask.cpp +++ b/examples/lock-app/silabs/efr32/src/AppTask.cpp @@ -252,6 +252,21 @@ CHIP_ERROR AppTask::Init() sLockLED.Set(state.Value() == DlLockState::kUnlocked); #endif // ENABLE_WSTK_LEDS + // Update the LCD with the Stored value. Show QR Code if not provisioned +#ifdef DISPLAY_ENABLED + GetLCD().WriteDemoUI(state.Value() != DlLockState::kUnlocked); +#ifdef QR_CODE_ENABLED +#ifdef SL_WIFI + if (!ConnectivityMgr().IsWiFiStationProvisioned()) +#else + if (!ConnectivityMgr().IsThreadProvisioned()) +#endif /* !SL_WIFI */ + { + GetLCD().ShowQRCode(true, true); + } +#endif // QR_CODE_ENABLED +#endif + chip::DeviceLayer::PlatformMgr().ScheduleWork(UpdateClusterState, reinterpret_cast(nullptr)); ConfigurationMgr().LogDeviceConfig(); diff --git a/examples/ota-provider-app/esp32/main/CMakeLists.txt b/examples/ota-provider-app/esp32/main/CMakeLists.txt index 8c58d0b4b4fc18..7bbf39d18ab0e3 100644 --- a/examples/ota-provider-app/esp32/main/CMakeLists.txt +++ b/examples/ota-provider-app/esp32/main/CMakeLists.txt @@ -23,7 +23,6 @@ idf_component_register(PRIV_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/providers" SRC_DIRS "${CMAKE_CURRENT_LIST_DIR}" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/ota-provider-app/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/server" diff --git a/examples/ota-requestor-app/esp32/main/CMakeLists.txt b/examples/ota-requestor-app/esp32/main/CMakeLists.txt index cdd50a0b220c1b..f2320f4c3785f4 100644 --- a/examples/ota-requestor-app/esp32/main/CMakeLists.txt +++ b/examples/ota-requestor-app/esp32/main/CMakeLists.txt @@ -28,7 +28,6 @@ set(PRIV_INCLUDE_DIRS_LIST set(SRC_DIRS_LIST "${CMAKE_CURRENT_LIST_DIR}" - "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/ota-requestor-app/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/server" diff --git a/examples/ota-requestor-app/linux/README.md b/examples/ota-requestor-app/linux/README.md index f14d5fa7cdf094..9cb47171aae555 100644 --- a/examples/ota-requestor-app/linux/README.md +++ b/examples/ota-requestor-app/linux/README.md @@ -16,11 +16,13 @@ scripts/examples/gn_build_example.sh examples/ota-requestor-app/linux out/debug In addition to the general options available to all Linux applications, the following command line options are available for the OTA Requestor application. +Note that these options are for testing purposes. | Command Line Option | Description | | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | -a, --autoApplyImage | If supplied, apply the image immediately after download. Otherwise, the OTA update is complete after image download. | | -c, --requestorCanConsent \ | Value for the RequestorCanConsent field in the QueryImage command. If not supplied, the value is determined by the driver. | +| -d, --disableNotifyUpdateApplied | If supplied, disable sending of the NotifyUpdateApplied command. Otherwise, after successfully loading into the updated image, send the NotifyUpdateApplied command. | | -f, --otaDownloadPath \ | If supplied, the OTA image is downloaded to the given fully-qualified file-path. Otherwise, the default location for the downloaded image is at /tmp/test.bin | | -p, --periodicQueryTimeout \