diff --git a/.github/workflows/bloat_check.yaml b/.github/workflows/bloat_check.yaml index 7ec2a6bf692011..43a3993eee6a91 100644 --- a/.github/workflows/bloat_check.yaml +++ b/.github/workflows/bloat_check.yaml @@ -34,7 +34,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 steps: - name: Checkout diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 210106ccc08e0c..92acd73acef165 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -43,7 +43,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" @@ -139,7 +139,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" @@ -205,14 +205,14 @@ jobs: esac rm -rf ./out/sanitizers - BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="$GN_ARGS" --export-compile-commands + BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="$GN_ARGS" --add-export-compile-commands=* BUILD_TYPE=sanitizers scripts/tests/gn_tests.sh done - name: Generate tests with sanitizers (for tidy) if: github.event.pull_request.number != null run: | rm -rf ./out/sanitizers - BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="is_clang=true is_asan=true" --export-compile-commands + BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="is_clang=true is_asan=true" --add-export-compile-commands=* - name: Ensure codegen is done for sanitize run: | ./scripts/run_in_build_env.sh "./scripts/run_codegen_targets.sh out/sanitizers" @@ -308,7 +308,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" @@ -371,7 +371,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" @@ -439,7 +439,7 @@ jobs: # We want to build various standalone example apps (similar to what examples-linux-standalone.yaml # does), so use target_os="all" to get those picked up as part of the "unified" build. But then # to save CI resources we want to exclude the "host clang" build, which uses the pigweed clang. - scripts/build/gn_gen.sh --args='target_os="all" is_asan=true enable_host_clang_build=false' --export-compile-commands + scripts/build/gn_gen.sh --args='target_os="all" is_asan=true enable_host_clang_build=false' --add-export-compile-commands=* scripts/run_in_build_env.sh "ninja -C ./out/$BUILD_TYPE" scripts/tests/gn_tests.sh - name: Ensure codegen is done for default @@ -490,7 +490,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/chef.yaml b/.github/workflows/chef.yaml index a1e5907cb91a70..d7360f6cc4876d 100644 --- a/.github/workflows/chef.yaml +++ b/.github/workflows/chef.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 options: --user root steps: @@ -57,7 +57,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-esp32:81 + image: ghcr.io/project-chip/chip-build-esp32:90 options: --user root steps: @@ -78,7 +78,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nrf-platform:81 + image: ghcr.io/project-chip/chip-build-nrf-platform:90 options: --user root steps: @@ -99,7 +99,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-telink:81 + image: ghcr.io/project-chip/chip-build-telink:90 options: --user root steps: @@ -111,7 +111,7 @@ jobs: platform: telink # - name: Update Zephyr to specific revision (for developers purpose) # shell: bash - # run: scripts/run_in_build_env.sh "python3 scripts/tools/telink/update_zephyr.py 3ed7686a9378de6be1368c912f9a42f998bbfb18" + # run: scripts/run_in_build_env.sh "python3 scripts/tools/telink/update_zephyr.py f762f1a1027284e63e338e6d83deeade62f355b0" - name: CI Examples Telink shell: bash run: | diff --git a/.github/workflows/doxygen.yaml b/.github/workflows/doxygen.yaml index 9dc5bbab1ac574..e345ff2a75a70e 100644 --- a/.github/workflows/doxygen.yaml +++ b/.github/workflows/doxygen.yaml @@ -84,7 +84,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-doxygen:81 + image: ghcr.io/project-chip/chip-build-doxygen:90 if: github.actor != 'restyled-io[bot]' diff --git a/.github/workflows/examples-ameba.yaml b/.github/workflows/examples-ameba.yaml index 1c87787cf67ecc..a4b40a19339507 100644 --- a/.github/workflows/examples-ameba.yaml +++ b/.github/workflows/examples-ameba.yaml @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-ameba:81 + image: ghcr.io/project-chip/chip-build-ameba:90 options: --user root steps: diff --git a/.github/workflows/examples-asr.yaml b/.github/workflows/examples-asr.yaml index 7597ef1783eea4..143ce3364fafad 100644 --- a/.github/workflows/examples-asr.yaml +++ b/.github/workflows/examples-asr.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-asr:81 + image: ghcr.io/project-chip/chip-build-asr:90 options: --user root steps: diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index 9a51b612a18a7c..2e9cf4a8849edd 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-bouffalolab:81 + image: ghcr.io/project-chip/chip-build-bouffalolab:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-cc13xx_26xx.yaml b/.github/workflows/examples-cc13xx_26xx.yaml index 31988e66385236..097a7d103eac95 100644 --- a/.github/workflows/examples-cc13xx_26xx.yaml +++ b/.github/workflows/examples-cc13xx_26xx.yaml @@ -42,7 +42,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-ti:81 + image: ghcr.io/project-chip/chip-build-ti:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-cc32xx.yaml b/.github/workflows/examples-cc32xx.yaml index 24edcb3fa92603..25afa79903f12d 100644 --- a/.github/workflows/examples-cc32xx.yaml +++ b/.github/workflows/examples-cc32xx.yaml @@ -41,7 +41,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-ti:81 + image: ghcr.io/project-chip/chip-build-ti:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-efr32.yaml b/.github/workflows/examples-efr32.yaml index ab85bc1f6c9cdf..dd9fb120a365b2 100644 --- a/.github/workflows/examples-efr32.yaml +++ b/.github/workflows/examples-efr32.yaml @@ -41,7 +41,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-efr32:89 + image: ghcr.io/project-chip/chip-build-efr32:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-esp32.yaml b/.github/workflows/examples-esp32.yaml index b3a6ed24e66568..9853c0df51885d 100644 --- a/.github/workflows/examples-esp32.yaml +++ b/.github/workflows/examples-esp32.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-esp32:81 + image: ghcr.io/project-chip/chip-build-esp32:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -124,7 +124,7 @@ jobs: if: github.actor != 'restyled-io[bot]' && github.repository_owner == 'espressif' container: - image: ghcr.io/project-chip/chip-build-esp32:81 + image: ghcr.io/project-chip/chip-build-esp32:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-infineon.yaml b/.github/workflows/examples-infineon.yaml index ada44f1557baaf..49c2097cd696e8 100644 --- a/.github/workflows/examples-infineon.yaml +++ b/.github/workflows/examples-infineon.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-infineon:81 + image: ghcr.io/project-chip/chip-build-infineon:90 env: # TODO: this should probably be part of the dockerfile itself CY_TOOLS_PATHS: /opt/Tools/ModusToolbox/tools_3.2 diff --git a/.github/workflows/examples-linux-arm.yaml b/.github/workflows/examples-linux-arm.yaml index 5aeeb4d5494c4d..46c2173530c6be 100644 --- a/.github/workflows/examples-linux-arm.yaml +++ b/.github/workflows/examples-linux-arm.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-crosscompile:81 + image: ghcr.io/project-chip/chip-build-crosscompile:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-linux-imx.yaml b/.github/workflows/examples-linux-imx.yaml index d2f1014eb576cf..e1d64f7a058f1e 100644 --- a/.github/workflows/examples-linux-imx.yaml +++ b/.github/workflows/examples-linux-imx.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-imx:81 + image: ghcr.io/project-chip/chip-build-imx:90 steps: - name: Checkout diff --git a/.github/workflows/examples-linux-standalone.yaml b/.github/workflows/examples-linux-standalone.yaml index 2bed5acd82f040..8c483cacd45651 100644 --- a/.github/workflows/examples-linux-standalone.yaml +++ b/.github/workflows/examples-linux-standalone.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-linux-tv-casting-app.yaml b/.github/workflows/examples-linux-tv-casting-app.yaml index 31275c78501f5c..14bfb6fb91b17c 100644 --- a/.github/workflows/examples-linux-tv-casting-app.yaml +++ b/.github/workflows/examples-linux-tv-casting-app.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 steps: - name: Checkout diff --git a/.github/workflows/examples-mw320.yaml b/.github/workflows/examples-mw320.yaml index 8f76321a0c0242..077bdbbfb7f2b6 100644 --- a/.github/workflows/examples-mw320.yaml +++ b/.github/workflows/examples-mw320.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-nrfconnect.yaml b/.github/workflows/examples-nrfconnect.yaml index d781087fc84760..0db5e82e81d8e4 100644 --- a/.github/workflows/examples-nrfconnect.yaml +++ b/.github/workflows/examples-nrfconnect.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nrf-platform:81 + image: ghcr.io/project-chip/chip-build-nrf-platform:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-nuttx.yaml b/.github/workflows/examples-nuttx.yaml index f1f682e00898f6..cccfa44557a4ba 100644 --- a/.github/workflows/examples-nuttx.yaml +++ b/.github/workflows/examples-nuttx.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nuttx:81 + image: ghcr.io/project-chip/chip-build-nuttx:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-nxp.yaml b/.github/workflows/examples-nxp.yaml index f9c6392bdc71ed..aa782544d2ae1d 100644 --- a/.github/workflows/examples-nxp.yaml +++ b/.github/workflows/examples-nxp.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nxp:81 + image: ghcr.io/project-chip/chip-build-nxp:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: @@ -240,7 +240,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nxp-zephyr:81 + image: ghcr.io/project-chip/chip-build-nxp-zephyr:90 steps: - name: Checkout diff --git a/.github/workflows/examples-openiotsdk.yaml b/.github/workflows/examples-openiotsdk.yaml index 95389cb157f5ee..2d59643eeb3aac 100644 --- a/.github/workflows/examples-openiotsdk.yaml +++ b/.github/workflows/examples-openiotsdk.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-openiotsdk:81 + image: ghcr.io/project-chip/chip-build-openiotsdk:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" options: --privileged diff --git a/.github/workflows/examples-qpg.yaml b/.github/workflows/examples-qpg.yaml index 312c49329283cd..3287b281dc77ef 100644 --- a/.github/workflows/examples-qpg.yaml +++ b/.github/workflows/examples-qpg.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-stm32.yaml b/.github/workflows/examples-stm32.yaml index 2e8f8576735bfe..d10c91a8e8ca6d 100644 --- a/.github/workflows/examples-stm32.yaml +++ b/.github/workflows/examples-stm32.yaml @@ -41,7 +41,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-telink.yaml b/.github/workflows/examples-telink.yaml index a1d7244ab8f02f..6c8b9bd5217f32 100644 --- a/.github/workflows/examples-telink.yaml +++ b/.github/workflows/examples-telink.yaml @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-telink:81 + image: ghcr.io/project-chip/chip-build-telink:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -58,7 +58,7 @@ jobs: gh-context: ${{ toJson(github) }} # - name: Update Zephyr to specific revision (for developers purpose) - # run: scripts/run_in_build_env.sh "python3 scripts/tools/telink/update_zephyr.py 3ed7686a9378de6be1368c912f9a42f998bbfb18" + # run: scripts/run_in_build_env.sh "python3 scripts/tools/telink/update_zephyr.py f762f1a1027284e63e338e6d83deeade62f355b0" - name: Build example Telink (B92 retention) Air Quality Sensor App # Run test for master and s07641069 PRs @@ -167,14 +167,14 @@ jobs: - name: clean out build output (keep tools) run: rm -rf ./out/telink* - - name: Build example Telink (B92) Light Switch App with OTA, Shell, Factory Data + - name: Build example Telink (B92) Light Switch App with OTA (LZMA), Shell, Factory Data # Run test for master and all PRs run: | ./scripts/run_in_build_env.sh \ - "./scripts/build/build_examples.py --target 'telink-tlsr9528a-light-switch-ota-shell-factory-data' build" + "./scripts/build/build_examples.py --target 'telink-tlsr9528a-light-switch-ota-compress-lzma-shell-factory-data' build" .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - telink tlsr9528a light-switch-app-ota-shell-factory-data \ - out/telink-tlsr9528a-light-switch-ota-shell-factory-data/zephyr/zephyr.elf \ + telink tlsr9528a light-switch-app-ota-compress-lzma-shell-factory-data \ + out/telink-tlsr9528a-light-switch-ota-compress-lzma-shell-factory-data/zephyr/zephyr.elf \ /tmp/bloat_reports/ - name: clean out build output diff --git a/.github/workflows/examples-tizen.yaml b/.github/workflows/examples-tizen.yaml index f0e4dfb3a206dd..f465f3999f0f26 100644 --- a/.github/workflows/examples-tizen.yaml +++ b/.github/workflows/examples-tizen.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-tizen:81 + image: ghcr.io/project-chip/chip-build-tizen:90 options: --user root volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/full-android.yaml b/.github/workflows/full-android.yaml index c3871ad8815152..6acc150c03a111 100644 --- a/.github/workflows/full-android.yaml +++ b/.github/workflows/full-android.yaml @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-android:81 + image: ghcr.io/project-chip/chip-build-android:90 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/fuzzing-build.yaml b/.github/workflows/fuzzing-build.yaml index c37ca98e1a513e..f36b370448fa66 100644 --- a/.github/workflows/fuzzing-build.yaml +++ b/.github/workflows/fuzzing-build.yaml @@ -33,7 +33,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/java-tests.yaml b/.github/workflows/java-tests.yaml index abf2e75027b489..f416be3a4d2998 100644 --- a/.github/workflows/java-tests.yaml +++ b/.github/workflows/java-tests.yaml @@ -43,7 +43,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-java:81 + image: ghcr.io/project-chip/chip-build-java:90 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 2471529f4170fb..590a2595ee6f96 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 steps: - name: Checkout diff --git a/.github/workflows/minimal-build.yaml b/.github/workflows/minimal-build.yaml index dae8a2b8ce0a7f..da55158cc7c57f 100644 --- a/.github/workflows/minimal-build.yaml +++ b/.github/workflows/minimal-build.yaml @@ -34,7 +34,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-minimal:81 + image: ghcr.io/project-chip/chip-build-minimal:90 steps: - name: Checkout @@ -56,7 +56,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-minimal:81 + image: ghcr.io/project-chip/chip-build-minimal:90 steps: - name: Checkout diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index 5f9bbe7022826d..07b31eec0ddb11 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -41,7 +41,7 @@ jobs: if: github.actor != 'restyled-io[bot]' && github.repository_owner == 'espressif' container: - image: ghcr.io/project-chip/chip-build-esp32-qemu:81 + image: ghcr.io/project-chip/chip-build-esp32-qemu:90 volumes: - "/tmp/log_output:/tmp/test_logs" @@ -79,7 +79,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-tizen-qemu:81 + image: ghcr.io/project-chip/chip-build-tizen-qemu:90 options: --user root volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/release_artifacts.yaml b/.github/workflows/release_artifacts.yaml index 54997b6efa9b39..14b2c327452194 100644 --- a/.github/workflows/release_artifacts.yaml +++ b/.github/workflows/release_artifacts.yaml @@ -32,7 +32,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-esp32:81 + image: ghcr.io/project-chip/chip-build-esp32:90 steps: - name: Checkout @@ -64,7 +64,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-efr32:85 + image: ghcr.io/project-chip/chip-build-efr32:90 steps: - name: Checkout uses: actions/checkout@v4 diff --git a/.github/workflows/smoketest-android.yaml b/.github/workflows/smoketest-android.yaml index 7d0e124ca5656b..38a614e71246f5 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: ghcr.io/project-chip/chip-build-android:81 + image: ghcr.io/project-chip/chip-build-android:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 77c31b8be7212e..9a31e56ca8ef54 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -50,7 +50,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" @@ -457,7 +457,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" @@ -494,7 +494,7 @@ jobs: --target linux-x64-microwave-oven-ipv6only-no-ble-no-wifi-tsan-clang-test \ --target linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test \ --target linux-x64-network-manager-ipv6only-no-ble-no-wifi-tsan-clang-test \ - --target linux-x64-fabric-admin-rpc-ipv6only-clang \ + --target linux-x64-fabric-admin-rpc-ipv6only-no-ble-no-wifi-clang \ --target linux-x64-fabric-bridge-rpc-ipv6only-no-ble-no-wifi-clang \ --target linux-x64-light-data-model-no-unique-id-ipv6only-no-ble-no-wifi-clang \ --target linux-x64-python-bindings \ @@ -511,7 +511,7 @@ jobs: echo "CHIP_MICROWAVE_OVEN_APP: out/linux-x64-microwave-oven-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-microwave-oven-app" >> /tmp/test_env.yaml echo "CHIP_RVC_APP: out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app" >> /tmp/test_env.yaml echo "NETWORK_MANAGEMENT_APP: out/linux-x64-network-manager-ipv6only-no-ble-no-wifi-tsan-clang-test/matter-network-manager-app" >> /tmp/test_env.yaml - echo "FABRIC_ADMIN_APP: out/linux-x64-fabric-admin-rpc-ipv6only-clang/fabric-admin" >> /tmp/test_env.yaml + echo "FABRIC_ADMIN_APP: out/linux-x64-fabric-admin-rpc-ipv6only-no-ble-no-wifi-clang/fabric-admin" >> /tmp/test_env.yaml echo "FABRIC_BRIDGE_APP: out/linux-x64-fabric-bridge-rpc-ipv6only-no-ble-no-wifi-clang/fabric-bridge-app" >> /tmp/test_env.yaml echo "LIGHTING_APP_NO_UNIQUE_ID: out/linux-x64-light-data-model-no-unique-id-ipv6only-no-ble-no-wifi-clang/chip-lighting-app" >> /tmp/test_env.yaml echo "TRACE_APP: out/trace_data/app-{SCRIPT_BASE_NAME}" >> /tmp/test_env.yaml diff --git a/.github/workflows/unit_integration_test.yaml b/.github/workflows/unit_integration_test.yaml index 1cc021375d7b1c..b2fc345bda1a9d 100644 --- a/.github/workflows/unit_integration_test.yaml +++ b/.github/workflows/unit_integration_test.yaml @@ -40,7 +40,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/zap_regeneration.yaml b/.github/workflows/zap_regeneration.yaml index 483b9486d1bdc6..0d6d9b6db70ca8 100644 --- a/.github/workflows/zap_regeneration.yaml +++ b/.github/workflows/zap_regeneration.yaml @@ -30,7 +30,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 defaults: run: shell: sh diff --git a/.github/workflows/zap_templates.yaml b/.github/workflows/zap_templates.yaml index 383a98583bd9fc..c4edd57421ba6f 100644 --- a/.github/workflows/zap_templates.yaml +++ b/.github/workflows/zap_templates.yaml @@ -35,7 +35,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 defaults: run: shell: sh diff --git a/.gn b/.gn index f844fd20e9b87d..ebd301ee7cf8cd 100644 --- a/.gn +++ b/.gn @@ -35,8 +35,8 @@ default_args = { # Required for pw_unit_test pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" - pw_assert_BACKEND = "$dir_pw_assert_log" - pw_log_BACKEND = "$dir_pw_log_basic" + pw_assert_BACKEND = "//src/pw_backends/assert" + pw_log_BACKEND = "//src/pw_backends/log" # TODO: Make sure only unit tests link against this pw_build_LINK_DEPS = [ diff --git a/.vscode/launch.json b/.vscode/launch.json index fc821c76eb802c..97ba95d77f0bad 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -34,6 +34,25 @@ "args": [], "cwd": "${workspaceFolder}" }, + + { + "name": "Run pw FuzzTest (Linux x64) UnitTest Mode", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceFolder}/out/${input:outPWFuzzTestLinux}", + "cwd": "${workspaceFolder}" + }, + + { + "name": "Run pw FuzzTest (Linux x64) Continuous Fuzzing Mode", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceFolder}/out/${input:outPWFuzzTestLinux}", + "args": ["-fuzz=${input:fuzzTestName}"], + "cwd": "${workspaceFolder}", + "preLaunchTask": "" + }, + { "name": "QRCode Tests", "type": "cppdbg", @@ -528,6 +547,24 @@ "description": "Select the test to run" } }, + { + "type": "command", + "id": "outPWFuzzTestLinux", + "command": "shellCommand.execute", + "args": { + "command": "find ${workspaceFolder}/out/linux-x64-*/chip_pw_fuzztest/tests -type f -executable |sort |sed 's$${workspaceFolder}/out/$$'", + "description": "Select the FuzzTest to run" + } + }, + { + "id": "fuzzTestName", + "type": "command", + "command": "shellCommand.execute", + "args": { + "command": "./out/${input:outPWFuzzTestLinux} --list_fuzz_tests | grep 'Fuzz test:' | awk -F ': ' '{print $2}'", + "description": "Select the specific FuzzTest to fuzz continuously" + } + }, { "type": "pickString", "id": "mbedDebugProfile", diff --git a/config/bouffalolab/common/lib/pw_rpc/pw_rpc.gni b/config/bouffalolab/common/lib/pw_rpc/pw_rpc.gni index 2cfbc034e875eb..86c20ccc72cdc8 100644 --- a/config/bouffalolab/common/lib/pw_rpc/pw_rpc.gni +++ b/config/bouffalolab/common/lib/pw_rpc/pw_rpc.gni @@ -15,8 +15,8 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "${chip_root}/examples/platform/bouffalolab/common/rpc/pw_sys_io:pw_sys_io" diff --git a/config/efr32/lib/pw_rpc/pw_rpc.gni b/config/efr32/lib/pw_rpc/pw_rpc.gni index 101112c12dadc9..ac5e3831da388d 100644 --- a/config/efr32/lib/pw_rpc/pw_rpc.gni +++ b/config/efr32/lib/pw_rpc/pw_rpc.gni @@ -15,8 +15,8 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" pw_sys_io_BACKEND = "${chip_root}/examples/platform/silabs/pw_sys_io:pw_sys_io_silabs" diff --git a/config/esp32/components/chip/CMakeLists.txt b/config/esp32/components/chip/CMakeLists.txt index ddf4d72ff8691b..40f5c0cea2936d 100644 --- a/config/esp32/components/chip/CMakeLists.txt +++ b/config/esp32/components/chip/CMakeLists.txt @@ -310,6 +310,10 @@ if (CONFIG_ENABLE_ESP_INSIGHTS_TRACE) target_include_directories(${COMPONENT_LIB} INTERFACE "${CHIP_ROOT}/src/tracing/esp32_trace/include") endif() +if (CONFIG_CHIP_DEVICE_ENABLE_DYNAMIC_SERVER) + chip_gn_arg_append("chip_build_controller_dynamic_server" "true") +endif() + set(args_gn_input "${CMAKE_CURRENT_BINARY_DIR}/args.gn.in") file(GENERATE OUTPUT "${args_gn_input}" CONTENT "${chip_gn_args}") @@ -428,6 +432,8 @@ if(CONFIG_BT_ENABLED) idf_component_get_property(bt_dir bt COMPONENT_DIR) list(APPEND chip_libraries $) list(APPEND chip_libraries "${bt_dir}/controller/lib_${target_name}/${target_name}-bt-lib/libble_app.a") + elseif(target_name STREQUAL "esp32p4") + list(APPEND chip_libraries $) else() list(APPEND chip_libraries $ -lbtdm_app) endif() @@ -506,11 +512,13 @@ endif() idf_component_get_property(lwip_lib lwip COMPONENT_LIB) list(APPEND chip_libraries $) +if ("${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}" VERSION_GREATER_EQUAL "5.3" OR CONFIG_ESP32_WIFI_ENABLED) + idf_component_get_property(esp_wifi_lib esp_wifi COMPONENT_LIB) + list(APPEND chip_libraries $) +endif() if (CONFIG_ESP32_WIFI_ENABLED) - idf_component_get_property(esp_wifi_lib esp_wifi COMPONENT_LIB) idf_component_get_property(esp_wifi_dir esp_wifi COMPONENT_DIR) - list(APPEND chip_libraries $) if (CONFIG_IDF_TARGET_ESP32C2) set(blobs core net80211 pp) else() @@ -536,6 +544,7 @@ list(APPEND chip_libraries $) idf_component_get_property(esp_hw_support_lib esp_hw_support COMPONENT_LIB) list(APPEND chip_libraries $) +if (NOT CONFIG_IDF_TARGET_ESP32P4) idf_component_get_property(esp_phy_lib esp_phy COMPONENT_LIB) idf_component_get_property(esp_phy_dir esp_phy COMPONENT_DIR) list(APPEND chip_libraries $) @@ -550,8 +559,12 @@ endif() foreach(phy_blob ${phy_blobs}) list(APPEND chip_libraries "${esp_phy_dir}/lib/${target_name}/lib${phy_blob}.a") endforeach() +endif() -set(components_to_link esp_event hal esp_system soc efuse vfs driver esp_coex freertos esp_timer) +set(components_to_link esp_event hal esp_system soc efuse vfs driver freertos esp_timer) +if (NOT CONFIG_IDF_TARGET_ESP32P4) +list(APPEND components_to_link esp_coex) +endif() idf_build_get_property(build_components BUILD_COMPONENTS) foreach(component ${components_to_link}) # Some of the components are not present in IDF v4.x diff --git a/config/esp32/components/chip/Kconfig b/config/esp32/components/chip/Kconfig index c61ac770a608ff..2d8127900eed69 100644 --- a/config/esp32/components/chip/Kconfig +++ b/config/esp32/components/chip/Kconfig @@ -37,16 +37,6 @@ menu "CHIP Core" exchange (conversation) with a peer, e.g. a cloud service, a mobile application, or another device. - config MAX_BINDINGS - int "Max Bindings" - range 0 65535 - default 8 - help - The maximum number of simultaneously active CHIP Binding objects. - - A Binding object is used to configure how the local device communicates with - a remote entity, be it a cloud service, a mobile application, or another device. - config MAX_FABRICS int "Max Fabrics" range 5 255 @@ -203,6 +193,13 @@ menu "CHIP Core" help Specifies the maximum number of group key sets supported per fabric. + config CHIP_DEVICE_ENABLE_DYNAMIC_SERVER + bool "Enable dynamic server" + default n + help + Enable dynamic server to handle a different interaction model dispatch. + Can be implied when users do not want to use the same server clusters. + endmenu # "General Options" menu "Networking Options" diff --git a/config/esp32/components/chip/idf_component.yml b/config/esp32/components/chip/idf_component.yml index 2e7415827ff264..78d21af787c631 100644 --- a/config/esp32/components/chip/idf_component.yml +++ b/config/esp32/components/chip/idf_component.yml @@ -18,7 +18,7 @@ dependencies: - if: "idf_version >=4.4" espressif/esp_insights: - version: "1.0.1" + version: "1.2.2" require: public # There is an issue with IDF-Component-Manager when ESP Insights is included. # Issue: https://github.com/project-chip/connectedhomeip/issues/29125 @@ -26,14 +26,6 @@ dependencies: - if: "idf_version >=5.0" - if: "target != esp32h2" - # This matches the dependency of esp_insights - espressif/esp_diag_data_store: - version: "1.0.1" - require: public - rules: - - if: "idf_version >=5.0" - - if: "target != esp32h2" - espressif/esp_rcp_update: version: "1.2.0" rules: @@ -44,3 +36,8 @@ dependencies: require: public rules: - if: "idf_version >=4.3" + + espressif/esp_wifi_remote: + version: ">=0.1.12" + rules: + - if: "target in [esp32p4]" diff --git a/config/mbed/chip-gn/lib/pw_rpc/pw_rpc.gni b/config/mbed/chip-gn/lib/pw_rpc/pw_rpc.gni index 2b03f6b4c9958c..50ef9977fa54db 100644 --- a/config/mbed/chip-gn/lib/pw_rpc/pw_rpc.gni +++ b/config/mbed/chip-gn/lib/pw_rpc/pw_rpc.gni @@ -15,8 +15,8 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "${chip_root}/examples/platform/mbed/pw_sys_io:pw_sys_io_mbed" pw_rpc_system_server_BACKEND = diff --git a/config/nxp/lib/pw_rpc/pw_rpc.gni b/config/nxp/lib/pw_rpc/pw_rpc.gni index 68255db8bb96da..f91c53cf354da3 100644 --- a/config/nxp/lib/pw_rpc/pw_rpc.gni +++ b/config/nxp/lib/pw_rpc/pw_rpc.gni @@ -15,8 +15,8 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" pw_sys_io_BACKEND = "${chip_root}/examples/platform/nxp/pw_sys_io:pw_sys_io_nxp" diff --git a/config/qpg/chip-gn/build.sh b/config/qpg/chip-gn/build.sh index 541da2625253eb..974caaaf0ac2f9 100755 --- a/config/qpg/chip-gn/build.sh +++ b/config/qpg/chip-gn/build.sh @@ -31,7 +31,7 @@ gn \ --root-target=//config/qpg/chip-gn \ --dotfile="$GN_ROOT_TARGET/.gn" \ --script-executable=python3 \ - --export-compile-commands \ + --add-export-compile-commands="*" \ gen \ --check \ --args="$GN_ARGS" \ diff --git a/config/qpg/lib/pw_rpc/pw_rpc.gni b/config/qpg/lib/pw_rpc/pw_rpc.gni index 60fb93e6b8fc44..8e282c3bf053f2 100644 --- a/config/qpg/lib/pw_rpc/pw_rpc.gni +++ b/config/qpg/lib/pw_rpc/pw_rpc.gni @@ -15,8 +15,8 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "${chip_root}/examples/platform/qpg/pw_sys_io:pw_sys_io_qpg" pw_build_LINK_DEPS = [ diff --git a/config/telink/app/bootloader.conf b/config/telink/app/bootloader.conf index 52937e1649e9af..0ffacc8c0b052b 100644 --- a/config/telink/app/bootloader.conf +++ b/config/telink/app/bootloader.conf @@ -30,7 +30,8 @@ CONFIG_BOOT_SWAP_USING_SCRATCH=n CONFIG_BOOT_VALIDATE_SLOT0=y # Maximum number of image sectors supported by the bootloader. -CONFIG_BOOT_MAX_IMG_SECTORS=4096 +# Maximum signed image size: 512 * 4096 = 2M Bytes +CONFIG_BOOT_MAX_IMG_SECTORS=512 # Sets log level for modules which don't specify it explicitly. # When set to 0 it means log will not be activated for those modules. @@ -40,4 +41,4 @@ CONFIG_BOOT_MAX_IMG_SECTORS=4096 # - 2 WARNING, default to write LOG_LEVEL_WRN # - 3 INFO, default to write LOG_LEVEL_INFO # - 4 DEBUG, default to write LOG_LEVEL_DBG -CONFIG_LOG_DEFAULT_LEVEL=1 +CONFIG_LOG_DEFAULT_LEVEL=3 diff --git a/config/telink/app/bootloader_compress_lzma.conf b/config/telink/app/bootloader_compress_lzma.conf new file mode 100644 index 00000000000000..cb349eed0ce387 --- /dev/null +++ b/config/telink/app/bootloader_compress_lzma.conf @@ -0,0 +1,46 @@ +# +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# Enable overwrite the primary slot with the upgrade image instead of swapping them. +# This prevents the fallback recovery. +CONFIG_BOOT_UPGRADE_ONLY=y + +# Enable this option in case if the whole slot0 image need to be validated +# With disabled option the only image magic is validated +CONFIG_BOOT_VALIDATE_SLOT0=y + +# Maximum number of image sectors supported by the bootloader. +# Maximum signed image size: 512 * 4096 = 2M Bytes +CONFIG_BOOT_MAX_IMG_SECTORS=512 + +# Sets log level for modules which don't specify it explicitly. +# When set to 0 it means log will not be activated for those modules. +# Levels are: +# - 0 OFF, do not write by default +# - 1 ERROR, default to only write LOG_LEVEL_ERR +# - 2 WARNING, default to write LOG_LEVEL_WRN +# - 3 INFO, default to write LOG_LEVEL_INFO +# - 4 DEBUG, default to write LOG_LEVEL_DBG +CONFIG_LOG_DEFAULT_LEVEL=3 + +# LZMA used sys_heap based allocators +CONFIG_COMMON_LIBC_MALLOC_ARENA_SIZE=78000 + +# Enable build size optimizations +CONFIG_SIZE_OPTIMIZATIONS=y + +# Enable support LZMA compression +CONFIG_COMPRESS_LZMA=y diff --git a/config/telink/chip-module/CMakeLists.txt b/config/telink/chip-module/CMakeLists.txt index 7490cc497079cd..ade2bd310f8a02 100644 --- a/config/telink/chip-module/CMakeLists.txt +++ b/config/telink/chip-module/CMakeLists.txt @@ -155,6 +155,10 @@ set_property(GLOBAL APPEND PROPERTY ZEPHYR_INTERFACE_LIBS chip) include(${TELINK_COMMON}/common.cmake) +if (CONFIG_CHIP_APP_LOG_LEVEL GREATER_EQUAL 4) + include(${TELINK_COMMON}/build_info.cmake) +endif() + # ============================================================================== # Define 'process_binaries' target for collecting final binary to flash # ============================================================================== @@ -185,8 +189,17 @@ endif() # ============================================================================== if (CONFIG_CHIP_OTA_IMAGE_BUILD) + if (CONFIG_COMPRESS_LZMA) + add_custom_command( + OUTPUT ${PROJECT_BINARY_DIR}/${CONFIG_SIGNED_OTA_IMAGE_FILE_NAME} + COMMAND ${CMAKE_COMMAND} -E true + COMMENT "Fake command, ${CONFIG_SIGNED_OTA_IMAGE_FILE_NAME} file created in process_binaries target" + DEPENDS ${ZEPHYR_FINAL_EXECUTABLE} + ) + endif() + chip_ota_image(chip-ota-image - INPUT_FILES ${PROJECT_BINARY_DIR}/zephyr.signed.bin + INPUT_FILES ${PROJECT_BINARY_DIR}/${CONFIG_SIGNED_OTA_IMAGE_FILE_NAME} OUTPUT_FILE ${PROJECT_BINARY_DIR}/${CONFIG_CHIP_OTA_IMAGE_FILE_NAME} ) add_dependencies(chip-ota-image process_binaries) diff --git a/config/telink/chip-module/Kconfig b/config/telink/chip-module/Kconfig index 7d9296bed5dfcc..b06c7c855922d8 100644 --- a/config/telink/chip-module/Kconfig +++ b/config/telink/chip-module/Kconfig @@ -71,6 +71,27 @@ config CHIP_OTA_IMAGE_BUILD bool default y if CHIP_OTA_REQUESTOR +config SIGNED_OTA_IMAGE_FILE_NAME + string "Zephyr signed image file name" + default "zephyr.signed.lzma.signed.bin" if COMPRESS_LZMA + default "zephyr.signed.bin" + depends on CHIP_OTA_REQUESTOR + help + Provides the file name of the generated Zephyr signed image. + +config TELINK_OTA_BUTTON_TEST + bool "Enable image update initiation via button press" + default n + depends on CHIP_OTA_REQUESTOR + help + Merge the signed binary with the same version as the main into slot-1 of merged.hex. + Pressing the button initiates a forced image update. + +config TELINK_OTA_PARTITION_ADDR + hex "image-1 partition address" + default $(dt_node_reg_addr_hex,$(dt_nodelabel_path,slot1_partition),0) + depends on TELINK_OTA_BUTTON_TEST + config CHIP_ROTATING_DEVICE_ID bool "Generate rotating device ID" default y @@ -225,6 +246,7 @@ config CHIP_ENABLE_POWER_ON_FACTORY_RESET config CHIP_TASK_STACK_SIZE int + default 4864 if PM default 8192 config CHIP_USE_MARS_SENSOR diff --git a/config/telink/chip-module/Kconfig.defaults b/config/telink/chip-module/Kconfig.defaults index d28d77d6cffd32..bb722e8a3ab8bc 100644 --- a/config/telink/chip-module/Kconfig.defaults +++ b/config/telink/chip-module/Kconfig.defaults @@ -71,7 +71,7 @@ config IDLE_STACK_SIZE default 512 if PM config ISR_STACK_SIZE - default 502 if PM + default 576 if PM config SYSTEM_WORKQUEUE_STACK_SIZE default 616 if PM @@ -154,7 +154,7 @@ config BT_DEVICE_NAME_GATT_WRITABLE default n config B9X_BLE_CTRL_THREAD_STACK_SIZE - default 576 + default 648 config B9X_BLE_CTRL_MASTER_MAX_NUM default 0 @@ -261,10 +261,10 @@ config CHIP_ENABLE_ICD_SUPPORT default y if CHIP_THREAD_DEVICE_ROLE_SLEEPY_END_DEVICE config OPENTHREAD_THREAD_STACK_SIZE - default 2178 if PM + default 2400 if PM config OPENTHREAD_RADIO_WORKQUEUE_STACK_SIZE - default 361 if PM + default 432 if PM default 608 config OPENTHREAD_SLAAC @@ -366,6 +366,9 @@ config CHIP_WIFI_CONNECTION_RECOVERY_JITTER a random jitter interval is added to it to avoid periodicity. The random jitter is selected within range [-JITTER; +JITTER]. +config NET_MGMT_EVENT_STACK_SIZE + default 1128 + endif # CHIP_WIFI config CHIP_ENABLE_PAIRING_AUTOSTART @@ -448,7 +451,17 @@ config PWM_SHELL config OPENTHREAD_SHELL default n -config CHIP_TASK_STACK_SIZE - default 4864 if PM +# Thread analyzer +config THREAD_ANALYZER + default n + select THREAD_ANALYZER_AUTO + +config THREAD_ANALYZER_AUTO_INTERVAL + default 5 + depends on THREAD_ANALYZER_AUTO + +config THREAD_ANALYZER_LOG_LEVEL + default 3 # info + depends on THREAD_ANALYZER endif diff --git a/credentials/generate-revocation-set.py b/credentials/generate-revocation-set.py index e0d0cb611fa072..4cdcfdbad1ae26 100644 --- a/credentials/generate-revocation-set.py +++ b/credentials/generate-revocation-set.py @@ -26,6 +26,7 @@ import subprocess import sys from enum import Enum +from typing import Optional import click import requests @@ -91,6 +92,112 @@ def parse_vid_pid_from_distinguished_name(distinguished_name): return vid, pid +def get_akid(cert: x509.Certificate) -> Optional[bytes]: + try: + return cert.extensions.get_extension_for_oid(x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier + except Exception: + logging.warning("AKID not found in certificate") + return None + + +def get_skid(cert: x509.Certificate) -> Optional[bytes]: + try: + return cert.extensions.get_extension_for_oid(x509.OID_SUBJECT_KEY_IDENTIFIER).value.key_identifier + except Exception: + logging.warning("SKID not found in certificate") + return None + + +def get_subject_b64(cert: x509.Certificate) -> str: + return base64.b64encode(cert.subject.public_bytes()).decode('utf-8') + + +def get_issuer_b64(cert: x509.Certificate) -> str: + return base64.b64encode(cert.issuer.public_bytes()).decode('utf-8') + + +def verify_cert(cert: x509.Certificate, root: x509.Certificate) -> bool: + ''' + Verifies if the cert is signed by root. + ''' + + cert_akid = get_akid(cert) + root_skid = get_skid(root) + if cert_akid is None or root_skid is None or cert_akid != root_skid: + return False + + if cert.issuer != root.subject: + return False + + # public_key().verify() do not return anything if signature is valid, + # will raise an exception if signature is invalid + try: + root.public_key().verify(cert.signature, cert.tbs_certificate_bytes, ec.ECDSA(cert.signature_hash_algorithm)) + except Exception: + logging.warning(f"Signature verification failed for cert subject: {get_subject_b64(cert)}, issuer: {get_issuer_b64(cert)}") + return False + + return True + + +def is_self_signed_certificate(cert: x509.Certificate) -> bool: + return verify_cert(cert, cert) + + +# delegator is optional so can be None, but crl_signer and paa has to be present +def validate_cert_chain(crl_signer: x509.Certificate, crl_signer_delegator: x509.Certificate, paa: x509.Certificate): + ''' + There could be four scenarios: + 1. CRL Signer is PAA itself, hence its self-signed certificate + 2. CRL Signer is PAI certificate, and we can validate (crl_signer -> paa) chain + 3. CRL Signer delegator is PAA, and we can validate (crl_signer -> crl_signer_delegator(paa) -> paa) chain + 4. CRL Signer delegator is PAI, and we can validate (crl_signer -> crl_signer_delegator -> paa) chain + ''' + + if crl_signer_delegator: + return verify_cert(crl_signer, crl_signer_delegator) and verify_cert(crl_signer_delegator, paa) + else: + return verify_cert(crl_signer, paa) + + +def validate_vid_pid(revocation_point: dict, crl_signer_certificate: x509.Certificate, crl_signer_delegator_certificate: x509.Certificate) -> bool: + crl_signer_vid, crl_signer_pid = parse_vid_pid_from_distinguished_name(crl_signer_certificate.subject) + + if revocation_point["isPAA"]: + if crl_signer_vid is not None: + if revocation_point["vid"] != crl_signer_vid: + logging.warning("VID in CRL Signer Certificate does not match with VID in revocation point, continue...") + return False + else: + vid_to_match = crl_signer_vid + pid_to_match = crl_signer_pid + + # if the CRL Signer is delegated then match the VID and PID of the CRL Signer Delegator + if crl_signer_delegator_certificate: + vid_to_match, pid_to_match = parse_vid_pid_from_distinguished_name(crl_signer_delegator_certificate.subject) + + if vid_to_match is None or revocation_point["vid"] != vid_to_match: + logging.warning("VID in CRL Signer Certificate does not match with VID in revocation point, continue...") + return False + + if pid_to_match is not None: + if revocation_point["pid"] != pid_to_match: + logging.warning("PID in CRL Signer Certificate does not match with PID in revocation point, continue...") + return False + + return True + + +def fetch_crl_from_url(url: str, timeout: int) -> x509.CertificateRevocationList: + logging.debug(f"Fetching CRL from {url}") + + try: + r = requests.get(url, timeout=timeout) + return x509.load_der_x509_crl(r.content) + except Exception: + logging.error('Failed to fetch a valid CRL') + + class DCLDClient: ''' A client for interacting with DCLD using either the REST API or command line interface (CLI). @@ -172,30 +279,50 @@ def get_revocation_points(self) -> list[dict]: return response["PkiRevocationDistributionPoint"] - def get_paa_cert_for_crl_issuer(self, crl_signer_issuer_name_b64, crl_signer_authority_key_id) -> str: + def get_issuer_cert(self, cert: x509.Certificate) -> Optional[x509.Certificate]: ''' - Get PAA certificate for CRL issuer + Get the issuer certificate for Parameters ---------- - crl_signer_issuer_name_b64: str - The issuer name of the CRL signer. - crl_signer_authority_key_id: str - The authority key ID of the CRL signer. + cert: x509.Certificate + Certificate Returns ------- str - PAA certificate in PEM format + Issuer certificate in PEM format ''' + issuer_name_b64 = get_issuer_b64(cert) + akid = get_akid(cert) + if akid is None: + return + + # Convert CRL Signer AKID to colon separated hex + akid_hex = akid.hex().upper() + akid_hex = ':'.join([akid_hex[i:i+2] for i in range(0, len(akid_hex), 2)]) + + logging.debug( + f"Fetching issuer from:{self.rest_node_url}/dcl/pki/certificates/{issuer_name_b64}/{akid_hex}") + if self.use_rest: response = requests.get( - f"{self.rest_node_url}/dcl/pki/certificates/{crl_signer_issuer_name_b64}/{crl_signer_authority_key_id}").json() + f"{self.rest_node_url}/dcl/pki/certificates/{issuer_name_b64}/{akid_hex}").json() else: response = self.get_dcld_cmd_output_json( - ['query', 'pki', 'x509-cert', '-u', crl_signer_issuer_name_b64, '-k', crl_signer_authority_key_id]) + ['query', 'pki', 'x509-cert', '-u', issuer_name_b64, '-k', akid_hex]) + + issuer_certificate = response["approvedCertificates"]["certs"][0]["pemCert"] + + logging.debug(f"issuer: {issuer_certificate}") - return response["approvedCertificates"]["certs"][0]["pemCert"] + try: + issuer_certificate_object = x509.load_pem_x509_certificate(bytes(issuer_certificate, 'utf-8')) + except Exception: + logging.error('Failed to parse PAA certificate') + return + + return issuer_certificate_object def get_revocations_points_by_skid(self, issuer_subject_key_id) -> list[dict]: ''' @@ -211,6 +338,7 @@ def get_revocations_points_by_skid(self, issuer_subject_key_id) -> list[dict]: list[dict] List of revocation points ''' + if self.use_rest: response = requests.get(f"{self.rest_node_url}/dcl/pki/revocation-points/{issuer_subject_key_id}").json() else: @@ -268,97 +396,55 @@ def main(use_main_net_dcld: str, use_test_net_dcld: str, use_main_net_http: bool continue # 2. Parse the certificate - crl_signer_certificate = x509.load_pem_x509_certificate(bytes(revocation_point["crlSignerCertificate"], 'utf-8')) - - vid = revocation_point["vid"] - pid = revocation_point["pid"] - is_paa = revocation_point["isPAA"] - - # 3. && 4. Validate VID/PID - crl_vid, crl_pid = parse_vid_pid_from_distinguished_name(crl_signer_certificate.subject) - - if is_paa: - if crl_vid is not None: - if vid != crl_vid: - logging.warning("VID is not CRL VID, continue...") - continue - else: - if crl_vid is None or vid != crl_vid: - logging.warning("VID is not CRL VID, continue...") - continue - if crl_pid is not None: - if pid != crl_pid: - logging.warning("PID is not CRL PID, continue...") - continue - - # 5. Validate the certification path containing CRLSignerCertificate. - crl_signer_issuer_name = base64.b64encode(crl_signer_certificate.issuer.public_bytes()).decode('utf-8') - - crl_signer_authority_key_id = crl_signer_certificate.extensions.get_extension_for_oid( - x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier - - # Convert CRL Signer AKID to colon separated hex - crl_signer_authority_key_id = crl_signer_authority_key_id.hex().upper() - crl_signer_authority_key_id = ':'.join([crl_signer_authority_key_id[i:i+2] - for i in range(0, len(crl_signer_authority_key_id), 2)]) - - paa_certificate = dcld_client.get_paa_cert_for_crl_issuer(crl_signer_issuer_name, crl_signer_authority_key_id) - - if paa_certificate is None: - logging.warning("PAA Certificate not found, continue...") + try: + crl_signer_certificate = x509.load_pem_x509_certificate(bytes(revocation_point["crlSignerCertificate"], 'utf-8')) + except Exception: + logging.warning("CRL Signer Certificate is not valid, continue...") continue - paa_certificate_object = x509.load_pem_x509_certificate(bytes(paa_certificate, 'utf-8')) + # Parse the crl signer delegator + crl_signer_delegator_cert = None + if "crlSignerDelegator" in revocation_point: + crl_signer_delegator_cert_pem = revocation_point["crlSignerDelegator"] + logging.debug(f"CRLSignerDelegator: {crl_signer_delegator_cert_pem}") + try: + crl_signer_delegator_cert = x509.load_pem_x509_certificate(bytes(crl_signer_delegator_cert_pem, 'utf-8')) + except Exception: + logging.warning("CRL Signer Delegator Certificate not found...") - # TODO: use verify_directly_issued_by() method when we upgrade cryptography to v40.0.0 - # Verify issuer matches with subject - if crl_signer_certificate.issuer != paa_certificate_object.subject: - logging.warning("CRL Signer Certificate issuer does not match with PAA Certificate subject, continue...") + # 3. and 4. Validate VID/PID + if not validate_vid_pid(revocation_point, crl_signer_certificate, crl_signer_delegator_cert): + logging.warning("Failed to validate VID/PID, continue...") continue - # Check crl signers AKID matches with SKID of paa_certificate_object's AKID - paa_skid = paa_certificate_object.extensions.get_extension_for_oid(x509.OID_SUBJECT_KEY_IDENTIFIER).value.key_identifier - crl_akid = crl_signer_certificate.extensions.get_extension_for_oid(x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier - if paa_skid != crl_akid: - logging.warning("CRL Signer's AKID does not match with PAA Certificate SKID, continue...") + # 5. Validate the certification path containing CRLSignerCertificate. + paa_certificate_object = dcld_client.get_issuer_cert(crl_signer_certificate) + if paa_certificate_object is None: + logging.warning("PAA Certificate not found, continue...") continue - # verify if PAA singed the crl signer certificate - try: - paa_certificate_object.public_key().verify(crl_signer_certificate.signature, - crl_signer_certificate.tbs_certificate_bytes, - ec.ECDSA(crl_signer_certificate.signature_hash_algorithm)) - except Exception: - logging.warning("CRL Signer Certificate is not signed by PAA Certificate, continue...") + if validate_cert_chain(crl_signer_certificate, crl_signer_delegator_cert, paa_certificate_object) is False: + logging.warning("Failed to validate CRL Signer Certificate chain, continue...") continue # 6. Obtain the CRL - logging.debug(f"Fetching CRL from {revocation_point['dataURL']}") - try: - r = requests.get(revocation_point["dataURL"], timeout=5) - except Exception: - logging.error('Failed to fetch CRL') - continue - - try: - crl_file = x509.load_der_x509_crl(r.content) - except Exception: - logging.error('Failed to load CRL') + crl_file = fetch_crl_from_url(revocation_point["dataURL"], 5) # timeout in seconds + if crl_file is None: continue # 7. Perform CRL File Validation - crl_authority_key_id = crl_file.extensions.get_extension_for_oid(x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier - crl_signer_subject_key_id = crl_signer_certificate.extensions.get_extension_for_oid( - x509.OID_SUBJECT_KEY_IDENTIFIER).value.key_identifier - if crl_authority_key_id != crl_signer_subject_key_id: - logging.warning("CRL Authority Key ID is not CRL Signer Subject Key ID, continue...") + # a. + crl_signer_skid = get_skid(crl_signer_certificate) + crl_akid = get_akid(crl_file) + if crl_akid != crl_signer_skid: + logging.warning("CRL AKID is not CRL Signer SKID, continue...") continue - issuer_subject_key_id = ''.join('{:02X}'.format(x) for x in crl_authority_key_id) + crl_akid_hex = ''.join('{:02X}'.format(x) for x in crl_akid) # b. - same_issuer_points = dcld_client.get_revocations_points_by_skid(issuer_subject_key_id) - count_with_matching_vid_issuer_skid = sum(item.get('vid') == vid for item in same_issuer_points) + same_issuer_points = dcld_client.get_revocations_points_by_skid(crl_akid_hex) + count_with_matching_vid_issuer_skid = sum(item.get('vid') == revocation_point["vid"] for item in same_issuer_points) if count_with_matching_vid_issuer_skid > 1: try: @@ -377,40 +463,61 @@ def main(use_main_net_dcld: str, use_test_net_dcld: str, use_main_net_http: bool logging.warning("CRL Issuing Distribution Point URI is not CRL URL, continue...") continue - # 9. Assign CRL File Issuer - certificate_authority_name = base64.b64encode(crl_file.issuer.public_bytes()).decode('utf-8') - logging.debug(f"CRL File Issuer: {certificate_authority_name}") + # TODO: 8. Validate CRL as per Section 6.3 of RFC 5280 + + # 9. decide on certificate authority name and AKID + if revocation_point["isPAA"] and not is_self_signed_certificate(crl_signer_certificate): + certificate_authority_name_b64 = get_subject_b64(paa_certificate_object) + certificate_akid = get_skid(paa_certificate_object) + elif crl_signer_delegator_cert: + certificate_authority_name_b64 = get_subject_b64(crl_signer_delegator_cert) + certificate_akid = get_skid(crl_signer_delegator_cert) + else: + certificate_authority_name_b64 = get_subject_b64(crl_signer_certificate) + certificate_akid = get_skid(crl_signer_certificate) + + # validate issuer skid matchces with the one in revocation points + certificate_akid_hex = ''.join('{:02X}'.format(x) for x in certificate_akid) + + logging.debug(f"Certificate Authority Name: {certificate_authority_name_b64}") + logging.debug(f"Certificate AKID: {certificate_akid_hex}") + logging.debug(f"revocation_point['issuerSubjectKeyID']: {revocation_point['issuerSubjectKeyID']}") + + if revocation_point["issuerSubjectKeyID"] != certificate_akid_hex: + logging.warning("CRL Issuer Subject Key ID is not CRL Signer Subject Key ID, continue...") + continue serialnumber_list = [] # 10. Iterate through the Revoked Certificates List for revoked_cert in crl_file: - # a. try: revoked_cert_issuer = revoked_cert.extensions.get_extension_for_oid( x509.CRLEntryExtensionOID.CERTIFICATE_ISSUER).value.get_values_for_type(x509.DirectoryName).value if revoked_cert_issuer is not None: - if revoked_cert_issuer != certificate_authority_name: + # check if this really are the same thing + if revoked_cert_issuer != certificate_authority_name_b64: logging.warning("CRL Issuer is not CRL File Issuer, continue...") continue except Exception: + logging.warning("certificateIssuer entry extension not found in CRL") pass - # b. - # TODO: Verify that the certificate chain of the entry is linking to the same PAA - # that issued the CRLSignerCertificate for this entry, including path through - # CRLSignerDelegator if present. If the PAAs under which were issued the certificate - # and the CRLSignerCertificate are different, ignore the entry. - - # c. and d. serialnumber_list.append(bytes(str('{:02X}'.format(revoked_cert.serial_number)), 'utf-8').decode('utf-8')) - issuer_name = base64.b64encode(crl_file.issuer.public_bytes()).decode('utf-8') + entry = { + "type": "revocation_set", + "issuer_subject_key_id": certificate_akid_hex, + "issuer_name": certificate_authority_name_b64, + "revoked_serial_numbers": serialnumber_list, + "crl_signer_cert": revocation_point["crlSignerCertificate"], + } + + if "crlSignerDelegator" in revocation_point: + entry["crl_signer_delegator"] = revocation_point["crlSignerDelegator"] - revocation_set.append({"type": "revocation_set", - "issuer_subject_key_id": issuer_subject_key_id, - "issuer_name": issuer_name, - "revoked_serial_numbers": serialnumber_list}) + logging.debug(f"Entry to append: {entry}") + revocation_set.append(entry) with open(output, 'w+') as outfile: json.dump(revocation_set, outfile, indent=4) diff --git a/examples/air-quality-sensor-app/silabs/README.md b/examples/air-quality-sensor-app/silabs/README.md index 7279e23457ef01..b2687c6cadb8b0 100644 --- a/examples/air-quality-sensor-app/silabs/README.md +++ b/examples/air-quality-sensor-app/silabs/README.md @@ -257,6 +257,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/air-quality-sensor-app/silabs/build_for_wifi_args.gni b/examples/air-quality-sensor-app/silabs/build_for_wifi_args.gni index 718600a8115e59..8b5ccad9ebc272 100644 --- a/examples/air-quality-sensor-app/silabs/build_for_wifi_args.gni +++ b/examples/air-quality-sensor-app/silabs/build_for_wifi_args.gni @@ -15,7 +15,7 @@ import("//build_overrides/chip.gni") import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") chip_enable_wifi = true chip_enable_ota_requestor = true app_data_model = diff --git a/examples/all-clusters-app/ameba/README.md b/examples/all-clusters-app/ameba/README.md index 9c442d6652e84f..5cf2c9aab87015 100644 --- a/examples/all-clusters-app/ameba/README.md +++ b/examples/all-clusters-app/ameba/README.md @@ -27,11 +27,11 @@ The CHIP demo application is supported on - Pull docker image: - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 - Setup build environment: diff --git a/examples/all-clusters-app/esp32/main/CMakeLists.txt b/examples/all-clusters-app/esp32/main/CMakeLists.txt index 31292543ca5f50..c35efdf4def94e 100644 --- a/examples/all-clusters-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-app/esp32/main/CMakeLists.txt @@ -45,6 +45,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/icd/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/util" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/administrator-commissioning-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/air-quality-server" diff --git a/examples/all-clusters-app/esp32/main/Kconfig.projbuild b/examples/all-clusters-app/esp32/main/Kconfig.projbuild index 2cec0c32093734..72807a1618632a 100644 --- a/examples/all-clusters-app/esp32/main/Kconfig.projbuild +++ b/examples/all-clusters-app/esp32/main/Kconfig.projbuild @@ -26,6 +26,7 @@ menu "Demo" default DEVICE_TYPE_ESP32_C3_DEVKITM if IDF_TARGET_ESP32C3 default DEVICE_TYPE_ESP32_C2_DEVKITM if IDF_TARGET_ESP32C2 default DEVICE_TYPE_ESP32_C6_DEVKITC if IDF_TARGET_ESP32C6 + default DEVICE_TYPE_ESP32_P4_FUNCTION_EV_BOARD if IDF_TARGET_ESP32P4 help Specifies the type of ESP32 device. @@ -57,6 +58,9 @@ menu "Demo" config DEVICE_TYPE_ESP32_H2_DEVKITM bool "ESP32H2-DevKitM" depends on IDF_TARGET_ESP32H2 + config DEVICE_TYPE_ESP32_P4_FUNCTION_EV_BOARD + bool "ESP32P4 Function EV Board" + depends on IDF_TARGET_ESP32P4 endchoice choice @@ -87,7 +91,7 @@ menu "Demo" config TFT_PREDEFINED_DISPLAY_TYPE int range 0 5 - default 0 if DEVICE_TYPE_ESP32_DEVKITC || DEVICE_TYPE_ESP32_H2_DEVKITM + default 0 if DEVICE_TYPE_ESP32_DEVKITC || DEVICE_TYPE_ESP32_H2_DEVKITM || DEVICE_TYPE_ESP32_P4_FUNCTION_EV_BOARD default 0 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM || DEVICE_TYPE_ESP32_C6_DEVKITC default 3 if DEVICE_TYPE_M5STACK default 4 if DEVICE_TYPE_ESP32_WROVER_KIT @@ -118,7 +122,7 @@ menu "Demo" range 0 40 default 2 if DEVICE_TYPE_ESP32_DEVKITC #Use LED1 (blue LED) as status LED on DevKitC default 2 if DEVICE_TYPE_ESP32_ETHERNET_KIT - default 8 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM || DEVICE_TYPE_ESP32_C6_DEVKITC || DEVICE_TYPE_ESP32_H2_DEVKITM + default 8 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM || DEVICE_TYPE_ESP32_C6_DEVKITC || DEVICE_TYPE_ESP32_H2_DEVKITM || DEVICE_TYPE_ESP32_P4_FUNCTION_EV_BOARD default 26 if DEVICE_TYPE_ESP32_WROVER_KIT default 40 if DEVICE_TYPE_M5STACK help diff --git a/examples/all-clusters-app/esp32/sdkconfig.defaults.esp32p4 b/examples/all-clusters-app/esp32/sdkconfig.defaults.esp32p4 new file mode 100644 index 00000000000000..3211b306b2be99 --- /dev/null +++ b/examples/all-clusters-app/esp32/sdkconfig.defaults.esp32p4 @@ -0,0 +1,37 @@ +CONFIG_IDF_TARGET="esp32p4" + +# Flash size and partition +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" + +# Enable BLE Host but use remote controller +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y +CONFIG_BT_NIMBLE_TRANSPORT_UART=n +CONFIG_ESP_ENABLE_BT=y + +# Increase main task stack size +CONFIG_ESP_MAIN_TASK_STACK_SIZE=4096 + +# Disable Wi-Fi Soft AP +CONFIG_ESP_WIFI_SOFTAP_SUPPORT=n + +# LwIP +CONFIG_LWIP_IPV6_AUTOCONFIG=y +CONFIG_LWIP_IPV6_NUM_ADDRESSES=6 + +# mbedtls +CONFIG_MBEDTLS_HKDF_C=y + +# Matter shell +CONFIG_ENABLE_CHIP_SHELL=y + +# OTA requestor +CONFIG_ENABLE_OTA_REQUESTOR=y + +# Do not deinit BLE after commissioning +CONFIG_USE_BLE_ONLY_FOR_COMMISSIONING=n + +# ESP32-P4 Function EV Board use ESP32C6 as slave device +CONFIG_SLAVE_IDF_TARGET_ESP32C6=y diff --git a/examples/all-clusters-app/linux/with_pw_rpc.gni b/examples/all-clusters-app/linux/with_pw_rpc.gni index 0f1ab1ea89c121..a67251431a018c 100644 --- a/examples/all-clusters-app/linux/with_pw_rpc.gni +++ b/examples/all-clusters-app/linux/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -39,4 +39,3 @@ pw_build_LINK_DEPS = [ ] chip_enable_pw_rpc = true -chip_use_pw_logging = true diff --git a/examples/all-clusters-app/nrfconnect/prj.conf b/examples/all-clusters-app/nrfconnect/prj.conf index 5917c3a9c7a17e..075fdd8e9d8d19 100644 --- a/examples/all-clusters-app/nrfconnect/prj.conf +++ b/examples/all-clusters-app/nrfconnect/prj.conf @@ -54,3 +54,6 @@ CONFIG_CHIP_QSPI_NOR=n # Enable the Read Client for binding purposes CONFIG_CHIP_ENABLE_READ_CLIENT=y + +# Increase the settings partition +CONFIG_PM_PARTITION_SIZE_SETTINGS_STORAGE=0x8000 diff --git a/examples/all-clusters-app/nxp/mw320/include/CHIPProjectConfig.h b/examples/all-clusters-app/nxp/mw320/include/CHIPProjectConfig.h index 5e4a6b1e4f5419..d39e2dc0c03f6d 100644 --- a/examples/all-clusters-app/nxp/mw320/include/CHIPProjectConfig.h +++ b/examples/all-clusters-app/nxp/mw320/include/CHIPProjectConfig.h @@ -143,15 +143,6 @@ */ #define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 0 -/** - * CHIP_CONFIG_MAX_BINDINGS - * - * Maximum number of simultaneously active bindings per ChipExchangeManager - * 1 (Time Sync) + 2 (Two 1-way subscriptions) + 1 (Software Update) = 4 - * in the worst case. Keeping another 4 as buffer. - */ -#define CHIP_CONFIG_MAX_BINDINGS 6 - /** * CHIP_CONFIG_EVENT_LOGGING_WDM_OFFLOAD * diff --git a/examples/all-clusters-app/nxp/rt/rt1060/README.md b/examples/all-clusters-app/nxp/rt/rt1060/README.md index 96822ff6eb2453..3ddcbd7c853f9d 100644 --- a/examples/all-clusters-app/nxp/rt/rt1060/README.md +++ b/examples/all-clusters-app/nxp/rt/rt1060/README.md @@ -310,7 +310,7 @@ user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt106 build-time which will enable the device to join the Wi-Fi AP at startup): ``` -user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ gn gen --args="chip_enable_wifi=true iwx12_transceiver=true evkname=\"evkcmimxrt1060\" chip_config_network_layer_ble=false tcp_download=true wifi_ssid=\"your_wifi_ssid\" wifi_password=\"your_wifi_password\"" out/debug +user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ export ssid_name= && export ssid_password= && gn gen --args="chip_enable_wifi=true iwx12_transceiver=true evkname=\"evkcmimxrt1060\" chip_config_network_layer_ble=false wifi_auto_connect_at_boot=true wifi_auto_connect_at_boot_ssid=\"${ssid_name}\" wifi_auto_connect_at_boot_password=\"${ssid_password}\"" out/debug user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ ninja -C out/debug ``` @@ -400,7 +400,7 @@ user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt106 - Build Matter with Border Router configuration with onnetwork commissioning: ``` -user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ gn gen --args="chip_enable_wifi=true w8801_transceiver=true nxp_enable_matter_cli=true chip_config_network_layer_ble=false wifi_auto_connect_at_boot=true wifi_auto_connect_at_boot_ssid=\"your_wifi_ssid\" wifi_auto_connect_at_boot_password=\"your_wifi_password\" chip_enable_openthread=true k32w0_transceiver=true k32w0_transceiver_bin_path=\"/path/to/ot-rcp/ot-rcp-ble-hci-bb-k32w061.elf.bin.h\"" out/debug +user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ export ssid_name= && export ssid_password= && gn gen --args="chip_enable_wifi=true w8801_transceiver=true nxp_enable_matter_cli=true chip_config_network_layer_ble=false wifi_auto_connect_at_boot=true wifi_auto_connect_at_boot_ssid=\"${ssid_name}\" wifi_auto_connect_at_boot_password=\"${ssid_password}\" chip_enable_openthread=true k32w0_transceiver=true k32w0_transceiver_bin_path=\"/path/to/ot-rcp/ot-rcp-ble-hci-bb-k32w061.elf.bin.h\"" out/debug user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ ninja -C out/debug ``` diff --git a/examples/all-clusters-app/nxp/rt/rt1060/include/config/CHIPProjectConfig.h b/examples/all-clusters-app/nxp/rt/rt1060/include/config/CHIPProjectConfig.h index dd73c6c9eaaedd..61be0867102324 100644 --- a/examples/all-clusters-app/nxp/rt/rt1060/include/config/CHIPProjectConfig.h +++ b/examples/all-clusters-app/nxp/rt/rt1060/include/config/CHIPProjectConfig.h @@ -167,15 +167,6 @@ */ // #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 -/** - * CHIP_CONFIG_MAX_BINDINGS - * - * Maximum number of simultaneously active bindings per ChipExchangeManager - * 1 (Time Sync) + 2 (Two 1-way subscriptions) + 1 (Software Update) = 4 - * in the worst case. Keeping another 4 as buffer. - */ -#define CHIP_CONFIG_MAX_BINDINGS 6 - /** * CHIP_CONFIG_EVENT_LOGGING_WDM_OFFLOAD * diff --git a/examples/all-clusters-app/nxp/rt/rt1170/include/config/CHIPProjectConfig.h b/examples/all-clusters-app/nxp/rt/rt1170/include/config/CHIPProjectConfig.h index dd73c6c9eaaedd..61be0867102324 100644 --- a/examples/all-clusters-app/nxp/rt/rt1170/include/config/CHIPProjectConfig.h +++ b/examples/all-clusters-app/nxp/rt/rt1170/include/config/CHIPProjectConfig.h @@ -167,15 +167,6 @@ */ // #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 -/** - * CHIP_CONFIG_MAX_BINDINGS - * - * Maximum number of simultaneously active bindings per ChipExchangeManager - * 1 (Time Sync) + 2 (Two 1-way subscriptions) + 1 (Software Update) = 4 - * in the worst case. Keeping another 4 as buffer. - */ -#define CHIP_CONFIG_MAX_BINDINGS 6 - /** * CHIP_CONFIG_EVENT_LOGGING_WDM_OFFLOAD * diff --git a/examples/all-clusters-app/nxp/rt/rw61x/include/config/CHIPProjectConfig.h b/examples/all-clusters-app/nxp/rt/rw61x/include/config/CHIPProjectConfig.h index 2653e97705fe39..33a42909f464ea 100644 --- a/examples/all-clusters-app/nxp/rt/rw61x/include/config/CHIPProjectConfig.h +++ b/examples/all-clusters-app/nxp/rt/rw61x/include/config/CHIPProjectConfig.h @@ -168,15 +168,6 @@ */ // #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 -/** - * CHIP_CONFIG_MAX_BINDINGS - * - * Maximum number of simultaneously active bindings per ChipExchangeManager - * 1 (Time Sync) + 2 (Two 1-way subscriptions) + 1 (Software Update) = 4 - * in the worst case. Keeping another 4 as buffer. - */ -#define CHIP_CONFIG_MAX_BINDINGS 6 - /** * CHIP_CONFIG_EVENT_LOGGING_WDM_OFFLOAD * diff --git a/examples/all-clusters-minimal-app/ameba/README.md b/examples/all-clusters-minimal-app/ameba/README.md index b120d9c4bfebfa..447d950be39f86 100644 --- a/examples/all-clusters-minimal-app/ameba/README.md +++ b/examples/all-clusters-minimal-app/ameba/README.md @@ -27,13 +27,13 @@ The CHIP demo application is supported on - Pull docker image: ``` - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 ``` - Run docker container: ``` - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 ``` - Setup build environment: diff --git a/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt b/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt index f82f301e3ae362..680d4a9c02636e 100644 --- a/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-minimal-app/esp32/main/CMakeLists.txt @@ -38,6 +38,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/icd" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/util" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/administrator-commissioning-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/application-basic-server" diff --git a/examples/all-clusters-minimal-app/nrfconnect/prj.conf b/examples/all-clusters-minimal-app/nrfconnect/prj.conf index 58dae15804fe81..9e738ba64d1431 100644 --- a/examples/all-clusters-minimal-app/nrfconnect/prj.conf +++ b/examples/all-clusters-minimal-app/nrfconnect/prj.conf @@ -55,3 +55,6 @@ CONFIG_CHIP_QSPI_NOR=n # Enable Factory Data feature CONFIG_CHIP_FACTORY_DATA=y CONFIG_CHIP_FACTORY_DATA_BUILD=y + +# Increase the settings partition +CONFIG_PM_PARTITION_SIZE_SETTINGS_STORAGE=0x8000 diff --git a/examples/android/CHIPTest/BUILD.gn b/examples/android/CHIPTest/BUILD.gn index c8ccb2e614c103..7dee07e6f693c1 100644 --- a/examples/android/CHIPTest/BUILD.gn +++ b/examples/android/CHIPTest/BUILD.gn @@ -39,6 +39,7 @@ shared_library("jni") { "${chip_root}/src/platform/android:java", "${chip_root}/src/platform/android:logging", "${chip_root}/src/platform/tests:tests", + "${chip_root}/src/pw_backends/assert:assert.impl", "${chip_root}/third_party/inipp", "${chip_root}/third_party/nlfaultinjection:nlfaultinjection", ] diff --git a/examples/android/CHIPTest/args.gni b/examples/android/CHIPTest/args.gni index df7c34af9c20ae..04ba876aeb7ac9 100644 --- a/examples/android/CHIPTest/args.gni +++ b/examples/android/CHIPTest/args.gni @@ -28,8 +28,8 @@ chip_monolithic_tests = false pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" -pw_assert_BACKEND = "$dir_pw_assert_log" -pw_log_BACKEND = "$dir_pw_log_basic" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" pw_unit_test_BACKEND = "$dir_pw_unit_test:light" diff --git a/examples/bridge-app/esp32/main/CMakeLists.txt b/examples/bridge-app/esp32/main/CMakeLists.txt index 3330f6971b68cd..9d34b44a92f0e1 100644 --- a/examples/bridge-app/esp32/main/CMakeLists.txt +++ b/examples/bridge-app/esp32/main/CMakeLists.txt @@ -23,6 +23,7 @@ idf_component_register(PRIV_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/administrator-commissioning-server" diff --git a/examples/chef/chef.py b/examples/chef/chef.py index cecbf646ffeedf..8c54ee8dbbc6fb 100755 --- a/examples/chef/chef.py +++ b/examples/chef/chef.py @@ -884,7 +884,7 @@ def main() -> int: """)) if options.do_clean: shell.run_cmd("rm -rf out") - shell.run_cmd("gn gen --export-compile-commands out") + shell.run_cmd("gn gen --add-export-compile-commands=* out") shell.run_cmd("ninja -C out") # diff --git a/examples/chef/common/chef-fan-control-manager.cpp b/examples/chef/common/chef-fan-control-manager.cpp index 8d9ed5ae8bb699..7c2aec389e08a4 100644 --- a/examples/chef/common/chef-fan-control-manager.cpp +++ b/examples/chef/common/chef-fan-control-manager.cpp @@ -38,20 +38,45 @@ using namespace chip::app::Clusters::FanControl::Attributes; using Protocols::InteractionModel::Status; namespace { -class ChefFanControlManager : public AttributeAccessInterface, public Delegate +class ChefFanControlManager : public Delegate { public: - ChefFanControlManager(EndpointId aEndpointId) : - AttributeAccessInterface(Optional(aEndpointId), FanControl::Id), Delegate(aEndpointId) - {} + ChefFanControlManager(EndpointId aEndpointId) : Delegate(aEndpointId) {} - CHIP_ERROR Write(const ConcreteDataAttributePath & aPath, AttributeValueDecoder & aDecoder) override; - CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override; + void Init(); + void HandleFanControlAttributeChange(AttributeId attributeId, uint8_t type, uint16_t size, uint8_t * value); Status HandleStep(StepDirectionEnum aDirection, bool aWrap, bool aLowestOff) override; + DataModel::Nullable GetSpeedSetting(); + DataModel::Nullable GetPercentSetting(); private: - Nullable mPercentSetting{}; - Nullable mSpeedSetting{}; + uint8_t mPercentCurrent = 0; + uint8_t mSpeedCurrent = 0; + + // Fan Mode Limits + struct Range + { + bool Contains(int value) const { return value >= low && value <= high; } + int Low() const { return low; } + int High() const { return high; } + + int low; + int high; + }; + static constexpr Range kFanModeLowSpeedRange = { 1, 3 }; + static constexpr Range kFanModeMediumSpeedRange = { 4, 7 }; + static constexpr Range kFanModeHighSpeedRange = { 8, 10 }; + + static_assert(kFanModeLowSpeedRange.low <= kFanModeLowSpeedRange.high); + static_assert(kFanModeLowSpeedRange.high + 1 == kFanModeMediumSpeedRange.low); + static_assert(kFanModeMediumSpeedRange.high + 1 == kFanModeHighSpeedRange.low); + static_assert(kFanModeHighSpeedRange.low <= kFanModeHighSpeedRange.high); + + void FanModeWriteCallback(FanControl::FanModeEnum aNewFanMode); + void SetSpeedCurrent(uint8_t aNewSpeedCurrent); + void SetPercentCurrent(uint8_t aNewPercentCurrent); + void SetSpeedSetting(DataModel::Nullable aNewSpeedSetting); + static FanControl::FanModeEnum SpeedToFanMode(uint8_t speed); }; static std::unique_ptr mFanControlManager; @@ -99,98 +124,222 @@ Status ChefFanControlManager::HandleStep(StepDirectionEnum aDirection, bool aWra return SpeedSetting::Set(mEndpoint, newSpeedSetting); } -CHIP_ERROR ChefFanControlManager::Write(const ConcreteDataAttributePath & aPath, AttributeValueDecoder & aDecoder) +void ChefFanControlManager::HandleFanControlAttributeChange(AttributeId attributeId, uint8_t type, uint16_t size, uint8_t * value) { - VerifyOrDie(aPath.mClusterId == FanControl::Id); - VerifyOrDie(aPath.mEndpointId == mEndpoint); - - switch (aPath.mAttributeId) + ChipLogProgress(NotSpecified, "ChefFanControlManager::HandleFanControlAttributeChange"); + switch (attributeId) { - case SpeedSetting::Id: { - Nullable newSpeedSetting; - ReturnErrorOnFailure(aDecoder.Decode(newSpeedSetting)); - - // Ensure new speed is in bounds + case FanControl::Attributes::PercentSetting::Id: { + ChipLogProgress(NotSpecified, "ChefFanControlManager::HandleFanControlAttributeChange PercentSetting"); + DataModel::Nullable percentSetting; + if (!NumericAttributeTraits::IsNullValue(*value)) { - uint8_t maxSpeedSetting = 0; - Protocols::InteractionModel::Status status = SpeedMax::Get(mEndpoint, &maxSpeedSetting); - VerifyOrReturnError(status == Protocols::InteractionModel::Status::Success, CHIP_IM_GLOBAL_STATUS(Failure)); - - if (!newSpeedSetting.IsNull() && newSpeedSetting.Value() > maxSpeedSetting) - { - return CHIP_IM_GLOBAL_STATUS(ConstraintError); - } + percentSetting.SetNonNull(NumericAttributeTraits::StorageToWorking(*value)); } - - // Only act on changed. - if (newSpeedSetting != mSpeedSetting) + else { - mSpeedSetting = newSpeedSetting; - - // Mark both the setting AND the current dirty, since the current always - // tracks the target for our product. - MatterReportingAttributeChangeCallback(mEndpoint, FanControl::Id, Attributes::SpeedSetting::Id); - MatterReportingAttributeChangeCallback(mEndpoint, FanControl::Id, Attributes::SpeedCurrent::Id); + percentSetting.SetNull(); } + // The cluster code in fan-control-server.cpp is the only one allowed to set PercentSetting to null. + // This happens as a consequence of setting the FanMode to kAuto. In auto mode, percentCurrent should continue to report the + // real fan speed percentage. In this example, we set PercentCurrent to 0 here as we don't have a real value for the Fan + // speed or a FanAutoMode simulator. + // When not Null, SpeedCurrent tracks SpeedSetting's value. + SetPercentCurrent(percentSetting.ValueOr(0)); break; } - case PercentSetting::Id: { - Nullable newPercentSetting; - ReturnErrorOnFailure(aDecoder.Decode(newPercentSetting)); - // Ensure new speed in percent is valid. - if (!newPercentSetting.IsNull() && newPercentSetting.Value() > 100) + case FanControl::Attributes::SpeedSetting::Id: { + ChipLogProgress(NotSpecified, "ChefFanControlManager::HandleFanControlAttributeChange SpeedSetting"); + DataModel::Nullable speedSetting; + if (!NumericAttributeTraits::IsNullValue(*value)) { - return CHIP_IM_GLOBAL_STATUS(ConstraintError); + speedSetting.SetNonNull(NumericAttributeTraits::StorageToWorking(*value)); } - - // Only act on changed. - if (newPercentSetting != mPercentSetting) + else { - mPercentSetting = newPercentSetting; - - // Mark both the setting AND the current dirty, since the current always - // tracks the target for our product. - MatterReportingAttributeChangeCallback(mEndpoint, FanControl::Id, Attributes::PercentSetting::Id); - MatterReportingAttributeChangeCallback(mEndpoint, FanControl::Id, Attributes::PercentCurrent::Id); + speedSetting.SetNull(); } + // The cluster code in fan-control-server.cpp is the only one allowed to set speedSetting to null. + // This happens as a consequence of setting the FanMode to kAuto. In auto mode, speedCurrent should continue to report the + // real fan speed. In this example, we set SpeedCurrent to 0 here as we don't have a real value for the Fan speed or a + // FanAutoMode simulator. + // When not Null, SpeedCurrent tracks SpeedSetting's value. + SetSpeedCurrent(speedSetting.ValueOr(0)); + // Determine if the speed change should also change the fan mode + FanControl::Attributes::FanMode::Set(mEndpoint, SpeedToFanMode(mSpeedCurrent)); break; } - default: + + case FanControl::Attributes::FanMode::Id: { + ChipLogProgress(NotSpecified, "ChefFanControlManager::HandleFanControlAttributeChange FanMode"); + + static_assert(sizeof(FanControl::FanModeEnum) == 1); + FanControl::FanModeEnum fanMode = static_cast(*value); + FanModeWriteCallback(fanMode); break; } - // Fall through goes to attribute store legacy handling. - return CHIP_NO_ERROR; + default: { + break; + } + } +} + +FanControl::FanModeEnum ChefFanControlManager::SpeedToFanMode(uint8_t speed) +{ + if (speed == 0) + { + return FanControl::FanModeEnum::kOff; + } + if (kFanModeLowSpeedRange.Contains(speed)) + { + return FanControl::FanModeEnum::kLow; + } + if (kFanModeMediumSpeedRange.Contains(speed)) + { + return FanControl::FanModeEnum::kMedium; + } + return FanControl::FanModeEnum::kHigh; } -CHIP_ERROR ChefFanControlManager::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) +void ChefFanControlManager::SetPercentCurrent(uint8_t aNewPercentCurrent) { - VerifyOrDie(aPath.mClusterId == FanControl::Id); - VerifyOrDie(aPath.mEndpointId == mEndpoint); + if (aNewPercentCurrent == mPercentCurrent) + { + return; + } - switch (aPath.mAttributeId) + ChipLogDetail(NotSpecified, "ChefFanControlManager::SetPercentCurrent: %d", aNewPercentCurrent); + mPercentCurrent = aNewPercentCurrent; + Status status = FanControl::Attributes::PercentCurrent::Set(mEndpoint, mPercentCurrent); + if (status != Status::Success) { - case PercentCurrent::Id: { - // Current percents always tracks setting immediately in our implementation. - return aEncoder.Encode(mPercentSetting.ValueOr(0)); + ChipLogError(NotSpecified, "ChefFanControlManager::SetPercentCurrent: failed to set PercentCurrent attribute: %d", + to_underlying(status)); } - case PercentSetting::Id: { - return aEncoder.Encode(mPercentSetting); +} + +void ChefFanControlManager::SetSpeedCurrent(uint8_t aNewSpeedCurrent) +{ + if (aNewSpeedCurrent == mSpeedCurrent) + { + return; } - case SpeedCurrent::Id: { - // Current speed always tracks setting immediately in our implementation. - return aEncoder.Encode(mSpeedSetting.ValueOr(0)); + + ChipLogDetail(NotSpecified, "ChefFanControlManager::SetSpeedCurrent: %d", aNewSpeedCurrent); + mSpeedCurrent = aNewSpeedCurrent; + Status status = FanControl::Attributes::SpeedCurrent::Set(mEndpoint, aNewSpeedCurrent); + if (status != Status::Success) + { + ChipLogError(NotSpecified, "ChefFanControlManager::SetSpeedCurrent: failed to set SpeedCurrent attribute: %d", + to_underlying(status)); } - case SpeedSetting::Id: { - return aEncoder.Encode(mSpeedSetting); +} + +void ChefFanControlManager::FanModeWriteCallback(FanControl::FanModeEnum aNewFanMode) +{ + ChipLogDetail(NotSpecified, "ChefFanControlManager::FanModeWriteCallback: %d", to_underlying(aNewFanMode)); + switch (aNewFanMode) + { + case FanControl::FanModeEnum::kOff: { + if (mSpeedCurrent != 0) + { + DataModel::Nullable speedSetting(0); + SetSpeedSetting(speedSetting); + } + break; } - default: + case FanControl::FanModeEnum::kLow: { + if (!kFanModeLowSpeedRange.Contains(mSpeedCurrent)) + { + DataModel::Nullable speedSetting(kFanModeLowSpeedRange.Low()); + SetSpeedSetting(speedSetting); + } break; } - return CHIP_NO_ERROR; + case FanControl::FanModeEnum::kMedium: { + if (!kFanModeMediumSpeedRange.Contains(mSpeedCurrent)) + { + DataModel::Nullable speedSetting(kFanModeMediumSpeedRange.Low()); + SetSpeedSetting(speedSetting); + } + break; + } + case FanControl::FanModeEnum::kOn: + case FanControl::FanModeEnum::kHigh: { + if (!kFanModeHighSpeedRange.Contains(mSpeedCurrent)) + { + DataModel::Nullable speedSetting(kFanModeHighSpeedRange.Low()); + SetSpeedSetting(speedSetting); + } + break; + } + case FanControl::FanModeEnum::kSmart: + case FanControl::FanModeEnum::kAuto: { + ChipLogProgress(NotSpecified, "ChefFanControlManager::FanModeWriteCallback: Auto"); + break; + } + case FanControl::FanModeEnum::kUnknownEnumValue: { + ChipLogProgress(NotSpecified, "ChefFanControlManager::FanModeWriteCallback: Unknown"); + break; + } + } +} + +void ChefFanControlManager::SetSpeedSetting(DataModel::Nullable aNewSpeedSetting) +{ + if (aNewSpeedSetting.IsNull()) + { + ChipLogError(NotSpecified, "ChefFanControlManager::SetSpeedSetting: null value is invalid"); + return; + } + + if (aNewSpeedSetting.Value() != mSpeedCurrent) + { + Status status = FanControl::Attributes::SpeedSetting::Set(mEndpoint, aNewSpeedSetting); + if (status != Status::Success) + { + ChipLogError(NotSpecified, "ChefFanControlManager::SetSpeedSetting: failed to set SpeedSetting attribute: %d", + to_underlying(status)); + } + } +} + +void ChefFanControlManager::Init() +{ + SetPercentCurrent(GetPercentSetting().ValueOr(0)); + SetSpeedCurrent(GetSpeedSetting().ValueOr(0)); +} + +DataModel::Nullable ChefFanControlManager::GetPercentSetting() +{ + DataModel::Nullable percentSetting; + Status status = FanControl::Attributes::PercentSetting::Get(mEndpoint, percentSetting); + + if (status != Status::Success) + { + ChipLogError(NotSpecified, "ChefFanControlManager::GetPercentSetting: failed to get PercentSetting attribute: %d", + to_underlying(status)); + } + + return percentSetting; +} + +DataModel::Nullable ChefFanControlManager::GetSpeedSetting() +{ + DataModel::Nullable speedSetting; + Status status = FanControl::Attributes::SpeedSetting::Get(mEndpoint, speedSetting); + + if (status != Status::Success) + { + ChipLogError(NotSpecified, "ChefFanControlManager::GetSpeedSetting: failed to get SpeedSetting attribute: %d", + to_underlying(status)); + } + + return speedSetting; } } // anonymous namespace @@ -199,6 +348,11 @@ void emberAfFanControlClusterInitCallback(EndpointId endpoint) { VerifyOrDie(!mFanControlManager); mFanControlManager = std::make_unique(endpoint); - AttributeAccessInterfaceRegistry::Instance().Register(mFanControlManager.get()); FanControl::SetDefaultDelegate(endpoint, mFanControlManager.get()); + mFanControlManager->Init(); +} + +void HandleFanControlAttributeChange(AttributeId attributeId, uint8_t type, uint16_t size, uint8_t * value) +{ + mFanControlManager->HandleFanControlAttributeChange(attributeId, type, size, value); } diff --git a/examples/platform/silabs/efr32/wf200/sl_wfx_configuration.h b/examples/chef/common/chef-fan-control-manager.h similarity index 52% rename from examples/platform/silabs/efr32/wf200/sl_wfx_configuration.h rename to examples/chef/common/chef-fan-control-manager.h index deb468d1a6af73..36a90e6a886e92 100644 --- a/examples/platform/silabs/efr32/wf200/sl_wfx_configuration.h +++ b/examples/chef/common/chef-fan-control-manager.h @@ -1,12 +1,12 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2024 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 + * 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, @@ -15,16 +15,8 @@ * limitations under the License. */ -#pragma once +#include -// SL_WFX_DEFAULT_REQUEST_TIMEOUT_MS> Timeout period in milliseconds<250-10000> -// Default: 5000 -// Timeout period in milliseconds for requests. -#define SL_WFX_DEFAULT_REQUEST_TIMEOUT_MS (5000) - -// WFx Secure Link configuration - -// SL_WFX_SLK_CURVE25519> Use crypto curves -// Default: 1 -// If this option is enabled ECDH crypto is used, KDF otherwise. -#define SL_WFX_SLK_CURVE25519 (1) +#ifdef MATTER_DM_PLUGIN_FAN_CONTROL_SERVER +void HandleFanControlAttributeChange(AttributeId attributeId, uint8_t type, uint16_t size, uint8_t * value); +#endif diff --git a/examples/chef/common/stubs.cpp b/examples/chef/common/stubs.cpp index 5cbe80aa83f162..8c389028cd0530 100644 --- a/examples/chef/common/stubs.cpp +++ b/examples/chef/common/stubs.cpp @@ -74,6 +74,9 @@ const Clusters::Descriptor::Structs::SemanticTagStruct::Type freezerTagList[] #include "chef-operational-state-delegate-impl.h" #endif // MATTER_DM_PLUGIN_OPERATIONAL_STATE_SERVER +#ifdef MATTER_DM_PLUGIN_FAN_CONTROL_SERVER +#include "chef-fan-control-manager.h" +#endif // MATTER_DM_PLUGIN_FAN_CONTROL_SERVER #ifdef MATTER_DM_PLUGIN_TEMPERATURE_CONTROL_SERVER #include "temperature-control/static-supported-temperature-levels.h" #endif // MATTER_DM_PLUGIN_TEMPERATURE_CONTROL_SERVER @@ -253,6 +256,12 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & // WIP Apply attribute change to Light } +#ifdef MATTER_DM_PLUGIN_FAN_CONTROL_SERVER + else if (clusterId == FanControl::Id) + { + HandleFanControlAttributeChange(attributeId, type, size, value); + } +#endif // MATTER_DM_PLUGIN_FAN_CONTROL_SERVER } /** @brief OnOff Cluster Init diff --git a/examples/chef/devices/rootnode_contactsensor_lightsensor_occupancysensor_temperaturesensor_pressuresensor_flowsensor_humiditysensor_airqualitysensor_powersource_367e7cea91.matter b/examples/chef/devices/rootnode_contactsensor_lightsensor_occupancysensor_temperaturesensor_pressuresensor_flowsensor_humiditysensor_airqualitysensor_powersource_367e7cea91.matter new file mode 100644 index 00000000000000..27c88b4fb8435e --- /dev/null +++ b/examples/chef/devices/rootnode_contactsensor_lightsensor_occupancysensor_temperaturesensor_pressuresensor_flowsensor_humiditysensor_airqualitysensor_powersource_367e7cea91.matter @@ -0,0 +1,3142 @@ +// This IDL was generated automatically by ZAP. +// It is for view/code review purposes only. + +enum AreaTypeTag : enum8 { + kAisle = 0; + kAttic = 1; + kBackDoor = 2; + kBackYard = 3; + kBalcony = 4; + kBallroom = 5; + kBathroom = 6; + kBedroom = 7; + kBorder = 8; + kBoxroom = 9; + kBreakfastRoom = 10; + kCarport = 11; + kCellar = 12; + kCloakroom = 13; + kCloset = 14; + kConservatory = 15; + kCorridor = 16; + kCraftRoom = 17; + kCupboard = 18; + kDeck = 19; + kDen = 20; + kDining = 21; + kDrawingRoom = 22; + kDressingRoom = 23; + kDriveway = 24; + kElevator = 25; + kEnsuite = 26; + kEntrance = 27; + kEntryway = 28; + kFamilyRoom = 29; + kFoyer = 30; + kFrontDoor = 31; + kFrontYard = 32; + kGameRoom = 33; + kGarage = 34; + kGarageDoor = 35; + kGarden = 36; + kGardenDoor = 37; + kGuestBathroom = 38; + kGuestBedroom = 39; + kGuestRestroom = 40; + kGuestRoom = 41; + kGym = 42; + kHallway = 43; + kHearthRoom = 44; + kKidsRoom = 45; + kKidsBedroom = 46; + kKitchen = 47; + kLarder = 48; + kLaundryRoom = 49; + kLawn = 50; + kLibrary = 51; + kLivingRoom = 52; + kLounge = 53; + kMediaTVRoom = 54; + kMudRoom = 55; + kMusicRoom = 56; + kNursery = 57; + kOffice = 58; + kOutdoorKitchen = 59; + kOutside = 60; + kPantry = 61; + kParkingLot = 62; + kParlor = 63; + kPatio = 64; + kPlayRoom = 65; + kPoolRoom = 66; + kPorch = 67; + kPrimaryBathroom = 68; + kPrimaryBedroom = 69; + kRamp = 70; + kReceptionRoom = 71; + kRecreationRoom = 72; + kRestroom = 73; + kRoof = 74; + kSauna = 75; + kScullery = 76; + kSewingRoom = 77; + kShed = 78; + kSideDoor = 79; + kSideYard = 80; + kSittingRoom = 81; + kSnug = 82; + kSpa = 83; + kStaircase = 84; + kSteamRoom = 85; + kStorageRoom = 86; + kStudio = 87; + kStudy = 88; + kSunRoom = 89; + kSwimmingPool = 90; + kTerrace = 91; + kUtilityRoom = 92; + kWard = 93; + kWorkshop = 94; +} + +enum AtomicRequestTypeEnum : enum8 { + kBeginWrite = 0; + kCommitWrite = 1; + kRollbackWrite = 2; +} + +enum FloorSurfaceTag : enum8 { + kCarpet = 0; + kCeramic = 1; + kConcrete = 2; + kCork = 3; + kDeepCarpet = 4; + kDirt = 5; + kEngineeredWood = 6; + kGlass = 7; + kGrass = 8; + kHardwood = 9; + kLaminate = 10; + kLinoleum = 11; + kMat = 12; + kMetal = 13; + kPlastic = 14; + kPolishedConcrete = 15; + kRubber = 16; + kRug = 17; + kSand = 18; + kStone = 19; + kTatami = 20; + kTerrazzo = 21; + kTile = 22; + kVinyl = 23; +} + +enum LandmarkTag : enum8 { + kAirConditioner = 0; + kAirPurifier = 1; + kBackDoor = 2; + kBarStool = 3; + kBathMat = 4; + kBathtub = 5; + kBed = 6; + kBookshelf = 7; + kChair = 8; + kChristmasTree = 9; + kCoatRack = 10; + kCoffeeTable = 11; + kCookingRange = 12; + kCouch = 13; + kCountertop = 14; + kCradle = 15; + kCrib = 16; + kDesk = 17; + kDiningTable = 18; + kDishwasher = 19; + kDoor = 20; + kDresser = 21; + kLaundryDryer = 22; + kFan = 23; + kFireplace = 24; + kFreezer = 25; + kFrontDoor = 26; + kHighChair = 27; + kKitchenIsland = 28; + kLamp = 29; + kLitterBox = 30; + kMirror = 31; + kNightstand = 32; + kOven = 33; + kPetBed = 34; + kPetBowl = 35; + kPetCrate = 36; + kRefrigerator = 37; + kScratchingPost = 38; + kShoeRack = 39; + kShower = 40; + kSideDoor = 41; + kSink = 42; + kSofa = 43; + kStove = 44; + kTable = 45; + kToilet = 46; + kTrashCan = 47; + kLaundryWasher = 48; + kWindow = 49; + kWineCooler = 50; +} + +enum PositionTag : enum8 { + kLeft = 0; + kRight = 1; + kTop = 2; + kBottom = 3; + kMiddle = 4; + kRow = 5; + kColumn = 6; +} + +enum RelativePositionTag : enum8 { + kUnder = 0; + kNextTo = 1; + kAround = 2; + kOn = 3; + kAbove = 4; + kFrontOf = 5; + kBehind = 6; +} + +enum TestGlobalEnum : enum8 { + kSomeValue = 0; + kSomeOtherValue = 1; + kFinalValue = 2; +} + +enum ThreeLevelAutoEnum : enum8 { + kLow = 0; + kMedium = 1; + kHigh = 2; + kAutomatic = 3; +} + +bitmap TestGlobalBitmap : bitmap32 { + kFirstBit = 0x1; + kSecondBit = 0x2; +} + +struct TestGlobalStruct { + char_string<128> name = 0; + nullable TestGlobalBitmap myBitmap = 1; + optional nullable TestGlobalEnum myEnum = 2; +} + +struct LocationDescriptorStruct { + char_string<128> locationName = 0; + nullable int16s floorNumber = 1; + nullable AreaTypeTag areaType = 2; +} + +struct AtomicAttributeStatusStruct { + attrib_id attributeID = 0; + status statusCode = 1; +} + +/** Attributes and commands for putting a device into Identification mode (e.g. flashing a light). */ +cluster Identify = 3 { + revision 4; + + enum EffectIdentifierEnum : enum8 { + kBlink = 0; + kBreathe = 1; + kOkay = 2; + kChannelChange = 11; + kFinishEffect = 254; + kStopEffect = 255; + } + + enum EffectVariantEnum : enum8 { + kDefault = 0; + } + + enum IdentifyTypeEnum : enum8 { + kNone = 0; + kLightOutput = 1; + kVisibleIndicator = 2; + kAudibleBeep = 3; + kDisplay = 4; + kActuator = 5; + } + + attribute int16u identifyTime = 0; + readonly attribute IdentifyTypeEnum identifyType = 1; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct IdentifyRequest { + int16u identifyTime = 0; + } + + request struct TriggerEffectRequest { + EffectIdentifierEnum effectIdentifier = 0; + EffectVariantEnum effectVariant = 1; + } + + /** Command description for Identify */ + command access(invoke: manage) Identify(IdentifyRequest): DefaultSuccess = 0; + /** Command description for TriggerEffect */ + command access(invoke: manage) TriggerEffect(TriggerEffectRequest): DefaultSuccess = 64; +} + +/** The Descriptor Cluster is meant to replace the support from the Zigbee Device Object (ZDO) for describing a node, its endpoints and clusters. */ +cluster Descriptor = 29 { + revision 2; + + bitmap Feature : bitmap32 { + kTagList = 0x1; + } + + struct DeviceTypeStruct { + devtype_id deviceType = 0; + int16u revision = 1; + } + + struct SemanticTagStruct { + nullable vendor_id mfgCode = 0; + enum8 namespaceID = 1; + enum8 tag = 2; + optional nullable char_string label = 3; + } + + readonly attribute DeviceTypeStruct deviceTypeList[] = 0; + readonly attribute cluster_id serverList[] = 1; + readonly attribute cluster_id clientList[] = 2; + readonly attribute endpoint_no partsList[] = 3; + readonly attribute optional SemanticTagStruct tagList[] = 4; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** The Binding Cluster is meant to replace the support from the Zigbee Device Object (ZDO) for supporting the binding table. */ +cluster Binding = 30 { + revision 1; // NOTE: Default/not specifically set + + fabric_scoped struct TargetStruct { + optional node_id node = 1; + optional group_id group = 2; + optional endpoint_no endpoint = 3; + optional cluster_id cluster = 4; + fabric_idx fabricIndex = 254; + } + + attribute access(write: manage) TargetStruct binding[] = 0; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** The Access Control Cluster exposes a data model view of a + Node's Access Control List (ACL), which codifies the rules used to manage + and enforce Access Control for the Node's endpoints and their associated + cluster instances. */ +cluster AccessControl = 31 { + revision 2; + + enum AccessControlEntryAuthModeEnum : enum8 { + kPASE = 1; + kCASE = 2; + kGroup = 3; + } + + enum AccessControlEntryPrivilegeEnum : enum8 { + kView = 1; + kProxyView = 2; + kOperate = 3; + kManage = 4; + kAdminister = 5; + } + + enum AccessRestrictionTypeEnum : enum8 { + kAttributeAccessForbidden = 0; + kAttributeWriteForbidden = 1; + kCommandForbidden = 2; + kEventForbidden = 3; + } + + enum ChangeTypeEnum : enum8 { + kChanged = 0; + kAdded = 1; + kRemoved = 2; + } + + bitmap Feature : bitmap32 { + kExtension = 0x1; + kManagedDevice = 0x2; + } + + struct AccessRestrictionStruct { + AccessRestrictionTypeEnum type = 0; + nullable int32u id = 1; + } + + struct CommissioningAccessRestrictionEntryStruct { + endpoint_no endpoint = 0; + cluster_id cluster = 1; + AccessRestrictionStruct restrictions[] = 2; + } + + fabric_scoped struct AccessRestrictionEntryStruct { + fabric_sensitive endpoint_no endpoint = 0; + fabric_sensitive cluster_id cluster = 1; + fabric_sensitive AccessRestrictionStruct restrictions[] = 2; + fabric_idx fabricIndex = 254; + } + + struct AccessControlTargetStruct { + nullable cluster_id cluster = 0; + nullable endpoint_no endpoint = 1; + nullable devtype_id deviceType = 2; + } + + fabric_scoped struct AccessControlEntryStruct { + fabric_sensitive AccessControlEntryPrivilegeEnum privilege = 1; + fabric_sensitive AccessControlEntryAuthModeEnum authMode = 2; + nullable fabric_sensitive int64u subjects[] = 3; + nullable fabric_sensitive AccessControlTargetStruct targets[] = 4; + fabric_idx fabricIndex = 254; + } + + fabric_scoped struct AccessControlExtensionStruct { + fabric_sensitive octet_string<128> data = 1; + fabric_idx fabricIndex = 254; + } + + fabric_sensitive info event access(read: administer) AccessControlEntryChanged = 0 { + nullable node_id adminNodeID = 1; + nullable int16u adminPasscodeID = 2; + ChangeTypeEnum changeType = 3; + nullable AccessControlEntryStruct latestValue = 4; + fabric_idx fabricIndex = 254; + } + + fabric_sensitive info event access(read: administer) AccessControlExtensionChanged = 1 { + nullable node_id adminNodeID = 1; + nullable int16u adminPasscodeID = 2; + ChangeTypeEnum changeType = 3; + nullable AccessControlExtensionStruct latestValue = 4; + fabric_idx fabricIndex = 254; + } + + fabric_sensitive info event access(read: administer) FabricRestrictionReviewUpdate = 2 { + int64u token = 0; + optional long_char_string instruction = 1; + optional long_char_string ARLRequestFlowUrl = 2; + fabric_idx fabricIndex = 254; + } + + attribute access(read: administer, write: administer) AccessControlEntryStruct acl[] = 0; + attribute access(read: administer, write: administer) optional AccessControlExtensionStruct extension[] = 1; + readonly attribute int16u subjectsPerAccessControlEntry = 2; + readonly attribute int16u targetsPerAccessControlEntry = 3; + readonly attribute int16u accessControlEntriesPerFabric = 4; + readonly attribute optional CommissioningAccessRestrictionEntryStruct commissioningARL[] = 5; + readonly attribute optional AccessRestrictionEntryStruct arl[] = 6; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct ReviewFabricRestrictionsRequest { + CommissioningAccessRestrictionEntryStruct arl[] = 0; + } + + response struct ReviewFabricRestrictionsResponse = 1 { + int64u token = 0; + } + + /** This command signals to the service associated with the device vendor that the fabric administrator would like a review of the current restrictions on the accessing fabric. */ + fabric command access(invoke: administer) ReviewFabricRestrictions(ReviewFabricRestrictionsRequest): ReviewFabricRestrictionsResponse = 0; +} + +/** This cluster provides attributes and events for determining basic information about Nodes, which supports both + Commissioning and operational determination of Node characteristics, such as Vendor ID, Product ID and serial number, + which apply to the whole Node. Also allows setting user device information such as location. */ +cluster BasicInformation = 40 { + revision 3; + + enum ColorEnum : enum8 { + kBlack = 0; + kNavy = 1; + kGreen = 2; + kTeal = 3; + kMaroon = 4; + kPurple = 5; + kOlive = 6; + kGray = 7; + kBlue = 8; + kLime = 9; + kAqua = 10; + kRed = 11; + kFuchsia = 12; + kYellow = 13; + kWhite = 14; + kNickel = 15; + kChrome = 16; + kBrass = 17; + kCopper = 18; + kSilver = 19; + kGold = 20; + } + + enum ProductFinishEnum : enum8 { + kOther = 0; + kMatte = 1; + kSatin = 2; + kPolished = 3; + kRugged = 4; + kFabric = 5; + } + + struct CapabilityMinimaStruct { + int16u caseSessionsPerFabric = 0; + int16u subscriptionsPerFabric = 1; + } + + struct ProductAppearanceStruct { + ProductFinishEnum finish = 0; + nullable ColorEnum primaryColor = 1; + } + + critical event StartUp = 0 { + int32u softwareVersion = 0; + } + + critical event ShutDown = 1 { + } + + info event Leave = 2 { + fabric_idx fabricIndex = 0; + } + + info event ReachableChanged = 3 { + boolean reachableNewValue = 0; + } + + readonly attribute int16u dataModelRevision = 0; + readonly attribute char_string<32> vendorName = 1; + readonly attribute vendor_id vendorID = 2; + readonly attribute char_string<32> productName = 3; + readonly attribute int16u productID = 4; + attribute access(write: manage) char_string<32> nodeLabel = 5; + attribute access(write: administer) char_string<2> location = 6; + readonly attribute int16u hardwareVersion = 7; + readonly attribute char_string<64> hardwareVersionString = 8; + readonly attribute int32u softwareVersion = 9; + readonly attribute char_string<64> softwareVersionString = 10; + readonly attribute optional char_string<16> manufacturingDate = 11; + readonly attribute optional char_string<32> partNumber = 12; + readonly attribute optional long_char_string<256> productURL = 13; + readonly attribute optional char_string<64> productLabel = 14; + readonly attribute optional char_string<32> serialNumber = 15; + attribute access(write: manage) optional boolean localConfigDisabled = 16; + readonly attribute optional boolean reachable = 17; + readonly attribute char_string<32> uniqueID = 18; + readonly attribute CapabilityMinimaStruct capabilityMinima = 19; + readonly attribute optional ProductAppearanceStruct productAppearance = 20; + readonly attribute int32u specificationVersion = 21; + readonly attribute int16u maxPathsPerInvoke = 22; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + command MfgSpecificPing(): DefaultSuccess = 0; +} + +/** Nodes should be expected to be deployed to any and all regions of the world. These global regions + may have differing common languages, units of measurements, and numerical formatting + standards. As such, Nodes that visually or audibly convey information need a mechanism by which + they can be configured to use a user’s preferred language, units, etc */ +cluster LocalizationConfiguration = 43 { + revision 1; // NOTE: Default/not specifically set + + attribute access(write: manage) char_string<35> activeLocale = 0; + readonly attribute char_string supportedLocales[] = 1; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** This cluster is used to describe the configuration and capabilities of a physical power source that provides power to the Node. */ +cluster PowerSource = 47 { + revision 1; // NOTE: Default/not specifically set + + enum BatApprovedChemistryEnum : enum16 { + kUnspecified = 0; + kAlkaline = 1; + kLithiumCarbonFluoride = 2; + kLithiumChromiumOxide = 3; + kLithiumCopperOxide = 4; + kLithiumIronDisulfide = 5; + kLithiumManganeseDioxide = 6; + kLithiumThionylChloride = 7; + kMagnesium = 8; + kMercuryOxide = 9; + kNickelOxyhydride = 10; + kSilverOxide = 11; + kZincAir = 12; + kZincCarbon = 13; + kZincChloride = 14; + kZincManganeseDioxide = 15; + kLeadAcid = 16; + kLithiumCobaltOxide = 17; + kLithiumIon = 18; + kLithiumIonPolymer = 19; + kLithiumIronPhosphate = 20; + kLithiumSulfur = 21; + kLithiumTitanate = 22; + kNickelCadmium = 23; + kNickelHydrogen = 24; + kNickelIron = 25; + kNickelMetalHydride = 26; + kNickelZinc = 27; + kSilverZinc = 28; + kSodiumIon = 29; + kSodiumSulfur = 30; + kZincBromide = 31; + kZincCerium = 32; + } + + enum BatChargeFaultEnum : enum8 { + kUnspecified = 0; + kAmbientTooHot = 1; + kAmbientTooCold = 2; + kBatteryTooHot = 3; + kBatteryTooCold = 4; + kBatteryAbsent = 5; + kBatteryOverVoltage = 6; + kBatteryUnderVoltage = 7; + kChargerOverVoltage = 8; + kChargerUnderVoltage = 9; + kSafetyTimeout = 10; + } + + enum BatChargeLevelEnum : enum8 { + kOK = 0; + kWarning = 1; + kCritical = 2; + } + + enum BatChargeStateEnum : enum8 { + kUnknown = 0; + kIsCharging = 1; + kIsAtFullCharge = 2; + kIsNotCharging = 3; + } + + enum BatCommonDesignationEnum : enum16 { + kUnspecified = 0; + kAAA = 1; + kAA = 2; + kC = 3; + kD = 4; + k4v5 = 5; + k6v0 = 6; + k9v0 = 7; + k12AA = 8; + kAAAA = 9; + kA = 10; + kB = 11; + kF = 12; + kN = 13; + kNo6 = 14; + kSubC = 15; + kA23 = 16; + kA27 = 17; + kBA5800 = 18; + kDuplex = 19; + k4SR44 = 20; + k523 = 21; + k531 = 22; + k15v0 = 23; + k22v5 = 24; + k30v0 = 25; + k45v0 = 26; + k67v5 = 27; + kJ = 28; + kCR123A = 29; + kCR2 = 30; + k2CR5 = 31; + kCRP2 = 32; + kCRV3 = 33; + kSR41 = 34; + kSR43 = 35; + kSR44 = 36; + kSR45 = 37; + kSR48 = 38; + kSR54 = 39; + kSR55 = 40; + kSR57 = 41; + kSR58 = 42; + kSR59 = 43; + kSR60 = 44; + kSR63 = 45; + kSR64 = 46; + kSR65 = 47; + kSR66 = 48; + kSR67 = 49; + kSR68 = 50; + kSR69 = 51; + kSR516 = 52; + kSR731 = 53; + kSR712 = 54; + kLR932 = 55; + kA5 = 56; + kA10 = 57; + kA13 = 58; + kA312 = 59; + kA675 = 60; + kAC41E = 61; + k10180 = 62; + k10280 = 63; + k10440 = 64; + k14250 = 65; + k14430 = 66; + k14500 = 67; + k14650 = 68; + k15270 = 69; + k16340 = 70; + kRCR123A = 71; + k17500 = 72; + k17670 = 73; + k18350 = 74; + k18500 = 75; + k18650 = 76; + k19670 = 77; + k25500 = 78; + k26650 = 79; + k32600 = 80; + } + + enum BatFaultEnum : enum8 { + kUnspecified = 0; + kOverTemp = 1; + kUnderTemp = 2; + } + + enum BatReplaceabilityEnum : enum8 { + kUnspecified = 0; + kNotReplaceable = 1; + kUserReplaceable = 2; + kFactoryReplaceable = 3; + } + + enum PowerSourceStatusEnum : enum8 { + kUnspecified = 0; + kActive = 1; + kStandby = 2; + kUnavailable = 3; + } + + enum WiredCurrentTypeEnum : enum8 { + kAC = 0; + kDC = 1; + } + + enum WiredFaultEnum : enum8 { + kUnspecified = 0; + kOverVoltage = 1; + kUnderVoltage = 2; + } + + bitmap Feature : bitmap32 { + kWired = 0x1; + kBattery = 0x2; + kRechargeable = 0x4; + kReplaceable = 0x8; + } + + struct BatChargeFaultChangeType { + BatChargeFaultEnum current[] = 0; + BatChargeFaultEnum previous[] = 1; + } + + struct BatFaultChangeType { + BatFaultEnum current[] = 0; + BatFaultEnum previous[] = 1; + } + + struct WiredFaultChangeType { + WiredFaultEnum current[] = 0; + WiredFaultEnum previous[] = 1; + } + + info event WiredFaultChange = 0 { + WiredFaultEnum current[] = 0; + WiredFaultEnum previous[] = 1; + } + + info event BatFaultChange = 1 { + BatFaultEnum current[] = 0; + BatFaultEnum previous[] = 1; + } + + info event BatChargeFaultChange = 2 { + BatChargeFaultEnum current[] = 0; + BatChargeFaultEnum previous[] = 1; + } + + readonly attribute PowerSourceStatusEnum status = 0; + readonly attribute int8u order = 1; + readonly attribute char_string<60> description = 2; + readonly attribute optional nullable int32u wiredAssessedInputVoltage = 3; + readonly attribute optional nullable int16u wiredAssessedInputFrequency = 4; + readonly attribute optional WiredCurrentTypeEnum wiredCurrentType = 5; + readonly attribute optional nullable int32u wiredAssessedCurrent = 6; + readonly attribute optional int32u wiredNominalVoltage = 7; + readonly attribute optional int32u wiredMaximumCurrent = 8; + readonly attribute optional boolean wiredPresent = 9; + readonly attribute optional WiredFaultEnum activeWiredFaults[] = 10; + readonly attribute optional nullable int32u batVoltage = 11; + readonly attribute optional nullable int8u batPercentRemaining = 12; + readonly attribute optional nullable int32u batTimeRemaining = 13; + readonly attribute optional BatChargeLevelEnum batChargeLevel = 14; + readonly attribute optional boolean batReplacementNeeded = 15; + readonly attribute optional BatReplaceabilityEnum batReplaceability = 16; + readonly attribute optional boolean batPresent = 17; + readonly attribute optional BatFaultEnum activeBatFaults[] = 18; + readonly attribute optional char_string<60> batReplacementDescription = 19; + readonly attribute optional BatCommonDesignationEnum batCommonDesignation = 20; + readonly attribute optional char_string<20> batANSIDesignation = 21; + readonly attribute optional char_string<20> batIECDesignation = 22; + readonly attribute optional BatApprovedChemistryEnum batApprovedChemistry = 23; + readonly attribute optional int32u batCapacity = 24; + readonly attribute optional int8u batQuantity = 25; + readonly attribute optional BatChargeStateEnum batChargeState = 26; + readonly attribute optional nullable int32u batTimeToFullCharge = 27; + readonly attribute optional boolean batFunctionalWhileCharging = 28; + readonly attribute optional nullable int32u batChargingCurrent = 29; + readonly attribute optional BatChargeFaultEnum activeBatChargeFaults[] = 30; + readonly attribute endpoint_no endpointList[] = 31; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** This cluster is used to manage global aspects of the Commissioning flow. */ +cluster GeneralCommissioning = 48 { + revision 1; // NOTE: Default/not specifically set + + enum CommissioningErrorEnum : enum8 { + kOK = 0; + kValueOutsideRange = 1; + kInvalidAuthentication = 2; + kNoFailSafe = 3; + kBusyWithOtherAdmin = 4; + kRequiredTCNotAccepted = 5; + kTCAcknowledgementsNotReceived = 6; + kTCMinVersionNotMet = 7; + } + + enum RegulatoryLocationTypeEnum : enum8 { + kIndoor = 0; + kOutdoor = 1; + kIndoorOutdoor = 2; + } + + bitmap Feature : bitmap32 { + kTermsAndConditions = 0x1; + } + + struct BasicCommissioningInfo { + int16u failSafeExpiryLengthSeconds = 0; + int16u maxCumulativeFailsafeSeconds = 1; + } + + attribute access(write: administer) int64u breadcrumb = 0; + readonly attribute BasicCommissioningInfo basicCommissioningInfo = 1; + readonly attribute RegulatoryLocationTypeEnum regulatoryConfig = 2; + readonly attribute RegulatoryLocationTypeEnum locationCapability = 3; + readonly attribute boolean supportsConcurrentConnection = 4; + provisional readonly attribute access(read: administer) optional int16u TCAcceptedVersion = 5; + provisional readonly attribute access(read: administer) optional int16u TCMinRequiredVersion = 6; + provisional readonly attribute access(read: administer) optional bitmap16 TCAcknowledgements = 7; + provisional readonly attribute access(read: administer) optional boolean TCAcknowledgementsRequired = 8; + provisional readonly attribute access(read: administer) optional int32u TCUpdateDeadline = 9; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct ArmFailSafeRequest { + int16u expiryLengthSeconds = 0; + int64u breadcrumb = 1; + } + + response struct ArmFailSafeResponse = 1 { + CommissioningErrorEnum errorCode = 0; + char_string<128> debugText = 1; + } + + request struct SetRegulatoryConfigRequest { + RegulatoryLocationTypeEnum newRegulatoryConfig = 0; + char_string<2> countryCode = 1; + int64u breadcrumb = 2; + } + + response struct SetRegulatoryConfigResponse = 3 { + CommissioningErrorEnum errorCode = 0; + char_string debugText = 1; + } + + response struct CommissioningCompleteResponse = 5 { + CommissioningErrorEnum errorCode = 0; + char_string debugText = 1; + } + + request struct SetTCAcknowledgementsRequest { + int16u TCVersion = 0; + bitmap16 TCUserResponse = 1; + } + + response struct SetTCAcknowledgementsResponse = 7 { + CommissioningErrorEnum errorCode = 0; + } + + /** Arm the persistent fail-safe timer with an expiry time of now + ExpiryLengthSeconds using device clock */ + command access(invoke: administer) ArmFailSafe(ArmFailSafeRequest): ArmFailSafeResponse = 0; + /** Set the regulatory configuration to be used during commissioning */ + command access(invoke: administer) SetRegulatoryConfig(SetRegulatoryConfigRequest): SetRegulatoryConfigResponse = 2; + /** Signals the Server that the Client has successfully completed all steps of Commissioning/Recofiguration needed during fail-safe period. */ + fabric command access(invoke: administer) CommissioningComplete(): CommissioningCompleteResponse = 4; + /** This command sets the user acknowledgements received in the Enhanced Setup Flow Terms and Conditions into the node. */ + command access(invoke: administer) SetTCAcknowledgements(SetTCAcknowledgementsRequest): SetTCAcknowledgementsResponse = 6; +} + +/** Functionality to configure, enable, disable network credentials and access on a Matter device. */ +cluster NetworkCommissioning = 49 { + revision 1; // NOTE: Default/not specifically set + + enum NetworkCommissioningStatusEnum : enum8 { + kSuccess = 0; + kOutOfRange = 1; + kBoundsExceeded = 2; + kNetworkIDNotFound = 3; + kDuplicateNetworkID = 4; + kNetworkNotFound = 5; + kRegulatoryError = 6; + kAuthFailure = 7; + kUnsupportedSecurity = 8; + kOtherConnectionFailure = 9; + kIPV6Failed = 10; + kIPBindFailed = 11; + kUnknownError = 12; + } + + enum WiFiBandEnum : enum8 { + k2G4 = 0; + k3G65 = 1; + k5G = 2; + k6G = 3; + k60G = 4; + k1G = 5; + } + + bitmap Feature : bitmap32 { + kWiFiNetworkInterface = 0x1; + kThreadNetworkInterface = 0x2; + kEthernetNetworkInterface = 0x4; + kPerDeviceCredentials = 0x8; + } + + bitmap ThreadCapabilitiesBitmap : bitmap16 { + kIsBorderRouterCapable = 0x1; + kIsRouterCapable = 0x2; + kIsSleepyEndDeviceCapable = 0x4; + kIsFullThreadDevice = 0x8; + kIsSynchronizedSleepyEndDeviceCapable = 0x10; + } + + bitmap WiFiSecurityBitmap : bitmap8 { + kUnencrypted = 0x1; + kWEP = 0x2; + kWPAPersonal = 0x4; + kWPA2Personal = 0x8; + kWPA3Personal = 0x10; + kWPA3MatterPDC = 0x20; + } + + struct NetworkInfoStruct { + octet_string<32> networkID = 0; + boolean connected = 1; + optional nullable octet_string<20> networkIdentifier = 2; + optional nullable octet_string<20> clientIdentifier = 3; + } + + struct ThreadInterfaceScanResultStruct { + int16u panId = 0; + int64u extendedPanId = 1; + char_string<16> networkName = 2; + int16u channel = 3; + int8u version = 4; + octet_string<8> extendedAddress = 5; + int8s rssi = 6; + int8u lqi = 7; + } + + struct WiFiInterfaceScanResultStruct { + WiFiSecurityBitmap security = 0; + octet_string<32> ssid = 1; + octet_string<6> bssid = 2; + int16u channel = 3; + WiFiBandEnum wiFiBand = 4; + int8s rssi = 5; + } + + readonly attribute access(read: administer) int8u maxNetworks = 0; + readonly attribute access(read: administer) NetworkInfoStruct networks[] = 1; + readonly attribute optional int8u scanMaxTimeSeconds = 2; + readonly attribute optional int8u connectMaxTimeSeconds = 3; + attribute access(write: administer) boolean interfaceEnabled = 4; + readonly attribute access(read: administer) nullable NetworkCommissioningStatusEnum lastNetworkingStatus = 5; + readonly attribute access(read: administer) nullable octet_string<32> lastNetworkID = 6; + readonly attribute access(read: administer) nullable int32s lastConnectErrorValue = 7; + provisional readonly attribute optional WiFiBandEnum supportedWiFiBands[] = 8; + provisional readonly attribute optional ThreadCapabilitiesBitmap supportedThreadFeatures = 9; + provisional readonly attribute optional int16u threadVersion = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct ScanNetworksRequest { + optional nullable octet_string<32> ssid = 0; + optional int64u breadcrumb = 1; + } + + response struct ScanNetworksResponse = 1 { + NetworkCommissioningStatusEnum networkingStatus = 0; + optional char_string debugText = 1; + optional WiFiInterfaceScanResultStruct wiFiScanResults[] = 2; + optional ThreadInterfaceScanResultStruct threadScanResults[] = 3; + } + + request struct AddOrUpdateWiFiNetworkRequest { + octet_string<32> ssid = 0; + octet_string<64> credentials = 1; + optional int64u breadcrumb = 2; + optional octet_string<140> networkIdentity = 3; + optional octet_string<20> clientIdentifier = 4; + optional octet_string<32> possessionNonce = 5; + } + + request struct AddOrUpdateThreadNetworkRequest { + octet_string<254> operationalDataset = 0; + optional int64u breadcrumb = 1; + } + + request struct RemoveNetworkRequest { + octet_string<32> networkID = 0; + optional int64u breadcrumb = 1; + } + + response struct NetworkConfigResponse = 5 { + NetworkCommissioningStatusEnum networkingStatus = 0; + optional char_string<512> debugText = 1; + optional int8u networkIndex = 2; + optional octet_string<140> clientIdentity = 3; + optional octet_string<64> possessionSignature = 4; + } + + request struct ConnectNetworkRequest { + octet_string<32> networkID = 0; + optional int64u breadcrumb = 1; + } + + response struct ConnectNetworkResponse = 7 { + NetworkCommissioningStatusEnum networkingStatus = 0; + optional char_string debugText = 1; + nullable int32s errorValue = 2; + } + + request struct ReorderNetworkRequest { + octet_string<32> networkID = 0; + int8u networkIndex = 1; + optional int64u breadcrumb = 2; + } + + request struct QueryIdentityRequest { + octet_string<20> keyIdentifier = 0; + optional octet_string<32> possessionNonce = 1; + } + + response struct QueryIdentityResponse = 10 { + octet_string<140> identity = 0; + optional octet_string<64> possessionSignature = 1; + } + + /** Detemine the set of networks the device sees as available. */ + command access(invoke: administer) ScanNetworks(ScanNetworksRequest): ScanNetworksResponse = 0; + /** Add or update the credentials for a given Wi-Fi network. */ + command access(invoke: administer) AddOrUpdateWiFiNetwork(AddOrUpdateWiFiNetworkRequest): NetworkConfigResponse = 2; + /** Add or update the credentials for a given Thread network. */ + command access(invoke: administer) AddOrUpdateThreadNetwork(AddOrUpdateThreadNetworkRequest): NetworkConfigResponse = 3; + /** Remove the definition of a given network (including its credentials). */ + command access(invoke: administer) RemoveNetwork(RemoveNetworkRequest): NetworkConfigResponse = 4; + /** Connect to the specified network, using previously-defined credentials. */ + command access(invoke: administer) ConnectNetwork(ConnectNetworkRequest): ConnectNetworkResponse = 6; + /** Modify the order in which networks will be presented in the Networks attribute. */ + command access(invoke: administer) ReorderNetwork(ReorderNetworkRequest): NetworkConfigResponse = 8; + /** Retrieve details about and optionally proof of possession of a network client identity. */ + command access(invoke: administer) QueryIdentity(QueryIdentityRequest): QueryIdentityResponse = 9; +} + +/** The cluster provides commands for retrieving unstructured diagnostic logs from a Node that may be used to aid in diagnostics. */ +cluster DiagnosticLogs = 50 { + revision 1; // NOTE: Default/not specifically set + + enum IntentEnum : enum8 { + kEndUserSupport = 0; + kNetworkDiag = 1; + kCrashLogs = 2; + } + + enum StatusEnum : enum8 { + kSuccess = 0; + kExhausted = 1; + kNoLogs = 2; + kBusy = 3; + kDenied = 4; + } + + enum TransferProtocolEnum : enum8 { + kResponsePayload = 0; + kBDX = 1; + } + + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct RetrieveLogsRequestRequest { + IntentEnum intent = 0; + TransferProtocolEnum requestedProtocol = 1; + optional char_string<32> transferFileDesignator = 2; + } + + response struct RetrieveLogsResponse = 1 { + StatusEnum status = 0; + long_octet_string logContent = 1; + optional epoch_us UTCTimeStamp = 2; + optional systime_us timeSinceBoot = 3; + } + + /** Retrieving diagnostic logs from a Node */ + command RetrieveLogsRequest(RetrieveLogsRequestRequest): RetrieveLogsResponse = 0; +} + +/** The General Diagnostics Cluster, along with other diagnostics clusters, provide a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. */ +cluster GeneralDiagnostics = 51 { + revision 2; + + enum BootReasonEnum : enum8 { + kUnspecified = 0; + kPowerOnReboot = 1; + kBrownOutReset = 2; + kSoftwareWatchdogReset = 3; + kHardwareWatchdogReset = 4; + kSoftwareUpdateCompleted = 5; + kSoftwareReset = 6; + } + + enum HardwareFaultEnum : enum8 { + kUnspecified = 0; + kRadio = 1; + kSensor = 2; + kResettableOverTemp = 3; + kNonResettableOverTemp = 4; + kPowerSource = 5; + kVisualDisplayFault = 6; + kAudioOutputFault = 7; + kUserInterfaceFault = 8; + kNonVolatileMemoryError = 9; + kTamperDetected = 10; + } + + enum InterfaceTypeEnum : enum8 { + kUnspecified = 0; + kWiFi = 1; + kEthernet = 2; + kCellular = 3; + kThread = 4; + } + + enum NetworkFaultEnum : enum8 { + kUnspecified = 0; + kHardwareFailure = 1; + kNetworkJammed = 2; + kConnectionFailed = 3; + } + + enum RadioFaultEnum : enum8 { + kUnspecified = 0; + kWiFiFault = 1; + kCellularFault = 2; + kThreadFault = 3; + kNFCFault = 4; + kBLEFault = 5; + kEthernetFault = 6; + } + + bitmap Feature : bitmap32 { + kDataModelTest = 0x1; + } + + struct NetworkInterface { + char_string<32> name = 0; + boolean isOperational = 1; + nullable boolean offPremiseServicesReachableIPv4 = 2; + nullable boolean offPremiseServicesReachableIPv6 = 3; + octet_string<8> hardwareAddress = 4; + octet_string IPv4Addresses[] = 5; + octet_string IPv6Addresses[] = 6; + InterfaceTypeEnum type = 7; + } + + critical event HardwareFaultChange = 0 { + HardwareFaultEnum current[] = 0; + HardwareFaultEnum previous[] = 1; + } + + critical event RadioFaultChange = 1 { + RadioFaultEnum current[] = 0; + RadioFaultEnum previous[] = 1; + } + + critical event NetworkFaultChange = 2 { + NetworkFaultEnum current[] = 0; + NetworkFaultEnum previous[] = 1; + } + + critical event BootReason = 3 { + BootReasonEnum bootReason = 0; + } + + readonly attribute NetworkInterface networkInterfaces[] = 0; + readonly attribute int16u rebootCount = 1; + readonly attribute optional int64u upTime = 2; + readonly attribute optional int32u totalOperationalHours = 3; + readonly attribute optional BootReasonEnum bootReason = 4; + readonly attribute optional HardwareFaultEnum activeHardwareFaults[] = 5; + readonly attribute optional RadioFaultEnum activeRadioFaults[] = 6; + readonly attribute optional NetworkFaultEnum activeNetworkFaults[] = 7; + readonly attribute boolean testEventTriggersEnabled = 8; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct TestEventTriggerRequest { + octet_string<16> enableKey = 0; + int64u eventTrigger = 1; + } + + response struct TimeSnapshotResponse = 2 { + systime_ms systemTimeMs = 0; + nullable posix_ms posixTimeMs = 1; + } + + request struct PayloadTestRequestRequest { + octet_string<16> enableKey = 0; + int8u value = 1; + int16u count = 2; + } + + response struct PayloadTestResponse = 4 { + octet_string payload = 0; + } + + /** Provide a means for certification tests to trigger some test-plan-specific events */ + command access(invoke: manage) TestEventTrigger(TestEventTriggerRequest): DefaultSuccess = 0; + /** Take a snapshot of system time and epoch time. */ + command TimeSnapshot(): TimeSnapshotResponse = 1; + /** Request a variable length payload response. */ + command PayloadTestRequest(PayloadTestRequestRequest): PayloadTestResponse = 3; +} + +/** The Software Diagnostics Cluster provides a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. */ +cluster SoftwareDiagnostics = 52 { + revision 1; // NOTE: Default/not specifically set + + bitmap Feature : bitmap32 { + kWatermarks = 0x1; + } + + struct ThreadMetricsStruct { + int64u id = 0; + optional char_string<8> name = 1; + optional int32u stackFreeCurrent = 2; + optional int32u stackFreeMinimum = 3; + optional int32u stackSize = 4; + } + + info event SoftwareFault = 0 { + int64u id = 0; + optional char_string name = 1; + optional octet_string faultRecording = 2; + } + + readonly attribute optional ThreadMetricsStruct threadMetrics[] = 0; + readonly attribute optional int64u currentHeapFree = 1; + readonly attribute optional int64u currentHeapUsed = 2; + readonly attribute optional int64u currentHeapHighWatermark = 3; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + /** Reception of this command SHALL reset the values: The StackFreeMinimum field of the ThreadMetrics attribute, CurrentHeapHighWaterMark attribute. */ + command access(invoke: manage) ResetWatermarks(): DefaultSuccess = 0; +} + +/** Commands to trigger a Node to allow a new Administrator to commission it. */ +cluster AdministratorCommissioning = 60 { + revision 1; // NOTE: Default/not specifically set + + enum CommissioningWindowStatusEnum : enum8 { + kWindowNotOpen = 0; + kEnhancedWindowOpen = 1; + kBasicWindowOpen = 2; + } + + enum StatusCode : enum8 { + kBusy = 2; + kPAKEParameterError = 3; + kWindowNotOpen = 4; + } + + bitmap Feature : bitmap32 { + kBasic = 0x1; + } + + readonly attribute CommissioningWindowStatusEnum windowStatus = 0; + readonly attribute nullable fabric_idx adminFabricIndex = 1; + readonly attribute nullable vendor_id adminVendorId = 2; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct OpenCommissioningWindowRequest { + int16u commissioningTimeout = 0; + octet_string PAKEPasscodeVerifier = 1; + int16u discriminator = 2; + int32u iterations = 3; + octet_string<32> salt = 4; + } + + request struct OpenBasicCommissioningWindowRequest { + int16u commissioningTimeout = 0; + } + + /** This command is used by a current Administrator to instruct a Node to go into commissioning mode using enhanced commissioning method. */ + timed command access(invoke: administer) OpenCommissioningWindow(OpenCommissioningWindowRequest): DefaultSuccess = 0; + /** This command is used by a current Administrator to instruct a Node to go into commissioning mode using basic commissioning method, if the node supports it. */ + timed command access(invoke: administer) OpenBasicCommissioningWindow(OpenBasicCommissioningWindowRequest): DefaultSuccess = 1; + /** This command is used by a current Administrator to instruct a Node to revoke any active Open Commissioning Window or Open Basic Commissioning Window command. */ + timed command access(invoke: administer) RevokeCommissioning(): DefaultSuccess = 2; +} + +/** This cluster is used to add or remove Operational Credentials on a Commissionee or Node, as well as manage the associated Fabrics. */ +cluster OperationalCredentials = 62 { + revision 1; // NOTE: Default/not specifically set + + enum CertificateChainTypeEnum : enum8 { + kDACCertificate = 1; + kPAICertificate = 2; + } + + enum NodeOperationalCertStatusEnum : enum8 { + kOK = 0; + kInvalidPublicKey = 1; + kInvalidNodeOpId = 2; + kInvalidNOC = 3; + kMissingCsr = 4; + kTableFull = 5; + kInvalidAdminSubject = 6; + kFabricConflict = 9; + kLabelConflict = 10; + kInvalidFabricIndex = 11; + } + + fabric_scoped struct FabricDescriptorStruct { + octet_string<65> rootPublicKey = 1; + vendor_id vendorID = 2; + fabric_id fabricID = 3; + node_id nodeID = 4; + char_string<32> label = 5; + fabric_idx fabricIndex = 254; + } + + fabric_scoped struct NOCStruct { + fabric_sensitive octet_string noc = 1; + nullable fabric_sensitive octet_string icac = 2; + fabric_idx fabricIndex = 254; + } + + readonly attribute access(read: administer) NOCStruct NOCs[] = 0; + readonly attribute FabricDescriptorStruct fabrics[] = 1; + readonly attribute int8u supportedFabrics = 2; + readonly attribute int8u commissionedFabrics = 3; + readonly attribute octet_string trustedRootCertificates[] = 4; + readonly attribute int8u currentFabricIndex = 5; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct AttestationRequestRequest { + octet_string<32> attestationNonce = 0; + } + + response struct AttestationResponse = 1 { + octet_string<900> attestationElements = 0; + octet_string<64> attestationSignature = 1; + } + + request struct CertificateChainRequestRequest { + CertificateChainTypeEnum certificateType = 0; + } + + response struct CertificateChainResponse = 3 { + octet_string<600> certificate = 0; + } + + request struct CSRRequestRequest { + octet_string<32> CSRNonce = 0; + optional boolean isForUpdateNOC = 1; + } + + response struct CSRResponse = 5 { + octet_string NOCSRElements = 0; + octet_string attestationSignature = 1; + } + + request struct AddNOCRequest { + octet_string<400> NOCValue = 0; + optional octet_string<400> ICACValue = 1; + octet_string<16> IPKValue = 2; + int64u caseAdminSubject = 3; + vendor_id adminVendorId = 4; + } + + request struct UpdateNOCRequest { + octet_string NOCValue = 0; + optional octet_string ICACValue = 1; + } + + response struct NOCResponse = 8 { + NodeOperationalCertStatusEnum statusCode = 0; + optional fabric_idx fabricIndex = 1; + optional char_string<128> debugText = 2; + } + + request struct UpdateFabricLabelRequest { + char_string<32> label = 0; + } + + request struct RemoveFabricRequest { + fabric_idx fabricIndex = 0; + } + + request struct AddTrustedRootCertificateRequest { + octet_string rootCACertificate = 0; + } + + /** Sender is requesting attestation information from the receiver. */ + command access(invoke: administer) AttestationRequest(AttestationRequestRequest): AttestationResponse = 0; + /** Sender is requesting a device attestation certificate from the receiver. */ + command access(invoke: administer) CertificateChainRequest(CertificateChainRequestRequest): CertificateChainResponse = 2; + /** Sender is requesting a certificate signing request (CSR) from the receiver. */ + command access(invoke: administer) CSRRequest(CSRRequestRequest): CSRResponse = 4; + /** Sender is requesting to add the new node operational certificates. */ + command access(invoke: administer) AddNOC(AddNOCRequest): NOCResponse = 6; + /** Sender is requesting to update the node operational certificates. */ + fabric command access(invoke: administer) UpdateNOC(UpdateNOCRequest): NOCResponse = 7; + /** This command SHALL be used by an Administrative Node to set the user-visible Label field for a given Fabric, as reflected by entries in the Fabrics attribute. */ + fabric command access(invoke: administer) UpdateFabricLabel(UpdateFabricLabelRequest): NOCResponse = 9; + /** This command is used by Administrative Nodes to remove a given fabric index and delete all associated fabric-scoped data. */ + command access(invoke: administer) RemoveFabric(RemoveFabricRequest): NOCResponse = 10; + /** This command SHALL add a Trusted Root CA Certificate, provided as its CHIP Certificate representation. */ + command access(invoke: administer) AddTrustedRootCertificate(AddTrustedRootCertificateRequest): DefaultSuccess = 11; +} + +/** The Group Key Management Cluster is the mechanism by which group keys are managed. */ +cluster GroupKeyManagement = 63 { + revision 1; // NOTE: Default/not specifically set + + enum GroupKeySecurityPolicyEnum : enum8 { + kTrustFirst = 0; + kCacheAndSync = 1; + } + + bitmap Feature : bitmap32 { + kCacheAndSync = 0x1; + } + + fabric_scoped struct GroupInfoMapStruct { + group_id groupId = 1; + endpoint_no endpoints[] = 2; + optional char_string<16> groupName = 3; + fabric_idx fabricIndex = 254; + } + + fabric_scoped struct GroupKeyMapStruct { + group_id groupId = 1; + int16u groupKeySetID = 2; + fabric_idx fabricIndex = 254; + } + + struct GroupKeySetStruct { + int16u groupKeySetID = 0; + GroupKeySecurityPolicyEnum groupKeySecurityPolicy = 1; + nullable octet_string<16> epochKey0 = 2; + nullable epoch_us epochStartTime0 = 3; + nullable octet_string<16> epochKey1 = 4; + nullable epoch_us epochStartTime1 = 5; + nullable octet_string<16> epochKey2 = 6; + nullable epoch_us epochStartTime2 = 7; + } + + attribute access(write: manage) GroupKeyMapStruct groupKeyMap[] = 0; + readonly attribute GroupInfoMapStruct groupTable[] = 1; + readonly attribute int16u maxGroupsPerFabric = 2; + readonly attribute int16u maxGroupKeysPerFabric = 3; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct KeySetWriteRequest { + GroupKeySetStruct groupKeySet = 0; + } + + request struct KeySetReadRequest { + int16u groupKeySetID = 0; + } + + response struct KeySetReadResponse = 2 { + GroupKeySetStruct groupKeySet = 0; + } + + request struct KeySetRemoveRequest { + int16u groupKeySetID = 0; + } + + response struct KeySetReadAllIndicesResponse = 5 { + int16u groupKeySetIDs[] = 0; + } + + /** Write a new set of keys for the given key set id. */ + fabric command access(invoke: administer) KeySetWrite(KeySetWriteRequest): DefaultSuccess = 0; + /** Read the keys for a given key set id. */ + fabric command access(invoke: administer) KeySetRead(KeySetReadRequest): KeySetReadResponse = 1; + /** Revoke a Root Key from a Group */ + fabric command access(invoke: administer) KeySetRemove(KeySetRemoveRequest): DefaultSuccess = 3; + /** Return the list of Group Key Sets associated with the accessing fabric */ + fabric command access(invoke: administer) KeySetReadAllIndices(): KeySetReadAllIndicesResponse = 4; +} + +/** The Fixed Label Cluster provides a feature for the device to tag an endpoint with zero or more read only +labels. */ +cluster FixedLabel = 64 { + revision 1; // NOTE: Default/not specifically set + + struct LabelStruct { + char_string<16> label = 0; + char_string<16> value = 1; + } + + readonly attribute LabelStruct labelList[] = 0; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** This cluster provides an interface to a boolean state called StateValue. */ +cluster BooleanState = 69 { + revision 1; + + info event StateChange = 0 { + boolean stateValue = 0; + } + + readonly attribute boolean stateValue = 0; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting air quality classification */ +cluster AirQuality = 91 { + revision 1; // NOTE: Default/not specifically set + + enum AirQualityEnum : enum8 { + kUnknown = 0; + kGood = 1; + kFair = 2; + kModerate = 3; + kPoor = 4; + kVeryPoor = 5; + kExtremelyPoor = 6; + } + + bitmap Feature : bitmap32 { + kFair = 0x1; + kModerate = 0x2; + kVeryPoor = 0x4; + kExtremelyPoor = 0x8; + } + + readonly attribute AirQualityEnum airQuality = 0; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes and commands for configuring the measurement of illuminance, and reporting illuminance measurements. */ +cluster IlluminanceMeasurement = 1024 { + revision 3; + + enum LightSensorTypeEnum : enum8 { + kPhotodiode = 0; + kCMOS = 1; + } + + readonly attribute nullable int16u measuredValue = 0; + readonly attribute nullable int16u minMeasuredValue = 1; + readonly attribute nullable int16u maxMeasuredValue = 2; + readonly attribute optional int16u tolerance = 3; + readonly attribute optional nullable LightSensorTypeEnum lightSensorType = 4; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes and commands for configuring the measurement of temperature, and reporting temperature measurements. */ +cluster TemperatureMeasurement = 1026 { + revision 1; // NOTE: Default/not specifically set + + readonly attribute nullable temperature measuredValue = 0; + readonly attribute nullable temperature minMeasuredValue = 1; + readonly attribute nullable temperature maxMeasuredValue = 2; + readonly attribute optional int16u tolerance = 3; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes and commands for configuring the measurement of pressure, and reporting pressure measurements. */ +cluster PressureMeasurement = 1027 { + revision 3; + + bitmap Feature : bitmap32 { + kExtended = 0x1; + } + + readonly attribute nullable int16s measuredValue = 0; + readonly attribute nullable int16s minMeasuredValue = 1; + readonly attribute nullable int16s maxMeasuredValue = 2; + readonly attribute optional int16u tolerance = 3; + readonly attribute optional nullable int16s scaledValue = 16; + readonly attribute optional nullable int16s minScaledValue = 17; + readonly attribute optional nullable int16s maxScaledValue = 18; + readonly attribute optional int16u scaledTolerance = 19; + readonly attribute optional int8s scale = 20; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes and commands for configuring the measurement of flow, and reporting flow measurements. */ +cluster FlowMeasurement = 1028 { + revision 1; // NOTE: Default/not specifically set + + readonly attribute nullable int16u measuredValue = 0; + readonly attribute nullable int16u minMeasuredValue = 1; + readonly attribute nullable int16u maxMeasuredValue = 2; + readonly attribute optional int16u tolerance = 3; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes and commands for configuring the measurement of relative humidity, and reporting relative humidity measurements. */ +cluster RelativeHumidityMeasurement = 1029 { + revision 3; + + readonly attribute nullable int16u measuredValue = 0; + readonly attribute nullable int16u minMeasuredValue = 1; + readonly attribute nullable int16u maxMeasuredValue = 2; + readonly attribute optional int16u tolerance = 3; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** The server cluster provides an interface to occupancy sensing functionality based on one or more sensing modalities, including configuration and provision of notifications of occupancy status. */ +cluster OccupancySensing = 1030 { + revision 5; + + enum OccupancySensorTypeEnum : enum8 { + kPIR = 0; + kUltrasonic = 1; + kPIRAndUltrasonic = 2; + kPhysicalContact = 3; + } + + bitmap Feature : bitmap32 { + kOther = 0x1; + kPassiveInfrared = 0x2; + kUltrasonic = 0x4; + kPhysicalContact = 0x8; + kActiveInfrared = 0x10; + kRadar = 0x20; + kRFSensing = 0x40; + kVision = 0x80; + } + + bitmap OccupancyBitmap : bitmap8 { + kOccupied = 0x1; + } + + bitmap OccupancySensorTypeBitmap : bitmap8 { + kPIR = 0x1; + kUltrasonic = 0x2; + kPhysicalContact = 0x4; + } + + struct HoldTimeLimitsStruct { + int16u holdTimeMin = 0; + int16u holdTimeMax = 1; + int16u holdTimeDefault = 2; + } + + info event OccupancyChanged = 0 { + OccupancyBitmap occupancy = 0; + } + + readonly attribute OccupancyBitmap occupancy = 0; + readonly attribute OccupancySensorTypeEnum occupancySensorType = 1; + readonly attribute OccupancySensorTypeBitmap occupancySensorTypeBitmap = 2; + attribute access(write: manage) optional int16u holdTime = 3; + readonly attribute optional HoldTimeLimitsStruct holdTimeLimits = 4; + attribute access(write: manage) optional int16u PIROccupiedToUnoccupiedDelay = 16; + attribute access(write: manage) optional int16u PIRUnoccupiedToOccupiedDelay = 17; + attribute access(write: manage) optional int8u PIRUnoccupiedToOccupiedThreshold = 18; + attribute access(write: manage) optional int16u ultrasonicOccupiedToUnoccupiedDelay = 32; + attribute access(write: manage) optional int16u ultrasonicUnoccupiedToOccupiedDelay = 33; + attribute access(write: manage) optional int8u ultrasonicUnoccupiedToOccupiedThreshold = 34; + attribute access(write: manage) optional int16u physicalContactOccupiedToUnoccupiedDelay = 48; + attribute access(write: manage) optional int16u physicalContactUnoccupiedToOccupiedDelay = 49; + attribute access(write: manage) optional int8u physicalContactUnoccupiedToOccupiedThreshold = 50; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting carbon monoxide concentration measurements */ +cluster CarbonMonoxideConcentrationMeasurement = 1036 { + revision 3; + + enum LevelValueEnum : enum8 { + kUnknown = 0; + kLow = 1; + kMedium = 2; + kHigh = 3; + kCritical = 4; + } + + enum MeasurementMediumEnum : enum8 { + kAir = 0; + kWater = 1; + kSoil = 2; + } + + enum MeasurementUnitEnum : enum8 { + kPPM = 0; + kPPB = 1; + kPPT = 2; + kMGM3 = 3; + kUGM3 = 4; + kNGM3 = 5; + kPM3 = 6; + kBQM3 = 7; + } + + bitmap Feature : bitmap32 { + kNumericMeasurement = 0x1; + kLevelIndication = 0x2; + kMediumLevel = 0x4; + kCriticalLevel = 0x8; + kPeakMeasurement = 0x10; + kAverageMeasurement = 0x20; + } + + readonly attribute optional nullable single measuredValue = 0; + readonly attribute optional nullable single minMeasuredValue = 1; + readonly attribute optional nullable single maxMeasuredValue = 2; + readonly attribute optional nullable single peakMeasuredValue = 3; + readonly attribute optional elapsed_s peakMeasuredValueWindow = 4; + readonly attribute optional nullable single averageMeasuredValue = 5; + readonly attribute optional elapsed_s averageMeasuredValueWindow = 6; + readonly attribute optional single uncertainty = 7; + readonly attribute optional MeasurementUnitEnum measurementUnit = 8; + readonly attribute optional MeasurementMediumEnum measurementMedium = 9; + readonly attribute optional LevelValueEnum levelValue = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting carbon dioxide concentration measurements */ +cluster CarbonDioxideConcentrationMeasurement = 1037 { + revision 3; + + enum LevelValueEnum : enum8 { + kUnknown = 0; + kLow = 1; + kMedium = 2; + kHigh = 3; + kCritical = 4; + } + + enum MeasurementMediumEnum : enum8 { + kAir = 0; + kWater = 1; + kSoil = 2; + } + + enum MeasurementUnitEnum : enum8 { + kPPM = 0; + kPPB = 1; + kPPT = 2; + kMGM3 = 3; + kUGM3 = 4; + kNGM3 = 5; + kPM3 = 6; + kBQM3 = 7; + } + + bitmap Feature : bitmap32 { + kNumericMeasurement = 0x1; + kLevelIndication = 0x2; + kMediumLevel = 0x4; + kCriticalLevel = 0x8; + kPeakMeasurement = 0x10; + kAverageMeasurement = 0x20; + } + + readonly attribute optional nullable single measuredValue = 0; + readonly attribute optional nullable single minMeasuredValue = 1; + readonly attribute optional nullable single maxMeasuredValue = 2; + readonly attribute optional nullable single peakMeasuredValue = 3; + readonly attribute optional elapsed_s peakMeasuredValueWindow = 4; + readonly attribute optional nullable single averageMeasuredValue = 5; + readonly attribute optional elapsed_s averageMeasuredValueWindow = 6; + readonly attribute optional single uncertainty = 7; + readonly attribute optional MeasurementUnitEnum measurementUnit = 8; + readonly attribute optional MeasurementMediumEnum measurementMedium = 9; + readonly attribute optional LevelValueEnum levelValue = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting nitrogen dioxide concentration measurements */ +cluster NitrogenDioxideConcentrationMeasurement = 1043 { + revision 3; + + enum LevelValueEnum : enum8 { + kUnknown = 0; + kLow = 1; + kMedium = 2; + kHigh = 3; + kCritical = 4; + } + + enum MeasurementMediumEnum : enum8 { + kAir = 0; + kWater = 1; + kSoil = 2; + } + + enum MeasurementUnitEnum : enum8 { + kPPM = 0; + kPPB = 1; + kPPT = 2; + kMGM3 = 3; + kUGM3 = 4; + kNGM3 = 5; + kPM3 = 6; + kBQM3 = 7; + } + + bitmap Feature : bitmap32 { + kNumericMeasurement = 0x1; + kLevelIndication = 0x2; + kMediumLevel = 0x4; + kCriticalLevel = 0x8; + kPeakMeasurement = 0x10; + kAverageMeasurement = 0x20; + } + + readonly attribute optional nullable single measuredValue = 0; + readonly attribute optional nullable single minMeasuredValue = 1; + readonly attribute optional nullable single maxMeasuredValue = 2; + readonly attribute optional nullable single peakMeasuredValue = 3; + readonly attribute optional elapsed_s peakMeasuredValueWindow = 4; + readonly attribute optional nullable single averageMeasuredValue = 5; + readonly attribute optional elapsed_s averageMeasuredValueWindow = 6; + readonly attribute optional single uncertainty = 7; + readonly attribute optional MeasurementUnitEnum measurementUnit = 8; + readonly attribute optional MeasurementMediumEnum measurementMedium = 9; + readonly attribute optional LevelValueEnum levelValue = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting ozone concentration measurements */ +cluster OzoneConcentrationMeasurement = 1045 { + revision 3; + + enum LevelValueEnum : enum8 { + kUnknown = 0; + kLow = 1; + kMedium = 2; + kHigh = 3; + kCritical = 4; + } + + enum MeasurementMediumEnum : enum8 { + kAir = 0; + kWater = 1; + kSoil = 2; + } + + enum MeasurementUnitEnum : enum8 { + kPPM = 0; + kPPB = 1; + kPPT = 2; + kMGM3 = 3; + kUGM3 = 4; + kNGM3 = 5; + kPM3 = 6; + kBQM3 = 7; + } + + bitmap Feature : bitmap32 { + kNumericMeasurement = 0x1; + kLevelIndication = 0x2; + kMediumLevel = 0x4; + kCriticalLevel = 0x8; + kPeakMeasurement = 0x10; + kAverageMeasurement = 0x20; + } + + readonly attribute optional nullable single measuredValue = 0; + readonly attribute optional nullable single minMeasuredValue = 1; + readonly attribute optional nullable single maxMeasuredValue = 2; + readonly attribute optional nullable single peakMeasuredValue = 3; + readonly attribute optional elapsed_s peakMeasuredValueWindow = 4; + readonly attribute optional nullable single averageMeasuredValue = 5; + readonly attribute optional elapsed_s averageMeasuredValueWindow = 6; + readonly attribute optional single uncertainty = 7; + readonly attribute optional MeasurementUnitEnum measurementUnit = 8; + readonly attribute optional MeasurementMediumEnum measurementMedium = 9; + readonly attribute optional LevelValueEnum levelValue = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting PM2.5 concentration measurements */ +cluster Pm25ConcentrationMeasurement = 1066 { + revision 3; + + enum LevelValueEnum : enum8 { + kUnknown = 0; + kLow = 1; + kMedium = 2; + kHigh = 3; + kCritical = 4; + } + + enum MeasurementMediumEnum : enum8 { + kAir = 0; + kWater = 1; + kSoil = 2; + } + + enum MeasurementUnitEnum : enum8 { + kPPM = 0; + kPPB = 1; + kPPT = 2; + kMGM3 = 3; + kUGM3 = 4; + kNGM3 = 5; + kPM3 = 6; + kBQM3 = 7; + } + + bitmap Feature : bitmap32 { + kNumericMeasurement = 0x1; + kLevelIndication = 0x2; + kMediumLevel = 0x4; + kCriticalLevel = 0x8; + kPeakMeasurement = 0x10; + kAverageMeasurement = 0x20; + } + + readonly attribute optional nullable single measuredValue = 0; + readonly attribute optional nullable single minMeasuredValue = 1; + readonly attribute optional nullable single maxMeasuredValue = 2; + readonly attribute optional nullable single peakMeasuredValue = 3; + readonly attribute optional elapsed_s peakMeasuredValueWindow = 4; + readonly attribute optional nullable single averageMeasuredValue = 5; + readonly attribute optional elapsed_s averageMeasuredValueWindow = 6; + readonly attribute optional single uncertainty = 7; + readonly attribute optional MeasurementUnitEnum measurementUnit = 8; + readonly attribute optional MeasurementMediumEnum measurementMedium = 9; + readonly attribute optional LevelValueEnum levelValue = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting formaldehyde concentration measurements */ +cluster FormaldehydeConcentrationMeasurement = 1067 { + revision 3; + + enum LevelValueEnum : enum8 { + kUnknown = 0; + kLow = 1; + kMedium = 2; + kHigh = 3; + kCritical = 4; + } + + enum MeasurementMediumEnum : enum8 { + kAir = 0; + kWater = 1; + kSoil = 2; + } + + enum MeasurementUnitEnum : enum8 { + kPPM = 0; + kPPB = 1; + kPPT = 2; + kMGM3 = 3; + kUGM3 = 4; + kNGM3 = 5; + kPM3 = 6; + kBQM3 = 7; + } + + bitmap Feature : bitmap32 { + kNumericMeasurement = 0x1; + kLevelIndication = 0x2; + kMediumLevel = 0x4; + kCriticalLevel = 0x8; + kPeakMeasurement = 0x10; + kAverageMeasurement = 0x20; + } + + readonly attribute optional nullable single measuredValue = 0; + readonly attribute optional nullable single minMeasuredValue = 1; + readonly attribute optional nullable single maxMeasuredValue = 2; + readonly attribute optional nullable single peakMeasuredValue = 3; + readonly attribute optional elapsed_s peakMeasuredValueWindow = 4; + readonly attribute optional nullable single averageMeasuredValue = 5; + readonly attribute optional elapsed_s averageMeasuredValueWindow = 6; + readonly attribute optional single uncertainty = 7; + readonly attribute optional MeasurementUnitEnum measurementUnit = 8; + readonly attribute optional MeasurementMediumEnum measurementMedium = 9; + readonly attribute optional LevelValueEnum levelValue = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting PM1 concentration measurements */ +cluster Pm1ConcentrationMeasurement = 1068 { + revision 3; + + enum LevelValueEnum : enum8 { + kUnknown = 0; + kLow = 1; + kMedium = 2; + kHigh = 3; + kCritical = 4; + } + + enum MeasurementMediumEnum : enum8 { + kAir = 0; + kWater = 1; + kSoil = 2; + } + + enum MeasurementUnitEnum : enum8 { + kPPM = 0; + kPPB = 1; + kPPT = 2; + kMGM3 = 3; + kUGM3 = 4; + kNGM3 = 5; + kPM3 = 6; + kBQM3 = 7; + } + + bitmap Feature : bitmap32 { + kNumericMeasurement = 0x1; + kLevelIndication = 0x2; + kMediumLevel = 0x4; + kCriticalLevel = 0x8; + kPeakMeasurement = 0x10; + kAverageMeasurement = 0x20; + } + + readonly attribute optional nullable single measuredValue = 0; + readonly attribute optional nullable single minMeasuredValue = 1; + readonly attribute optional nullable single maxMeasuredValue = 2; + readonly attribute optional nullable single peakMeasuredValue = 3; + readonly attribute optional elapsed_s peakMeasuredValueWindow = 4; + readonly attribute optional nullable single averageMeasuredValue = 5; + readonly attribute optional elapsed_s averageMeasuredValueWindow = 6; + readonly attribute optional single uncertainty = 7; + readonly attribute optional MeasurementUnitEnum measurementUnit = 8; + readonly attribute optional MeasurementMediumEnum measurementMedium = 9; + readonly attribute optional LevelValueEnum levelValue = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting PM10 concentration measurements */ +cluster Pm10ConcentrationMeasurement = 1069 { + revision 3; + + enum LevelValueEnum : enum8 { + kUnknown = 0; + kLow = 1; + kMedium = 2; + kHigh = 3; + kCritical = 4; + } + + enum MeasurementMediumEnum : enum8 { + kAir = 0; + kWater = 1; + kSoil = 2; + } + + enum MeasurementUnitEnum : enum8 { + kPPM = 0; + kPPB = 1; + kPPT = 2; + kMGM3 = 3; + kUGM3 = 4; + kNGM3 = 5; + kPM3 = 6; + kBQM3 = 7; + } + + bitmap Feature : bitmap32 { + kNumericMeasurement = 0x1; + kLevelIndication = 0x2; + kMediumLevel = 0x4; + kCriticalLevel = 0x8; + kPeakMeasurement = 0x10; + kAverageMeasurement = 0x20; + } + + readonly attribute optional nullable single measuredValue = 0; + readonly attribute optional nullable single minMeasuredValue = 1; + readonly attribute optional nullable single maxMeasuredValue = 2; + readonly attribute optional nullable single peakMeasuredValue = 3; + readonly attribute optional elapsed_s peakMeasuredValueWindow = 4; + readonly attribute optional nullable single averageMeasuredValue = 5; + readonly attribute optional elapsed_s averageMeasuredValueWindow = 6; + readonly attribute optional single uncertainty = 7; + readonly attribute optional MeasurementUnitEnum measurementUnit = 8; + readonly attribute optional MeasurementMediumEnum measurementMedium = 9; + readonly attribute optional LevelValueEnum levelValue = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting total volatile organic compounds concentration measurements */ +cluster TotalVolatileOrganicCompoundsConcentrationMeasurement = 1070 { + revision 3; + + enum LevelValueEnum : enum8 { + kUnknown = 0; + kLow = 1; + kMedium = 2; + kHigh = 3; + kCritical = 4; + } + + enum MeasurementMediumEnum : enum8 { + kAir = 0; + kWater = 1; + kSoil = 2; + } + + enum MeasurementUnitEnum : enum8 { + kPPM = 0; + kPPB = 1; + kPPT = 2; + kMGM3 = 3; + kUGM3 = 4; + kNGM3 = 5; + kPM3 = 6; + kBQM3 = 7; + } + + bitmap Feature : bitmap32 { + kNumericMeasurement = 0x1; + kLevelIndication = 0x2; + kMediumLevel = 0x4; + kCriticalLevel = 0x8; + kPeakMeasurement = 0x10; + kAverageMeasurement = 0x20; + } + + readonly attribute optional nullable single measuredValue = 0; + readonly attribute optional nullable single minMeasuredValue = 1; + readonly attribute optional nullable single maxMeasuredValue = 2; + readonly attribute optional nullable single peakMeasuredValue = 3; + readonly attribute optional elapsed_s peakMeasuredValueWindow = 4; + readonly attribute optional nullable single averageMeasuredValue = 5; + readonly attribute optional elapsed_s averageMeasuredValueWindow = 6; + readonly attribute optional single uncertainty = 7; + readonly attribute optional MeasurementUnitEnum measurementUnit = 8; + readonly attribute optional MeasurementMediumEnum measurementMedium = 9; + readonly attribute optional LevelValueEnum levelValue = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Attributes for reporting radon concentration measurements */ +cluster RadonConcentrationMeasurement = 1071 { + revision 3; + + enum LevelValueEnum : enum8 { + kUnknown = 0; + kLow = 1; + kMedium = 2; + kHigh = 3; + kCritical = 4; + } + + enum MeasurementMediumEnum : enum8 { + kAir = 0; + kWater = 1; + kSoil = 2; + } + + enum MeasurementUnitEnum : enum8 { + kPPM = 0; + kPPB = 1; + kPPT = 2; + kMGM3 = 3; + kUGM3 = 4; + kNGM3 = 5; + kPM3 = 6; + kBQM3 = 7; + } + + bitmap Feature : bitmap32 { + kNumericMeasurement = 0x1; + kLevelIndication = 0x2; + kMediumLevel = 0x4; + kCriticalLevel = 0x8; + kPeakMeasurement = 0x10; + kAverageMeasurement = 0x20; + } + + readonly attribute optional nullable single measuredValue = 0; + readonly attribute optional nullable single minMeasuredValue = 1; + readonly attribute optional nullable single maxMeasuredValue = 2; + readonly attribute optional nullable single peakMeasuredValue = 3; + readonly attribute optional elapsed_s peakMeasuredValueWindow = 4; + readonly attribute optional nullable single averageMeasuredValue = 5; + readonly attribute optional elapsed_s averageMeasuredValueWindow = 6; + readonly attribute optional single uncertainty = 7; + readonly attribute optional MeasurementUnitEnum measurementUnit = 8; + readonly attribute optional MeasurementMediumEnum measurementMedium = 9; + readonly attribute optional LevelValueEnum levelValue = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +endpoint 0 { + device type ma_rootdevice = 22, version 1; + + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster AccessControl { + emits event AccessControlEntryChanged; + emits event AccessControlExtensionChanged; + callback attribute acl; + callback attribute extension; + callback attribute subjectsPerAccessControlEntry; + callback attribute targetsPerAccessControlEntry; + callback attribute accessControlEntriesPerFabric; + callback attribute attributeList; + ram attribute featureMap default = 1; + callback attribute clusterRevision; + } + + server cluster BasicInformation { + emits event StartUp; + emits event ShutDown; + emits event Leave; + callback attribute dataModelRevision; + callback attribute vendorName; + callback attribute vendorID; + callback attribute productName; + callback attribute productID; + persist attribute nodeLabel; + callback attribute location; + callback attribute hardwareVersion; + callback attribute hardwareVersionString; + callback attribute softwareVersion; + callback attribute softwareVersionString; + callback attribute manufacturingDate; + callback attribute partNumber; + callback attribute productURL; + callback attribute productLabel; + callback attribute serialNumber; + persist attribute localConfigDisabled default = 0; + callback attribute uniqueID; + callback attribute capabilityMinima; + callback attribute specificationVersion; + callback attribute maxPathsPerInvoke; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 3; + } + + server cluster LocalizationConfiguration { + ram attribute activeLocale; + callback attribute supportedLocales; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + } + + server cluster GeneralCommissioning { + ram attribute breadcrumb default = 0x0000000000000000; + callback attribute basicCommissioningInfo; + callback attribute regulatoryConfig; + callback attribute locationCapability; + callback attribute supportsConcurrentConnection; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 2; + + handle command ArmFailSafe; + handle command ArmFailSafeResponse; + handle command SetRegulatoryConfig; + handle command SetRegulatoryConfigResponse; + handle command CommissioningComplete; + handle command CommissioningCompleteResponse; + } + + server cluster NetworkCommissioning { + ram attribute maxNetworks; + callback attribute networks; + ram attribute scanMaxTimeSeconds; + ram attribute connectMaxTimeSeconds; + ram attribute interfaceEnabled; + ram attribute lastNetworkingStatus; + ram attribute lastNetworkID; + ram attribute lastConnectErrorValue; + ram attribute featureMap default = 1; + ram attribute clusterRevision default = 0x0001; + + handle command ScanNetworks; + handle command ScanNetworksResponse; + handle command AddOrUpdateWiFiNetwork; + handle command AddOrUpdateThreadNetwork; + handle command RemoveNetwork; + handle command NetworkConfigResponse; + handle command ConnectNetwork; + handle command ConnectNetworkResponse; + handle command ReorderNetwork; + } + + server cluster DiagnosticLogs { + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + + handle command RetrieveLogsRequest; + handle command RetrieveLogsResponse; + } + + server cluster GeneralDiagnostics { + emits event BootReason; + callback attribute networkInterfaces; + callback attribute rebootCount; + callback attribute upTime; + callback attribute totalOperationalHours; + callback attribute bootReason; + callback attribute activeHardwareFaults; + callback attribute activeRadioFaults; + callback attribute activeNetworkFaults; + callback attribute testEventTriggersEnabled default = false; + callback attribute featureMap; + callback attribute clusterRevision; + + handle command TestEventTrigger; + handle command TimeSnapshot; + handle command TimeSnapshotResponse; + } + + server cluster SoftwareDiagnostics { + callback attribute threadMetrics; + callback attribute currentHeapFree; + callback attribute currentHeapUsed; + callback attribute currentHeapHighWatermark; + callback attribute featureMap; + ram attribute clusterRevision default = 0x0001; + + handle command ResetWatermarks; + } + + server cluster AdministratorCommissioning { + callback attribute windowStatus; + callback attribute adminFabricIndex; + callback attribute adminVendorId; + ram attribute featureMap default = 1; + ram attribute clusterRevision default = 0x0001; + + handle command OpenCommissioningWindow; + handle command OpenBasicCommissioningWindow; + handle command RevokeCommissioning; + } + + server cluster OperationalCredentials { + callback attribute NOCs; + callback attribute fabrics; + callback attribute supportedFabrics; + callback attribute commissionedFabrics; + callback attribute trustedRootCertificates; + callback attribute currentFabricIndex; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 0x0001; + + handle command AttestationRequest; + handle command AttestationResponse; + handle command CertificateChainRequest; + handle command CertificateChainResponse; + handle command CSRRequest; + handle command CSRResponse; + handle command AddNOC; + handle command UpdateNOC; + handle command NOCResponse; + handle command UpdateFabricLabel; + handle command RemoveFabric; + handle command AddTrustedRootCertificate; + } + + server cluster GroupKeyManagement { + callback attribute groupKeyMap; + callback attribute groupTable; + callback attribute maxGroupsPerFabric; + callback attribute maxGroupKeysPerFabric; + callback attribute featureMap; + callback attribute clusterRevision; + + handle command KeySetWrite; + handle command KeySetRead; + handle command KeySetReadResponse; + handle command KeySetRemove; + handle command KeySetReadAllIndices; + handle command KeySetReadAllIndicesResponse; + } + + server cluster FixedLabel { + callback attribute labelList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + } +} +endpoint 1 { + device type ma_contactsensor = 21, version 1; + + binding cluster Binding; + + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x0; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 5; + + handle command Identify; + handle command TriggerEffect; + } + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster BooleanState { + ram attribute stateValue default = 0; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + } +} +endpoint 2 { + device type ma_lightsensor = 262, version 1; + + binding cluster Binding; + + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x0; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 5; + + handle command Identify; + handle command TriggerEffect; + } + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster IlluminanceMeasurement { + ram attribute measuredValue default = 0xC351; + ram attribute minMeasuredValue default = 1; + ram attribute maxMeasuredValue default = 0xfffe; + ram attribute lightSensorType default = 1; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 3; + } +} +endpoint 3 { + device type ma_occupancysensor = 263, version 4; + + binding cluster Binding; + + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x0; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 5; + + handle command Identify; + handle command TriggerEffect; + } + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster OccupancySensing { + ram attribute occupancy default = 0; + ram attribute occupancySensorType default = 0; + ram attribute occupancySensorTypeBitmap default = 0x1; + callback attribute holdTime; + callback attribute holdTimeLimits; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 5; + } +} +endpoint 4 { + device type ma_tempsensor = 770, version 1; + + binding cluster Binding; + + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x0; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 5; + + handle command Identify; + handle command TriggerEffect; + } + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster TemperatureMeasurement { + ram attribute measuredValue default = 2350; + ram attribute minMeasuredValue default = -27315; + ram attribute maxMeasuredValue default = 32767; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 4; + } +} +endpoint 5 { + device type ma_pressuresensor = 773, version 1; + + binding cluster Binding; + + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x0; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 5; + + handle command Identify; + handle command TriggerEffect; + } + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster PressureMeasurement { + ram attribute measuredValue default = 0xA; + ram attribute minMeasuredValue default = 1; + ram attribute maxMeasuredValue default = 32767; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 3; + } +} +endpoint 6 { + device type ma_flowsensor = 774, version 1; + + binding cluster Binding; + + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x0; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 5; + + handle command Identify; + handle command TriggerEffect; + } + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster FlowMeasurement { + ram attribute measuredValue default = 0xA; + ram attribute minMeasuredValue default = 0x1; + ram attribute maxMeasuredValue default = 0xFFF; + ram attribute tolerance default = 8; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 3; + } +} +endpoint 7 { + device type ma_humiditysensor = 775, version 1; + + binding cluster Binding; + + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x0; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 5; + + handle command Identify; + handle command TriggerEffect; + } + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster RelativeHumidityMeasurement { + ram attribute measuredValue default = 0x11d0; + ram attribute minMeasuredValue default = 0x1; + ram attribute maxMeasuredValue default = 0x2710; + ram attribute tolerance default = 8; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 3; + } +} +endpoint 8 { + device type ma_air_quality_sensor = 44, version 1; + + binding cluster Binding; + + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x00; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 5; + + handle command Identify; + handle command TriggerEffect; + } + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster AirQuality { + callback attribute airQuality; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 1; + } + + server cluster CarbonMonoxideConcentrationMeasurement { + callback attribute measuredValue; + callback attribute minMeasuredValue; + callback attribute maxMeasuredValue; + callback attribute peakMeasuredValue; + callback attribute peakMeasuredValueWindow; + callback attribute averageMeasuredValue; + callback attribute averageMeasuredValueWindow; + callback attribute uncertainty; + callback attribute measurementUnit; + callback attribute measurementMedium; + callback attribute levelValue; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 3; + } + + server cluster CarbonDioxideConcentrationMeasurement { + callback attribute measuredValue; + callback attribute minMeasuredValue; + callback attribute maxMeasuredValue; + callback attribute peakMeasuredValue; + callback attribute peakMeasuredValueWindow; + callback attribute averageMeasuredValue; + callback attribute averageMeasuredValueWindow; + callback attribute uncertainty; + callback attribute measurementUnit; + callback attribute measurementMedium; + callback attribute levelValue; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 3; + } + + server cluster NitrogenDioxideConcentrationMeasurement { + callback attribute measuredValue; + callback attribute minMeasuredValue; + callback attribute maxMeasuredValue; + callback attribute peakMeasuredValue; + callback attribute peakMeasuredValueWindow; + callback attribute averageMeasuredValue; + callback attribute averageMeasuredValueWindow; + callback attribute uncertainty; + callback attribute measurementUnit; + callback attribute measurementMedium; + callback attribute levelValue; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 3; + } + + server cluster OzoneConcentrationMeasurement { + callback attribute measuredValue; + callback attribute minMeasuredValue; + callback attribute maxMeasuredValue; + callback attribute peakMeasuredValue; + callback attribute peakMeasuredValueWindow; + callback attribute averageMeasuredValue; + callback attribute averageMeasuredValueWindow; + callback attribute uncertainty; + callback attribute measurementUnit; + callback attribute measurementMedium; + callback attribute levelValue; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 3; + } + + server cluster Pm25ConcentrationMeasurement { + callback attribute measuredValue; + callback attribute minMeasuredValue; + callback attribute maxMeasuredValue; + callback attribute peakMeasuredValue; + callback attribute peakMeasuredValueWindow; + callback attribute averageMeasuredValue; + callback attribute averageMeasuredValueWindow; + callback attribute uncertainty; + callback attribute measurementUnit; + callback attribute measurementMedium; + callback attribute levelValue; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 3; + } + + server cluster FormaldehydeConcentrationMeasurement { + callback attribute measuredValue; + callback attribute minMeasuredValue; + callback attribute maxMeasuredValue; + callback attribute peakMeasuredValue; + callback attribute peakMeasuredValueWindow; + callback attribute averageMeasuredValue; + callback attribute averageMeasuredValueWindow; + callback attribute uncertainty; + callback attribute measurementUnit; + callback attribute measurementMedium; + callback attribute levelValue; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 3; + } + + server cluster Pm1ConcentrationMeasurement { + callback attribute measuredValue; + callback attribute minMeasuredValue; + callback attribute maxMeasuredValue; + callback attribute peakMeasuredValue; + callback attribute peakMeasuredValueWindow; + callback attribute averageMeasuredValue; + callback attribute averageMeasuredValueWindow; + callback attribute uncertainty; + callback attribute measurementUnit; + callback attribute measurementMedium; + callback attribute levelValue; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 3; + } + + server cluster Pm10ConcentrationMeasurement { + callback attribute measuredValue; + callback attribute minMeasuredValue; + callback attribute maxMeasuredValue; + callback attribute peakMeasuredValue; + callback attribute peakMeasuredValueWindow; + callback attribute averageMeasuredValue; + callback attribute averageMeasuredValueWindow; + callback attribute uncertainty; + callback attribute measurementUnit; + callback attribute measurementMedium; + callback attribute levelValue; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 3; + } + + server cluster TotalVolatileOrganicCompoundsConcentrationMeasurement { + callback attribute measuredValue; + callback attribute minMeasuredValue; + callback attribute maxMeasuredValue; + callback attribute peakMeasuredValue; + callback attribute peakMeasuredValueWindow; + callback attribute averageMeasuredValue; + callback attribute averageMeasuredValueWindow; + callback attribute uncertainty; + callback attribute measurementUnit; + callback attribute measurementMedium; + callback attribute levelValue; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 3; + } + + server cluster RadonConcentrationMeasurement { + callback attribute measuredValue; + callback attribute minMeasuredValue; + callback attribute maxMeasuredValue; + callback attribute peakMeasuredValue; + callback attribute peakMeasuredValueWindow; + callback attribute averageMeasuredValue; + callback attribute averageMeasuredValueWindow; + callback attribute uncertainty; + callback attribute measurementUnit; + callback attribute measurementMedium; + callback attribute levelValue; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + ram attribute clusterRevision default = 3; + } +} +endpoint 9 { + device type ma_powersource = 17, version 1; + + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster PowerSource { + ram attribute status default = 1; + persist attribute order default = 1; + ram attribute description default = "Battery"; + ram attribute batVoltage default = 2590; + ram attribute batPercentRemaining default = 98; + ram attribute batTimeRemaining default = 52560000; + ram attribute batChargeLevel default = 0; + ram attribute batReplacementNeeded default = 0; + ram attribute batReplaceability default = 2; + ram attribute batPresent default = 1; + ram attribute batReplacementDescription default = "2x AA/LR6 Alkaline"; + ram attribute batCommonDesignation default = 2; + ram attribute batApprovedChemistry default = 1; + ram attribute batQuantity; + callback attribute endpointList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0x0A; + ram attribute clusterRevision default = 1; + } +} + + diff --git a/examples/chef/devices/rootnode_contactsensor_lightsensor_occupancysensor_temperaturesensor_pressuresensor_flowsensor_humiditysensor_airqualitysensor_powersource_367e7cea91.zap b/examples/chef/devices/rootnode_contactsensor_lightsensor_occupancysensor_temperaturesensor_pressuresensor_flowsensor_humiditysensor_airqualitysensor_powersource_367e7cea91.zap new file mode 100644 index 00000000000000..05d1c22eb23062 --- /dev/null +++ b/examples/chef/devices/rootnode_contactsensor_lightsensor_occupancysensor_temperaturesensor_pressuresensor_flowsensor_humiditysensor_airqualitysensor_powersource_367e7cea91.zap @@ -0,0 +1,9272 @@ +{ + "fileFormat": 2, + "featureLevel": 104, + "creator": "zap", + "keyValuePairs": [ + { + "key": "commandDiscovery", + "value": "1" + }, + { + "key": "defaultResponsePolicy", + "value": "always" + }, + { + "key": "manufacturerCodes", + "value": "0x1002" + } + ], + "package": [ + { + "pathRelativity": "relativeToZap", + "path": "../../../src/app/zap-templates/zcl/zcl.json", + "type": "zcl-properties", + "category": "matter", + "version": 1, + "description": "Matter SDK ZCL data" + }, + { + "pathRelativity": "relativeToZap", + "path": "../../../src/app/zap-templates/app-templates.json", + "type": "gen-templates-json", + "category": "matter", + "version": "chip-v1" + } + ], + "endpointTypes": [ + { + "id": 1, + "name": "MA-rootdevice", + "deviceTypeRef": { + "code": 22, + "profileId": 259, + "label": "MA-rootdevice", + "name": "MA-rootdevice", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 22, + "profileId": 259, + "label": "MA-rootdevice", + "name": "MA-rootdevice", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 1 + ], + "deviceIdentifiers": [ + 22 + ], + "deviceTypeName": "MA-rootdevice", + "deviceTypeCode": 22, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Access Control", + "code": 31, + "mfgCode": null, + "define": "ACCESS_CONTROL_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "ACL", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Extension", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "SubjectsPerAccessControlEntry", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "TargetsPerAccessControlEntry", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AccessControlEntriesPerFabric", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ], + "events": [ + { + "name": "AccessControlEntryChanged", + "code": 0, + "mfgCode": null, + "side": "server", + "included": 1 + }, + { + "name": "AccessControlExtensionChanged", + "code": 1, + "mfgCode": null, + "side": "server", + "included": 1 + } + ] + }, + { + "name": "Basic Information", + "code": 40, + "mfgCode": null, + "define": "BASIC_INFORMATION_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DataModelRevision", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "VendorName", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "VendorID", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "vendor_id", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ProductName", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ProductID", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "NodeLabel", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "NVM", + "singleton": 1, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "Location", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "HardwareVersion", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "HardwareVersionString", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "SoftwareVersion", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "SoftwareVersionString", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ManufacturingDate", + "code": 11, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "PartNumber", + "code": 12, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ProductURL", + "code": 13, + "mfgCode": null, + "side": "server", + "type": "long_char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ProductLabel", + "code": 14, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "SerialNumber", + "code": 15, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "LocalConfigDisabled", + "code": 16, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "NVM", + "singleton": 1, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "UniqueID", + "code": 18, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "CapabilityMinima", + "code": 19, + "mfgCode": null, + "side": "server", + "type": "CapabilityMinimaStruct", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "SpecificationVersion", + "code": 21, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxPathsPerInvoke", + "code": 22, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 1, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ], + "events": [ + { + "name": "StartUp", + "code": 0, + "mfgCode": null, + "side": "server", + "included": 1 + }, + { + "name": "ShutDown", + "code": 1, + "mfgCode": null, + "side": "server", + "included": 1 + }, + { + "name": "Leave", + "code": 2, + "mfgCode": null, + "side": "server", + "included": 1 + } + ] + }, + { + "name": "Localization Configuration", + "code": 43, + "mfgCode": null, + "define": "LOCALIZATION_CONFIGURATION_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "ActiveLocale", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "SupportedLocales", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "General Commissioning", + "code": 48, + "mfgCode": null, + "define": "GENERAL_COMMISSIONING_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "ArmFailSafe", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "ArmFailSafeResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "SetRegulatoryConfig", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "SetRegulatoryConfigResponse", + "code": 3, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "CommissioningComplete", + "code": 4, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "CommissioningCompleteResponse", + "code": 5, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "Breadcrumb", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0000000000000000", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "BasicCommissioningInfo", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "BasicCommissioningInfo", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RegulatoryConfig", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "RegulatoryLocationTypeEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LocationCapability", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "RegulatoryLocationTypeEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "SupportsConcurrentConnection", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "2", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Network Commissioning", + "code": 49, + "mfgCode": null, + "define": "NETWORK_COMMISSIONING_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "ScanNetworks", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "ScanNetworksResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "AddOrUpdateWiFiNetwork", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "AddOrUpdateThreadNetwork", + "code": 3, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "RemoveNetwork", + "code": 4, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "NetworkConfigResponse", + "code": 5, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "ConnectNetwork", + "code": 6, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "ConnectNetworkResponse", + "code": 7, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "ReorderNetwork", + "code": 8, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "MaxNetworks", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Networks", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ScanMaxTimeSeconds", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ConnectMaxTimeSeconds", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "InterfaceEnabled", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LastNetworkingStatus", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "NetworkCommissioningStatusEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LastNetworkID", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "octet_string", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LastConnectErrorValue", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "int32s", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0001", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Diagnostic Logs", + "code": 50, + "mfgCode": null, + "define": "DIAGNOSTIC_LOGS_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "RetrieveLogsRequest", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "RetrieveLogsResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "General Diagnostics", + "code": 51, + "mfgCode": null, + "define": "GENERAL_DIAGNOSTICS_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "TestEventTrigger", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TimeSnapshot", + "code": 1, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TimeSnapshotResponse", + "code": 2, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "NetworkInterfaces", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RebootCount", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "UpTime", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "TotalOperationalHours", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BootReason", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "BootReasonEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveHardwareFaults", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveRadioFaults", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveNetworkFaults", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "TestEventTriggersEnabled", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "false", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ], + "events": [ + { + "name": "BootReason", + "code": 3, + "mfgCode": null, + "side": "server", + "included": 1 + } + ] + }, + { + "name": "Software Diagnostics", + "code": 52, + "mfgCode": null, + "define": "SOFTWARE_DIAGNOSTICS_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "ResetWatermarks", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "ThreadMetrics", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "CurrentHeapFree", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "CurrentHeapUsed", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "CurrentHeapHighWatermark", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0001", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Administrator Commissioning", + "code": 60, + "mfgCode": null, + "define": "ADMINISTRATOR_COMMISSIONING_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "OpenCommissioningWindow", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "OpenBasicCommissioningWindow", + "code": 1, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "RevokeCommissioning", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "WindowStatus", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "CommissioningWindowStatusEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AdminFabricIndex", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "fabric_idx", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AdminVendorId", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "vendor_id", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0001", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Operational Credentials", + "code": 62, + "mfgCode": null, + "define": "OPERATIONAL_CREDENTIALS_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "AttestationRequest", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "AttestationResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "CertificateChainRequest", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "CertificateChainResponse", + "code": 3, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "CSRRequest", + "code": 4, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "CSRResponse", + "code": 5, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "AddNOC", + "code": 6, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "UpdateNOC", + "code": 7, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "NOCResponse", + "code": 8, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "UpdateFabricLabel", + "code": 9, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "RemoveFabric", + "code": 10, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "AddTrustedRootCertificate", + "code": 11, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "NOCs", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Fabrics", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "SupportedFabrics", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "CommissionedFabrics", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TrustedRootCertificates", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "CurrentFabricIndex", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0001", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Group Key Management", + "code": 63, + "mfgCode": null, + "define": "GROUP_KEY_MANAGEMENT_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "KeySetWrite", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "KeySetRead", + "code": 1, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "KeySetReadResponse", + "code": 2, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "KeySetRemove", + "code": 3, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "KeySetReadAllIndices", + "code": 4, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "KeySetReadAllIndicesResponse", + "code": 5, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "GroupKeyMap", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GroupTable", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxGroupsPerFabric", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxGroupKeysPerFabric", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Fixed Label", + "code": 64, + "mfgCode": null, + "define": "FIXED_LABEL_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "LabelList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + }, + { + "id": 2, + "name": "Anonymous Endpoint Type", + "deviceTypeRef": { + "code": 21, + "profileId": 259, + "label": "MA-contactsensor", + "name": "MA-contactsensor", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 21, + "profileId": 259, + "label": "MA-contactsensor", + "name": "MA-contactsensor", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 1 + ], + "deviceIdentifiers": [ + 21 + ], + "deviceTypeName": "MA-contactsensor", + "deviceTypeCode": 21, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "5", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Binding", + "code": 30, + "mfgCode": null, + "define": "BINDING_CLUSTER", + "side": "client", + "enabled": 1 + }, + { + "name": "Boolean State", + "code": 69, + "mfgCode": null, + "define": "BOOLEAN_STATE_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "StateValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 0, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + }, + { + "id": 3, + "name": "Anonymous Endpoint Type", + "deviceTypeRef": { + "code": 262, + "profileId": 259, + "label": "MA-lightsensor", + "name": "MA-lightsensor", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 262, + "profileId": 259, + "label": "MA-lightsensor", + "name": "MA-lightsensor", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 1 + ], + "deviceIdentifiers": [ + 262 + ], + "deviceTypeName": "MA-lightsensor", + "deviceTypeCode": 262, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "5", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Binding", + "code": 30, + "mfgCode": null, + "define": "BINDING_CLUSTER", + "side": "client", + "enabled": 1 + }, + { + "name": "Illuminance Measurement", + "code": 1024, + "mfgCode": null, + "define": "ILLUMINANCE_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0xC351", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0xfffe", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LightSensorType", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "LightSensorTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + }, + { + "id": 4, + "name": "Anonymous Endpoint Type", + "deviceTypeRef": { + "code": 263, + "profileId": 259, + "label": "MA-occupancysensor", + "name": "MA-occupancysensor", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 263, + "profileId": 259, + "label": "MA-occupancysensor", + "name": "MA-occupancysensor", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 4 + ], + "deviceIdentifiers": [ + 263 + ], + "deviceTypeName": "MA-occupancysensor", + "deviceTypeCode": 263, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "5", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Binding", + "code": 30, + "mfgCode": null, + "define": "BINDING_CLUSTER", + "side": "client", + "enabled": 1 + }, + { + "name": "Occupancy Sensing", + "code": 1030, + "mfgCode": null, + "define": "OCCUPANCY_SENSING_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "Occupancy", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "OccupancyBitmap", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "OccupancySensorType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "OccupancySensorTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "OccupancySensorTypeBitmap", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "OccupancySensorTypeBitmap", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "HoldTime", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "HoldTimeLimits", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "HoldTimeLimitsStruct", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "5", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + }, + { + "id": 5, + "name": "Anonymous Endpoint Type", + "deviceTypeRef": { + "code": 770, + "profileId": 259, + "label": "MA-tempsensor", + "name": "MA-tempsensor", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 770, + "profileId": 259, + "label": "MA-tempsensor", + "name": "MA-tempsensor", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 1 + ], + "deviceIdentifiers": [ + 770 + ], + "deviceTypeName": "MA-tempsensor", + "deviceTypeCode": 770, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "5", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Binding", + "code": 30, + "mfgCode": null, + "define": "BINDING_CLUSTER", + "side": "client", + "enabled": 1 + }, + { + "name": "Temperature Measurement", + "code": 1026, + "mfgCode": null, + "define": "TEMPERATURE_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "temperature", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "2350", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "temperature", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "-27315", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "temperature", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "32767", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "4", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + }, + { + "id": 6, + "name": "Anonymous Endpoint Type", + "deviceTypeRef": { + "code": 773, + "profileId": 259, + "label": "MA-pressuresensor", + "name": "MA-pressuresensor", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 773, + "profileId": 259, + "label": "MA-pressuresensor", + "name": "MA-pressuresensor", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 1 + ], + "deviceIdentifiers": [ + 773 + ], + "deviceTypeName": "MA-pressuresensor", + "deviceTypeCode": 773, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "5", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Binding", + "code": 30, + "mfgCode": null, + "define": "BINDING_CLUSTER", + "side": "client", + "enabled": 1 + }, + { + "name": "Pressure Measurement", + "code": 1027, + "mfgCode": null, + "define": "PRESSURE_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16s", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0xA", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int16s", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16s", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "32767", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + }, + { + "id": 7, + "name": "Anonymous Endpoint Type", + "deviceTypeRef": { + "code": 774, + "profileId": 259, + "label": "MA-flowsensor", + "name": "MA-flowsensor", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 774, + "profileId": 259, + "label": "MA-flowsensor", + "name": "MA-flowsensor", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 1 + ], + "deviceIdentifiers": [ + 774 + ], + "deviceTypeName": "MA-flowsensor", + "deviceTypeCode": 774, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "5", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Binding", + "code": 30, + "mfgCode": null, + "define": "BINDING_CLUSTER", + "side": "client", + "enabled": 1 + }, + { + "name": "Flow Measurement", + "code": 1028, + "mfgCode": null, + "define": "FLOW_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0xA", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0xFFF", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Tolerance", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "8", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + }, + { + "id": 8, + "name": "Anonymous Endpoint Type", + "deviceTypeRef": { + "code": 775, + "profileId": 259, + "label": "MA-humiditysensor", + "name": "MA-humiditysensor", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 775, + "profileId": 259, + "label": "MA-humiditysensor", + "name": "MA-humiditysensor", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 1 + ], + "deviceIdentifiers": [ + 775 + ], + "deviceTypeName": "MA-humiditysensor", + "deviceTypeCode": 775, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "5", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Binding", + "code": 30, + "mfgCode": null, + "define": "BINDING_CLUSTER", + "side": "client", + "enabled": 1 + }, + { + "name": "Relative Humidity Measurement", + "code": 1029, + "mfgCode": null, + "define": "RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x11d0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x2710", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Tolerance", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "8", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + }, + { + "id": 9, + "name": "Anonymous Endpoint Type", + "deviceTypeRef": { + "code": 44, + "profileId": 259, + "label": "MA-air-quality-sensor", + "name": "MA-air-quality-sensor", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 44, + "profileId": 259, + "label": "MA-air-quality-sensor", + "name": "MA-air-quality-sensor", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 1 + ], + "deviceIdentifiers": [ + 44 + ], + "deviceTypeName": "MA-air-quality-sensor", + "deviceTypeCode": 44, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x00", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "5", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Binding", + "code": 30, + "mfgCode": null, + "define": "BINDING_CLUSTER", + "side": "client", + "enabled": 1 + }, + { + "name": "Air Quality", + "code": 91, + "mfgCode": null, + "define": "AIR_QUALITY_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "AirQuality", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "AirQualityEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Carbon Monoxide Concentration Measurement", + "code": 1036, + "mfgCode": null, + "define": "CARBON_MONOXIDE_CONCENTRATION_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValue", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValueWindow", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValue", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValueWindow", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Uncertainty", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementUnit", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "MeasurementUnitEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementMedium", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "MeasurementMediumEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LevelValue", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "LevelValueEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Carbon Dioxide Concentration Measurement", + "code": 1037, + "mfgCode": null, + "define": "CARBON_DIOXIDE_CONCENTRATION_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValue", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValueWindow", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValue", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValueWindow", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Uncertainty", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementUnit", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "MeasurementUnitEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementMedium", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "MeasurementMediumEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LevelValue", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "LevelValueEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Nitrogen Dioxide Concentration Measurement", + "code": 1043, + "mfgCode": null, + "define": "NITROGEN_DIOXIDE_CONCENTRATION_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValue", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValueWindow", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValue", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValueWindow", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Uncertainty", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementUnit", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "MeasurementUnitEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementMedium", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "MeasurementMediumEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LevelValue", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "LevelValueEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Ozone Concentration Measurement", + "code": 1045, + "mfgCode": null, + "define": "OZONE_CONCENTRATION_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValue", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValueWindow", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValue", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValueWindow", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Uncertainty", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementUnit", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "MeasurementUnitEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementMedium", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "MeasurementMediumEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LevelValue", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "LevelValueEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "PM2.5 Concentration Measurement", + "code": 1066, + "mfgCode": null, + "define": "PM2_5_CONCENTRATION_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValue", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValueWindow", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValue", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValueWindow", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Uncertainty", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementUnit", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "MeasurementUnitEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementMedium", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "MeasurementMediumEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LevelValue", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "LevelValueEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Formaldehyde Concentration Measurement", + "code": 1067, + "mfgCode": null, + "define": "FORMALDEHYDE_CONCENTRATION_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValue", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValueWindow", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValue", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValueWindow", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Uncertainty", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementUnit", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "MeasurementUnitEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementMedium", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "MeasurementMediumEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LevelValue", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "LevelValueEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "PM1 Concentration Measurement", + "code": 1068, + "mfgCode": null, + "define": "PM1_CONCENTRATION_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValue", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValueWindow", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValue", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValueWindow", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Uncertainty", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementUnit", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "MeasurementUnitEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementMedium", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "MeasurementMediumEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LevelValue", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "LevelValueEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "PM10 Concentration Measurement", + "code": 1069, + "mfgCode": null, + "define": "PM10_CONCENTRATION_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValue", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValueWindow", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValue", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValueWindow", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Uncertainty", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementUnit", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "MeasurementUnitEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementMedium", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "MeasurementMediumEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LevelValue", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "LevelValueEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Total Volatile Organic Compounds Concentration Measurement", + "code": 1070, + "mfgCode": null, + "define": "TVOC_CONCENTRATION_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValue", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValueWindow", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValue", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValueWindow", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Uncertainty", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementUnit", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "MeasurementUnitEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementMedium", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "MeasurementMediumEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LevelValue", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "LevelValueEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Radon Concentration Measurement", + "code": 1071, + "mfgCode": null, + "define": "RADON_CONCENTRATION_MEASUREMENT_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "MeasuredValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MinMeasuredValue", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxMeasuredValue", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValue", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PeakMeasuredValueWindow", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValue", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AverageMeasuredValueWindow", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "elapsed_s", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Uncertainty", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "single", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementUnit", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "MeasurementUnitEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MeasurementMedium", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "MeasurementMediumEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LevelValue", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "LevelValueEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + }, + { + "id": 10, + "name": "Anonymous Endpoint Type", + "deviceTypeRef": { + "code": 17, + "profileId": 259, + "label": "MA-powersource", + "name": "MA-powersource", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 17, + "profileId": 259, + "label": "MA-powersource", + "name": "MA-powersource", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 1 + ], + "deviceIdentifiers": [ + 17 + ], + "deviceTypeName": "MA-powersource", + "deviceTypeCode": 17, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Power Source", + "code": 47, + "mfgCode": null, + "define": "POWER_SOURCE_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "Status", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "PowerSourceStatusEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Order", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "NVM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Description", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "Battery", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatVoltage", + "code": 11, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "2590", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatPercentRemaining", + "code": 12, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "98", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatTimeRemaining", + "code": 13, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "52560000", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatChargeLevel", + "code": 14, + "mfgCode": null, + "side": "server", + "type": "BatChargeLevelEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatReplacementNeeded", + "code": 15, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatReplaceability", + "code": 16, + "mfgCode": null, + "side": "server", + "type": "BatReplaceabilityEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "2", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatPresent", + "code": 17, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatReplacementDescription", + "code": 19, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "2x AA/LR6 Alkaline", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatCommonDesignation", + "code": 20, + "mfgCode": null, + "side": "server", + "type": "BatCommonDesignationEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "2", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatApprovedChemistry", + "code": 23, + "mfgCode": null, + "side": "server", + "type": "BatApprovedChemistryEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BatQuantity", + "code": 25, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "EndpointList", + "code": 31, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0A", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + } + ], + "endpoints": [ + { + "endpointTypeName": "MA-rootdevice", + "endpointTypeIndex": 0, + "profileId": 259, + "endpointId": 0, + "networkId": 0, + "parentEndpointIdentifier": null + }, + { + "endpointTypeName": "Anonymous Endpoint Type", + "endpointTypeIndex": 1, + "profileId": 259, + "endpointId": 1, + "networkId": 0, + "parentEndpointIdentifier": null + }, + { + "endpointTypeName": "Anonymous Endpoint Type", + "endpointTypeIndex": 2, + "profileId": 259, + "endpointId": 2, + "networkId": 0, + "parentEndpointIdentifier": null + }, + { + "endpointTypeName": "Anonymous Endpoint Type", + "endpointTypeIndex": 3, + "profileId": 259, + "endpointId": 3, + "networkId": 0, + "parentEndpointIdentifier": null + }, + { + "endpointTypeName": "Anonymous Endpoint Type", + "endpointTypeIndex": 4, + "profileId": 259, + "endpointId": 4, + "networkId": 0, + "parentEndpointIdentifier": null + }, + { + "endpointTypeName": "Anonymous Endpoint Type", + "endpointTypeIndex": 5, + "profileId": 259, + "endpointId": 5, + "networkId": 0, + "parentEndpointIdentifier": null + }, + { + "endpointTypeName": "Anonymous Endpoint Type", + "endpointTypeIndex": 6, + "profileId": 259, + "endpointId": 6, + "networkId": 0, + "parentEndpointIdentifier": null + }, + { + "endpointTypeName": "Anonymous Endpoint Type", + "endpointTypeIndex": 7, + "profileId": 259, + "endpointId": 7, + "networkId": 0, + "parentEndpointIdentifier": null + }, + { + "endpointTypeName": "Anonymous Endpoint Type", + "endpointTypeIndex": 8, + "profileId": 259, + "endpointId": 8, + "networkId": 0, + "parentEndpointIdentifier": null + }, + { + "endpointTypeName": "Anonymous Endpoint Type", + "endpointTypeIndex": 9, + "profileId": 259, + "endpointId": 9, + "networkId": 0, + "parentEndpointIdentifier": null + } + ] +} \ No newline at end of file diff --git a/examples/chef/devices/rootnode_fan_7N2TobIlOX.matter b/examples/chef/devices/rootnode_fan_7N2TobIlOX.matter index 78e524d7eb140a..1acdbca51279a4 100644 --- a/examples/chef/devices/rootnode_fan_7N2TobIlOX.matter +++ b/examples/chef/devices/rootnode_fan_7N2TobIlOX.matter @@ -1878,7 +1878,7 @@ endpoint 1 { ram attribute fanModeSequence default = 2; persist attribute percentSetting default = 0x00; ram attribute percentCurrent default = 0x00; - ram attribute speedMax default = 100; + ram attribute speedMax default = 10; persist attribute speedSetting default = 0x00; persist attribute speedCurrent default = 0; ram attribute rockSupport default = 0x03; diff --git a/examples/chef/devices/rootnode_fan_7N2TobIlOX.zap b/examples/chef/devices/rootnode_fan_7N2TobIlOX.zap index 1f976f24c67632..39239eaef90230 100644 --- a/examples/chef/devices/rootnode_fan_7N2TobIlOX.zap +++ b/examples/chef/devices/rootnode_fan_7N2TobIlOX.zap @@ -1,6 +1,6 @@ { "fileFormat": 2, - "featureLevel": 103, + "featureLevel": 104, "creator": "zap", "keyValuePairs": [ { @@ -41,14 +41,16 @@ "code": 22, "profileId": 259, "label": "MA-rootdevice", - "name": "MA-rootdevice" + "name": "MA-rootdevice", + "deviceTypeOrder": 0 }, "deviceTypes": [ { "code": 22, "profileId": 259, "label": "MA-rootdevice", - "name": "MA-rootdevice" + "name": "MA-rootdevice", + "deviceTypeOrder": 0 } ], "deviceVersions": [ @@ -2291,14 +2293,16 @@ "code": 43, "profileId": 259, "label": "MA-fan", - "name": "MA-fan" + "name": "MA-fan", + "deviceTypeOrder": 0 }, "deviceTypes": [ { "code": 43, "profileId": 259, "label": "MA-fan", - "name": "MA-fan" + "name": "MA-fan", + "deviceTypeOrder": 0 } ], "deviceVersions": [ @@ -2885,7 +2889,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "100", + "defaultValue": "10", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -3035,22 +3039,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, diff --git a/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter b/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter index 43e8de7b5f4ee1..1bc2e8726e1083 100644 --- a/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter +++ b/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter @@ -1845,7 +1845,7 @@ endpoint 1 { server cluster PressureMeasurement { ram attribute measuredValue default = 0xA; ram attribute minMeasuredValue default = 1; - ram attribute maxMeasuredValue default = 0xfffe; + ram attribute maxMeasuredValue default = 32767; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute attributeList; diff --git a/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.zap b/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.zap index 3131dca9c5d00d..f473e3dc7eb5d1 100644 --- a/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.zap +++ b/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.zap @@ -2721,7 +2721,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0xfffe", + "defaultValue": "32767", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -2830,4 +2830,4 @@ "parentEndpointIdentifier": null } ] -} \ No newline at end of file +} diff --git a/examples/chef/esp32/main/CMakeLists.txt b/examples/chef/esp32/main/CMakeLists.txt index 5c8963f7735f6d..a7905ff214c584 100644 --- a/examples/chef/esp32/main/CMakeLists.txt +++ b/examples/chef/esp32/main/CMakeLists.txt @@ -79,6 +79,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/zap-generated/attributes" "${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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" ) diff --git a/examples/chef/linux/with_pw_rpc.gni b/examples/chef/linux/with_pw_rpc.gni index 0f1ab1ea89c121..a67251431a018c 100644 --- a/examples/chef/linux/with_pw_rpc.gni +++ b/examples/chef/linux/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -39,4 +39,3 @@ pw_build_LINK_DEPS = [ ] chip_enable_pw_rpc = true -chip_use_pw_logging = true diff --git a/examples/chef/silabs/build_for_wifi_args.gni b/examples/chef/silabs/build_for_wifi_args.gni index 9394037ba0ee38..97180fa504123a 100644 --- a/examples/chef/silabs/build_for_wifi_args.gni +++ b/examples/chef/silabs/build_for_wifi_args.gni @@ -15,6 +15,6 @@ import("//build_overrides/chip.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") chip_enable_ota_requestor = true diff --git a/examples/chip-tool/commands/common/CHIPCommand.cpp b/examples/chip-tool/commands/common/CHIPCommand.cpp index 1c3df517bd89d0..4f14cb855e5af7 100644 --- a/examples/chip-tool/commands/common/CHIPCommand.cpp +++ b/examples/chip-tool/commands/common/CHIPCommand.cpp @@ -467,6 +467,11 @@ void CHIPCommand::ShutdownCommissioner(const CommissionerIdentity & key) CHIP_ERROR CHIPCommand::InitializeCommissioner(CommissionerIdentity & identity, chip::FabricId fabricId) { std::unique_ptr commissioner = std::make_unique(); +#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY + VerifyOrReturnError(chip::CanCastTo(CHIP_UDC_PORT + fabricId), CHIP_ERROR_INVALID_ARGUMENT); + uint16_t udcListenPort = static_cast(CHIP_UDC_PORT + fabricId); + commissioner->SetUdcListenPort(udcListenPort); +#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY chip::Controller::SetupParams commissionerParams; ReturnLogErrorOnFailure(mCredIssuerCmds->SetupDeviceAttestation(commissionerParams, sTrustStore, sRevocationDelegate)); diff --git a/examples/chip-tool/commands/common/Command.cpp b/examples/chip-tool/commands/common/Command.cpp index 82e9eedc461dd5..91a65db789d976 100644 --- a/examples/chip-tool/commands/common/Command.cpp +++ b/examples/chip-tool/commands/common/Command.cpp @@ -55,6 +55,10 @@ bool Command::InitArguments(int argc, char ** argv) { optionalArgsCount++; } + else if (argvExtraArgsCount == 0) + { + mandatoryArgsCount++; + } else { mandatoryArgsCount++; diff --git a/examples/common/pigweed/RpcService.cpp b/examples/common/pigweed/RpcService.cpp index 74d0b891e9b00d..ee999c4b172fc9 100644 --- a/examples/common/pigweed/RpcService.cpp +++ b/examples/common/pigweed/RpcService.cpp @@ -25,7 +25,6 @@ #include "pw_hdlc/decoder.h" #include "pw_hdlc/default_addresses.h" #include "pw_hdlc/rpc_channel.h" -#include "pw_log/log.h" #include "pw_rpc/channel.h" #include "pw_status/status.h" #include "pw_stream/sys_io_stream.h" @@ -96,20 +95,6 @@ void Start(void (*RegisterServices)(pw::rpc::Server &), ::chip::rpc::Mutex * uar PW_DASSERT(RegisterServices != nullptr); uart_mutex = uart_mutex_; - // Send log messages to HDLC address 1. This prevents logs from interfering - // with pw_rpc communications. - pw::log_basic::SetOutput([](std::string_view log) { - if (uart_mutex) - { - uart_mutex->Lock(); - } - pw::hdlc::WriteUIFrame(1, pw::as_bytes(pw::span(log)), sysIoWriter); - if (uart_mutex) - { - uart_mutex->Unlock(); - } - }); - // Set up the server and start processing data. RegisterServices(server); diff --git a/examples/common/pigweed/rpc_console/py/chip_rpc/console.py b/examples/common/pigweed/rpc_console/py/chip_rpc/console.py index 50f0b030f51725..31ecd9df03e0f0 100644 --- a/examples/common/pigweed/rpc_console/py/chip_rpc/console.py +++ b/examples/common/pigweed/rpc_console/py/chip_rpc/console.py @@ -39,7 +39,7 @@ import argparse import sys from pathlib import Path -from typing import Any, Collection +from typing import Collection import pw_system.console from pw_hdlc import rpc @@ -52,7 +52,6 @@ from button_service import button_service_pb2 from descriptor_service import descriptor_service_pb2 from device_service import device_service_pb2 -from echo_service import echo_pb2 from fabric_admin_service import fabric_admin_service_pb2 from fabric_bridge_service import fabric_bridge_service_pb2 from lighting_service import lighting_service_pb2 @@ -72,13 +71,6 @@ def _parse_args(): type=int, default=115200, help='the baud rate to use') - parser.add_argument( - '-o', - '--output', - type=argparse.FileType('wb'), - default=sys.stdout.buffer, - help=('The file to which to write device output (HDLC channel 1); ' - 'provide - or omit for stdout.')) parser.add_argument( '-r', '--raw_serial', @@ -99,7 +91,7 @@ def _parse_args(): def show_console(device: str, baudrate: int, token_databases: Collection[Path], - socket_addr: str, output: Any, raw_serial: bool) -> int: + socket_addr: str, raw_serial: bool) -> int: # TODO: this shows a default console with little customization # Ideally we should at least customize the default messages @@ -114,7 +106,6 @@ def show_console(device: str, baudrate: int, device=device, baudrate=baudrate, socket_addr=socket_addr, - output=output, hdlc_encoding=not raw_serial, token_databases=token_databases, logfile="", @@ -122,14 +113,10 @@ def show_console(device: str, baudrate: int, channel_id=rpc.DEFAULT_CHANNEL_ID, # Defaults beyond the original console - proto_globs=[], ticks_per_second=None, host_logfile="", json_logfile="", rpc_logging=False, - # the pt-python based console seems to break on python 3.1 with - # "set_wakeup_fd only works in main thread of the main interpreter" - use_ipython=True, compiled_protos=[ actions_service_pb2, attributes_service_pb2, @@ -137,7 +124,6 @@ def show_console(device: str, baudrate: int, button_service_pb2, descriptor_service_pb2, device_service_pb2, - echo_pb2, fabric_admin_service_pb2, fabric_bridge_service_pb2, lighting_service_pb2, diff --git a/examples/common/pigweed/system_rpc_server.cc b/examples/common/pigweed/system_rpc_server.cc index 098aa3b1711058..360bdef947e631 100644 --- a/examples/common/pigweed/system_rpc_server.cc +++ b/examples/common/pigweed/system_rpc_server.cc @@ -20,7 +20,6 @@ #include "pw_hdlc/decoder.h" #include "pw_hdlc/default_addresses.h" #include "pw_hdlc/rpc_channel.h" -#include "pw_log/log.h" #include "pw_rpc_system_server/rpc_server.h" #include "pw_stream/sys_io_stream.h" @@ -40,12 +39,7 @@ rpc::Server server(channels); } // namespace -void Init() -{ - // Send log messages to HDLC address 1. This prevents logs from interfering - // with pw_rpc communications. - pw::log_basic::SetOutput([](std::string_view log) { pw::hdlc::WriteUIFrame(1, pw::as_bytes(pw::span(log)), writer); }); -} +void Init() {} rpc::Server & Server() { diff --git a/examples/contact-sensor-app/nxp/common/AppTask.cpp b/examples/contact-sensor-app/nxp/common/AppTask.cpp index 7539bc61e09a1f..2b102adc1b4924 100644 --- a/examples/contact-sensor-app/nxp/common/AppTask.cpp +++ b/examples/contact-sensor-app/nxp/common/AppTask.cpp @@ -18,10 +18,6 @@ #include "AppTask.h" -#if CONFIG_LOW_POWER -#include "PWR_Interface.h" -#endif - #include #include @@ -36,18 +32,6 @@ void ContactSensorApp::AppTask::PreInitMatterStack() ChipLogProgress(DeviceLayer, "Welcome to NXP Contact Sensor Demo App"); } -#if CONFIG_LOW_POWER -void ContactSensorApp::AppTask::AppMatter_DisallowDeviceToSleep() -{ - PWR_DisallowDeviceToSleep(); -} - -void ContactSensorApp::AppTask::AppMatter_AllowDeviceToSleep() -{ - PWR_AllowDeviceToSleep(); -} -#endif - ContactSensorApp::AppTask & ContactSensorApp::AppTask::GetDefaultInstance() { static ContactSensorApp::AppTask sAppTask; diff --git a/examples/contact-sensor-app/nxp/common/include/AppTask.h b/examples/contact-sensor-app/nxp/common/include/AppTask.h index 407572aad254e6..7a4a9a61617970 100644 --- a/examples/contact-sensor-app/nxp/common/include/AppTask.h +++ b/examples/contact-sensor-app/nxp/common/include/AppTask.h @@ -34,10 +34,6 @@ class AppTask : public chip::NXP::App::AppTaskFreeRTOS // AppTaskFreeRTOS virtual methods void PreInitMatterStack() override; -#if CONFIG_LOW_POWER - void AppMatter_DisallowDeviceToSleep() override; - void AppMatter_AllowDeviceToSleep() override; -#endif // This returns an instance of this class. static AppTask & GetDefaultInstance(); diff --git a/examples/darwin-framework-tool/BUILD.gn b/examples/darwin-framework-tool/BUILD.gn index f5333c9f42c4e1..257431b2425aec 100644 --- a/examples/darwin-framework-tool/BUILD.gn +++ b/examples/darwin-framework-tool/BUILD.gn @@ -46,6 +46,9 @@ declare_args() { # Enable automatic leak checks before the application exits enable_leak_checking = !is_asan && target_os == "mac" + + # Use Network.framework instead of POSIX sockets + use_network_framework = false } sdk = "macosx" @@ -53,7 +56,9 @@ sdk_build_dir_suffix = "" if (getenv("SDKROOT") != "") { sdk = getenv("SDKROOT") sdk_root_parts = string_split(getenv("SDKROOT"), ".") - sdk_build_dir_suffix = "-${sdk_root_parts[0]}" + if (sdk_root_parts[0] != "macosx") { + sdk_build_dir_suffix = "-${sdk_root_parts[0]}" + } } output_sdk_type = "Debug${sdk_build_dir_suffix}" @@ -123,6 +128,12 @@ action("build-darwin-framework") { args += [ "--no-enable-encoding-sentinel-enum-values" ] } + if (defined(use_network_framework) && use_network_framework) { + args += [ "--use-network-framework" ] + } else { + args += [ "--no-use-network-framework" ] + } + output_name = "Matter.framework" outputs = [ "${root_out_dir}/macos_framework_output/Build/Products/${output_sdk_type}/${output_name}", @@ -134,7 +145,7 @@ action("build-darwin-framework") { "${root_out_dir}/macos_framework_output/Build", ] - if (sdk == "macosx") { + if (sdk == "macosx" || sdk_root_parts[0] == "macosx") { outputs += [ "${root_out_dir}/macos_framework_output/Build/Intermediates.noindex/Matter.build/${output_sdk_type}/Matter.build/out/lib/libCHIP.a" ] } } @@ -275,21 +286,19 @@ executable("darwin-framework-tool") { "${root_out_dir}/macos_framework_output/Build/Intermediates.noindex/Matter.build/${output_sdk_type}/Matter.build/out/gen/include", ] - defines = [ - "CHIP_HAVE_CONFIG_H=1", - "CHIP_SYSTEM_CONFIG_USE_SOCKETS=1", - ] + defines = [ "CHIP_HAVE_CONFIG_H=1" ] frameworks += [ "CoreFoundation.framework", "Foundation.framework", "CoreBluetooth.framework", "Network.framework", + "IOKit.framework", ] # Other SDKs are linked statically to Matter.framework but the macosx SDK is linked dynamically but needs some symbols that are # not exposed by the dylib. - if (sdk == "macosx") { + if (sdk == "macosx" || sdk_root_parts[0] == "macosx") { libs = [ "${root_out_dir}/macos_framework_output/Build/Intermediates.noindex/Matter.build/${output_sdk_type}/Matter.build/out/lib/libCHIP.a" ] } diff --git a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm index 69071d4c423776..6b9dfcec29be9e 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm +++ b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm @@ -172,10 +172,17 @@ NSError * error; __auto_type * operationalKeypair = [certificateIssuer issueOperationalKeypairWithControllerStorage:controllerStorage error:&error]; + SecKeyRef publicKey = [operationalKeypair copyPublicKey]; + __auto_type * operational = [certificateIssuer issueOperationalCertificateForNodeID:nodeId fabricID:fabricId - publicKey:operationalKeypair.publicKey + publicKey:publicKey error:&error]; + + if (publicKey != NULL) { + CFAutorelease(publicKey); + } + VerifyOrReturnError(nil == error, MTRErrorToCHIPErrorCode(error), ChipLogError(chipTool, "Can not issue an operational certificate: %@", error)); __auto_type * controllerStorageQueue = dispatch_queue_create("com.chip.storage", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); diff --git a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h index f0ee3f8db6092b..58be7f2ac4b041 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h +++ b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h @@ -22,7 +22,7 @@ @interface CHIPToolKeypair : NSObject - (BOOL)initialize; - (NSData *)signMessageECDSA_RAW:(NSData *)message; -- (SecKeyRef)publicKey; +- (SecKeyRef)copyPublicKey; - (CHIP_ERROR)Serialize:(chip::Crypto::P256SerializedKeypair &)output; - (CHIP_ERROR)Deserialize:(chip::Crypto::P256SerializedKeypair &)input; - (CHIP_ERROR)createOrLoadKeys:(id)storage; diff --git a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm index ce0ef5819b6ac1..a09975d68da41f 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm +++ b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm @@ -65,7 +65,7 @@ - (NSData *)signMessageECDSA_RAW:(NSData *)message return out_signature; } -- (SecKeyRef)publicKey +- (SecKeyRef)copyPublicKey { if (_mPublicKey == nil) { chip::Crypto::P256PublicKey publicKey = _mKeyPair.Pubkey(); @@ -79,7 +79,13 @@ - (SecKeyRef)publicKey }; _mPublicKey = SecKeyCreateWithData((__bridge CFDataRef) publicKeyNSData, (__bridge CFDictionaryRef) attributes, nullptr); } - return _mPublicKey; + + if (_mPublicKey) { + CFRetain(_mPublicKey); + return _mPublicKey; + } + + return NULL; } - (CHIP_ERROR)Deserialize:(chip::Crypto::P256SerializedKeypair &)input diff --git a/examples/dishwasher-app/silabs/README.md b/examples/dishwasher-app/silabs/README.md index 9a8a102cbd147d..ffc56f3580697b 100644 --- a/examples/dishwasher-app/silabs/README.md +++ b/examples/dishwasher-app/silabs/README.md @@ -10,6 +10,7 @@ An example showing the use of Matter on the Silicon Labs EFR32 MG24 boards. - [Flashing the Application](#flashing-the-application) - [Viewing Logging Output](#viewing-logging-output) - [Running the Complete Example](#running-the-complete-example) + - [Commissioning](#commissioning)
@@ -211,6 +212,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/dishwasher-app/silabs/build_for_wifi_args.gni b/examples/dishwasher-app/silabs/build_for_wifi_args.gni index 7e52816578fbee..0a421db59d117d 100644 --- a/examples/dishwasher-app/silabs/build_for_wifi_args.gni +++ b/examples/dishwasher-app/silabs/build_for_wifi_args.gni @@ -16,7 +16,7 @@ import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") sl_enable_test_event_trigger = true chip_enable_ota_requestor = true diff --git a/examples/energy-management-app/esp32/main/CMakeLists.txt b/examples/energy-management-app/esp32/main/CMakeLists.txt index e5459616238d3d..06623d3faf839d 100644 --- a/examples/energy-management-app/esp32/main/CMakeLists.txt +++ b/examples/energy-management-app/esp32/main/CMakeLists.txt @@ -44,6 +44,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/shell_extension" "${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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/administrator-commissioning-server" diff --git a/examples/energy-management-app/linux/README.md b/examples/energy-management-app/linux/README.md index d28121f0a6d33b..87b6d9dd93db39 100644 --- a/examples/energy-management-app/linux/README.md +++ b/examples/energy-management-app/linux/README.md @@ -24,6 +24,7 @@ details. - [Activating python virtual env](#activating-python-virtual-env) - [Interacting with CHIP-REPL and the example app](#interacting-with-chip-repl-and-the-example-app) - [Using chip-repl to Fake a charging session](#using-chip-repl-to-fake-a-charging-session) + - [Water Heater App: Interaction using the chip-tool and TestEventTriggers](#water-heater-app-interaction-using-the-chip-tool-and-testeventtriggers)
@@ -238,8 +239,9 @@ data (e.g. fabric info). ## CHIP-REPL Interaction -- See chip-repl documentation in - [Matter_REPL_Intro](../../../docs/development_controllers/chip-repl/Matter_REPL_Intro.ipynb) +- See chip-repl documentation in: + - [Working with Python CHIP Controller](../../../docs/development_controllers/chip-repl/python_chip_controller_building.md) + - [Matter_REPL_Intro](../../../docs/development_controllers/chip-repl/Matter_REPL_Intro.ipynb) ### Building chip-repl: diff --git a/examples/energy-management-app/silabs/README.md b/examples/energy-management-app/silabs/README.md index 5c1955a5071f3c..2b565ec4b30e77 100644 --- a/examples/energy-management-app/silabs/README.md +++ b/examples/energy-management-app/silabs/README.md @@ -108,14 +108,14 @@ creating real products based on the Silicon Labs platform. To build the Water Heater example you can change the args to gn gen (see BUILD.gn for arg options) - $ gn gen out/debug --args='chip_enable_example_evse_device=false chip_enable_example_water_heater_device=true' + $ gn gen out/debug --args='sl_enable_example_evse_device=false sl_enable_example_water_heater_device=true' $ ninja -C out/debug To change Device Energy Management feature support (e.g. Power forecast or State forecast reporting), you can change the args to gn gen (see BUILD.gn for arg options) - $ gn gen out/debug --args='chip_dem_support_state_forecast_reporting=true chip_dem_support_power_forecast_reporting=false' + $ gn gen out/debug --args='sl_dem_support_state_forecast_reporting=true sl_dem_support_power_forecast_reporting=false' $ ninja -C out/debug - To delete generated executable, libraries and object files use: @@ -127,10 +127,6 @@ creating real products based on the Silicon Labs platform. $ ./scripts/examples/gn_silabs_example.sh ./examples/energy-management-app/silabs/ ./out/energy-management-app_ICD BRD4187C --icd - or use gn as previously mentioned but adding the following arguments: - - $ gn gen out/debug '--args=SILABS_BOARD="BRD4187C" enable_sleepy_device=true chip_openthread_ftd=false' - * Build the example with pigweed RPC $ ./scripts/examples/gn_silabs_example.sh examples/energy-management-app/silabs/ out/energy_management_app_rpc BRD4187C 'import("//with_pw_rpc.gni")' @@ -257,6 +253,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/energy-management-app/silabs/build_for_wifi_args.gni b/examples/energy-management-app/silabs/build_for_wifi_args.gni index 1b1c0ecd6a7c78..feeffecd6f935a 100644 --- a/examples/energy-management-app/silabs/build_for_wifi_args.gni +++ b/examples/energy-management-app/silabs/build_for_wifi_args.gni @@ -16,7 +16,7 @@ import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") sl_enable_test_event_trigger = true chip_enable_ota_requestor = false diff --git a/examples/fabric-admin/README.md b/examples/fabric-admin/README.md index bdfb82d5ac5d8d..92fdffda6b830f 100644 --- a/examples/fabric-admin/README.md +++ b/examples/fabric-admin/README.md @@ -23,13 +23,13 @@ For Raspberry Pi 4 example: ### Pull Docker Images ``` -docker pull ghcr.io/project-chip/chip-build-crosscompile:81 +docker pull ghcr.io/project-chip/chip-build-crosscompile:90 ``` ### Run docker ``` -docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:81 /bin/bash +docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:90 /bin/bash ``` ### Build diff --git a/examples/fabric-admin/args.gni b/examples/fabric-admin/args.gni index 63c91c70c209cd..83300d797ed08a 100644 --- a/examples/fabric-admin/args.gni +++ b/examples/fabric-admin/args.gni @@ -32,4 +32,3 @@ matter_log_json_payload_decode_full = true # make fabric-admin very strict by default chip_tlv_validate_char_string_on_read = true chip_tlv_validate_char_string_on_write = true -chip_enable_ble = true diff --git a/examples/fabric-admin/commands/common/CHIPCommand.cpp b/examples/fabric-admin/commands/common/CHIPCommand.cpp index c23ea82f202cf7..e7f4071d122b31 100644 --- a/examples/fabric-admin/commands/common/CHIPCommand.cpp +++ b/examples/fabric-admin/commands/common/CHIPCommand.cpp @@ -182,7 +182,7 @@ CHIP_ERROR CHIPCommand::MaybeSetUpStack() mCredIssuerCmds->SetCredentialIssuerOption(CredentialIssuerCommands::CredentialIssuerOptions::kAllowTestCdSigningKey, allowTestCdSigningKey); - ReturnLogErrorOnFailure(PairingManager::Instance().Init(&CurrentCommissioner(), mCredIssuerCmds)); + ReturnLogErrorOnFailure(admin::PairingManager::Instance().Init(&CurrentCommissioner(), mCredIssuerCmds)); return CHIP_NO_ERROR; } diff --git a/examples/fabric-admin/commands/fabric-sync/Commands.h b/examples/fabric-admin/commands/fabric-sync/Commands.h index 47f7207922beae..0f2f3f64c35d5c 100644 --- a/examples/fabric-admin/commands/fabric-sync/Commands.h +++ b/examples/fabric-admin/commands/fabric-sync/Commands.h @@ -26,11 +26,11 @@ void registerCommandsFabricSync(Commands & commands, CredentialIssuerCommands * const char * clusterName = "FabricSync"; commands_list clusterCommands = { - make_unique(credsIssuerConfig), - make_unique(credsIssuerConfig), - make_unique(credsIssuerConfig), - make_unique(credsIssuerConfig), - make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), }; commands.RegisterCommandSet(clusterName, clusterCommands, "Commands for fabric synchronization."); diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp index f10db13e939acd..315bf2f3711f35 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -30,6 +30,8 @@ using namespace ::chip; +namespace admin { + void FabricSyncAddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) { if (mBridgeNodeId != deviceId) @@ -49,14 +51,14 @@ void FabricSyncAddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_E if (err == CHIP_NO_ERROR) { - DeviceMgr().SetRemoteBridgeNodeId(mBridgeNodeId); + DeviceManager::Instance().SetRemoteBridgeNodeId(mBridgeNodeId); ChipLogProgress(NotSpecified, "Successfully paired bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mBridgeNodeId)); - DeviceMgr().UpdateLastUsedNodeId(mBridgeNodeId); - DeviceMgr().SubscribeRemoteFabricBridge(); + DeviceManager::Instance().UpdateLastUsedNodeId(mBridgeNodeId); + DeviceManager::Instance().SubscribeRemoteFabricBridge(); - if (DeviceMgr().IsLocalBridgeReady()) + if (DeviceManager::Instance().IsLocalBridgeReady()) { // After successful commissioning of the Commissionee, initiate Reverse Commissioning // via the Commissioner Control Cluster. However, we must first verify that the @@ -64,7 +66,7 @@ void FabricSyncAddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_E // // Note: The Fabric-Admin MUST NOT send the RequestCommissioningApproval command // if the remote Fabric-Bridge lacks Fabric Synchronization support. - DeviceLayer::SystemLayer().ScheduleLambda([]() { DeviceMgr().ReadSupportedDeviceCategories(); }); + DeviceLayer::SystemLayer().ScheduleLambda([]() { DeviceManager::Instance().ReadSupportedDeviceCategories(); }); } } else @@ -78,18 +80,19 @@ void FabricSyncAddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_E CHIP_ERROR FabricSyncAddBridgeCommand::RunCommand(NodeId remoteId) { - if (DeviceMgr().IsFabricSyncReady()) + if (DeviceManager::Instance().IsFabricSyncReady()) { // print to console - fprintf(stderr, "Remote Fabric Bridge has already been configured."); + fprintf(stderr, "Remote Fabric Bridge has already been configured.\n"); return CHIP_NO_ERROR; } - PairingManager::Instance().SetCommissioningDelegate(this); + PairingManager::Instance().SetPairingDelegate(this); mBridgeNodeId = remoteId; - DeviceMgr().PairRemoteFabricBridge(remoteId, mSetupPINCode, reinterpret_cast(mRemoteAddr.data()), mRemotePort); + DeviceManager::Instance().PairRemoteFabricBridge(remoteId, mSetupPINCode, reinterpret_cast(mRemoteAddr.data()), + mRemotePort); return CHIP_NO_ERROR; } @@ -104,7 +107,7 @@ void FabricSyncRemoveBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR if (err == CHIP_NO_ERROR) { - DeviceMgr().SetRemoteBridgeNodeId(kUndefinedNodeId); + DeviceManager::Instance().SetRemoteBridgeNodeId(kUndefinedNodeId); ChipLogProgress(NotSpecified, "Successfully removed bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mBridgeNodeId)); } @@ -119,19 +122,19 @@ void FabricSyncRemoveBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR CHIP_ERROR FabricSyncRemoveBridgeCommand::RunCommand() { - NodeId bridgeNodeId = DeviceMgr().GetRemoteBridgeNodeId(); + NodeId bridgeNodeId = DeviceManager::Instance().GetRemoteBridgeNodeId(); if (bridgeNodeId == kUndefinedNodeId) { // print to console - fprintf(stderr, "Remote Fabric Bridge is not configured yet, nothing to remove."); + fprintf(stderr, "Remote Fabric Bridge is not configured yet, nothing to remove.\n"); return CHIP_NO_ERROR; } mBridgeNodeId = bridgeNodeId; PairingManager::Instance().SetPairingDelegate(this); - DeviceMgr().UnpairRemoteFabricBridge(); + DeviceManager::Instance().UnpairRemoteFabricBridge(); return CHIP_NO_ERROR; } @@ -155,8 +158,8 @@ void FabricSyncAddLocalBridgeCommand::OnCommissioningComplete(NodeId deviceId, C if (err == CHIP_NO_ERROR) { - DeviceMgr().SetLocalBridgeNodeId(mLocalBridgeNodeId); - DeviceMgr().UpdateLastUsedNodeId(mLocalBridgeNodeId); + DeviceManager::Instance().SetLocalBridgeNodeId(mLocalBridgeNodeId); + DeviceManager::Instance().UpdateLastUsedNodeId(mLocalBridgeNodeId); ChipLogProgress(NotSpecified, "Successfully paired local bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mLocalBridgeNodeId)); } @@ -171,26 +174,26 @@ void FabricSyncAddLocalBridgeCommand::OnCommissioningComplete(NodeId deviceId, C CHIP_ERROR FabricSyncAddLocalBridgeCommand::RunCommand(NodeId deviceId) { - if (DeviceMgr().IsLocalBridgeReady()) + if (DeviceManager::Instance().IsLocalBridgeReady()) { // print to console - fprintf(stderr, "Local Fabric Bridge has already been configured."); + fprintf(stderr, "Local Fabric Bridge has already been configured.\n"); return CHIP_NO_ERROR; } - PairingManager::Instance().SetCommissioningDelegate(this); + PairingManager::Instance().SetPairingDelegate(this); mLocalBridgeNodeId = deviceId; if (mSetupPINCode.HasValue()) { - DeviceMgr().SetLocalBridgeSetupPinCode(mSetupPINCode.Value()); + DeviceManager::Instance().SetLocalBridgeSetupPinCode(mSetupPINCode.Value()); } if (mLocalPort.HasValue()) { - DeviceMgr().SetLocalBridgePort(mLocalPort.Value()); + DeviceManager::Instance().SetLocalBridgePort(mLocalPort.Value()); } - DeviceMgr().PairLocalFabricBridge(deviceId); + DeviceManager::Instance().PairLocalFabricBridge(deviceId); return CHIP_NO_ERROR; } @@ -205,7 +208,7 @@ void FabricSyncRemoveLocalBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_E if (err == CHIP_NO_ERROR) { - DeviceMgr().SetLocalBridgeNodeId(kUndefinedNodeId); + DeviceManager::Instance().SetLocalBridgeNodeId(kUndefinedNodeId); ChipLogProgress(NotSpecified, "Successfully removed local bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mLocalBridgeNodeId)); } @@ -220,19 +223,19 @@ void FabricSyncRemoveLocalBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_E CHIP_ERROR FabricSyncRemoveLocalBridgeCommand::RunCommand() { - NodeId bridgeNodeId = DeviceMgr().GetLocalBridgeNodeId(); + NodeId bridgeNodeId = DeviceManager::Instance().GetLocalBridgeNodeId(); if (bridgeNodeId == kUndefinedNodeId) { // print to console - fprintf(stderr, "Local Fabric Bridge is not configured yet, nothing to remove."); + fprintf(stderr, "Local Fabric Bridge is not configured yet, nothing to remove.\n"); return CHIP_NO_ERROR; } mLocalBridgeNodeId = bridgeNodeId; PairingManager::Instance().SetPairingDelegate(this); - DeviceMgr().UnpairLocalFabricBridge(); + DeviceManager::Instance().UnpairLocalFabricBridge(); return CHIP_NO_ERROR; } @@ -248,14 +251,14 @@ void FabricSyncDeviceCommand::OnCommissioningWindowOpened(NodeId deviceId, CHIP_ CHIP_ERROR error = ManualSetupPayloadGenerator(payload).payloadDecimalStringRepresentation(manualCode); if (error == CHIP_NO_ERROR) { - NodeId nodeId = DeviceMgr().GetNextAvailableNodeId(); + NodeId nodeId = DeviceManager::Instance().GetNextAvailableNodeId(); - PairingManager::Instance().SetCommissioningDelegate(this); + PairingManager::Instance().SetPairingDelegate(this); mAssignedNodeId = nodeId; usleep(kCommissionPrepareTimeMs * 1000); - DeviceMgr().PairRemoteDevice(nodeId, payloadBuffer); + DeviceManager::Instance().PairRemoteDevice(nodeId, payloadBuffer); } else { @@ -281,7 +284,7 @@ void FabricSyncDeviceCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERRO if (err == CHIP_NO_ERROR) { - DeviceMgr().AddSyncedDevice(Device(mAssignedNodeId, mRemoteEndpointId)); + DeviceManager::Instance().AddSyncedDevice(Device(mAssignedNodeId, mRemoteEndpointId)); } else { @@ -290,18 +293,20 @@ void FabricSyncDeviceCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERRO } } -CHIP_ERROR FabricSyncDeviceCommand::RunCommand(EndpointId remoteId) +CHIP_ERROR FabricSyncDeviceCommand::RunCommand(EndpointId remoteEndpointId) { - if (!DeviceMgr().IsFabricSyncReady()) + if (!DeviceManager::Instance().IsFabricSyncReady()) { // print to console - fprintf(stderr, "Remote Fabric Bridge is not configured yet."); + fprintf(stderr, "Remote Fabric Bridge is not configured yet.\n"); return CHIP_NO_ERROR; } PairingManager::Instance().SetOpenCommissioningWindowDelegate(this); - DeviceMgr().OpenRemoteDeviceCommissioningWindow(remoteId); + DeviceManager::Instance().OpenRemoteDeviceCommissioningWindow(remoteEndpointId); return CHIP_NO_ERROR; } + +} // namespace admin diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h index 8d14529155cab4..444fb96a9ad402 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h @@ -21,10 +21,12 @@ #include #include +namespace admin { + // Constants constexpr uint32_t kCommissionPrepareTimeMs = 500; -class FabricSyncAddBridgeCommand : public CHIPCommand, public CommissioningDelegate +class FabricSyncAddBridgeCommand : public CHIPCommand, public PairingDelegate { public: FabricSyncAddBridgeCommand(CredentialIssuerCommands * credIssuerCommands) : CHIPCommand("add-bridge", credIssuerCommands) @@ -69,7 +71,7 @@ class FabricSyncRemoveBridgeCommand : public CHIPCommand, public PairingDelegate chip::NodeId mBridgeNodeId; }; -class FabricSyncAddLocalBridgeCommand : public CHIPCommand, public CommissioningDelegate +class FabricSyncAddLocalBridgeCommand : public CHIPCommand, public PairingDelegate { public: FabricSyncAddLocalBridgeCommand(CredentialIssuerCommands * credIssuerCommands) : @@ -114,7 +116,7 @@ class FabricSyncRemoveLocalBridgeCommand : public CHIPCommand, public PairingDel chip::NodeId mLocalBridgeNodeId; }; -class FabricSyncDeviceCommand : public CHIPCommand, public CommissioningWindowDelegate, public CommissioningDelegate +class FabricSyncDeviceCommand : public CHIPCommand, public CommissioningWindowDelegate, public PairingDelegate { public: FabricSyncDeviceCommand(CredentialIssuerCommands * credIssuerCommands) : CHIPCommand("sync-device", credIssuerCommands) @@ -122,8 +124,8 @@ class FabricSyncDeviceCommand : public CHIPCommand, public CommissioningWindowDe AddArgument("endpointid", 0, UINT16_MAX, &mRemoteEndpointId); } - void OnCommissioningWindowOpened(NodeId deviceId, CHIP_ERROR status, chip::SetupPayload payload) override; - void OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) override; + void OnCommissioningWindowOpened(chip::NodeId deviceId, CHIP_ERROR status, chip::SetupPayload payload) override; + void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) override; /////////// CHIPCommand Interface ///////// CHIP_ERROR RunCommand() override { return RunCommand(mRemoteEndpointId); } @@ -134,5 +136,7 @@ class FabricSyncDeviceCommand : public CHIPCommand, public CommissioningWindowDe chip::EndpointId mRemoteEndpointId = chip::kInvalidEndpointId; chip::NodeId mAssignedNodeId = chip::kUndefinedNodeId; - CHIP_ERROR RunCommand(chip::EndpointId remoteId); + CHIP_ERROR RunCommand(chip::EndpointId remoteEndpointId); }; + +} // namespace admin diff --git a/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp b/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp index 0209a783739b74..bd352257266828 100644 --- a/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp +++ b/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp @@ -117,7 +117,7 @@ void ENFORCE_FORMAT(3, 0) LoggingCallback(const char * module, uint8_t category, #if defined(PW_RPC_ENABLED) void AttemptRpcClientConnect(System::Layer * systemLayer, void * appState) { - if (StartRpcClient() == CHIP_NO_ERROR) + if (admin::StartRpcClient() == CHIP_NO_ERROR) { // print to console fprintf(stderr, "Connected to Fabric-Bridge\n"); @@ -199,8 +199,8 @@ CHIP_ERROR InteractiveStartCommand::RunCommand() } #if defined(PW_RPC_ENABLED) - SetRpcRemoteServerPort(mFabricBridgeServerPort.Value()); - InitRpcServer(mLocalServerPort.Value()); + admin::SetRpcRemoteServerPort(mFabricBridgeServerPort.Value()); + admin::InitRpcServer(mLocalServerPort.Value()); ChipLogProgress(NotSpecified, "PW_RPC initialized."); DeviceLayer::PlatformMgr().ScheduleWork(ExecuteDeferredConnect, 0); #endif diff --git a/examples/fabric-admin/commands/pairing/PairingCommand.cpp b/examples/fabric-admin/commands/pairing/PairingCommand.cpp index 37578472b70fbd..5ac731871f9af8 100644 --- a/examples/fabric-admin/commands/pairing/PairingCommand.cpp +++ b/examples/fabric-admin/commands/pairing/PairingCommand.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -33,10 +34,6 @@ #include -#if defined(PW_RPC_ENABLED) -#include -#endif - using namespace ::chip; using namespace ::chip::Controller; @@ -405,7 +402,7 @@ void PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err) fprintf(stderr, "New device with Node ID: 0x%lx has been successfully added.\n", nodeId); // CurrentCommissioner() has a lifetime that is the entire life of the application itself // so it is safe to provide to StartDeviceSynchronization. - DeviceSynchronizer::Instance().StartDeviceSynchronization(&CurrentCommissioner(), mNodeId, mDeviceIsICD); + admin::DeviceSynchronizer::Instance().StartDeviceSynchronization(&CurrentCommissioner(), mNodeId, mDeviceIsICD); } else { @@ -534,16 +531,16 @@ void PairingCommand::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E PairingCommand * command = reinterpret_cast(context); VerifyOrReturn(command != nullptr, ChipLogError(NotSpecified, "OnCurrentFabricRemove: context is null")); + ChipLogProgress(NotSpecified, "PairingCommand::OnCurrentFabricRemove"); + if (err == CHIP_NO_ERROR) { // print to console fprintf(stderr, "Device with Node ID: 0x%lx has been successfully removed.\n", nodeId); -#if defined(PW_RPC_ENABLED) app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(command->CurrentCommissioner().GetFabricIndex(), nodeId); ScopedNodeId scopedNodeId(nodeId, command->CurrentCommissioner().GetFabricIndex()); - RemoveSynchronizedDevice(scopedNodeId); -#endif + admin::DeviceManager::Instance().RemoveSyncedDevice(scopedNodeId); } else { diff --git a/examples/fabric-admin/device_manager/BridgeSubscription.cpp b/examples/fabric-admin/device_manager/BridgeSubscription.cpp index 2efcadaaa63ee5..1df9371ff74dff 100644 --- a/examples/fabric-admin/device_manager/BridgeSubscription.cpp +++ b/examples/fabric-admin/device_manager/BridgeSubscription.cpp @@ -17,12 +17,14 @@ */ #include "BridgeSubscription.h" -#include +#include "DeviceManager.h" using namespace ::chip; using namespace ::chip::app; using chip::app::ReadClient; +namespace admin { + namespace { constexpr uint16_t kSubscribeMinInterval = 0; @@ -78,7 +80,7 @@ void BridgeSubscription::OnAttributeData(const ConcreteDataAttributePath & path, return; } - DeviceMgr().HandleAttributeData(path, *data); + DeviceManager::Instance().HandleAttributeData(path, *data); } void BridgeSubscription::OnEventData(const app::EventHeader & eventHeader, TLV::TLVReader * data, const app::StatusIB * status) @@ -99,7 +101,7 @@ void BridgeSubscription::OnEventData(const app::EventHeader & eventHeader, TLV:: return; } - DeviceMgr().HandleEventData(eventHeader, *data); + DeviceManager::Instance().HandleEventData(eventHeader, *data); } void BridgeSubscription::OnError(CHIP_ERROR error) @@ -157,3 +159,5 @@ void BridgeSubscription::OnDeviceConnectionFailure(const ScopedNodeId & peerId, ChipLogError(NotSpecified, "BridgeSubscription failed to connect to " ChipLogFormatX64, ChipLogValueX64(peerId.GetNodeId())); OnDone(nullptr); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/BridgeSubscription.h b/examples/fabric-admin/device_manager/BridgeSubscription.h index bd2a70279af065..e5f8c73fc14257 100644 --- a/examples/fabric-admin/device_manager/BridgeSubscription.h +++ b/examples/fabric-admin/device_manager/BridgeSubscription.h @@ -24,6 +24,8 @@ #include #include +namespace admin { + /** * @brief Class used to subscribe to attributes and events from the remote bridged device. * @@ -75,3 +77,5 @@ class BridgeSubscription : public chip::app::ReadClient::Callback chip::EndpointId mEndpointId; bool subscriptionStarted = false; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/CommissionerControl.cpp b/examples/fabric-admin/device_manager/CommissionerControl.cpp index b919ceb0683192..a0c24eb956d5bb 100644 --- a/examples/fabric-admin/device_manager/CommissionerControl.cpp +++ b/examples/fabric-admin/device_manager/CommissionerControl.cpp @@ -1,8 +1,28 @@ +/* + * Copyright (c) 2024 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 "CommissionerControl.h" -#include +#include "DeviceManager.h" using namespace ::chip; +namespace admin { + void CommissionerControl::Init(Controller::DeviceCommissioner & commissioner, NodeId nodeId, EndpointId endpointId) { // Ensure that mCommissioner is not already initialized @@ -64,7 +84,7 @@ void CommissionerControl::OnResponse(app::CommandSender * client, const app::Con if (data != nullptr) { - DeviceMgr().HandleCommandResponse(path, *data); + DeviceManager::Instance().HandleCommandResponse(path, *data); } } @@ -102,6 +122,9 @@ void CommissionerControl::OnDone(app::CommandSender * client) CHIP_ERROR CommissionerControl::SendCommandForType(CommandType commandType, DeviceProxy * device) { + ChipLogProgress(AppServer, "Sending command with Endpoint ID: %d, Command Type: %d", mEndpointId, + static_cast(commandType)); + switch (commandType) { case CommandType::kRequestCommissioningApproval: @@ -139,3 +162,5 @@ void CommissionerControl::OnDeviceConnectionFailureFn(void * context, const Scop VerifyOrReturn(self != nullptr, ChipLogError(NotSpecified, "OnDeviceConnectedFn: context is null")); self->OnDone(nullptr); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/CommissionerControl.h b/examples/fabric-admin/device_manager/CommissionerControl.h index 1fad323e125c2a..392367d6c04367 100644 --- a/examples/fabric-admin/device_manager/CommissionerControl.h +++ b/examples/fabric-admin/device_manager/CommissionerControl.h @@ -21,6 +21,8 @@ #include #include +namespace admin { + /** * @class CommissionerControl * @brief This class handles sending CHIP commands related to commissioning, including sending @@ -123,3 +125,5 @@ class CommissionerControl : public chip::app::CommandSender::Callback chip::app::Clusters::CommissionerControl::Commands::RequestCommissioningApproval::Type mRequestCommissioningApproval; chip::app::Clusters::CommissionerControl::Commands::CommissionNode::Type mCommissionNode; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index e52027c8f533f1..9f40f92a87c411 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -25,8 +25,14 @@ #include #include +#if defined(PW_RPC_ENABLED) +#include +#endif + using namespace chip; +namespace admin { + namespace { constexpr EndpointId kAggregatorEndpointId = 1; @@ -36,9 +42,6 @@ constexpr uint16_t kMaxDiscriminatorLength = 4095; } // namespace -// Define the static member -DeviceManager DeviceManager::sInstance; - void DeviceManager::Init() { // TODO: (#34113) Init mLastUsedNodeId from chip config file @@ -69,7 +72,11 @@ void DeviceManager::UpdateLastUsedNodeId(NodeId nodeId) void DeviceManager::SetRemoteBridgeNodeId(chip::NodeId nodeId) { mRemoteBridgeNodeId = nodeId; - mCommissionerControl.Init(PairingManager::Instance().CurrentCommissioner(), mRemoteBridgeNodeId, kAggregatorEndpointId); + + if (mRemoteBridgeNodeId != kUndefinedNodeId) + { + mCommissionerControl.Init(PairingManager::Instance().CurrentCommissioner(), mRemoteBridgeNodeId, kAggregatorEndpointId); + } } void DeviceManager::AddSyncedDevice(const Device & device) @@ -103,8 +110,13 @@ Device * DeviceManager::FindDeviceByNode(NodeId nodeId) return nullptr; } -void DeviceManager::RemoveSyncedDevice(NodeId nodeId) +void DeviceManager::RemoveSyncedDevice(chip::ScopedNodeId scopedNodeId) { +#if defined(PW_RPC_ENABLED) + RemoveSynchronizedDevice(scopedNodeId); +#endif + + NodeId nodeId = scopedNodeId.GetNodeId(); Device * device = FindDeviceByNode(nodeId); if (device == nullptr) { @@ -253,6 +265,10 @@ void DeviceManager::HandleReadSupportedDeviceCategories(TLV::TLVReader & data) ChipLogProgress(NotSpecified, "Remote Fabric-Bridge supports Fabric Synchronization, start reverse commissioning."); RequestCommissioningApproval(); } + else + { + ChipLogProgress(NotSpecified, "Remote Fabric-Bridge does not support Fabric Synchronization."); + } } void DeviceManager::RequestCommissioningApproval() @@ -400,6 +416,8 @@ void DeviceManager::SendCommissionNodeRequest(uint64_t requestId, uint16_t respo void DeviceManager::HandleReverseOpenCommissioningWindow(TLV::TLVReader & data) { + ChipLogProgress(NotSpecified, "Handle ReverseOpenCommissioningWindow command."); + app::Clusters::CommissionerControl::Commands::ReverseOpenCommissioningWindow::DecodableType value; CHIP_ERROR error = app::DataModel::Decode(data, value); @@ -453,15 +471,4 @@ void DeviceManager::HandleCommandResponse(const app::ConcreteCommandPath & path, } } -void DeviceManager::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) -{ - if (err != CHIP_NO_ERROR) - { - ChipLogError(NotSpecified, "Failed to remove synced device:(" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, - ChipLogValueX64(deviceId), err.Format()); - return; - } - - RemoveSyncedDevice(deviceId); - ChipLogProgress(NotSpecified, "Synced device with NodeId:" ChipLogFormatX64 " has been removed.", ChipLogValueX64(deviceId)); -} +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceManager.h b/examples/fabric-admin/device_manager/DeviceManager.h index 6adc8f243e6b1a..594fcfc5745703 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.h +++ b/examples/fabric-admin/device_manager/DeviceManager.h @@ -26,6 +26,8 @@ #include #include +namespace admin { + constexpr uint32_t kDefaultSetupPinCode = 20202021; constexpr uint16_t kDefaultLocalBridgePort = 5540; constexpr uint16_t kResponseTimeoutSeconds = 30; @@ -48,11 +50,17 @@ class Device chip::EndpointId mEndpointId; }; -class DeviceManager : public PairingDelegate +class DeviceManager { public: DeviceManager() = default; + static DeviceManager & Instance() + { + static DeviceManager instance; + return instance; + } + void Init(); chip::NodeId GetNextAvailableNodeId(); @@ -75,7 +83,7 @@ class DeviceManager : public PairingDelegate void AddSyncedDevice(const Device & device); - void RemoveSyncedDevice(chip::NodeId nodeId); + void RemoveSyncedDevice(chip::ScopedNodeId scopedNodeId); /** * @brief Determines whether a given nodeId corresponds to the "current bridge device," either local or remote. @@ -173,10 +181,6 @@ class DeviceManager : public PairingDelegate Device * FindDeviceByNode(chip::NodeId nodeId); private: - friend DeviceManager & DeviceMgr(); - - void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; - void RequestCommissioningApproval(); void HandleReadSupportedDeviceCategories(chip::TLV::TLVReader & data); @@ -212,17 +216,4 @@ class DeviceManager : public PairingDelegate FabricSyncGetter mFabricSyncGetter; }; -/** - * Returns the public interface of the DeviceManager singleton object. - * - * Applications should use this to access features of the DeviceManager - * object. - */ -inline DeviceManager & DeviceMgr() -{ - if (!DeviceManager::sInstance.mInitialized) - { - DeviceManager::sInstance.Init(); - } - return DeviceManager::sInstance; -} +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSubscription.cpp b/examples/fabric-admin/device_manager/DeviceSubscription.cpp index 434d349e8c5113..996656a0de2bdc 100644 --- a/examples/fabric-admin/device_manager/DeviceSubscription.cpp +++ b/examples/fabric-admin/device_manager/DeviceSubscription.cpp @@ -33,6 +33,8 @@ using namespace ::chip; using namespace ::chip::app; using chip::app::ReadClient; +namespace admin { + namespace { void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) @@ -281,3 +283,5 @@ void DeviceSubscription::StopSubscription() MoveToState(State::AwaitingDestruction); mOnDoneCallback(mScopedNodeId); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSubscription.h b/examples/fabric-admin/device_manager/DeviceSubscription.h index 8db31d6e9037fc..808da10c321851 100644 --- a/examples/fabric-admin/device_manager/DeviceSubscription.h +++ b/examples/fabric-admin/device_manager/DeviceSubscription.h @@ -20,7 +20,6 @@ #include #include #include - #include #if defined(PW_RPC_ENABLED) @@ -28,6 +27,8 @@ #include "fabric_bridge_service/fabric_bridge_service.rpc.pb.h" #endif +namespace admin { + class DeviceSubscriptionManager; /// Attribute subscription to attributes that are important to keep track and send to fabric-bridge @@ -95,3 +96,5 @@ class DeviceSubscription : public chip::app::ReadClient::Callback bool mChangeDetected = false; State mState = State::Idle; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp index 0410c162a8e43a..46f94c99c81138 100644 --- a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp @@ -32,11 +32,7 @@ using namespace ::chip; using namespace ::chip::app; -DeviceSubscriptionManager & DeviceSubscriptionManager::Instance() -{ - static DeviceSubscriptionManager instance; - return instance; -} +namespace admin { CHIP_ERROR DeviceSubscriptionManager::StartSubscription(Controller::DeviceController & controller, ScopedNodeId scopedNodeId) { @@ -78,3 +74,5 @@ void DeviceSubscriptionManager::DeviceSubscriptionTerminated(ScopedNodeId scoped VerifyOrDie(it != mDeviceSubscriptionMap.end()); mDeviceSubscriptionMap.erase(scopedNodeId); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h index 1b5c45fd05ae16..5f04522dcc1fac 100644 --- a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h +++ b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h @@ -25,10 +25,16 @@ #include +namespace admin { + class DeviceSubscriptionManager { public: - static DeviceSubscriptionManager & Instance(); + static DeviceSubscriptionManager & Instance() + { + static DeviceSubscriptionManager instance; + return instance; + } /// Usually called after we have added a synchronized device to fabric-bridge to monitor /// for any changes that need to be propagated to fabric-bridge. @@ -52,3 +58,5 @@ class DeviceSubscriptionManager std::unordered_map, ScopedNodeIdHasher> mDeviceSubscriptionMap; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSynchronization.cpp b/examples/fabric-admin/device_manager/DeviceSynchronization.cpp index 1e8728ee59b567..092c2505d19d73 100644 --- a/examples/fabric-admin/device_manager/DeviceSynchronization.cpp +++ b/examples/fabric-admin/device_manager/DeviceSynchronization.cpp @@ -35,6 +35,8 @@ using namespace ::chip; using namespace ::chip::app; using chip::app::ReadClient; +namespace admin { + namespace { void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) @@ -141,7 +143,7 @@ void DeviceSynchronizer::OnReportEnd() void DeviceSynchronizer::OnDone(app::ReadClient * apReadClient) { #if defined(PW_RPC_ENABLED) - if (mState == State::ReceivedResponse && !DeviceMgr().IsCurrentBridgeDevice(mNodeId)) + if (mState == State::ReceivedResponse && !DeviceManager::Instance().IsCurrentBridgeDevice(mNodeId)) { GetUniqueId(); if (mState == State::GettingUid) @@ -228,15 +230,15 @@ void DeviceSynchronizer::GetUniqueId() VerifyOrReturn(!mCurrentDeviceData.has_unique_id, ChipLogDetail(NotSpecified, "We already have UniqueId")); #endif - auto * device = DeviceMgr().FindDeviceByNode(mNodeId); + auto * device = DeviceManager::Instance().FindDeviceByNode(mNodeId); // If there is no associated remote Fabric Sync Aggregator there is no other place for us to try // getting the UniqueId from and can return leaving the state in ReceivedResponse. VerifyOrReturn(device, ChipLogDetail(NotSpecified, "No remote Fabric Sync Aggregator to get UniqueId from")); // Because device is not-null we expect IsFabricSyncReady to be true. IsFabricSyncReady indicates we have a // connection to the remote Fabric Sync Aggregator. - VerifyOrDie(DeviceMgr().IsFabricSyncReady()); - auto remoteBridgeNodeId = DeviceMgr().GetRemoteBridgeNodeId(); + VerifyOrDie(DeviceManager::Instance().IsFabricSyncReady()); + auto remoteBridgeNodeId = DeviceManager::Instance().GetRemoteBridgeNodeId(); EndpointId remoteEndpointIdOfInterest = device->GetEndpointId(); ChipLogDetail(NotSpecified, "Attempting to get UniqueId from remote Fabric Sync Aggregator"); @@ -324,3 +326,5 @@ const char * DeviceSynchronizer::GetStateStr() const } return "N/A"; } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSynchronization.h b/examples/fabric-admin/device_manager/DeviceSynchronization.h index 28880c6faec7a1..8f089ef6534d5f 100644 --- a/examples/fabric-admin/device_manager/DeviceSynchronization.h +++ b/examples/fabric-admin/device_manager/DeviceSynchronization.h @@ -22,7 +22,6 @@ #include #include #include - #include #if defined(PW_RPC_ENABLED) @@ -30,6 +29,8 @@ #include "fabric_bridge_service/fabric_bridge_service.rpc.pb.h" #endif +namespace admin { + /// Ensures that device data is synchronized to the remote fabric bridge. /// /// Includes a state machine that: @@ -100,3 +101,5 @@ class DeviceSynchronizer : public chip::app::ReadClient::Callback #endif UniqueIdGetter mUniqueIdGetter; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/FabricSyncGetter.cpp b/examples/fabric-admin/device_manager/FabricSyncGetter.cpp index 5201048c3faea6..7e5118090716c0 100644 --- a/examples/fabric-admin/device_manager/FabricSyncGetter.cpp +++ b/examples/fabric-admin/device_manager/FabricSyncGetter.cpp @@ -22,6 +22,8 @@ using namespace ::chip; using namespace ::chip::app; using chip::app::ReadClient; +namespace admin { + namespace { void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) @@ -119,3 +121,5 @@ void FabricSyncGetter::OnDeviceConnectionFailure(const ScopedNodeId & peerId, CH OnDone(nullptr); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/FabricSyncGetter.h b/examples/fabric-admin/device_manager/FabricSyncGetter.h index d6d3a5bce8c9f5..bed3c2fbb54385 100644 --- a/examples/fabric-admin/device_manager/FabricSyncGetter.h +++ b/examples/fabric-admin/device_manager/FabricSyncGetter.h @@ -24,6 +24,8 @@ #include #include +namespace admin { + /** * @brief Class used to get FabricSynchronization from SupportedDeviceCategories attribute of Commissioner Control Cluster. * @@ -73,3 +75,5 @@ class FabricSyncGetter : public chip::app::ReadClient::Callback chip::Callback::Callback mOnDeviceConnectedCallback; chip::Callback::Callback mOnDeviceConnectionFailureCallback; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/PairingManager.cpp b/examples/fabric-admin/device_manager/PairingManager.cpp index 41b4c8744e16b3..8474d78f023343 100644 --- a/examples/fabric-admin/device_manager/PairingManager.cpp +++ b/examples/fabric-admin/device_manager/PairingManager.cpp @@ -23,18 +23,17 @@ #include #include +#include #include #include #include #include -#if defined(PW_RPC_ENABLED) -#include -#endif - using namespace ::chip; using namespace ::chip::Controller; +namespace admin { + namespace { CHIP_ERROR GetPayload(const char * setUpCode, SetupPayload & payload) @@ -310,10 +309,10 @@ void PairingManager::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err) ChipLogProgress(NotSpecified, "Device commissioning Failure: %s", ErrorStr(err)); } - if (mCommissioningDelegate) + if (mPairingDelegate) { - mCommissioningDelegate->OnCommissioningComplete(nodeId, err); - SetCommissioningDelegate(nullptr); + mPairingDelegate->OnCommissioningComplete(nodeId, err); + SetPairingDelegate(nullptr); } } @@ -545,17 +544,23 @@ void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E PairingManager * self = reinterpret_cast(context); VerifyOrReturn(self != nullptr, ChipLogError(NotSpecified, "OnCurrentFabricRemove: context is null")); + ChipLogProgress(NotSpecified, "PairingManager::OnCurrentFabricRemove"); + if (err == CHIP_NO_ERROR) { // print to console - fprintf(stderr, "Device with Node ID: " ChipLogFormatX64 "has been successfully removed.\n", ChipLogValueX64(nodeId)); + fprintf(stderr, "Device with Node ID: " ChipLogFormatX64 " has been successfully removed.\n", ChipLogValueX64(nodeId)); + + if (self->mPairingDelegate) + { + self->mPairingDelegate->OnDeviceRemoved(nodeId, err); + self->SetPairingDelegate(nullptr); + } -#if defined(PW_RPC_ENABLED) FabricIndex fabricIndex = self->CurrentCommissioner().GetFabricIndex(); app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(fabricIndex, nodeId); ScopedNodeId scopedNodeId(nodeId, fabricIndex); - RemoveSynchronizedDevice(scopedNodeId); -#endif + DeviceManager::Instance().RemoveSyncedDevice(scopedNodeId); } else { @@ -655,3 +660,5 @@ CHIP_ERROR PairingManager::UnpairDevice(NodeId nodeId) } }); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/PairingManager.h b/examples/fabric-admin/device_manager/PairingManager.h index 50e64f9f0ca67f..77cec24876e9f2 100644 --- a/examples/fabric-admin/device_manager/PairingManager.h +++ b/examples/fabric-admin/device_manager/PairingManager.h @@ -25,6 +25,8 @@ #include #include +namespace admin { + // Constants constexpr uint16_t kMaxManualCodeLength = 22; @@ -35,18 +37,12 @@ class CommissioningWindowDelegate virtual ~CommissioningWindowDelegate() = default; }; -class CommissioningDelegate -{ -public: - virtual void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) = 0; - virtual ~CommissioningDelegate() = default; -}; - class PairingDelegate { public: - virtual void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) = 0; - virtual ~PairingDelegate() = default; + virtual void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) {} + virtual void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) {} + virtual ~PairingDelegate() = default; }; /** @@ -83,7 +79,6 @@ class PairingManager : public chip::Controller::DevicePairingDelegate, CHIP_ERROR Init(chip::Controller::DeviceCommissioner * commissioner, CredentialIssuerCommands * credIssuerCmds); void SetOpenCommissioningWindowDelegate(CommissioningWindowDelegate * delegate) { mCommissioningWindowDelegate = delegate; } - void SetCommissioningDelegate(CommissioningDelegate * delegate) { mCommissioningDelegate = delegate; } void SetPairingDelegate(PairingDelegate * delegate) { mPairingDelegate = delegate; } PairingDelegate * GetPairingDelegate() { return mPairingDelegate; } @@ -179,7 +174,6 @@ class PairingManager : public chip::Controller::DevicePairingDelegate, CredentialIssuerCommands * mCredIssuerCmds = nullptr; CommissioningWindowDelegate * mCommissioningWindowDelegate = nullptr; - CommissioningDelegate * mCommissioningDelegate = nullptr; PairingDelegate * mPairingDelegate = nullptr; chip::NodeId mNodeId = chip::kUndefinedNodeId; @@ -214,3 +208,5 @@ class PairingManager : public chip::Controller::DevicePairingDelegate, chip::Platform::UniquePtr mCurrentFabricRemover; chip::Callback::Callback mCurrentFabricRemoveCallback; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/UniqueIdGetter.cpp b/examples/fabric-admin/device_manager/UniqueIdGetter.cpp index 3a6d6af69d032b..cc3567deda6bd2 100644 --- a/examples/fabric-admin/device_manager/UniqueIdGetter.cpp +++ b/examples/fabric-admin/device_manager/UniqueIdGetter.cpp @@ -22,6 +22,8 @@ using namespace ::chip; using namespace ::chip::app; using chip::app::ReadClient; +namespace admin { + namespace { void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) @@ -139,3 +141,5 @@ void UniqueIdGetter::OnDeviceConnectionFailure(const ScopedNodeId & peerId, CHIP OnDone(nullptr); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/UniqueIdGetter.h b/examples/fabric-admin/device_manager/UniqueIdGetter.h index 86d5d82f656bd5..eba4451599c3ee 100644 --- a/examples/fabric-admin/device_manager/UniqueIdGetter.h +++ b/examples/fabric-admin/device_manager/UniqueIdGetter.h @@ -24,6 +24,8 @@ #include #include +namespace admin { + /** * @brief Class used to get UniqueID from Bridged Device Basic Information Cluster * @@ -73,3 +75,5 @@ class UniqueIdGetter : public chip::app::ReadClient::Callback char mUniqueId[33]; chip::EndpointId mEndpointId; }; + +} // namespace admin diff --git a/examples/fabric-admin/main.cpp b/examples/fabric-admin/main.cpp index 5768abf496fefc..5b7219a2109786 100644 --- a/examples/fabric-admin/main.cpp +++ b/examples/fabric-admin/main.cpp @@ -32,7 +32,7 @@ using namespace chip; void ApplicationInit() { - DeviceMgr().Init(); + admin::DeviceManager::Instance().Init(); } // ================================================================================ diff --git a/examples/fabric-admin/rpc/RpcClient.cpp b/examples/fabric-admin/rpc/RpcClient.cpp index 9964dc6767b67e..f99d925d9d3da3 100644 --- a/examples/fabric-admin/rpc/RpcClient.cpp +++ b/examples/fabric-admin/rpc/RpcClient.cpp @@ -28,6 +28,8 @@ using namespace chip; +namespace admin { + namespace { // Constants @@ -57,7 +59,7 @@ CHIP_ERROR WaitForResponse(CallType & call) } else { - fprintf(stderr, "RPC Response timed out!"); + fprintf(stderr, "RPC Response timed out!\n"); return CHIP_ERROR_TIMEOUT; } } @@ -227,3 +229,5 @@ CHIP_ERROR DeviceReachableChanged(const chip_rpc_ReachabilityChanged & data) return WaitForResponse(call); } + +} // namespace admin diff --git a/examples/fabric-admin/rpc/RpcClient.h b/examples/fabric-admin/rpc/RpcClient.h index a4cefe8bd8e076..642e2637710ad4 100644 --- a/examples/fabric-admin/rpc/RpcClient.h +++ b/examples/fabric-admin/rpc/RpcClient.h @@ -23,6 +23,8 @@ #include "fabric_bridge_service/fabric_bridge_service.rpc.pb.h" +namespace admin { + /** * @brief Sets the RPC server port to which the RPC client will connect. * @@ -99,3 +101,5 @@ CHIP_ERROR AdminCommissioningAttributeChanged(const chip_rpc_AdministratorCommis * - CHIP_ERROR_INTERNAL: An internal error occurred while activating the RPC call. */ CHIP_ERROR DeviceReachableChanged(const chip_rpc_ReachabilityChanged & data); + +} // namespace admin diff --git a/examples/fabric-admin/rpc/RpcServer.cpp b/examples/fabric-admin/rpc/RpcServer.cpp index e10bb64cdc050f..05fb9492248131 100644 --- a/examples/fabric-admin/rpc/RpcServer.cpp +++ b/examples/fabric-admin/rpc/RpcServer.cpp @@ -38,6 +38,8 @@ using namespace ::chip; +namespace admin { + namespace { #if defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE @@ -110,9 +112,9 @@ class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate ChipLogValueX64(scopedNodeId.GetNodeId()), commissioningTimeoutSec, iterations, discriminator); // Open the device commissioning window using raw binary data for salt and verifier - DeviceMgr().OpenDeviceCommissioningWindow(scopedNodeId, iterations, commissioningTimeoutSec, discriminator, - ByteSpan(request.salt.bytes, request.salt.size), - ByteSpan(request.verifier.bytes, request.verifier.size)); + DeviceManager::Instance().OpenDeviceCommissioningWindow(scopedNodeId, iterations, commissioningTimeoutSec, discriminator, + ByteSpan(request.salt.bytes, request.salt.size), + ByteSpan(request.verifier.bytes, request.verifier.size)); response.success = true; @@ -144,13 +146,13 @@ class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate if (error == CHIP_NO_ERROR) { - NodeId nodeId = DeviceMgr().GetNextAvailableNodeId(); + NodeId nodeId = DeviceManager::Instance().GetNextAvailableNodeId(); // After responding with RequestCommissioningApproval to the node where the client initiated the // RequestCommissioningApproval, you need to wait for it to open a commissioning window on its bridge. usleep(kCommissionPrepareTimeMs * 1000); - DeviceMgr().PairRemoteDevice(nodeId, code.c_str()); + DeviceManager::Instance().PairRemoteDevice(nodeId, code.c_str()); } else { @@ -254,3 +256,5 @@ void InitRpcServer(uint16_t rpcServerPort) std::thread rpc_service(RunRpcService); rpc_service.detach(); } + +} // namespace admin diff --git a/examples/fabric-admin/rpc/RpcServer.h b/examples/fabric-admin/rpc/RpcServer.h index d283c0db5a0248..c8fcd33324588e 100644 --- a/examples/fabric-admin/rpc/RpcServer.h +++ b/examples/fabric-admin/rpc/RpcServer.h @@ -18,4 +18,8 @@ #pragma once +namespace admin { + void InitRpcServer(uint16_t rpcServerPort); + +} // namespace admin diff --git a/examples/fabric-admin/scripts/fabric-sync-app.py b/examples/fabric-admin/scripts/fabric-sync-app.py index bc26c655be9024..3de85b9f672887 100755 --- a/examples/fabric-admin/scripts/fabric-sync-app.py +++ b/examples/fabric-admin/scripts/fabric-sync-app.py @@ -32,6 +32,7 @@ async def forward_f(prefix: bytes, f_in: asyncio.StreamReader, This function can optionally feed received lines to a callback function. """ + while line := await f_in.readline(): if cb is not None: cb(line) diff --git a/examples/fabric-admin/scripts/run_fabric_sync.sh b/examples/fabric-admin/scripts/run_fabric_sync.sh index 49182f7ce92825..60e6f9554ec855 100755 --- a/examples/fabric-admin/scripts/run_fabric_sync.sh +++ b/examples/fabric-admin/scripts/run_fabric_sync.sh @@ -104,6 +104,11 @@ else exit 1 fi +# Remove previous log files +rm /tmp/fabric_admin.log +rm /tmp/fabric_bridge_app.log +echo "Removed fabric sync log files." + # Start fabric-bridge-app if available and redirect its output to /dev/null if [ -f "$FABRIC_BRIDGE_APP_PATH" ]; then "$FABRIC_BRIDGE_APP_PATH" >"$FABRIC_BRIDGE_APP_LOG" 2>&1 & diff --git a/examples/fabric-admin/scripts/stop_fabric_sync.sh b/examples/fabric-admin/scripts/stop_fabric_sync.sh index a03e188b5eb0c6..e9e44f4a5dc9e6 100755 --- a/examples/fabric-admin/scripts/stop_fabric_sync.sh +++ b/examples/fabric-admin/scripts/stop_fabric_sync.sh @@ -22,6 +22,3 @@ fi # Remove /tmp/chip_* files and directories rm -rf /tmp/chip_* echo "Removed /tmp/chip_* files and directories." -rm /tmp/fabric_admin.log -rm /tmp/fabric_bridge_app.log -echo "Removed fabric sync log files." diff --git a/examples/fabric-admin/with_pw_rpc.gni b/examples/fabric-admin/with_pw_rpc.gni index abb9ac65f27e78..d5e1aae432216d 100644 --- a/examples/fabric-admin/with_pw_rpc.gni +++ b/examples/fabric-admin/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -39,4 +39,3 @@ pw_build_LINK_DEPS = [ ] chip_enable_pw_rpc = true -chip_use_pw_logging = true diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h index 06fd9026d44225..7b5711d39557e9 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h @@ -20,6 +20,8 @@ #include #include +namespace bridge { + /** * @brief CADMIN cluster implementation for handling attribute interactions of bridged device endpoints. * @@ -56,3 +58,5 @@ class BridgedAdministratorCommissioning : public chip::app::AttributeAccessInter // to reflect this change. chip::app::AttributeAccessInterface * mOriginalAttributeInterface = nullptr; }; + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDevice.h b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDevice.h index d2c5a64b9ef4b7..ed5c9710624225 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDevice.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDevice.h @@ -23,6 +23,8 @@ #include +namespace bridge { + class BridgedDevice { public: @@ -90,3 +92,5 @@ class BridgedDevice BridgedAttributes mAttributes; AdminCommissioningAttributes mAdminCommissioningAttributes; }; + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceBasicInformationImpl.h b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceBasicInformationImpl.h index 23403438ab2be8..f57f7d0362ae73 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceBasicInformationImpl.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceBasicInformationImpl.h @@ -18,6 +18,8 @@ #include #include +namespace bridge { + class BridgedDeviceBasicInformationImpl : public chip::app::AttributeAccessInterface { public: @@ -30,3 +32,5 @@ class BridgedDeviceBasicInformationImpl : public chip::app::AttributeAccessInter CHIP_ERROR Read(const chip::app::ConcreteReadAttributePath & path, chip::app::AttributeValueEncoder & encoder) override; CHIP_ERROR Write(const chip::app::ConcreteDataAttributePath & path, chip::app::AttributeValueDecoder & decoder) override; }; + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h index 127898fc5b2fab..d06c6fa4ae366e 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h @@ -24,11 +24,19 @@ #include +namespace bridge { + class BridgedDeviceManager { public: BridgedDeviceManager() = default; + static BridgedDeviceManager & Instance() + { + static BridgedDeviceManager instance; + return instance; + } + /** * @brief Initializes the BridgedDeviceManager. * @@ -110,8 +118,6 @@ class BridgedDeviceManager BridgedDevice * GetDeviceByUniqueId(const std::string & id); private: - friend BridgedDeviceManager & BridgeDeviceMgr(); - /** * Creates a new unique ID that is not used by any other mDevice */ @@ -124,13 +130,4 @@ class BridgedDeviceManager std::unique_ptr mDevices[CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT + 1]; }; -/** - * Returns the public interface of the BridgedDeviceManager singleton object. - * - * Applications should use this to access features of the BridgedDeviceManager - * object. - */ -inline BridgedDeviceManager & BridgeDeviceMgr() -{ - return BridgedDeviceManager::sInstance; -} +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp index a0d87cbb3b81ef..6cfb5a5caaedd7 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp @@ -26,6 +26,8 @@ using namespace chip::app; using namespace chip::app::Clusters; using namespace chip::app::Clusters::AdministratorCommissioning; +namespace bridge { + CHIP_ERROR BridgedAdministratorCommissioning::Init() { // We expect initialization after emberAfInit(). This allows us to unregister the existing @@ -43,7 +45,7 @@ CHIP_ERROR BridgedAdministratorCommissioning::Read(const ConcreteReadAttributePa { VerifyOrDie(aPath.mClusterId == Clusters::AdministratorCommissioning::Id); EndpointId endpointId = aPath.mEndpointId; - BridgedDevice * device = BridgeDeviceMgr().GetDevice(endpointId); + BridgedDevice * device = BridgedDeviceManager::Instance().GetDevice(endpointId); if (!device) { @@ -79,3 +81,5 @@ CHIP_ERROR BridgedAdministratorCommissioning::Read(const ConcreteReadAttributePa return CHIP_NO_ERROR; } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDevice.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDevice.cpp index f462d1cce6efd5..bd88c89145930e 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDevice.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDevice.cpp @@ -27,6 +27,8 @@ using namespace chip; using namespace chip::app::Clusters::Actions; +namespace bridge { + BridgedDevice::BridgedDevice(ScopedNodeId scopedNodeId) { mReachable = false; @@ -116,3 +118,5 @@ void BridgedDevice::SetAdminCommissioningAttributes(const AdminCommissioningAttr } }); } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp index 7fa48a4a158ddd..3a03d8f84a81a0 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp @@ -29,12 +29,14 @@ using namespace ::chip; using namespace ::chip::app; using namespace ::chip::app::Clusters; +namespace bridge { + CHIP_ERROR BridgedDeviceBasicInformationImpl::Read(const ConcreteReadAttributePath & path, AttributeValueEncoder & encoder) { // Registration is done for the bridged device basic information only VerifyOrDie(path.mClusterId == app::Clusters::BridgedDeviceBasicInformation::Id); - BridgedDevice * dev = BridgeDeviceMgr().GetDevice(path.mEndpointId); + BridgedDevice * dev = BridgedDeviceManager::Instance().GetDevice(path.mEndpointId); VerifyOrReturnError(dev != nullptr, CHIP_ERROR_NOT_FOUND); switch (path.mAttributeId) @@ -91,7 +93,7 @@ CHIP_ERROR BridgedDeviceBasicInformationImpl::Write(const ConcreteDataAttributeP { VerifyOrDie(path.mClusterId == app::Clusters::BridgedDeviceBasicInformation::Id); - BridgedDevice * dev = BridgeDeviceMgr().GetDevice(path.mEndpointId); + BridgedDevice * dev = BridgedDeviceManager::Instance().GetDevice(path.mEndpointId); VerifyOrReturnError(dev != nullptr, CHIP_ERROR_NOT_FOUND); if (!dev->IsReachable()) @@ -105,3 +107,5 @@ CHIP_ERROR BridgedDeviceBasicInformationImpl::Write(const ConcreteDataAttributeP return CHIP_ERROR_INVALID_ARGUMENT; } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp index 0265f912027ca0..5c53d413cbb344 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp @@ -45,6 +45,8 @@ using namespace chip::Transport; using namespace chip::DeviceLayer; using namespace chip::app::Clusters; +namespace bridge { + namespace { constexpr uint8_t kMaxRetries = 10; @@ -174,9 +176,6 @@ const EmberAfDeviceType sBridgedDeviceTypes[] = { { DEVICE_TYPE_BRIDGED_NODE, DE } // namespace -// Define the static member -BridgedDeviceManager BridgedDeviceManager::sInstance; - void BridgedDeviceManager::Init() { mFirstDynamicEndpointId = static_cast( @@ -343,3 +342,5 @@ std::optional BridgedDeviceManager::RemoveDeviceByScopedNodeId(chip::S } return std::nullopt; } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp b/examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp index 8a5c5af3db0566..aa12a4274ca0f8 100644 --- a/examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp +++ b/examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp @@ -186,13 +186,13 @@ CHIP_ERROR CommissionerControlDelegate::HandleCommissionNode(const Commissioning VerifyOrReturnError(mNextStep == Step::kStartCommissionNode, CHIP_ERROR_INCORRECT_STATE); #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE - err = CommissionNode(Controller::CommissioningWindowPasscodeParams() - .SetSetupPIN(kSetupPinCode) - .SetTimeout(params.commissioningTimeout) - .SetDiscriminator(params.discriminator) - .SetIteration(params.iterations) - .SetSalt(params.salt), - mVendorId, mProductId); + err = bridge::CommissionNode(Controller::CommissioningWindowPasscodeParams() + .SetSetupPIN(kSetupPinCode) + .SetTimeout(params.commissioningTimeout) + .SetDiscriminator(params.discriminator) + .SetIteration(params.iterations) + .SetSalt(params.salt), + mVendorId, mProductId); #else ChipLogProgress(NotSpecified, "Failed to reverse commission bridge: PW_RPC_FABRIC_BRIDGE_SERVICE not defined"); err = CHIP_ERROR_NOT_IMPLEMENTED; @@ -209,6 +209,8 @@ CHIP_ERROR CommissionerControlDelegate::HandleCommissionNode(const Commissioning } // namespace app } // namespace chip +namespace bridge { + CHIP_ERROR CommissionerControlInit() { CHIP_ERROR err; @@ -262,3 +264,5 @@ CHIP_ERROR CommissionerControlShutdown() return CHIP_NO_ERROR; } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/README.md b/examples/fabric-bridge-app/linux/README.md index fdb466147e3cf4..912bb32c01dafb 100644 --- a/examples/fabric-bridge-app/linux/README.md +++ b/examples/fabric-bridge-app/linux/README.md @@ -100,13 +100,13 @@ defined: Pull Docker Images ``` - docker pull ghcr.io/project-chip/chip-build-crosscompile:81 + docker pull ghcr.io/project-chip/chip-build-crosscompile:90 ``` Run docker ``` - docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:81 /bin/bash + docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:90 /bin/bash ``` Build diff --git a/examples/fabric-bridge-app/linux/RpcClient.cpp b/examples/fabric-bridge-app/linux/RpcClient.cpp index 732fdf8aa1bf80..ef41ae261dab9b 100644 --- a/examples/fabric-bridge-app/linux/RpcClient.cpp +++ b/examples/fabric-bridge-app/linux/RpcClient.cpp @@ -35,6 +35,8 @@ using namespace chip; +namespace bridge { + namespace { // Constants @@ -205,3 +207,5 @@ CHIP_ERROR KeepActive(chip::ScopedNodeId scopedNodeId, uint32_t stayActiveDurati return WaitForResponse(call); } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/RpcServer.cpp b/examples/fabric-bridge-app/linux/RpcServer.cpp index 5fea43c6ef2953..e699c474104064 100644 --- a/examples/fabric-bridge-app/linux/RpcServer.cpp +++ b/examples/fabric-bridge-app/linux/RpcServer.cpp @@ -37,6 +37,8 @@ using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; +namespace bridge { + namespace { #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE @@ -116,7 +118,7 @@ pw::Status FabricBridge::AddSynchronizedDevice(const chip_rpc_SynchronizedDevice device->SetBridgedAttributes(attributes); device->SetIcd(request.has_is_icd && request.is_icd); - auto result = BridgeDeviceMgr().AddDeviceEndpoint(std::move(device), 1 /* parentEndpointId */); + auto result = BridgedDeviceManager::Instance().AddDeviceEndpoint(std::move(device), 1 /* parentEndpointId */); if (!result.has_value()) { ChipLogError(NotSpecified, "Failed to add device with Id=[%d:0x" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), @@ -124,7 +126,7 @@ pw::Status FabricBridge::AddSynchronizedDevice(const chip_rpc_SynchronizedDevice return pw::Status::Unknown(); } - BridgedDevice * addedDevice = BridgeDeviceMgr().GetDeviceByScopedNodeId(scopedNodeId); + BridgedDevice * addedDevice = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(scopedNodeId); VerifyOrDie(addedDevice); CHIP_ERROR err = EcosystemInformation::EcosystemInformationServer::Instance().AddEcosystemInformationClusterToEndpoint( @@ -141,7 +143,7 @@ pw::Status FabricBridge::RemoveSynchronizedDevice(const chip_rpc_SynchronizedDev ChipLogProgress(NotSpecified, "Received RemoveSynchronizedDevice: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), ChipLogValueX64(scopedNodeId.GetNodeId())); - auto removed_idx = BridgeDeviceMgr().RemoveDeviceByScopedNodeId(scopedNodeId); + auto removed_idx = BridgedDeviceManager::Instance().RemoveDeviceByScopedNodeId(scopedNodeId); if (!removed_idx.has_value()) { ChipLogError(NotSpecified, "Failed to remove device with Id=[%d:0x" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), @@ -159,7 +161,7 @@ pw::Status FabricBridge::ActiveChanged(const chip_rpc_KeepActiveChanged & reques ChipLogProgress(NotSpecified, "Received ActiveChanged: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), ChipLogValueX64(scopedNodeId.GetNodeId())); - auto * device = BridgeDeviceMgr().GetDeviceByScopedNodeId(scopedNodeId); + auto * device = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(scopedNodeId); if (device == nullptr) { ChipLogError(NotSpecified, "Could not find bridged device associated with Id=[%d:0x" ChipLogFormatX64 "]", @@ -179,7 +181,7 @@ pw::Status FabricBridge::AdminCommissioningAttributeChanged(const chip_rpc_Admin ChipLogProgress(NotSpecified, "Received CADMIN attribute change: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), ChipLogValueX64(scopedNodeId.GetNodeId())); - auto * device = BridgeDeviceMgr().GetDeviceByScopedNodeId(scopedNodeId); + auto * device = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(scopedNodeId); if (device == nullptr) { ChipLogError(NotSpecified, "Could not find bridged device associated with Id=[%d:0x" ChipLogFormatX64 "]", @@ -218,7 +220,7 @@ pw::Status FabricBridge::DeviceReachableChanged(const chip_rpc_ReachabilityChang ChipLogProgress(NotSpecified, "Received device reachable changed: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), ChipLogValueX64(scopedNodeId.GetNodeId())); - auto * device = BridgeDeviceMgr().GetDeviceByScopedNodeId(scopedNodeId); + auto * device = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(scopedNodeId); if (device == nullptr) { ChipLogError(NotSpecified, "Could not find bridged device associated with Id=[%d:0x" ChipLogFormatX64 "]", @@ -256,3 +258,5 @@ void InitRpcServer(uint16_t rpcServerPort) std::thread rpc_service(RunRpcService); rpc_service.detach(); } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/include/CommissionerControlDelegate.h b/examples/fabric-bridge-app/linux/include/CommissionerControlDelegate.h index fceb80c2d802f5..2f9e15f508cccb 100644 --- a/examples/fabric-bridge-app/linux/include/CommissionerControlDelegate.h +++ b/examples/fabric-bridge-app/linux/include/CommissionerControlDelegate.h @@ -89,5 +89,9 @@ class CommissionerControlDelegate : public Delegate } // namespace app } // namespace chip +namespace bridge { + CHIP_ERROR CommissionerControlInit(); CHIP_ERROR CommissionerControlShutdown(); + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/include/RpcClient.h b/examples/fabric-bridge-app/linux/include/RpcClient.h index 1ede84ff446ecd..9a06686f068455 100644 --- a/examples/fabric-bridge-app/linux/include/RpcClient.h +++ b/examples/fabric-bridge-app/linux/include/RpcClient.h @@ -22,6 +22,8 @@ #include #include +namespace bridge { + /** * Sets the RPC server port to which the RPC client will connect. * @@ -70,3 +72,5 @@ CHIP_ERROR CommissionNode(chip::Controller::CommissioningWindowPasscodeParams params, chip::VendorId vendorId, uint16_t productId); CHIP_ERROR KeepActive(chip::ScopedNodeId scopedNodeId, uint32_t stayActiveDurationMs, uint32_t timeoutMs); + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/include/RpcServer.h b/examples/fabric-bridge-app/linux/include/RpcServer.h index d283c0db5a0248..ab0626c866d1a8 100644 --- a/examples/fabric-bridge-app/linux/include/RpcServer.h +++ b/examples/fabric-bridge-app/linux/include/RpcServer.h @@ -18,4 +18,8 @@ #pragma once +namespace bridge { + void InitRpcServer(uint16_t rpcServerPort); + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/main.cpp b/examples/fabric-bridge-app/linux/main.cpp index 574053424f7895..8c622cac541004 100644 --- a/examples/fabric-bridge-app/linux/main.cpp +++ b/examples/fabric-bridge-app/linux/main.cpp @@ -98,7 +98,7 @@ ArgParser::OptionSet sProgramCustomOptions = { HandleCustomOption, sProgramCusto #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE void AttemptRpcClientConnect(System::Layer * systemLayer, void * appState) { - if (StartRpcClient() == CHIP_NO_ERROR) + if (bridge::StartRpcClient() == CHIP_NO_ERROR) { ChipLogProgress(NotSpecified, "Connected to Fabric-Admin"); } @@ -110,6 +110,10 @@ void AttemptRpcClientConnect(System::Layer * systemLayer, void * appState) } #endif // defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE +} // namespace + +namespace bridge { + class AdministratorCommissioningCommandHandler : public CommandHandlerInterface { public: @@ -147,7 +151,7 @@ void AdministratorCommissioningCommandHandler::InvokeCommand(HandlerContext & ha Status status = Status::Failure; #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE - BridgedDevice * device = BridgeDeviceMgr().GetDevice(endpointId); + BridgedDevice * device = BridgedDeviceManager::Instance().GetDevice(endpointId); // TODO: issues:#33784, need to make OpenCommissioningWindow synchronous if (device != nullptr && @@ -210,7 +214,7 @@ void BridgedDeviceInformationCommandHandler::InvokeCommand(HandlerContext & hand return; } - BridgedDevice * device = BridgeDeviceMgr().GetDevice(endpointId); + BridgedDevice * device = BridgedDeviceManager::Instance().GetDevice(endpointId); if (device == nullptr || !device->IsIcd()) { handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, Status::Failure); @@ -241,27 +245,27 @@ BridgedDeviceBasicInformationImpl gBridgedDeviceBasicInformationAttributes; AdministratorCommissioningCommandHandler gAdministratorCommissioningCommandHandler; BridgedDeviceInformationCommandHandler gBridgedDeviceInformationCommandHandler; -} // namespace +} // namespace bridge void ApplicationInit() { ChipLogDetail(NotSpecified, "Fabric-Bridge: ApplicationInit()"); MatterEcosystemInformationPluginServerInitCallback(); - CommandHandlerInterfaceRegistry::Instance().RegisterCommandHandler(&gAdministratorCommissioningCommandHandler); - CommandHandlerInterfaceRegistry::Instance().RegisterCommandHandler(&gBridgedDeviceInformationCommandHandler); - AttributeAccessInterfaceRegistry::Instance().Register(&gBridgedDeviceBasicInformationAttributes); + CommandHandlerInterfaceRegistry::Instance().RegisterCommandHandler(&bridge::gAdministratorCommissioningCommandHandler); + CommandHandlerInterfaceRegistry::Instance().RegisterCommandHandler(&bridge::gBridgedDeviceInformationCommandHandler); + AttributeAccessInterfaceRegistry::Instance().Register(&bridge::gBridgedDeviceBasicInformationAttributes); #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE - SetRpcRemoteServerPort(gFabricAdminServerPort); - InitRpcServer(gLocalServerPort); + bridge::SetRpcRemoteServerPort(gFabricAdminServerPort); + bridge::InitRpcServer(gLocalServerPort); AttemptRpcClientConnect(&DeviceLayer::SystemLayer(), nullptr); #endif - BridgeDeviceMgr().Init(); - VerifyOrDie(gBridgedAdministratorCommissioning.Init() == CHIP_NO_ERROR); + bridge::BridgedDeviceManager::Instance().Init(); + VerifyOrDie(bridge::gBridgedAdministratorCommissioning.Init() == CHIP_NO_ERROR); - VerifyOrDieWithMsg(CommissionerControlInit() == CHIP_NO_ERROR, NotSpecified, + VerifyOrDieWithMsg(bridge::CommissionerControlInit() == CHIP_NO_ERROR, NotSpecified, "Failed to initialize Commissioner Control Server"); } @@ -269,7 +273,7 @@ void ApplicationShutdown() { ChipLogDetail(NotSpecified, "Fabric-Bridge: ApplicationShutdown()"); - if (CommissionerControlShutdown() != CHIP_NO_ERROR) + if (bridge::CommissionerControlShutdown() != CHIP_NO_ERROR) { ChipLogError(NotSpecified, "Failed to shutdown Commissioner Control Server"); } diff --git a/examples/fabric-bridge-app/linux/with_pw_rpc.gni b/examples/fabric-bridge-app/linux/with_pw_rpc.gni index e1bd567cf22db2..335a1f309666b0 100644 --- a/examples/fabric-bridge-app/linux/with_pw_rpc.gni +++ b/examples/fabric-bridge-app/linux/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -38,5 +38,4 @@ pw_build_LINK_DEPS = [ "$dir_pw_log:impl", ] -chip_use_pw_logging = true bridge_enable_pw_rpc = true diff --git a/examples/fabric-sync/BUILD.gn b/examples/fabric-sync/BUILD.gn index de193bd5f6207a..95b0ce3c60c46e 100644 --- a/examples/fabric-sync/BUILD.gn +++ b/examples/fabric-sync/BUILD.gn @@ -22,21 +22,35 @@ assert(chip_build_tools) executable("fabric-sync") { cflags = [ "-Wconversion" ] + defines = [] + + if (chip_build_libshell) { + defines += [ "ENABLE_CHIP_SHELL" ] + } + include_dirs = [ ".", "${chip_root}/src/lib", ] + if (chip_build_libshell) { + include_dirs += [ "shell" ] + } + sources = [ "main.cpp" ] deps = [ + "${chip_root}/examples/fabric-sync/admin:fabric-admin-lib", "${chip_root}/examples/fabric-sync/bridge:fabric-bridge-lib", - "${chip_root}/examples/fabric-sync/bridge:fabric-bridge-zap", "${chip_root}/examples/platform/linux:app-main", "${chip_root}/src/lib", "${chip_root}/third_party/inipp", ] + if (chip_build_libshell) { + deps += [ "${chip_root}/examples/fabric-sync/shell" ] + } + output_dir = root_out_dir } diff --git a/examples/fabric-sync/README.md b/examples/fabric-sync/README.md index 0309218725f02b..0fd4735c745552 100644 --- a/examples/fabric-sync/README.md +++ b/examples/fabric-sync/README.md @@ -92,13 +92,13 @@ defined: Pull Docker Images ``` - docker pull ghcr.io/project-chip/chip-build-crosscompile:81 + docker pull ghcr.io/project-chip/chip-build-crosscompile:90 ``` Run docker ``` - docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:81 /bin/bash + docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:90 /bin/bash ``` Build diff --git a/examples/fabric-sync/admin/BUILD.gn b/examples/fabric-sync/admin/BUILD.gn new file mode 100644 index 00000000000000..2ccc30ca2f7976 --- /dev/null +++ b/examples/fabric-sync/admin/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("${chip_root}/src/app/chip_data_model.gni") + +config("config") { + include_dirs = [ + ".", + "${chip_root}/examples/fabric-sync", + "${chip_root}/examples/platform/linux", + "${chip_root}/src/lib", + ] +} + +source_set("fabric-admin-lib") { + public_configs = [ ":config" ] + + sources = [ + "BridgeSubscription.cpp", + "BridgeSubscription.h", + "CommissionerControl.cpp", + "CommissionerControl.h", + "DeviceManager.cpp", + "DeviceManager.h", + "DeviceSubscription.cpp", + "DeviceSubscription.h", + "DeviceSubscriptionManager.cpp", + "DeviceSubscriptionManager.h", + "DeviceSynchronization.cpp", + "DeviceSynchronization.h", + "FabricAdmin.cpp", + "FabricAdmin.h", + "FabricSyncGetter.cpp", + "FabricSyncGetter.h", + "PairingManager.cpp", + "PairingManager.h", + "UniqueIdGetter.cpp", + "UniqueIdGetter.h", + ] + + deps = [ + "${chip_root}/examples/fabric-sync/bridge:fabric-bridge-lib", + "${chip_root}/examples/platform/linux:app-main", + "${chip_root}/src/lib", + ] +} diff --git a/examples/fabric-sync/admin/BridgeSubscription.cpp b/examples/fabric-sync/admin/BridgeSubscription.cpp new file mode 100644 index 00000000000000..1df9371ff74dff --- /dev/null +++ b/examples/fabric-sync/admin/BridgeSubscription.cpp @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2024 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 "BridgeSubscription.h" +#include "DeviceManager.h" + +using namespace ::chip; +using namespace ::chip::app; +using chip::app::ReadClient; + +namespace admin { + +namespace { + +constexpr uint16_t kSubscribeMinInterval = 0; +constexpr uint16_t kSubscribeMaxInterval = 60; + +void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) +{ + reinterpret_cast(context)->OnDeviceConnected(exchangeMgr, sessionHandle); +} + +void OnDeviceConnectionFailureWrapper(void * context, const ScopedNodeId & peerId, CHIP_ERROR error) +{ + reinterpret_cast(context)->OnDeviceConnectionFailure(peerId, error); +} + +} // namespace + +BridgeSubscription::BridgeSubscription() : + mOnDeviceConnectedCallback(OnDeviceConnectedWrapper, this), + mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureWrapper, this) +{} + +CHIP_ERROR BridgeSubscription::StartSubscription(Controller::DeviceController & controller, NodeId nodeId, EndpointId endpointId) +{ + assertChipStackLockedByCurrentThread(); + + VerifyOrDie(!subscriptionStarted); // Ensure it's not called multiple times. + + // Mark as started + subscriptionStarted = true; + + mEndpointId = endpointId; + + CHIP_ERROR err = controller.GetConnectedDevice(nodeId, &mOnDeviceConnectedCallback, &mOnDeviceConnectionFailureCallback); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to connect to remote fabric sync bridge %" CHIP_ERROR_FORMAT, err.Format()); + } + return err; +} + +void BridgeSubscription::OnAttributeData(const ConcreteDataAttributePath & path, TLV::TLVReader * data, const StatusIB & status) +{ + if (!status.IsSuccess()) + { + ChipLogError(NotSpecified, "Response Failure: %" CHIP_ERROR_FORMAT, status.ToChipError().Format()); + return; + } + + if (data == nullptr) + { + ChipLogError(NotSpecified, "Response Failure: No Data"); + return; + } + + DeviceManager::Instance().HandleAttributeData(path, *data); +} + +void BridgeSubscription::OnEventData(const app::EventHeader & eventHeader, TLV::TLVReader * data, const app::StatusIB * status) +{ + if (status != nullptr) + { + CHIP_ERROR error = status->ToChipError(); + if (CHIP_NO_ERROR != error) + { + ChipLogError(NotSpecified, "Response Failure: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + } + + if (data == nullptr) + { + ChipLogError(NotSpecified, "Response Failure: No Data"); + return; + } + + DeviceManager::Instance().HandleEventData(eventHeader, *data); +} + +void BridgeSubscription::OnError(CHIP_ERROR error) +{ + ChipLogProgress(NotSpecified, "Error on remote fabric sync bridge subscription: %" CHIP_ERROR_FORMAT, error.Format()); +} + +void BridgeSubscription::OnDone(ReadClient * apReadClient) +{ + mClient.reset(); + ChipLogProgress(NotSpecified, "The remote fabric sync bridge subscription is terminated"); + + // Reset the subscription state to allow retry + subscriptionStarted = false; + + // TODO:(#36092) Fabric-Admin should attempt to re-subscribe when the subscription to the remote bridge is terminated. +} + +void BridgeSubscription::OnDeviceConnected(Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) +{ + mClient = std::make_unique(app::InteractionModelEngine::GetInstance(), &exchangeMgr /* echangeMgr */, + *this /* callback */, ReadClient::InteractionType::Subscribe); + VerifyOrDie(mClient); + + AttributePathParams readPaths[1]; + readPaths[0] = AttributePathParams(mEndpointId, Clusters::Descriptor::Id, Clusters::Descriptor::Attributes::PartsList::Id); + + EventPathParams eventPaths[1]; + eventPaths[0] = EventPathParams(mEndpointId, Clusters::CommissionerControl::Id, + Clusters::CommissionerControl::Events::CommissioningRequestResult::Id); + eventPaths[0].mIsUrgentEvent = true; + + ReadPrepareParams readParams(sessionHandle); + + readParams.mpAttributePathParamsList = readPaths; + readParams.mAttributePathParamsListSize = 1; + readParams.mpEventPathParamsList = eventPaths; + readParams.mEventPathParamsListSize = 1; + readParams.mMinIntervalFloorSeconds = kSubscribeMinInterval; + readParams.mMaxIntervalCeilingSeconds = kSubscribeMaxInterval; + readParams.mKeepSubscriptions = true; + + CHIP_ERROR err = mClient->SendRequest(readParams); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to issue subscription to the Descriptor Cluster of the remote bridged device."); + OnDone(nullptr); + return; + } +} + +void BridgeSubscription::OnDeviceConnectionFailure(const ScopedNodeId & peerId, CHIP_ERROR error) +{ + ChipLogError(NotSpecified, "BridgeSubscription failed to connect to " ChipLogFormatX64, ChipLogValueX64(peerId.GetNodeId())); + OnDone(nullptr); +} + +} // namespace admin diff --git a/examples/fabric-sync/admin/BridgeSubscription.h b/examples/fabric-sync/admin/BridgeSubscription.h new file mode 100644 index 00000000000000..e5f8c73fc14257 --- /dev/null +++ b/examples/fabric-sync/admin/BridgeSubscription.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2024 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 + +namespace admin { + +/** + * @brief Class used to subscribe to attributes and events from the remote bridged device. + * + * The Descriptor Cluster contains attributes such as the Parts List, which provides a list + * of endpoints or devices that are part of a composite device or bridge. The CommissionerControl + * Cluster generates events related to commissioning requests, which can be monitored to track + * device commissioning status. + * + * When subscribing to attributes and events of a bridged device from another fabric, the class: + * - Establishes a secure session with the device (if needed) via CASE (Chip over + * Authenticated Session Establishment) session. + * - Subscribes to the specified attributes in the Descriptor Cluster (e.g., Parts List) and + * events in the CommissionerControl Cluster (e.g., CommissioningRequestResult) of the remote + * device on the specified node and endpoint. + * - Invokes the provided callback upon successful or unsuccessful subscription, allowing + * further handling of data or errors. + * + * This class also implements the necessary callbacks to handle attribute data reports, event data, + * errors, and session establishment procedures. + */ +class BridgeSubscription : public chip::app::ReadClient::Callback +{ +public: + BridgeSubscription(); + + CHIP_ERROR StartSubscription(chip::Controller::DeviceController & controller, chip::NodeId nodeId, chip::EndpointId endpointId); + + /////////////////////////////////////////////////////////////// + // ReadClient::Callback implementation + /////////////////////////////////////////////////////////////// + void OnAttributeData(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data, + const chip::app::StatusIB & status) override; + void OnEventData(const chip::app::EventHeader & eventHeader, chip::TLV::TLVReader * data, + const chip::app::StatusIB * status) override; + void OnError(CHIP_ERROR error) override; + void OnDone(chip::app::ReadClient * apReadClient) override; + + /////////////////////////////////////////////////////////////// + // callbacks for CASE session establishment + /////////////////////////////////////////////////////////////// + void OnDeviceConnected(chip::Messaging::ExchangeManager & exchangeMgr, const chip::SessionHandle & sessionHandle); + void OnDeviceConnectionFailure(const chip::ScopedNodeId & peerId, CHIP_ERROR error); + +private: + std::unique_ptr mClient; + + chip::Callback::Callback mOnDeviceConnectedCallback; + chip::Callback::Callback mOnDeviceConnectionFailureCallback; + chip::EndpointId mEndpointId; + bool subscriptionStarted = false; +}; + +} // namespace admin diff --git a/examples/fabric-sync/admin/CommissionerControl.cpp b/examples/fabric-sync/admin/CommissionerControl.cpp new file mode 100644 index 00000000000000..a0c24eb956d5bb --- /dev/null +++ b/examples/fabric-sync/admin/CommissionerControl.cpp @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2024 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 "CommissionerControl.h" +#include "DeviceManager.h" + +using namespace ::chip; + +namespace admin { + +void CommissionerControl::Init(Controller::DeviceCommissioner & commissioner, NodeId nodeId, EndpointId endpointId) +{ + // Ensure that mCommissioner is not already initialized + VerifyOrDie(mCommissioner == nullptr); + + ChipLogProgress(NotSpecified, "Initilize CommissionerControl"); + mCommissioner = &commissioner; + mDestinationId = nodeId; + mEndpointId = endpointId; +} + +CHIP_ERROR CommissionerControl::RequestCommissioningApproval(uint64_t requestId, uint16_t vendorId, uint16_t productId, + Optional label) +{ + VerifyOrReturnError(mCommissioner != nullptr, CHIP_ERROR_INCORRECT_STATE); + + ChipLogProgress(NotSpecified, "Sending RequestCommissioningApproval to node " ChipLogFormatX64, + ChipLogValueX64(mDestinationId)); + + mRequestCommissioningApproval.requestID = requestId; + mRequestCommissioningApproval.vendorID = static_cast(vendorId); + mRequestCommissioningApproval.productID = productId; + + if (label.HasValue()) + { + VerifyOrReturnError(label.Value().size() <= kMaxDeviceLabelLength, CHIP_ERROR_BUFFER_TOO_SMALL); + memcpy(mLabelBuffer, label.Value().data(), label.Value().size()); + mRequestCommissioningApproval.label = Optional>(CharSpan(mLabelBuffer, label.Value().size())); + } + + mCommandType = CommandType::kRequestCommissioningApproval; + return mCommissioner->GetConnectedDevice(mDestinationId, &mOnDeviceConnectedCallback, &mOnDeviceConnectionFailureCallback); +} + +CHIP_ERROR CommissionerControl::CommissionNode(uint64_t requestId, uint16_t responseTimeoutSeconds) +{ + VerifyOrReturnError(mCommissioner != nullptr, CHIP_ERROR_INCORRECT_STATE); + + ChipLogProgress(NotSpecified, "Sending CommissionNode to node " ChipLogFormatX64, ChipLogValueX64(mDestinationId)); + + mCommissionNode.requestID = requestId; + mCommissionNode.responseTimeoutSeconds = responseTimeoutSeconds; + + mCommandType = CommandType::kCommissionNode; + return mCommissioner->GetConnectedDevice(mDestinationId, &mOnDeviceConnectedCallback, &mOnDeviceConnectionFailureCallback); +} + +void CommissionerControl::OnResponse(app::CommandSender * client, const app::ConcreteCommandPath & path, + const app::StatusIB & status, TLV::TLVReader * data) +{ + ChipLogProgress(NotSpecified, "CommissionerControl: OnResponse."); + + CHIP_ERROR error = status.ToChipError(); + if (CHIP_NO_ERROR != error) + { + ChipLogError(NotSpecified, "Response Failure: %s", ErrorStr(error)); + return; + } + + if (data != nullptr) + { + DeviceManager::Instance().HandleCommandResponse(path, *data); + } +} + +void CommissionerControl::OnError(const app::CommandSender * client, CHIP_ERROR error) +{ + // Handle the error, then reset mCommandSender + ChipLogProgress(NotSpecified, "CommissionerControl: OnError: Error: %s", ErrorStr(error)); +} + +void CommissionerControl::OnDone(app::CommandSender * client) +{ + ChipLogProgress(NotSpecified, "CommissionerControl: OnDone."); + + switch (mCommandType) + { + case CommandType::kRequestCommissioningApproval: + ChipLogProgress(NotSpecified, "CommissionerControl: Command RequestCommissioningApproval has been successfully processed."); + break; + + case CommandType::kCommissionNode: + ChipLogProgress(NotSpecified, "CommissionerControl: Command CommissionNode has been successfully processed."); + break; + + default: + ChipLogError(NotSpecified, "CommissionerControl: Unknown or unhandled command type in OnDone."); + break; + } + + // Reset command type to undefined after processing is done + mCommandType = CommandType::kUndefined; + + // Ensure that mCommandSender is cleaned up after it is done + mCommandSender.reset(); +} + +CHIP_ERROR CommissionerControl::SendCommandForType(CommandType commandType, DeviceProxy * device) +{ + ChipLogProgress(AppServer, "Sending command with Endpoint ID: %d, Command Type: %d", mEndpointId, + static_cast(commandType)); + + switch (commandType) + { + case CommandType::kRequestCommissioningApproval: + return SendCommand(device, mEndpointId, app::Clusters::CommissionerControl::Id, + app::Clusters::CommissionerControl::Commands::RequestCommissioningApproval::Id, + mRequestCommissioningApproval); + case CommandType::kCommissionNode: + return SendCommand(device, mEndpointId, app::Clusters::CommissionerControl::Id, + app::Clusters::CommissionerControl::Commands::CommissionNode::Id, mCommissionNode); + default: + return CHIP_ERROR_INVALID_ARGUMENT; + } +} + +void CommissionerControl::OnDeviceConnectedFn(void * context, Messaging::ExchangeManager & exchangeMgr, + const SessionHandle & sessionHandle) +{ + CommissionerControl * self = reinterpret_cast(context); + VerifyOrReturn(self != nullptr, ChipLogError(NotSpecified, "OnDeviceConnectedFn: context is null")); + + OperationalDeviceProxy device(&exchangeMgr, sessionHandle); + + CHIP_ERROR err = self->SendCommandForType(self->mCommandType, &device); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to send CommissionerControl command."); + self->OnDone(nullptr); + } +} + +void CommissionerControl::OnDeviceConnectionFailureFn(void * context, const ScopedNodeId & peerId, CHIP_ERROR err) +{ + LogErrorOnFailure(err); + CommissionerControl * self = reinterpret_cast(context); + VerifyOrReturn(self != nullptr, ChipLogError(NotSpecified, "OnDeviceConnectedFn: context is null")); + self->OnDone(nullptr); +} + +} // namespace admin diff --git a/examples/fabric-sync/admin/CommissionerControl.h b/examples/fabric-sync/admin/CommissionerControl.h new file mode 100644 index 00000000000000..392367d6c04367 --- /dev/null +++ b/examples/fabric-sync/admin/CommissionerControl.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2024 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 + +namespace admin { + +/** + * @class CommissionerControl + * @brief This class handles sending CHIP commands related to commissioning, including sending + * commissioning approval requests and commissioning nodes. + * + * The class acts as a command sender and implements the `chip::app::CommandSender::Callback` interface + * to handle responses, errors, and completion events for the commands it sends. It relies on external + * CCTRL delegate and server mechanisms to manage the overall protocol and state transitions, including + * processing the CommissioningRequestResult and invoking CommissionNode. + */ +class CommissionerControl : public chip::app::CommandSender::Callback +{ +public: + CommissionerControl() : + mOnDeviceConnectedCallback(OnDeviceConnectedFn, this), mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureFn, this) + {} + + /** + * @brief Initializes the CommissionerControl with a DeviceCommissioner, NodeId, and EndpointId. + * + * @param commissioner The DeviceCommissioner to use for the commissioning process. + * @param nodeId The node ID of the remote fabric bridge. + * @param endpointId The endpoint on which to send CommissionerControl commands. + */ + void Init(chip::Controller::DeviceCommissioner & commissioner, chip::NodeId nodeId, chip::EndpointId endpointId); + + /** + * @brief Sends a RequestCommissioningApproval command to the device. + * + * @param requestId The unique request ID. + * @param vendorId The vendor ID of the device. + * @param productId The product ID of the device. + * @param label Optional label for the device. + * @return CHIP_ERROR CHIP_NO_ERROR on success, or an appropriate error code on failure. + */ + CHIP_ERROR RequestCommissioningApproval(uint64_t requestId, uint16_t vendorId, uint16_t productId, + chip::Optional label); + /** + * @brief Sends a CommissionNode command to the device. + * + * @param requestId The unique request ID. + * @param responseTimeoutSeconds Timeout for the response in seconds. + * @return CHIP_ERROR CHIP_NO_ERROR on success, or an appropriate error code on failure. + */ + CHIP_ERROR CommissionNode(uint64_t requestId, uint16_t responseTimeoutSeconds); + + /////////// CommandSender Callback Interface ///////// + virtual void OnResponse(chip::app::CommandSender * client, const chip::app::ConcreteCommandPath & path, + const chip::app::StatusIB & status, chip::TLV::TLVReader * data) override; + + virtual void OnError(const chip::app::CommandSender * client, CHIP_ERROR error) override; + + virtual void OnDone(chip::app::CommandSender * client) override; + +private: + static constexpr uint16_t kMaxDeviceLabelLength = 64; + + enum class CommandType : uint8_t + { + kUndefined = 0, + kRequestCommissioningApproval = 1, + kCommissionNode = 2, + }; + + template + CHIP_ERROR SendCommand(chip::DeviceProxy * device, chip::EndpointId endpointId, chip::ClusterId clusterId, + chip::CommandId commandId, const T & value) + { + chip::app::CommandPathParams commandPath = { endpointId, clusterId, commandId, + (chip::app::CommandPathFlags::kEndpointIdValid) }; + mCommandSender = std::make_unique(this, device->GetExchangeManager(), false, false, + device->GetSecureSession().Value()->AllowsLargePayload()); + + VerifyOrReturnError(mCommandSender != nullptr, CHIP_ERROR_NO_MEMORY); + + chip::app::CommandSender::AddRequestDataParameters addRequestDataParams(chip::NullOptional); + ReturnErrorOnFailure(mCommandSender->AddRequestData(commandPath, value, addRequestDataParams)); + ReturnErrorOnFailure(mCommandSender->SendCommandRequest(device->GetSecureSession().Value())); + + return CHIP_NO_ERROR; + } + + CHIP_ERROR SendCommandForType(CommandType commandType, chip::DeviceProxy * device); + + static void OnDeviceConnectedFn(void * context, chip::Messaging::ExchangeManager & exchangeMgr, + const chip::SessionHandle & sessionHandle); + static void OnDeviceConnectionFailureFn(void * context, const chip::ScopedNodeId & peerId, CHIP_ERROR error); + + // Private data members + chip::Controller::DeviceCommissioner * mCommissioner = nullptr; + std::unique_ptr mCommandSender; + chip::NodeId mDestinationId = chip::kUndefinedNodeId; + chip::EndpointId mEndpointId = chip::kRootEndpointId; + CommandType mCommandType = CommandType::kUndefined; + char mLabelBuffer[kMaxDeviceLabelLength]; + + chip::Callback::Callback mOnDeviceConnectedCallback; + chip::Callback::Callback mOnDeviceConnectionFailureCallback; + + chip::app::Clusters::CommissionerControl::Commands::RequestCommissioningApproval::Type mRequestCommissioningApproval; + chip::app::Clusters::CommissionerControl::Commands::CommissionNode::Type mCommissionNode; +}; + +} // namespace admin diff --git a/examples/fabric-sync/admin/DeviceManager.cpp b/examples/fabric-sync/admin/DeviceManager.cpp new file mode 100644 index 00000000000000..69aa0a583f7273 --- /dev/null +++ b/examples/fabric-sync/admin/DeviceManager.cpp @@ -0,0 +1,543 @@ +/* + * Copyright (c) 2024 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 "DeviceManager.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +using namespace chip; + +namespace admin { + +namespace { + +constexpr EndpointId kAggregatorEndpointId = 1; +constexpr uint16_t kWindowTimeout = 300; +constexpr uint16_t kIteration = 1000; +constexpr uint16_t kMaxDiscriminatorLength = 4095; + +} // namespace + +LinuxCommissionableDataProvider sCommissionableDataProvider; + +void DeviceManager::Init() +{ + // TODO: (#34113) Init mLastUsedNodeId from chip config file + mLastUsedNodeId = 1; + mInitialized = true; + + ChipLogProgress(NotSpecified, "DeviceManager initialized: last used nodeId " ChipLogFormatX64, + ChipLogValueX64(mLastUsedNodeId)); +} + +NodeId DeviceManager::GetNextAvailableNodeId() +{ + mLastUsedNodeId++; + VerifyOrDieWithMsg(mLastUsedNodeId < std::numeric_limits::max(), NotSpecified, "No more available NodeIds."); + + return mLastUsedNodeId; +} + +void DeviceManager::UpdateLastUsedNodeId(NodeId nodeId) +{ + if (nodeId > mLastUsedNodeId) + { + mLastUsedNodeId = nodeId; + ChipLogProgress(NotSpecified, "Updating last used NodeId to " ChipLogFormatX64, ChipLogValueX64(mLastUsedNodeId)); + } +} + +void DeviceManager::SetRemoteBridgeNodeId(chip::NodeId nodeId) +{ + mRemoteBridgeNodeId = nodeId; + + if (mRemoteBridgeNodeId != kUndefinedNodeId) + { + mCommissionerControl.Init(PairingManager::Instance().CurrentCommissioner(), mRemoteBridgeNodeId, kAggregatorEndpointId); + } +} + +void DeviceManager::AddSyncedDevice(const SyncedDevice & device) +{ + mSyncedDevices.insert(device); + ChipLogProgress(NotSpecified, "Added synced device: NodeId:" ChipLogFormatX64 ", EndpointId %u", + ChipLogValueX64(device.GetNodeId()), device.GetEndpointId()); +} + +SyncedDevice * DeviceManager::FindDeviceByEndpoint(EndpointId endpointId) +{ + for (auto & device : mSyncedDevices) + { + if (device.GetEndpointId() == endpointId) + { + return const_cast(&device); + } + } + return nullptr; +} + +SyncedDevice * DeviceManager::FindDeviceByNode(NodeId nodeId) +{ + for (auto & device : mSyncedDevices) + { + if (device.GetNodeId() == nodeId) + { + return const_cast(&device); + } + } + return nullptr; +} + +void DeviceManager::RemoveSyncedDevice(chip::ScopedNodeId scopedNodeId) +{ + NodeId nodeId = scopedNodeId.GetNodeId(); + + if (bridge::FabricBridge::Instance().RemoveSynchronizedDevice(scopedNodeId) != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to remove Node ID:" ChipLogFormatX64, ChipLogValueX64(nodeId)); + } + + SyncedDevice * device = FindDeviceByNode(nodeId); + if (device == nullptr) + { + ChipLogProgress(NotSpecified, "No device found with NodeId:" ChipLogFormatX64, ChipLogValueX64(nodeId)); + return; + } + + mSyncedDevices.erase(*device); + ChipLogProgress(NotSpecified, "Removed synced device: NodeId:" ChipLogFormatX64 ", EndpointId %u", + ChipLogValueX64(device->GetNodeId()), device->GetEndpointId()); +} + +void DeviceManager::OpenLocalBridgeCommissioningWindow(uint32_t iterations, uint16_t commissioningTimeoutSec, + uint16_t discriminator, const ByteSpan & salt, const ByteSpan & verifier) +{ + ChipLogProgress(NotSpecified, "Opening commissioning window of the local bridge"); + + auto & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); + auto commissioningTimeout = System::Clock::Seconds16(commissioningTimeoutSec); + + Optional> spake2pVerifier = verifier.empty() + ? Optional>::Missing() + : Optional>(std::vector(verifier.begin(), verifier.end())); + + Optional> spake2pSalt = salt.empty() + ? Optional>::Missing() + : Optional>(std::vector(salt.begin(), salt.end())); + + CHIP_ERROR err = + sCommissionableDataProvider.Init(spake2pVerifier, spake2pSalt, iterations, Optional(), discriminator); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to initialize the commissionable data provider of the local bridge: %s", ErrorStr(err)); + return; + } + + DeviceLayer::SetCommissionableDataProvider(&sCommissionableDataProvider); + + err = commissionMgr.OpenBasicCommissioningWindow(commissioningTimeout); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to open commissioning window of the local bridge: %s", ErrorStr(err)); + } +} + +void DeviceManager::OpenDeviceCommissioningWindow(ScopedNodeId scopedNodeId, uint32_t iterations, uint16_t commissioningTimeoutSec, + uint16_t discriminator, const ByteSpan & salt, const ByteSpan & verifier) +{ + // PairingManager isn't currently capable of OpenCommissioningWindow on a device of a fabric that it doesn't have + // the controller for. Currently no implementation need this functionality, but should they need it they will hit + // the verify or die below and it will be the responsiblity of whoever requires that functionality to implement. + VerifyOrDie(PairingManager::Instance().CurrentCommissioner().GetFabricIndex() == scopedNodeId.GetFabricIndex()); + ChipLogProgress(NotSpecified, "Opening commissioning window for Node ID: " ChipLogFormatX64, + ChipLogValueX64(scopedNodeId.GetNodeId())); + + // Open the commissioning window of a device within its own fabric. + CHIP_ERROR err = PairingManager::Instance().OpenCommissioningWindow( + scopedNodeId.GetNodeId(), kRootEndpointId, commissioningTimeoutSec, iterations, discriminator, salt, verifier); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to open commissioning window: %s", ErrorStr(err)); + } +} + +void DeviceManager::OpenRemoteDeviceCommissioningWindow(EndpointId remoteEndpointId) +{ + // Open the commissioning window of a device from another fabric via its fabric bridge. + // This method constructs and sends a command to open the commissioning window for a device + // that is part of a different fabric, accessed through a fabric bridge. + + // Use random discriminator to have less chance of collision. + uint16_t discriminator = + Crypto::GetRandU16() % (kMaxDiscriminatorLength + 1); // Include the upper limit kMaxDiscriminatorLength + + ByteSpan emptySalt; + ByteSpan emptyVerifier; + + CHIP_ERROR err = PairingManager::Instance().OpenCommissioningWindow(mRemoteBridgeNodeId, remoteEndpointId, kWindowTimeout, + kIteration, discriminator, emptySalt, emptyVerifier); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to open commissioning window: %s", ErrorStr(err)); + } +} + +CHIP_ERROR DeviceManager::PairRemoteFabricBridge(NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, + uint16_t deviceRemotePort) +{ + CHIP_ERROR err = PairingManager::Instance().PairDevice(nodeId, setupPINCode, deviceRemoteIp, deviceRemotePort); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, + "Failed to pair remote fabric bridge: Node ID " ChipLogFormatX64 " with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(nodeId), err.Format()); + return err; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DeviceManager::PairRemoteDevice(NodeId nodeId, const char * payload) +{ + CHIP_ERROR err = PairingManager::Instance().PairDeviceWithCode(nodeId, payload); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to pair device: Node ID " ChipLogFormatX64 " with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(nodeId), err.Format()); + return err; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DeviceManager::PairRemoteDevice(NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, + uint16_t deviceRemotePort) +{ + CHIP_ERROR err = PairingManager::Instance().PairDevice(nodeId, setupPINCode, deviceRemoteIp, deviceRemotePort); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to pair device: Node ID " ChipLogFormatX64 " with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(nodeId), err.Format()); + return err; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DeviceManager::UnpairRemoteFabricBridge() +{ + if (mRemoteBridgeNodeId == kUndefinedNodeId) + { + ChipLogError(NotSpecified, "Remote bridge node ID is undefined; cannot unpair device."); + return CHIP_ERROR_INCORRECT_STATE; + } + + CHIP_ERROR err = PairingManager::Instance().UnpairDevice(mRemoteBridgeNodeId); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to unpair remote bridge device " ChipLogFormatX64, ChipLogValueX64(mRemoteBridgeNodeId)); + return err; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DeviceManager::UnpairRemoteDevice(NodeId nodeId) +{ + CHIP_ERROR err = PairingManager::Instance().UnpairDevice(nodeId); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to unpair remote device " ChipLogFormatX64, ChipLogValueX64(nodeId)); + return err; + } + + return CHIP_NO_ERROR; +} + +void DeviceManager::SubscribeRemoteFabricBridge() +{ + ChipLogProgress(NotSpecified, "Start subscription to the remote bridge."); + + CHIP_ERROR error = mBridgeSubscriber.StartSubscription(PairingManager::Instance().CurrentCommissioner(), mRemoteBridgeNodeId, + kAggregatorEndpointId); + + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to subscribe to the remote bridge (NodeId: %lu). Error: %" CHIP_ERROR_FORMAT, + mRemoteBridgeNodeId, error.Format()); + return; + } +} + +void DeviceManager::ReadSupportedDeviceCategories() +{ + if (!IsFabricSyncReady()) + { + // print to console + fprintf(stderr, "Remote Fabric Bridge is not configured yet.\n"); + return; + } + + ChipLogProgress(NotSpecified, "Read SupportedDeviceCategories from the remote bridge."); + + CHIP_ERROR error = mFabricSyncGetter.GetFabricSynchronizationData( + [this](TLV::TLVReader & data) { this->HandleReadSupportedDeviceCategories(data); }, + PairingManager::Instance().CurrentCommissioner(), this->GetRemoteBridgeNodeId(), kAggregatorEndpointId); + + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, + "Failed to read SupportedDeviceCategories from the remote bridge (NodeId: %lu). Error: %" CHIP_ERROR_FORMAT, + mRemoteBridgeNodeId, error.Format()); + } +} + +void DeviceManager::HandleReadSupportedDeviceCategories(TLV::TLVReader & data) +{ + ChipLogProgress(NotSpecified, "Attribute SupportedDeviceCategories detected."); + + BitMask value; + CHIP_ERROR error = app::DataModel::Decode(data, value); + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to decode attribute value. Error: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + + if (value.Has(app::Clusters::CommissionerControl::SupportedDeviceCategoryBitmap::kFabricSynchronization)) + { + ChipLogProgress(NotSpecified, "Remote Fabric-Bridge supports Fabric Synchronization, start reverse commissioning."); + RequestCommissioningApproval(); + } + else + { + ChipLogProgress(NotSpecified, "Remote Fabric-Bridge does not support Fabric Synchronization."); + } +} + +void DeviceManager::RequestCommissioningApproval() +{ + ChipLogProgress(NotSpecified, "Starting reverse commissioning for bridge device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(mRemoteBridgeNodeId)); + + uint64_t requestId = Crypto::GetRandU64(); + uint16_t vendorId = static_cast(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID); + uint16_t productId = static_cast(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID); + + CHIP_ERROR error = mCommissionerControl.RequestCommissioningApproval(requestId, vendorId, productId, NullOptional); + + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, + "Failed to request commissioning-approval to the remote bridge (NodeId: %lu). Error: %" CHIP_ERROR_FORMAT, + mRemoteBridgeNodeId, error.Format()); + return; + } + + mRequestId = requestId; +} + +void DeviceManager::HandleCommissioningRequestResult(TLV::TLVReader & data) +{ + ChipLogProgress(NotSpecified, "CommissioningRequestResult event received."); + + app::Clusters::CommissionerControl::Events::CommissioningRequestResult::DecodableType value; + CHIP_ERROR error = app::DataModel::Decode(data, value); + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to decode event value. Error: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + + if (value.requestID != mRequestId) + { + ChipLogError(NotSpecified, "The RequestId does not match the RequestId provided to RequestCommissioningApproval"); + return; + } + + if (value.statusCode != static_cast(Protocols::InteractionModel::Status::Success)) + { + ChipLogError(NotSpecified, "The server is not ready to begin commissioning the requested device"); + return; + } + + // The server is ready to begin commissioning the requested device, request the Commissioner Control Server to begin + // commissioning a previously approved request. + SendCommissionNodeRequest(value.requestID, kResponseTimeoutSeconds); +} + +void DeviceManager::HandleAttributePartsListUpdate(TLV::TLVReader & data) +{ + ChipLogProgress(NotSpecified, "Attribute PartsList change detected:"); + + app::DataModel::DecodableList value; + CHIP_ERROR error = app::DataModel::Decode(data, value); + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to decode attribute value. Error: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + + std::set newEndpoints; + + // Populate the newEndpoints set from the decoded value using an iterator + auto iter = value.begin(); + while (iter.Next()) + { + newEndpoints.insert(iter.GetValue()); + } + + if (iter.GetStatus() != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to iterate over decoded attribute value."); + return; + } + + // Compare newEndpoints with mSyncedDevices to determine added and removed endpoints + std::vector addedEndpoints; + std::vector removedEndpoints; + + // Note: We're using vectors and manual searches instead of set operations + // because we need to work with the SyncedDevice objects in mSyncedDevices, + // not just their EndpointIds. This approach allows us to access the full + // Device information when processing changes. + + // Find added endpoints + for (const auto & endpoint : newEndpoints) + { + if (FindDeviceByEndpoint(endpoint) == nullptr) + { + addedEndpoints.push_back(endpoint); + } + } + + // Find removed endpoints + for (auto & device : mSyncedDevices) + { + EndpointId endpointId = device.GetEndpointId(); + if (newEndpoints.find(endpointId) == newEndpoints.end()) + { + removedEndpoints.push_back(endpointId); + } + } + + // Process added endpoints + for (const auto & endpoint : addedEndpoints) + { + // print to console + fprintf(stderr, "A new device is added on Endpoint: %u\n", endpoint); + } + + // Process removed endpoints + for (const auto & endpoint : removedEndpoints) + { + ChipLogProgress(NotSpecified, "Endpoint removed: %u", endpoint); + + SyncedDevice * device = FindDeviceByEndpoint(endpoint); + + if (device == nullptr) + { + ChipLogProgress(NotSpecified, "No device on Endpoint: %u", endpoint); + continue; + } + } +} + +void DeviceManager::SendCommissionNodeRequest(uint64_t requestId, uint16_t responseTimeoutSeconds) +{ + ChipLogProgress(NotSpecified, "Request the Commissioner Control Server to begin commissioning a previously approved request."); + + CHIP_ERROR error = mCommissionerControl.CommissionNode(requestId, responseTimeoutSeconds); + + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, + "Failed to send CommissionNode command to the remote bridge (NodeId: %lu). Error: %" CHIP_ERROR_FORMAT, + mRemoteBridgeNodeId, error.Format()); + return; + } +} + +void DeviceManager::HandleReverseOpenCommissioningWindow(TLV::TLVReader & data) +{ + ChipLogProgress(NotSpecified, "Handle ReverseOpenCommissioningWindow command."); + + app::Clusters::CommissionerControl::Commands::ReverseOpenCommissioningWindow::DecodableType value; + CHIP_ERROR error = app::DataModel::Decode(data, value); + + if (error != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to decode command response value. Error: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + + // Log all fields + ChipLogProgress(NotSpecified, "DecodableType fields:"); + ChipLogProgress(NotSpecified, " commissioningTimeout: %u", value.commissioningTimeout); + ChipLogProgress(NotSpecified, " discriminator: %u", value.discriminator); + ChipLogProgress(NotSpecified, " iterations: %u", value.iterations); + ChipLogProgress(NotSpecified, " PAKEPasscodeVerifier size: %lu", value.PAKEPasscodeVerifier.size()); + ChipLogProgress(NotSpecified, " salt size: %lu", value.salt.size()); + + OpenLocalBridgeCommissioningWindow(value.iterations, value.commissioningTimeout, value.discriminator, + ByteSpan(value.salt.data(), value.salt.size()), + ByteSpan(value.PAKEPasscodeVerifier.data(), value.PAKEPasscodeVerifier.size())); +} + +void DeviceManager::HandleAttributeData(const app::ConcreteDataAttributePath & path, TLV::TLVReader & data) +{ + if (path.mClusterId == app::Clusters::Descriptor::Id && + path.mAttributeId == app::Clusters::Descriptor::Attributes::PartsList::Id) + { + HandleAttributePartsListUpdate(data); + return; + } +} + +void DeviceManager::HandleEventData(const app::EventHeader & header, TLV::TLVReader & data) +{ + if (header.mPath.mClusterId == app::Clusters::CommissionerControl::Id && + header.mPath.mEventId == app::Clusters::CommissionerControl::Events::CommissioningRequestResult::Id) + { + HandleCommissioningRequestResult(data); + } +} + +void DeviceManager::HandleCommandResponse(const app::ConcreteCommandPath & path, TLV::TLVReader & data) +{ + ChipLogProgress(NotSpecified, "Command Response received."); + + if (path.mClusterId == app::Clusters::CommissionerControl::Id && + path.mCommandId == app::Clusters::CommissionerControl::Commands::ReverseOpenCommissioningWindow::Id) + { + VerifyOrDie(path.mEndpointId == kAggregatorEndpointId); + HandleReverseOpenCommissioningWindow(data); + } +} + +} // namespace admin diff --git a/examples/fabric-sync/admin/DeviceManager.h b/examples/fabric-sync/admin/DeviceManager.h new file mode 100644 index 00000000000000..9afb1eec7d033f --- /dev/null +++ b/examples/fabric-sync/admin/DeviceManager.h @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2024 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 "BridgeSubscription.h" +#include "CommissionerControl.h" +#include "FabricSyncGetter.h" +#include "PairingManager.h" + +#include +#include +#include + +namespace admin { + +constexpr uint32_t kDefaultSetupPinCode = 20202021; +constexpr uint16_t kResponseTimeoutSeconds = 30; + +class SyncedDevice +{ +public: + SyncedDevice(chip::NodeId nodeId, chip::EndpointId endpointId) : mNodeId(nodeId), mEndpointId(endpointId) {} + + chip::NodeId GetNodeId() const { return mNodeId; } + chip::EndpointId GetEndpointId() const { return mEndpointId; } + + bool operator<(const SyncedDevice & other) const + { + return mNodeId < other.mNodeId || (mNodeId == other.mNodeId && mEndpointId < other.mEndpointId); + } + +private: + chip::NodeId mNodeId; + chip::EndpointId mEndpointId; +}; + +class DeviceManager +{ +public: + DeviceManager() = default; + + static DeviceManager & Instance() + { + static DeviceManager instance; + return instance; + } + + void Init(); + + chip::NodeId GetNextAvailableNodeId(); + + chip::NodeId GetRemoteBridgeNodeId() const { return mRemoteBridgeNodeId; } + + void UpdateLastUsedNodeId(chip::NodeId nodeId); + + void SetRemoteBridgeNodeId(chip::NodeId nodeId); + + bool IsFabricSyncReady() const { return mRemoteBridgeNodeId != chip::kUndefinedNodeId; } + + void AddSyncedDevice(const SyncedDevice & device); + + void RemoveSyncedDevice(chip::ScopedNodeId scopedNodeId); + + /** + * @brief Determines whether a given nodeId corresponds to the remote bridge device. + * + * @param nodeId The ID of the node being checked. + * + * @return true if the nodeId matches the remote bridge device; otherwise, false. + */ + bool IsCurrentBridgeDevice(chip::NodeId nodeId) const { return nodeId == mRemoteBridgeNodeId; } + + /** + * @brief Open the commissioning window of the local bridge. + * + * @param iterations The number of PBKDF (Password-Based Key Derivation Function) iterations to use + * for deriving the PAKE (Password Authenticated Key Exchange) verifier. + * @param commissioningTimeoutSec The time in seconds before the commissioning window closes. This value determines + * how long the commissioning window remains open for incoming connections. + * @param discriminator The device-specific discriminator, determined during commissioning, which helps + * to uniquely identify the device among others. + * @param salt The salt used in the cryptographic operations for commissioning. + * @param verifier The PAKE verifier used to authenticate the commissioning process. + * + */ + void OpenLocalBridgeCommissioningWindow(uint32_t iterations, uint16_t commissioningTimeoutSec, uint16_t discriminator, + const chip::ByteSpan & salt, const chip::ByteSpan & verifier); + + /** + * @brief Open the commissioning window for a specific device within its own fabric. + * + * This function initiates the process to open the commissioning window for a device identified by the given node ID. + * + * @param scopedNodeId The scoped node ID of the device that should open the commissioning window. + * @param iterations The number of PBKDF (Password-Based Key Derivation Function) iterations to use + * for deriving the PAKE (Password Authenticated Key Exchange) verifier. + * @param commissioningTimeoutSec The time in seconds before the commissioning window closes. This value determines + * how long the commissioning window remains open for incoming connections. + * @param discriminator The device-specific discriminator, determined during commissioning, which helps + * to uniquely identify the device among others. + * @param salt The salt used in the cryptographic operations for commissioning. + * @param verifier The PAKE verifier used to authenticate the commissioning process. + * + */ + void OpenDeviceCommissioningWindow(chip::ScopedNodeId scopedNodeId, uint32_t iterations, uint16_t commissioningTimeoutSec, + uint16_t discriminator, const chip::ByteSpan & salt, const chip::ByteSpan & verifier); + + /** + * @brief Open the commissioning window of a device from another fabric via its fabric bridge. + * + * This function initiates the process to open the commissioning window for a device that belongs to another + * fabric, accessed through a fabric bridge. + * + * @param remoteEndpointId The endpoint ID of the remote device that should open the commissioning window. + * This endpoint is associated with the device in the other fabric, accessed via the + * fabric bridge. + * + * @note This function is used when the device to be commissioned is part of a different fabric and must be + * accessed through an intermediary fabric bridge. + */ + void OpenRemoteDeviceCommissioningWindow(chip::EndpointId remoteEndpointId); + + /** + * @brief Pair a remote fabric bridge with a given node ID. + * + * This function initiates the pairing process for a remote fabric bridge using the specified parameters. + + * @param nodeId The user-defined ID for the node being commissioned. It doesn’t need to be the same ID, + * as for the first fabric. + * @param setupPINCode The setup PIN code used to authenticate the pairing process. + * @param deviceRemoteIp The IP address of the remote device that is being paired as part of the fabric bridge. + * @param deviceRemotePort The secured device port of the remote device that is being paired as part of the fabric bridge. + * + * @return CHIP_ERROR Returns CHIP_NO_ERROR on success or an appropriate error code on failure. + */ + CHIP_ERROR PairRemoteFabricBridge(chip::NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, + uint16_t deviceRemotePort); + + /** + * @brief Pair a remote Matter device to the current fabric. + * + * This function initiates the pairing process for a remote device using the specified parameters. + + * @param nodeId The user-defined ID for the node being commissioned. It doesn’t need to be the same ID, + * as for the first fabric. + * @param payload The the QR code payload or a manual pairing code generated by the first commissioner + * instance when opened commissioning window. + * + * @return CHIP_ERROR Returns CHIP_NO_ERROR on success or an appropriate error code on failure. + */ + CHIP_ERROR PairRemoteDevice(chip::NodeId nodeId, const char * payload); + + /** + * @brief Pair a remote Matter device to the current fabric. + * + * This function initiates the pairing process for a remote device using the specified parameters. + + * @param nodeId The user-defined ID for the node being commissioned. It doesn’t need to be the same ID, + * as for the first fabric. + * @param setupPINCode The setup PIN code used to authenticate the pairing process. + * @param deviceRemoteIp The IP address of the remote device that is being paired as part of the fabric bridge. + * @param deviceRemotePort The secured device port of the remote device that is being paired as part of the fabric bridge. + * + * @return CHIP_ERROR Returns CHIP_NO_ERROR on success or an appropriate error code on failure. + */ + CHIP_ERROR PairRemoteDevice(chip::NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, uint16_t deviceRemotePort); + + /** + * @brief Unpair the remote Matter fabric bridge. + * + * This function initiates the unpairing process for the remote Matter fabric bridge from the current fabric. + * + * @return CHIP_ERROR Returns CHIP_NO_ERROR on success or an appropriate error code on failure. + */ + CHIP_ERROR UnpairRemoteFabricBridge(); + + /** + * @brief Unpair a specific remote Matter device from the current fabric. + * + * This function removes a specific remote device, identified by the node ID, from the fabric. + * + * @param nodeId The user-defined ID of the node that is being unpaired. + * + * @return CHIP_ERROR Returns CHIP_NO_ERROR on success or an appropriate error code on failure. + */ + CHIP_ERROR UnpairRemoteDevice(chip::NodeId nodeId); + + void SubscribeRemoteFabricBridge(); + + void ReadSupportedDeviceCategories(); + + void HandleAttributeData(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader & data); + + void HandleEventData(const chip::app::EventHeader & header, chip::TLV::TLVReader & data); + + void HandleCommandResponse(const chip::app::ConcreteCommandPath & path, chip::TLV::TLVReader & data); + + SyncedDevice * FindDeviceByEndpoint(chip::EndpointId endpointId); + SyncedDevice * FindDeviceByNode(chip::NodeId nodeId); + +private: + void RequestCommissioningApproval(); + + void HandleReadSupportedDeviceCategories(chip::TLV::TLVReader & data); + + void HandleCommissioningRequestResult(chip::TLV::TLVReader & data); + + void HandleAttributePartsListUpdate(chip::TLV::TLVReader & data); + + void SendCommissionNodeRequest(uint64_t requestId, uint16_t responseTimeoutSeconds); + + void HandleReverseOpenCommissioningWindow(chip::TLV::TLVReader & data); + + chip::NodeId mLastUsedNodeId = 0; + + // The Node ID of the remote bridge used for Fabric-Sync + // This represents the bridge on the other ecosystem. + chip::NodeId mRemoteBridgeNodeId = chip::kUndefinedNodeId; + + std::set mSyncedDevices; + bool mInitialized = false; + uint64_t mRequestId = 0; + + BridgeSubscription mBridgeSubscriber; + CommissionerControl mCommissionerControl; + FabricSyncGetter mFabricSyncGetter; +}; + +} // namespace admin diff --git a/examples/fabric-sync/admin/DeviceSubscription.cpp b/examples/fabric-sync/admin/DeviceSubscription.cpp new file mode 100644 index 00000000000000..9379df6910f84a --- /dev/null +++ b/examples/fabric-sync/admin/DeviceSubscription.cpp @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2024 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 "DeviceSubscription.h" +#include "DeviceManager.h" + +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::app; +using chip::app::ReadClient; + +namespace admin { + +namespace { + +void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) +{ + reinterpret_cast(context)->OnDeviceConnected(exchangeMgr, sessionHandle); +} + +void OnDeviceConnectionFailureWrapper(void * context, const ScopedNodeId & peerId, CHIP_ERROR error) +{ + reinterpret_cast(context)->OnDeviceConnectionFailure(peerId, error); +} + +} // namespace + +DeviceSubscription::DeviceSubscription() : + mOnDeviceConnectedCallback(OnDeviceConnectedWrapper, this), + mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureWrapper, this) +{} + +void DeviceSubscription::OnAttributeData(const ConcreteDataAttributePath & path, TLV::TLVReader * data, const StatusIB & status) +{ + VerifyOrDie(path.mEndpointId == kRootEndpointId); + VerifyOrDie(path.mClusterId == Clusters::AdministratorCommissioning::Id); + + switch (path.mAttributeId) + { + case Clusters::AdministratorCommissioning::Attributes::WindowStatus::Id: { + Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum windowStatus; + CHIP_ERROR err = data->Get(windowStatus); + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(NotSpecified, "Failed to read WindowStatus")); + VerifyOrReturn(windowStatus != Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kUnknownEnumValue); + mCurrentAdministratorCommissioningAttributes.windowStatus = windowStatus; + mChangeDetected = true; + break; + } + case Clusters::AdministratorCommissioning::Attributes::AdminFabricIndex::Id: { + FabricIndex fabricIndex; + CHIP_ERROR err = data->Get(fabricIndex); + if (err == CHIP_NO_ERROR) + { + mCurrentAdministratorCommissioningAttributes.openerFabricIndex = fabricIndex; + } + else + { + mCurrentAdministratorCommissioningAttributes.openerFabricIndex.reset(); + } + + mChangeDetected = true; + break; + } + case Clusters::AdministratorCommissioning::Attributes::AdminVendorId::Id: { + VendorId vendorId; + CHIP_ERROR err = data->Get(vendorId); + if (err == CHIP_NO_ERROR) + { + mCurrentAdministratorCommissioningAttributes.openerVendorId = vendorId; + } + else + { + mCurrentAdministratorCommissioningAttributes.openerVendorId.reset(); + } + + mChangeDetected = true; + break; + } + default: + break; + } +} + +void DeviceSubscription::OnReportEnd() +{ + // Report end is at the end of all attributes (success) + if (mChangeDetected) + { + CHIP_ERROR err = + bridge::FabricBridge::Instance().AdminCommissioningAttributeChanged(mCurrentAdministratorCommissioningAttributes); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Cannot forward Administrator Commissioning Attribute to fabric bridge %" CHIP_ERROR_FORMAT, + err.Format()); + } + mChangeDetected = false; + } +} + +void DeviceSubscription::OnDone(ReadClient * apReadClient) +{ + // After calling mOnDoneCallback we are indicating that `this` is deleted and we shouldn't do anything else with + // DeviceSubscription. + MoveToState(State::AwaitingDestruction); + mOnDoneCallback(mScopedNodeId); +} + +void DeviceSubscription::OnError(CHIP_ERROR error) +{ + if (error == CHIP_ERROR_TIMEOUT && mState == State::SubscriptionStarted) + { + if (bridge::FabricBridge::Instance().DeviceReachableChanged(mCurrentAdministratorCommissioningAttributes.id, false) != + CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to update the device reachability state"); + } + } + + ChipLogProgress(NotSpecified, "Error subscribing: %" CHIP_ERROR_FORMAT, error.Format()); +} + +void DeviceSubscription::OnDeviceConnected(Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) +{ + if (mState == State::Stopping) + { + // After calling mOnDoneCallback we are indicating that `this` is deleted and we shouldn't do anything else with + // DeviceSubscription. + MoveToState(State::AwaitingDestruction); + mOnDoneCallback(mScopedNodeId); + return; + } + VerifyOrDie(mState == State::Connecting); + mClient = std::make_unique(app::InteractionModelEngine::GetInstance(), &exchangeMgr /* echangeMgr */, + *this /* callback */, ReadClient::InteractionType::Subscribe); + VerifyOrDie(mClient); + + AttributePathParams readPaths[1]; + readPaths[0] = AttributePathParams(kRootEndpointId, Clusters::AdministratorCommissioning::Id); + + ReadPrepareParams readParams(sessionHandle); + + readParams.mpAttributePathParamsList = readPaths; + readParams.mAttributePathParamsListSize = 1; + readParams.mMaxIntervalCeilingSeconds = 5 * 60; + + CHIP_ERROR err = mClient->SendRequest(readParams); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to issue subscription to AdministratorCommissioning data"); + // After calling mOnDoneCallback we are indicating that `this` is deleted and we shouldn't do anything else with + // DeviceSubscription. + MoveToState(State::AwaitingDestruction); + mOnDoneCallback(mScopedNodeId); + return; + } + MoveToState(State::SubscriptionStarted); +} + +void DeviceSubscription::MoveToState(const State aTargetState) +{ + mState = aTargetState; + ChipLogDetail(NotSpecified, "DeviceSubscription moving to [%10.10s]", GetStateStr()); +} + +const char * DeviceSubscription::GetStateStr() const +{ + switch (mState) + { + case State::Idle: + return "Idle"; + + case State::Connecting: + return "Connecting"; + + case State::Stopping: + return "Stopping"; + + case State::SubscriptionStarted: + return "SubscriptionStarted"; + + case State::AwaitingDestruction: + return "AwaitingDestruction"; + } + return "N/A"; +} + +void DeviceSubscription::OnDeviceConnectionFailure(const ScopedNodeId & peerId, CHIP_ERROR error) +{ + VerifyOrDie(mState == State::Connecting || mState == State::Stopping); + ChipLogError(NotSpecified, "DeviceSubscription failed to connect to " ChipLogFormatX64, ChipLogValueX64(peerId.GetNodeId())); + + if (mState == State::Connecting) + { + if (bridge::FabricBridge::Instance().DeviceReachableChanged(mCurrentAdministratorCommissioningAttributes.id, false) != + CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to update the device reachability state"); + } + } + + // After calling mOnDoneCallback we are indicating that `this` is deleted and we shouldn't do anything else with + // DeviceSubscription. + MoveToState(State::AwaitingDestruction); + mOnDoneCallback(mScopedNodeId); +} + +CHIP_ERROR DeviceSubscription::StartSubscription(OnDoneCallback onDoneCallback, Controller::DeviceController & controller, + ScopedNodeId scopedNodeId) +{ + assertChipStackLockedByCurrentThread(); + VerifyOrDie(mState == State::Idle); + VerifyOrReturnError(controller.GetFabricIndex() == scopedNodeId.GetFabricIndex(), CHIP_ERROR_INVALID_ARGUMENT); + + mScopedNodeId = scopedNodeId; + + mCurrentAdministratorCommissioningAttributes = AdministratorCommissioningChanged_init_default; + mCurrentAdministratorCommissioningAttributes.id = scopedNodeId; + mCurrentAdministratorCommissioningAttributes.windowStatus = + Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen; + + mOnDoneCallback = onDoneCallback; + MoveToState(State::Connecting); + CHIP_ERROR err = + controller.GetConnectedDevice(scopedNodeId.GetNodeId(), &mOnDeviceConnectedCallback, &mOnDeviceConnectionFailureCallback); + if (err != CHIP_NO_ERROR) + { + MoveToState(State::Idle); + } + return err; +} + +void DeviceSubscription::StopSubscription() +{ + assertChipStackLockedByCurrentThread(); + VerifyOrDie(mState != State::Idle); + // Something is seriously wrong if we die on the line below + VerifyOrDie(mState != State::AwaitingDestruction); + + if (mState == State::Stopping) + { + // Stop is called again while we are still waiting on connected callbacks + return; + } + + if (mState == State::Connecting) + { + MoveToState(State::Stopping); + return; + } + + // By calling reset on our ReadClient we terminate the subscription. + VerifyOrDie(mClient); + mClient.reset(); + // After calling mOnDoneCallback we are indicating that `this` is deleted and we shouldn't do anything else with + // DeviceSubscription. + MoveToState(State::AwaitingDestruction); + mOnDoneCallback(mScopedNodeId); +} + +} // namespace admin diff --git a/examples/fabric-sync/admin/DeviceSubscription.h b/examples/fabric-sync/admin/DeviceSubscription.h new file mode 100644 index 00000000000000..59169223e6fbb7 --- /dev/null +++ b/examples/fabric-sync/admin/DeviceSubscription.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#pragma once + +#include +#include +#include +#include +#include + +namespace admin { + +class DeviceSubscriptionManager; + +/// Attribute subscription to attributes that are important to keep track and send to fabric-bridge +/// via RPC when change has been identified. +/// +/// An instance of DeviceSubscription is intended to be used only once. Once a DeviceSubscription is +/// terminated, either from an error or from subscriptions getting shut down, we expect the instance +/// to be deleted. Any new subscription should instantiate another instance of DeviceSubscription. +class DeviceSubscription : public chip::app::ReadClient::Callback +{ +public: + using OnDoneCallback = std::function; + + DeviceSubscription(); + + CHIP_ERROR StartSubscription(OnDoneCallback onDoneCallback, chip::Controller::DeviceController & controller, + chip::ScopedNodeId nodeId); + + /// This will trigger stopping the subscription. Once subscription is stopped the OnDoneCallback + /// provided in StartSubscription will be called to indicate that subscription have been terminated. + /// + /// Must only be called after StartSubscription was successfully called. + void StopSubscription(); + + /////////////////////////////////////////////////////////////// + // ReadClient::Callback implementation + /////////////////////////////////////////////////////////////// + void OnAttributeData(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data, + const chip::app::StatusIB & status) override; + void OnReportEnd() override; + void OnError(CHIP_ERROR error) override; + void OnDone(chip::app::ReadClient * apReadClient) override; + + /////////////////////////////////////////////////////////////// + // callbacks for CASE session establishment + /////////////////////////////////////////////////////////////// + void OnDeviceConnected(chip::Messaging::ExchangeManager & exchangeMgr, const chip::SessionHandle & sessionHandle); + void OnDeviceConnectionFailure(const chip::ScopedNodeId & peerId, CHIP_ERROR error); + +private: + enum class State : uint8_t + { + Idle, ///< Default state that the object starts out in, where no work has commenced + Connecting, ///< We are waiting for OnDeviceConnected or OnDeviceConnectionFailure callbacks to be called + Stopping, ///< We are waiting for OnDeviceConnected or OnDeviceConnectionFailure callbacks so we can terminate + SubscriptionStarted, ///< We have started a subscription. + AwaitingDestruction, ///< The object has completed its work and is awaiting destruction. + }; + + void MoveToState(const State aTargetState); + const char * GetStateStr() const; + + chip::ScopedNodeId mScopedNodeId; + + OnDoneCallback mOnDoneCallback; + std::unique_ptr mClient; + + chip::Callback::Callback mOnDeviceConnectedCallback; + chip::Callback::Callback mOnDeviceConnectionFailureCallback; + + bridge::AdministratorCommissioningChanged mCurrentAdministratorCommissioningAttributes; + + bool mChangeDetected = false; + State mState = State::Idle; +}; + +} // namespace admin diff --git a/examples/fabric-sync/admin/DeviceSubscriptionManager.cpp b/examples/fabric-sync/admin/DeviceSubscriptionManager.cpp new file mode 100644 index 00000000000000..d2209bdd5d52ba --- /dev/null +++ b/examples/fabric-sync/admin/DeviceSubscriptionManager.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2024 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 "DeviceSubscriptionManager.h" +#include "DeviceManager.h" + +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::app; + +namespace admin { + +DeviceSubscriptionManager & DeviceSubscriptionManager::Instance() +{ + static DeviceSubscriptionManager instance; + return instance; +} + +CHIP_ERROR DeviceSubscriptionManager::StartSubscription(Controller::DeviceController & controller, ScopedNodeId scopedNodeId) +{ + assertChipStackLockedByCurrentThread(); + auto it = mDeviceSubscriptionMap.find(scopedNodeId); + VerifyOrReturnError((it == mDeviceSubscriptionMap.end()), CHIP_ERROR_INCORRECT_STATE); + + auto deviceSubscription = std::make_unique(); + VerifyOrReturnError(deviceSubscription, CHIP_ERROR_NO_MEMORY); + ReturnErrorOnFailure(deviceSubscription->StartSubscription( + [this](ScopedNodeId aNodeId) { this->DeviceSubscriptionTerminated(aNodeId); }, controller, scopedNodeId)); + + mDeviceSubscriptionMap[scopedNodeId] = std::move(deviceSubscription); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DeviceSubscriptionManager::RemoveSubscription(ScopedNodeId scopedNodeId) +{ + assertChipStackLockedByCurrentThread(); + auto it = mDeviceSubscriptionMap.find(scopedNodeId); + VerifyOrReturnError((it != mDeviceSubscriptionMap.end()), CHIP_ERROR_NOT_FOUND); + // We cannot safely erase the DeviceSubscription from mDeviceSubscriptionMap. + // After calling StopSubscription we expect DeviceSubscription to eventually + // call the OnDoneCallback we provided in StartSubscription which will call + // DeviceSubscriptionTerminated where it will be erased from the + // mDeviceSubscriptionMap. + it->second->StopSubscription(); + return CHIP_NO_ERROR; +} + +void DeviceSubscriptionManager::DeviceSubscriptionTerminated(ScopedNodeId scopedNodeId) +{ + assertChipStackLockedByCurrentThread(); + auto it = mDeviceSubscriptionMap.find(scopedNodeId); + // DeviceSubscriptionTerminated is a private method that is expected to only + // be called by DeviceSubscription when it is terminal and is ready to be + // cleaned up and removed. If it is not mapped that means something has gone + // really wrong and there is likely a memory leak somewhere. + VerifyOrDie(it != mDeviceSubscriptionMap.end()); + mDeviceSubscriptionMap.erase(scopedNodeId); +} + +} // namespace admin diff --git a/examples/fabric-sync/admin/DeviceSubscriptionManager.h b/examples/fabric-sync/admin/DeviceSubscriptionManager.h new file mode 100644 index 00000000000000..eb32d3f439276d --- /dev/null +++ b/examples/fabric-sync/admin/DeviceSubscriptionManager.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2024 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 "DeviceSubscription.h" + +#include +#include +#include + +#include + +namespace admin { + +class DeviceSubscriptionManager +{ +public: + static DeviceSubscriptionManager & Instance(); + + /// Usually called after we have added a synchronized device to fabric-bridge to monitor + /// for any changes that need to be propagated to fabric-bridge. + CHIP_ERROR StartSubscription(chip::Controller::DeviceController & controller, chip::ScopedNodeId scopedNodeId); + + CHIP_ERROR RemoveSubscription(chip::ScopedNodeId scopedNodeId); + +private: + struct ScopedNodeIdHasher + { + std::size_t operator()(const chip::ScopedNodeId & scopedNodeId) const + { + std::size_t h1 = std::hash{}(scopedNodeId.GetFabricIndex()); + std::size_t h2 = std::hash{}(scopedNodeId.GetNodeId()); + // Bitshifting h2 reduces collisions when fabricIndex == nodeId. + return h1 ^ (h2 << 1); + } + }; + + void DeviceSubscriptionTerminated(chip::ScopedNodeId scopedNodeId); + + std::unordered_map, ScopedNodeIdHasher> mDeviceSubscriptionMap; +}; + +} // namespace admin diff --git a/examples/fabric-sync/admin/DeviceSynchronization.cpp b/examples/fabric-sync/admin/DeviceSynchronization.cpp new file mode 100644 index 00000000000000..05a4fa9db8f398 --- /dev/null +++ b/examples/fabric-sync/admin/DeviceSynchronization.cpp @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2024 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 "DeviceSynchronization.h" +#include "DeviceManager.h" +#include "DeviceSubscriptionManager.h" + +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::app; +using chip::app::ReadClient; + +namespace admin { + +namespace { + +constexpr uint16_t kBasicInformationAttributeBufSize = 128; + +void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) +{ + reinterpret_cast(context)->OnDeviceConnected(exchangeMgr, sessionHandle); +} + +void OnDeviceConnectionFailureWrapper(void * context, const ScopedNodeId & peerId, CHIP_ERROR error) +{ + reinterpret_cast(context)->OnDeviceConnectionFailure(peerId, error); +} + +bool SuccessOrLog(CHIP_ERROR err, const char * name) +{ + if (err == CHIP_NO_ERROR) + { + return true; + } + + ChipLogError(NotSpecified, "Failed to read %s: %" CHIP_ERROR_FORMAT, name, err.Format()); + + return false; +} + +} // namespace + +DeviceSynchronizer & DeviceSynchronizer::Instance() +{ + static DeviceSynchronizer instance; + return instance; +} + +DeviceSynchronizer::DeviceSynchronizer() : + mOnDeviceConnectedCallback(OnDeviceConnectedWrapper, this), + mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureWrapper, this) +{} + +void DeviceSynchronizer::OnAttributeData(const ConcreteDataAttributePath & path, TLV::TLVReader * data, const StatusIB & status) +{ + VerifyOrDie(path.mEndpointId == kRootEndpointId); + VerifyOrDie(path.mClusterId == Clusters::BasicInformation::Id); + + if (!status.IsSuccess()) + { + ChipLogError(NotSpecified, "Response Failure: %" CHIP_ERROR_FORMAT, status.ToChipError().Format()); + return; + } + + switch (path.mAttributeId) + { + case Clusters::BasicInformation::Attributes::UniqueID::Id: { + char uniqueIdBuffer[kBasicInformationAttributeBufSize]; + if (SuccessOrLog(data->GetString(uniqueIdBuffer, sizeof(uniqueIdBuffer)), "UniqueId")) + { + mCurrentDeviceData.uniqueId = std::string(uniqueIdBuffer); + } + } + break; + case Clusters::BasicInformation::Attributes::VendorName::Id: { + char vendorNameBuffer[kBasicInformationAttributeBufSize]; + if (SuccessOrLog(data->GetString(vendorNameBuffer, sizeof(vendorNameBuffer)), "VendorName")) + { + mCurrentDeviceData.vendorName = std::string(vendorNameBuffer); + } + } + break; + case Clusters::BasicInformation::Attributes::ProductName::Id: { + char productNameBuffer[kBasicInformationAttributeBufSize]; + if (SuccessOrLog(data->GetString(productNameBuffer, sizeof(productNameBuffer)), "ProductName")) + { + mCurrentDeviceData.productName = std::string(productNameBuffer); + } + } + break; + case Clusters::BasicInformation::Attributes::NodeLabel::Id: { + char nodeLabelBuffer[kBasicInformationAttributeBufSize]; + if (SuccessOrLog(data->GetString(nodeLabelBuffer, sizeof(nodeLabelBuffer)), "NodeLabel")) + { + mCurrentDeviceData.nodeLabel = std::string(nodeLabelBuffer); + } + } + break; + case Clusters::BasicInformation::Attributes::HardwareVersionString::Id: { + char hardwareVersionStringBuffer[kBasicInformationAttributeBufSize]; + if (SuccessOrLog(data->GetString(hardwareVersionStringBuffer, sizeof(hardwareVersionStringBuffer)), + "HardwareVersionString")) + { + mCurrentDeviceData.hardwareVersionString = std::string(hardwareVersionStringBuffer); + } + } + break; + case Clusters::BasicInformation::Attributes::SoftwareVersionString::Id: { + char softwareVersionStringBuffer[kBasicInformationAttributeBufSize]; + if (SuccessOrLog(data->GetString(softwareVersionStringBuffer, sizeof(softwareVersionStringBuffer)), + "SoftwareVersionString")) + { + mCurrentDeviceData.softwareVersionString = std::string(softwareVersionStringBuffer); + } + } + break; + default: + break; + } +} + +void DeviceSynchronizer::OnReportEnd() +{ + // Report end is at the end of all attributes (success) + MoveToState(State::ReceivedResponse); +} + +void DeviceSynchronizer::OnDone(app::ReadClient * apReadClient) +{ + ChipLogProgress(NotSpecified, "Synchronization complete for NodeId:" ChipLogFormatX64, ChipLogValueX64(mNodeId)); + + if (mState == State::ReceivedResponse && !DeviceManager::Instance().IsCurrentBridgeDevice(mNodeId)) + { + GetUniqueId(); + if (mState == State::GettingUid) + { + ChipLogProgress(NotSpecified, + "GetUniqueId was successful and we rely on callback to call SynchronizationCompleteAddDevice."); + return; + } + SynchronizationCompleteAddDevice(); + } + + MoveToState(State::Idle); +} + +void DeviceSynchronizer::OnError(CHIP_ERROR error) +{ + MoveToState(State::ReceivedError); + ChipLogProgress(NotSpecified, "Error fetching device data: %" CHIP_ERROR_FORMAT, error.Format()); +} + +void DeviceSynchronizer::OnDeviceConnected(Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) +{ + mClient = std::make_unique(app::InteractionModelEngine::GetInstance(), &exchangeMgr /* echangeMgr */, + *this /* callback */, ReadClient::InteractionType::Read); + VerifyOrDie(mClient); + + AttributePathParams readPaths[1]; + readPaths[0] = AttributePathParams(kRootEndpointId, Clusters::BasicInformation::Id); + + ReadPrepareParams readParams(sessionHandle); + + readParams.mpAttributePathParamsList = readPaths; + readParams.mAttributePathParamsListSize = 1; + + CHIP_ERROR err = mClient->SendRequest(readParams); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to issue read for BasicInformation data"); + MoveToState(State::Idle); + } + MoveToState(State::AwaitingResponse); +} + +void DeviceSynchronizer::OnDeviceConnectionFailure(const ScopedNodeId & peerId, CHIP_ERROR error) +{ + ChipLogError(NotSpecified, "Device Sync failed to connect to " ChipLogFormatX64, ChipLogValueX64(peerId.GetNodeId())); + MoveToState(State::Idle); +} + +void DeviceSynchronizer::StartDeviceSynchronization(Controller::DeviceController * controller, NodeId nodeId, bool deviceIsIcd) +{ + VerifyOrDie(controller); + if (mState != State::Idle) + { + ChipLogError(NotSpecified, "Device Sync NOT POSSIBLE: another sync is in progress"); + return; + } + + mNodeId = nodeId; + + ChipLogProgress(NotSpecified, "Start device synchronization for NodeId:" ChipLogFormatX64, ChipLogValueX64(mNodeId)); + + mCurrentDeviceData = SynchronizedDevice_init_default; + mCurrentDeviceData.id = chip::ScopedNodeId(nodeId, controller->GetFabricIndex()); + mCurrentDeviceData.isIcd = deviceIsIcd; + + ReturnOnFailure(controller->GetConnectedDevice(nodeId, &mOnDeviceConnectedCallback, &mOnDeviceConnectionFailureCallback)); + mController = controller; + MoveToState(State::Connecting); +} + +void DeviceSynchronizer::GetUniqueId() +{ + VerifyOrDie(mState == State::ReceivedResponse); + VerifyOrDie(mController); + + // If we have a UniqueId we can return leaving state in ReceivedResponse. + VerifyOrReturn(!mCurrentDeviceData.uniqueId.has_value(), ChipLogDetail(NotSpecified, "We already have UniqueId")); + + auto * device = DeviceManager::Instance().FindDeviceByNode(mNodeId); + // If there is no associated remote Fabric Sync Aggregator there is no other place for us to try + // getting the UniqueId from and can return leaving the state in ReceivedResponse. + VerifyOrReturn(device, ChipLogDetail(NotSpecified, "No remote Fabric Sync Aggregator to get UniqueId from")); + + // Because device is not-null we expect IsFabricSyncReady to be true. IsFabricSyncReady indicates we have a + // connection to the remote Fabric Sync Aggregator. + VerifyOrDie(DeviceManager::Instance().IsFabricSyncReady()); + auto remoteBridgeNodeId = DeviceManager::Instance().GetRemoteBridgeNodeId(); + EndpointId remoteEndpointIdOfInterest = device->GetEndpointId(); + + ChipLogDetail(NotSpecified, "Attempting to get UniqueId from remote Fabric Sync Aggregator"); + CHIP_ERROR err = mUniqueIdGetter.GetUniqueId( + [this](std::optional aUniqueId) { + if (aUniqueId.has_value()) + { + // Convert CharSpan to std::string and set it as uniqueId + this->mCurrentDeviceData.uniqueId = std::string(aUniqueId.value().data(), aUniqueId.value().size()); + } + else + { + ChipLogError(NotSpecified, "We expected to get UniqueId from remote Fabric Sync Aggregator, but failed"); + } + this->SynchronizationCompleteAddDevice(); + }, + *mController, remoteBridgeNodeId, remoteEndpointIdOfInterest); + + if (err == CHIP_NO_ERROR) + { + MoveToState(State::GettingUid); + } + else + { + ChipLogDetail(NotSpecified, "Failed to get UniqueId from remote Fabric Sync Aggregator") + } +} + +void DeviceSynchronizer::SynchronizationCompleteAddDevice() +{ + VerifyOrDie(mState == State::ReceivedResponse || mState == State::GettingUid); + ChipLogProgress(NotSpecified, "Synchronization complete and add device"); + + bridge::FabricBridge::Instance().AddSynchronizedDevice(mCurrentDeviceData); + + // TODO(#35077) Figure out how we should reflect CADMIN values of ICD. + if (!mCurrentDeviceData.isIcd) + { + VerifyOrDie(mController); + ScopedNodeId scopedNodeId(mNodeId, mController->GetFabricIndex()); + CHIP_ERROR err = DeviceSubscriptionManager::Instance().StartSubscription(*mController, scopedNodeId); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed start subscription to NodeId:" ChipLogFormatX64, ChipLogValueX64(mNodeId)); + bridge::FabricBridge::Instance().DeviceReachableChanged(mCurrentDeviceData.id, false); + } + } + + MoveToState(State::Idle); +} + +void DeviceSynchronizer::MoveToState(const State targetState) +{ + mState = targetState; + ChipLogDetail(NotSpecified, "DeviceSynchronizer moving to [%10.10s]", GetStateStr()); +} + +const char * DeviceSynchronizer::GetStateStr() const +{ + switch (mState) + { + case State::Idle: + return "Idle"; + + case State::Connecting: + return "Connecting"; + + case State::AwaitingResponse: + return "AwaitingResponse"; + + case State::ReceivedResponse: + return "ReceivedResponse"; + + case State::ReceivedError: + return "ReceivedError"; + + case State::GettingUid: + return "GettingUid"; + } + return "N/A"; +} + +} // namespace admin diff --git a/examples/fabric-sync/admin/DeviceSynchronization.h b/examples/fabric-sync/admin/DeviceSynchronization.h new file mode 100644 index 00000000000000..1a72a447993b9d --- /dev/null +++ b/examples/fabric-sync/admin/DeviceSynchronization.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2024 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 "UniqueIdGetter.h" + +#include +#include +#include +#include +#include + +namespace admin { + +/// Ensures that device data is synchronized to the remote fabric bridge. +/// +/// Includes a state machine that: +/// - initiates a "read basic information data" command to fetch basic information +/// - upon receiving such information, ensures that synchronized device data is sent +/// to the remote end. +class DeviceSynchronizer : public chip::app::ReadClient::Callback +{ +public: + DeviceSynchronizer(); + + /// Usually called after commissioning is complete, initiates a + /// read of required data from the remote node ID and then will synchronize + /// the device towards the fabric bridge + /// + /// @param controller Must be a non-null pointer. The DeviceController instance + /// pointed to must out live the entire device synchronization process. + /// @param nodeId Node ID of the device we need to syncronize data from. + /// @param deviceIsIcd If the device is an ICD device. + void StartDeviceSynchronization(chip::Controller::DeviceController * controller, chip::NodeId nodeId, bool deviceIsIcd); + + /////////////////////////////////////////////////////////////// + // ReadClient::Callback implementation + /////////////////////////////////////////////////////////////// + void OnAttributeData(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data, + const chip::app::StatusIB & status) override; + void OnReportEnd() override; + void OnError(CHIP_ERROR error) override; + void OnDone(chip::app::ReadClient * apReadClient) override; + + /////////////////////////////////////////////////////////////// + // callbacks for CASE session establishment + /////////////////////////////////////////////////////////////// + void OnDeviceConnected(chip::Messaging::ExchangeManager & exchangeMgr, const chip::SessionHandle & sessionHandle); + void OnDeviceConnectionFailure(const chip::ScopedNodeId & peerId, CHIP_ERROR error); + + static DeviceSynchronizer & Instance(); + +private: + enum class State : uint8_t + { + Idle, ///< Default state that the object starts out in, where no work has commenced + Connecting, ///< We are waiting for OnDeviceConnected or OnDeviceConnectionFailure callbacks to be called + AwaitingResponse, ///< We have started reading BasicInformation cluster attributes + ReceivedResponse, ///< We have received a ReportEnd from reading BasicInformation cluster attributes + ReceivedError, ///< We recieved an error while reading of BasicInformation cluster attributes + GettingUid, ///< We are getting UniqueId from the remote fabric sync bridge. + }; + + void GetUniqueId(); + void SynchronizationCompleteAddDevice(); + + void MoveToState(const State targetState); + const char * GetStateStr() const; + + std::unique_ptr mClient; + + chip::Callback::Callback mOnDeviceConnectedCallback; + chip::Callback::Callback mOnDeviceConnectionFailureCallback; + + State mState = State::Idle; + // mController is expected to remain valid throughout the entire device synchronization process (i.e. when + // mState != Idle). + chip::Controller::DeviceController * mController = nullptr; + chip::NodeId mNodeId = chip::kUndefinedNodeId; + bridge::SynchronizedDevice mCurrentDeviceData; + UniqueIdGetter mUniqueIdGetter; +}; + +} // namespace admin diff --git a/examples/fabric-sync/admin/FabricAdmin.cpp b/examples/fabric-sync/admin/FabricAdmin.cpp new file mode 100644 index 00000000000000..4e170ce78db043 --- /dev/null +++ b/examples/fabric-sync/admin/FabricAdmin.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2024 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 "FabricAdmin.h" + +using namespace ::chip; + +namespace admin { + +namespace { + +constexpr uint32_t kCommissionPrepareTimeMs = 500; + +} // namespace + +FabricAdmin FabricAdmin::sInstance; + +FabricAdmin & FabricAdmin::Instance() +{ + if (!sInstance.mInitialized) + { + sInstance.Init(); + } + return sInstance; +} + +CHIP_ERROR FabricAdmin::OpenCommissioningWindow(Controller::CommissioningWindowVerifierParams params, FabricIndex fabricIndex) +{ + ScopedNodeId scopedNodeId(params.GetNodeId(), fabricIndex); + uint32_t iterations = params.GetIteration(); + uint16_t discriminator = params.GetDiscriminator(); + uint16_t commissioningTimeoutSec = static_cast(params.GetTimeout().count()); + + // Log request details for debugging purposes + ChipLogProgress(NotSpecified, + "Received OpenCommissioningWindow request: NodeId " ChipLogFormatX64 + ", Timeout: %u, Iterations: %u, Discriminator: %u", + ChipLogValueX64(scopedNodeId.GetNodeId()), commissioningTimeoutSec, iterations, discriminator); + + // Open the device commissioning window with provided salt and verifier data + DeviceManager::Instance().OpenDeviceCommissioningWindow(scopedNodeId, iterations, commissioningTimeoutSec, discriminator, + ByteSpan(params.GetSalt().data(), params.GetSalt().size()), + ByteSpan(params.GetVerifier().data(), params.GetVerifier().size())); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR +FabricAdmin::CommissionRemoteBridge(Controller::CommissioningWindowPasscodeParams params, VendorId vendorId, uint16_t productId) +{ + char saltHex[Crypto::kSpake2p_Max_PBKDF_Salt_Length * 2 + 1]; + Encoding::BytesToHex(params.GetSalt().data(), params.GetSalt().size(), saltHex, sizeof(saltHex), + Encoding::HexFlags::kNullTerminate); + + ChipLogProgress(NotSpecified, "Received CommissionNode request"); + + SetupPayload setupPayload = SetupPayload(); + + setupPayload.setUpPINCode = params.GetSetupPIN(); + setupPayload.version = 0; + setupPayload.vendorID = vendorId; + setupPayload.productID = productId; + setupPayload.rendezvousInformation.SetValue(RendezvousInformationFlag::kOnNetwork); + + SetupDiscriminator discriminator{}; + discriminator.SetLongValue(params.GetDiscriminator()); + setupPayload.discriminator = discriminator; + + QRCodeSetupPayloadGenerator generator(setupPayload); + std::string code; + CHIP_ERROR err = generator.payloadBase38RepresentationWithAutoTLVBuffer(code); + + if (err == CHIP_NO_ERROR) + { + NodeId nodeId = DeviceManager::Instance().GetNextAvailableNodeId(); + + // After responding with RequestCommissioningApproval to the node where the client initiated the + // RequestCommissioningApproval, you need to wait for it to open a commissioning window on its bridge. + usleep(kCommissionPrepareTimeMs * 1000); + + DeviceManager::Instance().PairRemoteDevice(nodeId, code.c_str()); + } + else + { + ChipLogError(NotSpecified, "Unable to generate pairing code for setup payload: %" CHIP_ERROR_FORMAT, err.Format()); + return err; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FabricAdmin::KeepActive(ScopedNodeId scopedNodeId, uint32_t stayActiveDurationMs, uint32_t timeoutMs) +{ + ChipLogProgress(NotSpecified, "Received KeepActive request: Id[%d, 0x" ChipLogFormatX64 "], %u", scopedNodeId.GetFabricIndex(), + ChipLogValueX64(scopedNodeId.GetNodeId()), stayActiveDurationMs); + + KeepActiveWorkData * data = Platform::New(this, scopedNodeId, stayActiveDurationMs, timeoutMs); + VerifyOrReturnError(data != nullptr, CHIP_ERROR_NO_MEMORY); + + DeviceLayer::PlatformMgr().ScheduleWork(KeepActiveWork, reinterpret_cast(data)); + return CHIP_NO_ERROR; +} + +void FabricAdmin::ScheduleSendingKeepActiveOnCheckIn(ScopedNodeId scopedNodeId, uint32_t stayActiveDurationMs, uint32_t timeoutMs) +{ + // Accessing mPendingCheckIn should only be done while holding ChipStackLock + assertChipStackLockedByCurrentThread(); + + auto timeNow = System::SystemClock().GetMonotonicTimestamp(); + System::Clock::Timestamp expiryTimestamp = timeNow + System::Clock::Milliseconds64(timeoutMs); + KeepActiveDataForCheckIn checkInData = { .mStayActiveDurationMs = stayActiveDurationMs, + .mRequestExpiryTimestamp = expiryTimestamp }; + + auto it = mPendingCheckIn.find(scopedNodeId); + if (it != mPendingCheckIn.end()) + { + checkInData.mStayActiveDurationMs = std::max(checkInData.mStayActiveDurationMs, it->second.mStayActiveDurationMs); + checkInData.mRequestExpiryTimestamp = std::max(checkInData.mRequestExpiryTimestamp, it->second.mRequestExpiryTimestamp); + } + + mPendingCheckIn[scopedNodeId] = checkInData; +} + +} // namespace admin diff --git a/examples/fabric-sync/admin/FabricAdmin.h b/examples/fabric-sync/admin/FabricAdmin.h new file mode 100644 index 00000000000000..bec98dc4140183 --- /dev/null +++ b/examples/fabric-sync/admin/FabricAdmin.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2024 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 "DeviceManager.h" + +#include +#include +#include +#include + +namespace admin { + +struct ScopedNodeIdHasher +{ + std::size_t operator()(const chip::ScopedNodeId & scopedNodeId) const + { + std::size_t h1 = std::hash{}(scopedNodeId.GetFabricIndex()); + std::size_t h2 = std::hash{}(scopedNodeId.GetNodeId()); + // Bitshifting h2 reduces collisions when fabricIndex == nodeId. + return h1 ^ (h2 << 1); + } +}; + +class FabricAdmin final : public bridge::FabricAdminDelegate +{ +public: + static FabricAdmin & Instance(); + + CHIP_ERROR OpenCommissioningWindow(chip::Controller::CommissioningWindowVerifierParams params, + chip::FabricIndex fabricIndex) override; + + CHIP_ERROR + CommissionRemoteBridge(chip::Controller::CommissioningWindowPasscodeParams params, chip::VendorId vendorId, + uint16_t productId) override; + + CHIP_ERROR KeepActive(chip::ScopedNodeId scopedNodeId, uint32_t stayActiveDurationMs, uint32_t timeoutMs) override; + + void ScheduleSendingKeepActiveOnCheckIn(chip::ScopedNodeId scopedNodeId, uint32_t stayActiveDurationMs, uint32_t timeoutMs); + +private: + struct KeepActiveDataForCheckIn + { + uint32_t mStayActiveDurationMs = 0; + chip::System::Clock::Timestamp mRequestExpiryTimestamp; + }; + + struct KeepActiveWorkData + { + KeepActiveWorkData(FabricAdmin * fabricAdmin, chip::ScopedNodeId scopedNodeId, uint32_t stayActiveDurationMs, + uint32_t timeoutMs) : + mFabricAdmin(fabricAdmin), + mScopedNodeId(scopedNodeId), mStayActiveDurationMs(stayActiveDurationMs), mTimeoutMs(timeoutMs) + {} + + FabricAdmin * mFabricAdmin; + chip::ScopedNodeId mScopedNodeId; + uint32_t mStayActiveDurationMs; + uint32_t mTimeoutMs; + }; + + static void KeepActiveWork(intptr_t arg) + { + KeepActiveWorkData * data = reinterpret_cast(arg); + data->mFabricAdmin->ScheduleSendingKeepActiveOnCheckIn(data->mScopedNodeId, data->mStayActiveDurationMs, data->mTimeoutMs); + chip::Platform::Delete(data); + } + + // Modifications to mPendingCheckIn should be done on the MatterEventLoop thread + // otherwise we would need a mutex protecting this data to prevent race as this + // data is accessible by both RPC thread and Matter eventloop. + std::unordered_map mPendingCheckIn; + + static FabricAdmin sInstance; + + bool mInitialized = false; + + void Init() { mInitialized = true; } +}; + +} // namespace admin diff --git a/examples/fabric-sync/admin/FabricSyncGetter.cpp b/examples/fabric-sync/admin/FabricSyncGetter.cpp new file mode 100644 index 00000000000000..7e5118090716c0 --- /dev/null +++ b/examples/fabric-sync/admin/FabricSyncGetter.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2024 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 "FabricSyncGetter.h" + +using namespace ::chip; +using namespace ::chip::app; +using chip::app::ReadClient; + +namespace admin { + +namespace { + +void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) +{ + reinterpret_cast(context)->OnDeviceConnected(exchangeMgr, sessionHandle); +} + +void OnDeviceConnectionFailureWrapper(void * context, const ScopedNodeId & peerId, CHIP_ERROR error) +{ + reinterpret_cast(context)->OnDeviceConnectionFailure(peerId, error); +} + +} // namespace + +FabricSyncGetter::FabricSyncGetter() : + mOnDeviceConnectedCallback(OnDeviceConnectedWrapper, this), + mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureWrapper, this) +{} + +CHIP_ERROR FabricSyncGetter::GetFabricSynchronizationData(OnDoneCallback onDoneCallback, Controller::DeviceController & controller, + NodeId nodeId, EndpointId endpointId) +{ + assertChipStackLockedByCurrentThread(); + + mEndpointId = endpointId; + mOnDoneCallback = onDoneCallback; + + CHIP_ERROR err = controller.GetConnectedDevice(nodeId, &mOnDeviceConnectedCallback, &mOnDeviceConnectionFailureCallback); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to connect to remote fabric bridge %" CHIP_ERROR_FORMAT, err.Format()); + } + return err; +} + +void FabricSyncGetter::OnAttributeData(const ConcreteDataAttributePath & path, TLV::TLVReader * data, const StatusIB & status) +{ + VerifyOrDie(path.mClusterId == Clusters::CommissionerControl::Id); + + if (!status.IsSuccess()) + { + ChipLogError(NotSpecified, "Response Failure: %" CHIP_ERROR_FORMAT, status.ToChipError().Format()); + return; + } + + switch (path.mAttributeId) + { + case Clusters::CommissionerControl::Attributes::SupportedDeviceCategories::Id: { + mOnDoneCallback(*data); + break; + } + default: + break; + } +} + +void FabricSyncGetter::OnError(CHIP_ERROR error) +{ + ChipLogProgress(NotSpecified, "Error Getting SupportedDeviceCategories: %" CHIP_ERROR_FORMAT, error.Format()); +} + +void FabricSyncGetter::OnDone(ReadClient * apReadClient) +{ + ChipLogProgress(NotSpecified, "Reading SupportedDeviceCategories is done."); +} + +void FabricSyncGetter::OnDeviceConnected(Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) +{ + mClient = std::make_unique(app::InteractionModelEngine::GetInstance(), &exchangeMgr, *this /* callback */, + ReadClient::InteractionType::Read); + VerifyOrDie(mClient); + + AttributePathParams readPaths[1]; + readPaths[0] = AttributePathParams(mEndpointId, Clusters::CommissionerControl::Id, + Clusters::CommissionerControl::Attributes::SupportedDeviceCategories::Id); + + ReadPrepareParams readParams(sessionHandle); + + readParams.mpAttributePathParamsList = readPaths; + readParams.mAttributePathParamsListSize = 1; + + CHIP_ERROR err = mClient->SendRequest(readParams); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to read SupportedDeviceCategories from the bridged device."); + OnDone(nullptr); + return; + } +} + +void FabricSyncGetter::OnDeviceConnectionFailure(const ScopedNodeId & peerId, CHIP_ERROR error) +{ + ChipLogError(NotSpecified, "FabricSyncGetter failed to connect to " ChipLogFormatX64, ChipLogValueX64(peerId.GetNodeId())); + + OnDone(nullptr); +} + +} // namespace admin diff --git a/examples/fabric-sync/admin/FabricSyncGetter.h b/examples/fabric-sync/admin/FabricSyncGetter.h new file mode 100644 index 00000000000000..bed3c2fbb54385 --- /dev/null +++ b/examples/fabric-sync/admin/FabricSyncGetter.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2024 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 + +namespace admin { + +/** + * @brief Class used to get FabricSynchronization from SupportedDeviceCategories attribute of Commissioner Control Cluster. + * + * Functionality: + * - Establishes a CASE session to communicate with the remote bridge. + * - Retrieves the attribute data from the endpoint which host Aggregator. + * - Provides callbacks for success, error, and completion when retrieving data. + */ +class FabricSyncGetter : public chip::app::ReadClient::Callback +{ +public: + using OnDoneCallback = std::function; + + FabricSyncGetter(); + + /** + * @brief Initiates the process of retrieving fabric synchronization data from the target device. + * + * @param onDoneCallback A callback function to be invoked when the data retrieval is complete. + * @param controller The device controller used to establish a session with the target device. + * @param nodeId The Node ID of the target device. + * @param endpointId The Endpoint ID from which to retrieve the fabric synchronization data. + * @return CHIP_ERROR Returns an error if the process fails, CHIP_NO_ERROR on success. + */ + CHIP_ERROR GetFabricSynchronizationData(OnDoneCallback onDoneCallback, chip::Controller::DeviceController & controller, + chip::NodeId nodeId, chip::EndpointId endpointId); + + /////////////////////////////////////////////////////////////// + // ReadClient::Callback implementation + /////////////////////////////////////////////////////////////// + void OnAttributeData(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data, + const chip::app::StatusIB & status) override; + void OnError(CHIP_ERROR error) override; + void OnDone(chip::app::ReadClient * apReadClient) override; + + /////////////////////////////////////////////////////////////// + // callbacks for CASE session establishment + /////////////////////////////////////////////////////////////// + void OnDeviceConnected(chip::Messaging::ExchangeManager & exchangeMgr, const chip::SessionHandle & sessionHandle); + void OnDeviceConnectionFailure(const chip::ScopedNodeId & peerId, CHIP_ERROR error); + +private: + std::unique_ptr mClient; + + OnDoneCallback mOnDoneCallback; + chip::EndpointId mEndpointId; + chip::Callback::Callback mOnDeviceConnectedCallback; + chip::Callback::Callback mOnDeviceConnectionFailureCallback; +}; + +} // namespace admin diff --git a/examples/fabric-sync/admin/PairingManager.cpp b/examples/fabric-sync/admin/PairingManager.cpp new file mode 100644 index 00000000000000..ba360051a27b84 --- /dev/null +++ b/examples/fabric-sync/admin/PairingManager.cpp @@ -0,0 +1,567 @@ +/* + * Copyright (c) 2024 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 "PairingManager.h" +#include "DeviceManager.h" +#include "DeviceSynchronization.h" + +#include +#include +#include + +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Controller; + +namespace admin { + +namespace { + +CHIP_ERROR GetPayload(const char * setUpCode, SetupPayload & payload) +{ + VerifyOrReturnValue(setUpCode, CHIP_ERROR_INVALID_ARGUMENT); + bool isQRCode = strncmp(setUpCode, kQRCodePrefix, strlen(kQRCodePrefix)) == 0; + if (isQRCode) + { + ReturnErrorOnFailure(QRCodeSetupPayloadParser(setUpCode).populatePayload(payload)); + VerifyOrReturnError(payload.isValidQRCodePayload(), CHIP_ERROR_INVALID_ARGUMENT); + } + else + { + ReturnErrorOnFailure(ManualSetupPayloadParser(setUpCode).populatePayload(payload)); + VerifyOrReturnError(payload.isValidManualCode(), CHIP_ERROR_INVALID_ARGUMENT); + } + + return CHIP_NO_ERROR; +} + +bool ParseAddressWithInterface(const char * addressString, Inet::IPAddress & address, Inet::InterfaceId & interfaceId) +{ + struct addrinfo hints; + struct addrinfo * result; + int ret; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + ret = getaddrinfo(addressString, nullptr, &hints, &result); + if (ret < 0) + { + ChipLogError(NotSpecified, "Invalid address: %s", addressString); + return false; + } + + if (result->ai_family == AF_INET6) + { + struct sockaddr_in6 * addr = reinterpret_cast(result->ai_addr); + address = Inet::IPAddress::FromSockAddr(*addr); + interfaceId = Inet::InterfaceId(addr->sin6_scope_id); + } +#if INET_CONFIG_ENABLE_IPV4 + else if (result->ai_family == AF_INET) + { + address = Inet::IPAddress::FromSockAddr(*reinterpret_cast(result->ai_addr)); + interfaceId = Inet::InterfaceId::Null(); + } +#endif // INET_CONFIG_ENABLE_IPV4 + else + { + ChipLogError(NotSpecified, "Unsupported address: %s", addressString); + freeaddrinfo(result); + return false; + } + + freeaddrinfo(result); + return true; +} + +} // namespace + +PairingManager::PairingManager() : + mOnOpenCommissioningWindowCallback(OnOpenCommissioningWindowResponse, this), + mOnOpenCommissioningWindowVerifierCallback(OnOpenCommissioningWindowVerifierResponse, this), + mCurrentFabricRemoveCallback(OnCurrentFabricRemove, this) +{} + +CHIP_ERROR PairingManager::Init(Controller::DeviceCommissioner * commissioner) +{ + VerifyOrReturnError(commissioner != nullptr, CHIP_ERROR_INCORRECT_STATE); + + mCommissioner = commissioner; + + return CHIP_NO_ERROR; +} + +CHIP_ERROR PairingManager::OpenCommissioningWindow(NodeId nodeId, EndpointId endpointId, uint16_t commissioningTimeoutSec, + uint32_t iterations, uint16_t discriminator, const ByteSpan & salt, + const ByteSpan & verifier) +{ + if (mCommissioner == nullptr) + { + ChipLogError(NotSpecified, "Commissioner is null, cannot open commissioning window"); + return CHIP_ERROR_INCORRECT_STATE; + } + + // Check if a window is already open + if (mWindowOpener != nullptr) + { + ChipLogError(NotSpecified, "A commissioning window is already open"); + return CHIP_ERROR_INCORRECT_STATE; + } + + // Ensure salt and verifier sizes are valid + if (!salt.empty() && salt.size() > chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length) + { + ChipLogError(NotSpecified, "Salt size exceeds buffer capacity"); + return CHIP_ERROR_BUFFER_TOO_SMALL; + } + + if (!verifier.empty() && verifier.size() > chip::Crypto::kSpake2p_VerifierSerialized_Length) + { + ChipLogError(NotSpecified, "Verifier size exceeds buffer capacity"); + return CHIP_ERROR_BUFFER_TOO_SMALL; + } + + if (!salt.empty()) + { + memcpy(mSaltBuffer, salt.data(), salt.size()); + mSalt = ByteSpan(mSaltBuffer, salt.size()); + } + else + { + mSalt = ByteSpan(); + } + + if (!verifier.empty()) + { + memcpy(mVerifierBuffer, verifier.data(), verifier.size()); + mVerifier = ByteSpan(mVerifierBuffer, verifier.size()); + } + else + { + mVerifier = ByteSpan(); + } + + return DeviceLayer::SystemLayer().ScheduleLambda([nodeId, endpointId, commissioningTimeoutSec, iterations, discriminator]() { + PairingManager & self = PairingManager::Instance(); + + if (self.mCommissioner == nullptr) + { + ChipLogError(NotSpecified, "Commissioner is null, cannot open commissioning window"); + return; + } + + self.mWindowOpener = Platform::MakeUnique(self.mCommissioner); + + if (!self.mVerifier.empty()) + { + if (self.mSalt.empty()) + { + ChipLogError(NotSpecified, "Salt is required when verifier is set"); + self.mWindowOpener.reset(); + return; + } + + // Open the commissioning window with verifier parameters + CHIP_ERROR err = + self.mWindowOpener->OpenCommissioningWindow(Controller::CommissioningWindowVerifierParams() + .SetNodeId(nodeId) + .SetEndpointId(endpointId) + .SetTimeout(commissioningTimeoutSec) + .SetIteration(iterations) + .SetDiscriminator(discriminator) + .SetVerifier(self.mVerifier) + .SetSalt(self.mSalt) + .SetCallback(&self.mOnOpenCommissioningWindowVerifierCallback)); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to open commissioning window with verifier: %s", ErrorStr(err)); + self.mWindowOpener.reset(); + } + } + else + { + SetupPayload ignored; + // Open the commissioning window with passcode parameters + CHIP_ERROR err = self.mWindowOpener->OpenCommissioningWindow(Controller::CommissioningWindowPasscodeParams() + .SetNodeId(nodeId) + .SetEndpointId(endpointId) + .SetTimeout(commissioningTimeoutSec) + .SetIteration(iterations) + .SetDiscriminator(discriminator) + .SetSetupPIN(NullOptional) + .SetSalt(NullOptional) + .SetCallback(&self.mOnOpenCommissioningWindowCallback), + ignored); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to open commissioning window with passcode: %s", ErrorStr(err)); + self.mWindowOpener.reset(); + } + } + }); +} + +void PairingManager::OnOpenCommissioningWindowResponse(void * context, NodeId remoteId, CHIP_ERROR err, SetupPayload payload) +{ + VerifyOrDie(context != nullptr); + PairingManager * self = static_cast(context); + if (self->mCommissioningWindowDelegate) + { + self->mCommissioningWindowDelegate->OnCommissioningWindowOpened(remoteId, err, payload); + self->SetOpenCommissioningWindowDelegate(nullptr); + } + + OnOpenCommissioningWindowVerifierResponse(context, remoteId, err); +} + +void PairingManager::OnOpenCommissioningWindowVerifierResponse(void * context, NodeId remoteId, CHIP_ERROR err) +{ + VerifyOrDie(context != nullptr); + PairingManager * self = static_cast(context); + LogErrorOnFailure(err); + + // Reset the window opener once the window operation is complete + self->mWindowOpener.reset(); +} + +void PairingManager::OnStatusUpdate(DevicePairingDelegate::Status status) +{ + switch (status) + { + case DevicePairingDelegate::Status::SecurePairingSuccess: + ChipLogProgress(NotSpecified, "CASE establishment successful"); + break; + case DevicePairingDelegate::Status::SecurePairingFailed: + ChipLogError(NotSpecified, "Secure Pairing Failed"); + break; + } +} + +void PairingManager::OnPairingComplete(CHIP_ERROR err) +{ + if (err == CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "PASE establishment successful"); + } + else + { + ChipLogProgress(NotSpecified, "Pairing Failure: %s", ErrorStr(err)); + } +} + +void PairingManager::OnPairingDeleted(CHIP_ERROR err) +{ + if (err == CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "Pairing Deleted Success"); + } + else + { + ChipLogProgress(NotSpecified, "Pairing Deleted Failure: %s", ErrorStr(err)); + } +} + +void PairingManager::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err) +{ + if (err == CHIP_NO_ERROR) + { + // print to console + fprintf(stderr, "New device with Node ID: " ChipLogFormatX64 " has been successfully added.\n", ChipLogValueX64(nodeId)); + + // mCommissioner has a lifetime that is the entire life of the application itself + // so it is safe to provide to StartDeviceSynchronization. + DeviceSynchronizer::Instance().StartDeviceSynchronization(mCommissioner, nodeId, false); + } + else + { + ChipLogProgress(NotSpecified, "Device commissioning Failure: %s", ErrorStr(err)); + } + + if (mPairingDelegate) + { + mPairingDelegate->OnCommissioningComplete(nodeId, err); + SetPairingDelegate(nullptr); + } +} + +void PairingManager::OnReadCommissioningInfo(const Controller::ReadCommissioningInfo & info) +{ + ChipLogProgress(AppServer, "OnReadCommissioningInfo - vendorId=0x%04X productId=0x%04X", info.basic.vendorId, + info.basic.productId); + + // The string in CharSpan received from the device is not null-terminated, we use std::string here for coping and + // appending a null-terminator at the end of the string. + std::string userActiveModeTriggerInstruction; + + // Note: the callback doesn't own the buffer, should make a copy if it will be used it later. + if (info.icd.userActiveModeTriggerInstruction.size() != 0) + { + userActiveModeTriggerInstruction = + std::string(info.icd.userActiveModeTriggerInstruction.data(), info.icd.userActiveModeTriggerInstruction.size()); + } + + if (info.icd.userActiveModeTriggerHint.HasAny()) + { + ChipLogProgress(AppServer, "OnReadCommissioningInfo - LIT UserActiveModeTriggerHint=0x%08x", + info.icd.userActiveModeTriggerHint.Raw()); + ChipLogProgress(AppServer, "OnReadCommissioningInfo - LIT UserActiveModeTriggerInstruction=%s", + userActiveModeTriggerInstruction.c_str()); + } + ChipLogProgress(AppServer, "OnReadCommissioningInfo ICD - IdleModeDuration=%u activeModeDuration=%u activeModeThreshold=%u", + info.icd.idleModeDuration, info.icd.activeModeDuration, info.icd.activeModeThreshold); +} + +void PairingManager::OnDiscoveredDevice(const Dnssd::CommissionNodeData & nodeData) +{ + // Ignore nodes with closed commissioning window + VerifyOrReturn(nodeData.commissioningMode != 0); + + auto & resolutionData = nodeData; + + const uint16_t port = resolutionData.port; + char buf[Inet::IPAddress::kMaxStringLength]; + resolutionData.ipAddress[0].ToString(buf); + ChipLogProgress(NotSpecified, "Discovered Device: %s:%u", buf, port); + + // Stop Mdns discovery. + auto err = mCommissioner->StopCommissionableDiscovery(); + + // Some platforms does not implement a mechanism to stop mdns browse, so + // we just ignore CHIP_ERROR_NOT_IMPLEMENTED instead of bailing out. + if (CHIP_NO_ERROR != err && CHIP_ERROR_NOT_IMPLEMENTED != err) + { + return; + } + + mCommissioner->RegisterDeviceDiscoveryDelegate(nullptr); + + auto interfaceId = resolutionData.ipAddress[0].IsIPv6LinkLocal() ? resolutionData.interfaceId : Inet::InterfaceId::Null(); + auto peerAddress = Transport::PeerAddress::UDP(resolutionData.ipAddress[0], port, interfaceId); + err = Pair(mNodeId, peerAddress); + if (CHIP_NO_ERROR != err) + { + ChipLogProgress(NotSpecified, "Failed to pair device: " ChipLogFormatX64 " %s", ChipLogValueX64(mNodeId), ErrorStr(err)); + } +} + +Optional PairingManager::FailSafeExpiryTimeoutSecs() const +{ + // No manual input, so do not need to extend. + return Optional(); +} + +bool PairingManager::ShouldWaitAfterDeviceAttestation() +{ + // If there is a vendor ID and product ID, request OnDeviceAttestationCompleted(). + // Currently this is added in the case that the example is performing reverse commissioning, + // but it would be an improvement to store that explicitly. + // TODO: Issue #35297 - [Fabric Sync] Improve where we get VID and PID when validating CCTRL CommissionNode command + SetupPayload payload; + CHIP_ERROR err = GetPayload(mOnboardingPayload, payload); + return err == CHIP_NO_ERROR && (payload.vendorID != 0 || payload.productID != 0); +} + +void PairingManager::OnDeviceAttestationCompleted(Controller::DeviceCommissioner * deviceCommissioner, DeviceProxy * device, + const Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, + Credentials::AttestationVerificationResult attestationResult) +{ + SetupPayload payload; + CHIP_ERROR parse_error = GetPayload(mOnboardingPayload, payload); + if (parse_error == CHIP_NO_ERROR && (payload.vendorID != 0 || payload.productID != 0)) + { + if (payload.vendorID == 0 || payload.productID == 0) + { + ChipLogProgress(NotSpecified, + "Failed validation: vendorID or productID must not be 0." + "Requested VID: %u, Requested PID: %u.", + payload.vendorID, payload.productID); + deviceCommissioner->ContinueCommissioningAfterDeviceAttestation( + device, Credentials::AttestationVerificationResult::kInvalidArgument); + return; + } + + if (payload.vendorID != info.BasicInformationVendorId() || payload.productID != info.BasicInformationProductId()) + { + ChipLogProgress(NotSpecified, + "Failed validation of vendorID or productID." + "Requested VID: %u, Requested PID: %u," + "Detected VID: %u, Detected PID %u.", + payload.vendorID, payload.productID, info.BasicInformationVendorId(), info.BasicInformationProductId()); + deviceCommissioner->ContinueCommissioningAfterDeviceAttestation( + device, + payload.vendorID == info.BasicInformationVendorId() + ? Credentials::AttestationVerificationResult::kDacProductIdMismatch + : Credentials::AttestationVerificationResult::kDacVendorIdMismatch); + return; + } + + // NOTE: This will log errors even if the attestion was successful. + CHIP_ERROR err = deviceCommissioner->ContinueCommissioningAfterDeviceAttestation(device, attestationResult); + if (CHIP_NO_ERROR != err) + { + ChipLogError(NotSpecified, "Failed to continue commissioning after device attestation, error: %s", ErrorStr(err)); + } + return; + } + + // Don't bypass attestation, continue with error. + CHIP_ERROR err = deviceCommissioner->ContinueCommissioningAfterDeviceAttestation(device, attestationResult); + if (CHIP_NO_ERROR != err) + { + ChipLogError(NotSpecified, "Failed to continue commissioning after device attestation, error: %s", ErrorStr(err)); + } +} + +CommissioningParameters PairingManager::GetCommissioningParameters() +{ + auto params = CommissioningParameters(); + params.SetSkipCommissioningComplete(false); + params.SetDeviceAttestationDelegate(this); + + return params; +} + +CHIP_ERROR PairingManager::Pair(NodeId remoteId, Transport::PeerAddress address) +{ + auto params = RendezvousParameters().SetSetupPINCode(mSetupPINCode).SetDiscriminator(mDiscriminator).SetPeerAddress(address); + + CHIP_ERROR err = CHIP_NO_ERROR; + auto commissioningParams = GetCommissioningParameters(); + err = CurrentCommissioner().PairDevice(remoteId, params, commissioningParams); + + return err; +} + +void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_ERROR err) +{ + PairingManager * self = reinterpret_cast(context); + VerifyOrReturn(self != nullptr, ChipLogError(NotSpecified, "OnCurrentFabricRemove: context is null")); + + ChipLogProgress(NotSpecified, "PairingManager::OnCurrentFabricRemove"); + + if (err == CHIP_NO_ERROR) + { + // print to console + fprintf(stderr, "Device with Node ID: " ChipLogFormatX64 " has been successfully removed.\n", ChipLogValueX64(nodeId)); + + if (self->mPairingDelegate) + { + self->mPairingDelegate->OnDeviceRemoved(nodeId, err); + self->SetPairingDelegate(nullptr); + } + } + else + { + ChipLogProgress(NotSpecified, "Device unpair Failure: " ChipLogFormatX64 " %s", ChipLogValueX64(nodeId), ErrorStr(err)); + } +} + +void PairingManager::InitPairingCommand() +{ + mCommissioner->RegisterPairingDelegate(this); +} + +CHIP_ERROR PairingManager::PairDeviceWithCode(NodeId nodeId, const char * payload) +{ + if (payload == nullptr || strlen(payload) > kMaxManualCodeLength + 1) + { + ChipLogError(NotSpecified, "PairDeviceWithCode failed: Invalid pairing payload"); + return CHIP_ERROR_INVALID_STRING_LENGTH; + } + + Platform::CopyString(mOnboardingPayload, sizeof(mOnboardingPayload), payload); + + return DeviceLayer::SystemLayer().ScheduleLambda([nodeId]() { + PairingManager & self = PairingManager::Instance(); + + self.InitPairingCommand(); + + CommissioningParameters commissioningParams = self.GetCommissioningParameters(); + auto discoveryType = DiscoveryType::kDiscoveryNetworkOnly; + + self.mNodeId = nodeId; + + CHIP_ERROR err = self.mCommissioner->PairDevice(nodeId, self.mOnboardingPayload, commissioningParams, discoveryType); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to pair device with code, error: %s", ErrorStr(err)); + } + }); +} + +CHIP_ERROR PairingManager::PairDevice(chip::NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, + uint16_t deviceRemotePort) +{ + if (deviceRemoteIp == nullptr || strlen(deviceRemoteIp) > Inet::IPAddress::kMaxStringLength) + { + ChipLogError(NotSpecified, "PairDevice failed: Invalid device remote IP address"); + return CHIP_ERROR_INVALID_STRING_LENGTH; + } + + Platform::CopyString(mRemoteIpAddr, sizeof(mRemoteIpAddr), deviceRemoteIp); + + return DeviceLayer::SystemLayer().ScheduleLambda([nodeId, setupPINCode, deviceRemotePort]() { + PairingManager & self = PairingManager::Instance(); + + self.InitPairingCommand(); + self.mSetupPINCode = setupPINCode; + + Inet::IPAddress address; + Inet::InterfaceId interfaceId; + + if (!ParseAddressWithInterface(self.mRemoteIpAddr, address, interfaceId)) + { + ChipLogError(NotSpecified, "Invalid IP address: %s", self.mRemoteIpAddr); + return; + } + + CHIP_ERROR err = self.Pair(nodeId, Transport::PeerAddress::UDP(address, deviceRemotePort, interfaceId)); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to pair device, error: %s", ErrorStr(err)); + } + }); +} + +CHIP_ERROR PairingManager::UnpairDevice(NodeId nodeId) +{ + return DeviceLayer::SystemLayer().ScheduleLambda([nodeId]() { + PairingManager & self = PairingManager::Instance(); + + self.InitPairingCommand(); + + self.mCurrentFabricRemover = Platform::MakeUnique(self.mCommissioner); + + if (!self.mCurrentFabricRemover) + { + ChipLogError(NotSpecified, "Failed to unpair device, mCurrentFabricRemover is null"); + return; + } + + CHIP_ERROR err = self.mCurrentFabricRemover->RemoveCurrentFabric(nodeId, &self.mCurrentFabricRemoveCallback); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to unpair device, error: %s", ErrorStr(err)); + } + }); +} + +} // namespace admin diff --git a/examples/fabric-sync/admin/PairingManager.h b/examples/fabric-sync/admin/PairingManager.h new file mode 100644 index 00000000000000..9d109911e195df --- /dev/null +++ b/examples/fabric-sync/admin/PairingManager.h @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace admin { + +// Constants +constexpr uint16_t kMaxManualCodeLength = 22; + +class CommissioningWindowDelegate +{ +public: + virtual void OnCommissioningWindowOpened(chip::NodeId deviceId, CHIP_ERROR err, chip::SetupPayload payload) = 0; + virtual ~CommissioningWindowDelegate() = default; +}; + +class PairingDelegate +{ +public: + virtual void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) {} + virtual void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) {} + virtual ~PairingDelegate() = default; +}; + +/** + * The PairingManager class is responsible for managing the commissioning and pairing process + * of Matter devices. PairingManager is designed to be used as a singleton, meaning that there + * should only be one instance of it running at any given time. + * + * Usage: + * + * 1. The class should be initialized when the system starts up, typically by invoking the static + * instance method to get the singleton. + * 2. To open a commissioning window, the appropriate method should be called on the PairingManager instance. + * 3. The PairingManager will handle the lifecycle of the CommissioningWindowOpener and ensure that + * resources are cleaned up appropriately when pairing is complete or the process is aborted. + * + * Example: + * + * @code + * PairingManager& manager = PairingManager::Instance(); + * manager.OpenCommissioningWindow(); + * @endcode + */ +class PairingManager : public chip::Controller::DevicePairingDelegate, + public chip::Controller::DeviceDiscoveryDelegate, + public chip::Credentials::DeviceAttestationDelegate +{ +public: + static PairingManager & Instance() + { + static PairingManager instance; + return instance; + } + + CHIP_ERROR Init(chip::Controller::DeviceCommissioner * commissioner); + + void SetOpenCommissioningWindowDelegate(CommissioningWindowDelegate * delegate) { mCommissioningWindowDelegate = delegate; } + void SetPairingDelegate(PairingDelegate * delegate) { mPairingDelegate = delegate; } + PairingDelegate * GetPairingDelegate() { return mPairingDelegate; } + + chip::Controller::DeviceCommissioner & CurrentCommissioner() { return *mCommissioner; }; + + /** + * Opens a commissioning window on the specified node and endpoint. + * Only one commissioning window can be active at a time. If a commissioning + * window is already open, this function will return an error. + * + * @param nodeId The target node ID for commissioning. + * @param endpointId The target endpoint ID for commissioning. + * @param commissioningTimeoutSec Timeout for the commissioning window in seconds. + * @param iterations Iterations for PBKDF calculations. + * @param discriminator Discriminator for commissioning. + * @param salt Optional salt for verifier-based commissioning. + * @param verifier Optional verifier for enhanced commissioning security. + * + * @return CHIP_ERROR_INCORRECT_STATE if a commissioning window is already open. + */ + CHIP_ERROR OpenCommissioningWindow(chip::NodeId nodeId, chip::EndpointId endpointId, uint16_t commissioningTimeoutSec, + uint32_t iterations, uint16_t discriminator, const chip::ByteSpan & salt, + const chip::ByteSpan & verifier); + + /** + * Pairs a device using a setup code payload. + * + * @param nodeId The target node ID for pairing. + * @param payload The setup code payload, which typically contains device-specific pairing information. + * + * @return CHIP_NO_ERROR on successful initiation of the pairing process, or an appropriate CHIP_ERROR if pairing fails. + */ + CHIP_ERROR PairDeviceWithCode(chip::NodeId nodeId, const char * payload); + + /** + * Pairs a device using its setup PIN code and remote IP address. + * + * @param nodeId The target node ID for pairing. + * @param setupPINCode The setup PIN code for the device, used for establishing a secure connection. + * @param deviceRemoteIp The IP address of the remote device. + * @param deviceRemotePort The port number on which the device is listening for pairing requests. + * + * @return CHIP_NO_ERROR if the pairing process is initiated successfully, or an appropriate CHIP_ERROR if pairing fails. + */ + CHIP_ERROR PairDevice(chip::NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, uint16_t deviceRemotePort); + + /** + * Unpairs a device with the specified node ID. + * + * @param nodeId The node ID of the device to be unpaired. + * + * @return CHIP_NO_ERROR if the device is successfully unpaired, or an appropriate CHIP_ERROR if the process fails. + */ + CHIP_ERROR UnpairDevice(chip::NodeId nodeId); + +private: + // Constructors + PairingManager(); + PairingManager(const PairingManager &) = delete; + PairingManager & operator=(const PairingManager &) = delete; + + // Private member functions (static and non-static) + chip::Controller::CommissioningParameters GetCommissioningParameters(); + void InitPairingCommand(); + CHIP_ERROR Pair(chip::NodeId remoteId, chip::Transport::PeerAddress address); + + /////////// DevicePairingDelegate Interface ///////// + void OnStatusUpdate(chip::Controller::DevicePairingDelegate::Status status) override; + void OnPairingComplete(CHIP_ERROR error) override; + void OnPairingDeleted(CHIP_ERROR error) override; + void OnReadCommissioningInfo(const chip::Controller::ReadCommissioningInfo & info) override; + void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR error) override; + + /////////// DeviceDiscoveryDelegate Interface ///////// + void OnDiscoveredDevice(const chip::Dnssd::CommissionNodeData & nodeData) override; + + /////////// DeviceAttestationDelegate Interface ///////// + chip::Optional FailSafeExpiryTimeoutSecs() const override; + bool ShouldWaitAfterDeviceAttestation() override; + void OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, chip::DeviceProxy * device, + const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, + chip::Credentials::AttestationVerificationResult attestationResult) override; + + static void OnOpenCommissioningWindowResponse(void * context, chip::NodeId deviceId, CHIP_ERROR status, + chip::SetupPayload payload); + static void OnOpenCommissioningWindowVerifierResponse(void * context, chip::NodeId deviceId, CHIP_ERROR status); + static void OnCurrentFabricRemove(void * context, chip::NodeId remoteNodeId, CHIP_ERROR status); + + // Private data members + chip::Controller::DeviceCommissioner * mCommissioner = nullptr; + + CommissioningWindowDelegate * mCommissioningWindowDelegate = nullptr; + PairingDelegate * mPairingDelegate = nullptr; + + chip::NodeId mNodeId = chip::kUndefinedNodeId; + chip::ByteSpan mVerifier; + chip::ByteSpan mSalt; + uint16_t mDiscriminator = 0; + uint32_t mSetupPINCode = 0; + uint8_t mVerifierBuffer[chip::Crypto::kSpake2p_VerifierSerialized_Length]; + uint8_t mSaltBuffer[chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length]; + char mRemoteIpAddr[chip::Inet::IPAddress::kMaxStringLength]; + char mOnboardingPayload[kMaxManualCodeLength + 1]; + + /** + * Holds the unique_ptr to the current CommissioningWindowOpener. + * Only one commissioning window opener can be active at a time. + * The pointer is reset when the commissioning window is closed or when an error occurs. + */ + chip::Platform::UniquePtr mWindowOpener; + chip::Callback::Callback mOnOpenCommissioningWindowCallback; + chip::Callback::Callback mOnOpenCommissioningWindowVerifierCallback; + + // For Unpair + chip::Platform::UniquePtr mCurrentFabricRemover; + chip::Callback::Callback mCurrentFabricRemoveCallback; +}; + +} // namespace admin diff --git a/examples/fabric-sync/admin/UniqueIdGetter.cpp b/examples/fabric-sync/admin/UniqueIdGetter.cpp new file mode 100644 index 00000000000000..cc3567deda6bd2 --- /dev/null +++ b/examples/fabric-sync/admin/UniqueIdGetter.cpp @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2024 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 "UniqueIdGetter.h" + +using namespace ::chip; +using namespace ::chip::app; +using chip::app::ReadClient; + +namespace admin { + +namespace { + +void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) +{ + reinterpret_cast(context)->OnDeviceConnected(exchangeMgr, sessionHandle); +} + +void OnDeviceConnectionFailureWrapper(void * context, const ScopedNodeId & peerId, CHIP_ERROR error) +{ + reinterpret_cast(context)->OnDeviceConnectionFailure(peerId, error); +} + +bool SuccessOrLog(CHIP_ERROR err, const char * name) +{ + if (err == CHIP_NO_ERROR) + { + return true; + } + + ChipLogError(NotSpecified, "Failed to read %s: %" CHIP_ERROR_FORMAT, name, err.Format()); + + return false; +} + +} // namespace + +UniqueIdGetter::UniqueIdGetter() : + mOnDeviceConnectedCallback(OnDeviceConnectedWrapper, this), + mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureWrapper, this) +{} + +CHIP_ERROR UniqueIdGetter::GetUniqueId(OnDoneCallback onDoneCallback, Controller::DeviceController & controller, NodeId nodeId, + EndpointId endpointId) +{ + assertChipStackLockedByCurrentThread(); + VerifyOrDie(!mCurrentlyGettingUid); + + mEndpointId = endpointId; + mOnDoneCallback = onDoneCallback; + mUniqueIdHasValue = false; + memset(mUniqueId, 0, sizeof(mUniqueId)); + mCurrentlyGettingUid = true; + + CHIP_ERROR err = controller.GetConnectedDevice(nodeId, &mOnDeviceConnectedCallback, &mOnDeviceConnectionFailureCallback); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to connect to remote fabric sync bridge %" CHIP_ERROR_FORMAT, err.Format()); + mCurrentlyGettingUid = false; + } + return err; +} + +void UniqueIdGetter::OnAttributeData(const ConcreteDataAttributePath & path, TLV::TLVReader * data, const StatusIB & status) +{ + VerifyOrDie(path.mClusterId == Clusters::BridgedDeviceBasicInformation::Id); + + if (!status.IsSuccess()) + { + ChipLogError(NotSpecified, "Response Failure: %" CHIP_ERROR_FORMAT, status.ToChipError().Format()); + return; + } + + switch (path.mAttributeId) + { + case Clusters::BridgedDeviceBasicInformation::Attributes::UniqueID::Id: { + mUniqueIdHasValue = SuccessOrLog(data->GetString(mUniqueId, sizeof(mUniqueId)), "UniqueId"); + break; + } + default: + break; + } +} + +void UniqueIdGetter::OnError(CHIP_ERROR error) +{ + ChipLogProgress(NotSpecified, "Error Getting UID: %" CHIP_ERROR_FORMAT, error.Format()); +} + +void UniqueIdGetter::OnDone(ReadClient * apReadClient) +{ + mCurrentlyGettingUid = false; + mOnDoneCallback(mUniqueIdHasValue ? std::make_optional(mUniqueId) : std::nullopt); +} + +void UniqueIdGetter::OnDeviceConnected(Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) +{ + VerifyOrDie(mCurrentlyGettingUid); + mClient = std::make_unique(app::InteractionModelEngine::GetInstance(), &exchangeMgr, *this /* callback */, + ReadClient::InteractionType::Read); + VerifyOrDie(mClient); + + AttributePathParams readPaths[1]; + readPaths[0] = AttributePathParams(mEndpointId, Clusters::BridgedDeviceBasicInformation::Id, + Clusters::BridgedDeviceBasicInformation::Attributes::UniqueID::Id); + + ReadPrepareParams readParams(sessionHandle); + + readParams.mpAttributePathParamsList = readPaths; + readParams.mAttributePathParamsListSize = 1; + + CHIP_ERROR err = mClient->SendRequest(readParams); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to read unique ID from the bridged device."); + OnDone(nullptr); + return; + } +} + +void UniqueIdGetter::OnDeviceConnectionFailure(const ScopedNodeId & peerId, CHIP_ERROR error) +{ + VerifyOrDie(mCurrentlyGettingUid); + ChipLogError(NotSpecified, "UniqueIdGetter failed to connect to " ChipLogFormatX64, ChipLogValueX64(peerId.GetNodeId())); + + OnDone(nullptr); +} + +} // namespace admin diff --git a/examples/fabric-sync/admin/UniqueIdGetter.h b/examples/fabric-sync/admin/UniqueIdGetter.h new file mode 100644 index 00000000000000..eba4451599c3ee --- /dev/null +++ b/examples/fabric-sync/admin/UniqueIdGetter.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2024 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 + +namespace admin { + +/** + * @brief Class used to get UniqueID from Bridged Device Basic Information Cluster + * + * When syncing a device from another fabric that does not have a UniqueID, spec + * dictates: + * When a Fabric Synchronizing Administrator commissions a Synchronized Device, + * it SHALL persist and maintain an association with the UniqueID in the Bridged + * Device Basic Information Cluster exposed by another Fabric Synchronizing + * Administrator. + * + * This class assists in retrieving the UniqueId in the above situation. + */ +class UniqueIdGetter : public chip::app::ReadClient::Callback +{ +public: + using OnDoneCallback = std::function)>; + + UniqueIdGetter(); + + CHIP_ERROR GetUniqueId(OnDoneCallback onDoneCallback, chip::Controller::DeviceController & controller, chip::NodeId nodeId, + chip::EndpointId endpointId); + + /////////////////////////////////////////////////////////////// + // ReadClient::Callback implementation + /////////////////////////////////////////////////////////////// + void OnAttributeData(const chip::app::ConcreteDataAttributePath & path, chip::TLV::TLVReader * data, + const chip::app::StatusIB & status) override; + void OnError(CHIP_ERROR error) override; + void OnDone(chip::app::ReadClient * apReadClient) override; + + /////////////////////////////////////////////////////////////// + // callbacks for CASE session establishment + /////////////////////////////////////////////////////////////// + void OnDeviceConnected(chip::Messaging::ExchangeManager & exchangeMgr, const chip::SessionHandle & sessionHandle); + void OnDeviceConnectionFailure(const chip::ScopedNodeId & peerId, CHIP_ERROR error); + +private: + std::unique_ptr mClient; + + OnDoneCallback mOnDoneCallback; + + chip::Callback::Callback mOnDeviceConnectedCallback; + chip::Callback::Callback mOnDeviceConnectionFailureCallback; + + bool mCurrentlyGettingUid = false; + bool mUniqueIdHasValue = false; + char mUniqueId[33]; + chip::EndpointId mEndpointId; +}; + +} // namespace admin diff --git a/examples/fabric-sync/bridge/BUILD.gn b/examples/fabric-sync/bridge/BUILD.gn index 310496bc54d06a..8fb79b89f2ea3b 100644 --- a/examples/fabric-sync/bridge/BUILD.gn +++ b/examples/fabric-sync/bridge/BUILD.gn @@ -17,7 +17,11 @@ import("${chip_root}/src/app/chip_data_model.gni") import("${chip_root}/src/lib/lib.gni") config("config") { - include_dirs = [ "include" ] + include_dirs = [ + ".", + "${chip_root}/examples/common", + "${chip_root}/examples/platform/linux", + ] } chip_data_model("fabric-bridge-zap") { @@ -41,15 +45,22 @@ source_set("fabric-bridge-lib") { public_configs = [ ":config" ] sources = [ + "include/Bridge.h", "include/BridgedAdministratorCommissioning.h", "include/BridgedDevice.h", "include/BridgedDeviceBasicInformationImpl.h", "include/BridgedDeviceManager.h", "include/CHIPProjectAppConfig.h", + "include/CommissionerControlDelegate.h", + "include/FabricAdminDelegate.h", + "include/FabricBridge.h", + "src/Bridge.cpp", "src/BridgedAdministratorCommissioning.cpp", "src/BridgedDevice.cpp", "src/BridgedDeviceBasicInformationImpl.cpp", "src/BridgedDeviceManager.cpp", + "src/CommissionerControlDelegate.cpp", + "src/FabricBridge.cpp", ] deps = [ diff --git a/examples/fabric-sync/bridge/include/Bridge.h b/examples/fabric-sync/bridge/include/Bridge.h new file mode 100644 index 00000000000000..d6ff91ededc4ec --- /dev/null +++ b/examples/fabric-sync/bridge/include/Bridge.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 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 "CommissionableInit.h" +#include "CommissionerControlDelegate.h" +#include "FabricAdminDelegate.h" + +namespace bridge { + +/** + * @brief Initializes the local fabric bridge system. + * + * This function sets up and initializes all necessary components required for + * device management and commissioning within the local fabric bridge. It interacts + * with the provided FabricAdminDelegate instance to manage fabric-level operations. + * Specifically, it registers command handlers, initializes device attributes, and + * prepares the bridge for commissioning operations. + * + * @param delegate A pointer to a FabricAdminDelegate instance, allowing the bridge + * to initialize and manage fabric operations. + * + * @return CHIP_NO_ERROR if all initializations are successful, or an appropriate + * CHIP_ERROR code if an initialization step fails. + */ +CHIP_ERROR BridgeInit(FabricAdminDelegate * delegate); + +/** + * @brief Shuts down the local fabric bridge system. + * + * This function performs cleanup operations and shuts down the bridge system components + * responsible for device management and commissioning. It stops the Commissioner Control + * Server and handles any errors that may occur during shutdown. + * + * @return CHIP_NO_ERROR if shutdown is successful, or an appropriate CHIP_ERROR code if any component fails to shut down. + */ +CHIP_ERROR BridgeShutdown(); + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/include/BridgedAdministratorCommissioning.h b/examples/fabric-sync/bridge/include/BridgedAdministratorCommissioning.h index 06fd9026d44225..7b5711d39557e9 100644 --- a/examples/fabric-sync/bridge/include/BridgedAdministratorCommissioning.h +++ b/examples/fabric-sync/bridge/include/BridgedAdministratorCommissioning.h @@ -20,6 +20,8 @@ #include #include +namespace bridge { + /** * @brief CADMIN cluster implementation for handling attribute interactions of bridged device endpoints. * @@ -56,3 +58,5 @@ class BridgedAdministratorCommissioning : public chip::app::AttributeAccessInter // to reflect this change. chip::app::AttributeAccessInterface * mOriginalAttributeInterface = nullptr; }; + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/include/BridgedDevice.h b/examples/fabric-sync/bridge/include/BridgedDevice.h index d2c5a64b9ef4b7..903d853ec8dce2 100644 --- a/examples/fabric-sync/bridge/include/BridgedDevice.h +++ b/examples/fabric-sync/bridge/include/BridgedDevice.h @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * @@ -23,6 +22,8 @@ #include +namespace bridge { + class BridgedDevice { public: @@ -90,3 +91,5 @@ class BridgedDevice BridgedAttributes mAttributes; AdminCommissioningAttributes mAdminCommissioningAttributes; }; + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/include/BridgedDeviceBasicInformationImpl.h b/examples/fabric-sync/bridge/include/BridgedDeviceBasicInformationImpl.h index 23403438ab2be8..f57f7d0362ae73 100644 --- a/examples/fabric-sync/bridge/include/BridgedDeviceBasicInformationImpl.h +++ b/examples/fabric-sync/bridge/include/BridgedDeviceBasicInformationImpl.h @@ -18,6 +18,8 @@ #include #include +namespace bridge { + class BridgedDeviceBasicInformationImpl : public chip::app::AttributeAccessInterface { public: @@ -30,3 +32,5 @@ class BridgedDeviceBasicInformationImpl : public chip::app::AttributeAccessInter CHIP_ERROR Read(const chip::app::ConcreteReadAttributePath & path, chip::app::AttributeValueEncoder & encoder) override; CHIP_ERROR Write(const chip::app::ConcreteDataAttributePath & path, chip::app::AttributeValueDecoder & decoder) override; }; + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/include/BridgedDeviceManager.h b/examples/fabric-sync/bridge/include/BridgedDeviceManager.h index 127898fc5b2fab..67efe74addb038 100644 --- a/examples/fabric-sync/bridge/include/BridgedDeviceManager.h +++ b/examples/fabric-sync/bridge/include/BridgedDeviceManager.h @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * @@ -24,11 +23,19 @@ #include +namespace bridge { + class BridgedDeviceManager { public: BridgedDeviceManager() = default; + static BridgedDeviceManager & Instance() + { + static BridgedDeviceManager instance; + return instance; + } + /** * @brief Initializes the BridgedDeviceManager. * @@ -52,9 +59,9 @@ class BridgedDeviceManager * * @param dev A pointer to the device to be added. * @param parentEndpointId The parent endpoint ID. Defaults to an invalid endpoint ID. - * @return int The index of the dynamic endpoint if successful, nullopt otherwise + * @return uint16_t The index of the dynamic endpoint if successful, nullopt otherwise */ - std::optional AddDeviceEndpoint(std::unique_ptr dev, + std::optional AddDeviceEndpoint(std::unique_ptr dev, chip::EndpointId parentEndpointId = chip::kInvalidEndpointId); /** @@ -100,9 +107,9 @@ class BridgedDeviceManager * found, it removes the dynamic endpoint. * * @param scopedNodeId The ScopedNodeId of the device to be removed. - * @return unsigned of the index of the removed dynamic endpoint if successful, nullopt otherwise. + * @return uint16_t of the index of the removed dynamic endpoint if successful, nullopt otherwise. */ - std::optional RemoveDeviceByScopedNodeId(chip::ScopedNodeId scopedNodeId); + std::optional RemoveDeviceByScopedNodeId(chip::ScopedNodeId scopedNodeId); /** * Finds the device with the given unique id (if any) @@ -110,27 +117,14 @@ class BridgedDeviceManager BridgedDevice * GetDeviceByUniqueId(const std::string & id); private: - friend BridgedDeviceManager & BridgeDeviceMgr(); - /** * Creates a new unique ID that is not used by any other mDevice */ std::string GenerateUniqueId(); - static BridgedDeviceManager sInstance; - chip::EndpointId mCurrentEndpointId; chip::EndpointId mFirstDynamicEndpointId; std::unique_ptr mDevices[CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT + 1]; }; -/** - * Returns the public interface of the BridgedDeviceManager singleton object. - * - * Applications should use this to access features of the BridgedDeviceManager - * object. - */ -inline BridgedDeviceManager & BridgeDeviceMgr() -{ - return BridgedDeviceManager::sInstance; -} +} // namespace bridge diff --git a/examples/fabric-sync/bridge/include/CHIPProjectAppConfig.h b/examples/fabric-sync/bridge/include/CHIPProjectAppConfig.h index b1a711658d3b91..ff6052169b488d 100644 --- a/examples/fabric-sync/bridge/include/CHIPProjectAppConfig.h +++ b/examples/fabric-sync/bridge/include/CHIPProjectAppConfig.h @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * @@ -36,6 +35,9 @@ // FabricSync needs to be both commissioners and commissionees #define CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE 1 +// See issue 23625. +#define CHIP_CONFIG_UNSAFE_SUBSCRIPTION_EXCHANGE_MANAGER_USE 1 + // Enable app platform #define CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED 1 diff --git a/examples/fabric-sync/bridge/include/CommissionerControlDelegate.h b/examples/fabric-sync/bridge/include/CommissionerControlDelegate.h new file mode 100644 index 00000000000000..45a927307bb9a7 --- /dev/null +++ b/examples/fabric-sync/bridge/include/CommissionerControlDelegate.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2024 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 "FabricAdminDelegate.h" + +#include +#include +#include + +namespace chip { +namespace app { +namespace Clusters { +namespace CommissionerControl { + +inline constexpr EndpointId kAggregatorEndpointId = 1; + +class CommissionerControlDelegate : public Delegate +{ +public: + CommissionerControlDelegate(bridge::FabricAdminDelegate * fabricAdmin) : mFabricAdmin(fabricAdmin) {} + + CHIP_ERROR HandleCommissioningApprovalRequest(const CommissioningApprovalRequest & request) override; + // TODO(#35627) clientNodeId should move towards ScopedNodeId. + CHIP_ERROR ValidateCommissionNodeCommand(NodeId clientNodeId, uint64_t requestId) override; + CHIP_ERROR GetCommissioningWindowParams(CommissioningWindowParams & outParams) override; + CHIP_ERROR HandleCommissionNode(const CommissioningWindowParams & params) override; + + ~CommissionerControlDelegate() = default; + +private: + enum class Step : uint8_t + { + // Ready to start reverse commissioning. + kIdle, + // Wait for the commission node command. + kWaitCommissionNodeRequest, + // Need to commission node. + kStartCommissionNode, + }; + + static const char * GetStateString(Step step) + { + switch (step) + { + case Step::kIdle: + return "kIdle"; + case Step::kWaitCommissionNodeRequest: + return "kWaitCommissionNodeRequest"; + case Step::kStartCommissionNode: + return "kStartCommissionNode"; + default: + return "Unknown"; + } + } + + void ResetDelegateState(); + + static constexpr size_t kLabelBufferSize = 64; + + Step mNextStep = Step::kIdle; + uint64_t mRequestId = 0; + NodeId mClientNodeId = kUndefinedNodeId; + VendorId mVendorId = VendorId::Unspecified; + uint16_t mProductId = 0; + char mLabelBuffer[kLabelBufferSize + 1]; + Optional mLabel; + + // Parameters needed for non-basic commissioning. + uint8_t mPBKDFSaltBuffer[Crypto::kSpake2p_Max_PBKDF_Salt_Length]; + ByteSpan mPBKDFSalt; + Crypto::Spake2pVerifierSerialized mPAKEPasscodeVerifierBuffer; + ByteSpan mPAKEPasscodeVerifier; + + bridge::FabricAdminDelegate * mFabricAdmin; +}; + +} // namespace CommissionerControl +} // namespace Clusters +} // namespace app +} // namespace chip + +namespace bridge { + +CHIP_ERROR CommissionerControlInit(bridge::FabricAdminDelegate * fabricAdmin); +CHIP_ERROR CommissionerControlShutdown(); + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/include/FabricAdminDelegate.h b/examples/fabric-sync/bridge/include/FabricAdminDelegate.h new file mode 100644 index 00000000000000..1637c5294fb7a7 --- /dev/null +++ b/examples/fabric-sync/bridge/include/FabricAdminDelegate.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace bridge { + +class FabricAdminDelegate +{ +public: + virtual ~FabricAdminDelegate() = default; + + /** + * Opens a commissioning window for a specified node using pre-computed PAKE passcode verifier. + * + * @param params Params for opening the commissioning window using verifier. + * @return CHIP_ERROR An error code indicating the success or failure of the operation. + * - CHIP_NO_ERROR: The RPC command was successfully sent. + * - CHIP_ERROR_BUSY: Another commissioning window is currently in progress. + * - CHIP_ERROR_INTERNAL: An internal error occurred. + */ + virtual CHIP_ERROR OpenCommissioningWindow(chip::Controller::CommissioningWindowVerifierParams params, + chip::FabricIndex fabricIndex) = 0; + + /** + * Reverse commission a bridge using the specified parameters. + * + * This function initiates the commissioning process for a bridge node, utilizing + * the provided passcode parameters, vendor ID, and product ID. + * + * @param params Parameters required for commissioning the device using passcode. + * @param vendorId The Vendor ID (VID) of the device being commissioned. This identifies + * the manufacturer of the device. + * @param productId The Product ID (PID) of the device being commissioned. This identifies + * the specific product within the vendor's lineup. + * + * @return CHIP_ERROR An error code indicating the success or failure of the operation. + * - CHIP_NO_ERROR: The RPC command was successfully sent and the commissioning process was initiated. + * - CHIP_ERROR_INTERNAL: An internal error occurred during the preparation or sending of the command. + */ + virtual CHIP_ERROR CommissionRemoteBridge(chip::Controller::CommissioningWindowPasscodeParams params, chip::VendorId vendorId, + uint16_t productId) = 0; + + virtual CHIP_ERROR KeepActive(chip::ScopedNodeId scopedNodeId, uint32_t stayActiveDurationMs, uint32_t timeoutMs) = 0; +}; + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/include/FabricBridge.h b/examples/fabric-sync/bridge/include/FabricBridge.h new file mode 100644 index 00000000000000..48a3ddae4fc0c2 --- /dev/null +++ b/examples/fabric-sync/bridge/include/FabricBridge.h @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2024 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 "FabricAdminDelegate.h" + +#include +#include +#include +#include +#include + +namespace bridge { + +#define ScopedNodeId_init_default chip::ScopedNodeId() +#define SynchronizedDevice_init_default \ + { \ + ScopedNodeId_init_default, /* id */ \ + std::nullopt, /* uniqueId */ \ + std::nullopt, /* vendorName */ \ + std::nullopt, /* vendorId */ \ + std::nullopt, /* productName */ \ + std::nullopt, /* productId */ \ + std::nullopt, /* nodeLabel */ \ + std::nullopt, /* hardwareVersion */ \ + std::nullopt, /* hardwareVersionString */ \ + std::nullopt, /* softwareVersion */ \ + std::nullopt, /* softwareVersionString */ \ + std::nullopt /* isIcd */ \ + } + +#define AdministratorCommissioningChanged_init_default \ + { \ + ScopedNodeId_init_default, /* id */ \ + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen, /* windowStatus */ \ + std::nullopt, /* openerFabricIndex */ \ + std::nullopt /* openerVendorId */ \ + } + +struct SynchronizedDevice +{ + chip::ScopedNodeId id; + + std::optional uniqueId; + std::optional vendorName; + std::optional vendorId; + std::optional productName; + std::optional productId; + std::optional nodeLabel; + std::optional hardwareVersion; + std::optional hardwareVersionString; + std::optional softwareVersion; + std::optional softwareVersionString; + std::optional isIcd; +}; + +struct AdministratorCommissioningChanged +{ + chip::ScopedNodeId id; + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum windowStatus; + std::optional openerFabricIndex; + std::optional openerVendorId; +}; + +class FabricBridge final +{ +public: + static FabricBridge & Instance(); + + void SetDelegate(FabricAdminDelegate * delegate) { mFabricAdmin = delegate; } + FabricAdminDelegate * GetDelegate() { return mFabricAdmin; } + + /** + * @brief Adds a synchronized device to the RPC client. + * + * This function attempts to add a device identified by its `nodeId` to the synchronized device list. + * It logs the progress and checks if an `AddSynchronizedDevice` operation is already in progress. + * If an operation is in progress, it returns `CHIP_ERROR_BUSY`. + * + * @return CHIP_ERROR An error code indicating the success or failure of the operation. + * - CHIP_NO_ERROR: The RPC command was successfully processed. + * - CHIP_ERROR_BUSY: Another operation is currently in progress. + * - CHIP_ERROR_INTERNAL: An internal error occurred while activating the RPC call. + */ + CHIP_ERROR AddSynchronizedDevice(const SynchronizedDevice & data); + + /** + * @brief Removes a synchronized device from the RPC client. + * + * This function attempts to remove a device identified by its `nodeId` from the synchronized device list. + * It logs the progress and checks if a `RemoveSynchronizedDevice` operation is already in progress. + * If an operation is in progress, it returns `CHIP_ERROR_BUSY`. + * + * @param scopedNodeId The Scoped Node ID of the device to be removed. + * @return CHIP_ERROR An error code indicating the success or failure of the operation. + * - CHIP_NO_ERROR: The RPC command was successfully processed. + * - CHIP_ERROR_BUSY: Another operation is currently in progress. + * - CHIP_ERROR_INTERNAL: An internal error occurred while activating the RPC call. + */ + CHIP_ERROR RemoveSynchronizedDevice(chip::ScopedNodeId scopedNodeId); + + /** + * @brief Received StayActiveResponse on behalf of client that previously called KeepActive + * + * @param scopedNodeId The Scoped Node ID of the device we recieved a StayActiveResponse. + * @param promisedActiveDurationMs the computed duration (in milliseconds) that the ICD intends to stay active for. + * @return CHIP_ERROR An error code indicating the success or failure of the operation. + * - CHIP_NO_ERROR: The RPC command was successfully processed. + * - CHIP_ERROR_BUSY: Another operation is currently in progress. + * - CHIP_ERROR_INTERNAL: An internal error occurred while activating the RPC call. + */ + CHIP_ERROR ActiveChanged(chip::ScopedNodeId scopedNodeId, uint32_t promisedActiveDurationMs); + + /** + * @brief CADMIN attribute has changed of one of the bridged devices that was previously added. + * + * @param data information regarding change in AdministratorCommissioning attributes + * @return CHIP_ERROR An error code indicating the success or failure of the operation. + * - CHIP_NO_ERROR: The RPC command was successfully processed. + * - CHIP_ERROR_BUSY: Another operation is currently in progress. + * - CHIP_ERROR_INTERNAL: An internal error occurred while activating the RPC call. + */ + CHIP_ERROR AdminCommissioningAttributeChanged(const AdministratorCommissioningChanged & data); + + /** + * @brief Notify the system that the reachability status of a bridged device has changed. + * + * @param scopedNodeId Identifier of the bridged device whose reachability has changed. + * @param reachability Boolean indicating the new reachability status of the device. + * - `true`: Device is reachable. + * - `false`: Device is not reachable. + * + * @return CHIP_ERROR Error code representing the outcome of the operation. + * - CHIP_NO_ERROR: The operation was successful. + * - CHIP_ERROR_BUSY: Another operation is currently in progress, preventing this action. + * - CHIP_ERROR_INTERNAL: An internal error occurred while processing the reachability change. + */ + CHIP_ERROR DeviceReachableChanged(chip::ScopedNodeId scopedNodeId, bool reachability); + +private: + static FabricBridge sInstance; + + FabricAdminDelegate * mFabricAdmin; +}; + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/Bridge.cpp b/examples/fabric-sync/bridge/src/Bridge.cpp new file mode 100644 index 00000000000000..3d0a4af56ff064 --- /dev/null +++ b/examples/fabric-sync/bridge/src/Bridge.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2024 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 "Bridge.h" + +#include "BridgedAdministratorCommissioning.h" +#include "BridgedDevice.h" +#include "BridgedDeviceBasicInformationImpl.h" +#include "BridgedDeviceManager.h" +#include "FabricBridge.h" + +#include +#include +#include + +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; +using namespace chip::app::Clusters::AdministratorCommissioning; +using namespace chip::app::Clusters::BridgedDeviceBasicInformation; + +// This is declared here and not in a header because zap/embr assumes all clusters +// are defined in a static endpoint in the .zap file. From there, the codegen will +// automatically use PluginApplicationCallbacksHeader.jinja to declare and call +// the respective Init callbacks. However, because EcosystemInformation cluster is only +// ever on a dynamic endpoint, this doesn't get declared and called for us, so we +// need to declare and call it ourselves where the application is initialized. +void MatterEcosystemInformationPluginServerInitCallback(); + +namespace bridge { + +namespace { + +class BridgedDeviceInformationCommandHandler : public CommandHandlerInterface +{ +public: + // Register for the BridgedDeviceBasicInformation cluster on all endpoints. + BridgedDeviceInformationCommandHandler() : + CommandHandlerInterface(Optional::Missing(), BridgedDeviceBasicInformation::Id) + {} + + void InvokeCommand(HandlerContext & handlerContext) override; +}; + +void BridgedDeviceInformationCommandHandler::InvokeCommand(HandlerContext & handlerContext) +{ + using Protocols::InteractionModel::Status; + VerifyOrReturn(handlerContext.mRequestPath.mCommandId == BridgedDeviceBasicInformation::Commands::KeepActive::Id); + + EndpointId endpointId = handlerContext.mRequestPath.mEndpointId; + ChipLogProgress(NotSpecified, "Received command to KeepActive on Endpoint: %d", endpointId); + + handlerContext.SetCommandHandled(); + + BridgedDeviceBasicInformation::Commands::KeepActive::DecodableType commandData; + if (DataModel::Decode(handlerContext.mPayload, commandData) != CHIP_NO_ERROR) + { + handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, Status::InvalidCommand); + return; + } + + const uint32_t kMinTimeoutMs = 30 * 1000; + const uint32_t kMaxTimeoutMs = 60 * 60 * 1000; + if (commandData.timeoutMs < kMinTimeoutMs || commandData.timeoutMs > kMaxTimeoutMs) + { + handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, Status::ConstraintError); + return; + } + + BridgedDevice * device = BridgedDeviceManager::Instance().GetDevice(endpointId); + if (device == nullptr || !device->IsIcd()) + { + handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, Status::Failure); + return; + } + + Status status = Status::Failure; + FabricAdminDelegate * adminDelegate = FabricBridge::Instance().GetDelegate(); + + if (adminDelegate) + { + CHIP_ERROR err = + adminDelegate->KeepActive(device->GetScopedNodeId(), commandData.stayActiveDuration, commandData.timeoutMs); + if (err == CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "KeepActive successfully processed"); + status = Status::Success; + } + else + { + ChipLogProgress(NotSpecified, "KeepActive failed to process: %s", ErrorStr(err)); + } + } + else + { + ChipLogProgress(NotSpecified, "Operation failed: adminDelegate is null"); + } + + handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, status); +} + +BridgedAdministratorCommissioning gBridgedAdministratorCommissioning; +BridgedDeviceBasicInformationImpl gBridgedDeviceBasicInformationAttributes; +BridgedDeviceInformationCommandHandler gBridgedDeviceInformationCommandHandler; + +} // namespace + +CHIP_ERROR BridgeInit(FabricAdminDelegate * delegate) +{ + MatterEcosystemInformationPluginServerInitCallback(); + CommandHandlerInterfaceRegistry::Instance().RegisterCommandHandler(&gBridgedDeviceInformationCommandHandler); + AttributeAccessInterfaceRegistry::Instance().Register(&gBridgedDeviceBasicInformationAttributes); + + BridgedDeviceManager::Instance().Init(); + FabricBridge::Instance().SetDelegate(delegate); + ReturnErrorOnFailure(gBridgedAdministratorCommissioning.Init()); + ReturnErrorOnFailure(CommissionerControlInit(delegate)); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR BridgeShutdown() +{ + CHIP_ERROR err = CommissionerControlShutdown(); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to shutdown Commissioner Control Server"); + } + + return err; +} + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/BridgedAdministratorCommissioning.cpp b/examples/fabric-sync/bridge/src/BridgedAdministratorCommissioning.cpp index a0d87cbb3b81ef..6cfb5a5caaedd7 100644 --- a/examples/fabric-sync/bridge/src/BridgedAdministratorCommissioning.cpp +++ b/examples/fabric-sync/bridge/src/BridgedAdministratorCommissioning.cpp @@ -26,6 +26,8 @@ using namespace chip::app; using namespace chip::app::Clusters; using namespace chip::app::Clusters::AdministratorCommissioning; +namespace bridge { + CHIP_ERROR BridgedAdministratorCommissioning::Init() { // We expect initialization after emberAfInit(). This allows us to unregister the existing @@ -43,7 +45,7 @@ CHIP_ERROR BridgedAdministratorCommissioning::Read(const ConcreteReadAttributePa { VerifyOrDie(aPath.mClusterId == Clusters::AdministratorCommissioning::Id); EndpointId endpointId = aPath.mEndpointId; - BridgedDevice * device = BridgeDeviceMgr().GetDevice(endpointId); + BridgedDevice * device = BridgedDeviceManager::Instance().GetDevice(endpointId); if (!device) { @@ -79,3 +81,5 @@ CHIP_ERROR BridgedAdministratorCommissioning::Read(const ConcreteReadAttributePa return CHIP_NO_ERROR; } + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/BridgedDevice.cpp b/examples/fabric-sync/bridge/src/BridgedDevice.cpp index f462d1cce6efd5..1368f19bdadf05 100644 --- a/examples/fabric-sync/bridge/src/BridgedDevice.cpp +++ b/examples/fabric-sync/bridge/src/BridgedDevice.cpp @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * @@ -27,6 +26,8 @@ using namespace chip; using namespace chip::app::Clusters::Actions; +namespace bridge { + BridgedDevice::BridgedDevice(ScopedNodeId scopedNodeId) { mReachable = false; @@ -116,3 +117,5 @@ void BridgedDevice::SetAdminCommissioningAttributes(const AdminCommissioningAttr } }); } + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/BridgedDeviceBasicInformationImpl.cpp b/examples/fabric-sync/bridge/src/BridgedDeviceBasicInformationImpl.cpp index 7fa48a4a158ddd..3a03d8f84a81a0 100644 --- a/examples/fabric-sync/bridge/src/BridgedDeviceBasicInformationImpl.cpp +++ b/examples/fabric-sync/bridge/src/BridgedDeviceBasicInformationImpl.cpp @@ -29,12 +29,14 @@ using namespace ::chip; using namespace ::chip::app; using namespace ::chip::app::Clusters; +namespace bridge { + CHIP_ERROR BridgedDeviceBasicInformationImpl::Read(const ConcreteReadAttributePath & path, AttributeValueEncoder & encoder) { // Registration is done for the bridged device basic information only VerifyOrDie(path.mClusterId == app::Clusters::BridgedDeviceBasicInformation::Id); - BridgedDevice * dev = BridgeDeviceMgr().GetDevice(path.mEndpointId); + BridgedDevice * dev = BridgedDeviceManager::Instance().GetDevice(path.mEndpointId); VerifyOrReturnError(dev != nullptr, CHIP_ERROR_NOT_FOUND); switch (path.mAttributeId) @@ -91,7 +93,7 @@ CHIP_ERROR BridgedDeviceBasicInformationImpl::Write(const ConcreteDataAttributeP { VerifyOrDie(path.mClusterId == app::Clusters::BridgedDeviceBasicInformation::Id); - BridgedDevice * dev = BridgeDeviceMgr().GetDevice(path.mEndpointId); + BridgedDevice * dev = BridgedDeviceManager::Instance().GetDevice(path.mEndpointId); VerifyOrReturnError(dev != nullptr, CHIP_ERROR_NOT_FOUND); if (!dev->IsReachable()) @@ -105,3 +107,5 @@ CHIP_ERROR BridgedDeviceBasicInformationImpl::Write(const ConcreteDataAttributeP return CHIP_ERROR_INVALID_ARGUMENT; } + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/BridgedDeviceManager.cpp b/examples/fabric-sync/bridge/src/BridgedDeviceManager.cpp index 0265f912027ca0..0ead453572aa4f 100644 --- a/examples/fabric-sync/bridge/src/BridgedDeviceManager.cpp +++ b/examples/fabric-sync/bridge/src/BridgedDeviceManager.cpp @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * @@ -45,6 +44,8 @@ using namespace chip::Transport; using namespace chip::DeviceLayer; using namespace chip::app::Clusters; +namespace bridge { + namespace { constexpr uint8_t kMaxRetries = 10; @@ -174,9 +175,6 @@ const EmberAfDeviceType sBridgedDeviceTypes[] = { { DEVICE_TYPE_BRIDGED_NODE, DE } // namespace -// Define the static member -BridgedDeviceManager BridgedDeviceManager::sInstance; - void BridgedDeviceManager::Init() { mFirstDynamicEndpointId = static_cast( @@ -184,7 +182,7 @@ void BridgedDeviceManager::Init() mCurrentEndpointId = mFirstDynamicEndpointId; } -std::optional BridgedDeviceManager::AddDeviceEndpoint(std::unique_ptr dev, +std::optional BridgedDeviceManager::AddDeviceEndpoint(std::unique_ptr dev, chip::EndpointId parentEndpointId) { EmberAfEndpointType * ep = dev->IsIcd() ? &sIcdBridgedNodeEndpoint : &sBridgedNodeEndpoint; @@ -194,6 +192,8 @@ std::optional BridgedDeviceManager::AddDeviceEndpoint(std::unique_ptr< // TODO: this shares data version among different clusters, which seems incorrect const chip::Span & dataVersionStorage = Span(sBridgedNodeDataVersions); + assertChipStackLockedByCurrentThread(); + if (dev->GetBridgedAttributes().uniqueId.empty()) { dev->SetUniqueId(GenerateUniqueId()); @@ -204,7 +204,7 @@ std::optional BridgedDeviceManager::AddDeviceEndpoint(std::unique_ptr< return std::nullopt; } - for (unsigned index = 0; index < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; index++) + for (uint16_t index = 0; index < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; index++) { if (mDevices[index]) { @@ -213,7 +213,6 @@ std::optional BridgedDeviceManager::AddDeviceEndpoint(std::unique_ptr< for (int retryCount = 0; retryCount < kMaxRetries; retryCount++) { - DeviceLayer::StackLock lock; dev->SetEndpointId(mCurrentEndpointId); dev->SetParentEndpointId(parentEndpointId); CHIP_ERROR err = @@ -327,9 +326,9 @@ BridgedDevice * BridgedDeviceManager::GetDeviceByScopedNodeId(chip::ScopedNodeId return nullptr; } -std::optional BridgedDeviceManager::RemoveDeviceByScopedNodeId(chip::ScopedNodeId scopedNodeId) +std::optional BridgedDeviceManager::RemoveDeviceByScopedNodeId(chip::ScopedNodeId scopedNodeId) { - for (unsigned index = 0; index < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; ++index) + for (uint16_t index = 0; index < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; ++index) { if (mDevices[index] && mDevices[index]->GetScopedNodeId() == scopedNodeId) { @@ -343,3 +342,5 @@ std::optional BridgedDeviceManager::RemoveDeviceByScopedNodeId(chip::S } return std::nullopt; } + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/CommissionerControlDelegate.cpp b/examples/fabric-sync/bridge/src/CommissionerControlDelegate.cpp new file mode 100644 index 00000000000000..12851177bcb212 --- /dev/null +++ b/examples/fabric-sync/bridge/src/CommissionerControlDelegate.cpp @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2024 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 "CommissionerControlDelegate.h" + +#include +#include +#include +#include +#include +#include + +using namespace chip; +using namespace chip::app; + +namespace { + +// Constants +constexpr uint16_t kDiscriminator = 3840; +constexpr uint16_t kWindowTimeout = 300; +constexpr uint16_t kIteration = 1000; +constexpr uint32_t kSetupPinCode = 20202021; + +std::unique_ptr sCommissionerControlDelegate; + +} // namespace + +namespace chip { +namespace app { +namespace Clusters { +namespace CommissionerControl { + +void CommissionerControlDelegate::ResetDelegateState() +{ + ChipLogProgress(NotSpecified, "CommissionerControlDelegate: Resetting delegate state"); + + // Reset the step to the initial state + mNextStep = Step::kIdle; + + // Reset identifiers and product information + mRequestId = 0; + mClientNodeId = kUndefinedNodeId; + mVendorId = VendorId::Unspecified; + mProductId = 0; + + // Clear the label buffer and optional label + memset(mLabelBuffer, 0, sizeof(mLabelBuffer)); + mLabel.ClearValue(); + + // Reset PBKDF salt and PAKE passcode verifier buffers + mPBKDFSalt = ByteSpan(); + memset(mPBKDFSaltBuffer, 0, sizeof(mPBKDFSaltBuffer)); + + mPAKEPasscodeVerifier = ByteSpan(); + memset(mPAKEPasscodeVerifierBuffer, 0, sizeof(mPAKEPasscodeVerifierBuffer)); +} + +CHIP_ERROR CommissionerControlDelegate::HandleCommissioningApprovalRequest(const CommissioningApprovalRequest & request) +{ + ChipLogProgress(NotSpecified, "CommissionerControlDelegate: Entering HandleCommissioningApprovalRequest, current state: %s", + GetStateString(mNextStep)); + + VerifyOrReturnError(mNextStep == Step::kIdle, CHIP_ERROR_INCORRECT_STATE); + + CommissionerControl::Events::CommissioningRequestResult::Type result; + result.requestID = request.requestId; + result.clientNodeID = request.clientNodeId; + result.fabricIndex = request.fabricIndex; + result.statusCode = static_cast(Protocols::InteractionModel::Status::Success); + + mRequestId = request.requestId; + mClientNodeId = request.clientNodeId; + mVendorId = request.vendorId; + mProductId = request.productId; + + if (request.label.HasValue()) + { + const CharSpan & labelSpan = request.label.Value(); + size_t labelLength = labelSpan.size(); + + if (labelLength >= kLabelBufferSize) + { + ChipLogError(Zcl, "Label too long to fit in buffer"); + return CHIP_ERROR_BUFFER_TOO_SMALL; + } + + if (labelLength == 0) + { + mLabel.ClearValue(); + } + else + { + memcpy(mLabelBuffer, labelSpan.data(), labelLength); + mLabelBuffer[labelLength] = '\0'; // Null-terminate the copied string + mLabel.SetValue(CharSpan(mLabelBuffer, labelLength)); + } + } + else + { + mLabel.ClearValue(); + } + + CHIP_ERROR err = CommissionerControlServer::Instance().GenerateCommissioningRequestResultEvent(kAggregatorEndpointId, result); + + if (err == CHIP_NO_ERROR) + { + mNextStep = Step::kWaitCommissionNodeRequest; + ChipLogProgress(NotSpecified, "CommissionerControlDelegate: State transitioned to %s", GetStateString(mNextStep)); + } + else + { + ResetDelegateState(); + } + + return err; +} + +CHIP_ERROR CommissionerControlDelegate::ValidateCommissionNodeCommand(NodeId clientNodeId, uint64_t requestId) +{ + ChipLogProgress(NotSpecified, "CommissionerControlDelegate: Entering ValidateCommissionNodeCommand, current state: %s", + GetStateString(mNextStep)); + + CHIP_ERROR err = CHIP_NO_ERROR; + + VerifyOrReturnError(mNextStep == Step::kWaitCommissionNodeRequest, CHIP_ERROR_INCORRECT_STATE); + + // Verify if the CommissionNode command is sent from the same NodeId as the RequestCommissioningApproval. + VerifyOrExit(mClientNodeId == clientNodeId, err = CHIP_ERROR_WRONG_NODE_ID); + + // Verify if the provided RequestId matches the value provided to the RequestCommissioningApproval. + VerifyOrExit(mRequestId == requestId, err = CHIP_ERROR_INCORRECT_STATE); + + mNextStep = Step::kStartCommissionNode; + ChipLogProgress(NotSpecified, "CommissionerControlDelegate: State transitioned to %s", GetStateString(mNextStep)); + +exit: + return err; +} + +CHIP_ERROR CommissionerControlDelegate::GetCommissioningWindowParams(CommissioningWindowParams & outParams) +{ + // Populate outParams with the required details. + outParams.iterations = kIteration; + outParams.commissioningTimeout = kWindowTimeout; + outParams.discriminator = kDiscriminator; + + ReturnErrorOnFailure(Crypto::DRBG_get_bytes(mPBKDFSaltBuffer, sizeof(mPBKDFSaltBuffer))); + mPBKDFSalt = ByteSpan(mPBKDFSaltBuffer); + outParams.salt = mPBKDFSalt; + + Crypto::Spake2pVerifier verifier; + uint32_t setupPIN = kSetupPinCode; + ReturnErrorOnFailure(PASESession::GeneratePASEVerifier(verifier, kIteration, mPBKDFSalt, false, setupPIN)); + + MutableByteSpan serializedVerifierSpan(mPAKEPasscodeVerifierBuffer); + ReturnErrorOnFailure(verifier.Serialize(serializedVerifierSpan)); + mPAKEPasscodeVerifier = serializedVerifierSpan; + outParams.PAKEPasscodeVerifier = mPAKEPasscodeVerifier; + + return CHIP_NO_ERROR; +} + +CHIP_ERROR CommissionerControlDelegate::HandleCommissionNode(const CommissioningWindowParams & params) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + ChipLogProgress(NotSpecified, "CommissionerControlDelegate: Entering HandleCommissionNode, current state: %s", + GetStateString(mNextStep)); + + VerifyOrReturnError(mNextStep == Step::kStartCommissionNode, CHIP_ERROR_INCORRECT_STATE); + + // Attempt to reverse commission the bridge using provided commissioning parameters. + err = mFabricAdmin->CommissionRemoteBridge(Controller::CommissioningWindowPasscodeParams() + .SetSetupPIN(kSetupPinCode) + .SetTimeout(params.commissioningTimeout) + .SetDiscriminator(params.discriminator) + .SetIteration(params.iterations) + .SetSalt(params.salt), + mVendorId, mProductId); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to reverse commission the fabric bridge. Error: %" CHIP_ERROR_FORMAT, err.Format()); + } + + // Reset the delegate's state to prepare for a new commissioning sequence. + ResetDelegateState(); + + return err; +} + +} // namespace CommissionerControl +} // namespace Clusters +} // namespace app +} // namespace chip + +namespace bridge { + +CHIP_ERROR CommissionerControlInit(bridge::FabricAdminDelegate * fabricAdmin) +{ + CHIP_ERROR err; + + if (sCommissionerControlDelegate) + { + ChipLogError(NotSpecified, "Commissioner Control Delegate already exists."); + return CHIP_ERROR_INCORRECT_STATE; + } + + sCommissionerControlDelegate = std::make_unique(fabricAdmin); + if (!sCommissionerControlDelegate) + { + ChipLogError(NotSpecified, "Failed to allocate memory for Commissioner Control Delegate."); + return CHIP_ERROR_NO_MEMORY; + } + + err = Clusters::CommissionerControl::CommissionerControlServer::Instance().Init(*sCommissionerControlDelegate); + if (err != CHIP_NO_ERROR) + { + ChipLogError(AppServer, "Initialization failed on Commissioner Control Delegate."); + sCommissionerControlDelegate.reset(); + return err; + } + + ChipLogProgress(Zcl, "Initializing SupportedDeviceCategories of Commissioner Control Cluster for this device."); + + BitMask supportedDeviceCategories; + supportedDeviceCategories.SetField(Clusters::CommissionerControl::SupportedDeviceCategoryBitmap::kFabricSynchronization, 1); + + Protocols::InteractionModel::Status status = + Clusters::CommissionerControl::CommissionerControlServer::Instance().SetSupportedDeviceCategoriesValue( + Clusters::CommissionerControl::kAggregatorEndpointId, supportedDeviceCategories); + + if (status != Protocols::InteractionModel::Status::Success) + { + ChipLogError(NotSpecified, "Failed to set SupportedDeviceCategories: %d", static_cast(status)); + sCommissionerControlDelegate.reset(); + return CHIP_ERROR_INTERNAL; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR CommissionerControlShutdown() +{ + if (sCommissionerControlDelegate) + { + sCommissionerControlDelegate.reset(); + } + + return CHIP_NO_ERROR; +} + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/FabricBridge.cpp b/examples/fabric-sync/bridge/src/FabricBridge.cpp new file mode 100644 index 00000000000000..aa856ccf129ccc --- /dev/null +++ b/examples/fabric-sync/bridge/src/FabricBridge.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2024 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 "FabricBridge.h" +#include "BridgedDevice.h" +#include "BridgedDeviceManager.h" + +#include +#include + +#include +#include + +using namespace chip; + +namespace bridge { + +FabricBridge FabricBridge::sInstance; + +FabricBridge & FabricBridge::Instance() +{ + return sInstance; +} + +CHIP_ERROR FabricBridge::AddSynchronizedDevice(const SynchronizedDevice & data) +{ + ChipLogProgress(NotSpecified, "Received AddSynchronizedDevice: Id=[%d:" ChipLogFormatX64 "]", data.id.GetFabricIndex(), + ChipLogValueX64(data.id.GetNodeId())); + + // Create a new BridgedDevice and set it as reachable + auto device = std::make_unique(data.id); + device->SetReachable(true); + + // Initialize BridgedDevice attributes from data + BridgedDevice::BridgedAttributes attributes; + + if (data.uniqueId.has_value()) + { + attributes.uniqueId = data.uniqueId.value(); + } + + if (data.vendorName.has_value()) + { + attributes.vendorName = data.vendorName.value(); + } + + if (data.vendorId.has_value()) + { + attributes.vendorId = data.vendorId.value(); + } + + if (data.productName.has_value()) + { + attributes.productName = data.productName.value(); + } + + if (data.productId.has_value()) + { + attributes.productId = data.productId.value(); + } + + if (data.nodeLabel.has_value()) + { + attributes.nodeLabel = data.nodeLabel.value(); + } + + if (data.hardwareVersion.has_value()) + { + attributes.hardwareVersion = data.hardwareVersion.value(); + } + + if (data.hardwareVersionString.has_value()) + { + attributes.hardwareVersionString = data.hardwareVersionString.value(); + } + + if (data.softwareVersion.has_value()) + { + attributes.softwareVersion = data.softwareVersion.value(); + } + + if (data.softwareVersionString.has_value()) + { + attributes.softwareVersionString = data.softwareVersionString.value(); + } + + // Set bridged device attributes and ICD status + device->SetBridgedAttributes(attributes); + device->SetIcd(data.isIcd.value_or(false)); + + // Add the device to the bridge manager with a parent endpoint + auto result = BridgedDeviceManager::Instance().AddDeviceEndpoint(std::move(device), /* parentEndpointId= */ 1); + if (!result.has_value()) + { + ChipLogError(NotSpecified, "Failed to add device with Id=[%d:0x" ChipLogFormatX64 "]", data.id.GetFabricIndex(), + ChipLogValueX64(data.id.GetNodeId())); + return CHIP_ERROR_ENDPOINT_POOL_FULL; + } + + // Retrieve and verify the added device by ScopedNodeId + BridgedDevice * addedDevice = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(data.id); + VerifyOrDie(addedDevice); + + ChipLogProgress(NotSpecified, "Added device with Id=[%d:0x" ChipLogFormatX64 "]", data.id.GetFabricIndex(), + ChipLogValueX64(data.id.GetNodeId())); + + // Add the Ecosystem Information Cluster to the device's endpoint + CHIP_ERROR err = + app::Clusters::EcosystemInformation::EcosystemInformationServer::Instance().AddEcosystemInformationClusterToEndpoint( + addedDevice->GetEndpointId()); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to add Ecosystem Information Cluster to endpoint %u: %" CHIP_ERROR_FORMAT, + addedDevice->GetEndpointId(), err.Format()); + } + + return err; +} + +CHIP_ERROR FabricBridge::RemoveSynchronizedDevice(ScopedNodeId scopedNodeId) +{ + ChipLogProgress(NotSpecified, "Received RemoveSynchronizedDevice: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), + ChipLogValueX64(scopedNodeId.GetNodeId())); + + auto removedIdx = BridgedDeviceManager::Instance().RemoveDeviceByScopedNodeId(scopedNodeId); + if (!removedIdx.has_value()) + { + ChipLogError(NotSpecified, "Failed to remove device with Id=[%d:0x" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), + ChipLogValueX64(scopedNodeId.GetNodeId())); + return CHIP_ERROR_NOT_FOUND; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FabricBridge::ActiveChanged(ScopedNodeId scopedNodeId, uint32_t promisedActiveDurationMs) +{ + ChipLogProgress(NotSpecified, "Received ActiveChanged: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), + ChipLogValueX64(scopedNodeId.GetNodeId())); + + auto * device = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(scopedNodeId); + if (device == nullptr) + { + ChipLogError(NotSpecified, "Could not find bridged device associated with Id=[%d:0x" ChipLogFormatX64 "]", + scopedNodeId.GetFabricIndex(), ChipLogValueX64(scopedNodeId.GetNodeId())); + return CHIP_ERROR_NOT_FOUND; + } + + device->LogActiveChangeEvent(promisedActiveDurationMs); + return CHIP_NO_ERROR; +} + +CHIP_ERROR FabricBridge::AdminCommissioningAttributeChanged(const AdministratorCommissioningChanged & data) +{ + ChipLogProgress(NotSpecified, "Received CADMIN attribute change: Id=[%d:" ChipLogFormatX64 "]", data.id.GetFabricIndex(), + ChipLogValueX64(data.id.GetNodeId())); + + auto * device = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(data.id); + if (device == nullptr) + { + ChipLogError(NotSpecified, "Could not find bridged device associated with Id=[%d:0x" ChipLogFormatX64 "]", + data.id.GetFabricIndex(), ChipLogValueX64(data.id.GetNodeId())); + return CHIP_ERROR_NOT_FOUND; + } + + BridgedDevice::AdminCommissioningAttributes adminCommissioningAttributes; + + VerifyOrReturnError(data.windowStatus < + app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kUnknownEnumValue, + CHIP_ERROR_INVALID_ARGUMENT); + + adminCommissioningAttributes.commissioningWindowStatus = data.windowStatus; + if (data.openerFabricIndex.has_value()) + { + VerifyOrReturnError(data.openerFabricIndex >= kMinValidFabricIndex, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(data.openerFabricIndex <= kMaxValidFabricIndex, CHIP_ERROR_INVALID_ARGUMENT); + adminCommissioningAttributes.openerFabricIndex = data.openerFabricIndex; + } + + if (data.openerVendorId.has_value()) + { + VerifyOrReturnError(data.openerVendorId != VendorId::NotSpecified, CHIP_ERROR_INVALID_ARGUMENT); + adminCommissioningAttributes.openerVendorId = data.openerVendorId; + } + + device->SetAdminCommissioningAttributes(adminCommissioningAttributes); + return CHIP_NO_ERROR; +} + +CHIP_ERROR FabricBridge::DeviceReachableChanged(ScopedNodeId scopedNodeId, bool reachability) +{ + ChipLogProgress(NotSpecified, "Received device reachable changed: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), + ChipLogValueX64(scopedNodeId.GetNodeId())); + + auto * device = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(scopedNodeId); + if (device == nullptr) + { + ChipLogError(NotSpecified, "Could not find bridged device associated with Id=[%d:0x" ChipLogFormatX64 "]", + scopedNodeId.GetFabricIndex(), ChipLogValueX64(scopedNodeId.GetNodeId())); + return CHIP_ERROR_NOT_FOUND; + } + + device->ReachableChanged(reachability); + + return CHIP_NO_ERROR; +} + +} // namespace bridge diff --git a/examples/fabric-sync/main.cpp b/examples/fabric-sync/main.cpp index 66541b32de91f9..8772400ff2ae16 100644 --- a/examples/fabric-sync/main.cpp +++ b/examples/fabric-sync/main.cpp @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * @@ -17,6 +16,13 @@ */ #include +#include +#include +#include + +#if defined(ENABLE_CHIP_SHELL) +#include "ShellCommands.h" +#endif using namespace chip; @@ -77,12 +83,21 @@ void ApplicationInit() // Redirect logs to the custom logging callback Logging::SetLogRedirectCallback(LoggingCallback); + + CHIP_ERROR err = bridge::BridgeInit(&admin::FabricAdmin::Instance()); + VerifyOrDieWithMsg(err == CHIP_NO_ERROR, NotSpecified, "Fabric-Sync: Failed to initialize bridge, error: %s", ErrorStr(err)); } void ApplicationShutdown() { ChipLogDetail(NotSpecified, "Fabric-Sync: ApplicationShutdown()"); CloseLogFile(); + + CHIP_ERROR err = bridge::BridgeShutdown(); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Fabric-Sync: Failed to shutdown bridge, error: %s", ErrorStr(err)); + } } int main(int argc, char * argv[]) @@ -90,6 +105,19 @@ int main(int argc, char * argv[]) VerifyOrDie(ChipLinuxAppInit(argc, argv) == 0); +#if defined(ENABLE_CHIP_SHELL) + Shell::RegisterCommands(); +#endif + + CHIP_ERROR err = admin::PairingManager::Instance().Init(GetDeviceCommissioner()); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "Failed to init PairingManager: %s ", ErrorStr(err)); + + // End the program with non zero error code to indicate a error. + return 1; + } + ChipLinuxAppMainLoop(); return 0; diff --git a/examples/fabric-sync/shell/AddBridgeCommand.cpp b/examples/fabric-sync/shell/AddBridgeCommand.cpp new file mode 100644 index 00000000000000..e6b9dd060351e6 --- /dev/null +++ b/examples/fabric-sync/shell/AddBridgeCommand.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2024 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 "AddBridgeCommand.h" + +#include +#include + +using namespace ::chip; + +namespace commands { + +AddBridgeCommand::AddBridgeCommand(chip::NodeId nodeId, uint32_t setupPINCode, const char * remoteAddr, uint16_t remotePort) : + mBridgeNodeId(nodeId), mSetupPINCode(setupPINCode), mRemoteAddr(remoteAddr), mRemotePort(remotePort) +{} + +void AddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) +{ + if (mBridgeNodeId != deviceId) + { + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to pair non-bridge device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + else + { + ChipLogProgress(NotSpecified, "Commissioning complete for non-bridge device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(deviceId)); + } + return; + } + + if (err == CHIP_NO_ERROR) + { + admin::DeviceManager::Instance().SetRemoteBridgeNodeId(mBridgeNodeId); + + ChipLogProgress(NotSpecified, "Successfully paired bridge device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(mBridgeNodeId)); + + admin::DeviceManager::Instance().UpdateLastUsedNodeId(mBridgeNodeId); + admin::DeviceManager::Instance().SubscribeRemoteFabricBridge(); + + // After successful commissioning of the Commissionee, initiate Reverse Commissioning + // via the Commissioner Control Cluster. However, we must first verify that the + // remote Fabric-Bridge supports Fabric Synchronization. + // + // Note: The Fabric-Admin MUST NOT send the RequestCommissioningApproval command + // if the remote Fabric-Bridge lacks Fabric Synchronization support. + DeviceLayer::SystemLayer().ScheduleLambda([]() { admin::DeviceManager::Instance().ReadSupportedDeviceCategories(); }); + } + else + { + ChipLogError(NotSpecified, "Failed to pair bridge device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + CommandRegistry::Instance().ResetActiveCommand(); +} + +CHIP_ERROR AddBridgeCommand::RunCommand() +{ + if (admin::DeviceManager::Instance().IsFabricSyncReady()) + { + // print to console + fprintf(stderr, "Remote Fabric Bridge has already been configured.\n"); + return CHIP_ERROR_INCORRECT_STATE; + } + + admin::PairingManager::Instance().SetPairingDelegate(this); + + ChipLogProgress(NotSpecified, "Running AddBridgeCommand with Node ID: %lu, PIN Code: %u, Address: %s, Port: %u", mBridgeNodeId, + mSetupPINCode, mRemoteAddr, mRemotePort); + + return admin::DeviceManager::Instance().PairRemoteFabricBridge(mBridgeNodeId, mSetupPINCode, mRemoteAddr, mRemotePort); +} + +} // namespace commands diff --git a/examples/fabric-sync/shell/AddBridgeCommand.h b/examples/fabric-sync/shell/AddBridgeCommand.h new file mode 100644 index 00000000000000..d2f6ff7b306c94 --- /dev/null +++ b/examples/fabric-sync/shell/AddBridgeCommand.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 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 + +namespace commands { + +class AddBridgeCommand : public Command, public admin::PairingDelegate +{ +public: + AddBridgeCommand(chip::NodeId nodeId, uint32_t setupPINCode, const char * remoteAddr, uint16_t remotePort); + void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) override; + CHIP_ERROR RunCommand() override; + +private: + chip::NodeId mBridgeNodeId; + uint32_t mSetupPINCode; + const char * mRemoteAddr; + uint16_t mRemotePort; +}; + +} // namespace commands diff --git a/examples/fabric-sync/shell/AddDeviceCommand.cpp b/examples/fabric-sync/shell/AddDeviceCommand.cpp new file mode 100644 index 00000000000000..a79e4696caaf4e --- /dev/null +++ b/examples/fabric-sync/shell/AddDeviceCommand.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2024 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 "AddDeviceCommand.h" + +#include +#include + +using namespace ::chip; + +namespace commands { + +AddDeviceCommand::AddDeviceCommand(chip::NodeId nodeId, uint32_t setupPINCode, const char * remoteAddr, uint16_t remotePort) : + mNodeId(nodeId), mSetupPINCode(setupPINCode), mRemoteAddr(remoteAddr), mRemotePort(remotePort) +{} + +void AddDeviceCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) +{ + if (mNodeId != deviceId) + { + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, + "Failed to pair non-specified device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + else + { + ChipLogProgress(NotSpecified, "Commissioning complete for non-specified device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(deviceId)); + } + return; + } + + if (err == CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "Successfully paired device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mNodeId)); + + admin::DeviceManager::Instance().UpdateLastUsedNodeId(mNodeId); + } + else + { + ChipLogError(NotSpecified, "Failed to pair device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + CommandRegistry::Instance().ResetActiveCommand(); +} + +CHIP_ERROR AddDeviceCommand::RunCommand() +{ + if (admin::DeviceManager::Instance().IsCurrentBridgeDevice(mNodeId)) + { + // print to console + fprintf(stderr, "The specified node ID has been reserved by the Fabric Bridge.\n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + ChipLogProgress(NotSpecified, "Running AddDeviceCommand with Node ID: %lu, PIN Code: %u, Address: %s, Port: %u", mNodeId, + mSetupPINCode, mRemoteAddr, mRemotePort); + + admin::PairingManager::Instance().SetPairingDelegate(this); + + return admin::DeviceManager::Instance().PairRemoteDevice(mNodeId, mSetupPINCode, mRemoteAddr, mRemotePort); +} + +} // namespace commands diff --git a/examples/fabric-sync/shell/AddDeviceCommand.h b/examples/fabric-sync/shell/AddDeviceCommand.h new file mode 100644 index 00000000000000..35d0ed93d9a416 --- /dev/null +++ b/examples/fabric-sync/shell/AddDeviceCommand.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 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 + +namespace commands { + +class AddDeviceCommand : public Command, public admin::PairingDelegate +{ +public: + AddDeviceCommand(chip::NodeId nodeId, uint32_t setupPINCode, const char * remoteAddr, uint16_t remotePort); + void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) override; + CHIP_ERROR RunCommand() override; + +private: + chip::NodeId mNodeId; + uint32_t mSetupPINCode; + const char * mRemoteAddr; + uint16_t mRemotePort; +}; + +} // namespace commands diff --git a/examples/fabric-sync/shell/BUILD.gn b/examples/fabric-sync/shell/BUILD.gn new file mode 100644 index 00000000000000..3aa56122254a4a --- /dev/null +++ b/examples/fabric-sync/shell/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("${chip_root}/src/app/chip_data_model.gni") + +config("config") { + include_dirs = [ + ".", + "${chip_root}/examples/common", + "${chip_root}/examples/fabric-sync", + ] +} + +source_set("shell") { + public_configs = [ ":config" ] + + sources = [ + "AddBridgeCommand.cpp", + "AddBridgeCommand.h", + "AddDeviceCommand.cpp", + "AddDeviceCommand.h", + "CommandRegistry.cpp", + "CommandRegistry.h", + "RemoveBridgeCommand.cpp", + "RemoveBridgeCommand.h", + "RemoveDeviceCommand.cpp", + "RemoveDeviceCommand.h", + "ShellCommands.cpp", + "ShellCommands.h", + "SyncDeviceCommand.cpp", + "SyncDeviceCommand.h", + ] + + deps = [ + "${chip_root}/examples/fabric-sync/admin:fabric-admin-lib", + "${chip_root}/examples/fabric-sync/bridge:fabric-bridge-lib", + "${chip_root}/src/lib", + ] +} diff --git a/examples/fabric-sync/shell/CommandRegistry.cpp b/examples/fabric-sync/shell/CommandRegistry.cpp new file mode 100644 index 00000000000000..34c01357eafd57 --- /dev/null +++ b/examples/fabric-sync/shell/CommandRegistry.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2024 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 "CommandRegistry.h" + +#include + +using namespace ::chip; + +namespace commands { + +void CommandRegistry::SetActiveCommand(std::unique_ptr command, uint32_t timeoutSeconds) +{ + mActiveCommand = std::move(command); + + // Cancel any previous timer to avoid multiple timers running simultaneously + DeviceLayer::SystemLayer().CancelTimer(OnTimeout, this); + + // Start a new timer for the specified timeout + CHIP_ERROR err = DeviceLayer::SystemLayer().StartTimer(System::Clock::Milliseconds32(timeoutSeconds * 1000), OnTimeout, this); + if (err != CHIP_NO_ERROR) + { + ResetActiveCommand(); + } +} + +void CommandRegistry::ResetActiveCommand() +{ + DeviceLayer::SystemLayer().CancelTimer(OnTimeout, this); + mActiveCommand.reset(); +} + +} // namespace commands diff --git a/examples/fabric-sync/shell/CommandRegistry.h b/examples/fabric-sync/shell/CommandRegistry.h new file mode 100644 index 00000000000000..0043c267a5104e --- /dev/null +++ b/examples/fabric-sync/shell/CommandRegistry.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2024 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 + +namespace commands { + +class Command +{ +public: + virtual ~Command() = default; + virtual CHIP_ERROR RunCommand() = 0; +}; + +class CommandRegistry +{ +public: + static CommandRegistry & Instance() + { + static CommandRegistry instance; + return instance; + } + + void SetActiveCommand(std::unique_ptr command, uint32_t timeoutSeconds = 30); + + Command * GetActiveCommand() { return mActiveCommand.get(); } + + void ResetActiveCommand(); + + bool IsCommandActive() const { return mActiveCommand != nullptr; } + +private: + CommandRegistry() = default; + + static void OnTimeout(chip::System::Layer * layer, void * appState) + { + // Callback function to reset the command when the timer expires + static_cast(appState)->ResetActiveCommand(); + } + + std::unique_ptr mActiveCommand; +}; + +} // namespace commands diff --git a/examples/fabric-sync/shell/RemoveBridgeCommand.cpp b/examples/fabric-sync/shell/RemoveBridgeCommand.cpp new file mode 100644 index 00000000000000..9a33b0b11ba94e --- /dev/null +++ b/examples/fabric-sync/shell/RemoveBridgeCommand.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2024 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 "RemoveBridgeCommand.h" + +#include +#include + +using namespace ::chip; + +namespace commands { + +void RemoveBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) +{ + if (mBridgeNodeId != deviceId) + { + ChipLogProgress(NotSpecified, "An non-bridge device: NodeId: " ChipLogFormatX64 " is removed.", ChipLogValueX64(deviceId)); + return; + } + + if (err == CHIP_NO_ERROR) + { + admin::DeviceManager::Instance().SetRemoteBridgeNodeId(kUndefinedNodeId); + + // print to console + fprintf(stderr, "Successfully removed bridge device: NodeId: " ChipLogFormatX64 "\n", ChipLogValueX64(mBridgeNodeId)); + } + else + { + ChipLogError(NotSpecified, "Failed to remove bridge device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + CommandRegistry::Instance().ResetActiveCommand(); +} + +CHIP_ERROR RemoveBridgeCommand::RunCommand() +{ + NodeId bridgeNodeId = admin::DeviceManager::Instance().GetRemoteBridgeNodeId(); + + if (bridgeNodeId == kUndefinedNodeId) + { + // print to console + fprintf(stderr, "Remote Fabric Bridge is not configured yet, nothing to remove.\n"); + return CHIP_ERROR_INCORRECT_STATE; + } + + mBridgeNodeId = bridgeNodeId; + + ChipLogProgress(NotSpecified, "Running RemoveBridgeCommand"); + + admin::PairingManager::Instance().SetPairingDelegate(this); + + return admin::DeviceManager::Instance().UnpairRemoteFabricBridge(); +} + +} // namespace commands diff --git a/examples/fabric-sync/shell/RemoveBridgeCommand.h b/examples/fabric-sync/shell/RemoveBridgeCommand.h new file mode 100644 index 00000000000000..b0e4b33d52ce8b --- /dev/null +++ b/examples/fabric-sync/shell/RemoveBridgeCommand.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 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 + +namespace commands { + +class RemoveBridgeCommand : public Command, public admin::PairingDelegate +{ +public: + void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; + CHIP_ERROR RunCommand() override; + +private: + chip::NodeId mBridgeNodeId = chip::kUndefinedNodeId; +}; + +} // namespace commands diff --git a/examples/fabric-sync/shell/RemoveDeviceCommand.cpp b/examples/fabric-sync/shell/RemoveDeviceCommand.cpp new file mode 100644 index 00000000000000..5e316658d5b303 --- /dev/null +++ b/examples/fabric-sync/shell/RemoveDeviceCommand.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024 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 "RemoveDeviceCommand.h" + +#include +#include + +using namespace ::chip; + +namespace commands { + +RemoveDeviceCommand::RemoveDeviceCommand(NodeId nodeId) : mNodeId(nodeId) {} + +void RemoveDeviceCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) +{ + if (mNodeId != deviceId) + { + ChipLogProgress(NotSpecified, "An non-specified device: NodeId: " ChipLogFormatX64 " is removed.", + ChipLogValueX64(deviceId)); + return; + } + + if (err == CHIP_NO_ERROR) + { + // print to console + fprintf(stderr, "Successfully removed device: NodeId: " ChipLogFormatX64 "\n", ChipLogValueX64(mNodeId)); + } + else + { + ChipLogError(NotSpecified, "Failed to remove device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + CommandRegistry::Instance().ResetActiveCommand(); +} + +CHIP_ERROR RemoveDeviceCommand::RunCommand() +{ + if (admin::DeviceManager::Instance().IsCurrentBridgeDevice(mNodeId)) + { + // print to console + fprintf(stderr, "The specified node ID has been reserved by the Fabric Bridge.\n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + admin::PairingManager::Instance().SetPairingDelegate(this); + + ChipLogProgress(NotSpecified, "Running RemoveDeviceCommand with Node ID: %lu", mNodeId); + + return admin::DeviceManager::Instance().UnpairRemoteDevice(mNodeId); +} + +} // namespace commands diff --git a/examples/fabric-sync/shell/RemoveDeviceCommand.h b/examples/fabric-sync/shell/RemoveDeviceCommand.h new file mode 100644 index 00000000000000..cb394d66b3b4ff --- /dev/null +++ b/examples/fabric-sync/shell/RemoveDeviceCommand.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2024 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 + +namespace commands { + +class RemoveDeviceCommand : public Command, public admin::PairingDelegate +{ +public: + RemoveDeviceCommand(chip::NodeId nodeId); + void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; + CHIP_ERROR RunCommand() override; + +private: + chip::NodeId mNodeId = chip::kUndefinedNodeId; +}; + +} // namespace commands diff --git a/examples/fabric-sync/shell/ShellCommands.cpp b/examples/fabric-sync/shell/ShellCommands.cpp new file mode 100644 index 00000000000000..4923823481635a --- /dev/null +++ b/examples/fabric-sync/shell/ShellCommands.cpp @@ -0,0 +1,255 @@ +/* + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ShellCommands.h" +#include "AddBridgeCommand.h" +#include "AddDeviceCommand.h" +#include "RemoveBridgeCommand.h" +#include "RemoveDeviceCommand.h" +#include "SyncDeviceCommand.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace chip { +namespace Shell { + +static CHIP_ERROR PrintAllCommands() +{ + streamer_t * sout = streamer_get(); + streamer_printf(sout, " help Usage: app \r\n"); + streamer_printf(sout, + " add-bridge Pair remote fabric bridge to local fabric. Usage: app add-bridge node-id setup-pin-code " + "device-remote-ip device-remote-port\r\n"); + streamer_printf(sout, " remove-bridge Remove the remote fabric bridge from the local fabric. Usage: app remove-bridge\r\n"); + streamer_printf(sout, + " add-device Pair a device to local fabric. Usage: app add-device node-id setup-pin-code " + "device-remote-ip device-remote-port\r\n"); + streamer_printf(sout, " remove-device Remove a device from the local fabric. Usage: app remove-device node-id\r\n"); + streamer_printf(sout, " sync-device Sync a device from other ecosystem. Usage: app sync-device endpointid\r\n"); + streamer_printf(sout, "\r\n"); + + return CHIP_NO_ERROR; +} + +static CHIP_ERROR HandleAddBridgeCommand(int argc, char ** argv) +{ + if (argc != 5) + { + fprintf(stderr, + "Invalid arguments. Usage: app add-bridge \n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Check if there is already an active command + if (commands::CommandRegistry::Instance().IsCommandActive()) + { + fprintf(stderr, "Another command is currently active. Please wait until it completes.\n"); + return CHIP_ERROR_BUSY; + } + + // Parse arguments + chip::NodeId nodeId = static_cast(strtoull(argv[1], nullptr, 10)); + uint32_t setupPINCode = static_cast(strtoul(argv[2], nullptr, 10)); + const char * remoteAddr = argv[3]; + uint16_t remotePort = static_cast(strtoul(argv[4], nullptr, 10)); + + auto command = std::make_unique(nodeId, setupPINCode, remoteAddr, remotePort); + + CHIP_ERROR result = command->RunCommand(); + if (result == CHIP_NO_ERROR) + { + commands::CommandRegistry::Instance().SetActiveCommand(std::move(command)); + } + + return result; +} + +static CHIP_ERROR HandleRemoveBridgeCommand(int argc, char ** argv) +{ + if (argc != 1) + { + fprintf(stderr, "Invalid arguments. Usage: app remove-bridge\n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Check if there is already an active command + if (commands::CommandRegistry::Instance().IsCommandActive()) + { + fprintf(stderr, "Another command is currently active. Please wait until it completes.\n"); + return CHIP_ERROR_BUSY; + } + + auto command = std::make_unique(); + + CHIP_ERROR result = command->RunCommand(); + if (result == CHIP_NO_ERROR) + { + commands::CommandRegistry::Instance().SetActiveCommand(std::move(command)); + } + + return result; +} + +static CHIP_ERROR HandleAddDeviceCommand(int argc, char ** argv) +{ + if (argc != 5) + { + fprintf(stderr, + "Invalid arguments. Usage: app add-device \n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Check if there is already an active command + if (commands::CommandRegistry::Instance().IsCommandActive()) + { + fprintf(stderr, "Another command is currently active. Please wait until it completes.\n"); + return CHIP_ERROR_BUSY; + } + + // Parse arguments + chip::NodeId nodeId = static_cast(strtoull(argv[1], nullptr, 10)); + uint32_t payload = static_cast(strtoul(argv[2], nullptr, 10)); + const char * remoteAddr = argv[3]; + uint16_t remotePort = static_cast(strtoul(argv[4], nullptr, 10)); + + auto command = std::make_unique(nodeId, payload, remoteAddr, remotePort); + + CHIP_ERROR result = command->RunCommand(); + if (result == CHIP_NO_ERROR) + { + commands::CommandRegistry::Instance().SetActiveCommand(std::move(command)); + } + + return result; +} + +static CHIP_ERROR HandleRemoveDeviceCommand(int argc, char ** argv) +{ + if (argc != 2) + { + fprintf(stderr, "Invalid arguments. Usage: app remove-device \n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Check if there is already an active command + if (commands::CommandRegistry::Instance().IsCommandActive()) + { + fprintf(stderr, "Another command is currently active. Please wait until it completes.\n"); + return CHIP_ERROR_BUSY; + } + + // Parse arguments + chip::NodeId nodeId = static_cast(strtoull(argv[1], nullptr, 10)); + + auto command = std::make_unique(nodeId); + + CHIP_ERROR result = command->RunCommand(); + if (result == CHIP_NO_ERROR) + { + commands::CommandRegistry::Instance().SetActiveCommand(std::move(command)); + } + + return result; +} + +static CHIP_ERROR HandleSyncDeviceCommand(int argc, char ** argv) +{ + if (argc != 2) + { + fprintf(stderr, "Invalid arguments. Usage: app sync-device\n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Check if there is already an active command + if (commands::CommandRegistry::Instance().IsCommandActive()) + { + fprintf(stderr, "Another command is currently active. Please wait until it completes.\n"); + return CHIP_ERROR_BUSY; + } + + // Parse arguments + chip::EndpointId endpointId = static_cast(strtoul(argv[1], nullptr, 10)); + + auto command = std::make_unique(endpointId); + + CHIP_ERROR result = command->RunCommand(); + if (result == CHIP_NO_ERROR) + { + commands::CommandRegistry::Instance().SetActiveCommand(std::move(command)); + } + + return result; +} + +static CHIP_ERROR AppPlatformHandler(int argc, char ** argv) +{ + CHIP_ERROR error = CHIP_NO_ERROR; + + if (argc == 0 || strcmp(argv[0], "help") == 0) + { + return PrintAllCommands(); + } + else if (argc == 0 || strcmp(argv[0], "?") == 0) + { + return PrintAllCommands(); + } + else if (strcmp(argv[0], "add-bridge") == 0) + { + return HandleAddBridgeCommand(argc, argv); + } + else if (strcmp(argv[0], "remove-bridge") == 0) + { + return HandleRemoveBridgeCommand(argc, argv); + } + else if (strcmp(argv[0], "add-device") == 0) + { + return HandleAddDeviceCommand(argc, argv); + } + else if (strcmp(argv[0], "remove-device") == 0) + { + return HandleRemoveDeviceCommand(argc, argv); + } + else if (strcmp(argv[0], "sync-device") == 0) + { + return HandleSyncDeviceCommand(argc, argv); + } + else + { + return CHIP_ERROR_INVALID_ARGUMENT; + } + return error; +} + +void RegisterCommands() +{ + + static const shell_command_t sDeviceComand = { &AppPlatformHandler, "app", "App commands. Usage: app [command_name]" }; + + // Register the root `device` command with the top-level shell. + Engine::Root().RegisterCommands(&sDeviceComand, 1); +} + +} // namespace Shell +} // namespace chip diff --git a/examples/fabric-sync/shell/ShellCommands.h b/examples/fabric-sync/shell/ShellCommands.h new file mode 100644 index 00000000000000..b5bd5085fba3dc --- /dev/null +++ b/examples/fabric-sync/shell/ShellCommands.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2024 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 + +namespace chip { +namespace Shell { + +void RegisterCommands(); + +} // namespace Shell +} // namespace chip diff --git a/examples/fabric-sync/shell/SyncDeviceCommand.cpp b/examples/fabric-sync/shell/SyncDeviceCommand.cpp new file mode 100644 index 00000000000000..871c8d68feedb7 --- /dev/null +++ b/examples/fabric-sync/shell/SyncDeviceCommand.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2024 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 "SyncDeviceCommand.h" + +#include +#include +#include + +using namespace ::chip; + +namespace { + +// Constants +constexpr uint32_t kCommissionPrepareTimeMs = 500; + +} // namespace + +namespace commands { + +SyncDeviceCommand::SyncDeviceCommand(EndpointId remoteEndpointId) : mRemoteEndpointId(remoteEndpointId) {} + +void SyncDeviceCommand::OnCommissioningWindowOpened(NodeId deviceId, CHIP_ERROR err, SetupPayload payload) +{ + ChipLogProgress(NotSpecified, "FabricSyncDeviceCommand::OnCommissioningWindowOpened"); + + if (err == CHIP_NO_ERROR) + { + char payloadBuffer[admin::kMaxManualCodeLength + 1]; + MutableCharSpan manualCode(payloadBuffer); + CHIP_ERROR error = ManualSetupPayloadGenerator(payload).payloadDecimalStringRepresentation(manualCode); + if (error == CHIP_NO_ERROR) + { + NodeId nodeId = admin::DeviceManager::Instance().GetNextAvailableNodeId(); + + admin::PairingManager::Instance().SetPairingDelegate(this); + mAssignedNodeId = nodeId; + + usleep(kCommissionPrepareTimeMs * 1000); + + admin::DeviceManager::Instance().PairRemoteDevice(nodeId, payloadBuffer); + } + else + { + ChipLogError(NotSpecified, "Unable to generate manual code for setup payload: %" CHIP_ERROR_FORMAT, error.Format()); + } + } + else + { + ChipLogError(NotSpecified, + "Failed to open synced device (0x:" ChipLogFormatX64 ") commissioning window: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } +} + +void SyncDeviceCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) +{ + if (mAssignedNodeId != deviceId) + { + // Ignore if the deviceId does not match the mAssignedNodeId. + // This scenario should not occur because no other device should be commissioned during the fabric sync process. + return; + } + + if (err == CHIP_NO_ERROR) + { + admin::DeviceManager::Instance().AddSyncedDevice(admin::SyncedDevice(mAssignedNodeId, mRemoteEndpointId)); + } + else + { + ChipLogError(NotSpecified, "Failed to pair synced device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + CommandRegistry::Instance().ResetActiveCommand(); +} + +CHIP_ERROR SyncDeviceCommand::RunCommand() +{ + if (!admin::DeviceManager::Instance().IsFabricSyncReady()) + { + // print to console + Shell::streamer_t * sout = Shell::streamer_get(); + Shell::streamer_printf(sout, "Remote Fabric Bridge has already been configured.\n"); + + return CHIP_ERROR_INCORRECT_STATE; + } + + ChipLogProgress(NotSpecified, "Running SyncDeviceCommand with EndpointId: %u", mRemoteEndpointId); + + admin::PairingManager::Instance().SetOpenCommissioningWindowDelegate(this); + admin::DeviceManager::Instance().OpenRemoteDeviceCommissioningWindow(mRemoteEndpointId); + + return CHIP_NO_ERROR; +} + +} // namespace commands diff --git a/examples/fabric-sync/shell/SyncDeviceCommand.h b/examples/fabric-sync/shell/SyncDeviceCommand.h new file mode 100644 index 00000000000000..270f57d8893f03 --- /dev/null +++ b/examples/fabric-sync/shell/SyncDeviceCommand.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 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 + +namespace commands { + +class SyncDeviceCommand : public Command, public admin::CommissioningWindowDelegate, public admin::PairingDelegate +{ +public: + SyncDeviceCommand(chip::EndpointId remoteEndpointId); + void OnCommissioningWindowOpened(chip::NodeId deviceId, CHIP_ERROR status, chip::SetupPayload payload) override; + void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) override; + CHIP_ERROR RunCommand() override; + +private: + chip::EndpointId mRemoteEndpointId = chip::kInvalidEndpointId; + chip::NodeId mAssignedNodeId = chip::kUndefinedNodeId; +}; + +} // namespace commands diff --git a/examples/laundry-washer-app/nxp/rt/rt1060/include/config/CHIPProjectConfig.h b/examples/laundry-washer-app/nxp/rt/rt1060/include/config/CHIPProjectConfig.h index dd73c6c9eaaedd..61be0867102324 100644 --- a/examples/laundry-washer-app/nxp/rt/rt1060/include/config/CHIPProjectConfig.h +++ b/examples/laundry-washer-app/nxp/rt/rt1060/include/config/CHIPProjectConfig.h @@ -167,15 +167,6 @@ */ // #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 -/** - * CHIP_CONFIG_MAX_BINDINGS - * - * Maximum number of simultaneously active bindings per ChipExchangeManager - * 1 (Time Sync) + 2 (Two 1-way subscriptions) + 1 (Software Update) = 4 - * in the worst case. Keeping another 4 as buffer. - */ -#define CHIP_CONFIG_MAX_BINDINGS 6 - /** * CHIP_CONFIG_EVENT_LOGGING_WDM_OFFLOAD * diff --git a/examples/laundry-washer-app/nxp/rt/rt1170/include/config/CHIPProjectConfig.h b/examples/laundry-washer-app/nxp/rt/rt1170/include/config/CHIPProjectConfig.h index dd73c6c9eaaedd..61be0867102324 100644 --- a/examples/laundry-washer-app/nxp/rt/rt1170/include/config/CHIPProjectConfig.h +++ b/examples/laundry-washer-app/nxp/rt/rt1170/include/config/CHIPProjectConfig.h @@ -167,15 +167,6 @@ */ // #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 -/** - * CHIP_CONFIG_MAX_BINDINGS - * - * Maximum number of simultaneously active bindings per ChipExchangeManager - * 1 (Time Sync) + 2 (Two 1-way subscriptions) + 1 (Software Update) = 4 - * in the worst case. Keeping another 4 as buffer. - */ -#define CHIP_CONFIG_MAX_BINDINGS 6 - /** * CHIP_CONFIG_EVENT_LOGGING_WDM_OFFLOAD * diff --git a/examples/laundry-washer-app/nxp/rt/rw61x/include/config/CHIPProjectConfig.h b/examples/laundry-washer-app/nxp/rt/rw61x/include/config/CHIPProjectConfig.h index 2653e97705fe39..33a42909f464ea 100644 --- a/examples/laundry-washer-app/nxp/rt/rw61x/include/config/CHIPProjectConfig.h +++ b/examples/laundry-washer-app/nxp/rt/rw61x/include/config/CHIPProjectConfig.h @@ -168,15 +168,6 @@ */ // #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 -/** - * CHIP_CONFIG_MAX_BINDINGS - * - * Maximum number of simultaneously active bindings per ChipExchangeManager - * 1 (Time Sync) + 2 (Two 1-way subscriptions) + 1 (Software Update) = 4 - * in the worst case. Keeping another 4 as buffer. - */ -#define CHIP_CONFIG_MAX_BINDINGS 6 - /** * CHIP_CONFIG_EVENT_LOGGING_WDM_OFFLOAD * diff --git a/examples/light-switch-app/ameba/README.md b/examples/light-switch-app/ameba/README.md index a0d02751a830c1..ea9304fe7ca4a9 100644 --- a/examples/light-switch-app/ameba/README.md +++ b/examples/light-switch-app/ameba/README.md @@ -26,11 +26,11 @@ The CHIP demo application is supported on - Pull docker image: - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 - Setup build environment: diff --git a/examples/light-switch-app/esp32/main/CMakeLists.txt b/examples/light-switch-app/esp32/main/CMakeLists.txt index b4b6f5946eb2f9..92be83565a138e 100644 --- a/examples/light-switch-app/esp32/main/CMakeLists.txt +++ b/examples/light-switch-app/esp32/main/CMakeLists.txt @@ -30,6 +30,7 @@ idf_component_register(PRIV_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/shell_extension" "${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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/icd/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" diff --git a/examples/light-switch-app/genio/args.gni b/examples/light-switch-app/genio/args.gni index ddbfb9fa47f20d..b684adc4a6b792 100644 --- a/examples/light-switch-app/genio/args.gni +++ b/examples/light-switch-app/genio/args.gni @@ -18,8 +18,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = true diff --git a/examples/light-switch-app/genio/build_for_wifi_args.gni b/examples/light-switch-app/genio/build_for_wifi_args.gni index cb0ea7600a2dd5..3001e6648f4aa8 100644 --- a/examples/light-switch-app/genio/build_for_wifi_args.gni +++ b/examples/light-switch-app/genio/build_for_wifi_args.gni @@ -18,5 +18,5 @@ mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false import("${chip_root}/src/platform/MT793X/wifi_args.gni") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/light-switch-app/qpg/args.gni b/examples/light-switch-app/qpg/args.gni index 9a69cd16959f6d..a6b8b77b72902c 100644 --- a/examples/light-switch-app/qpg/args.gni +++ b/examples/light-switch-app/qpg/args.gni @@ -32,5 +32,5 @@ chip_stack_lock_tracking = "none" matter_device_vid = "0xFFF1" matter_device_pid = "0x8004" -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/light-switch-app/silabs/README.md b/examples/light-switch-app/silabs/README.md index 898f8e8f299112..75411dd3055e72 100644 --- a/examples/light-switch-app/silabs/README.md +++ b/examples/light-switch-app/silabs/README.md @@ -263,6 +263,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/light-switch-app/silabs/build_for_wifi_args.gni b/examples/light-switch-app/silabs/build_for_wifi_args.gni index ac70e16a8b484f..ed368c024847b7 100644 --- a/examples/light-switch-app/silabs/build_for_wifi_args.gni +++ b/examples/light-switch-app/silabs/build_for_wifi_args.gni @@ -16,7 +16,7 @@ import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") chip_enable_ota_requestor = true app_data_model = "${chip_root}/examples/light-switch-app/light-switch-common" diff --git a/examples/lighting-app-data-mode-no-unique-id/linux/with_pw_rpc.gni b/examples/lighting-app-data-mode-no-unique-id/linux/with_pw_rpc.gni index 0f1ab1ea89c121..a67251431a018c 100644 --- a/examples/lighting-app-data-mode-no-unique-id/linux/with_pw_rpc.gni +++ b/examples/lighting-app-data-mode-no-unique-id/linux/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -39,4 +39,3 @@ pw_build_LINK_DEPS = [ ] chip_enable_pw_rpc = true -chip_use_pw_logging = true diff --git a/examples/lighting-app/ameba/README.md b/examples/lighting-app/ameba/README.md index 7527d02f725099..e91aec075b50c0 100644 --- a/examples/lighting-app/ameba/README.md +++ b/examples/lighting-app/ameba/README.md @@ -23,11 +23,11 @@ The CHIP demo application is supported on - Pull docker image: - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 - Setup build environment: diff --git a/examples/lighting-app/bouffalolab/bl602/args.gni b/examples/lighting-app/bouffalolab/bl602/args.gni index 0fcb5aac2edc9b..491e87ab3fb419 100644 --- a/examples/lighting-app/bouffalolab/bl602/args.gni +++ b/examples/lighting-app/bouffalolab/bl602/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/src/platform/bouffalolab/BL602/args.gni") bl_iot_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" chip_detail_logging = false diff --git a/examples/lighting-app/bouffalolab/bl702/args.gni b/examples/lighting-app/bouffalolab/bl702/args.gni index e06c706903b935..4e999b386d0d41 100644 --- a/examples/lighting-app/bouffalolab/bl702/args.gni +++ b/examples/lighting-app/bouffalolab/bl702/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/src/platform/bouffalolab/BL702/args.gni") bl_iot_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" chip_detail_logging = false diff --git a/examples/lighting-app/bouffalolab/bl702l/args.gni b/examples/lighting-app/bouffalolab/bl702l/args.gni index 3120af1cce60f6..44589ed15f5d5f 100644 --- a/examples/lighting-app/bouffalolab/bl702l/args.gni +++ b/examples/lighting-app/bouffalolab/bl702l/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/src/platform/bouffalolab/BL702L/args.gni") bl_iot_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" chip_detail_logging = false diff --git a/examples/lighting-app/esp32/main/CMakeLists.txt b/examples/lighting-app/esp32/main/CMakeLists.txt index d3dc3421cc105f..1ad5bc1aa37c9e 100644 --- a/examples/lighting-app/esp32/main/CMakeLists.txt +++ b/examples/lighting-app/esp32/main/CMakeLists.txt @@ -34,6 +34,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/shell_extension" "${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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/administrator-commissioning-server" diff --git a/examples/lighting-app/esp32/sdkconfig.defaults.esp32p4 b/examples/lighting-app/esp32/sdkconfig.defaults.esp32p4 new file mode 100644 index 00000000000000..3211b306b2be99 --- /dev/null +++ b/examples/lighting-app/esp32/sdkconfig.defaults.esp32p4 @@ -0,0 +1,37 @@ +CONFIG_IDF_TARGET="esp32p4" + +# Flash size and partition +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" + +# Enable BLE Host but use remote controller +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y +CONFIG_BT_NIMBLE_TRANSPORT_UART=n +CONFIG_ESP_ENABLE_BT=y + +# Increase main task stack size +CONFIG_ESP_MAIN_TASK_STACK_SIZE=4096 + +# Disable Wi-Fi Soft AP +CONFIG_ESP_WIFI_SOFTAP_SUPPORT=n + +# LwIP +CONFIG_LWIP_IPV6_AUTOCONFIG=y +CONFIG_LWIP_IPV6_NUM_ADDRESSES=6 + +# mbedtls +CONFIG_MBEDTLS_HKDF_C=y + +# Matter shell +CONFIG_ENABLE_CHIP_SHELL=y + +# OTA requestor +CONFIG_ENABLE_OTA_REQUESTOR=y + +# Do not deinit BLE after commissioning +CONFIG_USE_BLE_ONLY_FOR_COMMISSIONING=n + +# ESP32-P4 Function EV Board use ESP32C6 as slave device +CONFIG_SLAVE_IDF_TARGET_ESP32C6=y diff --git a/examples/lighting-app/genio/args.gni b/examples/lighting-app/genio/args.gni index e22869653722a7..cbdadf266953f2 100644 --- a/examples/lighting-app/genio/args.gni +++ b/examples/lighting-app/genio/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = true diff --git a/examples/lighting-app/genio/build_for_wifi_args.gni b/examples/lighting-app/genio/build_for_wifi_args.gni index cb0ea7600a2dd5..3001e6648f4aa8 100644 --- a/examples/lighting-app/genio/build_for_wifi_args.gni +++ b/examples/lighting-app/genio/build_for_wifi_args.gni @@ -18,5 +18,5 @@ mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false import("${chip_root}/src/platform/MT793X/wifi_args.gni") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/lighting-app/linux/with_pw_rpc.gni b/examples/lighting-app/linux/with_pw_rpc.gni index 0f1ab1ea89c121..a67251431a018c 100644 --- a/examples/lighting-app/linux/with_pw_rpc.gni +++ b/examples/lighting-app/linux/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -39,4 +39,3 @@ pw_build_LINK_DEPS = [ ] chip_enable_pw_rpc = true -chip_use_pw_logging = true diff --git a/examples/lighting-app/nrfconnect/CMakeLists.txt b/examples/lighting-app/nrfconnect/CMakeLists.txt index 59bf2f26bed466..dd5b65afe632df 100644 --- a/examples/lighting-app/nrfconnect/CMakeLists.txt +++ b/examples/lighting-app/nrfconnect/CMakeLists.txt @@ -51,6 +51,7 @@ target_sources(app PRIVATE main/AppTask.cpp main/main.cpp main/ZclCallbacks.cpp + ${CHIP_ROOT}/src/app/util/persistence/DeferredAttributePersistenceProvider.cpp ${NRFCONNECT_COMMON}/util/LEDWidget.cpp ${NRFCONNECT_COMMON}/util/PWMDevice.cpp) diff --git a/examples/lighting-app/nrfconnect/main/AppTask.cpp b/examples/lighting-app/nrfconnect/main/AppTask.cpp index 88964d9aa1d3c8..014849780caf06 100644 --- a/examples/lighting-app/nrfconnect/main/AppTask.cpp +++ b/examples/lighting-app/nrfconnect/main/AppTask.cpp @@ -26,13 +26,13 @@ #include #include -#include #include #include #include #include #include #include +#include #include #include #include diff --git a/examples/lighting-app/qpg/BUILD.gn b/examples/lighting-app/qpg/BUILD.gn index 886c8aa313d097..b4a2998f02dc7f 100644 --- a/examples/lighting-app/qpg/BUILD.gn +++ b/examples/lighting-app/qpg/BUILD.gn @@ -66,6 +66,7 @@ qpg_executable("lighting_app") { "${chip_root}/examples/lighting-app/lighting-common:color-format", "${chip_root}/examples/lighting-app/qpg/zap/", "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/app/util/persistence:deferred", "${chip_root}/src/lib", "${chip_root}/src/platform/logging:default", "${chip_root}/src/setup_payload", diff --git a/examples/lighting-app/qpg/args.gni b/examples/lighting-app/qpg/args.gni index ea22dfd187fbb2..37ca029954781a 100644 --- a/examples/lighting-app/qpg/args.gni +++ b/examples/lighting-app/qpg/args.gni @@ -30,5 +30,5 @@ chip_stack_lock_tracking = "none" matter_device_vid = "0xFFF1" matter_device_pid = "0x8005" -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/lighting-app/qpg/src/AppTask.cpp b/examples/lighting-app/qpg/src/AppTask.cpp index 90f2e30ecb03c5..0c09e97a6a5681 100644 --- a/examples/lighting-app/qpg/src/AppTask.cpp +++ b/examples/lighting-app/qpg/src/AppTask.cpp @@ -43,7 +43,7 @@ #include #include -#include +#include #include #include diff --git a/examples/lighting-app/silabs/README.md b/examples/lighting-app/silabs/README.md index 7052d4f71221c3..b783a6c328fac1 100644 --- a/examples/lighting-app/silabs/README.md +++ b/examples/lighting-app/silabs/README.md @@ -245,6 +245,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/lighting-app/silabs/build_for_wifi_args.gni b/examples/lighting-app/silabs/build_for_wifi_args.gni index 7e33551c30a97c..f8cc0089c8d416 100644 --- a/examples/lighting-app/silabs/build_for_wifi_args.gni +++ b/examples/lighting-app/silabs/build_for_wifi_args.gni @@ -16,7 +16,7 @@ import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") # Not needed for the Lighting-app chip_enable_read_client = false diff --git a/examples/lighting-app/silabs/data_model/lighting-thread-app.matter b/examples/lighting-app/silabs/data_model/lighting-thread-app.matter index 49684770a3bcaa..9fb02976f031d5 100644 --- a/examples/lighting-app/silabs/data_model/lighting-thread-app.matter +++ b/examples/lighting-app/silabs/data_model/lighting-thread-app.matter @@ -2672,7 +2672,7 @@ endpoint 1 { ram attribute colorCapabilities default = 0x1F; ram attribute colorTempPhysicalMinMireds default = 0x009A; ram attribute colorTempPhysicalMaxMireds default = 0x01C6; - ram attribute coupleColorTempToLevelMinMireds; + ram attribute coupleColorTempToLevelMinMireds default = 0x009A; persist attribute startUpColorTemperatureMireds default = 0x00FA; callback attribute generatedCommandList; callback attribute acceptedCommandList; diff --git a/examples/lighting-app/silabs/data_model/lighting-thread-app.zap b/examples/lighting-app/silabs/data_model/lighting-thread-app.zap index 62cc5c49eb9ac3..6e7931fbcf0f68 100644 --- a/examples/lighting-app/silabs/data_model/lighting-thread-app.zap +++ b/examples/lighting-app/silabs/data_model/lighting-thread-app.zap @@ -5022,7 +5022,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "0x009A", "reportable": 1, "minInterval": 0, "maxInterval": 65344, diff --git a/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter b/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter index 003a38e52c0214..1619fc9622caf4 100644 --- a/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter +++ b/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter @@ -2964,7 +2964,7 @@ endpoint 1 { ram attribute colorCapabilities default = 0x1F; ram attribute colorTempPhysicalMinMireds default = 0x009A; ram attribute colorTempPhysicalMaxMireds default = 0x01C6; - ram attribute coupleColorTempToLevelMinMireds; + ram attribute coupleColorTempToLevelMinMireds default = 0x009A; persist attribute startUpColorTemperatureMireds default = 0x00FA; ram attribute featureMap default = 0x1F; ram attribute clusterRevision default = 7; diff --git a/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap b/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap index 94397579a0a7d6..a0b64b71934eea 100644 --- a/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap +++ b/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap @@ -4797,7 +4797,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "0x009A", "reportable": 1, "minInterval": 0, "maxInterval": 65344, diff --git a/examples/lighting-app/telink/prj.conf b/examples/lighting-app/telink/prj.conf index 39eb720b20e2b9..9c7bab3e5f98f7 100644 --- a/examples/lighting-app/telink/prj.conf +++ b/examples/lighting-app/telink/prj.conf @@ -31,6 +31,7 @@ CONFIG_BT_DEVICE_NAME="TelinkLight" # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=1 +CONFIG_TELINK_OTA_BUTTON_TEST=n # Disable CHIP shell support CONFIG_CHIP_LIB_SHELL=n diff --git a/examples/lighting-app/tizen/README.md b/examples/lighting-app/tizen/README.md index 28e0d9b2c0b22b..d1b2fe474e9220 100644 --- a/examples/lighting-app/tizen/README.md +++ b/examples/lighting-app/tizen/README.md @@ -13,7 +13,7 @@ Generating tizen-arm-light ```sh gn gen --check \ --fail-on-unused-args \ - --export-compile-commands \ + --add-export-compile-commands=* \ --root=$PW_PROJECT_ROOT/examples/lighting-app/tizen \ "--args=target_os=\"tizen\" target_cpu=\"arm\" tizen_sdk_root=\"$TIZEN_SDK_ROOT\" tizen_sdk_sysroot=\"$TIZEN_SDK_SYSROOT\"" \ $PW_PROJECT_ROOT/out/tizen-arm-light diff --git a/examples/lighting-app/tizen/src/DBusInterface.cpp b/examples/lighting-app/tizen/src/DBusInterface.cpp index 5484c7daff3793..4a2aa18122c39c 100644 --- a/examples/lighting-app/tizen/src/DBusInterface.cpp +++ b/examples/lighting-app/tizen/src/DBusInterface.cpp @@ -203,7 +203,8 @@ gboolean DBusInterface::OnColorTemperatureChanged(LightAppColorControl * colorCo data.colorTemperatureMireds = light_app_color_control_get_color_temperature_mireds(colorControl); chip::DeviceLayer::StackLock lock; - ColorControlServer::Instance().moveToColorTempCommand(&handler, path, data); + auto status = ColorControlServer::Instance().moveToColorTempCommand(self->mEndpointId, data); + handler.AddStatus(path, status); return G_DBUS_METHOD_INVOCATION_HANDLED; } diff --git a/examples/lit-icd-app/esp32/main/CMakeLists.txt b/examples/lit-icd-app/esp32/main/CMakeLists.txt index 5f2850feff98b6..4d8fe2ab4bb163 100644 --- a/examples/lit-icd-app/esp32/main/CMakeLists.txt +++ b/examples/lit-icd-app/esp32/main/CMakeLists.txt @@ -29,6 +29,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/administrator-commissioning-server" diff --git a/examples/lit-icd-app/silabs/README.md b/examples/lit-icd-app/silabs/README.md index 4d1dee045c2e40..1b94dc5b902b73 100644 --- a/examples/lit-icd-app/silabs/README.md +++ b/examples/lit-icd-app/silabs/README.md @@ -250,6 +250,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/lit-icd-app/silabs/build_for_wifi_args.gni b/examples/lit-icd-app/silabs/build_for_wifi_args.gni index c8048dc71e3b4b..57843c9b5408eb 100644 --- a/examples/lit-icd-app/silabs/build_for_wifi_args.gni +++ b/examples/lit-icd-app/silabs/build_for_wifi_args.gni @@ -18,7 +18,7 @@ import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") chip_enable_ota_requestor = true app_data_model = "${chip_root}/examples/lit-icd-app/lit-icd-common" diff --git a/examples/lock-app/esp32/main/CMakeLists.txt b/examples/lock-app/esp32/main/CMakeLists.txt index 5c5f46abdd1860..028a92ae8dbd27 100644 --- a/examples/lock-app/esp32/main/CMakeLists.txt +++ b/examples/lock-app/esp32/main/CMakeLists.txt @@ -49,6 +49,7 @@ idf_component_register(INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/icd/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" @@ -162,6 +163,7 @@ idf_component_register(PRIV_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/common" "${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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/icd/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" diff --git a/examples/lock-app/genio/args.gni b/examples/lock-app/genio/args.gni index ddbfb9fa47f20d..b684adc4a6b792 100644 --- a/examples/lock-app/genio/args.gni +++ b/examples/lock-app/genio/args.gni @@ -18,8 +18,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = true diff --git a/examples/lock-app/genio/build_for_wifi_args.gni b/examples/lock-app/genio/build_for_wifi_args.gni index cb0ea7600a2dd5..3001e6648f4aa8 100644 --- a/examples/lock-app/genio/build_for_wifi_args.gni +++ b/examples/lock-app/genio/build_for_wifi_args.gni @@ -18,5 +18,5 @@ mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false import("${chip_root}/src/platform/MT793X/wifi_args.gni") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/lock-app/qpg/args.gni b/examples/lock-app/qpg/args.gni index d5dcdfe217c635..562005806d5059 100644 --- a/examples/lock-app/qpg/args.gni +++ b/examples/lock-app/qpg/args.gni @@ -31,5 +31,5 @@ chip_stack_lock_tracking = "none" matter_device_vid = "0xFFF1" matter_device_pid = "0x8006" -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/lock-app/silabs/README.md b/examples/lock-app/silabs/README.md index 7b4f7fdbdfaddf..0688f1ce70e93c 100644 --- a/examples/lock-app/silabs/README.md +++ b/examples/lock-app/silabs/README.md @@ -277,6 +277,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/lock-app/silabs/build_for_wifi_args.gni b/examples/lock-app/silabs/build_for_wifi_args.gni index cbc84b30bbe627..bb6da0b53563f5 100644 --- a/examples/lock-app/silabs/build_for_wifi_args.gni +++ b/examples/lock-app/silabs/build_for_wifi_args.gni @@ -16,7 +16,7 @@ import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") chip_enable_ota_requestor = true app_data_model = "${chip_root}/examples/lock-app/silabs/data_model:silabs-lock" diff --git a/examples/lock-app/silabs/src/LockManager.cpp b/examples/lock-app/silabs/src/LockManager.cpp index 1a4fd934631707..6f5aba9147f6b2 100644 --- a/examples/lock-app/silabs/src/LockManager.cpp +++ b/examples/lock-app/silabs/src/LockManager.cpp @@ -264,9 +264,11 @@ void LockManager::UnlockAfterUnlatch() bool succes = false; if (mUnlatchContext.mEndpointId != kInvalidEndpointId) { - succes = setLockState( - mUnlatchContext.mEndpointId, mUnlatchContext.mFabricIdx, mUnlatchContext.mNodeId, DlLockState::kUnlocked, - MakeOptional(chip::ByteSpan(mUnlatchContext.mPinBuffer, mUnlatchContext.mPinLength)), mUnlatchContext.mErr); + Optional pin = (mUnlatchContext.mPinLength) + ? MakeOptional(chip::ByteSpan(mUnlatchContext.mPinBuffer, mUnlatchContext.mPinLength)) + : Optional::Missing(); + succes = setLockState(mUnlatchContext.mEndpointId, mUnlatchContext.mFabricIdx, mUnlatchContext.mNodeId, + DlLockState::kUnlocked, pin, mUnlatchContext.mErr); } if (!succes) diff --git a/examples/ota-provider-app/esp32/main/CMakeLists.txt b/examples/ota-provider-app/esp32/main/CMakeLists.txt index 41acd9e9316e00..d651ac77065803 100644 --- a/examples/ota-provider-app/esp32/main/CMakeLists.txt +++ b/examples/ota-provider-app/esp32/main/CMakeLists.txt @@ -26,6 +26,7 @@ idf_component_register(PRIV_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/administrator-commissioning-server" diff --git a/examples/ota-requestor-app/ameba/README.md b/examples/ota-requestor-app/ameba/README.md index 1af661767dfd77..e748f41dc9b090 100644 --- a/examples/ota-requestor-app/ameba/README.md +++ b/examples/ota-requestor-app/ameba/README.md @@ -6,11 +6,11 @@ A prototype application that demonstrates OTA Requestor capabilities. - Pull docker image: - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 - Setup build environment: diff --git a/examples/ota-requestor-app/esp32/main/CMakeLists.txt b/examples/ota-requestor-app/esp32/main/CMakeLists.txt index fbda70f2cec48f..2688fea4977eab 100644 --- a/examples/ota-requestor-app/esp32/main/CMakeLists.txt +++ b/examples/ota-requestor-app/esp32/main/CMakeLists.txt @@ -31,6 +31,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/administrator-commissioning-server" diff --git a/examples/ota-requestor-app/genio/args.gni b/examples/ota-requestor-app/genio/args.gni index 7a6cc1c74c6394..89889de70bd9ea 100644 --- a/examples/ota-requestor-app/genio/args.gni +++ b/examples/ota-requestor-app/genio/args.gni @@ -18,8 +18,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = true diff --git a/examples/ota-requestor-app/genio/build_for_wifi_args.gni b/examples/ota-requestor-app/genio/build_for_wifi_args.gni index cb0ea7600a2dd5..3001e6648f4aa8 100644 --- a/examples/ota-requestor-app/genio/build_for_wifi_args.gni +++ b/examples/ota-requestor-app/genio/build_for_wifi_args.gni @@ -18,5 +18,5 @@ mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false import("${chip_root}/src/platform/MT793X/wifi_args.gni") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/pigweed-app/ameba/README.md b/examples/pigweed-app/ameba/README.md index 647809108e65ac..136a37a14caf41 100644 --- a/examples/pigweed-app/ameba/README.md +++ b/examples/pigweed-app/ameba/README.md @@ -31,11 +31,11 @@ following features are available: - Pull docker image: - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 - Setup build environment: diff --git a/examples/platform/esp32/common/Esp32AppServer.cpp b/examples/platform/esp32/common/Esp32AppServer.cpp index 37dd7f4fe4adcf..8740f39cdbc080 100644 --- a/examples/platform/esp32/common/Esp32AppServer.cpp +++ b/examples/platform/esp32/common/Esp32AppServer.cpp @@ -40,18 +40,6 @@ #include #endif -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#if CONFIG_BT_ENABLED -#include "esp_bt.h" -#if CONFIG_BT_NIMBLE_ENABLED -#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) -#include "esp_nimble_hci.h" -#endif // ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) -#include "nimble/nimble_port.h" -#endif // CONFIG_BT_NIMBLE_ENABLED -#endif // CONFIG_BT_ENABLED -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - #ifdef CONFIG_ENABLE_CHIP_SHELL #include #endif diff --git a/examples/platform/linux/AppMain.cpp b/examples/platform/linux/AppMain.cpp index a2e341efbe7a0f..e3b68e319e634e 100644 --- a/examples/platform/linux/AppMain.cpp +++ b/examples/platform/linux/AppMain.cpp @@ -96,6 +96,9 @@ #if CHIP_DEVICE_CONFIG_ENABLE_DEVICE_ENERGY_MANAGEMENT_TRIGGER #include #endif +#if CHIP_CONFIG_ENABLE_ICD_SERVER +#include +#endif #include #include @@ -298,6 +301,19 @@ void EventHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg) } } +void StopMainEventLoop() +{ + if (gMainLoopImplementation != nullptr) + { + gMainLoopImplementation->SignalSafeStopMainLoop(); + } + else + { + Server::GetInstance().GenerateShutDownEvent(); + PlatformMgr().ScheduleWork([](intptr_t) { PlatformMgr().StopEventLoopTask(); }); + } +} + void Cleanup() { #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED @@ -314,17 +330,9 @@ void Cleanup() // We should stop using signals for those faults, and move to a different notification // means, like a pipe. (see issue #19114) #if !defined(ENABLE_CHIP_SHELL) -void StopSignalHandler(int signal) +void StopSignalHandler(int /* signal */) { - if (gMainLoopImplementation != nullptr) - { - gMainLoopImplementation->SignalSafeStopMainLoop(); - } - else - { - Server::GetInstance().GenerateShutDownEvent(); - PlatformMgr().ScheduleWork([](intptr_t) { PlatformMgr().StopEventLoopTask(); }); - } + StopMainEventLoop(); } #endif // !defined(ENABLE_CHIP_SHELL) @@ -527,7 +535,10 @@ void ChipLinuxAppMainLoop(AppMainLoopImplementation * impl) #if defined(ENABLE_CHIP_SHELL) Engine::Root().Init(); - std::thread shellThread([]() { Engine::Root().RunMainLoop(); }); + std::thread shellThread([]() { + Engine::Root().RunMainLoop(); + StopMainEventLoop(); + }); Shell::RegisterCommissioneeCommands(); #endif initParams.operationalServicePort = CHIP_PORT; @@ -593,6 +604,9 @@ void ChipLinuxAppMainLoop(AppMainLoopImplementation * impl) static DeviceEnergyManagementTestEventTriggerHandler sDeviceEnergyManagementTestEventTriggerHandler; sTestEventTriggerDelegate.AddHandler(&sDeviceEnergyManagementTestEventTriggerHandler); #endif +#if CHIP_CONFIG_ENABLE_ICD_SERVER + sTestEventTriggerDelegate.AddHandler(&Server::GetInstance().GetICDManager()); +#endif initParams.testEventTriggerDelegate = &sTestEventTriggerDelegate; @@ -686,14 +700,15 @@ void ChipLinuxAppMainLoop(AppMainLoopImplementation * impl) Server::GetInstance().Shutdown(); #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE + // Commissioner shutdown call shuts down entire stack, including the platform manager. ShutdownCommissioner(); +#else + DeviceLayer::PlatformMgr().Shutdown(); #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE #if ENABLE_TRACING tracing_setup.StopTracing(); #endif - DeviceLayer::PlatformMgr().Shutdown(); - Cleanup(); } diff --git a/examples/platform/linux/BUILD.gn b/examples/platform/linux/BUILD.gn index 336534aae65043..30583ce7d0e399 100644 --- a/examples/platform/linux/BUILD.gn +++ b/examples/platform/linux/BUILD.gn @@ -15,6 +15,7 @@ import("//build_overrides/chip.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/common_flags.gni") +import("${chip_root}/src/app/icd/icd.gni") import("${chip_root}/src/lib/core/core.gni") import("${chip_root}/src/lib/lib.gni") import("${chip_root}/src/tracing/tracing_args.gni") @@ -133,6 +134,9 @@ source_set("app-main") { "${chip_root}/src/tracing", ] } + if (chip_enable_icd_server) { + deps += [ "${chip_root}/src/app/icd/server:manager" ] + } defines += [ "CHIP_DEVICE_CONFIG_ENABLE_SMOKE_CO_TRIGGER=${chip_enable_smoke_co_trigger}", diff --git a/examples/platform/linux/NamedPipeCommands.cpp b/examples/platform/linux/NamedPipeCommands.cpp index c77165e9000cf8..e07ea242f0faae 100644 --- a/examples/platform/linux/NamedPipeCommands.cpp +++ b/examples/platform/linux/NamedPipeCommands.cpp @@ -81,12 +81,15 @@ void * NamedPipeCommands::EventCommandListenerTask(void * arg) break; } - ssize_t readBytes = read(fd, readbuf, kChipEventCmdBufSize); - readbuf[readBytes - 1] = '\0'; - ChipLogProgress(NotSpecified, "Received payload: \"%s\"", readbuf); + ssize_t readBytes = read(fd, readbuf, kChipEventCmdBufSize); + if (readBytes > 0) + { + readbuf[readBytes - 1] = '\0'; + ChipLogProgress(NotSpecified, "Received payload: \"%s\"", readbuf); - // Process the received command request from event fifo - self->mDelegate->OnEventCommandReceived(readbuf); + // Process the received command request from event fifo + self->mDelegate->OnEventCommandReceived(readbuf); + } close(fd); } diff --git a/examples/platform/linux/system_rpc_server.cc b/examples/platform/linux/system_rpc_server.cc index 6323ad597d0cfe..b87a1c5d50bcc0 100644 --- a/examples/platform/linux/system_rpc_server.cc +++ b/examples/platform/linux/system_rpc_server.cc @@ -56,11 +56,6 @@ void set_socket_port(uint16_t new_socket_port) void Init() { - log_basic::SetOutput([](std::string_view log) { - std::fprintf(stderr, "%.*s\n", static_cast(log.size()), log.data()); - hdlc::WriteUIFrame(1, as_bytes(span(log)), socket_stream).IgnoreError(); // TODO(pwbug/387): Handle Status properly - }); - PW_LOG_INFO("Starting pw_rpc server on port %d", socket_port); PW_CHECK_OK(server_socket.Listen(socket_port)); auto accept_result = server_socket.Accept(); @@ -92,9 +87,18 @@ Status Start() // remote to connect. socket_stream.Close(); server_socket.Close(); - PW_CHECK_OK(server_socket.Listen(socket_port)); + Status status = server_socket.Listen(socket_port); + if (!status.ok()) + { + PW_LOG_ERROR("Listen failed. Exiting RPC Server loop"); + return status; + } auto accept_result = server_socket.Accept(); - PW_CHECK_OK(accept_result.status()); + if (!accept_result.status().ok()) + { + PW_LOG_ERROR("Accept failed. Exiting RPC Server loop"); + return accept_result.status(); + } socket_stream = *std::move(accept_result); } continue; diff --git a/examples/platform/nxp/common/app_task/include/AppTaskBase.h b/examples/platform/nxp/common/app_task/include/AppTaskBase.h index ab29af27c29561..2debabf28d305b 100644 --- a/examples/platform/nxp/common/app_task/include/AppTaskBase.h +++ b/examples/platform/nxp/common/app_task/include/AppTaskBase.h @@ -102,7 +102,7 @@ class AppTaskBase * This function can be overridden in order to implement a specific disallow mechanism. * */ - virtual void AppMatter_DisallowDeviceToSleep(void) {} + virtual void AppMatter_DisallowDeviceToSleep(void); /** * \brief Allow entering low power mode. @@ -110,7 +110,7 @@ class AppTaskBase * This function can be overridden in order to implement a specific allow mechanism. * */ - virtual void AppMatter_AllowDeviceToSleep(void) {} + virtual void AppMatter_AllowDeviceToSleep(void); /** * \brief Print onboarding information. diff --git a/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp b/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp index 2646ffca4ef26d..81907d21634318 100644 --- a/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp +++ b/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp @@ -75,6 +75,7 @@ #if CONFIG_LOW_POWER #include "LowPower.h" +#include "PWR_Interface.h" #endif #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR @@ -431,6 +432,20 @@ void chip::NXP::App::AppTaskBase::FactoryResetHandler(void) chip::Server::GetInstance().ScheduleFactoryReset(); } +void chip::NXP::App::AppTaskBase::AppMatter_DisallowDeviceToSleep(void) +{ +#if CONFIG_LOW_POWER + PWR_DisallowDeviceToSleep(); +#endif +} + +void chip::NXP::App::AppTaskBase::AppMatter_AllowDeviceToSleep(void) +{ +#if CONFIG_LOW_POWER + PWR_AllowDeviceToSleep(); +#endif +} + void chip::NXP::App::AppTaskBase::PrintOnboardingInfo() { #if CONFIG_NETWORK_LAYER_BLE diff --git a/examples/platform/nxp/mcxw71_k32w1/app/support/BUILD.gn b/examples/platform/nxp/mcxw71_k32w1/app/support/BUILD.gn index d49e9e7638c817..1034d91febf465 100644 --- a/examples/platform/nxp/mcxw71_k32w1/app/support/BUILD.gn +++ b/examples/platform/nxp/mcxw71_k32w1/app/support/BUILD.gn @@ -42,12 +42,14 @@ config("support_config") { source_set("freertos_memory_utils") { sources = [ - "FreeRtosHooks.c", - "FreeRtosHooks.h", + "FreeRtosHooks.cpp", "Memconfig.cpp", ] - deps = [ "${chip_root}/src/lib/support" ] + deps = [ + "${chip_root}/src/lib/support", + "${chip_root}/src/platform:platform_config_header", + ] cflags = [ "-Wconversion" ] @@ -57,5 +59,8 @@ source_set("freertos_memory_utils") { defines = [ "CHIP_PLAT_NVM_SUPPORT=3" ] } - public_configs = [ ":support_config" ] + public_configs = [ + ":support_config", + "${chip_root}/src:includes", + ] } diff --git a/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.c b/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.cpp similarity index 95% rename from examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.c rename to examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.cpp index bc5acf2e88401b..193b262231499d 100644 --- a/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.c +++ b/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.cpp @@ -27,6 +27,9 @@ #include #include +/* Include CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR */ +#include + #if (CHIP_PLAT_NVM_SUPPORT == 1) #include "NVM_Interface.h" #elif (CHIP_PLAT_NVM_SUPPORT == 3) @@ -55,6 +58,8 @@ #define APP_DBG_LOG(...) #endif +extern "C" { + static inline void mutex_init(mbedtls_threading_mutex_t * p_mutex) { assert(p_mutex != NULL); @@ -73,7 +78,7 @@ static inline int mutex_lock(mbedtls_threading_mutex_t * p_mutex) { assert(p_mutex != NULL); assert(*p_mutex != NULL); - return xSemaphoreTake(*p_mutex, portMAX_DELAY) != pdTRUE; + return xSemaphoreTake((SemaphoreHandle_t) (*p_mutex), portMAX_DELAY) != pdTRUE; } static inline int mutex_unlock(mbedtls_threading_mutex_t * p_mutex) @@ -153,3 +158,5 @@ void vApplicationIdleHook(void) OTAIdleActivities(); #endif } + +} // extern "C" diff --git a/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.h b/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.h index a27f72d498f81d..963b38973dd0f0 100644 --- a/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.h +++ b/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.h @@ -20,17 +20,15 @@ typedef void * mbedtls_threading_mutex_t; -extern void mbedtls_threading_set_alt(void (*mutex_init)(mbedtls_threading_mutex_t *), - void (*mutex_free)(mbedtls_threading_mutex_t *), - int (*mutex_lock)(mbedtls_threading_mutex_t *), - int (*mutex_unlock)(mbedtls_threading_mutex_t *)); - -extern void mbedtls_threading_free_alt(void); - #ifdef __cplusplus extern "C" { #endif +void mbedtls_threading_set_alt(void (*mutex_init)(mbedtls_threading_mutex_t *), void (*mutex_free)(mbedtls_threading_mutex_t *), + int (*mutex_lock)(mbedtls_threading_mutex_t *), int (*mutex_unlock)(mbedtls_threading_mutex_t *)); + +void mbedtls_threading_free_alt(void); + /**@brief Function for initializing alternative MbedTLS mutexes to enable the usage of the FreeRTOS implementation. */ void freertos_mbedtls_mutex_init(void); diff --git a/examples/platform/silabs/BaseApplication.cpp b/examples/platform/silabs/BaseApplication.cpp index bfa382305cf951..62c29569df435c 100644 --- a/examples/platform/silabs/BaseApplication.cpp +++ b/examples/platform/silabs/BaseApplication.cpp @@ -64,9 +64,9 @@ #include #ifdef SL_WIFI -#include "wfx_host_events.h" #include #include +#include #endif // SL_WIFI #ifdef DIC_ENABLE diff --git a/examples/platform/silabs/MatterConfig.cpp b/examples/platform/silabs/MatterConfig.cpp index 43bd2c181fd044..8c0488f74c1bd0 100644 --- a/examples/platform/silabs/MatterConfig.cpp +++ b/examples/platform/silabs/MatterConfig.cpp @@ -25,7 +25,7 @@ #include #ifdef SL_WIFI -#include "wfx_host_events.h" +#include #endif /* SL_WIFI */ #if PW_RPC_ENABLED @@ -41,7 +41,8 @@ #endif #if defined(SLI_SI91X_MCU_INTERFACE) && SLI_SI91X_MCU_INTERFACE == 1 -#include "WifiInterfaceAbstraction.h" +#include +#include #endif // SLI_SI91X_MCU_INTERFACE #include @@ -328,6 +329,7 @@ CHIP_ERROR SilabsMatterConfig::InitWiFi(void) extern "C" void vApplicationIdleHook(void) { #if (SLI_SI91X_MCU_INTERFACE && CHIP_CONFIG_ENABLE_ICD_SERVER) - sl_si91x_invoke_btn_press_event(); + SiWxPlatformInterface::sl_si91x_btn_event_handler(); + SiWxPlatformInterface::sl_si91x_uart_power_requirement_handler(); #endif } diff --git a/examples/platform/silabs/SiWx917/BUILD.gn b/examples/platform/silabs/SiWx917/BUILD.gn index 3409d8e815e6f0..2d6d3574ea3506 100644 --- a/examples/platform/silabs/SiWx917/BUILD.gn +++ b/examples/platform/silabs/SiWx917/BUILD.gn @@ -18,7 +18,7 @@ import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/examples/platform/silabs/args.gni") import("${chip_root}/src/lib/lib.gni") import("${chip_root}/src/platform/device.gni") -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") import("${chip_root}/third_party/silabs/silabs_board.gni") import("${silabs_sdk_build_root}/SiWx917_sdk.gni") @@ -28,19 +28,6 @@ declare_args() { # OTA timeout in seconds ota_periodic_query_timeout_sec = 86400 - # Wifi related stuff - they are overridden by gn -args="use_wf200=true" - sl_wfx_config_softap = false - sl_wfx_config_scan = true - - # Argument to force enable WPA3 security on rs91x - rs91x_wpa3_transition = true - - #default WiFi SSID - chip_default_wifi_ssid = "" - - #default Wifi Password - chip_default_wifi_psk = "" - # The EnableKey in hex string format used by TestEventTrigger command in # GeneralDiagnostics cluster. The length of the string should be 16 bytes. sl_test_event_trigger_enable_key = "00112233445566778899AABBCCDDEEFF" @@ -105,40 +92,6 @@ source_set("matter-shell") { ] } -config("wifi-interface-config") { - include_dirs = [ - "${silabs_plat_dir}/wifi", - "${silabs_common_plat_dir}/wifi", - ] -} - -source_set("wifi-interface") { - sources = [ - "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", - "SiWxWifiInterface.cpp", - - # Wi-Fi Config - Using the file sdk support until the wiseconnect file is fixed - "${sdk_support_root}/components/service/network_manager/src/sl_net_for_lwip.c", - ] - - public_deps = [ - "${chip_root}/src/app/icd/server:icd-server-config", - "${chip_root}/src/lib/core", - "${chip_root}/src/lib/support", - "${chip_root}/src/platform:platform", - "${chip_root}/src/platform/silabs/SiWx917:SiWx917", - "${lwip_root}:lwip", - ] - - public_configs = [ - ":siwx917-common-config", - "${silabs_sdk_build_root}:silabs_config", - ":chip_examples_project_config", - ":wifi-interface-config", - ":silabs-wifi-config", - ] -} - config("siwx917-common-config") { defines = [ "OTA_PERIODIC_TIMEOUT=${ota_periodic_query_timeout_sec}" ] @@ -163,46 +116,10 @@ config("siwx917-common-config") { ldflags = [ "-Wl,--no-warn-rwx-segment" ] } -config("silabs-wifi-config") { - defines = [] - include_dirs = [] - - if (chip_default_wifi_ssid != "") { - defines += [ - "SL_ONNETWORK_PAIRING=1", - "SL_WIFI_SSID=\"${chip_default_wifi_ssid}\"", - ] - } - if (chip_default_wifi_psk != "") { - assert(chip_default_wifi_ssid != "", - "ssid can't be null if psk is provided") - defines += [ "SL_WIFI_PSK=\"${chip_default_wifi_psk}\"" ] - } - - if (sl_wfx_config_softap) { - defines += [ "SL_WFX_CONFIG_SOFTAP" ] - } - - if (sl_wfx_config_scan) { - defines += [ "SL_WFX_CONFIG_SCAN" ] - } - - if (chip_enable_wifi_ipv4) { - defines += [ "CHIP_DEVICE_CONFIG_ENABLE_IPV4" ] - } - - if (rs91x_wpa3_transition) { - defines += [ "WIFI_ENABLE_SECURITY_WPA3_TRANSITION=1" ] - } -} - source_set("siwx917-common") { deps = [ "${silabs_common_plat_dir}/provision:storage" ] defines = [] - public_deps = [ - ":wifi-interface", - "${lwip_root}:lwip", - ] + public_deps = [] public_configs = [ ":siwx917-common-config", @@ -249,10 +166,6 @@ source_set("siwx917-common") { sources += [ "${silabs_common_plat_dir}/MemMonitoring.cpp" ] } - if (chip_enable_wifi) { - public_configs += [ ":silabs-wifi-config" ] - } - if (chip_build_libshell) { deps += [ ":matter-shell" ] diff --git a/examples/platform/silabs/display/demo-ui.c b/examples/platform/silabs/display/demo-ui.c index d909cb1f885172..fb41a5b3097583 100644 --- a/examples/platform/silabs/display/demo-ui.c +++ b/examples/platform/silabs/display/demo-ui.c @@ -27,9 +27,8 @@ #include "sl_memlcd.h" #include #if SL_WIFI && !SLI_SI91X_MCU_INTERFACE -#include "spi_multiplex.h" +#include #endif // SL_WIFI && !SLI_SI91X_MCU_INTERFACE -#include #include // Main Logo and App image diff --git a/examples/platform/silabs/efr32/BUILD.gn b/examples/platform/silabs/efr32/BUILD.gn index 9e6b700cfde727..e0e7b45070d2fc 100644 --- a/examples/platform/silabs/efr32/BUILD.gn +++ b/examples/platform/silabs/efr32/BUILD.gn @@ -27,19 +27,6 @@ declare_args() { # OTA timeout in seconds ota_periodic_query_timeout_sec = 86400 - # Wifi related stuff - they are overridden by gn -args="use_wf200=true" - sl_wfx_config_softap = false - sl_wfx_config_scan = true - - # Argument to force enable WPA3 security on rs91x - rs91x_wpa3_transition = true - - #default WiFi SSID - chip_default_wifi_ssid = "" - - #default Wifi Password - chip_default_wifi_psk = "" - # The EnableKey in hex string format used by TestEventTrigger command in # GeneralDiagnostics cluster. The length of the string should be 16 bytes. sl_test_event_trigger_enable_key = "00112233445566778899AABBCCDDEEFF" @@ -53,20 +40,6 @@ assert(!(use_rs9116 && chip_enable_openthread)) assert(!(use_SiWx917 && chip_enable_openthread)) assert(!(use_wf200 && chip_enable_openthread)) -if (chip_enable_wifi) { - assert(use_rs9116 || use_wf200 || use_SiWx917) - import("${chip_root}/src/platform/silabs/wifi_args.gni") - - if (use_rs9116) { - import("rs911x/rs911x.gni") - } else if (use_SiWx917) { - import("rs911x/rs9117.gni") - } - if (use_wf200) { - import("wf200/wf200.gni") - } -} - config("chip_examples_project_config") { include_dirs = [ "project_include" ] @@ -167,40 +140,6 @@ config("efr32-common-config") { ldflags = [ "-Wl,--no-warn-rwx-segment" ] } -config("silabs-wifi-config") { - defines = [] - include_dirs = [] - - if (chip_default_wifi_ssid != "") { - defines += [ - "SL_ONNETWORK_PAIRING=1", - "SL_WIFI_SSID=\"${chip_default_wifi_ssid}\"", - ] - } - if (chip_default_wifi_psk != "") { - assert(chip_default_wifi_ssid != "", - "ssid can't be null if psk is provided") - defines += [ "SL_WIFI_PSK=\"${chip_default_wifi_psk}\"" ] - } - - if (sl_wfx_config_softap) { - defines += [ "SL_WFX_CONFIG_SOFTAP" ] - } - - if (sl_wfx_config_scan) { - defines += [ "SL_WFX_CONFIG_SCAN" ] - } - - if (chip_enable_wifi_ipv4) { - defines += [ "CHIP_DEVICE_CONFIG_ENABLE_IPV4" ] - } - - if (rs91x_wpa3_transition) { - # TODO: Change this macro once WF200 support is provided - defines += [ "WIFI_ENABLE_SECURITY_WPA3_TRANSITION=1" ] - } -} - source_set("efr32-common") { deps = [ "${silabs_common_plat_dir}/provision:storage" ] defines = [] @@ -265,32 +204,6 @@ source_set("efr32-common") { ] } - if (chip_enable_wifi) { - if (use_rs9116) { - sources += rs911x_src_plat - - # All the stuff from wiseconnect - sources += rs911x_src_sapi - include_dirs += rs911x_inc_plat - - #add compilation flags for rs991x build. This will be addressed directly in wiseconnect sdk in the next version release of that sdk - cflags = rs911x_cflags - } else if (use_SiWx917) { - sources += rs911x_src_plat - - # All the stuff from wiseconnect - sources += rs9117_src_sapi - include_dirs += rs9117_inc_plat - - #add compilation flags for rs991x build. This will be addressed directly in wiseconnect sdk in the next version release of that sdk - } else if (use_wf200) { - sources += wf200_plat_src - include_dirs += wf200_plat_incs - } - - public_configs += [ ":silabs-wifi-config" ] - } - if (chip_build_libshell) { deps += [ ":matter-shell" ] diff --git a/examples/platform/silabs/provision/ProvisionStorageDefault.cpp b/examples/platform/silabs/provision/ProvisionStorageDefault.cpp index bc0bfbd8f06918..c6071094480363 100644 --- a/examples/platform/silabs/provision/ProvisionStorageDefault.cpp +++ b/examples/platform/silabs/provision/ProvisionStorageDefault.cpp @@ -17,7 +17,6 @@ #include "AttestationKey.h" #include "ProvisionStorage.h" #include -#include #include #include #include @@ -28,6 +27,7 @@ #include #include #include +#include #include #ifndef NDEBUG #if defined(SL_MATTER_TEST_EVENT_TRIGGER_ENABLED) && (SL_MATTER_GN_BUILD == 0) @@ -37,16 +37,7 @@ #ifdef OTA_ENCRYPTION_ENABLE #include #endif // OTA_ENCRYPTION_ENABLE -#ifdef SLI_SI91X_MCU_INTERFACE -#include -#else -#ifdef _SILICON_LABS_32B_SERIES_2 -#include -#elif defined(_SILICON_LABS_32B_SERIES_3) -#include "sl_se_manager.h" -#include "sl_se_manager_types.h" -#include -#endif // _SILICON_LABS_32B_SERIES_2 +#ifndef SLI_SI91X_MCU_INTERFACE #include #endif @@ -56,16 +47,6 @@ extern void setNvm3End(uint32_t addr); #include #endif -#if defined(_SILICON_LABS_32B_SERIES_3) -// To remove any ambiguities regarding the Flash aliases, use the below macro to ignore the 8 MSB. -#define FLASH_GENERIC_MASK 0x00FFFFFF -#define GENERIC_ADDRESS(addr) ((addr) &FLASH_GENERIC_MASK) - -// Transforms any address into an address using the same alias as FLASH_BASE from the CMSIS. -#define CMSIS_CONVERTED_ADDRESS(addr) (GENERIC_ADDRESS(addr) | FLASH_BASE) -sl_se_command_context_t cmd_ctx; -#endif // _SILICON_LABS_32B_SERIES_3 - extern uint8_t linker_nvm_end[]; using namespace chip::Credentials; @@ -86,42 +67,12 @@ size_t sCredentialsOffset = 0; CHIP_ERROR ErasePage(uint32_t addr) { -#ifdef SLI_SI91X_MCU_INTERFACE - rsi_flash_erase_sector((uint32_t *) addr); -#elif defined(_SILICON_LABS_32B_SERIES_2) - MSC_ErasePage((uint32_t *) addr); -#elif defined(_SILICON_LABS_32B_SERIES_3) - sl_status_t status; - uint32_t * data_start = NULL; - size_t data_size; - - status = sl_se_data_region_get_location(&cmd_ctx, (void **) &data_start, &data_size); - VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); - VerifyOrReturnError(GENERIC_ADDRESS(addr) > GENERIC_ADDRESS((uint32_t) data_start), CHIP_ERROR_INVALID_ADDRESS); - status = sl_se_data_region_erase(&cmd_ctx, (void *) addr, 1); // Erase one page - VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); -#endif - return CHIP_NO_ERROR; + return chip::DeviceLayer::Silabs::GetPlatform().FlashErasePage(addr); } CHIP_ERROR WritePage(uint32_t addr, const uint8_t * data, size_t size) { -#ifdef SLI_SI91X_MCU_INTERFACE - rsi_flash_write((uint32_t *) addr, (unsigned char *) data, size); -#elif defined(_SILICON_LABS_32B_SERIES_2) - MSC_WriteWord((uint32_t *) addr, data, size); -#elif defined(_SILICON_LABS_32B_SERIES_3) - sl_status_t status; - uint32_t * data_start = NULL; - size_t data_size; - - status = sl_se_data_region_get_location(&cmd_ctx, (void **) &data_start, &data_size); - VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); - VerifyOrReturnError(GENERIC_ADDRESS(addr) > GENERIC_ADDRESS((uint32_t) data_start), CHIP_ERROR_INVALID_ADDRESS); - status = sl_se_data_region_write(&cmd_ctx, (void *) addr, data, size); - VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); -#endif - return CHIP_NO_ERROR; + return chip::DeviceLayer::Silabs::GetPlatform().FlashWritePage(addr, data, size); } size_t RoundNearest(size_t n, size_t multiple) @@ -203,16 +154,8 @@ CHIP_ERROR Storage::Initialize(uint32_t flash_addr, uint32_t flash_size) { #ifndef SLI_SI91X_MCU_INTERFACE base_addr = (flash_addr + flash_size - FLASH_PAGE_SIZE); - -#ifdef _SILICON_LABS_32B_SERIES_2 - MSC_Init(); -#elif defined(_SILICON_LABS_32B_SERIES_3) - sl_status_t status; - status = sl_se_init(); - VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR_INTERNAL); - status = sl_se_init_command_context(&cmd_ctx); -#endif // _SILICON_LABS_32B_SERIES #endif // SLI_SI91X_MCU_INTERFACE + chip::DeviceLayer::Silabs::GetPlatform().FlashInit(); #ifdef SL_PROVISION_GENERATOR setNvm3End(base_addr); #endif diff --git a/examples/platform/silabs/uart.cpp b/examples/platform/silabs/uart.cpp index 6ef768ac652e19..c460554c6afc57 100644 --- a/examples/platform/silabs/uart.cpp +++ b/examples/platform/silabs/uart.cpp @@ -364,7 +364,7 @@ void USART_IRQHandler(void) { #ifdef ENABLE_CHIP_SHELL chip::NotifyShellProcess(); -#elif !defined(PW_RPC_ENABLED) && !defined(SL_WIFI) +#elif !defined(PW_RPC_ENABLED) && CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI otSysEventSignalPending(); #endif #ifdef SL_CATALOG_UARTDRV_EUSART_PRESENT @@ -411,7 +411,7 @@ static void UART_rx_callback(UARTDRV_Handle_t handle, Ecode_t transferStatus, ui #ifdef ENABLE_CHIP_SHELL chip::NotifyShellProcess(); -#elif !defined(PW_RPC_ENABLED) +#elif !defined(PW_RPC_ENABLED) && CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI otSysEventSignalPending(); #endif } diff --git a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h deleted file mode 100644 index a26ead2579b16a..00000000000000 --- a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#pragma once - -#include -#include -#include -#include - -/* - * Interface to RSI Sapis - */ - -#define WFX_RSI_WLAN_TASK_SZ (1024 + 512 + 256) /* Stack for the WLAN task */ // TODO: For rs9116 -#define WFX_RSI_BUF_SZ (1024 * 10) -#define WFX_RSI_DHCP_POLL_INTERVAL (250) /* Poll interval in ms for DHCP */ -#define WFX_RSI_NUM_TIMERS (2) /* Number of RSI timers to alloc */ - -typedef enum -{ - WFX_EVT_STA_CONN, - WFX_EVT_STA_DISCONN, - WFX_EVT_AP_START, - WFX_EVT_AP_STOP, - WFX_EVT_SCAN, /* This is used as scan result and start */ - WFX_EVT_STA_START_JOIN, - WFX_EVT_STA_DO_DHCP, - WFX_EVT_STA_DHCP_DONE, - WFX_EVT_DHCP_POLL -} WfxEventType_e; - -typedef enum -{ - WFX_RSI_ST_DEV_READY = (1 << 0), - WFX_RSI_ST_AP_READY = (1 << 1), - WFX_RSI_ST_STA_PROVISIONED = (1 << 2), - WFX_RSI_ST_STA_CONNECTING = (1 << 3), - WFX_RSI_ST_STA_CONNECTED = (1 << 4), - WFX_RSI_ST_STA_DHCP_DONE = (1 << 6), /* Requested to do DHCP after conn */ - WFX_RSI_ST_STA_MODE = (1 << 7), /* Enable Station Mode */ - WFX_RSI_ST_AP_MODE = (1 << 8), /* Enable AP Mode */ - WFX_RSI_ST_STA_READY = (WFX_RSI_ST_STA_CONNECTED | WFX_RSI_ST_STA_DHCP_DONE), - WFX_RSI_ST_STARTED = (1 << 9), /* RSI task started */ - WFX_RSI_ST_SCANSTARTED = (1 << 10), /* Scan Started */ -} WfxStateType_e; - -typedef struct WfxEvent_s -{ - WfxEventType_e eventType; - void * eventData; // event data TODO: confirm needed -} WfxEvent_t; - -typedef struct wfx_rsi_s -{ - uint16_t dev_state; - uint16_t ap_chan; /* The chan our STA is using */ - wfx_wifi_provision_t sec; -#ifdef SL_WFX_CONFIG_SCAN - void (*scan_cb)(wfx_wifi_scan_result_t *); - char * scan_ssid; /* Which one are we scanning for */ - size_t scan_ssid_length; -#endif -#ifdef SL_WFX_CONFIG_SOFTAP - sl_wfx_mac_address_t softap_mac; -#endif - sl_wfx_mac_address_t sta_mac; - sl_wfx_mac_address_t ap_mac; /* To which our STA is connected */ - sl_wfx_mac_address_t ap_bssid; /* To which our STA is connected */ - uint16_t join_retries; - uint8_t ip4_addr[4]; /* Not sure if this is enough */ -} WfxRsi_t; - -extern WfxRsi_t wfx_rsi; - -void sl_matter_wifi_task(void * arg); - -#if CHIP_DEVICE_CONFIG_ENABLE_IPV4 -void wfx_ip_changed_notify(int got_ip); -#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ - -int32_t wfx_rsi_get_ap_info(wfx_wifi_scan_result_t * ap); -int32_t wfx_rsi_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); -int32_t wfx_rsi_reset_count(); -int32_t sl_wifi_platform_disconnect(); - -// TODO : this needs to be extern otherwise we get a linking error. We need to figure out why in the header clean up -// NCP files are including this while being c files -#ifdef __cplusplus -extern "C" { -#endif -sl_status_t sl_matter_wifi_platform_init(void); - -#if CHIP_CONFIG_ENABLE_ICD_SERVER -#if SLI_SI91X_MCU_INTERFACE -void sl_si91x_invoke_btn_press_event(); -#endif // SLI_SI91X_MCU_INTERFACE -#if SLI_SI917 -int32_t wfx_rsi_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t sl_si91x_wifi_state); -#else -int32_t wfx_rsi_power_save(); -#endif /* SLI_SI917 */ -#endif /* SL_ICD_ENABLED */ -#ifdef __cplusplus -} -#endif - -/** - * @brief Posts an event to the Wi-Fi task - * - * @param[in] event Event to process. Must be valid ptr - */ -// TODO: Can't be a const & since the ncp builds are still using c files -void sl_matter_wifi_post_event(WfxEvent_t * event); diff --git a/examples/platform/telink/build_info.cmake b/examples/platform/telink/build_info.cmake new file mode 100644 index 00000000000000..f6a7ccfaee34f3 --- /dev/null +++ b/examples/platform/telink/build_info.cmake @@ -0,0 +1,148 @@ +# +# Copyright (c) 2024 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. + +# Matter git info +execute_process( + COMMAND git rev-parse HEAD + OUTPUT_VARIABLE MATTER_COMMIT_HASH + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git diff --quiet + RESULT_VARIABLE MATTER_LOCAL_STATUS +) + +if(MATTER_LOCAL_STATUS) + set(MATTER_LOCAL_STATUS "-dirty") +else() + set(MATTER_LOCAL_STATUS "") +endif() + +execute_process( + COMMAND git rev-parse --abbrev-ref HEAD + OUTPUT_VARIABLE MATTER_BRANCH_NAME + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND python3 -c "from datetime import datetime; print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))" + OUTPUT_VARIABLE BUILD_TIMESTAMP + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git show -s --format=%cd --date=format:%Y-%m-%d + OUTPUT_VARIABLE MATTER_COMMIT_DATE + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git remote get-url origin + OUTPUT_VARIABLE MATTER_REMOTE_URL + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +# Zephyr git info +execute_process( + COMMAND git -C ${ZEPHYR_BASE} rev-parse HEAD + OUTPUT_VARIABLE ZEPHYR_COMMIT_HASH + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git -C ${ZEPHYR_BASE} rev-parse --abbrev-ref HEAD + OUTPUT_VARIABLE ZEPHYR_BRANCH_NAME + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git -C ${ZEPHYR_BASE} show -s --format=%cd --date=format:%Y-%m-%d HEAD + OUTPUT_VARIABLE ZEPHYR_COMMIT_DATE + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND bash -c "git -C ${ZEPHYR_BASE} remote get-url \$(git -C ${ZEPHYR_BASE} remote | head -n 1)" + OUTPUT_VARIABLE ZEPHYR_REMOTE_URL + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git -C ${ZEPHYR_BASE} diff --quiet + RESULT_VARIABLE ZEPHYR_LOCAL_STATUS +) + +if(ZEPHYR_LOCAL_STATUS) + set(ZEPHYR_LOCAL_STATUS "-dirty") +else() + set(ZEPHYR_LOCAL_STATUS "") +endif() + +# Telink HAL info +execute_process( + COMMAND git -C ${ZEPHYR_BASE}/../modules/hal/telink rev-parse HEAD + OUTPUT_VARIABLE TELINK_HAL_COMMIT_HASH + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git -C ${ZEPHYR_BASE}/../modules/hal/telink diff --quiet + RESULT_VARIABLE HAL_LOCAL_STATUS +) + +if(TELINK_HAL_LOCAL_STATUS) + set(TELINK_HAL_LOCAL_STATUS "-dirty") +else() + set(TELINK_HAL_LOCAL_STATUS "") +endif() + +execute_process( + COMMAND git -C ${ZEPHYR_BASE}/../modules/hal/telink show -s --format=%cd --date=format:%Y-%m-%d + OUTPUT_VARIABLE TELINK_HAL_COMMIT_DATE + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +target_compile_definitions(app PRIVATE + MATTER_COMMIT_HASH="${MATTER_COMMIT_HASH}" + MATTER_BRANCH="${MATTER_BRANCH_NAME}" + BUILD_TIMESTAMP="${BUILD_TIMESTAMP}" + MATTER_COMMIT_DATE="${MATTER_COMMIT_DATE}" + MATTER_REMOTE_URL="${MATTER_REMOTE_URL}" + MATTER_LOCAL_STATUS="${MATTER_LOCAL_STATUS}" + + ZEPHYR_COMMIT_HASH="${ZEPHYR_COMMIT_HASH}" + ZEPHYR_BRANCH="${ZEPHYR_BRANCH_NAME}" + ZEPHYR_COMMIT_DATE="${ZEPHYR_COMMIT_DATE}" + ZEPHYR_REMOTE_URL="${ZEPHYR_REMOTE_URL}" + ZEPHYR_LOCAL_STATUS="${ZEPHYR_LOCAL_STATUS}" + + TELINK_HAL_COMMIT_HASH="${TELINK_HAL_COMMIT_HASH}" + TELINK_HAL_LOCAL_STATUS="${TELINK_HAL_LOCAL_STATUS}" + TELINK_HAL_COMMIT_DATE="${TELINK_HAL_COMMIT_DATE}" +) + +message(STATUS "Matter revision:") +message(STATUS " board: ${CONFIG_BOARD}") +message(STATUS " branch: ${MATTER_BRANCH_NAME} ${MATTER_COMMIT_HASH} ${MATTER_COMMIT_DATE}") +message(STATUS " remote: ${MATTER_REMOTE_URL}") +message(STATUS " build timestamp: ${BUILD_TIMESTAMP}") + +message(STATUS "Zephyr revision:") +message(STATUS " branch: ${ZEPHYR_BRANCH_NAME} ${ZEPHYR_COMMIT_HASH} ${ZEPHYR_COMMIT_DATE}") +message(STATUS " remote: ${ZEPHYR_REMOTE_URL}") + +message(STATUS "HAL revision:") +message(STATUS " commit: ${TELINK_HAL_COMMIT_HASH} ${TELINK_HAL_COMMIT_DATE}") diff --git a/examples/platform/telink/common.cmake b/examples/platform/telink/common.cmake index 34ff2dbffdf471..80050c81b3b641 100644 --- a/examples/platform/telink/common.cmake +++ b/examples/platform/telink/common.cmake @@ -63,7 +63,11 @@ else() unset(USB_CONF_OVERLAY_FILE) endif() -set(BOOT_CONF_OVERLAY_FILE "${CHIP_ROOT}/config/telink/app/bootloader.conf") +if(${CONFIG_COMPRESS_LZMA} MATCHES y) + set(BOOT_CONF_OVERLAY_FILE "${CHIP_ROOT}/config/telink/app/bootloader_compress_lzma.conf") +else() + set(BOOT_CONF_OVERLAY_FILE "${CHIP_ROOT}/config/telink/app/bootloader.conf") +endif() if(NOT EXISTS "${BOOT_CONF_OVERLAY_FILE}") message(FATAL_ERROR "${BOOT_CONF_OVERLAY_FILE} doesn't exist") endif() diff --git a/examples/platform/telink/common/include/AppTaskCommon.h b/examples/platform/telink/common/include/AppTaskCommon.h index ff3f7bf174a939..ac10ef587d2be9 100644 --- a/examples/platform/telink/common/include/AppTaskCommon.h +++ b/examples/platform/telink/common/include/AppTaskCommon.h @@ -84,6 +84,7 @@ class AppTaskCommon protected: CHIP_ERROR InitCommonParts(void); + void PrintFirmwareInfo(void); void DispatchEvent(AppEvent * event); void GetEvent(AppEvent * aEvent); @@ -111,6 +112,11 @@ class AppTaskCommon static void StartWiFiHandler(AppEvent * aEvent); #endif +#if CONFIG_TELINK_OTA_BUTTON_TEST + static void TestOTAButtonEventHandler(void); + static void TestOTAHandler(AppEvent * aEvent); +#endif + static void ExampleActionButtonEventHandler(void); void SetExampleButtonCallbacks(EventHandler aAction_CB); diff --git a/examples/platform/telink/common/src/AppTaskCommon.cpp b/examples/platform/telink/common/src/AppTaskCommon.cpp index 13036743a5db65..de5faa974a4847 100644 --- a/examples/platform/telink/common/src/AppTaskCommon.cpp +++ b/examples/platform/telink/common/src/AppTaskCommon.cpp @@ -240,11 +240,28 @@ CHIP_ERROR AppTaskCommon::StartApp(void) DispatchEvent(&event); } } +void AppTaskCommon::PrintFirmwareInfo(void) +{ + LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); +#if CONFIG_CHIP_APP_LOG_LEVEL > 3 + LOG_DBG("Matter revision: "); + LOG_DBG("\t board: %s", CONFIG_BOARD); + LOG_DBG("\t branch: %s %.8s%s %s", MATTER_BRANCH, MATTER_COMMIT_HASH, MATTER_LOCAL_STATUS, MATTER_COMMIT_DATE); + LOG_DBG("\t remote: %s", MATTER_REMOTE_URL); + LOG_DBG("\t build timestamp: %s", BUILD_TIMESTAMP); + + LOG_DBG("Zephyr revision: "); + LOG_DBG("\t branch: %s %.8s%s %s", ZEPHYR_BRANCH, ZEPHYR_COMMIT_HASH, ZEPHYR_LOCAL_STATUS, ZEPHYR_COMMIT_DATE); + LOG_DBG("\t remote: %s", ZEPHYR_REMOTE_URL); + LOG_DBG("\t HAL commit: %.8s%s %s", TELINK_HAL_COMMIT_HASH, TELINK_HAL_LOCAL_STATUS, TELINK_HAL_COMMIT_DATE); +#endif +} CHIP_ERROR AppTaskCommon::InitCommonParts(void) { CHIP_ERROR err; - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + PrintFirmwareInfo(); InitLeds(); UpdateStatusLED(); @@ -447,7 +464,11 @@ void AppTaskCommon::LinkButtons(ButtonManager & buttonManager) { buttonManager.addCallback(FactoryResetButtonEventHandler, 0, true); buttonManager.addCallback(ExampleActionButtonEventHandler, 1, true); +#if CONFIG_TELINK_OTA_BUTTON_TEST + buttonManager.addCallback(TestOTAButtonEventHandler, 2, true); +#else buttonManager.addCallback(StartBleAdvButtonEventHandler, 2, true); +#endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD buttonManager.addCallback(StartThreadButtonEventHandler, 3, true); #elif CHIP_DEVICE_CONFIG_ENABLE_WIFI @@ -595,6 +616,26 @@ void AppTaskCommon::FactoryResetTimerEventHandler(AppEvent * aEvent) LOG_INF("Factory Reset Trigger Counter is cleared"); } +#if CONFIG_TELINK_OTA_BUTTON_TEST +void AppTaskCommon::TestOTAButtonEventHandler(void) +{ + AppEvent event; + + event.Type = AppEvent::kEventType_Button; + event.ButtonEvent.Action = kButtonPushEvent; + event.Handler = TestOTAHandler; + GetAppTask().PostEvent(&event); +} + +void AppTaskCommon::TestOTAHandler(AppEvent * aEvent) +{ + LOG_INF("TestOTAHandler"); + + chip::DeviceLayer::OTAImageProcessorImpl imageProcessor; + imageProcessor.Apply(); +} +#endif + #if CHIP_DEVICE_CONFIG_ENABLE_THREAD void AppTaskCommon::StartThreadButtonEventHandler(void) { diff --git a/examples/pump-app/silabs/README.md b/examples/pump-app/silabs/README.md index 70d83e4de5f70c..0ca0f43a7a5784 100644 --- a/examples/pump-app/silabs/README.md +++ b/examples/pump-app/silabs/README.md @@ -242,6 +242,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/pump-app/silabs/build_for_wifi_args.gni b/examples/pump-app/silabs/build_for_wifi_args.gni index c9544469215d2a..9e6aeced58d2c0 100644 --- a/examples/pump-app/silabs/build_for_wifi_args.gni +++ b/examples/pump-app/silabs/build_for_wifi_args.gni @@ -16,7 +16,7 @@ import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") chip_enable_ota_requestor = true app_data_model = "${chip_root}/examples/pump-app/silabs/data_model:silabs-pump" diff --git a/examples/refrigerator-app/silabs/BUILD.gn b/examples/refrigerator-app/silabs/BUILD.gn index 9e63c6c10e164b..200c909b1f2629 100644 --- a/examples/refrigerator-app/silabs/BUILD.gn +++ b/examples/refrigerator-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -38,7 +38,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/refrigerator-app/silabs/build_for_wifi_args.gni b/examples/refrigerator-app/silabs/build_for_wifi_args.gni index e82cf8be12fc97..a12daf827a774f 100644 --- a/examples/refrigerator-app/silabs/build_for_wifi_args.gni +++ b/examples/refrigerator-app/silabs/build_for_wifi_args.gni @@ -15,7 +15,7 @@ import("//build_overrides/chip.gni") import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") chip_enable_wifi = true chip_enable_ota_requestor = true app_data_model = "${chip_root}/examples/refrigerator-app/silabs/data_model:silabs-refrigerator" diff --git a/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.matter b/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.matter index 173823b22d6439..49f9672046088a 100644 --- a/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.matter +++ b/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.matter @@ -241,6 +241,56 @@ struct AtomicAttributeStatusStruct { status statusCode = 1; } +/** Attributes and commands for putting a device into Identification mode (e.g. flashing a light). */ +cluster Identify = 3 { + revision 4; + + enum EffectIdentifierEnum : enum8 { + kBlink = 0; + kBreathe = 1; + kOkay = 2; + kChannelChange = 11; + kFinishEffect = 254; + kStopEffect = 255; + } + + enum EffectVariantEnum : enum8 { + kDefault = 0; + } + + enum IdentifyTypeEnum : enum8 { + kNone = 0; + kLightOutput = 1; + kVisibleIndicator = 2; + kAudibleBeep = 3; + kDisplay = 4; + kActuator = 5; + } + + attribute int16u identifyTime = 0; + readonly attribute IdentifyTypeEnum identifyType = 1; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct IdentifyRequest { + int16u identifyTime = 0; + } + + request struct TriggerEffectRequest { + EffectIdentifierEnum effectIdentifier = 0; + EffectVariantEnum effectVariant = 1; + } + + /** Command description for Identify */ + command access(invoke: manage) Identify(IdentifyRequest): DefaultSuccess = 0; + /** Command description for TriggerEffect */ + command access(invoke: manage) TriggerEffect(TriggerEffectRequest): DefaultSuccess = 64; +} + /** The Descriptor Cluster is meant to replace the support from the Zigbee Device Object (ZDO) for describing a node, its endpoints and clusters. */ cluster Descriptor = 29 { revision 2; @@ -922,53 +972,6 @@ cluster NetworkCommissioning = 49 { command access(invoke: administer) QueryIdentity(QueryIdentityRequest): QueryIdentityResponse = 9; } -/** The cluster provides commands for retrieving unstructured diagnostic logs from a Node that may be used to aid in diagnostics. */ -cluster DiagnosticLogs = 50 { - revision 1; // NOTE: Default/not specifically set - - enum IntentEnum : enum8 { - kEndUserSupport = 0; - kNetworkDiag = 1; - kCrashLogs = 2; - } - - enum StatusEnum : enum8 { - kSuccess = 0; - kExhausted = 1; - kNoLogs = 2; - kBusy = 3; - kDenied = 4; - } - - enum TransferProtocolEnum : enum8 { - kResponsePayload = 0; - kBDX = 1; - } - - readonly attribute command_id generatedCommandList[] = 65528; - readonly attribute command_id acceptedCommandList[] = 65529; - readonly attribute event_id eventList[] = 65530; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct RetrieveLogsRequestRequest { - IntentEnum intent = 0; - TransferProtocolEnum requestedProtocol = 1; - optional char_string<32> transferFileDesignator = 2; - } - - response struct RetrieveLogsResponse = 1 { - StatusEnum status = 0; - long_octet_string logContent = 1; - optional epoch_us UTCTimeStamp = 2; - optional systime_us timeSinceBoot = 3; - } - - /** Retrieving diagnostic logs from a Node */ - command RetrieveLogsRequest(RetrieveLogsRequestRequest): RetrieveLogsResponse = 0; -} - /** The General Diagnostics Cluster, along with other diagnostics clusters, provide a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. */ cluster GeneralDiagnostics = 51 { revision 2; @@ -1756,10 +1759,12 @@ endpoint 0 { ram attribute lastNetworkingStatus; ram attribute lastNetworkID; ram attribute lastConnectErrorValue; + callback attribute supportedThreadFeatures; + callback attribute threadVersion; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute attributeList; - ram attribute featureMap default = 2; + callback attribute featureMap default = 2; ram attribute clusterRevision default = 1; handle command ScanNetworks; @@ -1772,17 +1777,6 @@ endpoint 0 { handle command ReorderNetwork; } - server cluster DiagnosticLogs { - callback attribute generatedCommandList; - callback attribute acceptedCommandList; - callback attribute attributeList; - ram attribute featureMap default = 0; - ram attribute clusterRevision default = 1; - - handle command RetrieveLogsRequest; - handle command RetrieveLogsResponse; - } - server cluster GeneralDiagnostics { emits event HardwareFaultChange; emits event RadioFaultChange; @@ -1894,6 +1888,19 @@ endpoint 1 { device type ma_refrigerator = 112, version 1; + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x00; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 4; + + handle command Identify; + handle command TriggerEffect; + } + server cluster Descriptor { callback attribute deviceTypeList; callback attribute serverList; @@ -1920,7 +1927,7 @@ endpoint 1 { } server cluster RefrigeratorAlarm { - ram attribute mask default = 0; + ram attribute mask default = 1; ram attribute state default = 0; ram attribute supported default = 0; callback attribute generatedCommandList; diff --git a/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.zap b/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.zap index 57785bd3adc150..3a6bcd833161f6 100644 --- a/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.zap +++ b/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.zap @@ -1,6 +1,6 @@ { "fileFormat": 2, - "featureLevel": 103, + "featureLevel": 104, "creator": "zap", "keyValuePairs": [ { @@ -950,22 +950,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1120,22 +1104,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1609,113 +1577,37 @@ "reportableChange": 0 }, { - "name": "GeneratedCommandList", - "code": 65528, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, - { - "name": "AcceptedCommandList", - "code": 65529, + "name": "SupportedThreadFeatures", + "code": 9, "mfgCode": null, "side": "server", - "type": "array", + "type": "ThreadCapabilitiesBitmap", "included": 1, "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": null, + "defaultValue": "", "reportable": 1, "minInterval": 1, "maxInterval": 65534, "reportableChange": 0 }, { - "name": "AttributeList", - "code": 65531, + "name": "ThreadVersion", + "code": 10, "mfgCode": null, "side": "server", - "type": "array", + "type": "int16u", "included": 1, "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, - { - "name": "FeatureMap", - "code": 65532, - "mfgCode": null, - "side": "server", - "type": "bitmap32", - "included": 1, - "storageOption": "RAM", - "singleton": 0, - "bounded": 0, - "defaultValue": "2", + "defaultValue": "", "reportable": 1, "minInterval": 1, "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "ClusterRevision", - "code": 65533, - "mfgCode": null, - "side": "server", - "type": "int16u", - "included": 1, - "storageOption": "RAM", - "singleton": 0, - "bounded": 0, - "defaultValue": "1", - "reportable": 1, - "minInterval": 0, - "maxInterval": 65344, - "reportableChange": 0 - } - ] - }, - { - "name": "Diagnostic Logs", - "code": 50, - "mfgCode": null, - "define": "DIAGNOSTIC_LOGS_CLUSTER", - "side": "server", - "enabled": 1, - "commands": [ - { - "name": "RetrieveLogsRequest", - "code": 0, - "mfgCode": null, - "source": "client", - "isIncoming": 1, - "isEnabled": 1 - }, - { - "name": "RetrieveLogsResponse", - "code": 1, - "mfgCode": null, - "source": "server", - "isIncoming": 0, - "isEnabled": 1 - } - ], - "attributes": [ { "name": "GeneratedCommandList", "code": 65528, @@ -1748,22 +1640,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1787,10 +1663,10 @@ "side": "server", "type": "bitmap32", "included": 1, - "storageOption": "RAM", + "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "2", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -1808,8 +1684,8 @@ "bounded": 0, "defaultValue": "1", "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, + "minInterval": 0, + "maxInterval": 65344, "reportableChange": 0 } ] @@ -2416,22 +2292,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -3109,6 +2969,146 @@ "deviceTypeCode": 112, "deviceTypeProfileId": 259, "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x00", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "4", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, { "name": "Descriptor", "code": 29, @@ -3353,22 +3353,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -3437,7 +3421,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "1", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -3507,22 +3491,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, diff --git a/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.matter b/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.matter index d3a8603e740154..b4386fe9ef77ac 100644 --- a/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.matter +++ b/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.matter @@ -241,6 +241,56 @@ struct AtomicAttributeStatusStruct { status statusCode = 1; } +/** Attributes and commands for putting a device into Identification mode (e.g. flashing a light). */ +cluster Identify = 3 { + revision 4; + + enum EffectIdentifierEnum : enum8 { + kBlink = 0; + kBreathe = 1; + kOkay = 2; + kChannelChange = 11; + kFinishEffect = 254; + kStopEffect = 255; + } + + enum EffectVariantEnum : enum8 { + kDefault = 0; + } + + enum IdentifyTypeEnum : enum8 { + kNone = 0; + kLightOutput = 1; + kVisibleIndicator = 2; + kAudibleBeep = 3; + kDisplay = 4; + kActuator = 5; + } + + attribute int16u identifyTime = 0; + readonly attribute IdentifyTypeEnum identifyType = 1; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct IdentifyRequest { + int16u identifyTime = 0; + } + + request struct TriggerEffectRequest { + EffectIdentifierEnum effectIdentifier = 0; + EffectVariantEnum effectVariant = 1; + } + + /** Command description for Identify */ + command access(invoke: manage) Identify(IdentifyRequest): DefaultSuccess = 0; + /** Command description for TriggerEffect */ + command access(invoke: manage) TriggerEffect(TriggerEffectRequest): DefaultSuccess = 64; +} + /** The Descriptor Cluster is meant to replace the support from the Zigbee Device Object (ZDO) for describing a node, its endpoints and clusters. */ cluster Descriptor = 29 { revision 2; @@ -922,53 +972,6 @@ cluster NetworkCommissioning = 49 { command access(invoke: administer) QueryIdentity(QueryIdentityRequest): QueryIdentityResponse = 9; } -/** The cluster provides commands for retrieving unstructured diagnostic logs from a Node that may be used to aid in diagnostics. */ -cluster DiagnosticLogs = 50 { - revision 1; // NOTE: Default/not specifically set - - enum IntentEnum : enum8 { - kEndUserSupport = 0; - kNetworkDiag = 1; - kCrashLogs = 2; - } - - enum StatusEnum : enum8 { - kSuccess = 0; - kExhausted = 1; - kNoLogs = 2; - kBusy = 3; - kDenied = 4; - } - - enum TransferProtocolEnum : enum8 { - kResponsePayload = 0; - kBDX = 1; - } - - readonly attribute command_id generatedCommandList[] = 65528; - readonly attribute command_id acceptedCommandList[] = 65529; - readonly attribute event_id eventList[] = 65530; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct RetrieveLogsRequestRequest { - IntentEnum intent = 0; - TransferProtocolEnum requestedProtocol = 1; - optional char_string<32> transferFileDesignator = 2; - } - - response struct RetrieveLogsResponse = 1 { - StatusEnum status = 0; - long_octet_string logContent = 1; - optional epoch_us UTCTimeStamp = 2; - optional systime_us timeSinceBoot = 3; - } - - /** Retrieving diagnostic logs from a Node */ - command RetrieveLogsRequest(RetrieveLogsRequestRequest): RetrieveLogsResponse = 0; -} - /** The General Diagnostics Cluster, along with other diagnostics clusters, provide a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. */ cluster GeneralDiagnostics = 51 { revision 2; @@ -1667,10 +1670,11 @@ endpoint 0 { ram attribute lastNetworkingStatus; ram attribute lastNetworkID; ram attribute lastConnectErrorValue; + callback attribute supportedWiFiBands; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute attributeList; - ram attribute featureMap default = 2; + callback attribute featureMap default = 2; ram attribute clusterRevision default = 1; handle command ScanNetworks; @@ -1683,17 +1687,6 @@ endpoint 0 { handle command ReorderNetwork; } - server cluster DiagnosticLogs { - callback attribute generatedCommandList; - callback attribute acceptedCommandList; - callback attribute attributeList; - ram attribute featureMap default = 0; - ram attribute clusterRevision default = 1; - - handle command RetrieveLogsRequest; - handle command RetrieveLogsResponse; - } - server cluster GeneralDiagnostics { emits event HardwareFaultChange; emits event RadioFaultChange; @@ -1803,6 +1796,19 @@ endpoint 1 { device type ma_refrigerator = 112, version 1; + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x00; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 4; + + handle command Identify; + handle command TriggerEffect; + } + server cluster Descriptor { callback attribute deviceTypeList; callback attribute serverList; @@ -1829,7 +1835,7 @@ endpoint 1 { } server cluster RefrigeratorAlarm { - ram attribute mask default = 0; + ram attribute mask default = 1; ram attribute state default = 0; ram attribute supported default = 0; callback attribute generatedCommandList; diff --git a/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.zap b/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.zap index edc35aa7a37657..addfd6f5198818 100644 --- a/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.zap +++ b/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.zap @@ -1,6 +1,6 @@ { "fileFormat": 2, - "featureLevel": 103, + "featureLevel": 104, "creator": "zap", "keyValuePairs": [ { @@ -17,13 +17,6 @@ } ], "package": [ - { - "pathRelativity": "relativeToZap", - "path": "../../../../src/app/zap-templates/app-templates.json", - "type": "gen-templates-json", - "category": "matter", - "version": "chip-v1" - }, { "pathRelativity": "relativeToZap", "path": "../../../../src/app/zap-templates/zcl/zcl.json", @@ -31,6 +24,13 @@ "category": "matter", "version": 1, "description": "Matter SDK ZCL data" + }, + { + "pathRelativity": "relativeToZap", + "path": "../../../../src/app/zap-templates/app-templates.json", + "type": "gen-templates-json", + "category": "matter", + "version": "chip-v1" } ], "endpointTypes": [ @@ -950,22 +950,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1120,22 +1104,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1609,40 +1577,8 @@ "reportableChange": 0 }, { - "name": "GeneratedCommandList", - "code": 65528, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, - { - "name": "AcceptedCommandList", - "code": 65529, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, - { - "name": "AttributeList", - "code": 65531, + "name": "SupportedWiFiBands", + "code": 8, "mfgCode": null, "side": "server", "type": "array", @@ -1656,66 +1592,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "FeatureMap", - "code": 65532, - "mfgCode": null, - "side": "server", - "type": "bitmap32", - "included": 1, - "storageOption": "RAM", - "singleton": 0, - "bounded": 0, - "defaultValue": "2", - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, - { - "name": "ClusterRevision", - "code": 65533, - "mfgCode": null, - "side": "server", - "type": "int16u", - "included": 1, - "storageOption": "RAM", - "singleton": 0, - "bounded": 0, - "defaultValue": "1", - "reportable": 1, - "minInterval": 0, - "maxInterval": 65344, - "reportableChange": 0 - } - ] - }, - { - "name": "Diagnostic Logs", - "code": 50, - "mfgCode": null, - "define": "DIAGNOSTIC_LOGS_CLUSTER", - "side": "server", - "enabled": 1, - "commands": [ - { - "name": "RetrieveLogsRequest", - "code": 0, - "mfgCode": null, - "source": "client", - "isIncoming": 1, - "isEnabled": 1 - }, - { - "name": "RetrieveLogsResponse", - "code": 1, - "mfgCode": null, - "source": "server", - "isIncoming": 0, - "isEnabled": 1 - } - ], - "attributes": [ { "name": "GeneratedCommandList", "code": 65528, @@ -1748,22 +1624,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1787,10 +1647,10 @@ "side": "server", "type": "bitmap32", "included": 1, - "storageOption": "RAM", + "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "2", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -1808,8 +1668,8 @@ "bounded": 0, "defaultValue": "1", "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, + "minInterval": 0, + "maxInterval": 65344, "reportableChange": 0 } ] @@ -3014,6 +2874,146 @@ "deviceTypeCode": 112, "deviceTypeProfileId": 259, "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x00", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "4", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, { "name": "Descriptor", "code": 29, @@ -3258,22 +3258,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -3342,7 +3326,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "1", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -3412,22 +3396,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, diff --git a/examples/shell/genio/args.gni b/examples/shell/genio/args.gni index 8d2c11daa5b180..eda29ff0e68df2 100644 --- a/examples/shell/genio/args.gni +++ b/examples/shell/genio/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = false chip_config_network_layer_ble = false diff --git a/examples/shell/qpg/args.gni b/examples/shell/qpg/args.gni index 478e91d9cb05a6..c6c98b3fce747a 100644 --- a/examples/shell/qpg/args.gni +++ b/examples/shell/qpg/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/examples/platform/qpg/args.gni") qpg_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_build_libshell = true # Disable lock tracking, since our FreeRTOS configuration does not set diff --git a/examples/smoke-co-alarm-app/silabs/README.md b/examples/smoke-co-alarm-app/silabs/README.md index 7928107b35de47..520056661d8b3d 100644 --- a/examples/smoke-co-alarm-app/silabs/README.md +++ b/examples/smoke-co-alarm-app/silabs/README.md @@ -260,6 +260,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/smoke-co-alarm-app/silabs/build_for_wifi_args.gni b/examples/smoke-co-alarm-app/silabs/build_for_wifi_args.gni index e5097f8a1d82b7..bdebe11b9789f3 100644 --- a/examples/smoke-co-alarm-app/silabs/build_for_wifi_args.gni +++ b/examples/smoke-co-alarm-app/silabs/build_for_wifi_args.gni @@ -16,7 +16,7 @@ import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") chip_enable_ota_requestor = true app_data_model = diff --git a/examples/temperature-measurement-app/esp32/main/CMakeLists.txt b/examples/temperature-measurement-app/esp32/main/CMakeLists.txt index 8bc94f7b97969a..8036700df626a0 100644 --- a/examples/temperature-measurement-app/esp32/main/CMakeLists.txt +++ b/examples/temperature-measurement-app/esp32/main/CMakeLists.txt @@ -29,6 +29,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/zzz_generated/app-common/app-common/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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/administrator-commissioning-server" diff --git a/examples/thermostat/genio/args.gni b/examples/thermostat/genio/args.gni index ddbfb9fa47f20d..b684adc4a6b792 100644 --- a/examples/thermostat/genio/args.gni +++ b/examples/thermostat/genio/args.gni @@ -18,8 +18,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = true diff --git a/examples/thermostat/genio/build_for_wifi_args.gni b/examples/thermostat/genio/build_for_wifi_args.gni index cb0ea7600a2dd5..3001e6648f4aa8 100644 --- a/examples/thermostat/genio/build_for_wifi_args.gni +++ b/examples/thermostat/genio/build_for_wifi_args.gni @@ -18,5 +18,5 @@ mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false import("${chip_root}/src/platform/MT793X/wifi_args.gni") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/thermostat/nxp/rt/rt1060/include/config/CHIPProjectConfig.h b/examples/thermostat/nxp/rt/rt1060/include/config/CHIPProjectConfig.h index dd73c6c9eaaedd..61be0867102324 100644 --- a/examples/thermostat/nxp/rt/rt1060/include/config/CHIPProjectConfig.h +++ b/examples/thermostat/nxp/rt/rt1060/include/config/CHIPProjectConfig.h @@ -167,15 +167,6 @@ */ // #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 -/** - * CHIP_CONFIG_MAX_BINDINGS - * - * Maximum number of simultaneously active bindings per ChipExchangeManager - * 1 (Time Sync) + 2 (Two 1-way subscriptions) + 1 (Software Update) = 4 - * in the worst case. Keeping another 4 as buffer. - */ -#define CHIP_CONFIG_MAX_BINDINGS 6 - /** * CHIP_CONFIG_EVENT_LOGGING_WDM_OFFLOAD * diff --git a/examples/thermostat/nxp/rt/rt1170/include/config/CHIPProjectConfig.h b/examples/thermostat/nxp/rt/rt1170/include/config/CHIPProjectConfig.h index dd73c6c9eaaedd..61be0867102324 100644 --- a/examples/thermostat/nxp/rt/rt1170/include/config/CHIPProjectConfig.h +++ b/examples/thermostat/nxp/rt/rt1170/include/config/CHIPProjectConfig.h @@ -167,15 +167,6 @@ */ // #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 -/** - * CHIP_CONFIG_MAX_BINDINGS - * - * Maximum number of simultaneously active bindings per ChipExchangeManager - * 1 (Time Sync) + 2 (Two 1-way subscriptions) + 1 (Software Update) = 4 - * in the worst case. Keeping another 4 as buffer. - */ -#define CHIP_CONFIG_MAX_BINDINGS 6 - /** * CHIP_CONFIG_EVENT_LOGGING_WDM_OFFLOAD * diff --git a/examples/thermostat/nxp/rt/rw61x/include/config/CHIPProjectConfig.h b/examples/thermostat/nxp/rt/rw61x/include/config/CHIPProjectConfig.h index 2653e97705fe39..33a42909f464ea 100644 --- a/examples/thermostat/nxp/rt/rw61x/include/config/CHIPProjectConfig.h +++ b/examples/thermostat/nxp/rt/rw61x/include/config/CHIPProjectConfig.h @@ -168,15 +168,6 @@ */ // #define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 1 -/** - * CHIP_CONFIG_MAX_BINDINGS - * - * Maximum number of simultaneously active bindings per ChipExchangeManager - * 1 (Time Sync) + 2 (Two 1-way subscriptions) + 1 (Software Update) = 4 - * in the worst case. Keeping another 4 as buffer. - */ -#define CHIP_CONFIG_MAX_BINDINGS 6 - /** * CHIP_CONFIG_EVENT_LOGGING_WDM_OFFLOAD * diff --git a/examples/thermostat/qpg/args.gni b/examples/thermostat/qpg/args.gni index 693375e4388593..64d8c32d43a0ec 100644 --- a/examples/thermostat/qpg/args.gni +++ b/examples/thermostat/qpg/args.gni @@ -31,5 +31,5 @@ chip_stack_lock_tracking = "none" matter_device_vid = "0xFFF1" matter_device_pid = "0x8003" -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/thermostat/silabs/README.md b/examples/thermostat/silabs/README.md index 3205352bf07f1c..681618545b7a1a 100644 --- a/examples/thermostat/silabs/README.md +++ b/examples/thermostat/silabs/README.md @@ -251,6 +251,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/thermostat/silabs/build_for_wifi_args.gni b/examples/thermostat/silabs/build_for_wifi_args.gni index db1e280b0b31d2..76a77c24cdc1d8 100644 --- a/examples/thermostat/silabs/build_for_wifi_args.gni +++ b/examples/thermostat/silabs/build_for_wifi_args.gni @@ -15,7 +15,7 @@ import("//build_overrides/chip.gni") import("${chip_root}/config/standalone/args.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") chip_enable_wifi = true chip_enable_ota_requestor = true app_data_model = "${chip_root}/examples/thermostat/thermostat-common" diff --git a/examples/thread-br-app/esp32/main/CMakeLists.txt b/examples/thread-br-app/esp32/main/CMakeLists.txt index c0cb1234b0cca3..c1f82285e4ac7f 100644 --- a/examples/thread-br-app/esp32/main/CMakeLists.txt +++ b/examples/thread-br-app/esp32/main/CMakeLists.txt @@ -30,6 +30,7 @@ idf_component_register(PRIV_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/shell_extension" "${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/util/persistence" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/icd/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/clusters/access-control-server" diff --git a/examples/window-app/silabs/build_for_wifi_args.gni b/examples/window-app/silabs/build_for_wifi_args.gni index d6a8a54afbedb2..6f445aeb798eb9 100644 --- a/examples/window-app/silabs/build_for_wifi_args.gni +++ b/examples/window-app/silabs/build_for_wifi_args.gni @@ -15,7 +15,7 @@ import("//build_overrides/chip.gni") silabs_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") chip_enable_ota_requestor = true app_data_model = "${chip_root}/examples/window-app/common:window-common" diff --git a/examples/window-app/silabs/src/WindowManager.cpp b/examples/window-app/silabs/src/WindowManager.cpp index 8ae78b3d2e99b8..62e96802c323c8 100644 --- a/examples/window-app/silabs/src/WindowManager.cpp +++ b/examples/window-app/silabs/src/WindowManager.cpp @@ -35,9 +35,9 @@ #include #ifdef SL_WIFI -#include "wfx_host_events.h" #include #include +#include #endif #ifdef DISPLAY_ENABLED diff --git a/integrations/cloudbuild/chef.yaml b/integrations/cloudbuild/chef.yaml index fd34dab03f06d6..1eafb85580a072 100644 --- a/integrations/cloudbuild/chef.yaml +++ b/integrations/cloudbuild/chef.yaml @@ -1,5 +1,5 @@ steps: - - name: "ghcr.io/project-chip/chip-build-vscode:81" + - name: "ghcr.io/project-chip/chip-build-vscode:90" entrypoint: "bash" args: - "-c" @@ -7,7 +7,7 @@ steps: git config --global --add safe.directory "*" python scripts/checkout_submodules.py --shallow --recursive --platform esp32 nrfconnect silabs linux android id: Submodules - - name: "ghcr.io/project-chip/chip-build-vscode:81" + - name: "ghcr.io/project-chip/chip-build-vscode:90" # NOTE: silabs boostrap is NOT done with the rest as it requests a conflicting # jinja2 version (asks for 3.1.3 when constraints.txt asks for 3.0.3) env: @@ -23,7 +23,7 @@ steps: - name: pwenv path: /pwenv timeout: 900s - - name: "ghcr.io/project-chip/chip-build-vscode:81" + - name: "ghcr.io/project-chip/chip-build-vscode:90" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -38,7 +38,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:81" + - name: "ghcr.io/project-chip/chip-build-vscode:90" env: - PW_ENVIRONMENT_ROOT=/pwenv args: diff --git a/integrations/cloudbuild/smoke-test.yaml b/integrations/cloudbuild/smoke-test.yaml index 02e73512c43928..f1ca12766f0d29 100644 --- a/integrations/cloudbuild/smoke-test.yaml +++ b/integrations/cloudbuild/smoke-test.yaml @@ -1,5 +1,5 @@ steps: - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" entrypoint: "bash" args: - "-c" @@ -7,7 +7,7 @@ steps: git config --global --add safe.directory "*" python scripts/checkout_submodules.py --shallow --recursive --platform esp32 nrfconnect silabs linux android id: Submodules - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" # NOTE: silabs boostrap is NOT done with the rest as it requests a conflicting # jinja2 version (asks for 3.1.3 when constraints.txt asks for 3.0.3) env: @@ -24,7 +24,7 @@ steps: path: /pwenv timeout: 900s - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" id: ESP32 env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -45,7 +45,7 @@ steps: volumes: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" id: NRFConnect env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -66,7 +66,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" id: EFR32 env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -88,7 +88,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" id: Linux env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -141,7 +141,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" id: Android env: - PW_ENVIRONMENT_ROOT=/pwenv diff --git a/integrations/docker/images/base/chip-build/version b/integrations/docker/images/base/chip-build/version index 3c23aaad931620..2546ff1921d2dc 100644 --- a/integrations/docker/images/base/chip-build/version +++ b/integrations/docker/images/base/chip-build/version @@ -1 +1 @@ -90 : [Telink] Update Docker image (Zephyr update) +91 : [Ameba] Update matter timers and add more examples diff --git a/integrations/docker/images/chip-cert-bins/Dockerfile b/integrations/docker/images/chip-cert-bins/Dockerfile index 59c127dc1f8191..07c366231b8213 100644 --- a/integrations/docker/images/chip-cert-bins/Dockerfile +++ b/integrations/docker/images/chip-cert-bins/Dockerfile @@ -258,30 +258,36 @@ RUN apt-get update -y RUN apt-get install -y libssl-dev libdbus-1-dev libglib2.0-dev libavahi-client-dev avahi-utils iproute2 libcairo2-dev libgirepository1.0-dev python3-pip WORKDIR /root/ COPY --from=chip-build-cert-bins /root/.sdk-sha-version .sdk-sha-version -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-tool chip-tool -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-shell chip-shell -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-cert chip-cert -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-all-clusters-app chip-all-clusters-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-all-clusters-app-nlfaultinject chip-all-clusters-app-nlfaultinject -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-all-clusters-minimal-app chip-all-clusters-minimal-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-lighting-app chip-lighting-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-tv-casting-app chip-tv-casting-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-tv-app chip-tv-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-bridge-app chip-bridge-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/thermostat-app thermostat-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-ota-provider-app chip-ota-provider-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-ota-requestor-app chip-ota-requestor-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-lock-app chip-lock-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-app1 chip-app1 -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/lit-icd-app lit-icd-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-energy-management-app chip-energy-management-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-microwave-oven-app chip-microwave-oven-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-rvc-app chip-rvc-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/examples/fabric-admin/scripts/fabric-sync-app.py fabric-sync-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/fabric-bridge-app fabric-bridge-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/fabric-admin fabric-admin -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-lighting-data-model-no-unique-id-app chip-lighting-data-model-no-unique-id-app -COPY --from=chip-build-cert-bins /root/connectedhomeip/out/matter-network-manager-app matter-network-manager-app +RUN mkdir apps +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-tool apps/chip-tool +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-shell apps/chip-shell +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-cert apps/chip-cert +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-all-clusters-app apps/chip-all-clusters-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-all-clusters-app-nlfaultinject apps/hip-all-clusters-app-nlfaultinject +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-all-clusters-minimal-app apps/chip-all-clusters-minimal-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-lighting-app apps/chip-lighting-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-tv-casting-app apps/chip-tv-casting-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-tv-app apps/chip-tv-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-bridge-app apps/chip-bridge-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/thermostat-app apps/thermostat-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-ota-provider-app apps/chip-ota-provider-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-ota-requestor-app apps/chip-ota-requestor-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-lock-app apps/chip-lock-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-app1 apps/chip-app1 +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/lit-icd-app apps/lit-icd-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-energy-management-app apps/chip-energy-management-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-microwave-oven-app apps/chip-microwave-oven-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-rvc-app apps/chip-rvc-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/examples/fabric-admin/scripts/fabric-sync-app.py apps/fabric-sync-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/fabric-bridge-app apps/fabric-bridge-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/fabric-admin apps/fabric-admin +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/chip-lighting-data-model-no-unique-id-app apps/chip-lighting-data-model-no-unique-id-app +COPY --from=chip-build-cert-bins /root/connectedhomeip/out/matter-network-manager-app apps/matter-network-manager-app + +# Create symbolic links for now since this allows users to use existing configurations +# for running just `app-name` instead of `apps/app-name` +RUN ln -s apps/* . + # Stage 3.1: Setup the Matter Python environment COPY --from=chip-build-cert-bins /root/connectedhomeip/out/python_lib python_lib diff --git a/integrations/docker/images/stage-2/chip-build-ameba/Dockerfile b/integrations/docker/images/stage-2/chip-build-ameba/Dockerfile index 93217c332ef671..d3f8dadcb5332a 100644 --- a/integrations/docker/images/stage-2/chip-build-ameba/Dockerfile +++ b/integrations/docker/images/stage-2/chip-build-ameba/Dockerfile @@ -11,7 +11,7 @@ RUN set -x \ # Setup Ameba ARG AMEBA_DIR=/opt/ameba -ARG TAG_NAME=ameba_update_2024_03_22 +ARG TAG_NAME=ameba_update_2024_11_05 RUN set -x \ && apt-get update \ && mkdir ${AMEBA_DIR} \ diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index ff7dd298351688..0f80756ec49208 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -800,6 +800,8 @@ def BuildTelinkTarget(): target.AppendModifier('4mb', enable_4mb_flash=True) target.AppendModifier('mars', mars_board_config=True) target.AppendModifier('usb', usb_board_config=True) + target.AppendModifier('compress-lzma', compress_lzma_config=True) + target.AppendModifier('thread-analyzer', thread_analyzer_config=True) return target diff --git a/scripts/build/build_darwin_framework.py b/scripts/build/build_darwin_framework.py index d2d3665a1bcfd0..a048241ff1f396 100644 --- a/scripts/build/build_darwin_framework.py +++ b/scripts/build/build_darwin_framework.py @@ -91,7 +91,8 @@ def build_darwin_framework(args): 'CHIP_IS_ASAN': args.asan, 'CHIP_IS_BLE': args.ble, 'CHIP_IS_CLANG': args.clang, - 'CHIP_ENABLE_ENCODING_SENTINEL_ENUM_VALUES': args.enable_encoding_sentinel_enum_values + 'CHIP_ENABLE_ENCODING_SENTINEL_ENUM_VALUES': args.enable_encoding_sentinel_enum_values, + 'CHIP_USE_NETWORK_FRAMEWORK': args.use_network_framework } for option in options: command += ["{}={}".format(option, "YES" if options[option] else "NO")] @@ -176,6 +177,8 @@ def build_darwin_framework(args): parser.add_argument('--clang', action=argparse.BooleanOptionalAction) parser.add_argument('--enable-encoding-sentinel-enum-values', action=argparse.BooleanOptionalAction) parser.add_argument('--compdb', action=argparse.BooleanOptionalAction) + parser.add_argument('--use-network-framework', + action=argparse.BooleanOptionalAction) args = parser.parse_args() build_darwin_framework(args) diff --git a/scripts/build/builders/efr32.py b/scripts/build/builders/efr32.py index cb80eab890495d..871785fd2c9db8 100644 --- a/scripts/build/builders/efr32.py +++ b/scripts/build/builders/efr32.py @@ -337,7 +337,7 @@ def bundle_outputs(self): def generate(self): cmd = [ 'gn', 'gen', '--check', '--fail-on-unused-args', - '--export-compile-commands', + '--add-export-compile-commands=*', '--root=%s' % self.root ] if self.dotfile: diff --git a/scripts/build/builders/gn.py b/scripts/build/builders/gn.py index 6d9385bd4fc2aa..f65d8878c2ba60 100644 --- a/scripts/build/builders/gn.py +++ b/scripts/build/builders/gn.py @@ -55,7 +55,7 @@ def PostBuildCommand(self): def generate(self): cmd = [ 'gn', 'gen', '--check', '--fail-on-unused-args', - '--export-compile-commands', + '--add-export-compile-commands=*', '--root=%s' % self.root ] diff --git a/scripts/build/builders/host.py b/scripts/build/builders/host.py index 0ced1270fb583e..43b95b763278b8 100644 --- a/scripts/build/builders/host.py +++ b/scripts/build/builders/host.py @@ -354,6 +354,7 @@ def __init__(self, root, runner, app: HostApp, board=HostBoard.NATIVE, if not enable_ble: self.extra_gn_options.append('chip_config_network_layer_ble=false') + self.extra_gn_options.append('chip_enable_ble=false') if not enable_wifi: self.extra_gn_options.append('chip_enable_wifi=false') diff --git a/scripts/build/builders/nxp.py b/scripts/build/builders/nxp.py index fa24ef2d2d13ce..202c4e87ff4c98 100644 --- a/scripts/build/builders/nxp.py +++ b/scripts/build/builders/nxp.py @@ -421,7 +421,7 @@ def generate(self): elif self.build_system == NxpBuildSystem.GN: # add empty space at the end to avoid concatenation issue when there is no --args - cmd += 'gn gen --check --fail-on-unused-args --export-compile-commands --root=%s ' % self.root + cmd += 'gn gen --check --fail-on-unused-args --add-export-compile-commands=* --root=%s ' % self.root extra_args = [] diff --git a/scripts/build/builders/telink.py b/scripts/build/builders/telink.py index 1145b848a289b6..a4943007161f53 100644 --- a/scripts/build/builders/telink.py +++ b/scripts/build/builders/telink.py @@ -154,6 +154,8 @@ def __init__(self, enable_4mb_flash: bool = False, mars_board_config: bool = False, usb_board_config: bool = False, + compress_lzma_config: bool = False, + thread_analyzer_config: bool = False, ): super(TelinkBuilder, self).__init__(root, runner) self.app = app @@ -166,6 +168,8 @@ def __init__(self, self.enable_4mb_flash = enable_4mb_flash self.mars_board_config = mars_board_config self.usb_board_config = usb_board_config + self.compress_lzma_config = compress_lzma_config + self.thread_analyzer_config = thread_analyzer_config def get_cmd_prefixes(self): if not self._runner.dry_run: @@ -210,6 +214,12 @@ def generate(self): if self.usb_board_config: flags.append("-DTLNK_USB_DONGLE=y") + if self.compress_lzma_config: + flags.append("-DCONFIG_COMPRESS_LZMA=y") + + if self.thread_analyzer_config: + flags.append("-DCONFIG_THREAD_ANALYZER=y") + if self.options.pregen_dir: flags.append(f"-DCHIP_CODEGEN_PREGEN_DIR={shlex.quote(self.options.pregen_dir)}") diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index e58549453af58b..c473de1aa1d814 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -22,5 +22,5 @@ nuttx-x64-light qpg-qpg6105-{lock,light,shell,persistent-storage,light-switch,thermostat}[-updateimage] stm32-stm32wb5mm-dk-light tizen-arm-{all-clusters,chip-tool,light,tests}[-no-ble][-no-thread][-no-wifi][-asan][-ubsan][-coverage][-with-ui] -telink-{tlsr9118bdk40d,tlsr9518adk80d,tlsr9528a,tlsr9528a_retention,tlsr9258a,tlsr9258a_retention}-{air-quality-sensor,all-clusters,all-clusters-minimal,bridge,contact-sensor,light,light-switch,lock,ota-requestor,pump,pump-controller,shell,smoke-co-alarm,temperature-measurement,thermostat,window-covering}[-ota][-dfu][-shell][-rpc][-factory-data][-4mb][-mars][-usb] +telink-{tlsr9118bdk40d,tlsr9518adk80d,tlsr9528a,tlsr9528a_retention,tlsr9258a,tlsr9258a_retention}-{air-quality-sensor,all-clusters,all-clusters-minimal,bridge,contact-sensor,light,light-switch,lock,ota-requestor,pump,pump-controller,shell,smoke-co-alarm,temperature-measurement,thermostat,window-covering}[-ota][-dfu][-shell][-rpc][-factory-data][-4mb][-mars][-usb][-compress-lzma][-thread-analyzer] openiotsdk-{shell,lock}[-mbedtls][-psa] diff --git a/scripts/build/testdata/dry_run_efr32-brd4187c-light-rpc-no-version.txt b/scripts/build/testdata/dry_run_efr32-brd4187c-light-rpc-no-version.txt index d75eeabc3b6996..8d367e045510fb 100644 --- a/scripts/build/testdata/dry_run_efr32-brd4187c-light-rpc-no-version.txt +++ b/scripts/build/testdata/dry_run_efr32-brd4187c-light-rpc-no-version.txt @@ -2,7 +2,7 @@ cd "{root}" # Generating efr32-brd4187c-light-rpc-no-version -gn gen --check --fail-on-unused-args --export-compile-commands --root={root}/examples/lighting-app/silabs '--args=silabs_board="BRD4187C" is_debug=false import("//with_pw_rpc.gni") efr32_sdk_root="TEST_GSDK_ROOT" openthread_root="TEST_GSDK_ROOT/util/third_party/openthread" wiseconnect_sdk_root="TEST_WISECONNECT_SDK_ROOT" wifi_sdk_root="TEST_WIFI_SDK_ROOT"' {out}/efr32-brd4187c-light-rpc-no-version +gn gen --check --fail-on-unused-args '--add-export-compile-commands=*' --root={root}/examples/lighting-app/silabs '--args=silabs_board="BRD4187C" is_debug=false import("//with_pw_rpc.gni") efr32_sdk_root="TEST_GSDK_ROOT" openthread_root="TEST_GSDK_ROOT/util/third_party/openthread" wiseconnect_sdk_root="TEST_WISECONNECT_SDK_ROOT" wifi_sdk_root="TEST_WIFI_SDK_ROOT"' {out}/efr32-brd4187c-light-rpc-no-version # Building efr32-brd4187c-light-rpc-no-version ninja -C {out}/efr32-brd4187c-light-rpc-no-version diff --git a/scripts/build/testdata/dry_run_linux-arm64-chip-tool-ipv6only-clang.txt b/scripts/build/testdata/dry_run_linux-arm64-chip-tool-ipv6only-clang.txt index 58e095837e9a97..bcfce65eec65d8 100644 --- a/scripts/build/testdata/dry_run_linux-arm64-chip-tool-ipv6only-clang.txt +++ b/scripts/build/testdata/dry_run_linux-arm64-chip-tool-ipv6only-clang.txt @@ -4,7 +4,7 @@ cd "{root}" # Generating linux-arm64-chip-tool-ipv6only-clang bash -c ' PKG_CONFIG_PATH="SYSROOT_AARCH64/lib/aarch64-linux-gnu/pkgconfig" \ - gn gen --check --fail-on-unused-args --export-compile-commands --root={root}/examples/chip-tool '"'"'--args=chip_inet_config_enable_ipv4=false is_clang=true target_cpu="arm64" sysroot="SYSROOT_AARCH64"'"'"' {out}/linux-arm64-chip-tool-ipv6only-clang' + gn gen --check --fail-on-unused-args '"'"'--add-export-compile-commands=*'"'"' --root={root}/examples/chip-tool '"'"'--args=chip_inet_config_enable_ipv4=false is_clang=true target_cpu="arm64" sysroot="SYSROOT_AARCH64"'"'"' {out}/linux-arm64-chip-tool-ipv6only-clang' # Setting up Java deps third_party/java_deps/set_up_java_deps.sh diff --git a/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt b/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt index cc8ec0110ec923..dd9fd5f8e9622c 100644 --- a/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt +++ b/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt @@ -4,7 +4,7 @@ cd "{root}" # Generating linux-arm64-ota-requestor-nodeps-ipv6only bash -c ' PKG_CONFIG_PATH="SYSROOT_AARCH64/lib/aarch64-linux-gnu/pkgconfig" \ - gn gen --check --fail-on-unused-args --export-compile-commands --root={root}/examples/ota-requestor-app/linux '"'"'--args=chip_inet_config_enable_ipv4=false chip_config_network_layer_ble=false chip_enable_wifi=false chip_enable_openthread=false is_clang=true chip_crypto="mbedtls" target_cpu="arm64" sysroot="SYSROOT_AARCH64"'"'"' {out}/linux-arm64-ota-requestor-nodeps-ipv6only' + gn gen --check --fail-on-unused-args '"'"'--add-export-compile-commands=*'"'"' --root={root}/examples/ota-requestor-app/linux '"'"'--args=chip_inet_config_enable_ipv4=false chip_config_network_layer_ble=false chip_enable_ble=false chip_enable_wifi=false chip_enable_openthread=false is_clang=true chip_crypto="mbedtls" target_cpu="arm64" sysroot="SYSROOT_AARCH64"'"'"' {out}/linux-arm64-ota-requestor-nodeps-ipv6only' # Setting up Java deps third_party/java_deps/set_up_java_deps.sh diff --git a/scripts/build/testdata/dry_run_linux-x64-all-clusters-coverage.txt b/scripts/build/testdata/dry_run_linux-x64-all-clusters-coverage.txt index d2960f35542eba..00c4027603d13e 100644 --- a/scripts/build/testdata/dry_run_linux-x64-all-clusters-coverage.txt +++ b/scripts/build/testdata/dry_run_linux-x64-all-clusters-coverage.txt @@ -2,7 +2,7 @@ cd "{root}" # Generating linux-x64-all-clusters-coverage -gn gen --check --fail-on-unused-args --export-compile-commands --root={root}/examples/all-clusters-app/linux --args=use_coverage=true {out}/linux-x64-all-clusters-coverage +gn gen --check --fail-on-unused-args '--add-export-compile-commands=*' --root={root}/examples/all-clusters-app/linux --args=use_coverage=true {out}/linux-x64-all-clusters-coverage # Setting up Java deps third_party/java_deps/set_up_java_deps.sh diff --git a/scripts/build_python.sh b/scripts/build_python.sh index 7f03815f3fe7e3..649aeeeec19357 100755 --- a/scripts/build_python.sh +++ b/scripts/build_python.sh @@ -182,7 +182,7 @@ ninja -C "$OUTPUT_ROOT" python_wheels WHEEL=("$OUTPUT_ROOT"/controller/python/chip*.whl) # Add the matter_testing_infrastructure wheel -WHEEL+=("$OUTPUT_ROOT"/python/obj/src/python_testing/matter_testing_infrastructure/chip-testing._build_wheel/chip_testing-*.whl) +WHEEL+=("$OUTPUT_ROOT"/obj/src/python_testing/matter_testing_infrastructure/chip-testing._build_wheel/chip_testing*.whl) if [ "$install_pytest_requirements" = "yes" ]; then # Add the matter_yamltests_distribution wheel diff --git a/scripts/checkout_submodules.py b/scripts/checkout_submodules.py index 4d527148c7d9b0..78b51435eb64c1 100755 --- a/scripts/checkout_submodules.py +++ b/scripts/checkout_submodules.py @@ -113,7 +113,8 @@ def checkout_modules(modules: list, shallow: bool, force: bool, recursive: bool, names = ', '.join([module.name for module in modules]) logging.info(f'Checking out: {names}') - cmd = ['git', '-C', CHIP_ROOT, 'submodule', '--quiet', 'update', '--init'] + cmd = ['git', '-c', 'core.symlinks=true', '-C', CHIP_ROOT] + cmd += ['submodule', '--quiet', 'update', '--init'] cmd += ['--depth', '1'] if shallow else [] cmd += ['--force'] if force else [] cmd += ['--recursive'] if recursive else [] diff --git a/scripts/examples/gn_bouffalolab_example.sh b/scripts/examples/gn_bouffalolab_example.sh index 3942d796896027..79ccda9ae1f755 100755 --- a/scripts/examples/gn_bouffalolab_example.sh +++ b/scripts/examples/gn_bouffalolab_example.sh @@ -200,7 +200,7 @@ else example_dir=$MATTER_ROOT/examples/$example_name/bouffalolab/$bouffalo_chip output_dir=$MATTER_ROOT/$output_folder - gn gen --check --fail-on-unused-args --export-compile-commands --root="$example_dir" "$output_dir" --args="${optArgs[*]}" + gn gen --check --fail-on-unused-args --add-export-compile-commands=* --root="$example_dir" "$output_dir" --args="${optArgs[*]}" ninja -C "$output_dir" fi diff --git a/scripts/examples/gn_silabs_example.sh b/scripts/examples/gn_silabs_example.sh index bc06f8b2d28b0c..f68c938e579c45 100755 --- a/scripts/examples/gn_silabs_example.sh +++ b/scripts/examples/gn_silabs_example.sh @@ -340,7 +340,7 @@ else optArgs+="openthread_root=\"$GSDK_ROOT/util/third_party/openthread\" " fi - "$GN_PATH" gen --check --script-executable="$PYTHON_PATH" --fail-on-unused-args --export-compile-commands --root="$ROOT" --dotfile="$DOTFILE" --args="silabs_board=\"$SILABS_BOARD\" $optArgs" "$BUILD_DIR" + "$GN_PATH" gen --check --script-executable="$PYTHON_PATH" --fail-on-unused-args --add-export-compile-commands=* --root="$ROOT" --dotfile="$DOTFILE" --args="silabs_board=\"$SILABS_BOARD\" $optArgs" "$BUILD_DIR" if [ "$USE_SLC" == true ]; then # Activation needs to be after SLC generation which is done in gn gen. diff --git a/scripts/examples/gn_stm32_example.sh b/scripts/examples/gn_stm32_example.sh index 62c19cc3470de6..1167bd721dd54a 100755 --- a/scripts/examples/gn_stm32_example.sh +++ b/scripts/examples/gn_stm32_example.sh @@ -176,14 +176,14 @@ else BUILD_DIR=$OUTDIR/$STM32_BOARD echo BUILD_DIR="$BUILD_DIR" if [ "$USE_WIFI" == true ]; then - gn gen --check --fail-on-unused-args --export-compile-commands --root="$ROOT" --dotfile="$ROOT"/build_for_wifi_gnfile.gn --args="stm32_board=\"$STM32_BOARD\" $optArgs" "$BUILD_DIR" + gn gen --check --fail-on-unused-args --add-export-compile-commands=* --root="$ROOT" --dotfile="$ROOT"/build_for_wifi_gnfile.gn --args="stm32_board=\"$STM32_BOARD\" $optArgs" "$BUILD_DIR" else # thread build # if [ -z "$optArgs" ]; then - gn gen --check --fail-on-unused-args --export-compile-commands --root="$ROOT" --args="stm32_board=\"$STM32_BOARD\" treat_warnings_as_errors=false" --ide=json "$BUILD_DIR" + gn gen --check --fail-on-unused-args --add-export-compile-commands=* --root="$ROOT" --args="stm32_board=\"$STM32_BOARD\" treat_warnings_as_errors=false" --ide=json "$BUILD_DIR" else - gn gen --check --fail-on-unused-args --export-compile-commands --root="$ROOT" --args="stm32_board=\"$STM32_BOARD\" $optArgs treat_warnings_as_errors=false" --ide=json "$BUILD_DIR" + gn gen --check --fail-on-unused-args --add-export-compile-commands=* --root="$ROOT" --args="stm32_board=\"$STM32_BOARD\" $optArgs treat_warnings_as_errors=false" --ide=json "$BUILD_DIR" fi fi ninja -v -C "$BUILD_DIR"/ diff --git a/scripts/helpers/update_compile_commands.sh b/scripts/helpers/update_compile_commands.sh index 15b03c1799a0d7..d103a2a4183789 100755 --- a/scripts/helpers/update_compile_commands.sh +++ b/scripts/helpers/update_compile_commands.sh @@ -23,23 +23,23 @@ CHIP_ROOT="$(dirname "$0")/../.." source "$CHIP_ROOT/scripts/activate.sh" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=host_gcc +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:host_gcc" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.gcc.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=host_clang +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:host_clang" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.clang.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=host_gcc_mbedtls +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:host_gcc_mbedtls" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.mbedtls.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=android_x64 +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:android_x64" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.android_x64.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=android_arm64 +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:android_arm64" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.android_arm64.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=efr32_lock_app +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:efr32_lock_app" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.efr32.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=tizen_lighting_app +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:tizen_lighting_app" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.tizen_arm.json" diff --git a/scripts/tests/cirque_tests.sh b/scripts/tests/cirque_tests.sh index b7dcdbcab2ff6a..1a591bd30b0c3f 100755 --- a/scripts/tests/cirque_tests.sh +++ b/scripts/tests/cirque_tests.sh @@ -48,7 +48,7 @@ CIRQUE_TESTS=( "FailsafeTest" "MobileDeviceTest" "CommissioningTest" - "IcdWaitForActiveTest" + "IcdDeviceTest" "SplitCommissioningTest" "CommissioningFailureTest" "CommissioningFailureOnReportTest" diff --git a/scripts/tests/local.py b/scripts/tests/local.py index aaa4d88133a6dc..05cf2f129a05fb 100755 --- a/scripts/tests/local.py +++ b/scripts/tests/local.py @@ -31,8 +31,10 @@ import alive_progress import click +import colorama import coloredlogs import tabulate +import yaml # We compile for the local architecture. Figure out what platform we need @@ -43,12 +45,12 @@ def _get_native_machine_target(): """ current_system_info = platform.uname() arch = current_system_info.machine - if arch == 'x86_64': - arch = 'x64' - elif arch == 'i386' or arch == 'i686': - arch = 'x86' - elif arch in ('aarch64', 'aarch64_be', 'armv8b', 'armv8l'): - arch = 'arm64' + if arch == "x86_64": + arch = "x64" + elif arch == "i386" or arch == "i686": + arch = "x86" + elif arch in ("aarch64", "aarch64_be", "armv8b", "armv8l"): + arch = "arm64" return f"{current_system_info.system.lower()}-{arch}" @@ -94,6 +96,7 @@ class ExecutionTimeInfo: script: str duration_sec: float + status: str # Top level command, groups all other commands for the purpose of having @@ -165,14 +168,17 @@ def _do_build_apps(): f"{target_prefix}-all-clusters-no-ble-clang-boringssl", f"{target_prefix}-bridge-no-ble-clang-boringssl", f"{target_prefix}-energy-management-no-ble-clang-boringssl", + f"{target_prefix}-fabric-admin-no-ble-no-wifi-rpc-ipv6only-clang-boringssl", + f"{target_prefix}-fabric-bridge-no-ble-no-wifi-rpc-ipv6only-clang-boringssl", + f"{target_prefix}-light-data-model-no-unique-id-ipv6only-no-ble-no-wifi-clang", f"{target_prefix}-lit-icd-no-ble-clang-boringssl", f"{target_prefix}-lock-no-ble-clang-boringssl", f"{target_prefix}-microwave-oven-no-ble-clang-boringssl", + f"{target_prefix}-network-manager-ipv6only-no-ble-clang-boringssl", f"{target_prefix}-ota-provider-no-ble-clang-boringssl", f"{target_prefix}-ota-requestor-no-ble-clang-boringssl", f"{target_prefix}-rvc-no-ble-clang-boringssl", f"{target_prefix}-tv-app-no-ble-clang-boringssl", - f"{target_prefix}-network-manager-ipv6only-no-ble-clang-boringssl", ] cmd = ["./scripts/build/build_examples.py"] @@ -312,12 +318,24 @@ def _add_target_to_cmd(cmd, flag, path, runner): help="Don't actually execute the tests, just print out the command that would be run.", ) @click.option( - "--show_timings", + "--no-show-timings", default=False, is_flag=True, - show_default=True, help="At the end of the execution, show how many seconds each test took.", ) +@click.option( + "--keep-going", + default=False, + is_flag=True, + show_default=True, + help="Keep going on errors. Will report all failed tests at the end.", +) +@click.option( + "--fail-log-dir", + default=None, + help="Save failure logs into the specified directory instead of logging (as logging can be noisy/slow)", + type=click.Path(exists=True, file_okay=False, dir_okay=True), +) @click.option( "--runner", default="none", @@ -325,7 +343,14 @@ def _add_target_to_cmd(cmd, flag, path, runner): help="Determines the verbosity of script output", ) def python_tests( - test_filter, from_filter, from_skip_filter, dry_run, show_timings, runner + test_filter, + from_filter, + from_skip_filter, + dry_run, + no_show_timings, + runner, + keep_going, + fail_log_dir, ): """ Run python tests via `run_python_test.py` @@ -354,6 +379,11 @@ def as_runner(path): CHIP_RVC_APP: {as_runner(f'out/{target_prefix}-rvc-no-ble-clang-boringssl/chip-rvc-app')} NETWORK_MANAGEMENT_APP: { as_runner(f'out/{target_prefix}-network-manager-ipv6only-no-ble-clang-boringssl/matter-network-manager-app')} + FABRIC_ADMIN_APP: { + as_runner(f'out/{target_prefix}-fabric-admin-no-ble-no-wifi-rpc-ipv6only-clang-boringssl/fabric-admin')} + FABRIC_BRIDGE_APP: { + as_runner(f'out/{target_prefix}-fabric-bridge-no-ble-no-wifi-rpc-ipv6only-clang-boringssl/fabric-bridge-app')} + LIGHTING_APP_NO_UNIQUE_ID: {as_runner(f'out/{target_prefix}-light-data-model-no-unique-id-ipv6only-no-ble-no-wifi-clang/chip-lighting-app')} TRACE_APP: out/trace_data/app-{{SCRIPT_BASE_NAME}} TRACE_TEST_JSON: out/trace_data/test-{{SCRIPT_BASE_NAME}} TRACE_TEST_PERFETTO: out/trace_data/test-{{SCRIPT_BASE_NAME}} @@ -382,58 +412,13 @@ def as_runner(path): if not os.path.exists("out/trace_data"): os.mkdir("out/trace_data") - # IGNORES are taken out of `src/python_testing/execute_python_tests.py` in the SDK - excluded_patterns = { - "MinimalRepresentation.py", - "TC_CNET_4_4.py", - "TC_CCTRL_2_1.py", - "TC_CCTRL_2_2.py", - "TC_CCTRL_2_3.py", - "TC_DGGEN_3_2.py", - "TC_EEVSE_Utils.py", - "TC_ECOINFO_2_1.py", - "TC_ECOINFO_2_2.py", - "TC_EWATERHTRBase.py", - "TC_EWATERHTR_2_1.py", - "TC_EWATERHTR_2_2.py", - "TC_EWATERHTR_2_3.py", - "TC_EnergyReporting_Utils.py", - "TC_OpstateCommon.py", - "TC_pics_checker.py", - "TC_TMP_2_1.py", - "TC_MCORE_FS_1_1.py", - "TC_MCORE_FS_1_2.py", - "TC_MCORE_FS_1_3.py", - "TC_MCORE_FS_1_4.py", - "TC_MCORE_FS_1_5.py", - "TC_OCC_3_1.py", - "TC_OCC_3_2.py", - "TC_BRBINFO_4_1.py", - "TestCommissioningTimeSync.py", - "TestConformanceSupport.py", - "TestChoiceConformanceSupport.py", - "TC_DEMTestBase.py", - "choice_conformance_support.py", - "TestConformanceTest.py", # Unit test of the conformance test (TC_DeviceConformance) - does not run against an app. - "TestIdChecks.py", - "TestSpecParsingDeviceType.py", - "TestMatterTestingSupport.py", - "TestSpecParsingSupport.py", - "TestTimeSyncTrustedTimeSource.py", - "basic_composition_support.py", - "conformance_support.py", - "drlk_2_x_common.py", - "execute_python_tests.py", - "global_attribute_ids.py", - "hello_external_runner.py", - "hello_test.py", - "matter_testing_support.py", - "pics_support.py", - "spec_parsing_support.py", - "taglist_and_topology_test_support.py", - "test_plan_support.py", - "test_plan_table_generator.py", - } + metadata = yaml.full_load(open("src/python_testing/test_metadata.yaml")) + excluded_patterns = set([item["name"] for item in metadata["not_automated"]]) + + # NOTE: for slow tests. we add logs to not get impatient + slow_test_duration = dict( + [(item["name"], item["duration"]) for item in metadata["slow_tests"]] + ) if not os.path.isdir("src/python_testing"): raise Exception( @@ -448,32 +433,8 @@ def as_runner(path): test_scripts.append("src/controller/python/test/test_scripts/mobile-device-test.py") test_scripts.sort() # order consistent - # NOTE: VERY slow tests. we add logs to not get impatient - slow_test_duration = { - "mobile-device-test.py": "3 minutes", - "TC_AccessChecker.py": "1.5 minutes", - "TC_CADMIN_1_9.py": "40 seconds", - "TC_CC_2_2.py": "1.5 minutes", - "TC_DEM_2_10.py": "40 seconds", - "TC_DeviceBasicComposition.py": "25 seconds", - "TC_DRLK_2_12.py": "30 seconds", - "TC_DRLK_2_3.py": "30 seconds", - "TC_EEVSE_2_6.py": "30 seconds", - "TC_FAN_3_1.py": "15 seconds", - "TC_OPSTATE_2_5.py": "1.25 minutes", - "TC_OPSTATE_2_6.py": "35 seconds", - "TC_PS_2_3.py": "30 seconds", - "TC_RR_1_1.py": "25 seconds", - "TC_SWTCH.py": "1 minute", - "TC_TIMESYNC_2_10.py": "20 seconds", - "TC_TIMESYNC_2_11.py": "30 seconds", - "TC_TIMESYNC_2_12.py": "20 seconds", - "TC_TIMESYNC_2_7.py": "20 seconds", - "TC_TIMESYNC_2_8.py": "1.5 minutes", - "TC_ICDM_5_1.py": "TODO", - } - execution_times = [] + failed_tests = [] try: to_run = [] for script in fnmatch.filter(test_scripts, test_filter or "*.*"): @@ -524,12 +485,33 @@ def as_runner(path): if result.returncode != 0: logging.error("Test failed: %s", script) - logging.info("STDOUT:\n%s", result.stdout.decode("utf8")) - logging.warning("STDERR:\n%s", result.stderr.decode("utf8")) - sys.exit(1) + if fail_log_dir: + out_name = os.path.join(fail_log_dir, f"{base_name}.out.log") + err_name = os.path.join(fail_log_dir, f"{base_name}.err.log") + + logging.error("STDOUT IN %s", out_name) + logging.error("STDERR IN %s", err_name) + + with open(out_name, "wb") as f: + f.write(result.stdout) + with open(err_name, "wb") as f: + f.write(result.stdout) + + else: + logging.info("STDOUT:\n%s", result.stdout.decode("utf8")) + logging.warning("STDERR:\n%s", result.stderr.decode("utf8")) + if not keep_going: + sys.exit(1) + failed_tests.append(script) time_info = ExecutionTimeInfo( - script=base_name, duration_sec=(tend - tstart) + script=base_name, + duration_sec=(tend - tstart), + status=( + "PASS" + if result.returncode == 0 + else colorama.Fore.RED + "FAILURE" + colorama.Fore.RESET + ), ) execution_times.append(time_info) @@ -541,12 +523,25 @@ def as_runner(path): ) bar() finally: - if execution_times and show_timings: - execution_times.sort(key=lambda v: v.duration_sec) + if failed_tests and keep_going: + logging.error("FAILED TESTS:") + for name in failed_tests: + logging.error(" %s", name) + + if execution_times and not no_show_timings: + execution_times.sort( + key=lambda v: (0 if v.status == "PASS" else 1, v.duration_sec), + ) print( - tabulate.tabulate(execution_times, headers=["Script", "Duration(sec)"]) + tabulate.tabulate( + execution_times, headers=["Script", "Duration(sec)", "Status"] + ) ) + if failed_tests: + # Propagate the final failure + sys.exit(1) + def _do_build_fabric_sync_apps(): """ @@ -554,8 +549,8 @@ def _do_build_fabric_sync_apps(): """ target_prefix = _get_native_machine_target() targets = [ - f"{target_prefix}-fabric-bridge-boringssl-rpc-no-ble", - f"{target_prefix}-fabric-admin-boringssl-rpc", + f"{target_prefix}-fabric-admin-no-ble-no-wifi-rpc-ipv6only-clang-boringssl", + f"{target_prefix}-fabric-bridge-no-ble-no-wifi-rpc-ipv6only-clang-boringssl", f"{target_prefix}-all-clusters-boringssl-no-ble", ] @@ -698,7 +693,10 @@ def chip_tool_tests(target, target_glob, include_tags, expected_failures, runner target_prefix = _get_native_machine_target() cmd.extend( - ["--chip-tool", f"./out/{target_prefix}-chip-tool-no-ble-clang-boringssl/chip-tool"] + [ + "--chip-tool", + f"./out/{target_prefix}-chip-tool-no-ble-clang-boringssl/chip-tool", + ] ) if target is not None: diff --git a/scripts/tests/requirements.txt b/scripts/tests/requirements.txt index 9e2d8570359155..1fab1f84c7c77e 100644 --- a/scripts/tests/requirements.txt +++ b/scripts/tests/requirements.txt @@ -5,5 +5,6 @@ colorama coloredlogs diskcache mypy==1.10.1 +pyyaml tabulate websockets diff --git a/scripts/tools/telink/process_binaries.py b/scripts/tools/telink/process_binaries.py index 0f650e25427521..5144920dd86823 100755 --- a/scripts/tools/telink/process_binaries.py +++ b/scripts/tools/telink/process_binaries.py @@ -16,6 +16,7 @@ # limitations under the License. # +import lzma import os import subprocess import sys @@ -58,6 +59,45 @@ def merge_binaries(input_file1, input_file2, output_file, offset): # Obtain build configuration build_conf = BuildConfiguration(os.path.join(os.getcwd(), os.pardir)) + +def compress_lzma_firmware(input_file, output_file): + # Read the input firmware binary + with open(input_file, 'rb') as f: + firmware_data = f.read() # Read the rest of the file from the offset + + # Define the properties + lc = 1 # Literal context bits + lp = 2 # Literal position bits + pb = 0 # Position bits + dict_size = build_conf['CONFIG_COMPRESS_LZMA_DICTIONARY_SIZE'] # dictionary size + + # Create the LZMA compressor using the specified parameters + compressor = lzma.LZMACompressor( + format=lzma.FORMAT_RAW, # Use raw format to match with `lzma_raw_decoder()` in C + filters=[ + { + "id": lzma.FILTER_LZMA1, # Use LZMA1 filter for compatibility + "dict_size": dict_size, # Set dictionary size + "lc": lc, # Literal context bits + "lp": lp, # Literal position bits + "pb": pb, # Position bits + "mode": lzma.MODE_NORMAL, # Normal compression mode + "mf": lzma.MF_BT4, # Match finder algorithm + "depth": 0 # Default match finder depth + } + ] + ) + + # Compress the firmware data + compressed_data = compressor.compress(firmware_data) + compressor.flush() + + # Write the compressed binary to output file + with open(output_file, 'wb') as f: + f.write(compressed_data) + + print(f"Compressed {input_file} -> {output_file} (size reduced from {len(firmware_data)} to {len(compressed_data)} bytes)") + + # Clean up merged.bin from previous build if os.path.exists('merged.bin'): os.remove('merged.bin') @@ -83,7 +123,7 @@ def merge_binaries(input_file1, input_file2, output_file, offset): '--slot-size', str(build_conf['CONFIG_FLASH_LOAD_SIZE']), '--key', os.path.join(ZEPHYR_BASE, '../', build_conf['CONFIG_MCUBOOT_SIGNATURE_KEY_FILE']), 'merged.bin', - 'zephyr.signed.bin' + build_conf['CONFIG_SIGNED_OTA_IMAGE_FILE_NAME'] ] try: subprocess.run(sign_command, check=True) @@ -94,6 +134,31 @@ def merge_binaries(input_file1, input_file2, output_file, offset): # Merge MCUBoot binary if configured if build_conf.getboolean('CONFIG_BOOTLOADER_MCUBOOT'): merge_binaries('mcuboot.bin', 'zephyr.signed.bin', 'merged.bin', build_conf['CONFIG_FLASH_LOAD_OFFSET']) + if build_conf.getboolean('CONFIG_COMPRESS_LZMA'): + compress_lzma_firmware('zephyr.signed.bin', 'zephyr.signed.lzma.bin') + + sign_command = [ + 'python3', + os.path.join(ZEPHYR_BASE, '../bootloader/mcuboot/scripts/imgtool.py'), + 'sign', + '--version', '0.0.0+0', + '--align', '1', + '--header-size', str(build_conf['CONFIG_ROM_START_OFFSET']), + '--slot-size', str(build_conf['CONFIG_FLASH_LOAD_SIZE']), + '--key', os.path.join(ZEPHYR_BASE, '../', build_conf['CONFIG_MCUBOOT_SIGNATURE_KEY_FILE']), + '--pad-header', + 'zephyr.signed.lzma.bin', + build_conf['CONFIG_SIGNED_OTA_IMAGE_FILE_NAME'] + ] + + try: + subprocess.run(sign_command, check=True) + except subprocess.CalledProcessError as e: + raise RuntimeError(f"Error signing the image: {e}") + + if build_conf.getboolean('CONFIG_TELINK_OTA_BUTTON_TEST'): + merge_binaries('merged.bin', build_conf['CONFIG_SIGNED_OTA_IMAGE_FILE_NAME'], + 'merged.bin', build_conf['CONFIG_TELINK_OTA_PARTITION_ADDR']) # Merge Factory Data binary if configured if build_conf.getboolean('CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE'): diff --git a/src/BUILD.gn b/src/BUILD.gn index 722e0c8278582a..3676c92c97e8a4 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -100,7 +100,10 @@ if (chip_build_tests) { } if (chip_device_platform != "efr32") { - tests += [ "${chip_root}/src/app/tests" ] + tests += [ + "${chip_root}/src/app/tests", + "${chip_root}/src/app/util/persistence/tests", + ] # Disabled for EFR32 because _open is not implemented. # https://github.com/project-chip/connectedhomeip/issues/35624 diff --git a/src/access/BUILD.gn b/src/access/BUILD.gn index 3f3aaafe8a6a9b..66370090a4f582 100644 --- a/src/access/BUILD.gn +++ b/src/access/BUILD.gn @@ -78,3 +78,12 @@ static_library("access") { ] } } + +source_set("provider-impl") { + sources = [ "ProviderDeviceTypeResolver.h" ] + + public_deps = [ + ":access", + "${chip_root}/src/app/data-model-provider", + ] +} diff --git a/src/access/ProviderDeviceTypeResolver.h b/src/access/ProviderDeviceTypeResolver.h new file mode 100644 index 00000000000000..0a215d4a899930 --- /dev/null +++ b/src/access/ProviderDeviceTypeResolver.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include +#include + +namespace chip { +namespace Access { + +/// A device type resolver where the DataModel::Provider is fetched dynamically (may change over time) +class DynamicProviderDeviceTypeResolver : public chip::Access::AccessControl::DeviceTypeResolver +{ +public: + using ModelGetter = app::DataModel::Provider * (*) (); + + DynamicProviderDeviceTypeResolver(ModelGetter model) : mModelGetter(model) {} + + bool IsDeviceTypeOnEndpoint(chip::DeviceTypeId deviceType, chip::EndpointId endpoint) override + { + app::DataModel::Provider * model = mModelGetter(); + for (auto type = model->FirstDeviceType(endpoint); type.has_value(); type = model->NextDeviceType(endpoint, *type)) + { + if (type->deviceTypeId == deviceType) + { + return true; + } + } + return false; + } + +private: + ModelGetter mModelGetter; +}; + +} // namespace Access +} // namespace chip diff --git a/src/app/BUILD.gn b/src/app/BUILD.gn index 5fc0d0c8b97583..8b008c4e9b238b 100644 --- a/src/app/BUILD.gn +++ b/src/app/BUILD.gn @@ -186,7 +186,6 @@ static_library("interaction-model") { "WriteClient.h", "reporting/Engine.cpp", "reporting/Engine.h", - "reporting/Read.h", "reporting/ReportScheduler.h", "reporting/ReportSchedulerImpl.cpp", "reporting/ReportSchedulerImpl.h", @@ -199,8 +198,6 @@ static_library("interaction-model") { # # This breaks having `.h` and `.cpp` based off the same compilation unit and # should ideally be cleaned up. - "reporting/Read.cpp", - "reporting/Read.h", "reporting/reporting.h", ] @@ -267,6 +264,7 @@ static_library("interaction-model") { public_deps += [ ":global-attributes", "${chip_root}/src/access", + "${chip_root}/src/access:provider-impl", "${chip_root}/src/app/common:attribute-type", ] @@ -391,6 +389,18 @@ source_set("command-handler-impl") { ] } +source_set("attribute-persistence") { + sources = [ "SafeAttributePersistenceProvider.h" ] + + public_deps = [ + ":paths", + "${chip_root}/src/app/data-model:nullable", + "${chip_root}/src/app/util:types", + "${chip_root}/src/lib/support", + "${chip_root}/src/lib/support:span", + ] +} + # Note to developpers, instead of continuously adding files in the app librabry, it is recommand to create smaller source_sets that app can depend on. # This way, we can have a better understanding of dependencies and other componenets can depend on the different source_sets without needing to depend on the entire app library. static_library("app") { @@ -400,15 +410,10 @@ static_library("app") { "AttributePathExpandIterator.cpp", "AttributePathExpandIterator.h", "AttributePathExpandIterator.h", - "AttributePersistenceProvider.h", "ChunkedWriteCallback.cpp", "ChunkedWriteCallback.h", "CommandResponseHelper.h", "CommandResponseSender.cpp", - "DefaultAttributePersistenceProvider.cpp", - "DefaultAttributePersistenceProvider.h", - "DeferredAttributePersistenceProvider.cpp", - "DeferredAttributePersistenceProvider.h", "EventLogging.h", "EventManagement.cpp", "EventManagement.h", @@ -418,7 +423,6 @@ static_library("app") { "GenericEventManagementTestEventTriggerHandler.h", "OTAUserConsentCommon.h", "ReadHandler.cpp", - "SafeAttributePersistenceProvider.h", "TimerDelegates.cpp", "TimerDelegates.h", "WriteHandler.cpp", diff --git a/src/app/SafeAttributePersistenceProvider.h b/src/app/SafeAttributePersistenceProvider.h index 8d11d95d47b02d..b1e7148c79b1bb 100644 --- a/src/app/SafeAttributePersistenceProvider.h +++ b/src/app/SafeAttributePersistenceProvider.h @@ -18,12 +18,13 @@ #include #include #include -#include -#include #include #include #include +#include +#include + namespace chip { namespace app { diff --git a/src/app/chip_data_model.cmake b/src/app/chip_data_model.cmake index 75e2d8a349668a..0f628428952da8 100644 --- a/src/app/chip_data_model.cmake +++ b/src/app/chip_data_model.cmake @@ -164,6 +164,7 @@ function(chip_configure_data_model APP_TARGET) ${CHIP_APP_BASE_DIR}/util/generic-callback-stubs.cpp ${CHIP_APP_BASE_DIR}/util/privilege-storage.cpp ${CHIP_APP_BASE_DIR}/util/util.cpp + ${CHIP_APP_BASE_DIR}/util/persistence/DefaultAttributePersistenceProvider.cpp ${CODEGEN_DATA_MODEL_SOURCES} ${APP_GEN_FILES} ${APP_TEMPLATES_GEN_FILES} diff --git a/src/app/chip_data_model.gni b/src/app/chip_data_model.gni index 9f4ed594ccb912..3be8df5710616c 100644 --- a/src/app/chip_data_model.gni +++ b/src/app/chip_data_model.gni @@ -460,6 +460,7 @@ template("chip_data_model") { "${chip_root}/src/app/common:cluster-objects", "${chip_root}/src/app/common:enums", "${chip_root}/src/app/util:types", + "${chip_root}/src/app/util/persistence", "${chip_root}/src/controller", "${chip_root}/src/lib/core", "${chip_root}/src/lib/support", diff --git a/src/app/clusters/color-control-server/color-control-server.cpp b/src/app/clusters/color-control-server/color-control-server.cpp index d43590da31af93..a01de7fad22dcb 100644 --- a/src/app/clusters/color-control-server/color-control-server.cpp +++ b/src/app/clusters/color-control-server/color-control-server.cpp @@ -307,14 +307,14 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl { case EnhancedColorMode::kCurrentHueAndCurrentSaturation: #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV - ColorControlServer::Instance().moveToSaturation(static_cast(colorSaturationTransitionState->finalValue), - transitionTime10th, endpoint); + ColorControlServer::Instance().moveToSaturation( + endpoint, static_cast(colorSaturationTransitionState->finalValue), transitionTime10th); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV break; case EnhancedColorMode::kCurrentXAndCurrentY: #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY - ColorControlServer::Instance().moveToColor(colorXTransitionState->finalValue, colorYTransitionState->finalValue, - transitionTime10th, endpoint); + ColorControlServer::Instance().moveToColor(endpoint, colorXTransitionState->finalValue, + colorYTransitionState->finalValue, transitionTime10th); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY break; case EnhancedColorMode::kColorTemperatureMireds: @@ -326,8 +326,8 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl case EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation: #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV ColorControlServer::Instance().moveToHueAndSaturation( - colorHueTransitionState->finalEnhancedHue, static_cast(colorSaturationTransitionState->finalValue), - transitionTime10th, true, endpoint); + endpoint, colorHueTransitionState->finalEnhancedHue, + static_cast(colorSaturationTransitionState->finalValue), transitionTime10th, true); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV break; default: @@ -470,11 +470,9 @@ Status ColorControlServer::stopAllColorTransitions(EndpointId endpoint) return Status::Success; } -bool ColorControlServer::stopMoveStepCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - BitMask optionsMask, BitMask optionsOverride) +Status ColorControlServer::stopMoveStepCommand(EndpointId endpoint, const Commands::StopMoveStep::DecodableType & commandData) { - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; + Status status = Status::Success; // StopMoveStep command has no effect on an active color loop. // Fetch if it is supported and active. @@ -488,7 +486,7 @@ bool ColorControlServer::stopMoveStepCommand(app::CommandHandler * commandObj, c } } - if (shouldExecuteIfOff(endpoint, optionsMask, optionsOverride) && !isColorLoopActive) + if (shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride) && !isColorLoopActive) { status = stopAllColorTransitions(endpoint); @@ -507,8 +505,7 @@ bool ColorControlServer::stopMoveStepCommand(app::CommandHandler * commandObj, c #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV } - commandObj->AddStatus(commandPath, status); - return true; + return status; } bool ColorControlServer::shouldExecuteIfOff(EndpointId endpoint, BitMask optionMask, @@ -1261,15 +1258,15 @@ EmberEventControl * ColorControlServer::configureHSVEventControl(EndpointId endp } /** - * @brief executes move to saturation command + * @brief Executes move to saturation command * - * @param saturation target saturation - * @param transitionTime transition time in 10th of seconds - * @param endpoint target endpoint where to execute move - * @return Status::Success if successful,Status::UnsupportedEndpoint if the saturation transition state doesn't exist, - * Status::ConstraintError if the saturation is above maximum + * @param endpoint Target endpoint where to execute move + * @param saturation Target saturation + * @param transitionTime Transition time in 10th of seconds + * @return Status::Success When successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a saturation transition state. */ -Status ColorControlServer::moveToSaturation(uint8_t saturation, uint16_t transitionTime, EndpointId endpoint) +Status ColorControlServer::moveToSaturation(EndpointId endpoint, uint8_t saturation, uint16_t transitionTime) { Color16uTransitionState * colorSaturationTransitionState = getSaturationTransitionState(endpoint); VerifyOrReturnError(nullptr != colorSaturationTransitionState, Status::UnsupportedEndpoint); @@ -1300,19 +1297,19 @@ Status ColorControlServer::moveToSaturation(uint8_t saturation, uint16_t transit } /** - * @brief executes move to hue and saturatioan command + * @brief Executes move to hue and saturatioan command. * - * @param[in] hue target hue - * @param[in] saturation target saturation - * @param[in] transitionTime transition time in 10th of seconds + * @param[in] endpoint EndpointId of the recipient Color control cluster. + * @param[in] hue Target hue. + * @param[in] saturation Target saturation. + * @param[in] transitionTime Transition time in 10th of seconds. * @param[in] isEnhanced If True, function was called by EnhancedMoveHue command and rate is a uint16 value. If False function - * was called by MoveHue command and rate is a uint8 value - * @param[in] endpoint - * @return Status::Success if successful,Status::UnsupportedEndpoint if the saturation transition state doesn't exist, - * Status::ConstraintError if the saturation is above maximum + * was called by MoveHue command and rate is a uint8 value. + * @return Status::Success When successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a saturation transition state, */ -Status ColorControlServer::moveToHueAndSaturation(uint16_t hue, uint8_t saturation, uint16_t transitionTime, bool isEnhanced, - EndpointId endpoint) +Status ColorControlServer::moveToHueAndSaturation(EndpointId endpoint, uint16_t hue, uint8_t saturation, uint16_t transitionTime, + bool isEnhanced) { uint16_t currentHue = 0; uint16_t halfWay = isEnhanced ? HALF_MAX_UINT16T : HALF_MAX_UINT8T; @@ -1389,44 +1386,35 @@ Status ColorControlServer::moveToHueAndSaturation(uint16_t hue, uint8_t saturati } /** - * @brief Executes move Hue Command + * @brief Executes move Hue Command. * - * @param[in] endpoint + * @param[in] endpoint EndpointId of the recipient Color control cluster. * @param[in] moveMode * @param[in] rate * @param[in] optionsMask * @param[in] optionsOverride * @param[in] isEnhanced If True, function was called by EnhancedMoveHue command and rate is a uint16 value. If False function - * was called by MoveHue command and rate is a uint8 value - * @return true Success - * @return false Failed + * was called by MoveHue command and rate is a uint8 value. + * @return Status::Success when successful, + * Status::InvalidCommand when Rate is 0 or an unknown moveMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a hue transition state, */ -bool ColorControlServer::moveHueCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - HueMoveMode moveMode, uint16_t rate, BitMask optionsMask, - BitMask optionsOverride, bool isEnhanced) +Status ColorControlServer::moveHueCommand(EndpointId endpoint, HueMoveMode moveMode, uint16_t rate, + BitMask optionsMask, BitMask optionsOverride, + bool isEnhanced) { MATTER_TRACE_SCOPE("moveHue", "ColorControl"); - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - - uint16_t epIndex = getEndpointIndex(endpoint); - ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionStateByIndex(epIndex); - - VerifyOrExit(colorHueTransitionState != nullptr, status = Status::UnsupportedEndpoint); // check moveMode and rate before any operation is done on the transition states // rate value is ignored if the MoveMode is stop - if (moveMode == HueMoveMode::kUnknownEnumValue || (rate == 0 && moveMode != HueMoveMode::kStop)) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } + VerifyOrReturnValue(moveMode != HueMoveMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue((rate != 0 || moveMode == HueMoveMode::kStop), Status::InvalidCommand); - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + uint16_t epIndex = getEndpointIndex(endpoint); + ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionStateByIndex(epIndex); + VerifyOrReturnValue(colorHueTransitionState != nullptr, Status::UnsupportedEndpoint); + + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, optionsMask, optionsOverride), Status::Success); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); @@ -1438,8 +1426,7 @@ bool ColorControlServer::moveHueCommand(app::CommandHandler * commandObj, const // Per spec any saturation transition must also be cancelled. Color16uTransitionState * saturationState = getSaturationTransitionStateByIndex(epIndex); initSaturationTransitionState(endpoint, saturationState); - commandObj->AddStatus(commandPath, Status::Success); - return true; + return Status::Success; } // Handle color mode transition, if necessary. @@ -1491,50 +1478,42 @@ bool ColorControlServer::moveHueCommand(app::CommandHandler * commandObj, const // kick off the state machine: scheduleTimerCallbackMs(configureHSVEventControl(endpoint), TRANSITION_UPDATE_TIME_MS.count()); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } /** - * @brief Executes move to hue command + * @brief Executes move to hue command. * - * @param[in] endpoint + * @param[in] endpoint EndpointId of the recipient Color control cluster. * @param[in] hue - * @param[in] hueMoveMode + * @param[in] moveDirection * @param[in] transitionTime * @param[in] optionsMask * @param[in] optionsOverride * @param[in] isEnhanced If True, function was called by EnhancedMoveHue command and rate is a uint16 value. If False function - * was called by MoveHue command and rate is a uint8 value - * @return true Success - * @return false Failed + * was called by MoveHue command and rate is a uint8 value. + * @return Status::Success when successful, + * Status::InvalidCommand when Rate is 0 or an unknown moveDirection is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a hue transition state, + * Status::ConstraintError when the other parameters are outside their defined value range. */ -bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - uint16_t hue, DirectionEnum moveDirection, uint16_t transitionTime, - BitMask optionsMask, BitMask optionsOverride, - bool isEnhanced) +Status ColorControlServer::moveToHueCommand(EndpointId endpoint, uint16_t hue, DirectionEnum moveDirection, uint16_t transitionTime, + BitMask optionsMask, BitMask optionsOverride, + bool isEnhanced) { MATTER_TRACE_SCOPE("moveToHue", "ColorControl"); - EndpointId endpoint = commandPath.mEndpointId; + VerifyOrReturnValue(moveDirection != DirectionEnum::kUnknownEnumValue, Status::InvalidCommand); - Status status = Status::Success; - uint16_t currentHue = 0; - DirectionEnum direction; + // Command Parameters constraint checks: + VerifyOrReturnValue((isEnhanced || hue <= MAX_HUE_VALUE), Status::ConstraintError); ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionState(endpoint); + VerifyOrReturnValue(colorHueTransitionState != nullptr, Status::UnsupportedEndpoint); - VerifyOrExit(colorHueTransitionState != nullptr, status = Status::UnsupportedEndpoint); - - // Standard Hue limit checking: hue is 0..254. Spec dictates we ignore - // this and report a constraint error. - if (!isEnhanced && (hue > MAX_HUE_VALUE)) - { - commandObj->AddStatus(commandPath, Status::ConstraintError); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, optionsMask, optionsOverride), Status::Success); + uint16_t currentHue = 0; + DirectionEnum direction; if (isEnhanced) { Attributes::EnhancedCurrentHue::Get(endpoint, ¤tHue); @@ -1543,7 +1522,6 @@ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, cons { uint8_t current8bitHue = 0; Attributes::CurrentHue::Get(endpoint, ¤t8bitHue); - currentHue = static_cast(current8bitHue); } @@ -1577,18 +1555,11 @@ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, cons direction = moveDirection; break; case DirectionEnum::kUnknownEnumValue: - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; + return Status::InvalidCommand; /* No default case, so if a new direction value gets added we will just fail to compile until we handle it correctly. */ } - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } - // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); @@ -1626,57 +1597,43 @@ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, cons // kick off the state machine: scheduleTimerCallbackMs(configureHSVEventControl(endpoint), transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } /** - * @brief executes move to hue and saturatioan command - * - * @param[in] commandObj - * @param[in] commandPath + * @brief Executes move to hue and saturatioan command. + * @param[in] endpoint EndpointId of the recipient Color control cluster. * @param[in] hue * @param[in] saturation * @param[in] transitionTime * @param[in] optionsMask * @param[in] optionsOverride * @param[in] isEnhanced If True, function was called by EnhancedMoveHue command and rate is a uint16 value. If False function - * was called by MoveHue command and rate is a uint8 value - * @return true Success - * @return false Failed + * was called by MoveHue command and rate is a uint8 value. + * @return Status::Success when successful, + * Status::ConstraintError when the other parameters are outside their defined value range. + */ -bool ColorControlServer::moveToHueAndSaturationCommand(app::CommandHandler * commandObj, - const app::ConcreteCommandPath & commandPath, uint16_t hue, - uint8_t saturation, uint16_t transitionTime, - BitMask optionsMask, BitMask optionsOverride, - bool isEnhanced) +Status ColorControlServer::moveToHueAndSaturationCommand(EndpointId endpoint, uint16_t hue, uint8_t saturation, + uint16_t transitionTime, BitMask optionsMask, + BitMask optionsOverride, bool isEnhanced) { MATTER_TRACE_SCOPE("moveToHueAndSaturation", "ColorControl"); - // limit checking: hue and saturation are 0..254. Spec dictates we ignore - // this and report a constraint error. - if ((!isEnhanced && hue > MAX_HUE_VALUE) || saturation > MAX_SATURATION_VALUE) - { - commandObj->AddStatus(commandPath, Status::ConstraintError); - return true; - } + // Command Parameters constraint checks: + VerifyOrReturnValue((isEnhanced || hue <= MAX_HUE_VALUE), Status::ConstraintError); + VerifyOrReturnValue(saturation <= MAX_SATURATION_VALUE, Status::ConstraintError); - if (!shouldExecuteIfOff(commandPath.mEndpointId, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } - Status status = moveToHueAndSaturation(hue, saturation, transitionTime, isEnhanced, commandPath.mEndpointId); + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, optionsMask, optionsOverride), Status::Success); + + Status status = moveToHueAndSaturation(endpoint, hue, saturation, transitionTime, isEnhanced); #ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT - ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); + ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); #endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT - commandObj->AddStatus(commandPath, status); - return true; + return status; } /** - * @brief Executes step hue command + * @brief Executes step hue command. * * @param[in] endpoint * @param[in] stepMode @@ -1685,34 +1642,24 @@ bool ColorControlServer::moveToHueAndSaturationCommand(app::CommandHandler * com * @param[in] optionsMask * @param[in] optionsOverride * @param[in] isEnhanced If True, function was called by EnhancedMoveHue command and rate is a uint16 value. If False function - * was called by MoveHue command and rate is a uint8 value - * @return true Success - * @return false Failed + * was called by MoveHue command and rate is a uint8 value. + * @return Status::Success when successful, + * Status::InvalidCommand when StepSize is 0 or an unknown HueStepMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a hue transition state. */ -bool ColorControlServer::stepHueCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - HueStepMode stepMode, uint16_t stepSize, uint16_t transitionTime, - BitMask optionsMask, BitMask optionsOverride, bool isEnhanced) +Status ColorControlServer::stepHueCommand(EndpointId endpoint, HueStepMode stepMode, uint16_t stepSize, uint16_t transitionTime, + BitMask optionsMask, BitMask optionsOverride, + bool isEnhanced) { MATTER_TRACE_SCOPE("stepHue", "ColorControl"); - EndpointId endpoint = commandPath.mEndpointId; - - Status status = Status::Success; + // Confirm validity of the step mode and step size received + VerifyOrReturnValue(stepMode != HueStepMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue(stepSize != 0, Status::InvalidCommand); ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionState(endpoint); - VerifyOrExit(colorHueTransitionState != nullptr, status = Status::UnsupportedEndpoint); + VerifyOrReturnValue(colorHueTransitionState != nullptr, Status::UnsupportedEndpoint); - // Confirm validity of the step mode and step size received - if (stepMode == HueStepMode::kUnknownEnumValue || stepSize == 0) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } - - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, optionsMask, optionsOverride), Status::Success); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); @@ -1770,71 +1717,55 @@ bool ColorControlServer::stepHueCommand(app::CommandHandler * commandObj, const // kick off the state machine: scheduleTimerCallbackMs(configureHSVEventControl(endpoint), transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } -bool ColorControlServer::moveSaturationCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveSaturation::DecodableType & commandData) +/** + * @brief Executes moveSaturation command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::InvalidCommand when a rate of 0 for a non-stop move or an unknown SaturationMoveMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a saturation transition state. + */ +Status ColorControlServer::moveSaturationCommand(EndpointId endpoint, const Commands::MoveSaturation::DecodableType & commandData) { MATTER_TRACE_SCOPE("moveSaturation", "ColorControl"); - auto & moveMode = commandData.moveMode; - auto & rate = commandData.rate; - auto & optionsMask = commandData.optionsMask; - auto & optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - - uint16_t epIndex = getEndpointIndex(endpoint); - Color16uTransitionState * colorSaturationTransitionState = getSaturationTransitionStateByIndex(epIndex); - VerifyOrExit(colorSaturationTransitionState != nullptr, status = Status::UnsupportedEndpoint); - // check moveMode and rate before any operation is done on the transition states // rate value is ignored if the MoveMode is stop - if (moveMode == SaturationMoveMode::kUnknownEnumValue || (rate == 0 && moveMode != SaturationMoveMode::kStop)) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } + VerifyOrReturnValue(commandData.moveMode != SaturationMoveMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue(commandData.rate != 0 || commandData.moveMode == SaturationMoveMode::kStop, Status::InvalidCommand); - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } - - uint16_t transitionTime; + uint16_t epIndex = getEndpointIndex(endpoint); + Color16uTransitionState * colorSaturationTransitionState = getSaturationTransitionStateByIndex(epIndex); + VerifyOrReturnValue(colorSaturationTransitionState != nullptr, Status::UnsupportedEndpoint); + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); - // now, kick off the state machine. initSaturationTransitionState(endpoint, colorSaturationTransitionState); - - if (moveMode == SaturationMoveMode::kStop) + if (commandData.moveMode == SaturationMoveMode::kStop) { // Per spec any hue transition must also be cancelled. ColorHueTransitionState * hueState = getColorHueTransitionStateByIndex(epIndex); initHueTransitionState(endpoint, hueState, false /*isEnhancedHue don't care*/); - commandObj->AddStatus(commandPath, Status::Success); - return true; + return Status::Success; } // Handle color mode transition, if necessary. handleModeSwitch(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation); - if (moveMode == SaturationMoveMode::kUp) + if (commandData.moveMode == SaturationMoveMode::kUp) { colorSaturationTransitionState->finalValue = MAX_SATURATION_VALUE; } - else if (moveMode == SaturationMoveMode::kDown) + else if (commandData.moveMode == SaturationMoveMode::kDown) { colorSaturationTransitionState->finalValue = MIN_SATURATION_VALUE; } - transitionTime = computeTransitionTimeFromStateAndRate(colorSaturationTransitionState, rate); - + uint16_t transitionTime = computeTransitionTimeFromStateAndRate(colorSaturationTransitionState, commandData.rate); colorSaturationTransitionState->stepsRemaining = transitionTime; colorSaturationTransitionState->stepsTotal = transitionTime; colorSaturationTransitionState->timeRemaining = transitionTime; @@ -1847,97 +1778,72 @@ bool ColorControlServer::moveSaturationCommand(app::CommandHandler * commandObj, // kick off the state machine: scheduleTimerCallbackMs(configureHSVEventControl(endpoint), TRANSITION_UPDATE_TIME_MS.count()); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } /** - * @brief executes move to saturation command - * - * @param commandObj - * @param commandPath - * @param commandData - * @return true - * @return false + * @brief Executes move to saturation command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a saturation transition state (verified in + * moveToSaturation function) Status::ConstraintError when a command parameters is outside its defined value range. */ -bool ColorControlServer::moveToSaturationCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveToSaturation::DecodableType & commandData) +Status ColorControlServer::moveToSaturationCommand(EndpointId endpoint, + const Commands::MoveToSaturation::DecodableType & commandData) { MATTER_TRACE_SCOPE("moveToSaturation", "ColorControl"); - // limit checking: saturation is 0..254. Spec dictates we ignore - // this and report a malformed packet. - if (commandData.saturation > MAX_SATURATION_VALUE) - { - commandObj->AddStatus(commandPath, Status::ConstraintError); - return true; - } + // Command Parameters constraint checks: + VerifyOrReturnValue(commandData.saturation <= MAX_SATURATION_VALUE, Status::ConstraintError); - if (!shouldExecuteIfOff(commandPath.mEndpointId, commandData.optionsMask, commandData.optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } - Status status = moveToSaturation(commandData.saturation, commandData.transitionTime, commandPath.mEndpointId); + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); + Status status = moveToSaturation(endpoint, commandData.saturation, commandData.transitionTime); #ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT - ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); + ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); #endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT - commandObj->AddStatus(commandPath, status); - return true; + return status; } -bool ColorControlServer::stepSaturationCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::StepSaturation::DecodableType & commandData) +/** + * @brief Executes step saturation command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::InvalidCommand when a step size of 0 or an unknown SaturationStepMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a saturation transition state. + */ +Status ColorControlServer::stepSaturationCommand(EndpointId endpoint, const Commands::StepSaturation::DecodableType & commandData) { MATTER_TRACE_SCOPE("stepSaturation", "ColorControl"); - auto stepMode = commandData.stepMode; - uint8_t stepSize = commandData.stepSize; - uint8_t transitionTime = commandData.transitionTime; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint8_t currentSaturation = 0; + // Confirm validity of the step mode and step size received + VerifyOrReturnValue(commandData.stepMode != SaturationStepMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue(commandData.stepSize != 0, Status::InvalidCommand); Color16uTransitionState * colorSaturationTransitionState = getSaturationTransitionState(endpoint); - VerifyOrExit(colorSaturationTransitionState != nullptr, status = Status::UnsupportedEndpoint); - - // Confirm validity of the step mode and step size received - if (stepMode == SaturationStepMode::kUnknownEnumValue || stepSize == 0) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } + VerifyOrReturnValue(colorSaturationTransitionState != nullptr, Status::UnsupportedEndpoint); - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); - // Handle color mode transition, if necessary. handleModeSwitch(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation); - // now, kick off the state machine. initSaturationTransitionState(endpoint, colorSaturationTransitionState); - currentSaturation = static_cast(colorSaturationTransitionState->currentValue); + uint8_t currentSaturation = static_cast(colorSaturationTransitionState->currentValue); - if (stepMode == SaturationStepMode::kUp) + if (commandData.stepMode == SaturationStepMode::kUp) { - colorSaturationTransitionState->finalValue = addSaturation(currentSaturation, stepSize); + colorSaturationTransitionState->finalValue = addSaturation(currentSaturation, commandData.stepSize); } - else if (stepMode == SaturationStepMode::kDown) + else if (commandData.stepMode == SaturationStepMode::kDown) { - colorSaturationTransitionState->finalValue = subtractSaturation(currentSaturation, stepSize); + colorSaturationTransitionState->finalValue = subtractSaturation(currentSaturation, commandData.stepSize); } - colorSaturationTransitionState->stepsRemaining = std::max(transitionTime, 1); + colorSaturationTransitionState->stepsRemaining = std::max(commandData.transitionTime, 1); colorSaturationTransitionState->stepsTotal = colorSaturationTransitionState->stepsRemaining; - colorSaturationTransitionState->timeRemaining = transitionTime; - colorSaturationTransitionState->transitionTime = transitionTime; + colorSaturationTransitionState->timeRemaining = commandData.transitionTime; + colorSaturationTransitionState->transitionTime = commandData.transitionTime; colorSaturationTransitionState->endpoint = endpoint; colorSaturationTransitionState->lowLimit = MIN_SATURATION_VALUE; colorSaturationTransitionState->highLimit = MAX_SATURATION_VALUE; @@ -1945,65 +1851,52 @@ bool ColorControlServer::stepSaturationCommand(app::CommandHandler * commandObj, SetHSVRemainingTime(endpoint); // kick off the state machine: - scheduleTimerCallbackMs(configureHSVEventControl(endpoint), transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + scheduleTimerCallbackMs(configureHSVEventControl(endpoint), commandData.transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); + return Status::Success; } -bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::ColorLoopSet::DecodableType & commandData) +/** + * @brief Executes ColorLoop command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::InvalidCommand when an unknown action or direction is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a hue transition state. + */ +Status ColorControlServer::colorLoopCommand(EndpointId endpoint, const Commands::ColorLoopSet::DecodableType & commandData) { MATTER_TRACE_SCOPE("colorLoop", "ColorControl"); - auto updateFlags = commandData.updateFlags; - auto action = commandData.action; - auto direction = commandData.direction; - uint16_t time = commandData.time; - uint16_t startHue = commandData.startHue; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint8_t isColorLoopActive = 0; - uint8_t deactiveColorLoop = 0; + // Validate the action and direction parameters of the command + VerifyOrReturnValue(commandData.action != ColorLoopActionEnum::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue(commandData.direction != ColorLoopDirectionEnum::kUnknownEnumValue, Status::InvalidCommand); uint16_t epIndex = getEndpointIndex(endpoint); ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionStateByIndex(epIndex); - VerifyOrExit(colorHueTransitionState != nullptr, status = Status::UnsupportedEndpoint); - - // Validate the action and direction parameters of the command - if (action == ColorLoopActionEnum::kUnknownEnumValue || direction == ColorLoopDirectionEnum::kUnknownEnumValue) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } + VerifyOrReturnValue(colorHueTransitionState != nullptr, Status::UnsupportedEndpoint); - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); + uint8_t isColorLoopActive = 0; // In case of get failure, isColorLoopActive will remain at the init value 0 (not active) if (Attributes::ColorLoopActive::Get(endpoint, &isColorLoopActive) != Status::Success) { ChipLogError(Zcl, "Failed to retrieve ColorLoopActive value"); } - deactiveColorLoop = updateFlags.Has(ColorLoopUpdateFlags::kUpdateAction) && (action == ColorLoopAction::kDeactivate); + uint8_t deactiveColorLoop = + commandData.updateFlags.Has(ColorLoopUpdateFlags::kUpdateAction) && (commandData.action == ColorLoopAction::kDeactivate); - if (updateFlags.Has(ColorLoopUpdateFlags::kUpdateDirection)) + if (commandData.updateFlags.Has(ColorLoopUpdateFlags::kUpdateDirection)) { - Attributes::ColorLoopDirection::Set(endpoint, to_underlying(direction)); + Attributes::ColorLoopDirection::Set(endpoint, to_underlying(commandData.direction)); // Checks if color loop is active and stays active if (isColorLoopActive && !deactiveColorLoop) { - colorHueTransitionState->up = (direction == ColorLoopDirectionEnum::kIncrement); + colorHueTransitionState->up = (commandData.direction == ColorLoopDirectionEnum::kIncrement); colorHueTransitionState->initialEnhancedHue = colorHueTransitionState->currentEnhancedHue; - if (direction == ColorLoopDirectionEnum::kIncrement) + if (commandData.direction == ColorLoopDirectionEnum::kIncrement) { colorHueTransitionState->finalEnhancedHue = static_cast(colorHueTransitionState->initialEnhancedHue - 1); } @@ -2015,14 +1908,14 @@ bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, cons } } - if (updateFlags.Has(ColorLoopUpdateFlags::kUpdateTime)) + if (commandData.updateFlags.Has(ColorLoopUpdateFlags::kUpdateTime)) { - Attributes::ColorLoopTime::Set(endpoint, time); + Attributes::ColorLoopTime::Set(endpoint, commandData.time); // Checks if color loop is active and stays active if (isColorLoopActive && !deactiveColorLoop) { - colorHueTransitionState->stepsTotal = static_cast(time * TRANSITION_STEPS_PER_1S); + colorHueTransitionState->stepsTotal = static_cast(commandData.time * TRANSITION_STEPS_PER_1S); colorHueTransitionState->initialEnhancedHue = colorHueTransitionState->currentEnhancedHue; if (colorHueTransitionState->up) @@ -2037,14 +1930,14 @@ bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, cons } } - if (updateFlags.Has(ColorLoopUpdateFlags::kUpdateStartHue)) + if (commandData.updateFlags.Has(ColorLoopUpdateFlags::kUpdateStartHue)) { - Attributes::ColorLoopStartEnhancedHue::Set(endpoint, startHue); + Attributes::ColorLoopStartEnhancedHue::Set(endpoint, commandData.startHue); } - if (updateFlags.Has(ColorLoopUpdateFlags::kUpdateAction)) + if (commandData.updateFlags.Has(ColorLoopUpdateFlags::kUpdateAction)) { - if (action == ColorLoopAction::kDeactivate) + if (commandData.action == ColorLoopAction::kDeactivate) { if (isColorLoopActive) { @@ -2063,26 +1956,24 @@ bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, cons // Do Nothing since it's not on } } - else if (action == ColorLoopAction::kActivateFromColorLoopStartEnhancedHue) + else if (commandData.action == ColorLoopAction::kActivateFromColorLoopStartEnhancedHue) { startColorLoop(endpoint, true); } - else if (action == ColorLoopAction::kActivateFromEnhancedCurrentHue) + else if (commandData.action == ColorLoopAction::kActivateFromEnhancedCurrentHue) { startColorLoop(endpoint, false); } } -exit: #ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); #endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } /** - * @brief updates Hue and saturation after timer is finished + * @brief Updates Hue and saturation after timer is finished. * * @param endpoint */ @@ -2251,13 +2142,13 @@ EmberEventControl * ColorControlServer::configureXYEventControl(EndpointId endpo /** * @brief executes move to saturation command * + * @param endpoint target endpoint where to execute move * @param colorX target X * @param colorY target Y * @param transitionTime transition time in 10th of seconds - * @param endpoint target endpoint where to execute move * @return Status::Success if successful,Status::UnsupportedEndpoint XY is not supported on the endpoint */ -Status ColorControlServer::moveToColor(uint16_t colorX, uint16_t colorY, uint16_t transitionTime, EndpointId endpoint) +Status ColorControlServer::moveToColor(EndpointId endpoint, uint16_t colorX, uint16_t colorY, uint16_t transitionTime) { uint16_t epIndex = getEndpointIndex(endpoint); Color16uTransitionState * colorXTransitionState = getXTransitionStateByIndex(epIndex); @@ -2303,45 +2194,42 @@ Status ColorControlServer::moveToColor(uint16_t colorX, uint16_t colorY, uint16_ return Status::Success; } -bool ColorControlServer::moveToColorCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveToColor::DecodableType & commandData) +/** + * @brief executes move to color command + * @param endpoint endpointId of the recipient Color control cluster + * @param commandData Struct containing the parameters of the command + * @return Status::Success when successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a Color XY transition state (verified in + * moveToColor function), + */ +Status ColorControlServer::moveToColorCommand(EndpointId endpoint, const Commands::MoveToColor::DecodableType & commandData) { - if (!shouldExecuteIfOff(commandPath.mEndpointId, commandData.optionsMask, commandData.optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); - Status status = moveToColor(commandData.colorX, commandData.colorY, commandData.transitionTime, commandPath.mEndpointId); + Status status = moveToColor(endpoint, commandData.colorX, commandData.colorY, commandData.transitionTime); #ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT - ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); + ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); #endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT - commandObj->AddStatus(commandPath, status); - return true; + return status; } -bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveColor::DecodableType & commandData) +/** + * @brief executes move color command + * @param endpoint endpointId of the recipient Color control cluster + * @param commandData Struct containing the parameters of the command + * @return Status::Success when successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a Color XY transition state (verified in + * moveToColor). + */ +Status ColorControlServer::moveColorCommand(EndpointId endpoint, const Commands::MoveColor::DecodableType & commandData) { - int16_t rateX = commandData.rateX; - int16_t rateY = commandData.rateY; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint16_t epIndex = getEndpointIndex(endpoint); Color16uTransitionState * colorXTransitionState = getXTransitionStateByIndex(epIndex); Color16uTransitionState * colorYTransitionState = getYTransitionStateByIndex(epIndex); + VerifyOrReturnValue(colorXTransitionState != nullptr, Status::UnsupportedEndpoint); + VerifyOrReturnValue(colorYTransitionState != nullptr, Status::UnsupportedEndpoint); - VerifyOrExit(colorXTransitionState != nullptr, status = Status::UnsupportedEndpoint); - VerifyOrExit(colorYTransitionState != nullptr, status = Status::UnsupportedEndpoint); - - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); uint16_t transitionTimeX, transitionTimeY; uint16_t unsignedRate; @@ -2349,11 +2237,10 @@ bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, cons // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); - if (rateX == 0 && rateY == 0) + if (commandData.rateX == 0 && commandData.rateY == 0) { // any current transition has been stopped. We are done. - commandObj->AddStatus(commandPath, Status::Success); - return true; + return Status::Success; } // Handle color mode transition, if necessary. @@ -2362,15 +2249,15 @@ bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, cons // now, kick off the state machine. Attributes::CurrentX::Get(endpoint, &(colorXTransitionState->initialValue)); colorXTransitionState->currentValue = colorXTransitionState->initialValue; - if (rateX > 0) + if (commandData.rateX > 0) { colorXTransitionState->finalValue = MAX_CIE_XY_VALUE; - unsignedRate = static_cast(rateX); + unsignedRate = static_cast(commandData.rateX); } else { colorXTransitionState->finalValue = MIN_CIE_XY_VALUE; - unsignedRate = static_cast(rateX * -1); + unsignedRate = static_cast(commandData.rateX * -1); } transitionTimeX = computeTransitionTimeFromStateAndRate(colorXTransitionState, unsignedRate); colorXTransitionState->stepsRemaining = transitionTimeX; @@ -2383,15 +2270,15 @@ bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, cons Attributes::CurrentY::Get(endpoint, &(colorYTransitionState->initialValue)); colorYTransitionState->currentValue = colorYTransitionState->initialValue; - if (rateY > 0) + if (commandData.rateY > 0) { colorYTransitionState->finalValue = MAX_CIE_XY_VALUE; - unsignedRate = static_cast(rateY); + unsignedRate = static_cast(commandData.rateY); } else { colorYTransitionState->finalValue = MIN_CIE_XY_VALUE; - unsignedRate = static_cast(rateY * -1); + unsignedRate = static_cast(commandData.rateY * -1); } transitionTimeY = computeTransitionTimeFromStateAndRate(colorYTransitionState, unsignedRate); colorYTransitionState->stepsRemaining = transitionTimeY; @@ -2406,52 +2293,36 @@ bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, cons // kick off the state machine: scheduleTimerCallbackMs(configureXYEventControl(endpoint), TRANSITION_UPDATE_TIME_MS.count()); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } -bool ColorControlServer::stepColorCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::StepColor::DecodableType & commandData) +/** + * @brief executes step color command + * @param endpoint endpointId of the recipient Color control cluster + * @param commandData Struct containing the parameters of the command + * @return Status::Success when successful, + * Status::InvalidCommand when a step X and Y of 0 is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a Color XY transition state. + */ +Status ColorControlServer::stepColorCommand(EndpointId endpoint, const Commands::StepColor::DecodableType & commandData) { - int16_t stepX = commandData.stepX; - int16_t stepY = commandData.stepY; - uint16_t transitionTime = commandData.transitionTime; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - uint16_t currentColorX = 0; - uint16_t currentColorY = 0; - uint16_t colorX = 0; - uint16_t colorY = 0; - - Status status = Status::Success; + VerifyOrReturnValue(commandData.stepX != 0 || commandData.stepY != 0, Status::InvalidCommand); uint16_t epIndex = getEndpointIndex(endpoint); Color16uTransitionState * colorXTransitionState = getXTransitionStateByIndex(epIndex); Color16uTransitionState * colorYTransitionState = getYTransitionStateByIndex(epIndex); - VerifyOrExit(colorXTransitionState != nullptr, status = Status::UnsupportedEndpoint); - VerifyOrExit(colorYTransitionState != nullptr, status = Status::UnsupportedEndpoint); - - if (stepX == 0 && stepY == 0) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } - - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(colorXTransitionState != nullptr, Status::UnsupportedEndpoint); + VerifyOrReturnValue(colorYTransitionState != nullptr, Status::UnsupportedEndpoint); + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); + uint16_t currentColorX = 0; + uint16_t currentColorY = 0; Attributes::CurrentX::Get(endpoint, ¤tColorX); Attributes::CurrentY::Get(endpoint, ¤tColorY); - colorX = findNewColorValueFromStep(currentColorX, stepX); - colorY = findNewColorValueFromStep(currentColorY, stepY); + uint16_t colorX = findNewColorValueFromStep(currentColorX, commandData.stepX); + uint16_t colorY = findNewColorValueFromStep(currentColorY, commandData.stepY); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); @@ -2463,10 +2334,10 @@ bool ColorControlServer::stepColorCommand(app::CommandHandler * commandObj, cons colorXTransitionState->initialValue = currentColorX; colorXTransitionState->currentValue = currentColorX; colorXTransitionState->finalValue = colorX; - colorXTransitionState->stepsRemaining = std::max(transitionTime, 1); + colorXTransitionState->stepsRemaining = std::max(commandData.transitionTime, 1); colorXTransitionState->stepsTotal = colorXTransitionState->stepsRemaining; - colorXTransitionState->timeRemaining = transitionTime; - colorXTransitionState->transitionTime = transitionTime; + colorXTransitionState->timeRemaining = commandData.transitionTime; + colorXTransitionState->transitionTime = commandData.transitionTime; colorXTransitionState->endpoint = endpoint; colorXTransitionState->lowLimit = MIN_CIE_XY_VALUE; colorXTransitionState->highLimit = MAX_CIE_XY_VALUE; @@ -2476,20 +2347,17 @@ bool ColorControlServer::stepColorCommand(app::CommandHandler * commandObj, cons colorYTransitionState->finalValue = colorY; colorYTransitionState->stepsRemaining = colorXTransitionState->stepsRemaining; colorYTransitionState->stepsTotal = colorXTransitionState->stepsRemaining; - colorYTransitionState->timeRemaining = transitionTime; - colorYTransitionState->transitionTime = transitionTime; + colorYTransitionState->timeRemaining = commandData.transitionTime; + colorYTransitionState->transitionTime = commandData.transitionTime; colorYTransitionState->endpoint = endpoint; colorYTransitionState->lowLimit = MIN_CIE_XY_VALUE; colorYTransitionState->highLimit = MAX_CIE_XY_VALUE; - SetQuietReportRemainingTime(endpoint, transitionTime, true /* isNewTransition */); + SetQuietReportRemainingTime(endpoint, commandData.transitionTime, true /* isNewTransition */); // kick off the state machine: - scheduleTimerCallbackMs(configureXYEventControl(endpoint), transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + scheduleTimerCallbackMs(configureXYEventControl(endpoint), commandData.transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); + return Status::Success; } /** @@ -2563,12 +2431,12 @@ ColorControlServer::Color16uTransitionState * ColorControlServer::getTempTransit } /** - * @brief executes move to color temp logic + * @brief Executes move to color temp logic. * * @param aEndpoint * @param colorTemperature * @param transitionTime - * @return Status::Success if successful, Status::UnsupportedEndpoint if the endpoint doesn't support color temperature + * @return Status::Success if successful, Status::UnsupportedEndpoint if the endpoint doesn't support color temperature. */ Status ColorControlServer::moveToColorTemp(EndpointId aEndpoint, uint16_t colorTemperature, uint16_t transitionTime) { @@ -2764,49 +2632,28 @@ void ColorControlServer::updateTempCommand(EndpointId endpoint) } /** - * @brief move color temp command - * - * @param moveMode - * @param rate - * @param colorTemperatureMinimum - * @param colorTemperatureMaximum - * @param optionsMask - * @param optionsOverride - * @return true - * @return false + * @brief Executes move color temp command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::InvalidCommand when a rate of 0 for a non-stop move or an unknown HueMoveMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a color temp transition state. */ -bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveColorTemperature::DecodableType & commandData) -{ - auto moveMode = commandData.moveMode; - uint16_t rate = commandData.rate; - uint16_t colorTemperatureMinimum = commandData.colorTemperatureMinimumMireds; - uint16_t colorTemperatureMaximum = commandData.colorTemperatureMaximumMireds; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint16_t tempPhysicalMin = MIN_TEMPERATURE_VALUE; - uint16_t tempPhysicalMax = MAX_TEMPERATURE_VALUE; - uint16_t transitionTime; - - Color16uTransitionState * colorTempTransitionState = getTempTransitionState(endpoint); - VerifyOrExit(colorTempTransitionState != nullptr, status = Status::UnsupportedEndpoint); - +Status ColorControlServer::moveColorTempCommand(EndpointId endpoint, + const Commands::MoveColorTemperature::DecodableType & commandData) +{ // check moveMode and rate before any operation is done on the transition states // rate value is ignored if the MoveMode is stop - if (moveMode == HueMoveMode::kUnknownEnumValue || (rate == 0 && moveMode != HueMoveMode::kStop)) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } + VerifyOrReturnValue(commandData.moveMode != HueMoveMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue((commandData.rate != 0 || commandData.moveMode == HueMoveMode::kStop), Status::InvalidCommand); - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + Color16uTransitionState * colorTempTransitionState = getTempTransitionState(endpoint); + VerifyOrReturnValue(colorTempTransitionState != nullptr, Status::UnsupportedEndpoint); + + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); + uint16_t tempPhysicalMin = MIN_TEMPERATURE_VALUE; + uint16_t tempPhysicalMax = MAX_TEMPERATURE_VALUE; Attributes::ColorTempPhysicalMinMireds::Get(endpoint, &tempPhysicalMin); Attributes::ColorTempPhysicalMaxMireds::Get(endpoint, &tempPhysicalMax); @@ -2815,15 +2662,12 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); - - if (moveMode == HueMoveMode::kStop) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + // For HueMoveMode::kStop we are done here. + VerifyOrReturnValue(commandData.moveMode != HueMoveMode::kStop, Status::Success); // Per spec, colorTemperatureMinimumMireds field is limited to ColorTempPhysicalMinMireds and // when colorTemperatureMinimumMireds field is 0, ColorTempPhysicalMinMireds shall be used (always > 0) + uint16_t colorTemperatureMinimum = commandData.colorTemperatureMinimumMireds; if (colorTemperatureMinimum < tempPhysicalMin) { colorTemperatureMinimum = tempPhysicalMin; @@ -2831,6 +2675,7 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, // Per spec, colorTemperatureMaximumMireds field is limited to ColorTempPhysicalMaxMireds and // when colorTemperatureMaximumMireds field is 0, ColorTempPhysicalMaxMireds shall be used + uint16_t colorTemperatureMaximum = commandData.colorTemperatureMaximumMireds; if ((colorTemperatureMaximum == 0) || (colorTemperatureMaximum > tempPhysicalMax)) { colorTemperatureMaximum = tempPhysicalMax; @@ -2844,7 +2689,7 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, Attributes::ColorTemperatureMireds::Get(endpoint, &colorTempTransitionState->initialValue); colorTempTransitionState->currentValue = colorTempTransitionState->initialValue; - if (moveMode == HueMoveMode::kUp) + if (commandData.moveMode == HueMoveMode::kUp) { if (tempPhysicalMax > colorTemperatureMaximum) { @@ -2866,7 +2711,8 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, colorTempTransitionState->finalValue = tempPhysicalMin; } } - transitionTime = computeTransitionTimeFromStateAndRate(colorTempTransitionState, rate); + + uint16_t transitionTime = computeTransitionTimeFromStateAndRate(colorTempTransitionState, commandData.rate); colorTempTransitionState->stepsRemaining = transitionTime; colorTempTransitionState->stepsTotal = transitionTime; colorTempTransitionState->timeRemaining = transitionTime; @@ -2879,63 +2725,54 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, // kick off the state machine: scheduleTimerCallbackMs(configureTempEventControl(endpoint), TRANSITION_UPDATE_TIME_MS.count()); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } -bool ColorControlServer::moveToColorTempCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveToColorTemperature::DecodableType & commandData) +/** + * @brief Executes move to color temp command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a color XY transition state (verified in + * moveToColorTemp function). + */ +Status ColorControlServer::moveToColorTempCommand(EndpointId endpoint, + const Commands::MoveToColorTemperature::DecodableType & commandData) { - if (!shouldExecuteIfOff(commandPath.mEndpointId, commandData.optionsMask, commandData.optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); - Status status = moveToColorTemp(commandPath.mEndpointId, commandData.colorTemperatureMireds, commandData.transitionTime); + Status status = moveToColorTemp(endpoint, commandData.colorTemperatureMireds, commandData.transitionTime); #ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT - ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); + ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); #endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT - commandObj->AddStatus(commandPath, status); - return true; + return status; } -bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::StepColorTemperature::DecodableType & commandData) +/** + * @brief Executes step color temp command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command + * @return Status::Success when successful, + * Status::InvalidCommand when stepSize is 0 or an unknown stepMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a color temp transition state. + */ +Status ColorControlServer::stepColorTempCommand(EndpointId endpoint, + const Commands::StepColorTemperature::DecodableType & commandData) { - auto stepMode = commandData.stepMode; - uint16_t stepSize = commandData.stepSize; - uint16_t transitionTime = commandData.transitionTime; - uint16_t colorTemperatureMinimum = commandData.colorTemperatureMinimumMireds; - uint16_t colorTemperatureMaximum = commandData.colorTemperatureMaximumMireds; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint16_t tempPhysicalMin = MIN_TEMPERATURE_VALUE; - uint16_t tempPhysicalMax = MAX_TEMPERATURE_VALUE; + // Confirm validity of the step mode and step size received + VerifyOrReturnValue(commandData.stepMode != HueStepMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue(commandData.stepSize != 0, Status::InvalidCommand); Color16uTransitionState * colorTempTransitionState = getTempTransitionState(endpoint); - VerifyOrExit(colorTempTransitionState != nullptr, status = Status::UnsupportedEndpoint); + VerifyOrReturnValue(colorTempTransitionState != nullptr, Status::UnsupportedEndpoint); - // Confirm validity of the step mode and step size received - if (stepMode == HueStepMode::kUnknownEnumValue || stepSize == 0) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } - - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); + uint16_t tempPhysicalMin = MIN_TEMPERATURE_VALUE; + uint16_t tempPhysicalMax = MAX_TEMPERATURE_VALUE; Attributes::ColorTempPhysicalMinMireds::Get(endpoint, &tempPhysicalMin); Attributes::ColorTempPhysicalMaxMireds::Get(endpoint, &tempPhysicalMax); @@ -2944,6 +2781,7 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, // Per spec, colorTemperatureMinimumMireds field is limited to ColorTempPhysicalMinMireds and // when colorTemperatureMinimumMireds field is 0, ColorTempPhysicalMinMireds shall be used (always > 0) + uint16_t colorTemperatureMinimum = commandData.colorTemperatureMinimumMireds; if (colorTemperatureMinimum < tempPhysicalMin) { colorTemperatureMinimum = tempPhysicalMin; @@ -2951,6 +2789,7 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, // Per spec, colorTemperatureMaximumMireds field is limited to ColorTempPhysicalMaxMireds and // when colorTemperatureMaximumMireds field is 0, ColorTempPhysicalMaxMireds shall be used + uint16_t colorTemperatureMaximum = commandData.colorTemperatureMaximumMireds; if ((colorTemperatureMaximum == 0) || (colorTemperatureMaximum > tempPhysicalMax)) { colorTemperatureMaximum = tempPhysicalMax; @@ -2966,9 +2805,10 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, colorTempTransitionState->currentValue = colorTempTransitionState->initialValue; - if (stepMode == HueStepMode::kUp) + if (commandData.stepMode == HueStepMode::kUp) { - uint32_t finalValue32u = static_cast(colorTempTransitionState->initialValue) + static_cast(stepSize); + uint32_t finalValue32u = + static_cast(colorTempTransitionState->initialValue) + static_cast(commandData.stepSize); if (finalValue32u > UINT16_MAX) { colorTempTransitionState->finalValue = UINT16_MAX; @@ -2978,9 +2818,10 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, colorTempTransitionState->finalValue = static_cast(finalValue32u); } } - else if (stepMode == HueStepMode::kDown) + else if (commandData.stepMode == HueStepMode::kDown) { - uint32_t finalValue32u = static_cast(colorTempTransitionState->initialValue) - static_cast(stepSize); + uint32_t finalValue32u = + static_cast(colorTempTransitionState->initialValue) - static_cast(commandData.stepSize); if (finalValue32u > UINT16_MAX) { colorTempTransitionState->finalValue = 0; @@ -2990,22 +2831,20 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, colorTempTransitionState->finalValue = static_cast(finalValue32u); } } - colorTempTransitionState->stepsRemaining = std::max(transitionTime, 1); + colorTempTransitionState->stepsRemaining = std::max(commandData.transitionTime, 1); colorTempTransitionState->stepsTotal = colorTempTransitionState->stepsRemaining; - colorTempTransitionState->timeRemaining = transitionTime; - colorTempTransitionState->transitionTime = transitionTime; + colorTempTransitionState->timeRemaining = commandData.transitionTime; + colorTempTransitionState->transitionTime = commandData.transitionTime; colorTempTransitionState->endpoint = endpoint; colorTempTransitionState->lowLimit = colorTemperatureMinimum; colorTempTransitionState->highLimit = colorTemperatureMaximum; - SetQuietReportRemainingTime(endpoint, transitionTime, true /* isNewTransition */); + SetQuietReportRemainingTime(endpoint, commandData.transitionTime, true /* isNewTransition */); // kick off the state machine: - scheduleTimerCallbackMs(configureTempEventControl(endpoint), transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + scheduleTimerCallbackMs(configureTempEventControl(endpoint), + commandData.transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); + return Status::Success; } void ColorControlServer::levelControlColorTempChangeCommand(EndpointId endpoint) @@ -3201,96 +3040,119 @@ Status ColorControlServer::SetQuietReportRemainingTime(EndpointId endpoint, uint bool emberAfColorControlClusterMoveHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveHue::DecodableType & commandData) { - return ColorControlServer::Instance().moveHueCommand(commandObj, commandPath, commandData.moveMode, commandData.rate, - commandData.optionsMask, commandData.optionsOverride, false); + Status status = ColorControlServer::Instance().moveHueCommand(commandPath.mEndpointId, commandData.moveMode, commandData.rate, + commandData.optionsMask, commandData.optionsOverride, false); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveSaturationCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveSaturation::DecodableType & commandData) { - - return ColorControlServer::Instance().moveSaturationCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveSaturationCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveToHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveToHue::DecodableType & commandData) { - return ColorControlServer::Instance().moveToHueCommand(commandObj, commandPath, commandData.hue, commandData.direction, - commandData.transitionTime, commandData.optionsMask, - commandData.optionsOverride, false); + Status status = ColorControlServer::Instance().moveToHueCommand(commandPath.mEndpointId, commandData.hue, commandData.direction, + commandData.transitionTime, commandData.optionsMask, + commandData.optionsOverride, false); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveToSaturationCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveToSaturation::DecodableType & commandData) { - return ColorControlServer::Instance().moveToSaturationCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveToSaturationCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveToHueAndSaturationCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveToHueAndSaturation::DecodableType & commandData) { - return ColorControlServer::Instance().moveToHueAndSaturationCommand( - commandObj, commandPath, commandData.hue, commandData.saturation, commandData.transitionTime, commandData.optionsMask, + Status status = ColorControlServer::Instance().moveToHueAndSaturationCommand( + commandPath.mEndpointId, commandData.hue, commandData.saturation, commandData.transitionTime, commandData.optionsMask, commandData.optionsOverride, false); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterStepHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StepHue::DecodableType & commandData) { - return ColorControlServer::Instance().stepHueCommand(commandObj, commandPath, commandData.stepMode, commandData.stepSize, - commandData.transitionTime, commandData.optionsMask, - commandData.optionsOverride, false); + Status status = ColorControlServer::Instance().stepHueCommand(commandPath.mEndpointId, commandData.stepMode, + commandData.stepSize, commandData.transitionTime, + commandData.optionsMask, commandData.optionsOverride, false); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterStepSaturationCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StepSaturation::DecodableType & commandData) { - return ColorControlServer::Instance().stepSaturationCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().stepSaturationCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterEnhancedMoveHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::EnhancedMoveHue::DecodableType & commandData) { - return ColorControlServer::Instance().moveHueCommand(commandObj, commandPath, commandData.moveMode, commandData.rate, - commandData.optionsMask, commandData.optionsOverride, true); + Status status = ColorControlServer::Instance().moveHueCommand(commandPath.mEndpointId, commandData.moveMode, commandData.rate, + commandData.optionsMask, commandData.optionsOverride, true); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterEnhancedMoveToHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::EnhancedMoveToHue::DecodableType & commandData) { - return ColorControlServer::Instance().moveToHueCommand(commandObj, commandPath, commandData.enhancedHue, commandData.direction, - commandData.transitionTime, commandData.optionsMask, - commandData.optionsOverride, true); + Status status = ColorControlServer::Instance().moveToHueCommand(commandPath.mEndpointId, commandData.enhancedHue, + commandData.direction, commandData.transitionTime, + commandData.optionsMask, commandData.optionsOverride, true); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterEnhancedMoveToHueAndSaturationCallback( app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::EnhancedMoveToHueAndSaturation::DecodableType & commandData) { - return ColorControlServer::Instance().moveToHueAndSaturationCommand(commandObj, commandPath, commandData.enhancedHue, - commandData.saturation, commandData.transitionTime, - commandData.optionsMask, commandData.optionsOverride, true); + Status status = ColorControlServer::Instance().moveToHueAndSaturationCommand( + commandPath.mEndpointId, commandData.enhancedHue, commandData.saturation, commandData.transitionTime, + commandData.optionsMask, commandData.optionsOverride, true); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterEnhancedStepHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::EnhancedStepHue::DecodableType & commandData) { - return ColorControlServer::Instance().stepHueCommand(commandObj, commandPath, commandData.stepMode, commandData.stepSize, - commandData.transitionTime, commandData.optionsMask, - commandData.optionsOverride, true); + Status status = ColorControlServer::Instance().stepHueCommand(commandPath.mEndpointId, commandData.stepMode, + commandData.stepSize, commandData.transitionTime, + commandData.optionsMask, commandData.optionsOverride, true); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterColorLoopSetCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::ColorLoopSet::DecodableType & commandData) { - return ColorControlServer::Instance().colorLoopCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().colorLoopCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV @@ -3300,19 +3162,25 @@ bool emberAfColorControlClusterColorLoopSetCallback(app::CommandHandler * comman bool emberAfColorControlClusterMoveToColorCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveToColor::DecodableType & commandData) { - return ColorControlServer::Instance().moveToColorCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveToColorCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveColorCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveColor::DecodableType & commandData) { - return ColorControlServer::Instance().moveColorCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveColorCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterStepColorCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StepColor::DecodableType & commandData) { - return ColorControlServer::Instance().stepColorCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().stepColorCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY @@ -3323,21 +3191,27 @@ bool emberAfColorControlClusterMoveToColorTemperatureCallback(app::CommandHandle const app::ConcreteCommandPath & commandPath, const Commands::MoveToColorTemperature::DecodableType & commandData) { - return ColorControlServer::Instance().moveToColorTempCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveToColorTempCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveColorTemperatureCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveColorTemperature::DecodableType & commandData) { - return ColorControlServer::Instance().moveColorTempCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveColorTempCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterStepColorTemperatureCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StepColorTemperature::DecodableType & commandData) { - return ColorControlServer::Instance().stepColorTempCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().stepColorTempCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } void emberAfPluginLevelControlCoupledColorTempChangeCallback(EndpointId endpoint) @@ -3350,8 +3224,9 @@ void emberAfPluginLevelControlCoupledColorTempChangeCallback(EndpointId endpoint bool emberAfColorControlClusterStopMoveStepCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StopMoveStep::DecodableType & commandData) { - return ColorControlServer::Instance().stopMoveStepCommand(commandObj, commandPath, commandData.optionsMask, - commandData.optionsOverride); + Status status = ColorControlServer::Instance().stopMoveStepCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } void emberAfColorControlClusterServerInitCallback(EndpointId endpoint) diff --git a/src/app/clusters/color-control-server/color-control-server.h b/src/app/clusters/color-control-server/color-control-server.h index 422c7f592f8b33..40ae30aeb2224f 100644 --- a/src/app/clusters/color-control-server/color-control-server.h +++ b/src/app/clusters/color-control-server/color-control-server.h @@ -143,57 +143,69 @@ class ColorControlServer bool HasFeature(chip::EndpointId endpoint, Feature feature); chip::Protocols::InteractionModel::Status stopAllColorTransitions(chip::EndpointId endpoint); - bool stopMoveStepCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - chip::BitMask optionsMask, - chip::BitMask optionsOverride); + chip::Protocols::InteractionModel::Status + stopMoveStepCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::StopMoveStep::DecodableType & commandData); #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV - bool moveHueCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - MoveModeEnum moveMode, uint16_t rate, - chip::BitMask optionsMask, - chip::BitMask optionsOverride, bool isEnhanced); - bool moveToHueCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, uint16_t hue, - DirectionEnum moveDirection, uint16_t transitionTime, - chip::BitMask optionsMask, - chip::BitMask optionsOverride, bool isEnhanced); - bool moveToHueAndSaturationCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - uint16_t hue, uint8_t saturation, uint16_t transitionTime, - chip::BitMask optionsMask, - chip::BitMask optionsOverride, - bool isEnhanced); - bool stepHueCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - StepModeEnum stepMode, uint16_t stepSize, uint16_t transitionTime, - chip::BitMask optionsMask, - chip::BitMask optionsOverride, bool isEnhanced); - bool moveSaturationCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::MoveSaturation::DecodableType & commandData); - bool moveToSaturationCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::MoveToSaturation::DecodableType & commandData); - bool stepSaturationCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::StepSaturation::DecodableType & commandData); - bool colorLoopCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::ColorLoopSet::DecodableType & commandData); + // The Command's DecodableType are not used to pass arguments in the following HSV handlers, + // as they handle both standard and Enhanced HSV commands. + // The command arguments are decoupled in the command callback. + chip::Protocols::InteractionModel::Status + moveHueCommand(const chip::EndpointId endpoint, MoveModeEnum moveMode, uint16_t rate, + chip::BitMask optionsMask, + chip::BitMask optionsOverride, bool isEnhanced); + chip::Protocols::InteractionModel::Status + moveToHueCommand(const chip::EndpointId endpoint, uint16_t hue, DirectionEnum moveDirection, uint16_t transitionTime, + chip::BitMask optionsMask, + chip::BitMask optionsOverride, bool isEnhanced); + chip::Protocols::InteractionModel::Status + moveToHueAndSaturationCommand(const chip::EndpointId endpoint, uint16_t hue, uint8_t saturation, uint16_t transitionTime, + chip::BitMask optionsMask, + chip::BitMask optionsOverride, bool isEnhanced); + chip::Protocols::InteractionModel::Status + stepHueCommand(const chip::EndpointId endpoint, StepModeEnum stepMode, uint16_t stepSize, uint16_t transitionTime, + chip::BitMask optionsMask, + chip::BitMask optionsOverride, bool isEnhanced); + + chip::Protocols::InteractionModel::Status + moveSaturationCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::MoveSaturation::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + moveToSaturationCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::MoveToSaturation::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + stepSaturationCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::StepSaturation::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + colorLoopCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::ColorLoopSet::DecodableType & commandData); void updateHueSatCommand(chip::EndpointId endpoint); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY - bool moveToColorCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::MoveToColor::DecodableType & commandData); - bool moveColorCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::MoveColor::DecodableType & commandData); - bool stepColorCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::StepColor::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + moveToColorCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::MoveToColor::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + moveColorCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::MoveColor::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + stepColorCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::StepColor::DecodableType & commandData); void updateXYCommand(chip::EndpointId endpoint); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP - bool moveColorTempCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::MoveColorTemperature::DecodableType & commandData); - bool - moveToColorTempCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, + chip::Protocols::InteractionModel::Status + moveColorTempCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::MoveColorTemperature::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + moveToColorTempCommand(const chip::EndpointId endpoint, const chip::app::Clusters::ColorControl::Commands::MoveToColorTemperature::DecodableType & commandData); - bool stepColorTempCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::StepColorTemperature::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + stepColorTempCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::StepColorTemperature::DecodableType & commandData); void levelControlColorTempChangeCommand(chip::EndpointId endpoint); void startUpColorTempCommand(chip::EndpointId endpoint); void updateTempCommand(chip::EndpointId endpoint); @@ -231,10 +243,10 @@ class ColorControlServer uint16_t getEndpointIndex(chip::EndpointId); #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV - chip::Protocols::InteractionModel::Status moveToSaturation(uint8_t saturation, uint16_t transitionTime, - chip::EndpointId endpoint); - chip::Protocols::InteractionModel::Status moveToHueAndSaturation(uint16_t hue, uint8_t saturation, uint16_t transitionTime, - bool isEnhanced, chip::EndpointId endpoint); + chip::Protocols::InteractionModel::Status moveToSaturation(chip::EndpointId endpoint, uint8_t saturation, + uint16_t transitionTime); + chip::Protocols::InteractionModel::Status moveToHueAndSaturation(chip::EndpointId endpoint, uint16_t hue, uint8_t saturation, + uint16_t transitionTime, bool isEnhanced); ColorHueTransitionState * getColorHueTransitionState(chip::EndpointId endpoint); Color16uTransitionState * getSaturationTransitionState(chip::EndpointId endpoint); ColorHueTransitionState * getColorHueTransitionStateByIndex(uint16_t index); @@ -255,8 +267,8 @@ class ColorControlServer #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY - chip::Protocols::InteractionModel::Status moveToColor(uint16_t colorX, uint16_t colorY, uint16_t transitionTime, - chip::EndpointId endpoint); + chip::Protocols::InteractionModel::Status moveToColor(chip::EndpointId endpoint, uint16_t colorX, uint16_t colorY, + uint16_t transitionTime); Color16uTransitionState * getXTransitionState(chip::EndpointId endpoint); Color16uTransitionState * getYTransitionState(chip::EndpointId endpoint); Color16uTransitionState * getXTransitionStateByIndex(uint16_t index); diff --git a/src/app/clusters/fan-control-server/fan-control-server.cpp b/src/app/clusters/fan-control-server/fan-control-server.cpp index 46f4c6d7c0bb70..7ece1a1b575a24 100644 --- a/src/app/clusters/fan-control-server/fan-control-server.cpp +++ b/src/app/clusters/fan-control-server/fan-control-server.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include @@ -85,6 +86,10 @@ namespace { // Indicates if the write operation is from the cluster server itself bool gWriteFromClusterLogic = false; +// Avoid circular callback calls when adjusting SpeedSetting and PercentSetting together. +ScopedChangeOnly gSpeedWriteInProgress(false); +ScopedChangeOnly gPercentWriteInProgress(false); + Status SetFanModeToOff(EndpointId endpointId) { FanModeEnum currentFanMode; @@ -185,6 +190,10 @@ MatterFanControlClusterServerPreAttributeChangedCallback(const ConcreteAttribute break; } case SpeedSetting::Id: { + if (gSpeedWriteInProgress) + { + return Status::WriteIgnored; + } if (SupportsMultiSpeed(attributePath.mEndpointId)) { // Check if the SpeedSetting is null. @@ -224,6 +233,10 @@ MatterFanControlClusterServerPreAttributeChangedCallback(const ConcreteAttribute break; } case PercentSetting::Id: { + if (gPercentWriteInProgress) + { + return Status::WriteIgnored; + } // Check if the PercentSetting is null. if (NumericAttributeTraits::IsNullValue(*value)) { @@ -362,12 +375,18 @@ void MatterFanControlClusterServerAttributeChangedCallback(const app::ConcreteAt DataModel::Nullable percentSetting; Status status = PercentSetting::Get(attributePath.mEndpointId, percentSetting); VerifyOrReturn(Status::Success == status && !percentSetting.IsNull()); + uint8_t speedMax; + status = SpeedMax::Get(attributePath.mEndpointId, &speedMax); + VerifyOrReturn(Status::Success == status, + ChipLogError(Zcl, "Failed to get SpeedMax with error: 0x%02x", to_underlying(status))); + // Avoid circular callback calls + ScopedChange PercentWriteInProgress(gPercentWriteInProgress, true); // If PercentSetting is set to 0, the server SHALL set the FanMode attribute value to Off. if (percentSetting.Value() == 0) { status = SetFanModeToOff(attributePath.mEndpointId); - VerifyOrReturn(Status::Success == status, + VerifyOrReturn(status == Status::Success, ChipLogError(Zcl, "Failed to set FanMode to off with error: 0x%02x", to_underlying(status))); } @@ -375,26 +394,13 @@ void MatterFanControlClusterServerAttributeChangedCallback(const app::ConcreteAt { // Adjust SpeedSetting from a percent value change for PercentSetting // speed = ceil( SpeedMax * (percent * 0.01) ) - uint8_t speedMax; - status = SpeedMax::Get(attributePath.mEndpointId, &speedMax); - VerifyOrReturn(Status::Success == status, - ChipLogError(Zcl, "Failed to get SpeedMax with error: 0x%02x", to_underlying(status))); - - DataModel::Nullable currentSpeedSetting; - status = SpeedSetting::Get(attributePath.mEndpointId, currentSpeedSetting); - VerifyOrReturn(Status::Success == status, - ChipLogError(Zcl, "Failed to get SpeedSetting with error: 0x%02x", to_underlying(status))); - uint16_t percent = percentSetting.Value(); // Plus 99 then integer divide by 100 instead of multiplying 0.01 to avoid floating point precision error uint8_t speedSetting = static_cast((speedMax * percent + 99) / 100); - if (currentSpeedSetting.IsNull() || speedSetting != currentSpeedSetting.Value()) - { - status = SpeedSetting::Set(attributePath.mEndpointId, speedSetting); - VerifyOrReturn(Status::Success == status, - ChipLogError(Zcl, "Failed to set SpeedSetting with error: 0x%02x", to_underlying(status))); - } + status = SpeedSetting::Set(attributePath.mEndpointId, speedSetting); + VerifyOrDo(Status::Success == status, + ChipLogError(Zcl, "Failed to set SpeedSetting with error: 0x%02x", to_underlying(status))); } break; } @@ -404,7 +410,13 @@ void MatterFanControlClusterServerAttributeChangedCallback(const app::ConcreteAt DataModel::Nullable speedSetting; Status status = SpeedSetting::Get(attributePath.mEndpointId, speedSetting); VerifyOrReturn(Status::Success == status && !speedSetting.IsNull()); + uint8_t speedMax; + status = SpeedMax::Get(attributePath.mEndpointId, &speedMax); + VerifyOrReturn(Status::Success == status, + ChipLogError(Zcl, "Failed to get SpeedMax with error: 0x%02x", to_underlying(status))); + // Avoid circular callback calls + ScopedChange SpeedWriteInProgress(gSpeedWriteInProgress, true); // If SpeedSetting is set to 0, the server SHALL set the FanMode attribute value to Off. if (speedSetting.Value() == 0) { @@ -415,25 +427,12 @@ void MatterFanControlClusterServerAttributeChangedCallback(const app::ConcreteAt // Adjust PercentSetting from a speed value change for SpeedSetting // percent = floor( speed/SpeedMax * 100 ) - uint8_t speedMax; - status = SpeedMax::Get(attributePath.mEndpointId, &speedMax); - VerifyOrReturn(Status::Success == status, - ChipLogError(Zcl, "Failed to get SpeedMax with error: 0x%02x", to_underlying(status))); - - DataModel::Nullable currentPercentSetting; - status = PercentSetting::Get(attributePath.mEndpointId, currentPercentSetting); - VerifyOrReturn(Status::Success == status, - ChipLogError(Zcl, "Failed to get PercentSetting with error: 0x%02x", to_underlying(status))); - float speed = speedSetting.Value(); Percent percentSetting = static_cast(speed / speedMax * 100); - if (currentPercentSetting.IsNull() || percentSetting != currentPercentSetting.Value()) - { - status = PercentSetting::Set(attributePath.mEndpointId, percentSetting); - VerifyOrReturn(Status::Success == status, - ChipLogError(Zcl, "Failed to set PercentSetting with error: 0x%02x", to_underlying(status))); - } + status = PercentSetting::Set(attributePath.mEndpointId, percentSetting); + VerifyOrDo(Status::Success == status, + ChipLogError(Zcl, "Failed to set PercentSetting with error: 0x%02x", to_underlying(status))); } break; } diff --git a/src/app/clusters/mode-base-server/mode-base-server.h b/src/app/clusters/mode-base-server/mode-base-server.h index f787e9fc19f11f..06c22f3a42cd3e 100644 --- a/src/app/clusters/mode-base-server/mode-base-server.h +++ b/src/app/clusters/mode-base-server/mode-base-server.h @@ -20,8 +20,8 @@ #include "mode-base-cluster-objects.h" #include -#include #include +#include #include namespace chip { diff --git a/src/app/clusters/thermostat-server/thermostat-server.cpp b/src/app/clusters/thermostat-server/thermostat-server.cpp index bda97c5cb1f22f..a1f0d27779571f 100644 --- a/src/app/clusters/thermostat-server/thermostat-server.cpp +++ b/src/app/clusters/thermostat-server/thermostat-server.cpp @@ -220,6 +220,292 @@ int16_t EnforceCoolingSetpointLimits(int16_t CoolingSetpoint, EndpointId endpoin return CoolingSetpoint; } +struct SetpointLimits +{ + bool autoSupported = false; + bool heatSupported = false; + bool coolSupported = false; + bool occupancySupported = false; + + int16_t absMinHeatSetpointLimit; + int16_t absMaxHeatSetpointLimit; + int16_t minHeatSetpointLimit; + int16_t maxHeatSetpointLimit; + int16_t absMinCoolSetpointLimit; + int16_t absMaxCoolSetpointLimit; + int16_t minCoolSetpointLimit; + int16_t maxCoolSetpointLimit; + int16_t deadBand = 0; + int16_t occupiedCoolingSetpoint; + int16_t occupiedHeatingSetpoint; + int16_t unoccupiedCoolingSetpoint; + int16_t unoccupiedHeatingSetpoint; +}; + +/** + * @brief Reads all the attributes for enforcing setpoint limits + * + * @param endpoint The endpoint for the server whose limits are being enforced + * @param setpointLimits The SetpointLimits to populate + * @return Success if the limits were read completely, otherwise an error code + */ +Status GetSetpointLimits(EndpointId endpoint, SetpointLimits & setpointLimits) +{ + uint32_t flags; + if (FeatureMap::Get(endpoint, &flags) != Status::Success) + { + ChipLogError(Zcl, "GetSetpointLimits: could not get feature flags"); + flags = FEATURE_MAP_DEFAULT; + } + + auto featureMap = BitMask(flags); + setpointLimits.autoSupported = featureMap.Has(Feature::kAutoMode); + setpointLimits.heatSupported = featureMap.Has(Feature::kHeating); + setpointLimits.coolSupported = featureMap.Has(Feature::kCooling); + setpointLimits.occupancySupported = featureMap.Has(Feature::kOccupancy); + + if (setpointLimits.autoSupported) + { + int8_t deadBand; + if (MinSetpointDeadBand::Get(endpoint, &deadBand) != Status::Success) + { + deadBand = kDefaultDeadBand; + } + setpointLimits.deadBand = static_cast(deadBand * 10); + } + + if (AbsMinCoolSetpointLimit::Get(endpoint, &setpointLimits.absMinCoolSetpointLimit) != Status::Success) + setpointLimits.absMinCoolSetpointLimit = kDefaultAbsMinCoolSetpointLimit; + + if (AbsMaxCoolSetpointLimit::Get(endpoint, &setpointLimits.absMaxCoolSetpointLimit) != Status::Success) + setpointLimits.absMaxCoolSetpointLimit = kDefaultAbsMaxCoolSetpointLimit; + + if (MinCoolSetpointLimit::Get(endpoint, &setpointLimits.minCoolSetpointLimit) != Status::Success) + setpointLimits.minCoolSetpointLimit = setpointLimits.absMinCoolSetpointLimit; + + if (MaxCoolSetpointLimit::Get(endpoint, &setpointLimits.maxCoolSetpointLimit) != Status::Success) + setpointLimits.maxCoolSetpointLimit = setpointLimits.absMaxCoolSetpointLimit; + + if (AbsMinHeatSetpointLimit::Get(endpoint, &setpointLimits.absMinHeatSetpointLimit) != Status::Success) + setpointLimits.absMinHeatSetpointLimit = kDefaultAbsMinHeatSetpointLimit; + + if (AbsMaxHeatSetpointLimit::Get(endpoint, &setpointLimits.absMaxHeatSetpointLimit) != Status::Success) + setpointLimits.absMaxHeatSetpointLimit = kDefaultAbsMaxHeatSetpointLimit; + + if (MinHeatSetpointLimit::Get(endpoint, &setpointLimits.minHeatSetpointLimit) != Status::Success) + setpointLimits.minHeatSetpointLimit = setpointLimits.absMinHeatSetpointLimit; + + if (MaxHeatSetpointLimit::Get(endpoint, &setpointLimits.maxHeatSetpointLimit) != Status::Success) + setpointLimits.maxHeatSetpointLimit = setpointLimits.absMaxHeatSetpointLimit; + + if (setpointLimits.coolSupported) + { + if (OccupiedCoolingSetpoint::Get(endpoint, &setpointLimits.occupiedCoolingSetpoint) != Status::Success) + { + // We're substituting the failure code here for backwards-compatibility reasons + ChipLogError(Zcl, "Error: Can not read Occupied Cooling Setpoint"); + return Status::Failure; + } + } + + if (setpointLimits.heatSupported) + { + if (OccupiedHeatingSetpoint::Get(endpoint, &setpointLimits.occupiedHeatingSetpoint) != Status::Success) + { + // We're substituting the failure code here for backwards-compatibility reasons + ChipLogError(Zcl, "Error: Can not read Occupied Heating Setpoint"); + return Status::Failure; + } + } + + if (setpointLimits.coolSupported && setpointLimits.occupancySupported) + { + if (UnoccupiedCoolingSetpoint::Get(endpoint, &setpointLimits.unoccupiedCoolingSetpoint) != Status::Success) + { + // We're substituting the failure code here for backwards-compatibility reasons + ChipLogError(Zcl, "Error: Can not read Unoccupied Cooling Setpoint"); + return Status::Failure; + } + } + + if (setpointLimits.heatSupported && setpointLimits.occupancySupported) + { + if (UnoccupiedHeatingSetpoint::Get(endpoint, &setpointLimits.unoccupiedHeatingSetpoint) != Status::Success) + { + // We're substituting the failure code here for backwards-compatibility reasons + ChipLogError(Zcl, "Error: Can not read Unoccupied Heating Setpoint"); + return Status::Failure; + } + } + return Status::Success; +} + +/** + * @brief Checks to see if it's possible to adjust the heating setpoint to preserve a given deadband + * if the cooling setpoint is changed + * + * @param autoSupported Whether or not the thermostat supports Auto mode + * @param newCoolingSetpoing The desired cooling setpoint + * @param minHeatingSetpoint The minimum allowed heating setpoint + * @param deadband The deadband to preserve + * @return Success if the deadband can be preserved, InvalidValue if it cannot + */ +Status CheckHeatingSetpointDeadband(bool autoSupported, int16_t newCoolingSetpoint, int16_t minHeatingSetpoint, int16_t deadband) +{ + if (!autoSupported) + { + return Status::Success; + } + int16_t maxValidHeatingSetpoint = static_cast(newCoolingSetpoint - deadband); + if (maxValidHeatingSetpoint < minHeatingSetpoint) + { + // If we need to adjust the heating setpoint to preserve the deadband, it will go below the min heat setpoint + return Status::InvalidValue; + } + // It's possible to adjust the heating setpoint, if needed + return Status::Success; +} + +/** + * @brief Checks to see if it's possible to adjust the cooling setpoint to preserve a given deadband + * if the heating setpoint is changed + * + * @param autoSupported Whether or not the thermostat supports Auto mode + * @param newHeatingSetpoint The desired heating setpoint + * @param maxCoolingSetpoint The maximum allowed cooling setpoint + * @param deadband The deadband to preserve + * @return Success if the deadband can be preserved, InvalidValue if it cannot + */ +Status CheckCoolingSetpointDeadband(bool autoSupported, int16_t newHeatingSetpoint, int16_t maxCoolingSetpoint, int16_t deadband) +{ + if (!autoSupported) + { + return Status::Success; + } + int16_t minValidCoolingSetpoint = static_cast(newHeatingSetpoint + deadband); + if (minValidCoolingSetpoint > maxCoolingSetpoint) + { + // If we need to adjust the cooling setpoint to preserve the deadband, it will go above the max cool setpoint + return Status::InvalidValue; + } + // It's possible to adjust the cooling setpoint, if needed + return Status::Success; +} + +typedef Status (*SetpointSetter)(EndpointId endpoint, int16_t value); + +/** + * @brief Attempts to ensure that a change to the heating setpoint maintains the deadband with the cooling setpoint + * by adjusting the cooling setpoint + * + * @param endpoint The endpoint on which the heating setpoint has been changed + * @param currentCoolingSetpoint The current cooling setpoint + * @param newHeatingSetpoint The newly adjusted heating setpoint + * @param maxCoolingSetpoint The maximum allowed cooling setpoint + * @param deadband The deadband to preserve + * @param setter A function for setting the cooling setpoint + */ +void EnsureCoolingSetpointDeadband(EndpointId endpoint, int16_t currentCoolingSetpoint, int16_t newHeatingSetpoint, + int16_t maxCoolingSetpoint, int16_t deadband, SetpointSetter setter) +{ + int16_t minValidCoolingSetpoint = static_cast(newHeatingSetpoint + deadband); + if (currentCoolingSetpoint >= minValidCoolingSetpoint) + { + // The current cooling setpoint doesn't violate the deadband + return; + } + if (minValidCoolingSetpoint > maxCoolingSetpoint) + { + // Adjusting the cool setpoint to preserve the deadband would violate the max cool setpoint + // This should have been caught in CheckCoolingSetpointDeadband, so log and exit + ChipLogError(Zcl, "Failed ensuring cooling setpoint deadband"); + return; + } + // Adjust the cool setpoint to preserve deadband + auto status = setter(endpoint, minValidCoolingSetpoint); + if (status != Status::Success) + { + ChipLogError(Zcl, "Error: EnsureCoolingSetpointDeadband failed!"); + } +} + +/** + * @brief Attempts to ensure that a change to the cooling setpoint maintains the deadband with the heating setpoint + * by adjusting the heating setpoint + * + * @param endpoint The endpoint on which the cooling setpoint has been changed + * @param currentHeatingSetpointThe current heating setpoint + * @param newCoolingSetpoint The newly adjusted cooling setpoint + * @param minHeatingSetpoint The minimum allowed cooling setpoint + * @param deadband The deadband to preserve + * @param setter A function for setting the heating setpoint + */ +void EnsureHeatingSetpointDeadband(EndpointId endpoint, int16_t currentHeatingSetpoint, int16_t newCoolingSetpoint, + int16_t minHeatingSetpoint, int16_t deadband, SetpointSetter setter) +{ + int16_t maxValidHeatingSetpoint = static_cast(newCoolingSetpoint - deadband); + if (currentHeatingSetpoint <= maxValidHeatingSetpoint) + { + // The current heating setpoint doesn't violate the deadband + return; + } + if (maxValidHeatingSetpoint < minHeatingSetpoint) + { + // Adjusting the heating setpoint to preserve the deadband would violate the min heating setpoint + // This should have been caught in CheckHeatingSetpointDeadband, so log and exit + ChipLogError(Zcl, "Failed ensuring heating setpoint deadband"); + return; + } + // Adjust the heating setpoint to preserve deadband + auto status = setter(endpoint, maxValidHeatingSetpoint); + if (status != Status::Success) + { + ChipLogError(Zcl, "Error: EnsureHeatingSetpointDeadband failed!"); + } +} + +/** + * @brief For thermostats that support auto, shift setpoints to maintain the current deadband + * Note: this assumes that the shift is possible; setpoint changes which prevent the deadband + * from being maintained due to the min/max limits for setpoints should be rejected by + * MatterThermostatClusterServerPreAttributeChangedCallback + * + * @param attributePath + */ +void EnsureDeadband(const ConcreteAttributePath & attributePath) +{ + auto endpoint = attributePath.mEndpointId; + SetpointLimits setpointLimits; + auto status = GetSetpointLimits(endpoint, setpointLimits); + if (status != Status::Success) + { + return; + } + if (!setpointLimits.autoSupported) + { + return; + } + switch (attributePath.mAttributeId) + { + case OccupiedHeatingSetpoint::Id: + EnsureCoolingSetpointDeadband(endpoint, setpointLimits.occupiedCoolingSetpoint, setpointLimits.occupiedHeatingSetpoint, + setpointLimits.maxCoolSetpointLimit, setpointLimits.deadBand, OccupiedCoolingSetpoint::Set); + break; + case OccupiedCoolingSetpoint::Id: + EnsureHeatingSetpointDeadband(endpoint, setpointLimits.occupiedHeatingSetpoint, setpointLimits.occupiedCoolingSetpoint, + setpointLimits.minHeatSetpointLimit, setpointLimits.deadBand, OccupiedHeatingSetpoint::Set); + break; + case UnoccupiedHeatingSetpoint::Id: + EnsureCoolingSetpointDeadband(endpoint, setpointLimits.unoccupiedCoolingSetpoint, setpointLimits.unoccupiedHeatingSetpoint, + setpointLimits.maxCoolSetpointLimit, setpointLimits.deadBand, UnoccupiedCoolingSetpoint::Set); + break; + case UnoccupiedCoolingSetpoint::Id: + EnsureHeatingSetpointDeadband(endpoint, setpointLimits.unoccupiedHeatingSetpoint, setpointLimits.unoccupiedCoolingSetpoint, + setpointLimits.minHeatSetpointLimit, setpointLimits.deadBand, UnoccupiedHeatingSetpoint::Set); + break; + } +} + Delegate * GetDelegate(EndpointId endpoint) { uint16_t ep = @@ -477,14 +763,9 @@ void MatterThermostatClusterServerAttributeChangedCallback(const ConcreteAttribu return; } - auto featureMap = BitMask(flags); - if (!featureMap.Has(Feature::kPresets)) - { - // This server does not support presets, so nothing to do - return; - } - - bool occupied = true; + auto featureMap = BitMask(flags); + bool supportsPresets = featureMap.Has(Feature::kPresets); + bool occupied = true; if (featureMap.Has(Feature::kOccupancy)) { BitMask occupancy; @@ -499,19 +780,20 @@ void MatterThermostatClusterServerAttributeChangedCallback(const ConcreteAttribu { case OccupiedHeatingSetpoint::Id: case OccupiedCoolingSetpoint::Id: - clearActivePreset = occupied; + clearActivePreset = supportsPresets && occupied; + EnsureDeadband(attributePath); break; case UnoccupiedHeatingSetpoint::Id: case UnoccupiedCoolingSetpoint::Id: - clearActivePreset = !occupied; + clearActivePreset = supportsPresets && !occupied; + EnsureDeadband(attributePath); break; } - if (!clearActivePreset) + if (clearActivePreset) { - return; + ChipLogProgress(Zcl, "Setting active preset to null"); + gThermostatAttrAccess.SetActivePreset(attributePath.mEndpointId, std::nullopt); } - ChipLogProgress(Zcl, "Setting active preset to null"); - gThermostatAttrAccess.SetActivePreset(attributePath.mEndpointId, std::nullopt); } } // namespace Thermostat @@ -535,15 +817,15 @@ void emberAfThermostatClusterServerInitCallback(chip::EndpointId endpoint) // or should this just be the responsibility of the thermostat application? } -Protocols::InteractionModel::Status -MatterThermostatClusterServerPreAttributeChangedCallback(const app::ConcreteAttributePath & attributePath, - EmberAfAttributeType attributeType, uint16_t size, uint8_t * value) +Status MatterThermostatClusterServerPreAttributeChangedCallback(const app::ConcreteAttributePath & attributePath, + EmberAfAttributeType attributeType, uint16_t size, uint8_t * value) { EndpointId endpoint = attributePath.mEndpointId; int16_t requested; // Limits will be needed for all checks // so we just get them all now + // TODO: use GetSetpointLimits to fetch this information int16_t AbsMinHeatSetpointLimit; int16_t AbsMaxHeatSetpointLimit; int16_t MinHeatSetpointLimit; @@ -649,12 +931,8 @@ MatterThermostatClusterServerPreAttributeChangedCallback(const app::ConcreteAttr if (requested < AbsMinHeatSetpointLimit || requested < MinHeatSetpointLimit || requested > AbsMaxHeatSetpointLimit || requested > MaxHeatSetpointLimit) return Status::InvalidValue; - if (AutoSupported) - { - if (requested > OccupiedCoolingSetpoint - DeadBandTemp) - return Status::InvalidValue; - } - return Status::Success; + return CheckCoolingSetpointDeadband(AutoSupported, requested, std::min(MaxCoolSetpointLimit, AbsMaxCoolSetpointLimit), + DeadBandTemp); } case OccupiedCoolingSetpoint::Id: { @@ -664,12 +942,8 @@ MatterThermostatClusterServerPreAttributeChangedCallback(const app::ConcreteAttr if (requested < AbsMinCoolSetpointLimit || requested < MinCoolSetpointLimit || requested > AbsMaxCoolSetpointLimit || requested > MaxCoolSetpointLimit) return Status::InvalidValue; - if (AutoSupported) - { - if (requested < OccupiedHeatingSetpoint + DeadBandTemp) - return Status::InvalidValue; - } - return Status::Success; + return CheckHeatingSetpointDeadband(AutoSupported, requested, std::max(MinHeatSetpointLimit, AbsMinHeatSetpointLimit), + DeadBandTemp); } case UnoccupiedHeatingSetpoint::Id: { @@ -679,12 +953,8 @@ MatterThermostatClusterServerPreAttributeChangedCallback(const app::ConcreteAttr if (requested < AbsMinHeatSetpointLimit || requested < MinHeatSetpointLimit || requested > AbsMaxHeatSetpointLimit || requested > MaxHeatSetpointLimit) return Status::InvalidValue; - if (AutoSupported) - { - if (requested > UnoccupiedCoolingSetpoint - DeadBandTemp) - return Status::InvalidValue; - } - return Status::Success; + return CheckCoolingSetpointDeadband(AutoSupported, requested, std::min(MaxCoolSetpointLimit, AbsMaxCoolSetpointLimit), + DeadBandTemp); } case UnoccupiedCoolingSetpoint::Id: { requested = static_cast(chip::Encoding::LittleEndian::Get16(value)); @@ -693,12 +963,8 @@ MatterThermostatClusterServerPreAttributeChangedCallback(const app::ConcreteAttr if (requested < AbsMinCoolSetpointLimit || requested < MinCoolSetpointLimit || requested > AbsMaxCoolSetpointLimit || requested > MaxCoolSetpointLimit) return Status::InvalidValue; - if (AutoSupported) - { - if (requested < UnoccupiedHeatingSetpoint + DeadBandTemp) - return Status::InvalidValue; - } - return Status::Success; + return CheckHeatingSetpointDeadband(AutoSupported, requested, std::max(MinHeatSetpointLimit, AbsMinHeatSetpointLimit), + DeadBandTemp); } case MinHeatSetpointLimit::Id: { diff --git a/src/app/codegen-data-model-provider/CodegenDataModelProvider.cpp b/src/app/codegen-data-model-provider/CodegenDataModelProvider.cpp index eab221a86906b8..3e5e3a8cf039c8 100644 --- a/src/app/codegen-data-model-provider/CodegenDataModelProvider.cpp +++ b/src/app/codegen-data-model-provider/CodegenDataModelProvider.cpp @@ -241,6 +241,8 @@ DataModel::CommandEntry CommandEntryFrom(const ConcreteClusterPath & clusterPath entry.info.flags.Set(DataModel::CommandQualityFlags::kFabricScoped, CommandIsFabricScoped(clusterPath.mClusterId, clusterCommandId)); + entry.info.flags.Set(DataModel::CommandQualityFlags::kLargeMessage, + CommandHasLargePayload(clusterPath.mClusterId, clusterCommandId)); return entry; } diff --git a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp index aa357ce4dfb5cb..a558b8e986298a 100644 --- a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp +++ b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp @@ -48,6 +48,7 @@ namespace chip { namespace app { + namespace { using namespace chip::app::Compatibility::Internal; diff --git a/src/app/data-model-provider/MetadataTypes.h b/src/app/data-model-provider/MetadataTypes.h index a3541faeabbf25..c1d173c985ee7a 100644 --- a/src/app/data-model-provider/MetadataTypes.h +++ b/src/app/data-model-provider/MetadataTypes.h @@ -83,10 +83,12 @@ struct AttributeEntry static const AttributeEntry kInvalid; }; +// Bitmask values for different Command qualities. enum class CommandQualityFlags : uint32_t { kFabricScoped = 0x0001, kTimed = 0x0002, // `T` quality on commands + kLargeMessage = 0x0004, // `L` quality on commands }; struct CommandInfo diff --git a/src/app/dynamic_server/AccessControl.cpp b/src/app/dynamic_server/AccessControl.cpp index 9f39040e00b056..75385f49308792 100644 --- a/src/app/dynamic_server/AccessControl.cpp +++ b/src/app/dynamic_server/AccessControl.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -34,22 +35,13 @@ namespace { // DynamicDispatch.cpp. constexpr EndpointId kSupportedEndpoint = 0; -class DeviceTypeResolver : public Access::AccessControl::DeviceTypeResolver +class DeviceTypeResolver : public chip::Access::DynamicProviderDeviceTypeResolver { public: - bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) override - { - chip::app::DataModel::Provider * model = chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); - - for (auto type = model->FirstDeviceType(endpoint); type.has_value(); type = model->NextDeviceType(endpoint, *type)) - { - if (type->deviceTypeId == deviceType) - { - return true; - } - } - return false; - } + DeviceTypeResolver() : + chip::Access::DynamicProviderDeviceTypeResolver( + [] { return chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); }) + {} }; // TODO: Make the policy more configurable by consumers. diff --git a/src/app/icd/client/DefaultICDClientStorage.cpp b/src/app/icd/client/DefaultICDClientStorage.cpp index 2a1bc6a5d4fb86..242b81ef24a562 100644 --- a/src/app/icd/client/DefaultICDClientStorage.cpp +++ b/src/app/icd/client/DefaultICDClientStorage.cpp @@ -542,5 +542,14 @@ CHIP_ERROR DefaultICDClientStorage::ProcessCheckInPayload(const ByteSpan & paylo iterator->Release(); return CHIP_ERROR_NOT_FOUND; } + +void DefaultICDClientStorage::Shutdown() +{ + mICDClientInfoIterators.ReleaseAll(); + mpClientInfoStore = nullptr; + mpKeyStore = nullptr; + mFabricList.clear(); +} + } // namespace app } // namespace chip diff --git a/src/app/icd/client/DefaultICDClientStorage.h b/src/app/icd/client/DefaultICDClientStorage.h index 13064fe649c61b..09431b701460c7 100644 --- a/src/app/icd/client/DefaultICDClientStorage.h +++ b/src/app/icd/client/DefaultICDClientStorage.h @@ -120,6 +120,12 @@ class DefaultICDClientStorage : public ICDClientStorage CHIP_ERROR ProcessCheckInPayload(const ByteSpan & payload, ICDClientInfo & clientInfo, Protocols::SecureChannel::CounterType & counter) override; + /** + * Shut down DefaultICDClientStorage + * + */ + void Shutdown(); + #if CONFIG_BUILD_FOR_HOST_UNIT_TEST size_t GetFabricListSize() { return mFabricList.size(); } diff --git a/src/app/reporting/Engine.cpp b/src/app/reporting/Engine.cpp index 284aa6fa66db06..ea4c0014e71397 100644 --- a/src/app/reporting/Engine.cpp +++ b/src/app/reporting/Engine.cpp @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -53,6 +52,87 @@ Status EventPathValid(DataModel::Provider * model, const ConcreteEventPath & eve return Status::Success; } +DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, + const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, + AttributeReportIBs::Builder & reportBuilder, + const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState) +{ + ChipLogDetail(DataManagement, " Cluster %" PRIx32 ", Attribute %" PRIx32 " is dirty", path.mClusterId, + path.mAttributeId); + DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, + DataModelCallbacks::OperationOrder::Pre, path); + + DataModel::ReadAttributeRequest readRequest; + + if (isFabricFiltered) + { + readRequest.readFlags.Set(DataModel::ReadFlags::kFabricFiltered); + } + readRequest.subjectDescriptor = &subjectDescriptor; + readRequest.path = path; + + DataVersion version = 0; + if (std::optional clusterInfo = dataModel->GetClusterInfo(path); clusterInfo.has_value()) + { + version = clusterInfo->dataVersion; + } + else + { + ChipLogError(DataManagement, "Read request on unknown cluster - no data version available"); + } + + TLV::TLVWriter checkpoint; + reportBuilder.Checkpoint(checkpoint); + + AttributeValueEncoder attributeValueEncoder(reportBuilder, subjectDescriptor, path, version, isFabricFiltered, encoderState); + + DataModel::ActionReturnStatus status = dataModel->ReadAttribute(readRequest, attributeValueEncoder); + + if (status.IsSuccess()) + { + // TODO: this callback being only executed on success is awkward. The Write callback is always done + // for both read and write. + // + // For now this preserves existing/previous code logic, however we should consider to ALWAYS + // call this. + DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, + DataModelCallbacks::OperationOrder::Post, path); + return status; + } + + // Encoder state is relevant for errors in case they are retryable. + // + // Generally only out of space encoding errors would be retryable, however we save the state + // for all errors in case this is information that is useful (retry or error position). + if (encoderState != nullptr) + { + *encoderState = attributeValueEncoder.GetState(); + } + +#if CHIP_CONFIG_DATA_MODEL_EXTRA_LOGGING + // Out of space errors may be chunked data, reporting those cases would be very confusing + // as they are not fully errors. Report only others (which presumably are not recoverable + // and will be sent to the client as well). + if (!status.IsOutOfSpaceEncodingResponse()) + { + DataModel::ActionReturnStatus::StringStorage storage; + ChipLogError(DataManagement, "Failed to read attribute: %s", status.c_str(storage)); + } +#endif + return status; +} + +bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion) +{ + std::optional info = dataModel->GetClusterInfo(path); + if (!info.has_value()) + { + return false; + } + + return (info->dataVersion == dataVersion); +} + } // namespace Engine::Engine(InteractionModelEngine * apImEngine) : mpImEngine(apImEngine) {} @@ -85,9 +165,9 @@ bool Engine::IsClusterDataVersionMatch(const SingleLinkedListNodeGetDataModelProvider(), - ConcreteClusterPath(filter->mValue.mEndpointId, filter->mValue.mClusterId), - filter->mValue.mDataVersion.Value())) + if (!IsClusterDataVersionEqualTo(mpImEngine->GetDataModelProvider(), + ConcreteClusterPath(filter->mValue.mEndpointId, filter->mValue.mClusterId), + filter->mValue.mDataVersion.Value())) { existVersionMismatch = true; } @@ -199,8 +279,8 @@ CHIP_ERROR Engine::BuildSingleReportDataAttributeReportIBs(ReportDataMessage::Bu // Load the saved state from previous encoding session for chunking of one single attribute (list chunking). AttributeEncodeState encodeState = apReadHandler->GetAttributeEncodeState(); DataModel::ActionReturnStatus status = - Impl::RetrieveClusterData(mpImEngine->GetDataModelProvider(), apReadHandler->GetSubjectDescriptor(), - apReadHandler->IsFabricFiltered(), attributeReportIBs, pathForRetrieval, &encodeState); + RetrieveClusterData(mpImEngine->GetDataModelProvider(), apReadHandler->GetSubjectDescriptor(), + apReadHandler->IsFabricFiltered(), attributeReportIBs, pathForRetrieval, &encodeState); if (status.IsError()) { // Operation error set, since this will affect early return or override on status encoding diff --git a/src/app/reporting/Read.cpp b/src/app/reporting/Read.cpp deleted file mode 100644 index db55b14cd257b3..00000000000000 --- a/src/app/reporting/Read.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2024 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include -#include -#include -#include -#include -#include - -namespace chip { -namespace app { -namespace reporting { -namespace Impl { - -DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, - const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, - AttributeReportIBs::Builder & reportBuilder, - const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState) -{ - ChipLogDetail(DataManagement, " Cluster %" PRIx32 ", Attribute %" PRIx32 " is dirty", path.mClusterId, - path.mAttributeId); - DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, - DataModelCallbacks::OperationOrder::Pre, path); - - DataModel::ReadAttributeRequest readRequest; - - if (isFabricFiltered) - { - readRequest.readFlags.Set(DataModel::ReadFlags::kFabricFiltered); - } - readRequest.subjectDescriptor = &subjectDescriptor; - readRequest.path = path; - - DataVersion version = 0; - if (std::optional clusterInfo = dataModel->GetClusterInfo(path); clusterInfo.has_value()) - { - version = clusterInfo->dataVersion; - } - else - { - ChipLogError(DataManagement, "Read request on unknown cluster - no data version available"); - } - - TLV::TLVWriter checkpoint; - reportBuilder.Checkpoint(checkpoint); - - AttributeValueEncoder attributeValueEncoder(reportBuilder, subjectDescriptor, path, version, isFabricFiltered, encoderState); - - DataModel::ActionReturnStatus status = dataModel->ReadAttribute(readRequest, attributeValueEncoder); - - if (status.IsSuccess()) - { - // Odd ifdef is to only do this if the `Read-Check` does not do it already. - // TODO: this callback being only executed on success is awkward. The Write callback is always done - // for both read and write. - // - // For now this preserves existing/previous code logic, however we should consider to ALWAYS - // call this. - DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, - DataModelCallbacks::OperationOrder::Post, path); - return status; - } - - // Encoder state is relevant for errors in case they are retryable. - // - // Generally only out of space encoding errors would be retryable, however we save the state - // for all errors in case this is information that is useful (retry or error position). - if (encoderState != nullptr) - { - *encoderState = attributeValueEncoder.GetState(); - } - - // Out of space errors may be chunked data, reporting those cases would be very confusing - // as they are not fully errors. Report only others (which presumably are not recoverable - // and will be sent to the client as well). - if (!status.IsOutOfSpaceEncodingResponse()) - { - DataModel::ActionReturnStatus::StringStorage storage; -#if CHIP_CONFIG_DATA_MODEL_EXTRA_LOGGING - ChipLogError(DataManagement, "Failed to read attribute: %s", status.c_str(storage)); -#endif - } - return status; -} - -bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion) -{ - std::optional info = dataModel->GetClusterInfo(path); - if (!info.has_value()) - { - return false; - } - - return (info->dataVersion == dataVersion); -} - -} // namespace Impl -} // namespace reporting -} // namespace app -} // namespace chip diff --git a/src/app/reporting/Read.h b/src/app/reporting/Read.h deleted file mode 100644 index 6731addfab736e..00000000000000 --- a/src/app/reporting/Read.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2024 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace chip { -namespace app { -namespace reporting { -namespace Impl { - -DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, - const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, - AttributeReportIBs::Builder & reportBuilder, - const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState); - -bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion); -} // namespace Impl - -} // namespace reporting -} // namespace app -} // namespace chip diff --git a/src/app/server/BUILD.gn b/src/app/server/BUILD.gn index 4addf8eea938e3..43c970843ba66d 100644 --- a/src/app/server/BUILD.gn +++ b/src/app/server/BUILD.gn @@ -52,10 +52,13 @@ static_library("server") { cflags = [ "-Wconversion" ] public_deps = [ + "${chip_root}/src/access", + "${chip_root}/src/access:provider-impl", "${chip_root}/src/app", "${chip_root}/src/app:test-event-trigger", "${chip_root}/src/app/icd/server:icd-server-config", "${chip_root}/src/app/icd/server:observer", + "${chip_root}/src/app/util/persistence", "${chip_root}/src/lib/address_resolve", "${chip_root}/src/lib/dnssd", "${chip_root}/src/lib/dnssd:naming", diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index cfb8d21de3a130..6808431b67bf4f 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -17,6 +17,7 @@ #include +#include #include #include @@ -82,23 +83,9 @@ using chip::Transport::TcpListenParameters; namespace { -class DeviceTypeResolver : public chip::Access::AccessControl::DeviceTypeResolver -{ -public: - bool IsDeviceTypeOnEndpoint(chip::DeviceTypeId deviceType, chip::EndpointId endpoint) override - { - chip::app::DataModel::Provider * model = chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); - - for (auto type = model->FirstDeviceType(endpoint); type.has_value(); type = model->NextDeviceType(endpoint, *type)) - { - if (type->deviceTypeId == deviceType) - { - return true; - } - } - return false; - } -} sDeviceTypeResolver; +chip::Access::DynamicProviderDeviceTypeResolver sDeviceTypeResolver([] { + return chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); +}); } // namespace diff --git a/src/app/server/Server.h b/src/app/server/Server.h index 2f61197fcee2dd..fc6f7ac10750d3 100644 --- a/src/app/server/Server.h +++ b/src/app/server/Server.h @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -81,6 +80,11 @@ #endif // CHIP_CONFIG_ENABLE_ICD_CIP #endif // CHIP_CONFIG_ENABLE_ICD_SERVER +// TODO: https://github.com/project-chip/connectedhomeip/issues/36472 +// this strongly couples Server to Ember and this dependency should +// be removed +#include + namespace chip { inline constexpr size_t kMaxBlePendingPackets = 1; diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 03dadc061740a6..105d09f7ad6fc8 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -181,8 +181,6 @@ source_set("app-test-stubs") { "test-interaction-model-api.h", ] - public_configs = [ "${chip_root}/src/lib/support/pw_log_chip:config" ] - public_deps = [ "${chip_root}/src/app/util/mock:mock_codegen_data_model", "${chip_root}/src/app/util/mock:mock_ember", @@ -200,7 +198,6 @@ chip_test_suite("tests") { "TestAttributeAccessInterfaceCache.cpp", "TestAttributePathExpandIterator.cpp", "TestAttributePathParams.cpp", - "TestAttributePersistenceProvider.cpp", "TestAttributeValueDecoder.cpp", "TestAttributeValueEncoder.cpp", "TestBasicCommandPathRegistry.cpp", diff --git a/src/app/tests/suites/certification/Test_TC_DEMM_1_2.yaml b/src/app/tests/suites/certification/Test_TC_DEMM_1_2.yaml index 900428998445ea..c03711c6bc4c8f 100644 --- a/src/app/tests/suites/certification/Test_TC_DEMM_1_2.yaml +++ b/src/app/tests/suites/certification/Test_TC_DEMM_1_2.yaml @@ -36,11 +36,11 @@ tests: - Verify that each ModeOptionsStruct entry’s ModeTags field has: at least one entry the values of the Value fields that are not larger than 16 bits - for each Value field: Is the mode tag value a defined common tag value (Auto(0x0000), Quick(0x0001), Quiet(0x0002), LowNoise(0x0003), LowEnergy(0x0004), Vacation(0x0005), Min(0x0006), Max(0x0007), Night(0x0008), Day(0x0009)) or a defined cluster-derived tag value (No Optimization, Device Optimization, Local Optimization, Grid Optimization) or in the MfgTags (0x8000 to 0xBFFF) range - - for at least one Value field: Is the mode tag value a defined common tag value (Auto(0x0000), Quick(0x0001), Quiet(0x0002), LowNoise(0x0003), LowEnergy(0x0004), Vacation(0x0005), Min(0x0006), Max(0x0007), Night(0x0008), Day(0x0009)) or a derived cluster value (RapidCool, RapidFreeze) - - Verify that at least one ModeOptionsStruct entry includes either the RapidCool semantic tag or the RapidFreeze semantic tag in the SemanticTags field + - for at least one Value field: Is the mode tag value a defined common tag value (Auto(0x0000), Quick(0x0001), Quiet(0x0002), LowNoise(0x0003), LowEnergy(0x0004), Vacation(0x0005), Min(0x0006), Max(0x0007), Night(0x0008), Day(0x0009)) or a derived cluster value (No Optimization, Device Optimization, Local Optimization, Grid Optimization) + - Verify that at least one SupportedModes entry includes the No Optimization mode tag or Local Optimization mode tag or Grid Optimization mode tag. + - Verify that an entry in the SupportedModes attribute that include one of Device Optimization, Local Optimization, Grid Optimization does not also include No Optimization mode tag. - Save the Mode field values as supported_modes_dut on the TH (Chip-tool) and below is the sample log provided for the raspi platform: - [1705923890.093456][23589:23591] CHIP:DMG: } [1705923890.094137][23589:23591] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_009F Attribute 0x0000_0000 DataVersion: 2217281174 [1705923890.094312][23589:23591] CHIP:TOO: SupportedModes: 5 entries diff --git a/src/app/util/attribute-storage-null-handling.h b/src/app/util/attribute-storage-null-handling.h index 22dd0e6dab5ce3..ace14c48c8517b 100644 --- a/src/app/util/attribute-storage-null-handling.h +++ b/src/app/util/attribute-storage-null-handling.h @@ -60,22 +60,27 @@ struct NumericAttributeTraits static constexpr WorkingType StorageToWorking(StorageType storageValue) { return storageValue; } private: + // Ensure that this generic NumericAttributeTraits implementation is being used for some type for which it + // actually works. + static_assert(std::is_floating_point_v || std::is_integral_v || std::is_enum_v, + "NumericAttributeTraits specialization needed for this type"); + // We need to make sure we never look like we are assigning NaN to an // integer, even in a not-reached branch. Without "if constexpr", the best // we can do is these functions using enable_if. - template ::value, int> = 0> + template , int> = 0> static constexpr StorageType GetNullValue() { return std::numeric_limits::quiet_NaN(); } - template ::value, int> = 0> + template , int> = 0> static constexpr StorageType GetNullValue() { return std::is_signed::value ? std::numeric_limits::min() : std::numeric_limits::max(); } - template ::value, int> = 0> + template , int> = 0> static constexpr StorageType GetNullValue() { static_assert(!std::is_signed>::value, "Enums must be unsigned"); diff --git a/src/app/util/attribute-storage.cpp b/src/app/util/attribute-storage.cpp index 51c01c7e43fa80..4d9cc2368f6900 100644 --- a/src/app/util/attribute-storage.cpp +++ b/src/app/util/attribute-storage.cpp @@ -20,7 +20,6 @@ #include #include -#include #include #include #include @@ -28,6 +27,7 @@ #include #include #include +#include #include #include #include diff --git a/src/app/AttributePersistenceProvider.h b/src/app/util/persistence/AttributePersistenceProvider.h similarity index 100% rename from src/app/AttributePersistenceProvider.h rename to src/app/util/persistence/AttributePersistenceProvider.h diff --git a/src/app/util/persistence/BUILD.gn b/src/app/util/persistence/BUILD.gn new file mode 100644 index 00000000000000..dbc8dbe31b0c58 --- /dev/null +++ b/src/app/util/persistence/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") + +source_set("persistence") { + sources = [ + "AttributePersistenceProvider.h", + "DefaultAttributePersistenceProvider.cpp", + "DefaultAttributePersistenceProvider.h", + ] + + public_deps = [ + "${chip_root}/src/app:attribute-persistence", + "${chip_root}/src/app:paths", + "${chip_root}/src/app/util:types", + "${chip_root}/src/lib/core", + "${chip_root}/src/lib/support", + "${chip_root}/src/lib/support:span", + ] +} + +source_set("deferred") { + sources = [ + "DeferredAttributePersistenceProvider.cpp", + "DeferredAttributePersistenceProvider.h", + ] + + public_deps = [ + ":persistence", + "${chip_root}/src/lib/support", + "${chip_root}/src/lib/support:span", + "${chip_root}/src/platform", + "${chip_root}/src/system", + ] +} diff --git a/src/app/DefaultAttributePersistenceProvider.cpp b/src/app/util/persistence/DefaultAttributePersistenceProvider.cpp similarity index 98% rename from src/app/DefaultAttributePersistenceProvider.cpp rename to src/app/util/persistence/DefaultAttributePersistenceProvider.cpp index 40ce5213628944..70488e80e7e1d7 100644 --- a/src/app/DefaultAttributePersistenceProvider.cpp +++ b/src/app/util/persistence/DefaultAttributePersistenceProvider.cpp @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include -#include #include #include #include diff --git a/src/app/DefaultAttributePersistenceProvider.h b/src/app/util/persistence/DefaultAttributePersistenceProvider.h similarity index 97% rename from src/app/DefaultAttributePersistenceProvider.h rename to src/app/util/persistence/DefaultAttributePersistenceProvider.h index 3e18808f366d37..a4796f2b63b11d 100644 --- a/src/app/DefaultAttributePersistenceProvider.h +++ b/src/app/util/persistence/DefaultAttributePersistenceProvider.h @@ -15,8 +15,8 @@ */ #pragma once -#include #include +#include #include #include diff --git a/src/app/DeferredAttributePersistenceProvider.cpp b/src/app/util/persistence/DeferredAttributePersistenceProvider.cpp similarity index 97% rename from src/app/DeferredAttributePersistenceProvider.cpp rename to src/app/util/persistence/DeferredAttributePersistenceProvider.cpp index 26adcb18c8dcf7..6b1822f29257ac 100644 --- a/src/app/DeferredAttributePersistenceProvider.cpp +++ b/src/app/util/persistence/DeferredAttributePersistenceProvider.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include diff --git a/src/app/DeferredAttributePersistenceProvider.h b/src/app/util/persistence/DeferredAttributePersistenceProvider.h similarity index 98% rename from src/app/DeferredAttributePersistenceProvider.h rename to src/app/util/persistence/DeferredAttributePersistenceProvider.h index 6c641dc17d4400..592408b96b39ac 100644 --- a/src/app/DeferredAttributePersistenceProvider.h +++ b/src/app/util/persistence/DeferredAttributePersistenceProvider.h @@ -15,7 +15,7 @@ */ #pragma once -#include +#include #include #include #include diff --git a/examples/platform/silabs/efr32/wf200/wf200.gni b/src/app/util/persistence/tests/BUILD.gn similarity index 54% rename from examples/platform/silabs/efr32/wf200/wf200.gni rename to src/app/util/persistence/tests/BUILD.gn index c7ebbb8647788c..7a0bd524305623 100644 --- a/examples/platform/silabs/efr32/wf200/wf200.gni +++ b/src/app/util/persistence/tests/BUILD.gn @@ -12,19 +12,23 @@ # See the License for the specific language governing permissions and # limitations under the License. +import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/efr32_sdk.gni") -import("${silabs_sdk_build_root}/efr32_sdk.gni") +import("//build_overrides/pigweed.gni") -wf200_plat_incs = [ - "${examples_plat_dir}/wf200", - "${silabs_common_plat_dir}/wifi", -] +import("${chip_root}/build/chip/chip_test_suite.gni") -wf200_plat_src = [ - "${examples_plat_dir}/wf200/sl_wfx_task.c", - "${examples_plat_dir}/wf200/wf200_init.c", - "${examples_plat_dir}/wf200/efr_spi.c", - "${examples_plat_dir}/wf200/Wf200WifiInterface.cpp", - "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", -] +chip_test_suite("tests") { + output_name = "libAppUtilPersistenceTests" + + test_sources = [ "TestAttributePersistenceProvider.cpp" ] + + cflags = [ "-Wconversion" ] + + public_deps = [ + "${chip_root}/src/app/common:cluster-objects", + "${chip_root}/src/app/util/persistence", + "${chip_root}/src/lib/core:string-builder-adapters", + "${chip_root}/src/lib/support:testing", + ] +} diff --git a/src/app/tests/TestAttributePersistenceProvider.cpp b/src/app/util/persistence/tests/TestAttributePersistenceProvider.cpp similarity index 99% rename from src/app/tests/TestAttributePersistenceProvider.cpp rename to src/app/util/persistence/tests/TestAttributePersistenceProvider.cpp index 1b8c7ee3d3872c..1324f37a7138c3 100644 --- a/src/app/tests/TestAttributePersistenceProvider.cpp +++ b/src/app/util/persistence/tests/TestAttributePersistenceProvider.cpp @@ -17,7 +17,7 @@ */ #include -#include +#include #include #include #include diff --git a/src/app/zap-templates/templates/app/cluster-objects-src.zapt b/src/app/zap-templates/templates/app/cluster-objects-src.zapt index 1322756b85213e..e32a0be1165120 100644 --- a/src/app/zap-templates/templates/app/cluster-objects-src.zapt +++ b/src/app/zap-templates/templates/app/cluster-objects-src.zapt @@ -261,5 +261,21 @@ bool CommandIsFabricScoped(ClusterId aCluster, CommandId aCommand) return false; } +bool CommandHasLargePayload(ClusterId aCluster, CommandId aCommand) +{ + {{#zcl_clusters}} + {{#zcl_commands}} + {{#if isLargeMessage}} + if ((aCluster == Clusters::{{asUpperCamelCase parent.name}}::Id) && + (aCommand == Clusters::{{asUpperCamelCase parent.name}}::Commands::{{asUpperCamelCase name}}::Id)) + { + return true; + } + {{/if}} + {{/zcl_commands}} + {{/zcl_clusters}} + return false; +} + } // namespace app } // namespace chip diff --git a/src/app/zap-templates/templates/app/cluster-objects.zapt b/src/app/zap-templates/templates/app/cluster-objects.zapt index e9f42b17c5ff66..00cd367f85bfcb 100644 --- a/src/app/zap-templates/templates/app/cluster-objects.zapt +++ b/src/app/zap-templates/templates/app/cluster-objects.zapt @@ -228,6 +228,7 @@ public: bool CommandNeedsTimedInvoke(ClusterId aCluster, CommandId aCommand); bool CommandIsFabricScoped(ClusterId aCluster, CommandId aCommand); +bool CommandHasLargePayload(ClusterId aCluster, CommandId aCommand); } // namespace app } // namespace chip diff --git a/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml index 13d1f7a9e77be2..516fe8753a3ef8 100644 --- a/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml @@ -18,10 +18,10 @@ limitations under the License. XML generated by Alchemy; DO NOT EDIT. Source: src/app_clusters/CameraAVStreamManagement.adoc Parameters: in-progress -Git: 0.9-fall2024-411-g9835b5cd7 +Git: 1.3-3830-g1f08d6f40 --> - + @@ -144,152 +144,309 @@ Git: 0.9-fall2024-411-g9835b5cd7 - + Cameras Camera AV Stream Management 0x0551 CAMERA_AV_STREAM_MANAGEMENT_CLUSTER The Camera AV Stream Management cluster is used to allow clients to manage, control, and configure various audio, video, and snapshot streams on a camera. true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - MaxConcurrentVideoEncoders - MaxEncodedPixelRate - VideoSensorParams - NightVisionCapable - MinViewport - RateDistortionTradeOffPoints - MaxContentBufferSize - MicrophoneCapabilities - SpeakerCapabilities - TwoWayTalkSupport - SupportedSnapshotParams - MaxNetworkBandwidth - CurrentFrameRate - + + MaxConcurrentVideoEncoders + + + + + + MaxEncodedPixelRate + + + + + + VideoSensorParams + + + + + + NightVisionCapable + + + + + + MinViewport + + + + + + RateDistortionTradeOffPoints + + + + + + MaxContentBufferSize + + + + + + MicrophoneCapabilities + + + + + + SpeakerCapabilities + + + + + + + + + TwoWayTalkSupport + + + + + + + + + SupportedSnapshotParams + + + + + MaxNetworkBandwidth + + CurrentFrameRate + + + + + + HDRModeEnabled + + + + + FabricsUsingCamera + + AllocatedVideoStreams + + + + + + AllocatedAudioStreams + + + + + + AllocatedSnapshotStreams + + + + + + RankedVideoStreamPrioritiesList + + + + + + SoftRecordingPrivacyModeEnabled + + + - CurrentVideoCodecs - CurrentSnapshotConfig - FabricsUsingCamera - AllocatedVideoStreams - AllocatedAudioStreams - AllocatedSnapshotStreams - - - - - SoftRecordingPrivacyModeEnabled - SoftLivestreamPrivacyModeEnabled - HardPrivacyModeOn - + + SoftLivestreamPrivacyModeEnabled + + + + + + HardPrivacyModeOn + + + + NightVision + + + + + + - + + NightVisionIllum + + + + + + - + + Viewport + + + - + + SpeakerMuted + + + + + + - + + SpeakerVolumeLevel + + + + + + - Viewport - + + SpeakerMaxLevel - + + + + + + - + + SpeakerMinLevel - + + + + + + - + + MicrophoneMuted + + + - + + MicrophoneVolumeLevel + + + - + + MicrophoneMaxLevel - + + + - + + MicrophoneMinLevel - + + + - + + MicrophoneAGCEnabled + + + - + + ImageRotation + + + - + + ImageFlipHorizontal + + + - ImageRotation - ImageFlipHorizontal - ImageFlipVertical - + + ImageFlipVertical + + + - + + LocalVideoRecordingEnabled + + + + + + - + + LocalSnapshotRecordingEnabled + + + + + + - + + StatusLightEnabled + - + + StatusLightBrightness + This command SHALL allocate an audio stream on the camera and return an allocated audio stream identifier. @@ -300,17 +457,26 @@ Git: 0.9-fall2024-411-g9835b5cd7 + + + This command SHALL be sent by the camera in response to the AudioStreamAllocate command, carrying the newly allocated audio stream identifier. + + + This command SHALL deallocate an audio stream on the camera, corresponding to the given audio stream identifier. + + + @@ -328,11 +494,17 @@ Git: 0.9-fall2024-411-g9835b5cd7 + + + This command SHALL be sent by the camera in response to the VideoStreamAllocate command, carrying the newly allocated video stream identifier. + + + @@ -342,34 +514,49 @@ Git: 0.9-fall2024-411-g9835b5cd7 + + + This command SHALL deallocate a video stream on the camera, corresponding to the given video stream identifier. + + + This command SHALL allocate a snapshot stream on the device and return an allocated snapshot stream identifier. - + + + + This command SHALL be sent by the device in response to the SnapshotStreamAllocate command, carrying the newly allocated snapshot stream identifier. + + + This command SHALL deallocate an snapshot stream on the camera, corresponding to the given snapshot stream identifier. + + + @@ -380,40 +567,23 @@ Git: 0.9-fall2024-411-g9835b5cd7 This command SHALL return a Snapshot from the camera. - + + + + This command SHALL be sent by the device in response to the CaptureSnapshot command, carrying the requested snapshot. + - - - - This command sets the viewport in all video streams. - - - - - - The data fields for this command SHALL be as follows: - - - - - - The data fields for this command SHALL be as follows: - - - - - - The data fields for this command SHALL be as follows: - - + + + @@ -429,6 +599,9 @@ Git: 0.9-fall2024-411-g9835b5cd7 This event SHALL be generated when there is a modification in the corresponding video stream. + + + @@ -440,6 +613,9 @@ Git: 0.9-fall2024-411-g9835b5cd7 This event SHALL be generated when there is a modification in the corresponding audio stream. + + + @@ -451,7 +627,39 @@ Git: 0.9-fall2024-411-g9835b5cd7 This event SHALL be generated when there is a modification in the corresponding snapshot stream. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml index 8e1feb4fb30c55..54fe73d5f0df74 100644 --- a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml +++ b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml @@ -40,7 +40,6 @@ limitations under the License. ACL - EXTENSION DATA_MODEL_REVISION @@ -2156,7 +2155,7 @@ limitations under the License. - + MA-oven CHIP Oven @@ -2252,7 +2251,7 @@ limitations under the License. - + MA-laundry-dryer CHIP Laundry Dryer @@ -2445,7 +2444,6 @@ limitations under the License. - MA-all-clusters-app CHIP @@ -2664,7 +2662,7 @@ limitations under the License. - + Energy EVSE CHIP EVSE @@ -2683,11 +2681,11 @@ limitations under the License. Device Energy Management CHIP Device Energy Management - Simple + Utility 0x0103 0x050D + Endpoint - diff --git a/src/app/zap-templates/zcl/data-model/chip/zone-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/zone-management-cluster.xml index 27a947b5610015..32e9a4b18ad4b0 100644 --- a/src/app/zap-templates/zcl/data-model/chip/zone-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/zone-management-cluster.xml @@ -18,7 +18,7 @@ limitations under the License. XML generated by Alchemy; DO NOT EDIT. Source: src/app_clusters/ZoneManagement.adoc Parameters: in-progress -Git: 0.9-fall2024-302-gebc8548b3 +Git: 1.4-282-gad46b0990 --> @@ -78,12 +78,13 @@ Git: 0.9-fall2024-302-gebc8548b3 - + + @@ -94,16 +95,19 @@ Git: 0.9-fall2024-302-gebc8548b3 This cluster provides an interface to manage regions of interest, or Zones, which can be either manufacturer or user defined. true - - + + + + + true SupportedZoneSources Zones - TimeControl - Sensitivity + Triggers + Sensitivity This command SHALL create and store a TwoD Cartesian Zone. @@ -148,7 +152,7 @@ Git: 0.9-fall2024-302-gebc8548b3 - This event SHALL be generated when either when the TriggerDetectedDuration value is exceeded by the TimeSinceInitialTrigger value or when the MaxDuration value is exceeded by the TimeSinceInitialTrigger value as described in ZoneTriggeringTimeControlStruct. + This event SHALL be generated when either when the TriggerDetectedDuration value is exceeded by the TimeSinceInitialTrigger value or when the MaxDuration value is exceeded by the TimeSinceInitialTrigger value as described in ZoneTriggerControlStruct. diff --git a/src/app/zap-templates/zcl/zcl-with-test-extensions.json b/src/app/zap-templates/zcl/zcl-with-test-extensions.json index 39301cdc30cecc..0912be1df2db37 100644 --- a/src/app/zap-templates/zcl/zcl-with-test-extensions.json +++ b/src/app/zap-templates/zcl/zcl-with-test-extensions.json @@ -677,7 +677,6 @@ "MinViewport", "MicrophoneCapabilities", "SpeakerCapabilities", - "CurrentSnapshotConfig", "Viewport" ] }, diff --git a/src/app/zap-templates/zcl/zcl.json b/src/app/zap-templates/zcl/zcl.json index c2de6acabf2951..3a62c4c84ca6eb 100644 --- a/src/app/zap-templates/zcl/zcl.json +++ b/src/app/zap-templates/zcl/zcl.json @@ -671,7 +671,6 @@ "MinViewport", "MicrophoneCapabilities", "SpeakerCapabilities", - "CurrentSnapshotConfig", "Viewport" ] }, diff --git a/src/controller/CHIPDeviceControllerSystemState.h b/src/controller/CHIPDeviceControllerSystemState.h index e040ad14616431..0a6476ff38e49f 100644 --- a/src/controller/CHIPDeviceControllerSystemState.h +++ b/src/controller/CHIPDeviceControllerSystemState.h @@ -201,7 +201,7 @@ class DeviceControllerSystemState // // The stack will shut down when all references are released. // - // NB: The system state is owned by the factory; Relase() will not free it + // NB: The system state is owned by the factory; Release() will not free it // but will free its members (Shutdown()). // // Returns true if the system state was shut down in response to this call. diff --git a/src/controller/data_model/controller-clusters.matter b/src/controller/data_model/controller-clusters.matter index 24c7e00c623b53..31da395b05cd31 100644 --- a/src/controller/data_model/controller-clusters.matter +++ b/src/controller/data_model/controller-clusters.matter @@ -9443,6 +9443,7 @@ provisional cluster ZoneManagement = 1360 { bitmap Feature : bitmap32 { kTwoDimensionalCartesianZone = 0x1; + kPerZoneSensitivity = 0x2; } struct TwoDCartesianVertexStruct { @@ -9463,11 +9464,12 @@ provisional cluster ZoneManagement = 1360 { ZoneSourceEnum zoneSource = 2; } - struct ZoneTriggeringTimeControlStruct { + struct ZoneTriggerControlStruct { int16u initialDuration = 0; int16u augmentationDuration = 1; elapsed_s maxDuration = 2; int16u blindDuration = 3; + optional int8u sensitivity = 4; } info event ZoneTriggered = 0 { @@ -9482,8 +9484,8 @@ provisional cluster ZoneManagement = 1360 { readonly attribute ZoneSourceEnum supportedZoneSources[] = 0; readonly attribute optional ZoneInformationStruct zones[] = 1; - attribute ZoneTriggeringTimeControlStruct timeControl[] = 2; - attribute int8u sensitivity = 3; + attribute ZoneTriggerControlStruct triggers[] = 2; + attribute optional int8u sensitivity = 3; readonly attribute command_id generatedCommandList[] = 65528; readonly attribute command_id acceptedCommandList[] = 65529; readonly attribute event_id eventList[] = 65530; @@ -9566,12 +9568,12 @@ provisional cluster CameraAvStreamManagement = 1361 { } bitmap Feature : bitmap32 { - kPrivacy = 0x1; - kAudio = 0x2; - kSpeaker = 0x4; - kImageControl = 0x8; - kVideo = 0x10; - kSnapshot = 0x20; + kAudio = 0x1; + kVideo = 0x2; + kSnapshot = 0x4; + kPrivacy = 0x8; + kSpeaker = 0x10; + kImageControl = 0x20; kWatermark = 0x40; kOnScreenDisplay = 0x80; kLocalStorage = 0x100; @@ -9703,39 +9705,33 @@ provisional cluster CameraAvStreamManagement = 1361 { readonly attribute int32u maxNetworkBandwidth = 11; readonly attribute optional int16u currentFrameRate = 12; attribute access(read: manage, write: manage) optional boolean HDRModeEnabled = 13; - readonly attribute optional VideoCodecEnum currentVideoCodecs[] = 14; - readonly attribute optional SnapshotParamsStruct currentSnapshotConfig = 15; - readonly attribute fabric_idx fabricsUsingCamera[] = 16; - readonly attribute optional VideoStreamStruct allocatedVideoStreams[] = 17; - readonly attribute optional AudioStreamStruct allocatedAudioStreams[] = 18; - readonly attribute optional SnapshotStreamStruct allocatedSnapshotStreams[] = 19; - attribute access(read: administer, write: administer) optional StreamTypeEnum rankedVideoStreamPrioritiesList[] = 20; - attribute optional boolean softRecordingPrivacyModeEnabled = 21; - attribute optional boolean softLivestreamPrivacyModeEnabled = 22; - readonly attribute optional boolean hardPrivacyModeOn = 23; - attribute access(read: manage, write: manage) optional TriStateAutoEnum nightVision = 24; - attribute access(read: manage, write: manage) optional TriStateAutoEnum nightVisionIllum = 25; - attribute access(read: manage, write: manage) optional boolean AWBEnabled = 26; - attribute access(read: manage, write: manage) optional boolean autoShutterSpeedEnabled = 27; - attribute access(read: manage, write: manage) optional boolean autoISOEnabled = 28; - readonly attribute optional ViewportStruct viewport = 29; - attribute access(read: manage, write: manage) optional boolean speakerMuted = 30; - attribute access(read: manage, write: manage) optional int8u speakerVolumeLevel = 31; - attribute access(read: manage, write: manage) optional int8u speakerMaxLevel = 32; - attribute access(read: manage, write: manage) optional int8u speakerMinLevel = 33; - attribute access(read: manage, write: manage) optional boolean microphoneMuted = 34; - attribute access(read: manage, write: manage) optional int8u microphoneVolumeLevel = 35; - attribute access(read: manage, write: manage) optional int8u microphoneMaxLevel = 36; - attribute access(read: manage, write: manage) optional int8u microphoneMinLevel = 37; - attribute access(read: manage, write: manage) optional boolean microphoneAGCEnabled = 38; - readonly attribute optional int16u imageRotation = 39; - readonly attribute optional boolean imageFlipHorizontal = 40; - readonly attribute optional boolean imageFlipVertical = 41; - attribute access(read: manage, write: manage) optional boolean localVideoRecordingEnabled = 42; - attribute access(read: manage, write: manage) optional boolean localSnapshotRecordingEnabled = 43; - attribute access(read: manage, write: manage) optional boolean statusLightEnabled = 44; - attribute access(read: manage, write: manage) optional ThreeLevelAutoEnum statusLightBrightness = 45; - attribute access(read: manage, write: manage) optional TriStateAutoEnum depthSensorStatus = 46; + readonly attribute fabric_idx fabricsUsingCamera[] = 14; + readonly attribute optional VideoStreamStruct allocatedVideoStreams[] = 15; + readonly attribute optional AudioStreamStruct allocatedAudioStreams[] = 16; + readonly attribute optional SnapshotStreamStruct allocatedSnapshotStreams[] = 17; + readonly attribute optional StreamTypeEnum rankedVideoStreamPrioritiesList[] = 18; + attribute optional boolean softRecordingPrivacyModeEnabled = 19; + attribute optional boolean softLivestreamPrivacyModeEnabled = 20; + readonly attribute optional boolean hardPrivacyModeOn = 21; + attribute access(read: manage, write: manage) optional TriStateAutoEnum nightVision = 22; + attribute access(read: manage, write: manage) optional TriStateAutoEnum nightVisionIllum = 23; + attribute access(read: manage, write: manage) optional ViewportStruct viewport = 24; + attribute access(read: manage, write: manage) optional boolean speakerMuted = 25; + attribute access(read: manage, write: manage) optional int8u speakerVolumeLevel = 26; + readonly attribute access(read: manage) optional int8u speakerMaxLevel = 27; + readonly attribute access(read: manage) optional int8u speakerMinLevel = 28; + attribute access(read: manage, write: manage) optional boolean microphoneMuted = 29; + attribute access(read: manage, write: manage) optional int8u microphoneVolumeLevel = 30; + readonly attribute access(read: manage) optional int8u microphoneMaxLevel = 31; + readonly attribute access(read: manage) optional int8u microphoneMinLevel = 32; + attribute access(read: manage, write: manage) optional boolean microphoneAGCEnabled = 33; + attribute access(read: manage, write: manage) optional int16u imageRotation = 34; + attribute access(read: manage, write: manage) optional boolean imageFlipHorizontal = 35; + attribute access(read: manage, write: manage) optional boolean imageFlipVertical = 36; + attribute access(read: manage, write: manage) optional boolean localVideoRecordingEnabled = 37; + attribute access(read: manage, write: manage) optional boolean localSnapshotRecordingEnabled = 38; + attribute access(read: manage, write: manage) optional boolean statusLightEnabled = 39; + attribute access(read: manage, write: manage) optional ThreeLevelAutoEnum statusLightBrightness = 40; readonly attribute command_id generatedCommandList[] = 65528; readonly attribute command_id acceptedCommandList[] = 65529; readonly attribute event_id eventList[] = 65530; @@ -9792,7 +9788,7 @@ provisional cluster CameraAvStreamManagement = 1361 { request struct SnapshotStreamAllocateRequest { ImageCodecEnum imageCodec = 0; - int16u frameRate = 1; + int16u maxFrameRate = 1; int32u bitRate = 2; VideoResolutionStruct minResolution = 3; VideoResolutionStruct maxResolution = 4; @@ -9822,22 +9818,6 @@ provisional cluster CameraAvStreamManagement = 1361 { VideoResolutionStruct resolution = 2; } - request struct SetViewportRequest { - ViewportStruct viewport = 0; - } - - request struct SetImageRotationRequest { - int16u angle = 0; - } - - request struct SetImageFlipHorizontalRequest { - boolean enabled = 0; - } - - request struct SetImageFlipVerticalRequest { - boolean enabled = 0; - } - /** This command SHALL allocate an audio stream on the camera and return an allocated audio stream identifier. */ command access(invoke: manage) AudioStreamAllocate(AudioStreamAllocateRequest): AudioStreamAllocateResponse = 0; /** This command SHALL deallocate an audio stream on the camera, corresponding to the given audio stream identifier. */ @@ -9855,15 +9835,7 @@ provisional cluster CameraAvStreamManagement = 1361 { /** This command SHALL set the relative priorities of the various stream types on the camera. */ command access(invoke: administer) SetStreamPriorities(SetStreamPrioritiesRequest): DefaultSuccess = 10; /** This command SHALL return a Snapshot from the camera. */ - command access(invoke: manage) CaptureSnapshot(CaptureSnapshotRequest): DefaultSuccess = 11; - /** This command sets the viewport in all video streams. */ - command access(invoke: manage) SetViewport(SetViewportRequest): DefaultSuccess = 13; - /** The data fields for this command SHALL be as follows: */ - command access(invoke: manage) SetImageRotation(SetImageRotationRequest): DefaultSuccess = 14; - /** The data fields for this command SHALL be as follows: */ - command access(invoke: manage) SetImageFlipHorizontal(SetImageFlipHorizontalRequest): DefaultSuccess = 15; - /** The data fields for this command SHALL be as follows: */ - command access(invoke: manage) SetImageFlipVertical(SetImageFlipVerticalRequest): DefaultSuccess = 16; + command CaptureSnapshot(CaptureSnapshotRequest): DefaultSuccess = 11; } /** The WebRTC transport provider cluster provides a way for stream providers (e.g. Cameras) to stream or receive their data through WebRTC. */ diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 7f821fefc0c9ac..3eb6dd82e459cd 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -50,6 +50,7 @@ using namespace TLV; AndroidDeviceControllerWrapper::~AndroidDeviceControllerWrapper() { + getICDClientStorage()->Shutdown(); mController->Shutdown(); if (mKeypairBridge != nullptr) diff --git a/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java b/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java index 06b8dd8ff0b54c..228e0236ed0785 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java @@ -59283,7 +59283,7 @@ public static class ZoneManagementCluster extends BaseChipCluster { private static final long SUPPORTED_ZONE_SOURCES_ATTRIBUTE_ID = 0L; private static final long ZONES_ATTRIBUTE_ID = 1L; - private static final long TIME_CONTROL_ATTRIBUTE_ID = 2L; + private static final long TRIGGERS_ATTRIBUTE_ID = 2L; private static final long SENSITIVITY_ATTRIBUTE_ID = 3L; private static final long GENERATED_COMMAND_LIST_ATTRIBUTE_ID = 65528L; private static final long ACCEPTED_COMMAND_LIST_ATTRIBUTE_ID = 65529L; @@ -59422,8 +59422,8 @@ public interface ZonesAttributeCallback extends BaseAttributeCallback { void onSuccess(List value); } - public interface TimeControlAttributeCallback extends BaseAttributeCallback { - void onSuccess(List value); + public interface TriggersAttributeCallback extends BaseAttributeCallback { + void onSuccess(List value); } public interface GeneratedCommandListAttributeCallback extends BaseAttributeCallback { @@ -59494,39 +59494,39 @@ public void onSuccess(byte[] tlv) { }, ZONES_ATTRIBUTE_ID, minInterval, maxInterval); } - public void readTimeControlAttribute( - TimeControlAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TIME_CONTROL_ATTRIBUTE_ID); + public void readTriggersAttribute( + TriggersAttributeCallback callback) { + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TRIGGERS_ATTRIBUTE_ID); readAttribute(new ReportCallbackImpl(callback, path) { @Override public void onSuccess(byte[] tlv) { - List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); + List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, TIME_CONTROL_ATTRIBUTE_ID, true); + }, TRIGGERS_ATTRIBUTE_ID, true); } - public void writeTimeControlAttribute(DefaultClusterCallback callback, ArrayList value) { - writeTimeControlAttribute(callback, value, 0); + public void writeTriggersAttribute(DefaultClusterCallback callback, ArrayList value) { + writeTriggersAttribute(callback, value, 0); } - public void writeTimeControlAttribute(DefaultClusterCallback callback, ArrayList value, int timedWriteTimeoutMs) { + public void writeTriggersAttribute(DefaultClusterCallback callback, ArrayList value, int timedWriteTimeoutMs) { BaseTLVType tlvValue = ArrayType.generateArrayType(value, (elementvalue) -> elementvalue.encodeTlv()); - writeAttribute(new WriteAttributesCallbackImpl(callback), TIME_CONTROL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + writeAttribute(new WriteAttributesCallbackImpl(callback), TRIGGERS_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); } - public void subscribeTimeControlAttribute( - TimeControlAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TIME_CONTROL_ATTRIBUTE_ID); + public void subscribeTriggersAttribute( + TriggersAttributeCallback callback, int minInterval, int maxInterval) { + ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, TRIGGERS_ATTRIBUTE_ID); subscribeAttribute(new ReportCallbackImpl(callback, path) { @Override public void onSuccess(byte[] tlv) { - List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); + List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); callback.onSuccess(value); } - }, TIME_CONTROL_ATTRIBUTE_ID, minInterval, maxInterval); + }, TRIGGERS_ATTRIBUTE_ID, minInterval, maxInterval); } public void readSensitivityAttribute( @@ -59738,39 +59738,33 @@ public static class CameraAvStreamManagementCluster extends BaseChipCluster { private static final long MAX_NETWORK_BANDWIDTH_ATTRIBUTE_ID = 11L; private static final long CURRENT_FRAME_RATE_ATTRIBUTE_ID = 12L; private static final long HDR_MODE_ENABLED_ATTRIBUTE_ID = 13L; - private static final long CURRENT_VIDEO_CODECS_ATTRIBUTE_ID = 14L; - private static final long CURRENT_SNAPSHOT_CONFIG_ATTRIBUTE_ID = 15L; - private static final long FABRICS_USING_CAMERA_ATTRIBUTE_ID = 16L; - private static final long ALLOCATED_VIDEO_STREAMS_ATTRIBUTE_ID = 17L; - private static final long ALLOCATED_AUDIO_STREAMS_ATTRIBUTE_ID = 18L; - private static final long ALLOCATED_SNAPSHOT_STREAMS_ATTRIBUTE_ID = 19L; - private static final long RANKED_VIDEO_STREAM_PRIORITIES_LIST_ATTRIBUTE_ID = 20L; - private static final long SOFT_RECORDING_PRIVACY_MODE_ENABLED_ATTRIBUTE_ID = 21L; - private static final long SOFT_LIVESTREAM_PRIVACY_MODE_ENABLED_ATTRIBUTE_ID = 22L; - private static final long HARD_PRIVACY_MODE_ON_ATTRIBUTE_ID = 23L; - private static final long NIGHT_VISION_ATTRIBUTE_ID = 24L; - private static final long NIGHT_VISION_ILLUM_ATTRIBUTE_ID = 25L; - private static final long AWB_ENABLED_ATTRIBUTE_ID = 26L; - private static final long AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID = 27L; - private static final long AUTO_ISO_ENABLED_ATTRIBUTE_ID = 28L; - private static final long VIEWPORT_ATTRIBUTE_ID = 29L; - private static final long SPEAKER_MUTED_ATTRIBUTE_ID = 30L; - private static final long SPEAKER_VOLUME_LEVEL_ATTRIBUTE_ID = 31L; - private static final long SPEAKER_MAX_LEVEL_ATTRIBUTE_ID = 32L; - private static final long SPEAKER_MIN_LEVEL_ATTRIBUTE_ID = 33L; - private static final long MICROPHONE_MUTED_ATTRIBUTE_ID = 34L; - private static final long MICROPHONE_VOLUME_LEVEL_ATTRIBUTE_ID = 35L; - private static final long MICROPHONE_MAX_LEVEL_ATTRIBUTE_ID = 36L; - private static final long MICROPHONE_MIN_LEVEL_ATTRIBUTE_ID = 37L; - private static final long MICROPHONE_AGC_ENABLED_ATTRIBUTE_ID = 38L; - private static final long IMAGE_ROTATION_ATTRIBUTE_ID = 39L; - private static final long IMAGE_FLIP_HORIZONTAL_ATTRIBUTE_ID = 40L; - private static final long IMAGE_FLIP_VERTICAL_ATTRIBUTE_ID = 41L; - private static final long LOCAL_VIDEO_RECORDING_ENABLED_ATTRIBUTE_ID = 42L; - private static final long LOCAL_SNAPSHOT_RECORDING_ENABLED_ATTRIBUTE_ID = 43L; - private static final long STATUS_LIGHT_ENABLED_ATTRIBUTE_ID = 44L; - private static final long STATUS_LIGHT_BRIGHTNESS_ATTRIBUTE_ID = 45L; - private static final long DEPTH_SENSOR_STATUS_ATTRIBUTE_ID = 46L; + private static final long FABRICS_USING_CAMERA_ATTRIBUTE_ID = 14L; + private static final long ALLOCATED_VIDEO_STREAMS_ATTRIBUTE_ID = 15L; + private static final long ALLOCATED_AUDIO_STREAMS_ATTRIBUTE_ID = 16L; + private static final long ALLOCATED_SNAPSHOT_STREAMS_ATTRIBUTE_ID = 17L; + private static final long RANKED_VIDEO_STREAM_PRIORITIES_LIST_ATTRIBUTE_ID = 18L; + private static final long SOFT_RECORDING_PRIVACY_MODE_ENABLED_ATTRIBUTE_ID = 19L; + private static final long SOFT_LIVESTREAM_PRIVACY_MODE_ENABLED_ATTRIBUTE_ID = 20L; + private static final long HARD_PRIVACY_MODE_ON_ATTRIBUTE_ID = 21L; + private static final long NIGHT_VISION_ATTRIBUTE_ID = 22L; + private static final long NIGHT_VISION_ILLUM_ATTRIBUTE_ID = 23L; + private static final long VIEWPORT_ATTRIBUTE_ID = 24L; + private static final long SPEAKER_MUTED_ATTRIBUTE_ID = 25L; + private static final long SPEAKER_VOLUME_LEVEL_ATTRIBUTE_ID = 26L; + private static final long SPEAKER_MAX_LEVEL_ATTRIBUTE_ID = 27L; + private static final long SPEAKER_MIN_LEVEL_ATTRIBUTE_ID = 28L; + private static final long MICROPHONE_MUTED_ATTRIBUTE_ID = 29L; + private static final long MICROPHONE_VOLUME_LEVEL_ATTRIBUTE_ID = 30L; + private static final long MICROPHONE_MAX_LEVEL_ATTRIBUTE_ID = 31L; + private static final long MICROPHONE_MIN_LEVEL_ATTRIBUTE_ID = 32L; + private static final long MICROPHONE_AGC_ENABLED_ATTRIBUTE_ID = 33L; + private static final long IMAGE_ROTATION_ATTRIBUTE_ID = 34L; + private static final long IMAGE_FLIP_HORIZONTAL_ATTRIBUTE_ID = 35L; + private static final long IMAGE_FLIP_VERTICAL_ATTRIBUTE_ID = 36L; + private static final long LOCAL_VIDEO_RECORDING_ENABLED_ATTRIBUTE_ID = 37L; + private static final long LOCAL_SNAPSHOT_RECORDING_ENABLED_ATTRIBUTE_ID = 38L; + private static final long STATUS_LIGHT_ENABLED_ATTRIBUTE_ID = 39L; + private static final long STATUS_LIGHT_BRIGHTNESS_ATTRIBUTE_ID = 40L; private static final long GENERATED_COMMAND_LIST_ATTRIBUTE_ID = 65528L; private static final long ACCEPTED_COMMAND_LIST_ATTRIBUTE_ID = 65529L; private static final long EVENT_LIST_ATTRIBUTE_ID = 65530L; @@ -59984,11 +59978,11 @@ public void onResponse(StructType invokeStructValue) { }}, commandId, commandArgs, timedInvokeTimeoutMs); } - public void snapshotStreamAllocate(SnapshotStreamAllocateResponseCallback callback, Integer imageCodec, Integer frameRate, Long bitRate, ChipStructs.CameraAvStreamManagementClusterVideoResolutionStruct minResolution, ChipStructs.CameraAvStreamManagementClusterVideoResolutionStruct maxResolution, Integer quality) { - snapshotStreamAllocate(callback, imageCodec, frameRate, bitRate, minResolution, maxResolution, quality, 0); + public void snapshotStreamAllocate(SnapshotStreamAllocateResponseCallback callback, Integer imageCodec, Integer maxFrameRate, Long bitRate, ChipStructs.CameraAvStreamManagementClusterVideoResolutionStruct minResolution, ChipStructs.CameraAvStreamManagementClusterVideoResolutionStruct maxResolution, Integer quality) { + snapshotStreamAllocate(callback, imageCodec, maxFrameRate, bitRate, minResolution, maxResolution, quality, 0); } - public void snapshotStreamAllocate(SnapshotStreamAllocateResponseCallback callback, Integer imageCodec, Integer frameRate, Long bitRate, ChipStructs.CameraAvStreamManagementClusterVideoResolutionStruct minResolution, ChipStructs.CameraAvStreamManagementClusterVideoResolutionStruct maxResolution, Integer quality, int timedInvokeTimeoutMs) { + public void snapshotStreamAllocate(SnapshotStreamAllocateResponseCallback callback, Integer imageCodec, Integer maxFrameRate, Long bitRate, ChipStructs.CameraAvStreamManagementClusterVideoResolutionStruct minResolution, ChipStructs.CameraAvStreamManagementClusterVideoResolutionStruct maxResolution, Integer quality, int timedInvokeTimeoutMs) { final long commandId = 7L; ArrayList elements = new ArrayList<>(); @@ -59996,9 +59990,9 @@ public void snapshotStreamAllocate(SnapshotStreamAllocateResponseCallback callba BaseTLVType imageCodectlvValue = new UIntType(imageCodec); elements.add(new StructElement(imageCodecFieldID, imageCodectlvValue)); - final long frameRateFieldID = 1L; - BaseTLVType frameRatetlvValue = new UIntType(frameRate); - elements.add(new StructElement(frameRateFieldID, frameRatetlvValue)); + final long maxFrameRateFieldID = 1L; + BaseTLVType maxFrameRatetlvValue = new UIntType(maxFrameRate); + elements.add(new StructElement(maxFrameRateFieldID, maxFrameRatetlvValue)); final long bitRateFieldID = 2L; BaseTLVType bitRatetlvValue = new UIntType(bitRate); @@ -60098,86 +60092,6 @@ public void onResponse(StructType invokeStructValue) { }}, commandId, commandArgs, timedInvokeTimeoutMs); } - public void setViewport(DefaultClusterCallback callback, ChipStructs.CameraAvStreamManagementClusterViewportStruct viewport) { - setViewport(callback, viewport, 0); - } - - public void setViewport(DefaultClusterCallback callback, ChipStructs.CameraAvStreamManagementClusterViewportStruct viewport, int timedInvokeTimeoutMs) { - final long commandId = 13L; - - ArrayList elements = new ArrayList<>(); - final long viewportFieldID = 0L; - BaseTLVType viewporttlvValue = viewport.encodeTlv(); - elements.add(new StructElement(viewportFieldID, viewporttlvValue)); - - StructType commandArgs = new StructType(elements); - invoke(new InvokeCallbackImpl(callback) { - @Override - public void onResponse(StructType invokeStructValue) { - callback.onSuccess(); - }}, commandId, commandArgs, timedInvokeTimeoutMs); - } - - public void setImageRotation(DefaultClusterCallback callback, Integer angle) { - setImageRotation(callback, angle, 0); - } - - public void setImageRotation(DefaultClusterCallback callback, Integer angle, int timedInvokeTimeoutMs) { - final long commandId = 14L; - - ArrayList elements = new ArrayList<>(); - final long angleFieldID = 0L; - BaseTLVType angletlvValue = new UIntType(angle); - elements.add(new StructElement(angleFieldID, angletlvValue)); - - StructType commandArgs = new StructType(elements); - invoke(new InvokeCallbackImpl(callback) { - @Override - public void onResponse(StructType invokeStructValue) { - callback.onSuccess(); - }}, commandId, commandArgs, timedInvokeTimeoutMs); - } - - public void setImageFlipHorizontal(DefaultClusterCallback callback, Boolean enabled) { - setImageFlipHorizontal(callback, enabled, 0); - } - - public void setImageFlipHorizontal(DefaultClusterCallback callback, Boolean enabled, int timedInvokeTimeoutMs) { - final long commandId = 15L; - - ArrayList elements = new ArrayList<>(); - final long enabledFieldID = 0L; - BaseTLVType enabledtlvValue = new BooleanType(enabled); - elements.add(new StructElement(enabledFieldID, enabledtlvValue)); - - StructType commandArgs = new StructType(elements); - invoke(new InvokeCallbackImpl(callback) { - @Override - public void onResponse(StructType invokeStructValue) { - callback.onSuccess(); - }}, commandId, commandArgs, timedInvokeTimeoutMs); - } - - public void setImageFlipVertical(DefaultClusterCallback callback, Boolean enabled) { - setImageFlipVertical(callback, enabled, 0); - } - - public void setImageFlipVertical(DefaultClusterCallback callback, Boolean enabled, int timedInvokeTimeoutMs) { - final long commandId = 16L; - - ArrayList elements = new ArrayList<>(); - final long enabledFieldID = 0L; - BaseTLVType enabledtlvValue = new BooleanType(enabled); - elements.add(new StructElement(enabledFieldID, enabledtlvValue)); - - StructType commandArgs = new StructType(elements); - invoke(new InvokeCallbackImpl(callback) { - @Override - public void onResponse(StructType invokeStructValue) { - callback.onSuccess(); - }}, commandId, commandArgs, timedInvokeTimeoutMs); - } - public interface AudioStreamAllocateResponseCallback extends BaseClusterCallback { void onSuccess(Integer audioStreamID); } @@ -60214,14 +60128,6 @@ public interface SupportedSnapshotParamsAttributeCallback extends BaseAttributeC void onSuccess(List value); } - public interface CurrentVideoCodecsAttributeCallback extends BaseAttributeCallback { - void onSuccess(List value); - } - - public interface CurrentSnapshotConfigAttributeCallback extends BaseAttributeCallback { - void onSuccess(ChipStructs.CameraAvStreamManagementClusterSnapshotParamsStruct value); - } - public interface FabricsUsingCameraAttributeCallback extends BaseAttributeCallback { void onSuccess(List value); } @@ -60635,58 +60541,6 @@ public void onSuccess(byte[] tlv) { }, HDR_MODE_ENABLED_ATTRIBUTE_ID, minInterval, maxInterval); } - public void readCurrentVideoCodecsAttribute( - CurrentVideoCodecsAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, CURRENT_VIDEO_CODECS_ATTRIBUTE_ID); - - readAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, CURRENT_VIDEO_CODECS_ATTRIBUTE_ID, true); - } - - public void subscribeCurrentVideoCodecsAttribute( - CurrentVideoCodecsAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, CURRENT_VIDEO_CODECS_ATTRIBUTE_ID); - - subscribeAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - List value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, CURRENT_VIDEO_CODECS_ATTRIBUTE_ID, minInterval, maxInterval); - } - - public void readCurrentSnapshotConfigAttribute( - CurrentSnapshotConfigAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, CURRENT_SNAPSHOT_CONFIG_ATTRIBUTE_ID); - - readAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - ChipStructs.CameraAvStreamManagementClusterSnapshotParamsStruct value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, CURRENT_SNAPSHOT_CONFIG_ATTRIBUTE_ID, true); - } - - public void subscribeCurrentSnapshotConfigAttribute( - CurrentSnapshotConfigAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, CURRENT_SNAPSHOT_CONFIG_ATTRIBUTE_ID); - - subscribeAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - ChipStructs.CameraAvStreamManagementClusterSnapshotParamsStruct value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, CURRENT_SNAPSHOT_CONFIG_ATTRIBUTE_ID, minInterval, maxInterval); - } - public void readFabricsUsingCameraAttribute( FabricsUsingCameraAttributeCallback callback) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, FABRICS_USING_CAMERA_ATTRIBUTE_ID); @@ -60804,15 +60658,6 @@ public void onSuccess(byte[] tlv) { }, RANKED_VIDEO_STREAM_PRIORITIES_LIST_ATTRIBUTE_ID, true); } - public void writeRankedVideoStreamPrioritiesListAttribute(DefaultClusterCallback callback, ArrayList value) { - writeRankedVideoStreamPrioritiesListAttribute(callback, value, 0); - } - - public void writeRankedVideoStreamPrioritiesListAttribute(DefaultClusterCallback callback, ArrayList value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = ArrayType.generateArrayType(value, (elementvalue) -> new UIntType(elementvalue)); - writeAttribute(new WriteAttributesCallbackImpl(callback), RANKED_VIDEO_STREAM_PRIORITIES_LIST_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - public void subscribeRankedVideoStreamPrioritiesListAttribute( RankedVideoStreamPrioritiesListAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, RANKED_VIDEO_STREAM_PRIORITIES_LIST_ATTRIBUTE_ID); @@ -60992,111 +60837,6 @@ public void onSuccess(byte[] tlv) { }, NIGHT_VISION_ILLUM_ATTRIBUTE_ID, minInterval, maxInterval); } - public void readAWBEnabledAttribute( - BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AWB_ENABLED_ATTRIBUTE_ID); - - readAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AWB_ENABLED_ATTRIBUTE_ID, true); - } - - public void writeAWBEnabledAttribute(DefaultClusterCallback callback, Boolean value) { - writeAWBEnabledAttribute(callback, value, 0); - } - - public void writeAWBEnabledAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new BooleanType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), AWB_ENABLED_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - - public void subscribeAWBEnabledAttribute( - BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AWB_ENABLED_ATTRIBUTE_ID); - - subscribeAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AWB_ENABLED_ATTRIBUTE_ID, minInterval, maxInterval); - } - - public void readAutoShutterSpeedEnabledAttribute( - BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID); - - readAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID, true); - } - - public void writeAutoShutterSpeedEnabledAttribute(DefaultClusterCallback callback, Boolean value) { - writeAutoShutterSpeedEnabledAttribute(callback, value, 0); - } - - public void writeAutoShutterSpeedEnabledAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new BooleanType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - - public void subscribeAutoShutterSpeedEnabledAttribute( - BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID); - - subscribeAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID, minInterval, maxInterval); - } - - public void readAutoISOEnabledAttribute( - BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AUTO_ISO_ENABLED_ATTRIBUTE_ID); - - readAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AUTO_ISO_ENABLED_ATTRIBUTE_ID, true); - } - - public void writeAutoISOEnabledAttribute(DefaultClusterCallback callback, Boolean value) { - writeAutoISOEnabledAttribute(callback, value, 0); - } - - public void writeAutoISOEnabledAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new BooleanType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), AUTO_ISO_ENABLED_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - - public void subscribeAutoISOEnabledAttribute( - BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AUTO_ISO_ENABLED_ATTRIBUTE_ID); - - subscribeAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AUTO_ISO_ENABLED_ATTRIBUTE_ID, minInterval, maxInterval); - } - public void readViewportAttribute( ViewportAttributeCallback callback) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VIEWPORT_ATTRIBUTE_ID); @@ -61110,6 +60850,15 @@ public void onSuccess(byte[] tlv) { }, VIEWPORT_ATTRIBUTE_ID, true); } + public void writeViewportAttribute(DefaultClusterCallback callback, ChipStructs.CameraAvStreamManagementClusterViewportStruct value) { + writeViewportAttribute(callback, value, 0); + } + + public void writeViewportAttribute(DefaultClusterCallback callback, ChipStructs.CameraAvStreamManagementClusterViewportStruct value, int timedWriteTimeoutMs) { + BaseTLVType tlvValue = value.encodeTlv(); + writeAttribute(new WriteAttributesCallbackImpl(callback), VIEWPORT_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + } + public void subscribeViewportAttribute( ViewportAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VIEWPORT_ATTRIBUTE_ID); @@ -61206,15 +60955,6 @@ public void onSuccess(byte[] tlv) { }, SPEAKER_MAX_LEVEL_ATTRIBUTE_ID, true); } - public void writeSpeakerMaxLevelAttribute(DefaultClusterCallback callback, Integer value) { - writeSpeakerMaxLevelAttribute(callback, value, 0); - } - - public void writeSpeakerMaxLevelAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), SPEAKER_MAX_LEVEL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - public void subscribeSpeakerMaxLevelAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SPEAKER_MAX_LEVEL_ATTRIBUTE_ID); @@ -61241,15 +60981,6 @@ public void onSuccess(byte[] tlv) { }, SPEAKER_MIN_LEVEL_ATTRIBUTE_ID, true); } - public void writeSpeakerMinLevelAttribute(DefaultClusterCallback callback, Integer value) { - writeSpeakerMinLevelAttribute(callback, value, 0); - } - - public void writeSpeakerMinLevelAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), SPEAKER_MIN_LEVEL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - public void subscribeSpeakerMinLevelAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SPEAKER_MIN_LEVEL_ATTRIBUTE_ID); @@ -61346,15 +61077,6 @@ public void onSuccess(byte[] tlv) { }, MICROPHONE_MAX_LEVEL_ATTRIBUTE_ID, true); } - public void writeMicrophoneMaxLevelAttribute(DefaultClusterCallback callback, Integer value) { - writeMicrophoneMaxLevelAttribute(callback, value, 0); - } - - public void writeMicrophoneMaxLevelAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), MICROPHONE_MAX_LEVEL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - public void subscribeMicrophoneMaxLevelAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MICROPHONE_MAX_LEVEL_ATTRIBUTE_ID); @@ -61381,15 +61103,6 @@ public void onSuccess(byte[] tlv) { }, MICROPHONE_MIN_LEVEL_ATTRIBUTE_ID, true); } - public void writeMicrophoneMinLevelAttribute(DefaultClusterCallback callback, Integer value) { - writeMicrophoneMinLevelAttribute(callback, value, 0); - } - - public void writeMicrophoneMinLevelAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), MICROPHONE_MIN_LEVEL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - public void subscribeMicrophoneMinLevelAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MICROPHONE_MIN_LEVEL_ATTRIBUTE_ID); @@ -61451,6 +61164,15 @@ public void onSuccess(byte[] tlv) { }, IMAGE_ROTATION_ATTRIBUTE_ID, true); } + public void writeImageRotationAttribute(DefaultClusterCallback callback, Integer value) { + writeImageRotationAttribute(callback, value, 0); + } + + public void writeImageRotationAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { + BaseTLVType tlvValue = new UIntType(value); + writeAttribute(new WriteAttributesCallbackImpl(callback), IMAGE_ROTATION_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + } + public void subscribeImageRotationAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, IMAGE_ROTATION_ATTRIBUTE_ID); @@ -61477,6 +61199,15 @@ public void onSuccess(byte[] tlv) { }, IMAGE_FLIP_HORIZONTAL_ATTRIBUTE_ID, true); } + public void writeImageFlipHorizontalAttribute(DefaultClusterCallback callback, Boolean value) { + writeImageFlipHorizontalAttribute(callback, value, 0); + } + + public void writeImageFlipHorizontalAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { + BaseTLVType tlvValue = new BooleanType(value); + writeAttribute(new WriteAttributesCallbackImpl(callback), IMAGE_FLIP_HORIZONTAL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + } + public void subscribeImageFlipHorizontalAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, IMAGE_FLIP_HORIZONTAL_ATTRIBUTE_ID); @@ -61503,6 +61234,15 @@ public void onSuccess(byte[] tlv) { }, IMAGE_FLIP_VERTICAL_ATTRIBUTE_ID, true); } + public void writeImageFlipVerticalAttribute(DefaultClusterCallback callback, Boolean value) { + writeImageFlipVerticalAttribute(callback, value, 0); + } + + public void writeImageFlipVerticalAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { + BaseTLVType tlvValue = new BooleanType(value); + writeAttribute(new WriteAttributesCallbackImpl(callback), IMAGE_FLIP_VERTICAL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + } + public void subscribeImageFlipVerticalAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, IMAGE_FLIP_VERTICAL_ATTRIBUTE_ID); @@ -61656,41 +61396,6 @@ public void onSuccess(byte[] tlv) { }, STATUS_LIGHT_BRIGHTNESS_ATTRIBUTE_ID, minInterval, maxInterval); } - public void readDepthSensorStatusAttribute( - IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEPTH_SENSOR_STATUS_ATTRIBUTE_ID); - - readAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, DEPTH_SENSOR_STATUS_ATTRIBUTE_ID, true); - } - - public void writeDepthSensorStatusAttribute(DefaultClusterCallback callback, Integer value) { - writeDepthSensorStatusAttribute(callback, value, 0); - } - - public void writeDepthSensorStatusAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), DEPTH_SENSOR_STATUS_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - - public void subscribeDepthSensorStatusAttribute( - IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEPTH_SENSOR_STATUS_ATTRIBUTE_ID); - - subscribeAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, DEPTH_SENSOR_STATUS_ATTRIBUTE_ID, minInterval, maxInterval); - } - public void readGeneratedCommandListAttribute( GeneratedCommandListAttributeCallback callback) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, GENERATED_COMMAND_LIST_ATTRIBUTE_ID); diff --git a/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java b/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java index b3fcd6df3bfde3..bbb319ba5334ab 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ChipStructs.java @@ -12952,26 +12952,30 @@ public String toString() { return output.toString(); } } -public static class ZoneManagementClusterZoneTriggeringTimeControlStruct { +public static class ZoneManagementClusterZoneTriggerControlStruct { public Integer initialDuration; public Integer augmentationDuration; public Long maxDuration; public Integer blindDuration; + public Optional sensitivity; private static final long INITIAL_DURATION_ID = 0L; private static final long AUGMENTATION_DURATION_ID = 1L; private static final long MAX_DURATION_ID = 2L; private static final long BLIND_DURATION_ID = 3L; + private static final long SENSITIVITY_ID = 4L; - public ZoneManagementClusterZoneTriggeringTimeControlStruct( + public ZoneManagementClusterZoneTriggerControlStruct( Integer initialDuration, Integer augmentationDuration, Long maxDuration, - Integer blindDuration + Integer blindDuration, + Optional sensitivity ) { this.initialDuration = initialDuration; this.augmentationDuration = augmentationDuration; this.maxDuration = maxDuration; this.blindDuration = blindDuration; + this.sensitivity = sensitivity; } public StructType encodeTlv() { @@ -12980,11 +12984,12 @@ public StructType encodeTlv() { values.add(new StructElement(AUGMENTATION_DURATION_ID, new UIntType(augmentationDuration))); values.add(new StructElement(MAX_DURATION_ID, new UIntType(maxDuration))); values.add(new StructElement(BLIND_DURATION_ID, new UIntType(blindDuration))); + values.add(new StructElement(SENSITIVITY_ID, sensitivity.map((nonOptionalsensitivity) -> new UIntType(nonOptionalsensitivity)).orElse(new EmptyType()))); return new StructType(values); } - public static ZoneManagementClusterZoneTriggeringTimeControlStruct decodeTlv(BaseTLVType tlvValue) { + public static ZoneManagementClusterZoneTriggerControlStruct decodeTlv(BaseTLVType tlvValue) { if (tlvValue == null || tlvValue.type() != TLVType.Struct) { return null; } @@ -12992,6 +12997,7 @@ public static ZoneManagementClusterZoneTriggeringTimeControlStruct decodeTlv(Bas Integer augmentationDuration = null; Long maxDuration = null; Integer blindDuration = null; + Optional sensitivity = Optional.empty(); for (StructElement element: ((StructType)tlvValue).value()) { if (element.contextTagNum() == INITIAL_DURATION_ID) { if (element.value(BaseTLVType.class).type() == TLVType.UInt) { @@ -13013,20 +13019,26 @@ public static ZoneManagementClusterZoneTriggeringTimeControlStruct decodeTlv(Bas UIntType castingValue = element.value(UIntType.class); blindDuration = castingValue.value(Integer.class); } + } else if (element.contextTagNum() == SENSITIVITY_ID) { + if (element.value(BaseTLVType.class).type() == TLVType.UInt) { + UIntType castingValue = element.value(UIntType.class); + sensitivity = Optional.of(castingValue.value(Integer.class)); + } } } - return new ZoneManagementClusterZoneTriggeringTimeControlStruct( + return new ZoneManagementClusterZoneTriggerControlStruct( initialDuration, augmentationDuration, maxDuration, - blindDuration + blindDuration, + sensitivity ); } @Override public String toString() { StringBuilder output = new StringBuilder(); - output.append("ZoneManagementClusterZoneTriggeringTimeControlStruct {\n"); + output.append("ZoneManagementClusterZoneTriggerControlStruct {\n"); output.append("\tinitialDuration: "); output.append(initialDuration); output.append("\n"); @@ -13039,6 +13051,9 @@ public String toString() { output.append("\tblindDuration: "); output.append(blindDuration); output.append("\n"); + output.append("\tsensitivity: "); + output.append(sensitivity); + output.append("\n"); output.append("}\n"); return output.toString(); } diff --git a/src/controller/java/generated/java/chip/devicecontroller/ClusterIDMapping.java b/src/controller/java/generated/java/chip/devicecontroller/ClusterIDMapping.java index 354f49ed6caa5d..86a43781fec889 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ClusterIDMapping.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ClusterIDMapping.java @@ -16897,7 +16897,7 @@ public long getID() { public enum Attribute { SupportedZoneSources(0L), Zones(1L), - TimeControl(2L), + Triggers(2L), Sensitivity(3L), GeneratedCommandList(65528L), AcceptedCommandList(65529L), @@ -17087,39 +17087,33 @@ public enum Attribute { MaxNetworkBandwidth(11L), CurrentFrameRate(12L), HDRModeEnabled(13L), - CurrentVideoCodecs(14L), - CurrentSnapshotConfig(15L), - FabricsUsingCamera(16L), - AllocatedVideoStreams(17L), - AllocatedAudioStreams(18L), - AllocatedSnapshotStreams(19L), - RankedVideoStreamPrioritiesList(20L), - SoftRecordingPrivacyModeEnabled(21L), - SoftLivestreamPrivacyModeEnabled(22L), - HardPrivacyModeOn(23L), - NightVision(24L), - NightVisionIllum(25L), - AWBEnabled(26L), - AutoShutterSpeedEnabled(27L), - AutoISOEnabled(28L), - Viewport(29L), - SpeakerMuted(30L), - SpeakerVolumeLevel(31L), - SpeakerMaxLevel(32L), - SpeakerMinLevel(33L), - MicrophoneMuted(34L), - MicrophoneVolumeLevel(35L), - MicrophoneMaxLevel(36L), - MicrophoneMinLevel(37L), - MicrophoneAGCEnabled(38L), - ImageRotation(39L), - ImageFlipHorizontal(40L), - ImageFlipVertical(41L), - LocalVideoRecordingEnabled(42L), - LocalSnapshotRecordingEnabled(43L), - StatusLightEnabled(44L), - StatusLightBrightness(45L), - DepthSensorStatus(46L), + FabricsUsingCamera(14L), + AllocatedVideoStreams(15L), + AllocatedAudioStreams(16L), + AllocatedSnapshotStreams(17L), + RankedVideoStreamPrioritiesList(18L), + SoftRecordingPrivacyModeEnabled(19L), + SoftLivestreamPrivacyModeEnabled(20L), + HardPrivacyModeOn(21L), + NightVision(22L), + NightVisionIllum(23L), + Viewport(24L), + SpeakerMuted(25L), + SpeakerVolumeLevel(26L), + SpeakerMaxLevel(27L), + SpeakerMinLevel(28L), + MicrophoneMuted(29L), + MicrophoneVolumeLevel(30L), + MicrophoneMaxLevel(31L), + MicrophoneMinLevel(32L), + MicrophoneAGCEnabled(33L), + ImageRotation(34L), + ImageFlipHorizontal(35L), + ImageFlipVertical(36L), + LocalVideoRecordingEnabled(37L), + LocalSnapshotRecordingEnabled(38L), + StatusLightEnabled(39L), + StatusLightBrightness(40L), GeneratedCommandList(65528L), AcceptedCommandList(65529L), EventList(65530L), @@ -17177,11 +17171,7 @@ public enum Command { SnapshotStreamAllocate(7L), SnapshotStreamDeallocate(9L), SetStreamPriorities(10L), - CaptureSnapshot(11L), - SetViewport(13L), - SetImageRotation(14L), - SetImageFlipHorizontal(15L), - SetImageFlipVertical(16L),; + CaptureSnapshot(11L),; private final long id; Command(long id) { this.id = id; @@ -17284,7 +17274,7 @@ public static VideoStreamDeallocateCommandField value(int id) throws NoSuchField } throw new NoSuchFieldError(); } - }public enum SnapshotStreamAllocateCommandField {ImageCodec(0),FrameRate(1),BitRate(2),MinResolution(3),MaxResolution(4),Quality(5),; + }public enum SnapshotStreamAllocateCommandField {ImageCodec(0),MaxFrameRate(1),BitRate(2),MinResolution(3),MaxResolution(4),Quality(5),; private final int id; SnapshotStreamAllocateCommandField(int id) { this.id = id; @@ -17352,74 +17342,6 @@ public static CaptureSnapshotCommandField value(int id) throws NoSuchFieldError } throw new NoSuchFieldError(); } - }public enum SetViewportCommandField {Viewport(0),; - private final int id; - SetViewportCommandField(int id) { - this.id = id; - } - - public int getID() { - return id; - } - public static SetViewportCommandField value(int id) throws NoSuchFieldError { - for (SetViewportCommandField field : SetViewportCommandField.values()) { - if (field.getID() == id) { - return field; - } - } - throw new NoSuchFieldError(); - } - }public enum SetImageRotationCommandField {Angle(0),; - private final int id; - SetImageRotationCommandField(int id) { - this.id = id; - } - - public int getID() { - return id; - } - public static SetImageRotationCommandField value(int id) throws NoSuchFieldError { - for (SetImageRotationCommandField field : SetImageRotationCommandField.values()) { - if (field.getID() == id) { - return field; - } - } - throw new NoSuchFieldError(); - } - }public enum SetImageFlipHorizontalCommandField {Enabled(0),; - private final int id; - SetImageFlipHorizontalCommandField(int id) { - this.id = id; - } - - public int getID() { - return id; - } - public static SetImageFlipHorizontalCommandField value(int id) throws NoSuchFieldError { - for (SetImageFlipHorizontalCommandField field : SetImageFlipHorizontalCommandField.values()) { - if (field.getID() == id) { - return field; - } - } - throw new NoSuchFieldError(); - } - }public enum SetImageFlipVerticalCommandField {Enabled(0),; - private final int id; - SetImageFlipVerticalCommandField(int id) { - this.id = id; - } - - public int getID() { - return id; - } - public static SetImageFlipVerticalCommandField value(int id) throws NoSuchFieldError { - for (SetImageFlipVerticalCommandField field : SetImageFlipVerticalCommandField.values()) { - if (field.getID() == id) { - return field; - } - } - throw new NoSuchFieldError(); - } }@Override public String getAttributeName(long id) throws NoSuchFieldError { return Attribute.value(id).toString(); diff --git a/src/controller/java/generated/java/chip/devicecontroller/ClusterInfoMapping.java b/src/controller/java/generated/java/chip/devicecontroller/ClusterInfoMapping.java index d0e83258a32ae5..42e96815ef9b43 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ClusterInfoMapping.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ClusterInfoMapping.java @@ -19955,7 +19955,7 @@ public void onError(Exception ex) { } } - public static class DelegatedZoneManagementClusterTimeControlAttributeCallback implements ChipClusters.ZoneManagementCluster.TimeControlAttributeCallback, DelegatedClusterCallback { + public static class DelegatedZoneManagementClusterTriggersAttributeCallback implements ChipClusters.ZoneManagementCluster.TriggersAttributeCallback, DelegatedClusterCallback { private ClusterCommandCallback callback; @Override public void setCallbackDelegate(ClusterCommandCallback callback) { @@ -19963,9 +19963,9 @@ public void setCallbackDelegate(ClusterCommandCallback callback) { } @Override - public void onSuccess(List valueList) { + public void onSuccess(List valueList) { Map responseValues = new LinkedHashMap<>(); - CommandResponseInfo commandResponseInfo = new CommandResponseInfo("valueList", "List"); + CommandResponseInfo commandResponseInfo = new CommandResponseInfo("valueList", "List"); responseValues.put(commandResponseInfo, valueList); callback.onSuccess(responseValues); } @@ -20252,48 +20252,6 @@ public void onError(Exception ex) { } } - public static class DelegatedCameraAvStreamManagementClusterCurrentVideoCodecsAttributeCallback implements ChipClusters.CameraAvStreamManagementCluster.CurrentVideoCodecsAttributeCallback, DelegatedClusterCallback { - private ClusterCommandCallback callback; - @Override - public void setCallbackDelegate(ClusterCommandCallback callback) { - this.callback = callback; - } - - @Override - public void onSuccess(List valueList) { - Map responseValues = new LinkedHashMap<>(); - CommandResponseInfo commandResponseInfo = new CommandResponseInfo("valueList", "List"); - responseValues.put(commandResponseInfo, valueList); - callback.onSuccess(responseValues); - } - - @Override - public void onError(Exception ex) { - callback.onFailure(ex); - } - } - - public static class DelegatedCameraAvStreamManagementClusterCurrentSnapshotConfigAttributeCallback implements ChipClusters.CameraAvStreamManagementCluster.CurrentSnapshotConfigAttributeCallback, DelegatedClusterCallback { - private ClusterCommandCallback callback; - @Override - public void setCallbackDelegate(ClusterCommandCallback callback) { - this.callback = callback; - } - - @Override - public void onSuccess(ChipStructs.CameraAvStreamManagementClusterSnapshotParamsStruct value) { - Map responseValues = new LinkedHashMap<>(); - CommandResponseInfo commandResponseInfo = new CommandResponseInfo("value", "ChipStructs.CameraAvStreamManagementClusterSnapshotParamsStruct"); - responseValues.put(commandResponseInfo, value); - callback.onSuccess(responseValues); - } - - @Override - public void onError(Exception ex) { - callback.onFailure(ex); - } - } - public static class DelegatedCameraAvStreamManagementClusterFabricsUsingCameraAttributeCallback implements ChipClusters.CameraAvStreamManagementCluster.FabricsUsingCameraAttributeCallback, DelegatedClusterCallback { private ClusterCommandCallback callback; @Override @@ -29807,8 +29765,8 @@ public Map> getCommandMap() { CommandParameterInfo cameraAvStreamManagementsnapshotStreamAllocateimageCodecCommandParameterInfo = new CommandParameterInfo("imageCodec", Integer.class, Integer.class); cameraAvStreamManagementsnapshotStreamAllocateCommandParams.put("imageCodec",cameraAvStreamManagementsnapshotStreamAllocateimageCodecCommandParameterInfo); - CommandParameterInfo cameraAvStreamManagementsnapshotStreamAllocateframeRateCommandParameterInfo = new CommandParameterInfo("frameRate", Integer.class, Integer.class); - cameraAvStreamManagementsnapshotStreamAllocateCommandParams.put("frameRate",cameraAvStreamManagementsnapshotStreamAllocateframeRateCommandParameterInfo); + CommandParameterInfo cameraAvStreamManagementsnapshotStreamAllocatemaxFrameRateCommandParameterInfo = new CommandParameterInfo("maxFrameRate", Integer.class, Integer.class); + cameraAvStreamManagementsnapshotStreamAllocateCommandParams.put("maxFrameRate",cameraAvStreamManagementsnapshotStreamAllocatemaxFrameRateCommandParameterInfo); CommandParameterInfo cameraAvStreamManagementsnapshotStreamAllocatebitRateCommandParameterInfo = new CommandParameterInfo("bitRate", Long.class, Long.class); cameraAvStreamManagementsnapshotStreamAllocateCommandParams.put("bitRate",cameraAvStreamManagementsnapshotStreamAllocatebitRateCommandParameterInfo); @@ -29825,7 +29783,7 @@ public Map> getCommandMap() { commandArguments.get("imageCodec") , (Integer) - commandArguments.get("frameRate") + commandArguments.get("maxFrameRate") , (Long) commandArguments.get("bitRate") @@ -29900,72 +29858,6 @@ public Map> getCommandMap() { ); cameraAvStreamManagementClusterInteractionInfoMap.put("captureSnapshot", cameraAvStreamManagementcaptureSnapshotInteractionInfo); - Map cameraAvStreamManagementsetViewportCommandParams = new LinkedHashMap(); - - InteractionInfo cameraAvStreamManagementsetViewportInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster) - .setViewport((DefaultClusterCallback) callback - , (ChipStructs.CameraAvStreamManagementClusterViewportStruct) - commandArguments.get("viewport") - ); - }, - () -> new DelegatedDefaultClusterCallback(), - cameraAvStreamManagementsetViewportCommandParams - ); - cameraAvStreamManagementClusterInteractionInfoMap.put("setViewport", cameraAvStreamManagementsetViewportInteractionInfo); - - Map cameraAvStreamManagementsetImageRotationCommandParams = new LinkedHashMap(); - - CommandParameterInfo cameraAvStreamManagementsetImageRotationangleCommandParameterInfo = new CommandParameterInfo("angle", Integer.class, Integer.class); - cameraAvStreamManagementsetImageRotationCommandParams.put("angle",cameraAvStreamManagementsetImageRotationangleCommandParameterInfo); - InteractionInfo cameraAvStreamManagementsetImageRotationInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster) - .setImageRotation((DefaultClusterCallback) callback - , (Integer) - commandArguments.get("angle") - ); - }, - () -> new DelegatedDefaultClusterCallback(), - cameraAvStreamManagementsetImageRotationCommandParams - ); - cameraAvStreamManagementClusterInteractionInfoMap.put("setImageRotation", cameraAvStreamManagementsetImageRotationInteractionInfo); - - Map cameraAvStreamManagementsetImageFlipHorizontalCommandParams = new LinkedHashMap(); - - CommandParameterInfo cameraAvStreamManagementsetImageFlipHorizontalenabledCommandParameterInfo = new CommandParameterInfo("enabled", Boolean.class, Boolean.class); - cameraAvStreamManagementsetImageFlipHorizontalCommandParams.put("enabled",cameraAvStreamManagementsetImageFlipHorizontalenabledCommandParameterInfo); - InteractionInfo cameraAvStreamManagementsetImageFlipHorizontalInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster) - .setImageFlipHorizontal((DefaultClusterCallback) callback - , (Boolean) - commandArguments.get("enabled") - ); - }, - () -> new DelegatedDefaultClusterCallback(), - cameraAvStreamManagementsetImageFlipHorizontalCommandParams - ); - cameraAvStreamManagementClusterInteractionInfoMap.put("setImageFlipHorizontal", cameraAvStreamManagementsetImageFlipHorizontalInteractionInfo); - - Map cameraAvStreamManagementsetImageFlipVerticalCommandParams = new LinkedHashMap(); - - CommandParameterInfo cameraAvStreamManagementsetImageFlipVerticalenabledCommandParameterInfo = new CommandParameterInfo("enabled", Boolean.class, Boolean.class); - cameraAvStreamManagementsetImageFlipVerticalCommandParams.put("enabled",cameraAvStreamManagementsetImageFlipVerticalenabledCommandParameterInfo); - InteractionInfo cameraAvStreamManagementsetImageFlipVerticalInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster) - .setImageFlipVertical((DefaultClusterCallback) callback - , (Boolean) - commandArguments.get("enabled") - ); - }, - () -> new DelegatedDefaultClusterCallback(), - cameraAvStreamManagementsetImageFlipVerticalCommandParams - ); - cameraAvStreamManagementClusterInteractionInfoMap.put("setImageFlipVertical", cameraAvStreamManagementsetImageFlipVerticalInteractionInfo); - commandMap.put("cameraAvStreamManagement", cameraAvStreamManagementClusterInteractionInfoMap); Map webRTCTransportProviderClusterInteractionInfoMap = new LinkedHashMap<>(); diff --git a/src/controller/java/generated/java/chip/devicecontroller/ClusterReadMapping.java b/src/controller/java/generated/java/chip/devicecontroller/ClusterReadMapping.java index 843114b4374f58..85d8c246765215 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ClusterReadMapping.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ClusterReadMapping.java @@ -18204,17 +18204,17 @@ private static Map readZoneManagementInteractionInfo() readZoneManagementZonesCommandParams ); result.put("readZonesAttribute", readZoneManagementZonesAttributeInteractionInfo); - Map readZoneManagementTimeControlCommandParams = new LinkedHashMap(); - InteractionInfo readZoneManagementTimeControlAttributeInteractionInfo = new InteractionInfo( + Map readZoneManagementTriggersCommandParams = new LinkedHashMap(); + InteractionInfo readZoneManagementTriggersAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { - ((ChipClusters.ZoneManagementCluster) cluster).readTimeControlAttribute( - (ChipClusters.ZoneManagementCluster.TimeControlAttributeCallback) callback + ((ChipClusters.ZoneManagementCluster) cluster).readTriggersAttribute( + (ChipClusters.ZoneManagementCluster.TriggersAttributeCallback) callback ); }, - () -> new ClusterInfoMapping.DelegatedZoneManagementClusterTimeControlAttributeCallback(), - readZoneManagementTimeControlCommandParams + () -> new ClusterInfoMapping.DelegatedZoneManagementClusterTriggersAttributeCallback(), + readZoneManagementTriggersCommandParams ); - result.put("readTimeControlAttribute", readZoneManagementTimeControlAttributeInteractionInfo); + result.put("readTriggersAttribute", readZoneManagementTriggersAttributeInteractionInfo); Map readZoneManagementSensitivityCommandParams = new LinkedHashMap(); InteractionInfo readZoneManagementSensitivityAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { @@ -18406,17 +18406,6 @@ private static Map readCameraAvStreamManagementInteract readCameraAvStreamManagementHDRModeEnabledCommandParams ); result.put("readHDRModeEnabledAttribute", readCameraAvStreamManagementHDRModeEnabledAttributeInteractionInfo); - Map readCameraAvStreamManagementCurrentVideoCodecsCommandParams = new LinkedHashMap(); - InteractionInfo readCameraAvStreamManagementCurrentVideoCodecsAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).readCurrentVideoCodecsAttribute( - (ChipClusters.CameraAvStreamManagementCluster.CurrentVideoCodecsAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedCameraAvStreamManagementClusterCurrentVideoCodecsAttributeCallback(), - readCameraAvStreamManagementCurrentVideoCodecsCommandParams - ); - result.put("readCurrentVideoCodecsAttribute", readCameraAvStreamManagementCurrentVideoCodecsAttributeInteractionInfo); Map readCameraAvStreamManagementFabricsUsingCameraCommandParams = new LinkedHashMap(); InteractionInfo readCameraAvStreamManagementFabricsUsingCameraAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { @@ -18527,39 +18516,6 @@ private static Map readCameraAvStreamManagementInteract readCameraAvStreamManagementNightVisionIllumCommandParams ); result.put("readNightVisionIllumAttribute", readCameraAvStreamManagementNightVisionIllumAttributeInteractionInfo); - Map readCameraAvStreamManagementAWBEnabledCommandParams = new LinkedHashMap(); - InteractionInfo readCameraAvStreamManagementAWBEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).readAWBEnabledAttribute( - (ChipClusters.BooleanAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedBooleanAttributeCallback(), - readCameraAvStreamManagementAWBEnabledCommandParams - ); - result.put("readAWBEnabledAttribute", readCameraAvStreamManagementAWBEnabledAttributeInteractionInfo); - Map readCameraAvStreamManagementAutoShutterSpeedEnabledCommandParams = new LinkedHashMap(); - InteractionInfo readCameraAvStreamManagementAutoShutterSpeedEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).readAutoShutterSpeedEnabledAttribute( - (ChipClusters.BooleanAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedBooleanAttributeCallback(), - readCameraAvStreamManagementAutoShutterSpeedEnabledCommandParams - ); - result.put("readAutoShutterSpeedEnabledAttribute", readCameraAvStreamManagementAutoShutterSpeedEnabledAttributeInteractionInfo); - Map readCameraAvStreamManagementAutoISOEnabledCommandParams = new LinkedHashMap(); - InteractionInfo readCameraAvStreamManagementAutoISOEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).readAutoISOEnabledAttribute( - (ChipClusters.BooleanAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedBooleanAttributeCallback(), - readCameraAvStreamManagementAutoISOEnabledCommandParams - ); - result.put("readAutoISOEnabledAttribute", readCameraAvStreamManagementAutoISOEnabledAttributeInteractionInfo); Map readCameraAvStreamManagementSpeakerMutedCommandParams = new LinkedHashMap(); InteractionInfo readCameraAvStreamManagementSpeakerMutedAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { @@ -18736,17 +18692,6 @@ private static Map readCameraAvStreamManagementInteract readCameraAvStreamManagementStatusLightBrightnessCommandParams ); result.put("readStatusLightBrightnessAttribute", readCameraAvStreamManagementStatusLightBrightnessAttributeInteractionInfo); - Map readCameraAvStreamManagementDepthSensorStatusCommandParams = new LinkedHashMap(); - InteractionInfo readCameraAvStreamManagementDepthSensorStatusAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).readDepthSensorStatusAttribute( - (ChipClusters.IntegerAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedIntegerAttributeCallback(), - readCameraAvStreamManagementDepthSensorStatusCommandParams - ); - result.put("readDepthSensorStatusAttribute", readCameraAvStreamManagementDepthSensorStatusAttributeInteractionInfo); Map readCameraAvStreamManagementGeneratedCommandListCommandParams = new LinkedHashMap(); InteractionInfo readCameraAvStreamManagementGeneratedCommandListAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { diff --git a/src/controller/java/generated/java/chip/devicecontroller/ClusterWriteMapping.java b/src/controller/java/generated/java/chip/devicecontroller/ClusterWriteMapping.java index 725fd0baeccf65..68d1f3792157cc 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ClusterWriteMapping.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ClusterWriteMapping.java @@ -3475,72 +3475,6 @@ public Map> getWriteAttributeMap() { writeCameraAvStreamManagementNightVisionIllumCommandParams ); writeCameraAvStreamManagementInteractionInfo.put("writeNightVisionIllumAttribute", writeCameraAvStreamManagementNightVisionIllumAttributeInteractionInfo); - Map writeCameraAvStreamManagementAWBEnabledCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementAWBEnabledCommandParameterInfo = - new CommandParameterInfo( - "value", - Boolean.class, - Boolean.class - ); - writeCameraAvStreamManagementAWBEnabledCommandParams.put( - "value", - cameraAvStreamManagementAWBEnabledCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementAWBEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeAWBEnabledAttribute( - (DefaultClusterCallback) callback, - (Boolean) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementAWBEnabledCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeAWBEnabledAttribute", writeCameraAvStreamManagementAWBEnabledAttributeInteractionInfo); - Map writeCameraAvStreamManagementAutoShutterSpeedEnabledCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementautoShutterSpeedEnabledCommandParameterInfo = - new CommandParameterInfo( - "value", - Boolean.class, - Boolean.class - ); - writeCameraAvStreamManagementAutoShutterSpeedEnabledCommandParams.put( - "value", - cameraAvStreamManagementautoShutterSpeedEnabledCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementAutoShutterSpeedEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeAutoShutterSpeedEnabledAttribute( - (DefaultClusterCallback) callback, - (Boolean) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementAutoShutterSpeedEnabledCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeAutoShutterSpeedEnabledAttribute", writeCameraAvStreamManagementAutoShutterSpeedEnabledAttributeInteractionInfo); - Map writeCameraAvStreamManagementAutoISOEnabledCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementautoISOEnabledCommandParameterInfo = - new CommandParameterInfo( - "value", - Boolean.class, - Boolean.class - ); - writeCameraAvStreamManagementAutoISOEnabledCommandParams.put( - "value", - cameraAvStreamManagementautoISOEnabledCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementAutoISOEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeAutoISOEnabledAttribute( - (DefaultClusterCallback) callback, - (Boolean) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementAutoISOEnabledCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeAutoISOEnabledAttribute", writeCameraAvStreamManagementAutoISOEnabledAttributeInteractionInfo); Map writeCameraAvStreamManagementSpeakerMutedCommandParams = new LinkedHashMap(); CommandParameterInfo cameraAvStreamManagementspeakerMutedCommandParameterInfo = new CommandParameterInfo( @@ -3585,50 +3519,6 @@ public Map> getWriteAttributeMap() { writeCameraAvStreamManagementSpeakerVolumeLevelCommandParams ); writeCameraAvStreamManagementInteractionInfo.put("writeSpeakerVolumeLevelAttribute", writeCameraAvStreamManagementSpeakerVolumeLevelAttributeInteractionInfo); - Map writeCameraAvStreamManagementSpeakerMaxLevelCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementspeakerMaxLevelCommandParameterInfo = - new CommandParameterInfo( - "value", - Integer.class, - Integer.class - ); - writeCameraAvStreamManagementSpeakerMaxLevelCommandParams.put( - "value", - cameraAvStreamManagementspeakerMaxLevelCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementSpeakerMaxLevelAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeSpeakerMaxLevelAttribute( - (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementSpeakerMaxLevelCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeSpeakerMaxLevelAttribute", writeCameraAvStreamManagementSpeakerMaxLevelAttributeInteractionInfo); - Map writeCameraAvStreamManagementSpeakerMinLevelCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementspeakerMinLevelCommandParameterInfo = - new CommandParameterInfo( - "value", - Integer.class, - Integer.class - ); - writeCameraAvStreamManagementSpeakerMinLevelCommandParams.put( - "value", - cameraAvStreamManagementspeakerMinLevelCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementSpeakerMinLevelAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeSpeakerMinLevelAttribute( - (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementSpeakerMinLevelCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeSpeakerMinLevelAttribute", writeCameraAvStreamManagementSpeakerMinLevelAttributeInteractionInfo); Map writeCameraAvStreamManagementMicrophoneMutedCommandParams = new LinkedHashMap(); CommandParameterInfo cameraAvStreamManagementmicrophoneMutedCommandParameterInfo = new CommandParameterInfo( @@ -3673,72 +3563,94 @@ public Map> getWriteAttributeMap() { writeCameraAvStreamManagementMicrophoneVolumeLevelCommandParams ); writeCameraAvStreamManagementInteractionInfo.put("writeMicrophoneVolumeLevelAttribute", writeCameraAvStreamManagementMicrophoneVolumeLevelAttributeInteractionInfo); - Map writeCameraAvStreamManagementMicrophoneMaxLevelCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementmicrophoneMaxLevelCommandParameterInfo = + Map writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams = new LinkedHashMap(); + CommandParameterInfo cameraAvStreamManagementmicrophoneAGCEnabledCommandParameterInfo = new CommandParameterInfo( "value", - Integer.class, - Integer.class + Boolean.class, + Boolean.class ); - writeCameraAvStreamManagementMicrophoneMaxLevelCommandParams.put( + writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams.put( "value", - cameraAvStreamManagementmicrophoneMaxLevelCommandParameterInfo + cameraAvStreamManagementmicrophoneAGCEnabledCommandParameterInfo ); - InteractionInfo writeCameraAvStreamManagementMicrophoneMaxLevelAttributeInteractionInfo = new InteractionInfo( + InteractionInfo writeCameraAvStreamManagementMicrophoneAGCEnabledAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeMicrophoneMaxLevelAttribute( + ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeMicrophoneAGCEnabledAttribute( (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") + (Boolean) commandArguments.get("value") ); }, () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementMicrophoneMaxLevelCommandParams + writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams ); - writeCameraAvStreamManagementInteractionInfo.put("writeMicrophoneMaxLevelAttribute", writeCameraAvStreamManagementMicrophoneMaxLevelAttributeInteractionInfo); - Map writeCameraAvStreamManagementMicrophoneMinLevelCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementmicrophoneMinLevelCommandParameterInfo = + writeCameraAvStreamManagementInteractionInfo.put("writeMicrophoneAGCEnabledAttribute", writeCameraAvStreamManagementMicrophoneAGCEnabledAttributeInteractionInfo); + Map writeCameraAvStreamManagementImageRotationCommandParams = new LinkedHashMap(); + CommandParameterInfo cameraAvStreamManagementimageRotationCommandParameterInfo = new CommandParameterInfo( "value", Integer.class, Integer.class ); - writeCameraAvStreamManagementMicrophoneMinLevelCommandParams.put( + writeCameraAvStreamManagementImageRotationCommandParams.put( "value", - cameraAvStreamManagementmicrophoneMinLevelCommandParameterInfo + cameraAvStreamManagementimageRotationCommandParameterInfo ); - InteractionInfo writeCameraAvStreamManagementMicrophoneMinLevelAttributeInteractionInfo = new InteractionInfo( + InteractionInfo writeCameraAvStreamManagementImageRotationAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeMicrophoneMinLevelAttribute( + ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeImageRotationAttribute( (DefaultClusterCallback) callback, (Integer) commandArguments.get("value") ); }, () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementMicrophoneMinLevelCommandParams + writeCameraAvStreamManagementImageRotationCommandParams ); - writeCameraAvStreamManagementInteractionInfo.put("writeMicrophoneMinLevelAttribute", writeCameraAvStreamManagementMicrophoneMinLevelAttributeInteractionInfo); - Map writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementmicrophoneAGCEnabledCommandParameterInfo = + writeCameraAvStreamManagementInteractionInfo.put("writeImageRotationAttribute", writeCameraAvStreamManagementImageRotationAttributeInteractionInfo); + Map writeCameraAvStreamManagementImageFlipHorizontalCommandParams = new LinkedHashMap(); + CommandParameterInfo cameraAvStreamManagementimageFlipHorizontalCommandParameterInfo = new CommandParameterInfo( "value", Boolean.class, Boolean.class ); - writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams.put( + writeCameraAvStreamManagementImageFlipHorizontalCommandParams.put( "value", - cameraAvStreamManagementmicrophoneAGCEnabledCommandParameterInfo + cameraAvStreamManagementimageFlipHorizontalCommandParameterInfo ); - InteractionInfo writeCameraAvStreamManagementMicrophoneAGCEnabledAttributeInteractionInfo = new InteractionInfo( + InteractionInfo writeCameraAvStreamManagementImageFlipHorizontalAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeMicrophoneAGCEnabledAttribute( + ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeImageFlipHorizontalAttribute( (DefaultClusterCallback) callback, (Boolean) commandArguments.get("value") ); }, () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams + writeCameraAvStreamManagementImageFlipHorizontalCommandParams ); - writeCameraAvStreamManagementInteractionInfo.put("writeMicrophoneAGCEnabledAttribute", writeCameraAvStreamManagementMicrophoneAGCEnabledAttributeInteractionInfo); + writeCameraAvStreamManagementInteractionInfo.put("writeImageFlipHorizontalAttribute", writeCameraAvStreamManagementImageFlipHorizontalAttributeInteractionInfo); + Map writeCameraAvStreamManagementImageFlipVerticalCommandParams = new LinkedHashMap(); + CommandParameterInfo cameraAvStreamManagementimageFlipVerticalCommandParameterInfo = + new CommandParameterInfo( + "value", + Boolean.class, + Boolean.class + ); + writeCameraAvStreamManagementImageFlipVerticalCommandParams.put( + "value", + cameraAvStreamManagementimageFlipVerticalCommandParameterInfo + ); + InteractionInfo writeCameraAvStreamManagementImageFlipVerticalAttributeInteractionInfo = new InteractionInfo( + (cluster, callback, commandArguments) -> { + ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeImageFlipVerticalAttribute( + (DefaultClusterCallback) callback, + (Boolean) commandArguments.get("value") + ); + }, + () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), + writeCameraAvStreamManagementImageFlipVerticalCommandParams + ); + writeCameraAvStreamManagementInteractionInfo.put("writeImageFlipVerticalAttribute", writeCameraAvStreamManagementImageFlipVerticalAttributeInteractionInfo); Map writeCameraAvStreamManagementLocalVideoRecordingEnabledCommandParams = new LinkedHashMap(); CommandParameterInfo cameraAvStreamManagementlocalVideoRecordingEnabledCommandParameterInfo = new CommandParameterInfo( @@ -3827,28 +3739,6 @@ public Map> getWriteAttributeMap() { writeCameraAvStreamManagementStatusLightBrightnessCommandParams ); writeCameraAvStreamManagementInteractionInfo.put("writeStatusLightBrightnessAttribute", writeCameraAvStreamManagementStatusLightBrightnessAttributeInteractionInfo); - Map writeCameraAvStreamManagementDepthSensorStatusCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementdepthSensorStatusCommandParameterInfo = - new CommandParameterInfo( - "value", - Integer.class, - Integer.class - ); - writeCameraAvStreamManagementDepthSensorStatusCommandParams.put( - "value", - cameraAvStreamManagementdepthSensorStatusCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementDepthSensorStatusAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeDepthSensorStatusAttribute( - (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementDepthSensorStatusCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeDepthSensorStatusAttribute", writeCameraAvStreamManagementDepthSensorStatusAttributeInteractionInfo); writeAttributeMap.put("cameraAvStreamManagement", writeCameraAvStreamManagementInteractionInfo); Map writeWebRTCTransportProviderInteractionInfo = new LinkedHashMap<>(); writeAttributeMap.put("webRTCTransportProvider", writeWebRTCTransportProviderInteractionInfo); diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/files.gni b/src/controller/java/generated/java/chip/devicecontroller/cluster/files.gni index 2aed70a3dcf4d6..a4fcda9f9bfcc0 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/files.gni +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/files.gni @@ -176,7 +176,7 @@ structs_sources = [ "${chip_root}/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterTwoDCartesianVertexStruct.kt", "${chip_root}/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterTwoDCartesianZoneStruct.kt", "${chip_root}/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterZoneInformationStruct.kt", - "${chip_root}/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterZoneTriggeringTimeControlStruct.kt", + "${chip_root}/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterZoneTriggerControlStruct.kt", ] eventstructs_sources = [ diff --git a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterZoneTriggeringTimeControlStruct.kt b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterZoneTriggerControlStruct.kt similarity index 74% rename from src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterZoneTriggeringTimeControlStruct.kt rename to src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterZoneTriggerControlStruct.kt index 3e55171ac8c1dc..76a8cbaf112a55 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterZoneTriggeringTimeControlStruct.kt +++ b/src/controller/java/generated/java/chip/devicecontroller/cluster/structs/ZoneManagementClusterZoneTriggerControlStruct.kt @@ -17,23 +17,26 @@ package chip.devicecontroller.cluster.structs import chip.devicecontroller.cluster.* +import java.util.Optional import matter.tlv.ContextSpecificTag import matter.tlv.Tag import matter.tlv.TlvReader import matter.tlv.TlvWriter -class ZoneManagementClusterZoneTriggeringTimeControlStruct( +class ZoneManagementClusterZoneTriggerControlStruct( val initialDuration: UInt, val augmentationDuration: UInt, val maxDuration: ULong, val blindDuration: UInt, + val sensitivity: Optional, ) { override fun toString(): String = buildString { - append("ZoneManagementClusterZoneTriggeringTimeControlStruct {\n") + append("ZoneManagementClusterZoneTriggerControlStruct {\n") append("\tinitialDuration : $initialDuration\n") append("\taugmentationDuration : $augmentationDuration\n") append("\tmaxDuration : $maxDuration\n") append("\tblindDuration : $blindDuration\n") + append("\tsensitivity : $sensitivity\n") append("}\n") } @@ -44,6 +47,10 @@ class ZoneManagementClusterZoneTriggeringTimeControlStruct( put(ContextSpecificTag(TAG_AUGMENTATION_DURATION), augmentationDuration) put(ContextSpecificTag(TAG_MAX_DURATION), maxDuration) put(ContextSpecificTag(TAG_BLIND_DURATION), blindDuration) + if (sensitivity.isPresent) { + val optsensitivity = sensitivity.get() + put(ContextSpecificTag(TAG_SENSITIVITY), optsensitivity) + } endStructure() } } @@ -53,24 +60,29 @@ class ZoneManagementClusterZoneTriggeringTimeControlStruct( private const val TAG_AUGMENTATION_DURATION = 1 private const val TAG_MAX_DURATION = 2 private const val TAG_BLIND_DURATION = 3 + private const val TAG_SENSITIVITY = 4 - fun fromTlv( - tlvTag: Tag, - tlvReader: TlvReader, - ): ZoneManagementClusterZoneTriggeringTimeControlStruct { + fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ZoneManagementClusterZoneTriggerControlStruct { tlvReader.enterStructure(tlvTag) val initialDuration = tlvReader.getUInt(ContextSpecificTag(TAG_INITIAL_DURATION)) val augmentationDuration = tlvReader.getUInt(ContextSpecificTag(TAG_AUGMENTATION_DURATION)) val maxDuration = tlvReader.getULong(ContextSpecificTag(TAG_MAX_DURATION)) val blindDuration = tlvReader.getUInt(ContextSpecificTag(TAG_BLIND_DURATION)) + val sensitivity = + if (tlvReader.isNextTag(ContextSpecificTag(TAG_SENSITIVITY))) { + Optional.of(tlvReader.getUInt(ContextSpecificTag(TAG_SENSITIVITY))) + } else { + Optional.empty() + } tlvReader.exitContainer() - return ZoneManagementClusterZoneTriggeringTimeControlStruct( + return ZoneManagementClusterZoneTriggerControlStruct( initialDuration, augmentationDuration, maxDuration, blindDuration, + sensitivity, ) } } diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/CameraAvStreamManagementCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/CameraAvStreamManagementCluster.kt index c0993403079dbf..ffcad10cbf9ef1 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/CameraAvStreamManagementCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/CameraAvStreamManagementCluster.kt @@ -133,29 +133,6 @@ class CameraAvStreamManagementCluster( object SubscriptionEstablished : SupportedSnapshotParamsAttributeSubscriptionState() } - class CurrentVideoCodecsAttribute(val value: List?) - - sealed class CurrentVideoCodecsAttributeSubscriptionState { - data class Success(val value: List?) : CurrentVideoCodecsAttributeSubscriptionState() - - data class Error(val exception: Exception) : CurrentVideoCodecsAttributeSubscriptionState() - - object SubscriptionEstablished : CurrentVideoCodecsAttributeSubscriptionState() - } - - class CurrentSnapshotConfigAttribute( - val value: CameraAvStreamManagementClusterSnapshotParamsStruct? - ) - - sealed class CurrentSnapshotConfigAttributeSubscriptionState { - data class Success(val value: CameraAvStreamManagementClusterSnapshotParamsStruct?) : - CurrentSnapshotConfigAttributeSubscriptionState() - - data class Error(val exception: Exception) : CurrentSnapshotConfigAttributeSubscriptionState() - - object SubscriptionEstablished : CurrentSnapshotConfigAttributeSubscriptionState() - } - class FabricsUsingCameraAttribute(val value: List) sealed class FabricsUsingCameraAttributeSubscriptionState { @@ -511,7 +488,7 @@ class CameraAvStreamManagementCluster( suspend fun snapshotStreamAllocate( imageCodec: UByte, - frameRate: UShort, + maxFrameRate: UShort, bitRate: UInt, minResolution: CameraAvStreamManagementClusterVideoResolutionStruct, maxResolution: CameraAvStreamManagementClusterVideoResolutionStruct, @@ -526,8 +503,8 @@ class CameraAvStreamManagementCluster( val TAG_IMAGE_CODEC_REQ: Int = 0 tlvWriter.put(ContextSpecificTag(TAG_IMAGE_CODEC_REQ), imageCodec) - val TAG_FRAME_RATE_REQ: Int = 1 - tlvWriter.put(ContextSpecificTag(TAG_FRAME_RATE_REQ), frameRate) + val TAG_MAX_FRAME_RATE_REQ: Int = 1 + tlvWriter.put(ContextSpecificTag(TAG_MAX_FRAME_RATE_REQ), maxFrameRate) val TAG_BIT_RATE_REQ: Int = 2 tlvWriter.put(ContextSpecificTag(TAG_BIT_RATE_REQ), bitRate) @@ -656,93 +633,6 @@ class CameraAvStreamManagementCluster( logger.log(Level.FINE, "Invoke command succeeded: ${response}") } - suspend fun setViewport( - viewport: CameraAvStreamManagementClusterViewportStruct, - timedInvokeTimeout: Duration? = null, - ) { - val commandId: UInt = 13u - - val tlvWriter = TlvWriter() - tlvWriter.startStructure(AnonymousTag) - - val TAG_VIEWPORT_REQ: Int = 0 - viewport.toTlv(ContextSpecificTag(TAG_VIEWPORT_REQ), tlvWriter) - tlvWriter.endStructure() - - val request: InvokeRequest = - InvokeRequest( - CommandPath(endpointId, clusterId = CLUSTER_ID, commandId), - tlvPayload = tlvWriter.getEncoded(), - timedRequest = timedInvokeTimeout, - ) - - val response: InvokeResponse = controller.invoke(request) - logger.log(Level.FINE, "Invoke command succeeded: ${response}") - } - - suspend fun setImageRotation(angle: UShort, timedInvokeTimeout: Duration? = null) { - val commandId: UInt = 14u - - val tlvWriter = TlvWriter() - tlvWriter.startStructure(AnonymousTag) - - val TAG_ANGLE_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ANGLE_REQ), angle) - tlvWriter.endStructure() - - val request: InvokeRequest = - InvokeRequest( - CommandPath(endpointId, clusterId = CLUSTER_ID, commandId), - tlvPayload = tlvWriter.getEncoded(), - timedRequest = timedInvokeTimeout, - ) - - val response: InvokeResponse = controller.invoke(request) - logger.log(Level.FINE, "Invoke command succeeded: ${response}") - } - - suspend fun setImageFlipHorizontal(enabled: Boolean, timedInvokeTimeout: Duration? = null) { - val commandId: UInt = 15u - - val tlvWriter = TlvWriter() - tlvWriter.startStructure(AnonymousTag) - - val TAG_ENABLED_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ENABLED_REQ), enabled) - tlvWriter.endStructure() - - val request: InvokeRequest = - InvokeRequest( - CommandPath(endpointId, clusterId = CLUSTER_ID, commandId), - tlvPayload = tlvWriter.getEncoded(), - timedRequest = timedInvokeTimeout, - ) - - val response: InvokeResponse = controller.invoke(request) - logger.log(Level.FINE, "Invoke command succeeded: ${response}") - } - - suspend fun setImageFlipVertical(enabled: Boolean, timedInvokeTimeout: Duration? = null) { - val commandId: UInt = 16u - - val tlvWriter = TlvWriter() - tlvWriter.startStructure(AnonymousTag) - - val TAG_ENABLED_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ENABLED_REQ), enabled) - tlvWriter.endStructure() - - val request: InvokeRequest = - InvokeRequest( - CommandPath(endpointId, clusterId = CLUSTER_ID, commandId), - tlvPayload = tlvWriter.getEncoded(), - timedRequest = timedInvokeTimeout, - ) - - val response: InvokeResponse = controller.invoke(request) - logger.log(Level.FINE, "Invoke command succeeded: ${response}") - } - suspend fun readMaxConcurrentVideoEncodersAttribute(): UByte? { val ATTRIBUTE_ID: UInt = 0u @@ -2126,7 +2016,7 @@ class CameraAvStreamManagementCluster( } } - suspend fun readCurrentVideoCodecsAttribute(): CurrentVideoCodecsAttribute { + suspend fun readFabricsUsingCameraAttribute(): FabricsUsingCameraAttribute { val ATTRIBUTE_ID: UInt = 14u val attributePath = @@ -2148,30 +2038,26 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Currentvideocodecs attribute not found in response" } + requireNotNull(attributeData) { "Fabricsusingcamera attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: List? = - if (tlvReader.isNextTag(AnonymousTag)) { - buildList { - tlvReader.enterArray(AnonymousTag) - while (!tlvReader.isEndOfContainer()) { - add(tlvReader.getUByte(AnonymousTag)) - } - tlvReader.exitContainer() + val decodedValue: List = + buildList { + tlvReader.enterArray(AnonymousTag) + while (!tlvReader.isEndOfContainer()) { + add(tlvReader.getUByte(AnonymousTag)) } - } else { - null + tlvReader.exitContainer() } - return CurrentVideoCodecsAttribute(decodedValue) + return FabricsUsingCameraAttribute(decodedValue) } - suspend fun subscribeCurrentVideoCodecsAttribute( + suspend fun subscribeFabricsUsingCameraAttribute( minInterval: Int, maxInterval: Int, - ): Flow { + ): Flow { val ATTRIBUTE_ID: UInt = 14u val attributePaths = listOf( @@ -2190,7 +2076,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - CurrentVideoCodecsAttributeSubscriptionState.Error( + FabricsUsingCameraAttributeSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -2204,34 +2090,30 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Currentvideocodecs attribute not found in Node State update" + "Fabricsusingcamera attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: List? = - if (tlvReader.isNextTag(AnonymousTag)) { - buildList { - tlvReader.enterArray(AnonymousTag) - while (!tlvReader.isEndOfContainer()) { - add(tlvReader.getUByte(AnonymousTag)) - } - tlvReader.exitContainer() + val decodedValue: List = + buildList { + tlvReader.enterArray(AnonymousTag) + while (!tlvReader.isEndOfContainer()) { + add(tlvReader.getUByte(AnonymousTag)) } - } else { - null + tlvReader.exitContainer() } - decodedValue?.let { emit(CurrentVideoCodecsAttributeSubscriptionState.Success(it)) } + emit(FabricsUsingCameraAttributeSubscriptionState.Success(decodedValue)) } SubscriptionState.SubscriptionEstablished -> { - emit(CurrentVideoCodecsAttributeSubscriptionState.SubscriptionEstablished) + emit(FabricsUsingCameraAttributeSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readCurrentSnapshotConfigAttribute(): CurrentSnapshotConfigAttribute { + suspend fun readAllocatedVideoStreamsAttribute(): AllocatedVideoStreamsAttribute { val ATTRIBUTE_ID: UInt = 15u val attributePath = @@ -2253,24 +2135,30 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Currentsnapshotconfig attribute not found in response" } + requireNotNull(attributeData) { "Allocatedvideostreams attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: CameraAvStreamManagementClusterSnapshotParamsStruct? = + val decodedValue: List? = if (tlvReader.isNextTag(AnonymousTag)) { - CameraAvStreamManagementClusterSnapshotParamsStruct.fromTlv(AnonymousTag, tlvReader) + buildList { + tlvReader.enterArray(AnonymousTag) + while (!tlvReader.isEndOfContainer()) { + add(CameraAvStreamManagementClusterVideoStreamStruct.fromTlv(AnonymousTag, tlvReader)) + } + tlvReader.exitContainer() + } } else { null } - return CurrentSnapshotConfigAttribute(decodedValue) + return AllocatedVideoStreamsAttribute(decodedValue) } - suspend fun subscribeCurrentSnapshotConfigAttribute( + suspend fun subscribeAllocatedVideoStreamsAttribute( minInterval: Int, maxInterval: Int, - ): Flow { + ): Flow { val ATTRIBUTE_ID: UInt = 15u val attributePaths = listOf( @@ -2289,7 +2177,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - CurrentSnapshotConfigAttributeSubscriptionState.Error( + AllocatedVideoStreamsAttributeSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -2303,28 +2191,39 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Currentsnapshotconfig attribute not found in Node State update" + "Allocatedvideostreams attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: CameraAvStreamManagementClusterSnapshotParamsStruct? = + val decodedValue: List? = if (tlvReader.isNextTag(AnonymousTag)) { - CameraAvStreamManagementClusterSnapshotParamsStruct.fromTlv(AnonymousTag, tlvReader) + buildList { + tlvReader.enterArray(AnonymousTag) + while (!tlvReader.isEndOfContainer()) { + add( + CameraAvStreamManagementClusterVideoStreamStruct.fromTlv( + AnonymousTag, + tlvReader, + ) + ) + } + tlvReader.exitContainer() + } } else { null } - decodedValue?.let { emit(CurrentSnapshotConfigAttributeSubscriptionState.Success(it)) } + decodedValue?.let { emit(AllocatedVideoStreamsAttributeSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(CurrentSnapshotConfigAttributeSubscriptionState.SubscriptionEstablished) + emit(AllocatedVideoStreamsAttributeSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readFabricsUsingCameraAttribute(): FabricsUsingCameraAttribute { + suspend fun readAllocatedAudioStreamsAttribute(): AllocatedAudioStreamsAttribute { val ATTRIBUTE_ID: UInt = 16u val attributePath = @@ -2346,26 +2245,30 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Fabricsusingcamera attribute not found in response" } + requireNotNull(attributeData) { "Allocatedaudiostreams attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: List = - buildList { - tlvReader.enterArray(AnonymousTag) - while (!tlvReader.isEndOfContainer()) { - add(tlvReader.getUByte(AnonymousTag)) + val decodedValue: List? = + if (tlvReader.isNextTag(AnonymousTag)) { + buildList { + tlvReader.enterArray(AnonymousTag) + while (!tlvReader.isEndOfContainer()) { + add(CameraAvStreamManagementClusterAudioStreamStruct.fromTlv(AnonymousTag, tlvReader)) + } + tlvReader.exitContainer() } - tlvReader.exitContainer() + } else { + null } - return FabricsUsingCameraAttribute(decodedValue) + return AllocatedAudioStreamsAttribute(decodedValue) } - suspend fun subscribeFabricsUsingCameraAttribute( + suspend fun subscribeAllocatedAudioStreamsAttribute( minInterval: Int, maxInterval: Int, - ): Flow { + ): Flow { val ATTRIBUTE_ID: UInt = 16u val attributePaths = listOf( @@ -2384,7 +2287,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - FabricsUsingCameraAttributeSubscriptionState.Error( + AllocatedAudioStreamsAttributeSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -2398,30 +2301,39 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Fabricsusingcamera attribute not found in Node State update" + "Allocatedaudiostreams attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: List = - buildList { - tlvReader.enterArray(AnonymousTag) - while (!tlvReader.isEndOfContainer()) { - add(tlvReader.getUByte(AnonymousTag)) + val decodedValue: List? = + if (tlvReader.isNextTag(AnonymousTag)) { + buildList { + tlvReader.enterArray(AnonymousTag) + while (!tlvReader.isEndOfContainer()) { + add( + CameraAvStreamManagementClusterAudioStreamStruct.fromTlv( + AnonymousTag, + tlvReader, + ) + ) + } + tlvReader.exitContainer() } - tlvReader.exitContainer() + } else { + null } - emit(FabricsUsingCameraAttributeSubscriptionState.Success(decodedValue)) + decodedValue?.let { emit(AllocatedAudioStreamsAttributeSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(FabricsUsingCameraAttributeSubscriptionState.SubscriptionEstablished) + emit(AllocatedAudioStreamsAttributeSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readAllocatedVideoStreamsAttribute(): AllocatedVideoStreamsAttribute { + suspend fun readAllocatedSnapshotStreamsAttribute(): AllocatedSnapshotStreamsAttribute { val ATTRIBUTE_ID: UInt = 17u val attributePath = @@ -2443,16 +2355,18 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Allocatedvideostreams attribute not found in response" } + requireNotNull(attributeData) { "Allocatedsnapshotstreams attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: List? = + val decodedValue: List? = if (tlvReader.isNextTag(AnonymousTag)) { - buildList { + buildList { tlvReader.enterArray(AnonymousTag) while (!tlvReader.isEndOfContainer()) { - add(CameraAvStreamManagementClusterVideoStreamStruct.fromTlv(AnonymousTag, tlvReader)) + add( + CameraAvStreamManagementClusterSnapshotStreamStruct.fromTlv(AnonymousTag, tlvReader) + ) } tlvReader.exitContainer() } @@ -2460,13 +2374,13 @@ class CameraAvStreamManagementCluster( null } - return AllocatedVideoStreamsAttribute(decodedValue) + return AllocatedSnapshotStreamsAttribute(decodedValue) } - suspend fun subscribeAllocatedVideoStreamsAttribute( + suspend fun subscribeAllocatedSnapshotStreamsAttribute( minInterval: Int, maxInterval: Int, - ): Flow { + ): Flow { val ATTRIBUTE_ID: UInt = 17u val attributePaths = listOf( @@ -2485,7 +2399,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - AllocatedVideoStreamsAttributeSubscriptionState.Error( + AllocatedSnapshotStreamsAttributeSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -2499,18 +2413,18 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Allocatedvideostreams attribute not found in Node State update" + "Allocatedsnapshotstreams attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: List? = + val decodedValue: List? = if (tlvReader.isNextTag(AnonymousTag)) { - buildList { + buildList { tlvReader.enterArray(AnonymousTag) while (!tlvReader.isEndOfContainer()) { add( - CameraAvStreamManagementClusterVideoStreamStruct.fromTlv( + CameraAvStreamManagementClusterSnapshotStreamStruct.fromTlv( AnonymousTag, tlvReader, ) @@ -2522,16 +2436,17 @@ class CameraAvStreamManagementCluster( null } - decodedValue?.let { emit(AllocatedVideoStreamsAttributeSubscriptionState.Success(it)) } + decodedValue?.let { emit(AllocatedSnapshotStreamsAttributeSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(AllocatedVideoStreamsAttributeSubscriptionState.SubscriptionEstablished) + emit(AllocatedSnapshotStreamsAttributeSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readAllocatedAudioStreamsAttribute(): AllocatedAudioStreamsAttribute { + suspend fun readRankedVideoStreamPrioritiesListAttribute(): + RankedVideoStreamPrioritiesListAttribute { val ATTRIBUTE_ID: UInt = 18u val attributePath = @@ -2553,16 +2468,18 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Allocatedaudiostreams attribute not found in response" } + requireNotNull(attributeData) { + "Rankedvideostreamprioritieslist attribute not found in response" + } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: List? = + val decodedValue: List? = if (tlvReader.isNextTag(AnonymousTag)) { - buildList { + buildList { tlvReader.enterArray(AnonymousTag) while (!tlvReader.isEndOfContainer()) { - add(CameraAvStreamManagementClusterAudioStreamStruct.fromTlv(AnonymousTag, tlvReader)) + add(tlvReader.getUByte(AnonymousTag)) } tlvReader.exitContainer() } @@ -2570,663 +2487,14 @@ class CameraAvStreamManagementCluster( null } - return AllocatedAudioStreamsAttribute(decodedValue) - } - - suspend fun subscribeAllocatedAudioStreamsAttribute( - minInterval: Int, - maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 18u - val attributePaths = - listOf( - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - ) - - val subscribeRequest: SubscribeRequest = - SubscribeRequest( - eventPaths = emptyList(), - attributePaths = attributePaths, - minInterval = Duration.ofSeconds(minInterval.toLong()), - maxInterval = Duration.ofSeconds(maxInterval.toLong()), - ) - - return controller.subscribe(subscribeRequest).transform { subscriptionState -> - when (subscriptionState) { - is SubscriptionState.SubscriptionErrorNotification -> { - emit( - AllocatedAudioStreamsAttributeSubscriptionState.Error( - Exception( - "Subscription terminated with error code: ${subscriptionState.terminationCause}" - ) - ) - ) - } - is SubscriptionState.NodeStateUpdate -> { - val attributeData = - subscriptionState.updateState.successes - .filterIsInstance() - .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - - requireNotNull(attributeData) { - "Allocatedaudiostreams attribute not found in Node State update" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: List? = - if (tlvReader.isNextTag(AnonymousTag)) { - buildList { - tlvReader.enterArray(AnonymousTag) - while (!tlvReader.isEndOfContainer()) { - add( - CameraAvStreamManagementClusterAudioStreamStruct.fromTlv( - AnonymousTag, - tlvReader, - ) - ) - } - tlvReader.exitContainer() - } - } else { - null - } - - decodedValue?.let { emit(AllocatedAudioStreamsAttributeSubscriptionState.Success(it)) } - } - SubscriptionState.SubscriptionEstablished -> { - emit(AllocatedAudioStreamsAttributeSubscriptionState.SubscriptionEstablished) - } - } - } - } - - suspend fun readAllocatedSnapshotStreamsAttribute(): AllocatedSnapshotStreamsAttribute { - val ATTRIBUTE_ID: UInt = 19u - - val attributePath = - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - - val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath)) - - val response = controller.read(readRequest) - - if (response.successes.isEmpty()) { - logger.log(Level.WARNING, "Read command failed") - throw IllegalStateException("Read command failed with failures: ${response.failures}") - } - - logger.log(Level.FINE, "Read command succeeded") - - val attributeData = - response.successes.filterIsInstance().firstOrNull { - it.path.attributeId == ATTRIBUTE_ID - } - - requireNotNull(attributeData) { "Allocatedsnapshotstreams attribute not found in response" } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: List? = - if (tlvReader.isNextTag(AnonymousTag)) { - buildList { - tlvReader.enterArray(AnonymousTag) - while (!tlvReader.isEndOfContainer()) { - add( - CameraAvStreamManagementClusterSnapshotStreamStruct.fromTlv(AnonymousTag, tlvReader) - ) - } - tlvReader.exitContainer() - } - } else { - null - } - - return AllocatedSnapshotStreamsAttribute(decodedValue) - } - - suspend fun subscribeAllocatedSnapshotStreamsAttribute( - minInterval: Int, - maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 19u - val attributePaths = - listOf( - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - ) - - val subscribeRequest: SubscribeRequest = - SubscribeRequest( - eventPaths = emptyList(), - attributePaths = attributePaths, - minInterval = Duration.ofSeconds(minInterval.toLong()), - maxInterval = Duration.ofSeconds(maxInterval.toLong()), - ) - - return controller.subscribe(subscribeRequest).transform { subscriptionState -> - when (subscriptionState) { - is SubscriptionState.SubscriptionErrorNotification -> { - emit( - AllocatedSnapshotStreamsAttributeSubscriptionState.Error( - Exception( - "Subscription terminated with error code: ${subscriptionState.terminationCause}" - ) - ) - ) - } - is SubscriptionState.NodeStateUpdate -> { - val attributeData = - subscriptionState.updateState.successes - .filterIsInstance() - .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - - requireNotNull(attributeData) { - "Allocatedsnapshotstreams attribute not found in Node State update" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: List? = - if (tlvReader.isNextTag(AnonymousTag)) { - buildList { - tlvReader.enterArray(AnonymousTag) - while (!tlvReader.isEndOfContainer()) { - add( - CameraAvStreamManagementClusterSnapshotStreamStruct.fromTlv( - AnonymousTag, - tlvReader, - ) - ) - } - tlvReader.exitContainer() - } - } else { - null - } - - decodedValue?.let { emit(AllocatedSnapshotStreamsAttributeSubscriptionState.Success(it)) } - } - SubscriptionState.SubscriptionEstablished -> { - emit(AllocatedSnapshotStreamsAttributeSubscriptionState.SubscriptionEstablished) - } - } - } - } - - suspend fun readRankedVideoStreamPrioritiesListAttribute(): - RankedVideoStreamPrioritiesListAttribute { - val ATTRIBUTE_ID: UInt = 20u - - val attributePath = - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - - val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath)) - - val response = controller.read(readRequest) - - if (response.successes.isEmpty()) { - logger.log(Level.WARNING, "Read command failed") - throw IllegalStateException("Read command failed with failures: ${response.failures}") - } - - logger.log(Level.FINE, "Read command succeeded") - - val attributeData = - response.successes.filterIsInstance().firstOrNull { - it.path.attributeId == ATTRIBUTE_ID - } - - requireNotNull(attributeData) { - "Rankedvideostreamprioritieslist attribute not found in response" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: List? = - if (tlvReader.isNextTag(AnonymousTag)) { - buildList { - tlvReader.enterArray(AnonymousTag) - while (!tlvReader.isEndOfContainer()) { - add(tlvReader.getUByte(AnonymousTag)) - } - tlvReader.exitContainer() - } - } else { - null - } - - return RankedVideoStreamPrioritiesListAttribute(decodedValue) - } - - suspend fun writeRankedVideoStreamPrioritiesListAttribute( - value: List, - timedWriteTimeout: Duration? = null, - ) { - val ATTRIBUTE_ID: UInt = 20u - - val tlvWriter = TlvWriter() - tlvWriter.startArray(AnonymousTag) - for (item in value.iterator()) { - tlvWriter.put(AnonymousTag, item) - } - tlvWriter.endArray() - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - - suspend fun subscribeRankedVideoStreamPrioritiesListAttribute( - minInterval: Int, - maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 20u - val attributePaths = - listOf( - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - ) - - val subscribeRequest: SubscribeRequest = - SubscribeRequest( - eventPaths = emptyList(), - attributePaths = attributePaths, - minInterval = Duration.ofSeconds(minInterval.toLong()), - maxInterval = Duration.ofSeconds(maxInterval.toLong()), - ) - - return controller.subscribe(subscribeRequest).transform { subscriptionState -> - when (subscriptionState) { - is SubscriptionState.SubscriptionErrorNotification -> { - emit( - RankedVideoStreamPrioritiesListAttributeSubscriptionState.Error( - Exception( - "Subscription terminated with error code: ${subscriptionState.terminationCause}" - ) - ) - ) - } - is SubscriptionState.NodeStateUpdate -> { - val attributeData = - subscriptionState.updateState.successes - .filterIsInstance() - .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - - requireNotNull(attributeData) { - "Rankedvideostreamprioritieslist attribute not found in Node State update" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: List? = - if (tlvReader.isNextTag(AnonymousTag)) { - buildList { - tlvReader.enterArray(AnonymousTag) - while (!tlvReader.isEndOfContainer()) { - add(tlvReader.getUByte(AnonymousTag)) - } - tlvReader.exitContainer() - } - } else { - null - } - - decodedValue?.let { - emit(RankedVideoStreamPrioritiesListAttributeSubscriptionState.Success(it)) - } - } - SubscriptionState.SubscriptionEstablished -> { - emit(RankedVideoStreamPrioritiesListAttributeSubscriptionState.SubscriptionEstablished) - } - } - } - } - - suspend fun readSoftRecordingPrivacyModeEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 21u - - val attributePath = - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - - val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath)) - - val response = controller.read(readRequest) - - if (response.successes.isEmpty()) { - logger.log(Level.WARNING, "Read command failed") - throw IllegalStateException("Read command failed with failures: ${response.failures}") - } - - logger.log(Level.FINE, "Read command succeeded") - - val attributeData = - response.successes.filterIsInstance().firstOrNull { - it.path.attributeId == ATTRIBUTE_ID - } - - requireNotNull(attributeData) { - "Softrecordingprivacymodeenabled attribute not found in response" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null - } - - return decodedValue - } - - suspend fun writeSoftRecordingPrivacyModeEnabledAttribute( - value: Boolean, - timedWriteTimeout: Duration? = null, - ) { - val ATTRIBUTE_ID: UInt = 21u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - - suspend fun subscribeSoftRecordingPrivacyModeEnabledAttribute( - minInterval: Int, - maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 21u - val attributePaths = - listOf( - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - ) - - val subscribeRequest: SubscribeRequest = - SubscribeRequest( - eventPaths = emptyList(), - attributePaths = attributePaths, - minInterval = Duration.ofSeconds(minInterval.toLong()), - maxInterval = Duration.ofSeconds(maxInterval.toLong()), - ) - - return controller.subscribe(subscribeRequest).transform { subscriptionState -> - when (subscriptionState) { - is SubscriptionState.SubscriptionErrorNotification -> { - emit( - BooleanSubscriptionState.Error( - Exception( - "Subscription terminated with error code: ${subscriptionState.terminationCause}" - ) - ) - ) - } - is SubscriptionState.NodeStateUpdate -> { - val attributeData = - subscriptionState.updateState.successes - .filterIsInstance() - .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - - requireNotNull(attributeData) { - "Softrecordingprivacymodeenabled attribute not found in Node State update" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null - } - - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } - } - SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) - } - } - } - } - - suspend fun readSoftLivestreamPrivacyModeEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 22u - - val attributePath = - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - - val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath)) - - val response = controller.read(readRequest) - - if (response.successes.isEmpty()) { - logger.log(Level.WARNING, "Read command failed") - throw IllegalStateException("Read command failed with failures: ${response.failures}") - } - - logger.log(Level.FINE, "Read command succeeded") - - val attributeData = - response.successes.filterIsInstance().firstOrNull { - it.path.attributeId == ATTRIBUTE_ID - } - - requireNotNull(attributeData) { - "Softlivestreamprivacymodeenabled attribute not found in response" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null - } - - return decodedValue - } - - suspend fun writeSoftLivestreamPrivacyModeEnabledAttribute( - value: Boolean, - timedWriteTimeout: Duration? = null, - ) { - val ATTRIBUTE_ID: UInt = 22u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - - suspend fun subscribeSoftLivestreamPrivacyModeEnabledAttribute( - minInterval: Int, - maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 22u - val attributePaths = - listOf( - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - ) - - val subscribeRequest: SubscribeRequest = - SubscribeRequest( - eventPaths = emptyList(), - attributePaths = attributePaths, - minInterval = Duration.ofSeconds(minInterval.toLong()), - maxInterval = Duration.ofSeconds(maxInterval.toLong()), - ) - - return controller.subscribe(subscribeRequest).transform { subscriptionState -> - when (subscriptionState) { - is SubscriptionState.SubscriptionErrorNotification -> { - emit( - BooleanSubscriptionState.Error( - Exception( - "Subscription terminated with error code: ${subscriptionState.terminationCause}" - ) - ) - ) - } - is SubscriptionState.NodeStateUpdate -> { - val attributeData = - subscriptionState.updateState.successes - .filterIsInstance() - .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - - requireNotNull(attributeData) { - "Softlivestreamprivacymodeenabled attribute not found in Node State update" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null - } - - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } - } - SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) - } - } - } - } - - suspend fun readHardPrivacyModeOnAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 23u - - val attributePath = - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - - val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath)) - - val response = controller.read(readRequest) - - if (response.successes.isEmpty()) { - logger.log(Level.WARNING, "Read command failed") - throw IllegalStateException("Read command failed with failures: ${response.failures}") - } - - logger.log(Level.FINE, "Read command succeeded") - - val attributeData = - response.successes.filterIsInstance().firstOrNull { - it.path.attributeId == ATTRIBUTE_ID - } - - requireNotNull(attributeData) { "Hardprivacymodeon attribute not found in response" } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null - } - - return decodedValue + return RankedVideoStreamPrioritiesListAttribute(decodedValue) } - suspend fun subscribeHardPrivacyModeOnAttribute( + suspend fun subscribeRankedVideoStreamPrioritiesListAttribute( minInterval: Int, maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 23u + ): Flow { + val ATTRIBUTE_ID: UInt = 18u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3244,7 +2512,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - BooleanSubscriptionState.Error( + RankedVideoStreamPrioritiesListAttributeSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -3258,29 +2526,37 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Hardprivacymodeon attribute not found in Node State update" + "Rankedvideostreamprioritieslist attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: List? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + buildList { + tlvReader.enterArray(AnonymousTag) + while (!tlvReader.isEndOfContainer()) { + add(tlvReader.getUByte(AnonymousTag)) + } + tlvReader.exitContainer() + } } else { null } - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } + decodedValue?.let { + emit(RankedVideoStreamPrioritiesListAttributeSubscriptionState.Success(it)) + } } SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) + emit(RankedVideoStreamPrioritiesListAttributeSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readNightVisionAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 24u + suspend fun readSoftRecordingPrivacyModeEnabledAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 19u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3301,13 +2577,15 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Nightvision attribute not found in response" } + requireNotNull(attributeData) { + "Softrecordingprivacymodeenabled attribute not found in response" + } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = + val decodedValue: Boolean? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) + tlvReader.getBoolean(AnonymousTag) } else { null } @@ -3315,8 +2593,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeNightVisionAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 24u + suspend fun writeSoftRecordingPrivacyModeEnabledAttribute( + value: Boolean, + timedWriteTimeout: Duration? = null, + ) { + val ATTRIBUTE_ID: UInt = 19u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -3355,11 +2636,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeNightVisionAttribute( + suspend fun subscribeSoftRecordingPrivacyModeEnabledAttribute( minInterval: Int, maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 24u + ): Flow { + val ATTRIBUTE_ID: UInt = 19u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3377,7 +2658,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - UByteSubscriptionState.Error( + BooleanSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -3390,28 +2671,30 @@ class CameraAvStreamManagementCluster( .filterIsInstance() .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Nightvision attribute not found in Node State update" } + requireNotNull(attributeData) { + "Softrecordingprivacymodeenabled attribute not found in Node State update" + } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = + val decodedValue: Boolean? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) + tlvReader.getBoolean(AnonymousTag) } else { null } - decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } + decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(UByteSubscriptionState.SubscriptionEstablished) + emit(BooleanSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readNightVisionIllumAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 25u + suspend fun readSoftLivestreamPrivacyModeEnabledAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 20u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3432,13 +2715,15 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Nightvisionillum attribute not found in response" } + requireNotNull(attributeData) { + "Softlivestreamprivacymodeenabled attribute not found in response" + } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = + val decodedValue: Boolean? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) + tlvReader.getBoolean(AnonymousTag) } else { null } @@ -3446,8 +2731,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeNightVisionIllumAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 25u + suspend fun writeSoftLivestreamPrivacyModeEnabledAttribute( + value: Boolean, + timedWriteTimeout: Duration? = null, + ) { + val ATTRIBUTE_ID: UInt = 20u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -3486,11 +2774,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeNightVisionIllumAttribute( + suspend fun subscribeSoftLivestreamPrivacyModeEnabledAttribute( minInterval: Int, maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 25u + ): Flow { + val ATTRIBUTE_ID: UInt = 20u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3508,7 +2796,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - UByteSubscriptionState.Error( + BooleanSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -3522,29 +2810,29 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Nightvisionillum attribute not found in Node State update" + "Softlivestreamprivacymodeenabled attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = + val decodedValue: Boolean? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) + tlvReader.getBoolean(AnonymousTag) } else { null } - decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } + decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(UByteSubscriptionState.SubscriptionEstablished) + emit(BooleanSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readAWBEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 26u + suspend fun readHardPrivacyModeOnAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 21u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3565,7 +2853,7 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Awbenabled attribute not found in response" } + requireNotNull(attributeData) { "Hardprivacymodeon attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -3579,51 +2867,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeAWBEnabledAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 26u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - - suspend fun subscribeAWBEnabledAttribute( + suspend fun subscribeHardPrivacyModeOnAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 26u + val ATTRIBUTE_ID: UInt = 21u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3654,7 +2902,9 @@ class CameraAvStreamManagementCluster( .filterIsInstance() .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Awbenabled attribute not found in Node State update" } + requireNotNull(attributeData) { + "Hardprivacymodeon attribute not found in Node State update" + } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -3674,8 +2924,8 @@ class CameraAvStreamManagementCluster( } } - suspend fun readAutoShutterSpeedEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 27u + suspend fun readNightVisionAttribute(): UByte? { + val ATTRIBUTE_ID: UInt = 22u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3696,13 +2946,13 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Autoshutterspeedenabled attribute not found in response" } + requireNotNull(attributeData) { "Nightvision attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: UByte? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + tlvReader.getUByte(AnonymousTag) } else { null } @@ -3710,11 +2960,8 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeAutoShutterSpeedEnabledAttribute( - value: Boolean, - timedWriteTimeout: Duration? = null, - ) { - val ATTRIBUTE_ID: UInt = 27u + suspend fun writeNightVisionAttribute(value: UByte, timedWriteTimeout: Duration? = null) { + val ATTRIBUTE_ID: UInt = 22u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -3753,11 +3000,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeAutoShutterSpeedEnabledAttribute( + suspend fun subscribeNightVisionAttribute( minInterval: Int, maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 27u + ): Flow { + val ATTRIBUTE_ID: UInt = 22u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3775,7 +3022,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - BooleanSubscriptionState.Error( + UByteSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -3788,30 +3035,28 @@ class CameraAvStreamManagementCluster( .filterIsInstance() .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { - "Autoshutterspeedenabled attribute not found in Node State update" - } + requireNotNull(attributeData) { "Nightvision attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: UByte? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + tlvReader.getUByte(AnonymousTag) } else { null } - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } + decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) + emit(UByteSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readAutoISOEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 28u + suspend fun readNightVisionIllumAttribute(): UByte? { + val ATTRIBUTE_ID: UInt = 23u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3832,13 +3077,13 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Autoisoenabled attribute not found in response" } + requireNotNull(attributeData) { "Nightvisionillum attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: UByte? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + tlvReader.getUByte(AnonymousTag) } else { null } @@ -3846,8 +3091,8 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeAutoISOEnabledAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 28u + suspend fun writeNightVisionIllumAttribute(value: UByte, timedWriteTimeout: Duration? = null) { + val ATTRIBUTE_ID: UInt = 23u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -3886,11 +3131,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeAutoISOEnabledAttribute( + suspend fun subscribeNightVisionIllumAttribute( minInterval: Int, maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 28u + ): Flow { + val ATTRIBUTE_ID: UInt = 23u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3908,7 +3153,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - BooleanSubscriptionState.Error( + UByteSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -3922,29 +3167,29 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Autoisoenabled attribute not found in Node State update" + "Nightvisionillum attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: UByte? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + tlvReader.getUByte(AnonymousTag) } else { null } - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } + decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) + emit(UByteSubscriptionState.SubscriptionEstablished) } } } } suspend fun readViewportAttribute(): ViewportAttribute { - val ATTRIBUTE_ID: UInt = 29u + val ATTRIBUTE_ID: UInt = 24u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -3979,11 +3224,54 @@ class CameraAvStreamManagementCluster( return ViewportAttribute(decodedValue) } + suspend fun writeViewportAttribute( + value: CameraAvStreamManagementClusterViewportStruct, + timedWriteTimeout: Duration? = null, + ) { + val ATTRIBUTE_ID: UInt = 24u + + val tlvWriter = TlvWriter() + value.toTlv(AnonymousTag, tlvWriter) + + val writeRequests: WriteRequests = + WriteRequests( + requests = + listOf( + WriteRequest( + attributePath = + AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), + tlvPayload = tlvWriter.getEncoded(), + ) + ), + timedRequest = timedWriteTimeout, + ) + + val response: WriteResponse = controller.write(writeRequests) + + when (response) { + is WriteResponse.Success -> { + logger.log(Level.FINE, "Write command succeeded") + } + is WriteResponse.PartialWriteFailure -> { + val aggregatedErrorMessage = + response.failures.joinToString("\n") { failure -> + "Error at ${failure.attributePath}: ${failure.ex.message}" + } + + response.failures.forEach { failure -> + logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") + } + + throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") + } + } + } + suspend fun subscribeViewportAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 29u + val ATTRIBUTE_ID: UInt = 24u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4035,7 +3323,7 @@ class CameraAvStreamManagementCluster( } suspend fun readSpeakerMutedAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 30u + val ATTRIBUTE_ID: UInt = 25u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4071,7 +3359,7 @@ class CameraAvStreamManagementCluster( } suspend fun writeSpeakerMutedAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 30u + val ATTRIBUTE_ID: UInt = 25u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -4114,7 +3402,7 @@ class CameraAvStreamManagementCluster( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 30u + val ATTRIBUTE_ID: UInt = 25u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4166,7 +3454,7 @@ class CameraAvStreamManagementCluster( } suspend fun readSpeakerVolumeLevelAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 31u + val ATTRIBUTE_ID: UInt = 26u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4202,7 +3490,7 @@ class CameraAvStreamManagementCluster( } suspend fun writeSpeakerVolumeLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 31u + val ATTRIBUTE_ID: UInt = 26u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -4245,7 +3533,7 @@ class CameraAvStreamManagementCluster( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 31u + val ATTRIBUTE_ID: UInt = 26u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4299,7 +3587,7 @@ class CameraAvStreamManagementCluster( } suspend fun readSpeakerMaxLevelAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 32u + val ATTRIBUTE_ID: UInt = 27u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4334,51 +3622,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeSpeakerMaxLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 32u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - suspend fun subscribeSpeakerMaxLevelAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 32u + val ATTRIBUTE_ID: UInt = 27u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4432,7 +3680,7 @@ class CameraAvStreamManagementCluster( } suspend fun readSpeakerMinLevelAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 33u + val ATTRIBUTE_ID: UInt = 28u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4467,51 +3715,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeSpeakerMinLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 33u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - suspend fun subscribeSpeakerMinLevelAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 33u + val ATTRIBUTE_ID: UInt = 28u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4565,7 +3773,7 @@ class CameraAvStreamManagementCluster( } suspend fun readMicrophoneMutedAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 34u + val ATTRIBUTE_ID: UInt = 29u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4601,7 +3809,7 @@ class CameraAvStreamManagementCluster( } suspend fun writeMicrophoneMutedAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 34u + val ATTRIBUTE_ID: UInt = 29u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -4644,7 +3852,7 @@ class CameraAvStreamManagementCluster( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 34u + val ATTRIBUTE_ID: UInt = 29u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4698,7 +3906,7 @@ class CameraAvStreamManagementCluster( } suspend fun readMicrophoneVolumeLevelAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 35u + val ATTRIBUTE_ID: UInt = 30u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4737,7 +3945,7 @@ class CameraAvStreamManagementCluster( value: UByte, timedWriteTimeout: Duration? = null, ) { - val ATTRIBUTE_ID: UInt = 35u + val ATTRIBUTE_ID: UInt = 30u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -4780,7 +3988,7 @@ class CameraAvStreamManagementCluster( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 35u + val ATTRIBUTE_ID: UInt = 30u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4834,7 +4042,7 @@ class CameraAvStreamManagementCluster( } suspend fun readMicrophoneMaxLevelAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 36u + val ATTRIBUTE_ID: UInt = 31u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4869,51 +4077,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeMicrophoneMaxLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 36u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - suspend fun subscribeMicrophoneMaxLevelAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 36u + val ATTRIBUTE_ID: UInt = 31u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4967,7 +4135,7 @@ class CameraAvStreamManagementCluster( } suspend fun readMicrophoneMinLevelAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 37u + val ATTRIBUTE_ID: UInt = 32u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5002,51 +4170,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeMicrophoneMinLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 37u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - suspend fun subscribeMicrophoneMinLevelAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 37u + val ATTRIBUTE_ID: UInt = 32u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5100,7 +4228,7 @@ class CameraAvStreamManagementCluster( } suspend fun readMicrophoneAGCEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 38u + val ATTRIBUTE_ID: UInt = 33u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5139,7 +4267,7 @@ class CameraAvStreamManagementCluster( value: Boolean, timedWriteTimeout: Duration? = null, ) { - val ATTRIBUTE_ID: UInt = 38u + val ATTRIBUTE_ID: UInt = 33u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -5182,7 +4310,7 @@ class CameraAvStreamManagementCluster( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 38u + val ATTRIBUTE_ID: UInt = 33u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5236,7 +4364,7 @@ class CameraAvStreamManagementCluster( } suspend fun readImageRotationAttribute(): UShort? { - val ATTRIBUTE_ID: UInt = 39u + val ATTRIBUTE_ID: UInt = 34u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5271,11 +4399,51 @@ class CameraAvStreamManagementCluster( return decodedValue } + suspend fun writeImageRotationAttribute(value: UShort, timedWriteTimeout: Duration? = null) { + val ATTRIBUTE_ID: UInt = 34u + + val tlvWriter = TlvWriter() + tlvWriter.put(AnonymousTag, value) + + val writeRequests: WriteRequests = + WriteRequests( + requests = + listOf( + WriteRequest( + attributePath = + AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), + tlvPayload = tlvWriter.getEncoded(), + ) + ), + timedRequest = timedWriteTimeout, + ) + + val response: WriteResponse = controller.write(writeRequests) + + when (response) { + is WriteResponse.Success -> { + logger.log(Level.FINE, "Write command succeeded") + } + is WriteResponse.PartialWriteFailure -> { + val aggregatedErrorMessage = + response.failures.joinToString("\n") { failure -> + "Error at ${failure.attributePath}: ${failure.ex.message}" + } + + response.failures.forEach { failure -> + logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") + } + + throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") + } + } + } + suspend fun subscribeImageRotationAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 39u + val ATTRIBUTE_ID: UInt = 34u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5327,7 +4495,7 @@ class CameraAvStreamManagementCluster( } suspend fun readImageFlipHorizontalAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 40u + val ATTRIBUTE_ID: UInt = 35u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5362,104 +4530,54 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun subscribeImageFlipHorizontalAttribute( - minInterval: Int, - maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 40u - val attributePaths = - listOf( - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - ) + suspend fun writeImageFlipHorizontalAttribute( + value: Boolean, + timedWriteTimeout: Duration? = null, + ) { + val ATTRIBUTE_ID: UInt = 35u - val subscribeRequest: SubscribeRequest = - SubscribeRequest( - eventPaths = emptyList(), - attributePaths = attributePaths, - minInterval = Duration.ofSeconds(minInterval.toLong()), - maxInterval = Duration.ofSeconds(maxInterval.toLong()), - ) + val tlvWriter = TlvWriter() + tlvWriter.put(AnonymousTag, value) - return controller.subscribe(subscribeRequest).transform { subscriptionState -> - when (subscriptionState) { - is SubscriptionState.SubscriptionErrorNotification -> { - emit( - BooleanSubscriptionState.Error( - Exception( - "Subscription terminated with error code: ${subscriptionState.terminationCause}" - ) + val writeRequests: WriteRequests = + WriteRequests( + requests = + listOf( + WriteRequest( + attributePath = + AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), + tlvPayload = tlvWriter.getEncoded(), ) - ) - } - is SubscriptionState.NodeStateUpdate -> { - val attributeData = - subscriptionState.updateState.successes - .filterIsInstance() - .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - - requireNotNull(attributeData) { - "Imagefliphorizontal attribute not found in Node State update" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null - } - - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } - } - SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) - } - } - } - } - - suspend fun readImageFlipVerticalAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 41u - - val attributePath = - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - - val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath)) - - val response = controller.read(readRequest) - - if (response.successes.isEmpty()) { - logger.log(Level.WARNING, "Read command failed") - throw IllegalStateException("Read command failed with failures: ${response.failures}") - } + ), + timedRequest = timedWriteTimeout, + ) - logger.log(Level.FINE, "Read command succeeded") + val response: WriteResponse = controller.write(writeRequests) - val attributeData = - response.successes.filterIsInstance().firstOrNull { - it.path.attributeId == ATTRIBUTE_ID + when (response) { + is WriteResponse.Success -> { + logger.log(Level.FINE, "Write command succeeded") } + is WriteResponse.PartialWriteFailure -> { + val aggregatedErrorMessage = + response.failures.joinToString("\n") { failure -> + "Error at ${failure.attributePath}: ${failure.ex.message}" + } - requireNotNull(attributeData) { "Imageflipvertical attribute not found in response" } + response.failures.forEach { failure -> + logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") + } - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null + throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") } - - return decodedValue + } } - suspend fun subscribeImageFlipVerticalAttribute( + suspend fun subscribeImageFlipHorizontalAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 41u + val ATTRIBUTE_ID: UInt = 35u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5491,7 +4609,7 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Imageflipvertical attribute not found in Node State update" + "Imagefliphorizontal attribute not found in Node State update" } // Decode the TLV data into the appropriate type @@ -5512,8 +4630,8 @@ class CameraAvStreamManagementCluster( } } - suspend fun readLocalVideoRecordingEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 42u + suspend fun readImageFlipVerticalAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 36u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5534,7 +4652,7 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Localvideorecordingenabled attribute not found in response" } + requireNotNull(attributeData) { "Imageflipvertical attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -5548,11 +4666,8 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeLocalVideoRecordingEnabledAttribute( - value: Boolean, - timedWriteTimeout: Duration? = null, - ) { - val ATTRIBUTE_ID: UInt = 42u + suspend fun writeImageFlipVerticalAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { + val ATTRIBUTE_ID: UInt = 36u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -5591,11 +4706,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeLocalVideoRecordingEnabledAttribute( + suspend fun subscribeImageFlipVerticalAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 42u + val ATTRIBUTE_ID: UInt = 36u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5627,7 +4742,7 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Localvideorecordingenabled attribute not found in Node State update" + "Imageflipvertical attribute not found in Node State update" } // Decode the TLV data into the appropriate type @@ -5648,8 +4763,8 @@ class CameraAvStreamManagementCluster( } } - suspend fun readLocalSnapshotRecordingEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 43u + suspend fun readLocalVideoRecordingEnabledAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 37u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5670,9 +4785,7 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { - "Localsnapshotrecordingenabled attribute not found in response" - } + requireNotNull(attributeData) { "Localvideorecordingenabled attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -5686,11 +4799,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeLocalSnapshotRecordingEnabledAttribute( + suspend fun writeLocalVideoRecordingEnabledAttribute( value: Boolean, timedWriteTimeout: Duration? = null, ) { - val ATTRIBUTE_ID: UInt = 43u + val ATTRIBUTE_ID: UInt = 37u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -5729,11 +4842,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeLocalSnapshotRecordingEnabledAttribute( + suspend fun subscribeLocalVideoRecordingEnabledAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 43u + val ATTRIBUTE_ID: UInt = 37u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5765,7 +4878,7 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Localsnapshotrecordingenabled attribute not found in Node State update" + "Localvideorecordingenabled attribute not found in Node State update" } // Decode the TLV data into the appropriate type @@ -5786,8 +4899,8 @@ class CameraAvStreamManagementCluster( } } - suspend fun readStatusLightEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 44u + suspend fun readLocalSnapshotRecordingEnabledAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 38u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5808,7 +4921,9 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Statuslightenabled attribute not found in response" } + requireNotNull(attributeData) { + "Localsnapshotrecordingenabled attribute not found in response" + } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -5822,11 +4937,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeStatusLightEnabledAttribute( + suspend fun writeLocalSnapshotRecordingEnabledAttribute( value: Boolean, timedWriteTimeout: Duration? = null, ) { - val ATTRIBUTE_ID: UInt = 44u + val ATTRIBUTE_ID: UInt = 38u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -5865,11 +4980,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeStatusLightEnabledAttribute( + suspend fun subscribeLocalSnapshotRecordingEnabledAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 44u + val ATTRIBUTE_ID: UInt = 38u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5901,7 +5016,7 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Statuslightenabled attribute not found in Node State update" + "Localsnapshotrecordingenabled attribute not found in Node State update" } // Decode the TLV data into the appropriate type @@ -5922,8 +5037,8 @@ class CameraAvStreamManagementCluster( } } - suspend fun readStatusLightBrightnessAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 45u + suspend fun readStatusLightEnabledAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 39u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5944,13 +5059,13 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Statuslightbrightness attribute not found in response" } + requireNotNull(attributeData) { "Statuslightenabled attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = + val decodedValue: Boolean? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) + tlvReader.getBoolean(AnonymousTag) } else { null } @@ -5958,11 +5073,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeStatusLightBrightnessAttribute( - value: UByte, + suspend fun writeStatusLightEnabledAttribute( + value: Boolean, timedWriteTimeout: Duration? = null, ) { - val ATTRIBUTE_ID: UInt = 45u + val ATTRIBUTE_ID: UInt = 39u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -6001,11 +5116,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeStatusLightBrightnessAttribute( + suspend fun subscribeStatusLightEnabledAttribute( minInterval: Int, maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 45u + ): Flow { + val ATTRIBUTE_ID: UInt = 39u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -6023,7 +5138,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - UByteSubscriptionState.Error( + BooleanSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -6037,29 +5152,29 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Statuslightbrightness attribute not found in Node State update" + "Statuslightenabled attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = + val decodedValue: Boolean? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) + tlvReader.getBoolean(AnonymousTag) } else { null } - decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } + decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(UByteSubscriptionState.SubscriptionEstablished) + emit(BooleanSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readDepthSensorStatusAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 46u + suspend fun readStatusLightBrightnessAttribute(): UByte? { + val ATTRIBUTE_ID: UInt = 40u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -6080,7 +5195,7 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Depthsensorstatus attribute not found in response" } + requireNotNull(attributeData) { "Statuslightbrightness attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -6094,8 +5209,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeDepthSensorStatusAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 46u + suspend fun writeStatusLightBrightnessAttribute( + value: UByte, + timedWriteTimeout: Duration? = null, + ) { + val ATTRIBUTE_ID: UInt = 40u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -6134,11 +5252,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeDepthSensorStatusAttribute( + suspend fun subscribeStatusLightBrightnessAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 46u + val ATTRIBUTE_ID: UInt = 40u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -6170,7 +5288,7 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Depthsensorstatus attribute not found in Node State update" + "Statuslightbrightness attribute not found in Node State update" } // Decode the TLV data into the appropriate type diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/ZoneManagementCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/ZoneManagementCluster.kt index c51fe6eaf0da23..9a85fdba030a1b 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/ZoneManagementCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/ZoneManagementCluster.kt @@ -72,15 +72,15 @@ class ZoneManagementCluster( object SubscriptionEstablished : ZonesAttributeSubscriptionState() } - class TimeControlAttribute(val value: List) + class TriggersAttribute(val value: List) - sealed class TimeControlAttributeSubscriptionState { - data class Success(val value: List) : - TimeControlAttributeSubscriptionState() + sealed class TriggersAttributeSubscriptionState { + data class Success(val value: List) : + TriggersAttributeSubscriptionState() - data class Error(val exception: Exception) : TimeControlAttributeSubscriptionState() + data class Error(val exception: Exception) : TriggersAttributeSubscriptionState() - object SubscriptionEstablished : TimeControlAttributeSubscriptionState() + object SubscriptionEstablished : TriggersAttributeSubscriptionState() } class GeneratedCommandListAttribute(val value: List) @@ -473,7 +473,7 @@ class ZoneManagementCluster( } } - suspend fun readTimeControlAttribute(): TimeControlAttribute { + suspend fun readTriggersAttribute(): TriggersAttribute { val ATTRIBUTE_ID: UInt = 2u val attributePath = @@ -495,24 +495,24 @@ class ZoneManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Timecontrol attribute not found in response" } + requireNotNull(attributeData) { "Triggers attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: List = - buildList { + val decodedValue: List = + buildList { tlvReader.enterArray(AnonymousTag) while (!tlvReader.isEndOfContainer()) { - add(ZoneManagementClusterZoneTriggeringTimeControlStruct.fromTlv(AnonymousTag, tlvReader)) + add(ZoneManagementClusterZoneTriggerControlStruct.fromTlv(AnonymousTag, tlvReader)) } tlvReader.exitContainer() } - return TimeControlAttribute(decodedValue) + return TriggersAttribute(decodedValue) } - suspend fun writeTimeControlAttribute( - value: List, + suspend fun writeTriggersAttribute( + value: List, timedWriteTimeout: Duration? = null, ) { val ATTRIBUTE_ID: UInt = 2u @@ -558,10 +558,10 @@ class ZoneManagementCluster( } } - suspend fun subscribeTimeControlAttribute( + suspend fun subscribeTriggersAttribute( minInterval: Int, maxInterval: Int, - ): Flow { + ): Flow { val ATTRIBUTE_ID: UInt = 2u val attributePaths = listOf( @@ -580,7 +580,7 @@ class ZoneManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - TimeControlAttributeSubscriptionState.Error( + TriggersAttributeSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -593,34 +593,29 @@ class ZoneManagementCluster( .filterIsInstance() .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Timecontrol attribute not found in Node State update" } + requireNotNull(attributeData) { "Triggers attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: List = - buildList { + val decodedValue: List = + buildList { tlvReader.enterArray(AnonymousTag) while (!tlvReader.isEndOfContainer()) { - add( - ZoneManagementClusterZoneTriggeringTimeControlStruct.fromTlv( - AnonymousTag, - tlvReader, - ) - ) + add(ZoneManagementClusterZoneTriggerControlStruct.fromTlv(AnonymousTag, tlvReader)) } tlvReader.exitContainer() } - emit(TimeControlAttributeSubscriptionState.Success(decodedValue)) + emit(TriggersAttributeSubscriptionState.Success(decodedValue)) } SubscriptionState.SubscriptionEstablished -> { - emit(TimeControlAttributeSubscriptionState.SubscriptionEstablished) + emit(TriggersAttributeSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readSensitivityAttribute(): UByte { + suspend fun readSensitivityAttribute(): UByte? { val ATTRIBUTE_ID: UInt = 3u val attributePath = @@ -646,7 +641,12 @@ class ZoneManagementCluster( // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte = tlvReader.getUByte(AnonymousTag) + val decodedValue: UByte? = + if (tlvReader.isNextTag(AnonymousTag)) { + tlvReader.getUByte(AnonymousTag) + } else { + null + } return decodedValue } @@ -730,9 +730,14 @@ class ZoneManagementCluster( // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte = tlvReader.getUByte(AnonymousTag) + val decodedValue: UByte? = + if (tlvReader.isNextTag(AnonymousTag)) { + tlvReader.getUByte(AnonymousTag) + } else { + null + } - emit(UByteSubscriptionState.Success(decodedValue)) + decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { emit(UByteSubscriptionState.SubscriptionEstablished) diff --git a/src/controller/java/generated/java/matter/controller/cluster/files.gni b/src/controller/java/generated/java/matter/controller/cluster/files.gni index 15406011f71772..b09fc7b799e316 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/files.gni +++ b/src/controller/java/generated/java/matter/controller/cluster/files.gni @@ -176,7 +176,7 @@ matter_structs_sources = [ "${chip_root}/src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterTwoDCartesianVertexStruct.kt", "${chip_root}/src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterTwoDCartesianZoneStruct.kt", "${chip_root}/src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterZoneInformationStruct.kt", - "${chip_root}/src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterZoneTriggeringTimeControlStruct.kt", + "${chip_root}/src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterZoneTriggerControlStruct.kt", ] matter_eventstructs_sources = [ diff --git a/src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterZoneTriggeringTimeControlStruct.kt b/src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterZoneTriggerControlStruct.kt similarity index 74% rename from src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterZoneTriggeringTimeControlStruct.kt rename to src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterZoneTriggerControlStruct.kt index 8978d74256a2c9..0927427722f34c 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterZoneTriggeringTimeControlStruct.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/structs/ZoneManagementClusterZoneTriggerControlStruct.kt @@ -16,24 +16,27 @@ */ package matter.controller.cluster.structs +import java.util.Optional import matter.controller.cluster.* import matter.tlv.ContextSpecificTag import matter.tlv.Tag import matter.tlv.TlvReader import matter.tlv.TlvWriter -class ZoneManagementClusterZoneTriggeringTimeControlStruct( +class ZoneManagementClusterZoneTriggerControlStruct( val initialDuration: UShort, val augmentationDuration: UShort, val maxDuration: UInt, val blindDuration: UShort, + val sensitivity: Optional, ) { override fun toString(): String = buildString { - append("ZoneManagementClusterZoneTriggeringTimeControlStruct {\n") + append("ZoneManagementClusterZoneTriggerControlStruct {\n") append("\tinitialDuration : $initialDuration\n") append("\taugmentationDuration : $augmentationDuration\n") append("\tmaxDuration : $maxDuration\n") append("\tblindDuration : $blindDuration\n") + append("\tsensitivity : $sensitivity\n") append("}\n") } @@ -44,6 +47,10 @@ class ZoneManagementClusterZoneTriggeringTimeControlStruct( put(ContextSpecificTag(TAG_AUGMENTATION_DURATION), augmentationDuration) put(ContextSpecificTag(TAG_MAX_DURATION), maxDuration) put(ContextSpecificTag(TAG_BLIND_DURATION), blindDuration) + if (sensitivity.isPresent) { + val optsensitivity = sensitivity.get() + put(ContextSpecificTag(TAG_SENSITIVITY), optsensitivity) + } endStructure() } } @@ -53,24 +60,29 @@ class ZoneManagementClusterZoneTriggeringTimeControlStruct( private const val TAG_AUGMENTATION_DURATION = 1 private const val TAG_MAX_DURATION = 2 private const val TAG_BLIND_DURATION = 3 + private const val TAG_SENSITIVITY = 4 - fun fromTlv( - tlvTag: Tag, - tlvReader: TlvReader, - ): ZoneManagementClusterZoneTriggeringTimeControlStruct { + fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): ZoneManagementClusterZoneTriggerControlStruct { tlvReader.enterStructure(tlvTag) val initialDuration = tlvReader.getUShort(ContextSpecificTag(TAG_INITIAL_DURATION)) val augmentationDuration = tlvReader.getUShort(ContextSpecificTag(TAG_AUGMENTATION_DURATION)) val maxDuration = tlvReader.getUInt(ContextSpecificTag(TAG_MAX_DURATION)) val blindDuration = tlvReader.getUShort(ContextSpecificTag(TAG_BLIND_DURATION)) + val sensitivity = + if (tlvReader.isNextTag(ContextSpecificTag(TAG_SENSITIVITY))) { + Optional.of(tlvReader.getUByte(ContextSpecificTag(TAG_SENSITIVITY))) + } else { + Optional.empty() + } tlvReader.exitContainer() - return ZoneManagementClusterZoneTriggeringTimeControlStruct( + return ZoneManagementClusterZoneTriggerControlStruct( initialDuration, augmentationDuration, maxDuration, blindDuration, + sensitivity, ) } } diff --git a/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp b/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp index c8247c5d4d31a8..deddd974e4515e 100644 --- a/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp +++ b/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp @@ -39628,8 +39628,8 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR } return value; } - case Attributes::TimeControl::Id: { - using TypeInfo = Attributes::TimeControl::TypeInfo; + case Attributes::Triggers::Id: { + using TypeInfo = Attributes::Triggers::TypeInfo; TypeInfo::DecodableType cppValue; *aError = app::DataModel::Decode(aReader, cppValue); if (*aError != CHIP_NO_ERROR) @@ -39672,34 +39672,50 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR chip::JniReferences::GetInstance().CreateBoxedObject( newElement_0_blindDurationClassName.c_str(), newElement_0_blindDurationCtorSignature.c_str(), jninewElement_0_blindDuration, newElement_0_blindDuration); + jobject newElement_0_sensitivity; + if (!entry_0.sensitivity.HasValue()) + { + chip::JniReferences::GetInstance().CreateOptional(nullptr, newElement_0_sensitivity); + } + else + { + jobject newElement_0_sensitivityInsideOptional; + std::string newElement_0_sensitivityInsideOptionalClassName = "java/lang/Integer"; + std::string newElement_0_sensitivityInsideOptionalCtorSignature = "(I)V"; + jint jninewElement_0_sensitivityInsideOptional = static_cast(entry_0.sensitivity.Value()); + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_0_sensitivityInsideOptionalClassName.c_str(), + newElement_0_sensitivityInsideOptionalCtorSignature.c_str(), jninewElement_0_sensitivityInsideOptional, + newElement_0_sensitivityInsideOptional); + chip::JniReferences::GetInstance().CreateOptional(newElement_0_sensitivityInsideOptional, + newElement_0_sensitivity); + } { - jclass zoneTriggeringTimeControlStructStructClass_1; + jclass zoneTriggerControlStructStructClass_1; err = chip::JniReferences::GetInstance().GetLocalClassRef( - env, "chip/devicecontroller/ChipStructs$ZoneManagementClusterZoneTriggeringTimeControlStruct", - zoneTriggeringTimeControlStructStructClass_1); + env, "chip/devicecontroller/ChipStructs$ZoneManagementClusterZoneTriggerControlStruct", + zoneTriggerControlStructStructClass_1); if (err != CHIP_NO_ERROR) { - ChipLogError(Zcl, "Could not find class ChipStructs$ZoneManagementClusterZoneTriggeringTimeControlStruct"); + ChipLogError(Zcl, "Could not find class ChipStructs$ZoneManagementClusterZoneTriggerControlStruct"); return nullptr; } - jmethodID zoneTriggeringTimeControlStructStructCtor_1; + jmethodID zoneTriggerControlStructStructCtor_1; err = chip::JniReferences::GetInstance().FindMethod( - env, zoneTriggeringTimeControlStructStructClass_1, "", - "(Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Long;Ljava/lang/Integer;)V", - &zoneTriggeringTimeControlStructStructCtor_1); - if (err != CHIP_NO_ERROR || zoneTriggeringTimeControlStructStructCtor_1 == nullptr) + env, zoneTriggerControlStructStructClass_1, "", + "(Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Long;Ljava/lang/Integer;Ljava/util/Optional;)V", + &zoneTriggerControlStructStructCtor_1); + if (err != CHIP_NO_ERROR || zoneTriggerControlStructStructCtor_1 == nullptr) { - ChipLogError(Zcl, - "Could not find ChipStructs$ZoneManagementClusterZoneTriggeringTimeControlStruct constructor"); + ChipLogError(Zcl, "Could not find ChipStructs$ZoneManagementClusterZoneTriggerControlStruct constructor"); return nullptr; } - newElement_0 = - env->NewObject(zoneTriggeringTimeControlStructStructClass_1, zoneTriggeringTimeControlStructStructCtor_1, - newElement_0_initialDuration, newElement_0_augmentationDuration, newElement_0_maxDuration, - newElement_0_blindDuration); + newElement_0 = env->NewObject(zoneTriggerControlStructStructClass_1, zoneTriggerControlStructStructCtor_1, + newElement_0_initialDuration, newElement_0_augmentationDuration, + newElement_0_maxDuration, newElement_0_blindDuration, newElement_0_sensitivity); } chip::JniReferences::GetInstance().AddToList(value, newElement_0); } @@ -40477,123 +40493,6 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR jnivalue, value); return value; } - case Attributes::CurrentVideoCodecs::Id: { - using TypeInfo = Attributes::CurrentVideoCodecs::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = app::DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) - { - return nullptr; - } - jobject value; - chip::JniReferences::GetInstance().CreateArrayList(value); - - auto iter_value_0 = cppValue.begin(); - while (iter_value_0.Next()) - { - auto & entry_0 = iter_value_0.GetValue(); - jobject newElement_0; - std::string newElement_0ClassName = "java/lang/Integer"; - std::string newElement_0CtorSignature = "(I)V"; - jint jninewElement_0 = static_cast(entry_0); - chip::JniReferences::GetInstance().CreateBoxedObject( - newElement_0ClassName.c_str(), newElement_0CtorSignature.c_str(), jninewElement_0, newElement_0); - chip::JniReferences::GetInstance().AddToList(value, newElement_0); - } - return value; - } - case Attributes::CurrentSnapshotConfig::Id: { - using TypeInfo = Attributes::CurrentSnapshotConfig::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = app::DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) - { - return nullptr; - } - jobject value; - jobject value_resolution; - jobject value_resolution_width; - std::string value_resolution_widthClassName = "java/lang/Integer"; - std::string value_resolution_widthCtorSignature = "(I)V"; - jint jnivalue_resolution_width = static_cast(cppValue.resolution.width); - chip::JniReferences::GetInstance().CreateBoxedObject(value_resolution_widthClassName.c_str(), - value_resolution_widthCtorSignature.c_str(), - jnivalue_resolution_width, value_resolution_width); - jobject value_resolution_height; - std::string value_resolution_heightClassName = "java/lang/Integer"; - std::string value_resolution_heightCtorSignature = "(I)V"; - jint jnivalue_resolution_height = static_cast(cppValue.resolution.height); - chip::JniReferences::GetInstance().CreateBoxedObject(value_resolution_heightClassName.c_str(), - value_resolution_heightCtorSignature.c_str(), - jnivalue_resolution_height, value_resolution_height); - - { - jclass videoResolutionStructStructClass_1; - err = chip::JniReferences::GetInstance().GetLocalClassRef( - env, "chip/devicecontroller/ChipStructs$CameraAvStreamManagementClusterVideoResolutionStruct", - videoResolutionStructStructClass_1); - if (err != CHIP_NO_ERROR) - { - ChipLogError(Zcl, "Could not find class ChipStructs$CameraAvStreamManagementClusterVideoResolutionStruct"); - return nullptr; - } - - jmethodID videoResolutionStructStructCtor_1; - err = chip::JniReferences::GetInstance().FindMethod(env, videoResolutionStructStructClass_1, "", - "(Ljava/lang/Integer;Ljava/lang/Integer;)V", - &videoResolutionStructStructCtor_1); - if (err != CHIP_NO_ERROR || videoResolutionStructStructCtor_1 == nullptr) - { - ChipLogError(Zcl, - "Could not find ChipStructs$CameraAvStreamManagementClusterVideoResolutionStruct constructor"); - return nullptr; - } - - value_resolution = env->NewObject(videoResolutionStructStructClass_1, videoResolutionStructStructCtor_1, - value_resolution_width, value_resolution_height); - } - jobject value_maxFrameRate; - std::string value_maxFrameRateClassName = "java/lang/Integer"; - std::string value_maxFrameRateCtorSignature = "(I)V"; - jint jnivalue_maxFrameRate = static_cast(cppValue.maxFrameRate); - chip::JniReferences::GetInstance().CreateBoxedObject(value_maxFrameRateClassName.c_str(), - value_maxFrameRateCtorSignature.c_str(), - jnivalue_maxFrameRate, value_maxFrameRate); - jobject value_imageCodec; - std::string value_imageCodecClassName = "java/lang/Integer"; - std::string value_imageCodecCtorSignature = "(I)V"; - jint jnivalue_imageCodec = static_cast(cppValue.imageCodec); - chip::JniReferences::GetInstance().CreateBoxedObject( - value_imageCodecClassName.c_str(), value_imageCodecCtorSignature.c_str(), jnivalue_imageCodec, value_imageCodec); - - { - jclass snapshotParamsStructStructClass_0; - err = chip::JniReferences::GetInstance().GetLocalClassRef( - env, "chip/devicecontroller/ChipStructs$CameraAvStreamManagementClusterSnapshotParamsStruct", - snapshotParamsStructStructClass_0); - if (err != CHIP_NO_ERROR) - { - ChipLogError(Zcl, "Could not find class ChipStructs$CameraAvStreamManagementClusterSnapshotParamsStruct"); - return nullptr; - } - - jmethodID snapshotParamsStructStructCtor_0; - err = chip::JniReferences::GetInstance().FindMethod( - env, snapshotParamsStructStructClass_0, "", - "(Lchip/devicecontroller/ChipStructs$CameraAvStreamManagementClusterVideoResolutionStruct;Ljava/lang/" - "Integer;Ljava/lang/Integer;)V", - &snapshotParamsStructStructCtor_0); - if (err != CHIP_NO_ERROR || snapshotParamsStructStructCtor_0 == nullptr) - { - ChipLogError(Zcl, "Could not find ChipStructs$CameraAvStreamManagementClusterSnapshotParamsStruct constructor"); - return nullptr; - } - - value = env->NewObject(snapshotParamsStructStructClass_0, snapshotParamsStructStructCtor_0, value_resolution, - value_maxFrameRate, value_imageCodec); - } - return value; - } case Attributes::FabricsUsingCamera::Id: { using TypeInfo = Attributes::FabricsUsingCamera::TypeInfo; TypeInfo::DecodableType cppValue; @@ -41252,54 +41151,6 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR value); return value; } - case Attributes::AWBEnabled::Id: { - using TypeInfo = Attributes::AWBEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = app::DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) - { - return nullptr; - } - jobject value; - std::string valueClassName = "java/lang/Boolean"; - std::string valueCtorSignature = "(Z)V"; - jboolean jnivalue = static_cast(cppValue); - chip::JniReferences::GetInstance().CreateBoxedObject(valueClassName.c_str(), valueCtorSignature.c_str(), - jnivalue, value); - return value; - } - case Attributes::AutoShutterSpeedEnabled::Id: { - using TypeInfo = Attributes::AutoShutterSpeedEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = app::DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) - { - return nullptr; - } - jobject value; - std::string valueClassName = "java/lang/Boolean"; - std::string valueCtorSignature = "(Z)V"; - jboolean jnivalue = static_cast(cppValue); - chip::JniReferences::GetInstance().CreateBoxedObject(valueClassName.c_str(), valueCtorSignature.c_str(), - jnivalue, value); - return value; - } - case Attributes::AutoISOEnabled::Id: { - using TypeInfo = Attributes::AutoISOEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = app::DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) - { - return nullptr; - } - jobject value; - std::string valueClassName = "java/lang/Boolean"; - std::string valueCtorSignature = "(Z)V"; - jboolean jnivalue = static_cast(cppValue); - chip::JniReferences::GetInstance().CreateBoxedObject(valueClassName.c_str(), valueCtorSignature.c_str(), - jnivalue, value); - return value; - } case Attributes::Viewport::Id: { using TypeInfo = Attributes::Viewport::TypeInfo; TypeInfo::DecodableType cppValue; @@ -41616,22 +41467,6 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR value); return value; } - case Attributes::DepthSensorStatus::Id: { - using TypeInfo = Attributes::DepthSensorStatus::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = app::DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) - { - return nullptr; - } - jobject value; - std::string valueClassName = "java/lang/Integer"; - std::string valueCtorSignature = "(I)V"; - jint jnivalue = static_cast(cppValue); - chip::JniReferences::GetInstance().CreateBoxedObject(valueClassName.c_str(), valueCtorSignature.c_str(), jnivalue, - value); - return value; - } case Attributes::GeneratedCommandList::Id: { using TypeInfo = Attributes::GeneratedCommandList::TypeInfo; TypeInfo::DecodableType cppValue; diff --git a/src/controller/python/chip/clusters/CHIPClusters.py b/src/controller/python/chip/clusters/CHIPClusters.py index 08f8182e6b6886..971bb232a097f3 100644 --- a/src/controller/python/chip/clusters/CHIPClusters.py +++ b/src/controller/python/chip/clusters/CHIPClusters.py @@ -12339,7 +12339,7 @@ class ChipClusters: "reportable": True, }, 0x00000002: { - "attributeName": "TimeControl", + "attributeName": "Triggers", "attributeId": 0x00000002, "type": "", "reportable": True, @@ -12447,7 +12447,7 @@ class ChipClusters: "commandName": "SnapshotStreamAllocate", "args": { "imageCodec": "int", - "frameRate": "int", + "maxFrameRate": "int", "bitRate": "int", "minResolution": "VideoResolutionStruct", "maxResolution": "VideoResolutionStruct", @@ -12476,34 +12476,6 @@ class ChipClusters: "requestedResolution": "VideoResolutionStruct", }, }, - 0x0000000D: { - "commandId": 0x0000000D, - "commandName": "SetViewport", - "args": { - "viewport": "ViewportStruct", - }, - }, - 0x0000000E: { - "commandId": 0x0000000E, - "commandName": "SetImageRotation", - "args": { - "angle": "int", - }, - }, - 0x0000000F: { - "commandId": 0x0000000F, - "commandName": "SetImageFlipHorizontal", - "args": { - "enabled": "bool", - }, - }, - 0x00000010: { - "commandId": 0x00000010, - "commandName": "SetImageFlipVertical", - "args": { - "enabled": "bool", - }, - }, }, "attributes": { 0x00000000: { @@ -12592,221 +12564,180 @@ class ChipClusters: "writable": True, }, 0x0000000E: { - "attributeName": "CurrentVideoCodecs", + "attributeName": "FabricsUsingCamera", "attributeId": 0x0000000E, "type": "int", "reportable": True, }, 0x0000000F: { - "attributeName": "CurrentSnapshotConfig", + "attributeName": "AllocatedVideoStreams", "attributeId": 0x0000000F, "type": "", "reportable": True, }, 0x00000010: { - "attributeName": "FabricsUsingCamera", + "attributeName": "AllocatedAudioStreams", "attributeId": 0x00000010, - "type": "int", + "type": "", "reportable": True, }, 0x00000011: { - "attributeName": "AllocatedVideoStreams", + "attributeName": "AllocatedSnapshotStreams", "attributeId": 0x00000011, "type": "", "reportable": True, }, 0x00000012: { - "attributeName": "AllocatedAudioStreams", + "attributeName": "RankedVideoStreamPrioritiesList", "attributeId": 0x00000012, - "type": "", + "type": "int", "reportable": True, }, 0x00000013: { - "attributeName": "AllocatedSnapshotStreams", + "attributeName": "SoftRecordingPrivacyModeEnabled", "attributeId": 0x00000013, - "type": "", + "type": "bool", "reportable": True, + "writable": True, }, 0x00000014: { - "attributeName": "RankedVideoStreamPrioritiesList", + "attributeName": "SoftLivestreamPrivacyModeEnabled", "attributeId": 0x00000014, - "type": "int", + "type": "bool", "reportable": True, "writable": True, }, 0x00000015: { - "attributeName": "SoftRecordingPrivacyModeEnabled", + "attributeName": "HardPrivacyModeOn", "attributeId": 0x00000015, "type": "bool", "reportable": True, - "writable": True, }, 0x00000016: { - "attributeName": "SoftLivestreamPrivacyModeEnabled", + "attributeName": "NightVision", "attributeId": 0x00000016, - "type": "bool", + "type": "int", "reportable": True, "writable": True, }, 0x00000017: { - "attributeName": "HardPrivacyModeOn", + "attributeName": "NightVisionIllum", "attributeId": 0x00000017, - "type": "bool", + "type": "int", "reportable": True, + "writable": True, }, 0x00000018: { - "attributeName": "NightVision", + "attributeName": "Viewport", "attributeId": 0x00000018, - "type": "int", + "type": "", "reportable": True, "writable": True, }, 0x00000019: { - "attributeName": "NightVisionIllum", + "attributeName": "SpeakerMuted", "attributeId": 0x00000019, - "type": "int", + "type": "bool", "reportable": True, "writable": True, }, 0x0000001A: { - "attributeName": "AWBEnabled", + "attributeName": "SpeakerVolumeLevel", "attributeId": 0x0000001A, - "type": "bool", + "type": "int", "reportable": True, "writable": True, }, 0x0000001B: { - "attributeName": "AutoShutterSpeedEnabled", + "attributeName": "SpeakerMaxLevel", "attributeId": 0x0000001B, - "type": "bool", + "type": "int", "reportable": True, - "writable": True, }, 0x0000001C: { - "attributeName": "AutoISOEnabled", + "attributeName": "SpeakerMinLevel", "attributeId": 0x0000001C, - "type": "bool", + "type": "int", "reportable": True, - "writable": True, }, 0x0000001D: { - "attributeName": "Viewport", + "attributeName": "MicrophoneMuted", "attributeId": 0x0000001D, - "type": "", + "type": "bool", "reportable": True, + "writable": True, }, 0x0000001E: { - "attributeName": "SpeakerMuted", + "attributeName": "MicrophoneVolumeLevel", "attributeId": 0x0000001E, - "type": "bool", + "type": "int", "reportable": True, "writable": True, }, 0x0000001F: { - "attributeName": "SpeakerVolumeLevel", + "attributeName": "MicrophoneMaxLevel", "attributeId": 0x0000001F, "type": "int", "reportable": True, - "writable": True, }, 0x00000020: { - "attributeName": "SpeakerMaxLevel", + "attributeName": "MicrophoneMinLevel", "attributeId": 0x00000020, "type": "int", "reportable": True, - "writable": True, }, 0x00000021: { - "attributeName": "SpeakerMinLevel", + "attributeName": "MicrophoneAGCEnabled", "attributeId": 0x00000021, - "type": "int", + "type": "bool", "reportable": True, "writable": True, }, 0x00000022: { - "attributeName": "MicrophoneMuted", + "attributeName": "ImageRotation", "attributeId": 0x00000022, - "type": "bool", + "type": "int", "reportable": True, "writable": True, }, 0x00000023: { - "attributeName": "MicrophoneVolumeLevel", + "attributeName": "ImageFlipHorizontal", "attributeId": 0x00000023, - "type": "int", + "type": "bool", "reportable": True, "writable": True, }, 0x00000024: { - "attributeName": "MicrophoneMaxLevel", + "attributeName": "ImageFlipVertical", "attributeId": 0x00000024, - "type": "int", + "type": "bool", "reportable": True, "writable": True, }, 0x00000025: { - "attributeName": "MicrophoneMinLevel", + "attributeName": "LocalVideoRecordingEnabled", "attributeId": 0x00000025, - "type": "int", + "type": "bool", "reportable": True, "writable": True, }, 0x00000026: { - "attributeName": "MicrophoneAGCEnabled", + "attributeName": "LocalSnapshotRecordingEnabled", "attributeId": 0x00000026, "type": "bool", "reportable": True, "writable": True, }, 0x00000027: { - "attributeName": "ImageRotation", - "attributeId": 0x00000027, - "type": "int", - "reportable": True, - }, - 0x00000028: { - "attributeName": "ImageFlipHorizontal", - "attributeId": 0x00000028, - "type": "bool", - "reportable": True, - }, - 0x00000029: { - "attributeName": "ImageFlipVertical", - "attributeId": 0x00000029, - "type": "bool", - "reportable": True, - }, - 0x0000002A: { - "attributeName": "LocalVideoRecordingEnabled", - "attributeId": 0x0000002A, - "type": "bool", - "reportable": True, - "writable": True, - }, - 0x0000002B: { - "attributeName": "LocalSnapshotRecordingEnabled", - "attributeId": 0x0000002B, - "type": "bool", - "reportable": True, - "writable": True, - }, - 0x0000002C: { "attributeName": "StatusLightEnabled", - "attributeId": 0x0000002C, + "attributeId": 0x00000027, "type": "bool", "reportable": True, "writable": True, }, - 0x0000002D: { + 0x00000028: { "attributeName": "StatusLightBrightness", - "attributeId": 0x0000002D, - "type": "int", - "reportable": True, - "writable": True, - }, - 0x0000002E: { - "attributeName": "DepthSensorStatus", - "attributeId": 0x0000002E, + "attributeId": 0x00000028, "type": "int", "reportable": True, "writable": True, diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index b7b73282715a22..b27196c7512fce 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -44337,8 +44337,8 @@ def descriptor(cls) -> ClusterObjectDescriptor: Fields=[ ClusterObjectFieldDescriptor(Label="supportedZoneSources", Tag=0x00000000, Type=typing.List[ZoneManagement.Enums.ZoneSourceEnum]), ClusterObjectFieldDescriptor(Label="zones", Tag=0x00000001, Type=typing.Optional[typing.List[ZoneManagement.Structs.ZoneInformationStruct]]), - ClusterObjectFieldDescriptor(Label="timeControl", Tag=0x00000002, Type=typing.List[ZoneManagement.Structs.ZoneTriggeringTimeControlStruct]), - ClusterObjectFieldDescriptor(Label="sensitivity", Tag=0x00000003, Type=uint), + ClusterObjectFieldDescriptor(Label="triggers", Tag=0x00000002, Type=typing.List[ZoneManagement.Structs.ZoneTriggerControlStruct]), + ClusterObjectFieldDescriptor(Label="sensitivity", Tag=0x00000003, Type=typing.Optional[uint]), ClusterObjectFieldDescriptor(Label="generatedCommandList", Tag=0x0000FFF8, Type=typing.List[uint]), ClusterObjectFieldDescriptor(Label="acceptedCommandList", Tag=0x0000FFF9, Type=typing.List[uint]), ClusterObjectFieldDescriptor(Label="attributeList", Tag=0x0000FFFB, Type=typing.List[uint]), @@ -44348,8 +44348,8 @@ def descriptor(cls) -> ClusterObjectDescriptor: supportedZoneSources: typing.List[ZoneManagement.Enums.ZoneSourceEnum] = field(default_factory=lambda: []) zones: typing.Optional[typing.List[ZoneManagement.Structs.ZoneInformationStruct]] = None - timeControl: typing.List[ZoneManagement.Structs.ZoneTriggeringTimeControlStruct] = field(default_factory=lambda: []) - sensitivity: uint = 0 + triggers: typing.List[ZoneManagement.Structs.ZoneTriggerControlStruct] = field(default_factory=lambda: []) + sensitivity: typing.Optional[uint] = None generatedCommandList: typing.List[uint] = field(default_factory=lambda: []) acceptedCommandList: typing.List[uint] = field(default_factory=lambda: []) attributeList: typing.List[uint] = field(default_factory=lambda: []) @@ -44413,6 +44413,7 @@ class ZoneUseEnum(MatterIntEnum): class Bitmaps: class Feature(IntFlag): kTwoDimensionalCartesianZone = 0x1 + kPerZoneSensitivity = 0x2 class Structs: @dataclass @@ -44461,7 +44462,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: zoneSource: 'ZoneManagement.Enums.ZoneSourceEnum' = 0 @dataclass - class ZoneTriggeringTimeControlStruct(ClusterObject): + class ZoneTriggerControlStruct(ClusterObject): @ChipUtility.classproperty def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( @@ -44470,12 +44471,14 @@ def descriptor(cls) -> ClusterObjectDescriptor: ClusterObjectFieldDescriptor(Label="augmentationDuration", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="maxDuration", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="blindDuration", Tag=3, Type=uint), + ClusterObjectFieldDescriptor(Label="sensitivity", Tag=4, Type=typing.Optional[uint]), ]) initialDuration: 'uint' = 0 augmentationDuration: 'uint' = 0 maxDuration: 'uint' = 0 blindDuration: 'uint' = 0 + sensitivity: 'typing.Optional[uint]' = None class Commands: @dataclass @@ -44610,7 +44613,7 @@ def attribute_type(cls) -> ClusterObjectFieldDescriptor: value: typing.Optional[typing.List[ZoneManagement.Structs.ZoneInformationStruct]] = None @dataclass - class TimeControl(ClusterAttributeDescriptor): + class Triggers(ClusterAttributeDescriptor): @ChipUtility.classproperty def cluster_id(cls) -> int: return 0x00000550 @@ -44621,9 +44624,9 @@ def attribute_id(cls) -> int: @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.List[ZoneManagement.Structs.ZoneTriggeringTimeControlStruct]) + return ClusterObjectFieldDescriptor(Type=typing.List[ZoneManagement.Structs.ZoneTriggerControlStruct]) - value: typing.List[ZoneManagement.Structs.ZoneTriggeringTimeControlStruct] = field(default_factory=lambda: []) + value: typing.List[ZoneManagement.Structs.ZoneTriggerControlStruct] = field(default_factory=lambda: []) @dataclass class Sensitivity(ClusterAttributeDescriptor): @@ -44637,9 +44640,9 @@ def attribute_id(cls) -> int: @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=uint) + return ClusterObjectFieldDescriptor(Type=typing.Optional[uint]) - value: uint = 0 + value: typing.Optional[uint] = None @dataclass class GeneratedCommandList(ClusterAttributeDescriptor): @@ -44787,39 +44790,33 @@ def descriptor(cls) -> ClusterObjectDescriptor: ClusterObjectFieldDescriptor(Label="maxNetworkBandwidth", Tag=0x0000000B, Type=uint), ClusterObjectFieldDescriptor(Label="currentFrameRate", Tag=0x0000000C, Type=typing.Optional[uint]), ClusterObjectFieldDescriptor(Label="HDRModeEnabled", Tag=0x0000000D, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="currentVideoCodecs", Tag=0x0000000E, Type=typing.Optional[typing.List[CameraAvStreamManagement.Enums.VideoCodecEnum]]), - ClusterObjectFieldDescriptor(Label="currentSnapshotConfig", Tag=0x0000000F, Type=typing.Optional[CameraAvStreamManagement.Structs.SnapshotParamsStruct]), - ClusterObjectFieldDescriptor(Label="fabricsUsingCamera", Tag=0x00000010, Type=typing.List[uint]), - ClusterObjectFieldDescriptor(Label="allocatedVideoStreams", Tag=0x00000011, Type=typing.Optional[typing.List[CameraAvStreamManagement.Structs.VideoStreamStruct]]), - ClusterObjectFieldDescriptor(Label="allocatedAudioStreams", Tag=0x00000012, Type=typing.Optional[typing.List[CameraAvStreamManagement.Structs.AudioStreamStruct]]), - ClusterObjectFieldDescriptor(Label="allocatedSnapshotStreams", Tag=0x00000013, Type=typing.Optional[typing.List[CameraAvStreamManagement.Structs.SnapshotStreamStruct]]), - ClusterObjectFieldDescriptor(Label="rankedVideoStreamPrioritiesList", Tag=0x00000014, Type=typing.Optional[typing.List[CameraAvStreamManagement.Enums.StreamTypeEnum]]), - ClusterObjectFieldDescriptor(Label="softRecordingPrivacyModeEnabled", Tag=0x00000015, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="softLivestreamPrivacyModeEnabled", Tag=0x00000016, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="hardPrivacyModeOn", Tag=0x00000017, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="nightVision", Tag=0x00000018, Type=typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum]), - ClusterObjectFieldDescriptor(Label="nightVisionIllum", Tag=0x00000019, Type=typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum]), - ClusterObjectFieldDescriptor(Label="AWBEnabled", Tag=0x0000001A, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="autoShutterSpeedEnabled", Tag=0x0000001B, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="autoISOEnabled", Tag=0x0000001C, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="viewport", Tag=0x0000001D, Type=typing.Optional[CameraAvStreamManagement.Structs.ViewportStruct]), - ClusterObjectFieldDescriptor(Label="speakerMuted", Tag=0x0000001E, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="speakerVolumeLevel", Tag=0x0000001F, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="speakerMaxLevel", Tag=0x00000020, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="speakerMinLevel", Tag=0x00000021, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="microphoneMuted", Tag=0x00000022, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="microphoneVolumeLevel", Tag=0x00000023, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="microphoneMaxLevel", Tag=0x00000024, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="microphoneMinLevel", Tag=0x00000025, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="microphoneAGCEnabled", Tag=0x00000026, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="imageRotation", Tag=0x00000027, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="imageFlipHorizontal", Tag=0x00000028, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="imageFlipVertical", Tag=0x00000029, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="localVideoRecordingEnabled", Tag=0x0000002A, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="localSnapshotRecordingEnabled", Tag=0x0000002B, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="statusLightEnabled", Tag=0x0000002C, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="statusLightBrightness", Tag=0x0000002D, Type=typing.Optional[Globals.Enums.ThreeLevelAutoEnum]), - ClusterObjectFieldDescriptor(Label="depthSensorStatus", Tag=0x0000002E, Type=typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum]), + ClusterObjectFieldDescriptor(Label="fabricsUsingCamera", Tag=0x0000000E, Type=typing.List[uint]), + ClusterObjectFieldDescriptor(Label="allocatedVideoStreams", Tag=0x0000000F, Type=typing.Optional[typing.List[CameraAvStreamManagement.Structs.VideoStreamStruct]]), + ClusterObjectFieldDescriptor(Label="allocatedAudioStreams", Tag=0x00000010, Type=typing.Optional[typing.List[CameraAvStreamManagement.Structs.AudioStreamStruct]]), + ClusterObjectFieldDescriptor(Label="allocatedSnapshotStreams", Tag=0x00000011, Type=typing.Optional[typing.List[CameraAvStreamManagement.Structs.SnapshotStreamStruct]]), + ClusterObjectFieldDescriptor(Label="rankedVideoStreamPrioritiesList", Tag=0x00000012, Type=typing.Optional[typing.List[CameraAvStreamManagement.Enums.StreamTypeEnum]]), + ClusterObjectFieldDescriptor(Label="softRecordingPrivacyModeEnabled", Tag=0x00000013, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="softLivestreamPrivacyModeEnabled", Tag=0x00000014, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="hardPrivacyModeOn", Tag=0x00000015, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="nightVision", Tag=0x00000016, Type=typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum]), + ClusterObjectFieldDescriptor(Label="nightVisionIllum", Tag=0x00000017, Type=typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum]), + ClusterObjectFieldDescriptor(Label="viewport", Tag=0x00000018, Type=typing.Optional[CameraAvStreamManagement.Structs.ViewportStruct]), + ClusterObjectFieldDescriptor(Label="speakerMuted", Tag=0x00000019, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="speakerVolumeLevel", Tag=0x0000001A, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="speakerMaxLevel", Tag=0x0000001B, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="speakerMinLevel", Tag=0x0000001C, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="microphoneMuted", Tag=0x0000001D, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="microphoneVolumeLevel", Tag=0x0000001E, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="microphoneMaxLevel", Tag=0x0000001F, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="microphoneMinLevel", Tag=0x00000020, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="microphoneAGCEnabled", Tag=0x00000021, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="imageRotation", Tag=0x00000022, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="imageFlipHorizontal", Tag=0x00000023, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="imageFlipVertical", Tag=0x00000024, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="localVideoRecordingEnabled", Tag=0x00000025, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="localSnapshotRecordingEnabled", Tag=0x00000026, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="statusLightEnabled", Tag=0x00000027, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="statusLightBrightness", Tag=0x00000028, Type=typing.Optional[Globals.Enums.ThreeLevelAutoEnum]), ClusterObjectFieldDescriptor(Label="generatedCommandList", Tag=0x0000FFF8, Type=typing.List[uint]), ClusterObjectFieldDescriptor(Label="acceptedCommandList", Tag=0x0000FFF9, Type=typing.List[uint]), ClusterObjectFieldDescriptor(Label="attributeList", Tag=0x0000FFFB, Type=typing.List[uint]), @@ -44841,8 +44838,6 @@ def descriptor(cls) -> ClusterObjectDescriptor: maxNetworkBandwidth: uint = 0 currentFrameRate: typing.Optional[uint] = None HDRModeEnabled: typing.Optional[bool] = None - currentVideoCodecs: typing.Optional[typing.List[CameraAvStreamManagement.Enums.VideoCodecEnum]] = None - currentSnapshotConfig: typing.Optional[CameraAvStreamManagement.Structs.SnapshotParamsStruct] = None fabricsUsingCamera: typing.List[uint] = field(default_factory=lambda: []) allocatedVideoStreams: typing.Optional[typing.List[CameraAvStreamManagement.Structs.VideoStreamStruct]] = None allocatedAudioStreams: typing.Optional[typing.List[CameraAvStreamManagement.Structs.AudioStreamStruct]] = None @@ -44853,9 +44848,6 @@ def descriptor(cls) -> ClusterObjectDescriptor: hardPrivacyModeOn: typing.Optional[bool] = None nightVision: typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum] = None nightVisionIllum: typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum] = None - AWBEnabled: typing.Optional[bool] = None - autoShutterSpeedEnabled: typing.Optional[bool] = None - autoISOEnabled: typing.Optional[bool] = None viewport: typing.Optional[CameraAvStreamManagement.Structs.ViewportStruct] = None speakerMuted: typing.Optional[bool] = None speakerVolumeLevel: typing.Optional[uint] = None @@ -44873,7 +44865,6 @@ def descriptor(cls) -> ClusterObjectDescriptor: localSnapshotRecordingEnabled: typing.Optional[bool] = None statusLightEnabled: typing.Optional[bool] = None statusLightBrightness: typing.Optional[Globals.Enums.ThreeLevelAutoEnum] = None - depthSensorStatus: typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum] = None generatedCommandList: typing.List[uint] = field(default_factory=lambda: []) acceptedCommandList: typing.List[uint] = field(default_factory=lambda: []) attributeList: typing.List[uint] = field(default_factory=lambda: []) @@ -44942,12 +44933,12 @@ class VideoCodecEnum(MatterIntEnum): class Bitmaps: class Feature(IntFlag): - kPrivacy = 0x1 - kAudio = 0x2 - kSpeaker = 0x4 - kImageControl = 0x8 - kVideo = 0x10 - kSnapshot = 0x20 + kAudio = 0x1 + kVideo = 0x2 + kSnapshot = 0x4 + kPrivacy = 0x8 + kSpeaker = 0x10 + kImageControl = 0x20 kWatermark = 0x40 kOnScreenDisplay = 0x80 kLocalStorage = 0x100 @@ -45299,7 +45290,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: return ClusterObjectDescriptor( Fields=[ ClusterObjectFieldDescriptor(Label="imageCodec", Tag=0, Type=CameraAvStreamManagement.Enums.ImageCodecEnum), - ClusterObjectFieldDescriptor(Label="frameRate", Tag=1, Type=uint), + ClusterObjectFieldDescriptor(Label="maxFrameRate", Tag=1, Type=uint), ClusterObjectFieldDescriptor(Label="bitRate", Tag=2, Type=uint), ClusterObjectFieldDescriptor(Label="minResolution", Tag=3, Type=CameraAvStreamManagement.Structs.VideoResolutionStruct), ClusterObjectFieldDescriptor(Label="maxResolution", Tag=4, Type=CameraAvStreamManagement.Structs.VideoResolutionStruct), @@ -45307,7 +45298,7 @@ def descriptor(cls) -> ClusterObjectDescriptor: ]) imageCodec: CameraAvStreamManagement.Enums.ImageCodecEnum = 0 - frameRate: uint = 0 + maxFrameRate: uint = 0 bitRate: uint = 0 minResolution: CameraAvStreamManagement.Structs.VideoResolutionStruct = field(default_factory=lambda: CameraAvStreamManagement.Structs.VideoResolutionStruct()) maxResolution: CameraAvStreamManagement.Structs.VideoResolutionStruct = field(default_factory=lambda: CameraAvStreamManagement.Structs.VideoResolutionStruct()) @@ -45399,70 +45390,6 @@ def descriptor(cls) -> ClusterObjectDescriptor: imageCodec: CameraAvStreamManagement.Enums.ImageCodecEnum = 0 resolution: CameraAvStreamManagement.Structs.VideoResolutionStruct = field(default_factory=lambda: CameraAvStreamManagement.Structs.VideoResolutionStruct()) - @dataclass - class SetViewport(ClusterCommand): - cluster_id: typing.ClassVar[int] = 0x00000551 - command_id: typing.ClassVar[int] = 0x0000000D - is_client: typing.ClassVar[bool] = True - response_type: typing.ClassVar[typing.Optional[str]] = None - - @ChipUtility.classproperty - def descriptor(cls) -> ClusterObjectDescriptor: - return ClusterObjectDescriptor( - Fields=[ - ClusterObjectFieldDescriptor(Label="viewport", Tag=0, Type=CameraAvStreamManagement.Structs.ViewportStruct), - ]) - - viewport: CameraAvStreamManagement.Structs.ViewportStruct = field(default_factory=lambda: CameraAvStreamManagement.Structs.ViewportStruct()) - - @dataclass - class SetImageRotation(ClusterCommand): - cluster_id: typing.ClassVar[int] = 0x00000551 - command_id: typing.ClassVar[int] = 0x0000000E - is_client: typing.ClassVar[bool] = True - response_type: typing.ClassVar[typing.Optional[str]] = None - - @ChipUtility.classproperty - def descriptor(cls) -> ClusterObjectDescriptor: - return ClusterObjectDescriptor( - Fields=[ - ClusterObjectFieldDescriptor(Label="angle", Tag=0, Type=uint), - ]) - - angle: uint = 0 - - @dataclass - class SetImageFlipHorizontal(ClusterCommand): - cluster_id: typing.ClassVar[int] = 0x00000551 - command_id: typing.ClassVar[int] = 0x0000000F - is_client: typing.ClassVar[bool] = True - response_type: typing.ClassVar[typing.Optional[str]] = None - - @ChipUtility.classproperty - def descriptor(cls) -> ClusterObjectDescriptor: - return ClusterObjectDescriptor( - Fields=[ - ClusterObjectFieldDescriptor(Label="enabled", Tag=0, Type=bool), - ]) - - enabled: bool = False - - @dataclass - class SetImageFlipVertical(ClusterCommand): - cluster_id: typing.ClassVar[int] = 0x00000551 - command_id: typing.ClassVar[int] = 0x00000010 - is_client: typing.ClassVar[bool] = True - response_type: typing.ClassVar[typing.Optional[str]] = None - - @ChipUtility.classproperty - def descriptor(cls) -> ClusterObjectDescriptor: - return ClusterObjectDescriptor( - Fields=[ - ClusterObjectFieldDescriptor(Label="enabled", Tag=0, Type=bool), - ]) - - enabled: bool = False - class Attributes: @dataclass class MaxConcurrentVideoEncoders(ClusterAttributeDescriptor): @@ -45688,38 +45615,6 @@ def attribute_type(cls) -> ClusterObjectFieldDescriptor: value: typing.Optional[bool] = None - @dataclass - class CurrentVideoCodecs(ClusterAttributeDescriptor): - @ChipUtility.classproperty - def cluster_id(cls) -> int: - return 0x00000551 - - @ChipUtility.classproperty - def attribute_id(cls) -> int: - return 0x0000000E - - @ChipUtility.classproperty - def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[typing.List[CameraAvStreamManagement.Enums.VideoCodecEnum]]) - - value: typing.Optional[typing.List[CameraAvStreamManagement.Enums.VideoCodecEnum]] = None - - @dataclass - class CurrentSnapshotConfig(ClusterAttributeDescriptor): - @ChipUtility.classproperty - def cluster_id(cls) -> int: - return 0x00000551 - - @ChipUtility.classproperty - def attribute_id(cls) -> int: - return 0x0000000F - - @ChipUtility.classproperty - def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[CameraAvStreamManagement.Structs.SnapshotParamsStruct]) - - value: typing.Optional[CameraAvStreamManagement.Structs.SnapshotParamsStruct] = None - @dataclass class FabricsUsingCamera(ClusterAttributeDescriptor): @ChipUtility.classproperty @@ -45728,7 +45623,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000010 + return 0x0000000E @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45744,7 +45639,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000011 + return 0x0000000F @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45760,7 +45655,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000012 + return 0x00000010 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45776,7 +45671,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000013 + return 0x00000011 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45792,7 +45687,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000014 + return 0x00000012 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45808,7 +45703,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000015 + return 0x00000013 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45824,7 +45719,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000016 + return 0x00000014 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45840,7 +45735,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000017 + return 0x00000015 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45856,7 +45751,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000018 + return 0x00000016 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45872,7 +45767,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000019 + return 0x00000017 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45880,54 +45775,6 @@ def attribute_type(cls) -> ClusterObjectFieldDescriptor: value: typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum] = None - @dataclass - class AWBEnabled(ClusterAttributeDescriptor): - @ChipUtility.classproperty - def cluster_id(cls) -> int: - return 0x00000551 - - @ChipUtility.classproperty - def attribute_id(cls) -> int: - return 0x0000001A - - @ChipUtility.classproperty - def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[bool]) - - value: typing.Optional[bool] = None - - @dataclass - class AutoShutterSpeedEnabled(ClusterAttributeDescriptor): - @ChipUtility.classproperty - def cluster_id(cls) -> int: - return 0x00000551 - - @ChipUtility.classproperty - def attribute_id(cls) -> int: - return 0x0000001B - - @ChipUtility.classproperty - def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[bool]) - - value: typing.Optional[bool] = None - - @dataclass - class AutoISOEnabled(ClusterAttributeDescriptor): - @ChipUtility.classproperty - def cluster_id(cls) -> int: - return 0x00000551 - - @ChipUtility.classproperty - def attribute_id(cls) -> int: - return 0x0000001C - - @ChipUtility.classproperty - def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[bool]) - - value: typing.Optional[bool] = None - @dataclass class Viewport(ClusterAttributeDescriptor): @ChipUtility.classproperty @@ -45936,7 +45783,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000001D + return 0x00000018 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45952,7 +45799,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000001E + return 0x00000019 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45968,7 +45815,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000001F + return 0x0000001A @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45984,7 +45831,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000020 + return 0x0000001B @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46000,7 +45847,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000021 + return 0x0000001C @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46016,7 +45863,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000022 + return 0x0000001D @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46032,7 +45879,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000023 + return 0x0000001E @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46048,7 +45895,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000024 + return 0x0000001F @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46064,7 +45911,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000025 + return 0x00000020 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46080,7 +45927,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000026 + return 0x00000021 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46096,7 +45943,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000027 + return 0x00000022 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46112,7 +45959,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000028 + return 0x00000023 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46128,7 +45975,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000029 + return 0x00000024 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46144,7 +45991,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000002A + return 0x00000025 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46160,7 +46007,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000002B + return 0x00000026 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46176,7 +46023,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000002C + return 0x00000027 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46192,7 +46039,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000002D + return 0x00000028 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46200,22 +46047,6 @@ def attribute_type(cls) -> ClusterObjectFieldDescriptor: value: typing.Optional[Globals.Enums.ThreeLevelAutoEnum] = None - @dataclass - class DepthSensorStatus(ClusterAttributeDescriptor): - @ChipUtility.classproperty - def cluster_id(cls) -> int: - return 0x00000551 - - @ChipUtility.classproperty - def attribute_id(cls) -> int: - return 0x0000002E - - @ChipUtility.classproperty - def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum]) - - value: typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum] = None - @dataclass class GeneratedCommandList(ClusterAttributeDescriptor): @ChipUtility.classproperty diff --git a/src/controller/python/test/test_scripts/base.py b/src/controller/python/test/test_scripts/base.py index dc07e15bc2f709..b2c6ee2bb5207e 100644 --- a/src/controller/python/test/test_scripts/base.py +++ b/src/controller/python/test/test_scripts/base.py @@ -1159,7 +1159,7 @@ def TestResolve(self, nodeid): return False async def TestTriggerTestEventHandler(self, nodeid, enable_key, event_trigger): - self.logger.info("Test trigger test event handler for device = %08x", nodeid) + self.logger.info("Test trigger test event handler for device = %08x trigger = %016x", nodeid, event_trigger) try: await self.devCtrl.SendCommand(nodeid, 0, Clusters.GeneralDiagnostics.Commands.TestEventTrigger(enableKey=enable_key, eventTrigger=event_trigger)) return True @@ -1167,10 +1167,10 @@ async def TestTriggerTestEventHandler(self, nodeid, enable_key, event_trigger): self.logger.exception("Failed to trigger test event handler {}".format(ex)) return False - async def TestWaitForActive(self, nodeid): + async def TestWaitForActive(self, nodeid, stayActiveDurationMs=30000): self.logger.info("Test wait for device = %08x", nodeid) try: - await self.devCtrl.WaitForActive(nodeid) + await self.devCtrl.WaitForActive(nodeid, stayActiveDurationMs=stayActiveDurationMs) return True except Exception as ex: self.logger.exception("Failed to wait for active. {}".format(ex)) diff --git a/src/controller/python/test/test_scripts/icd_wait_for_device_test.py b/src/controller/python/test/test_scripts/icd_device_test.py similarity index 83% rename from src/controller/python/test/test_scripts/icd_wait_for_device_test.py rename to src/controller/python/test/test_scripts/icd_device_test.py index e28a76e17ac41e..e93ee5dac399f3 100755 --- a/src/controller/python/test/test_scripts/icd_wait_for_device_test.py +++ b/src/controller/python/test/test_scripts/icd_device_test.py @@ -35,11 +35,15 @@ async def waitForActiveAndTriggerCheckIn(test, nodeid): - coro = test.TestWaitForActive(nodeid=nodeid) - await test.TestTriggerTestEventHandler(nodeid, bytes.fromhex("00112233445566778899aabbccddeeff"), 0x0046 << 48) + coro = test.TestWaitForActive(nodeid=nodeid, stayActiveDurationMs=10) return await coro +async def invalidateHalfCounterValuesAndWaitForCheckIn(test, nodeid, testEventKey): + await test.TestTriggerTestEventHandler(nodeid, bytes.fromhex(testEventKey), 0x0046_0000_0000_0003) + return await waitForActiveAndTriggerCheckIn(test, nodeid) + + async def main(): optParser = OptionParser() optParser.add_option( @@ -108,6 +112,15 @@ async def main(): help="Discovery type of commissioning. (0: networkOnly 1: networkOnlyWithoutPASEAutoRetry 2: All)", metavar="" ) + optParser.add_option( + "--test-event-key", + action="store", + dest="testEventKey", + default="00112233445566778899aabbccddeeff", + type=str, + help="Enable key of Test event trigger.", + metavar="" + ) (options, remainingArgs) = optParser.parse_args(sys.argv[1:]) @@ -125,9 +138,14 @@ async def main(): nodeid=options.nodeid), "Failed to finish key exchange") logger.info("Commissioning completed") + logger.info("Testing wait for active") FailIfNot(await waitForActiveAndTriggerCheckIn(test, nodeid=options.nodeid), "Failed to test wait for active") - logger.info('Successfully handled wait-for-active') + logger.info("Successfully handled wait-for-active") + + logger.info("Testing InvalidateHalfCounterValues for refresh key") + FailIfNot(await invalidateHalfCounterValuesAndWaitForCheckIn(test, nodeid=options.nodeid, testEventKey=options.testEventKey), "Failed to test wait for active") + logger.info("Successfully handled key refresh") timeoutTicker.stop() diff --git a/src/crypto/CHIPCryptoPAL.cpp b/src/crypto/CHIPCryptoPAL.cpp index 2caecbcb156779..1ac01d033dbcdf 100644 --- a/src/crypto/CHIPCryptoPAL.cpp +++ b/src/crypto/CHIPCryptoPAL.cpp @@ -330,16 +330,16 @@ CHIP_ERROR Spake2p::BeginVerifier(const uint8_t * my_identity, size_t my_identit } CHIP_ERROR Spake2p::BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, - size_t peer_identity_len, const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, - size_t w1in_len) + size_t peer_identity_len, const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin, + size_t w1sin_len) { VerifyOrReturnError(state == CHIP_SPAKE2P_STATE::INIT, CHIP_ERROR_INTERNAL); ReturnErrorOnFailure(InternalHash(my_identity, my_identity_len)); ReturnErrorOnFailure(InternalHash(peer_identity, peer_identity_len)); ReturnErrorOnFailure(WriteMN()); - ReturnErrorOnFailure(FELoad(w0in, w0in_len, w0)); - ReturnErrorOnFailure(FELoad(w1in, w1in_len, w1)); + ReturnErrorOnFailure(FELoad(w0sin, w0sin_len, w0)); + ReturnErrorOnFailure(FELoad(w1sin, w1sin_len, w1)); state = CHIP_SPAKE2P_STATE::STARTED; role = CHIP_SPAKE2P_ROLE::PROVER; diff --git a/src/crypto/CHIPCryptoPAL.h b/src/crypto/CHIPCryptoPAL.h index 80611e93d12d88..45e13f26bb782c 100644 --- a/src/crypto/CHIPCryptoPAL.h +++ b/src/crypto/CHIPCryptoPAL.h @@ -942,6 +942,9 @@ class Hash_SHA256_stream private: HashSHA256OpaqueContext mContext; +#if CHIP_CRYPTO_BORINGSSL || CHIP_CRYPTO_OPENSSL + bool mInitialized = false; +#endif }; class HKDF_sha @@ -1160,16 +1163,16 @@ class Spake2p * @param my_identity_len The prover identity length. * @param peer_identity The peer identity. May be NULL if identities are not established. * @param peer_identity_len The peer identity length. - * @param w0in The input w0 (an output from the PBKDF). - * @param w0in_len The input w0 length. - * @param w1in The input w1 (an output from the PBKDF). - * @param w1in_len The input w1 length. + * @param w0sin The input w0s (an output from the PBKDF). + * @param w0sin_len The input w0s length. + * @param w1sin The input w1s (an output from the PBKDF). + * @param w1sin_len The input w1s length. * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ virtual CHIP_ERROR BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, - size_t peer_identity_len, const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, - size_t w1in_len); + size_t peer_identity_len, const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin, + size_t w1sin_len); /** * @brief Compute the first round of the protocol. @@ -1344,26 +1347,26 @@ class Spake2p /* * @synopsis Compute w0sin mod p * - * @param w0out Output field element (modulo p) + * @param w0out Output field element w0 * @param w0_len Output field element length - * @param w1sin Input field element - * @param w1sin_len Input field element length + * @param w0sin Input field element + * @param w0sin_len Input field element length * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ virtual CHIP_ERROR ComputeW0(uint8_t * w0out, size_t * w0_len, const uint8_t * w0sin, size_t w0sin_len) = 0; /* - * @synopsis Compute w1in*G + * @synopsis Compute w1in*G where w1in is w1sin mod p * * @param Lout Output point in 0x04 || X || Y format. * @param L_len Output point length - * @param w1in Input field element - * @param w1in_len Input field element size + * @param w1sin Input field element + * @param w1sin_len Input field element size * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ - virtual CHIP_ERROR ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) = 0; + virtual CHIP_ERROR ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) = 0; void * M; void * N; @@ -1518,7 +1521,7 @@ class Spake2p_P256_SHA256_HKDF_HMAC : public Spake2p CHIP_ERROR PointIsValid(void * R) override; CHIP_ERROR ComputeW0(uint8_t * w0out, size_t * w0_len, const uint8_t * w0sin, size_t w0sin_len) override; - CHIP_ERROR ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) override; + CHIP_ERROR ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) override; protected: CHIP_ERROR InitImpl() override; @@ -1558,12 +1561,12 @@ class Spake2pVerifier CHIP_ERROR Generate(uint32_t pbkdf2IterCount, const ByteSpan & salt, uint32_t setupPin); /** - * @brief Compute the initiator values (w0, w1) used for PAKE input. + * @brief Compute the initiator values (w0s, w1s) used for PAKE input. * * @param pbkdf2IterCount Iteration count for PBKDF2 function * @param salt Salt to be used for Spake2+ operation * @param setupPin Provided setup PIN (passcode) - * @param ws The output pair (w0, w1) stored sequentially + * @param ws The output pair (w0s, w1s) stored sequentially * @param ws_len The output length * * @return CHIP_ERROR The result from running PBKDF2 diff --git a/src/crypto/CHIPCryptoPALOpenSSL.cpp b/src/crypto/CHIPCryptoPALOpenSSL.cpp index c1182ac8ebe03c..033be4488844b3 100644 --- a/src/crypto/CHIPCryptoPALOpenSSL.cpp +++ b/src/crypto/CHIPCryptoPALOpenSSL.cpp @@ -433,36 +433,57 @@ CHIP_ERROR Hash_SHA1(const uint8_t * data, const size_t data_length, uint8_t * o return CHIP_NO_ERROR; } -Hash_SHA256_stream::Hash_SHA256_stream() {} +// For OpenSSL, we store a pointer to the digest context (EVP_MD_CTX) since EVP_MD_CTX is Opaque. +static_assert(kMAX_Hash_SHA256_Context_Size >= sizeof(void *), + "kMAX_Hash_SHA256_Context_Size needs to at least be able to store a pointer"); -Hash_SHA256_stream::~Hash_SHA256_stream() +// Storing a pointer to EVP_MD_CTX in HashSHA256OpaqueContext instead of the actual EVP_MD_CTX structure, as EVP_MD_CTX was made +// opaque by OpenSSL and is dynamically allocated. +static inline void set_inner_hash_evp_md_ctx(HashSHA256OpaqueContext * context, EVP_MD_CTX * evp_ctx) { - Clear(); + *SafePointerCast(context) = evp_ctx; } -static_assert(kMAX_Hash_SHA256_Context_Size >= sizeof(SHA256_CTX), - "kMAX_Hash_SHA256_Context_Size is too small for the size of underlying SHA256_CTX"); +static inline EVP_MD_CTX * to_inner_hash_evp_md_ctx(HashSHA256OpaqueContext * context) +{ + return *SafePointerCast(context); +} -static inline SHA256_CTX * to_inner_hash_sha256_context(HashSHA256OpaqueContext * context) +Hash_SHA256_stream::Hash_SHA256_stream() : mInitialized(false) { - return SafePointerCast(context); + set_inner_hash_evp_md_ctx(&mContext, nullptr); +} + +Hash_SHA256_stream::~Hash_SHA256_stream() +{ + Clear(); } CHIP_ERROR Hash_SHA256_stream::Begin() { - SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext); - const int result = SHA256_Init(context); + EVP_MD_CTX * mdctx = EVP_MD_CTX_new(); + VerifyOrReturnError(mdctx != nullptr, CHIP_ERROR_INTERNAL); + + set_inner_hash_evp_md_ctx(&mContext, mdctx); + + const int result = EVP_DigestInit_ex(mdctx, _digestForType(DigestType::SHA256), nullptr); + VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL); + mInitialized = true; return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA256_stream::AddData(const ByteSpan data) { - SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext); + VerifyOrReturnError(mInitialized, CHIP_ERROR_UNINITIALIZED); + + EVP_MD_CTX * mdctx = to_inner_hash_evp_md_ctx(&mContext); + VerifyOrReturnError(mdctx != nullptr, CHIP_ERROR_INTERNAL); + + const int result = EVP_DigestUpdate(mdctx, data.data(), data.size()); - const int result = SHA256_Update(context, Uint8::to_const_uchar(data.data()), data.size()); VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; @@ -470,27 +491,43 @@ CHIP_ERROR Hash_SHA256_stream::AddData(const ByteSpan data) CHIP_ERROR Hash_SHA256_stream::GetDigest(MutableByteSpan & out_buffer) { - SHA256_CTX * context = to_inner_hash_sha256_context(&mContext); - // Back-up context as we are about to finalize the hash to extract digest. - SHA256_CTX previous_ctx = *context; + VerifyOrReturnError(mInitialized, CHIP_ERROR_UNINITIALIZED); + + EVP_MD_CTX * mdctx = to_inner_hash_evp_md_ctx(&mContext); + + // Back-up the context as we are about to finalize the hash to extract digest. + EVP_MD_CTX * previous_mdctx = EVP_MD_CTX_new(); + VerifyOrReturnError(previous_mdctx != nullptr, CHIP_ERROR_INTERNAL); + const int copy_result = EVP_MD_CTX_copy_ex(previous_mdctx, mdctx); + VerifyOrReturnError(copy_result == 1, CHIP_ERROR_INTERNAL); // Pad + compute digest, then finalize context. It is restored next line to continue. CHIP_ERROR result = Finish(out_buffer); - // Restore context prior to finalization. - *context = previous_ctx; + // free the finalized context. + EVP_MD_CTX_free(mdctx); + + // Restore the backed up context, to be able to get intermediate digest again if needed + set_inner_hash_evp_md_ctx(&mContext, previous_mdctx); return result; } CHIP_ERROR Hash_SHA256_stream::Finish(MutableByteSpan & out_buffer) { + unsigned int size; + VerifyOrReturnError(out_buffer.size() >= kSHA256_Hash_Length, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mInitialized, CHIP_ERROR_UNINITIALIZED); + + EVP_MD_CTX * mdctx = to_inner_hash_evp_md_ctx(&mContext); + + const int result = EVP_DigestFinal_ex(mdctx, out_buffer.data(), &size); - SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext); - const int result = SHA256_Final(Uint8::to_uchar(out_buffer.data()), context); VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(size == kSHA256_Hash_Length, CHIP_ERROR_INTERNAL); + out_buffer = out_buffer.SubSpan(0, kSHA256_Hash_Length); return CHIP_NO_ERROR; @@ -498,6 +535,13 @@ CHIP_ERROR Hash_SHA256_stream::Finish(MutableByteSpan & out_buffer) void Hash_SHA256_stream::Clear() { + EVP_MD_CTX * mdctx = to_inner_hash_evp_md_ctx(&mContext); + + // EVP_MD_CTX_free does nothing if a nullptr is passed to it + EVP_MD_CTX_free(mdctx); + set_inner_hash_evp_md_ctx(&mContext, nullptr); + + mInitialized = false; OPENSSL_cleanse(this, sizeof(*this)); } @@ -1405,6 +1449,8 @@ void Spake2p_P256_SHA256_HKDF_HMAC::Clear() BN_CTX_free(context->bn_ctx); } + sha256_hash_ctx.Clear(); + free_point(M); free_point(N); free_point(X); @@ -1562,7 +1608,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_ERROR_INTERNAL; int error_openssl = 0; @@ -1577,8 +1623,8 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le Lout_point = EC_POINT_new(context->curve); VerifyOrExit(Lout_point != nullptr, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(CanCastTo(w1in_len), error = CHIP_ERROR_INTERNAL); - BN_bin2bn(Uint8::to_const_uchar(w1in), static_cast(w1in_len), w1_bn); + VerifyOrExit(CanCastTo(w1sin_len), error = CHIP_ERROR_INTERNAL); + BN_bin2bn(Uint8::to_const_uchar(w1sin), static_cast(w1sin_len), w1_bn); error_openssl = BN_mod(w1_bn, w1_bn, (BIGNUM *) order, context->bn_ctx); VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL); diff --git a/src/crypto/CHIPCryptoPALPSA.cpp b/src/crypto/CHIPCryptoPALPSA.cpp index ba34669a51ba94..eb67240232240a 100644 --- a/src/crypto/CHIPCryptoPALPSA.cpp +++ b/src/crypto/CHIPCryptoPALPSA.cpp @@ -1042,7 +1042,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -1058,7 +1058,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); + result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1sin), w1sin_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); diff --git a/src/crypto/CHIPCryptoPALmbedTLS.cpp b/src/crypto/CHIPCryptoPALmbedTLS.cpp index 4df0ce97e30989..b2726424abc016 100644 --- a/src/crypto/CHIPCryptoPALmbedTLS.cpp +++ b/src/crypto/CHIPCryptoPALmbedTLS.cpp @@ -1092,7 +1092,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -1108,7 +1108,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); + result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1sin), w1sin_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); diff --git a/src/crypto/PSASpake2p.cpp b/src/crypto/PSASpake2p.cpp index ae98b083c8a812..6625f970db92e8 100644 --- a/src/crypto/PSASpake2p.cpp +++ b/src/crypto/PSASpake2p.cpp @@ -94,11 +94,11 @@ CHIP_ERROR PSASpake2p_P256_SHA256_HKDF_HMAC::BeginVerifier(const uint8_t * my_id CHIP_ERROR PSASpake2p_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, size_t peer_identity_len, - const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, - size_t w1in_len) + const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin, + size_t w1sin_len) { - VerifyOrReturnError(w0in_len <= kSpake2p_WS_Length, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(w1in_len <= kSpake2p_WS_Length, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(w0sin_len <= kSpake2p_WS_Length, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(w1sin_len <= kSpake2p_WS_Length, CHIP_ERROR_INVALID_ARGUMENT); uint8_t password[kSpake2p_WS_Length * 2]; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; @@ -107,13 +107,13 @@ CHIP_ERROR PSASpake2p_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_iden psa_pake_cs_set_algorithm(&cp, PSA_ALG_SPAKE2P_MATTER); psa_pake_cs_set_primitive(&cp, PSA_PAKE_PRIMITIVE(PSA_PAKE_PRIMITIVE_TYPE_ECC, PSA_ECC_FAMILY_SECP_R1, 256)); - memcpy(password + 0, w0in, w0in_len); - memcpy(password + w0in_len, w1in, w1in_len); + memcpy(password + 0, w0sin, w0sin_len); + memcpy(password + w0sin_len, w1sin, w1sin_len); psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE); psa_set_key_algorithm(&attributes, PSA_ALG_SPAKE2P_MATTER); psa_set_key_type(&attributes, PSA_KEY_TYPE_SPAKE2P_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)); - psa_status_t status = psa_import_key(&attributes, password, w0in_len + w1in_len, &mKey); + psa_status_t status = psa_import_key(&attributes, password, w0sin_len + w1sin_len, &mKey); psa_reset_key_attributes(&attributes); VerifyOrReturnError(status == PSA_SUCCESS, CHIP_ERROR_INTERNAL); diff --git a/src/crypto/PSASpake2p.h b/src/crypto/PSASpake2p.h index 9907b1ec09a5bc..163769037005d5 100644 --- a/src/crypto/PSASpake2p.h +++ b/src/crypto/PSASpake2p.h @@ -89,15 +89,16 @@ class PSASpake2p_P256_SHA256_HKDF_HMAC * @param my_identity_len The prover identity length. * @param peer_identity The peer identity. May be NULL if identities are not established. * @param peer_identity_len The peer identity length. - * @param w0in The input w0 (an output from the PBKDF). - * @param w0in_len The input w0 length. - * @param w1in The input w1 (an output from the PBKDF). - * @param w1in_len The input w1 length. + * @param w0sin The input w0s (an output from the PBKDF). + * @param w0sin_len The input w0s length. + * @param w1sin The input w1s (an output from the PBKDF). + * @param w1sin_len The input w1s length. * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ CHIP_ERROR BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, - size_t peer_identity_len, const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, size_t w1in_len); + size_t peer_identity_len, const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin, + size_t w1sin_len); /** * @brief Compute the first round of the protocol. diff --git a/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.h b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.h new file mode 100644 index 00000000000000..98ee86a800da09 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.h @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +MTR_NEWLY_AVAILABLE +@interface MTRAttributeValueWaiter : NSObject +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; + +/** + * Cancel the wait for the set of attribute path/value pairs represented by this + * MTRAttributeValueWaiter. If the completion has not been called yet, it will + * becalled with MTRErrorCodeCancelled. + */ +- (void)cancel; + +@property (readonly, nonatomic) NSUUID * UUID; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.mm b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.mm new file mode 100644 index 00000000000000..930bbd790cd299 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.mm @@ -0,0 +1,186 @@ +/** + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +#import + +#import "MTRAttributeValueWaiter_Internal.h" +#import "MTRDevice_Internal.h" +#import "MTRError_Internal.h" +#import "MTRLogging_Internal.h" +#import "MTRUnfairLock.h" + +@implementation MTRAwaitedAttributeState +- (instancetype)initWithValue:(MTRDeviceDataValueDictionary)value +{ + if (self = [super init]) { + _valueSatisfied = NO; + _value = value; + } + + return self; +} +@end + +MTR_DIRECT_MEMBERS +@interface MTRAttributeValueWaiter () +@property (nonatomic, retain) NSDictionary * valueExpectations; +// Protected by the MTRDevice's lock. +@property (nonatomic, readwrite, retain) dispatch_queue_t queue; +@property (nonatomic, readwrite, copy, nullable) MTRStatusCompletion completion; +@property (nonatomic, retain, readwrite, nullable) dispatch_source_t expirationTimer; +@property (nonatomic, readonly, retain) MTRDevice * device; +@end + +@implementation MTRAttributeValueWaiter { + // Protects queue/completion and expirationTimer. + os_unfair_lock _lock; +} + +- (instancetype)initWithDevice:(MTRDevice *)device values:(NSDictionary *)values queue:(dispatch_queue_t)queue completion:(MTRStatusCompletion)completion +{ + if (self = [super init]) { + auto * valueExpectations = [NSMutableDictionary dictionaryWithCapacity:values.count]; + for (MTRAttributePath * path in values) { + auto * valueExpectation = [[MTRAwaitedAttributeState alloc] initWithValue:values[path]]; + valueExpectations[path] = valueExpectation; + } + _valueExpectations = valueExpectations; + _queue = queue; + _completion = completion; + _device = device; + _UUID = [NSUUID UUID]; + _lock = OS_UNFAIR_LOCK_INIT; + } + + return self; +} + +- (void)dealloc +{ + [self cancel]; +} + +- (void)cancel +{ + [self.device _forgetAttributeWaiter:self]; + [self _notifyCancellation]; +} + +- (void)_notifyCancellation +{ + [self _notifyWithError:[MTRError errorForCHIPErrorCode:CHIP_ERROR_CANCELLED]]; +} + +- (BOOL)_attributeValue:(MTRDeviceDataValueDictionary)value reportedForPath:(MTRAttributePath *)path byDevice:(MTRDevice *)device +{ + MTRAwaitedAttributeState * valueExpectation = self.valueExpectations[path]; + if (!valueExpectation) { + // We don't care about this one. + return NO; + } + + MTRDeviceDataValueDictionary expectedValue = valueExpectation.value; + valueExpectation.valueSatisfied = [device _attributeDataValue:value satisfiesValueExpectation:expectedValue]; + return valueExpectation.valueSatisfied; +} + +- (BOOL)allValuesSatisfied +{ + for (MTRAwaitedAttributeState * valueExpectation in [self.valueExpectations allValues]) { + if (!valueExpectation.valueSatisfied) { + return NO; + } + } + + return YES; +} + +- (void)_notifyWithError:(NSError * _Nullable)error +{ + MTRStatusCompletion completion; + dispatch_queue_t queue; + { + // Ensure that we only call our completion once. + std::lock_guard lock(_lock); + if (!self.completion) { + return; + } + + completion = self.completion; + queue = self.queue; + self.completion = nil; + self.queue = nil; + + if (self.expirationTimer != nil) { + dispatch_source_cancel(self.expirationTimer); + self.expirationTimer = nil; + } + } + + if (!error) { + MTR_LOG("%@ %p wait for attribute values completed", self, self); + } else if (error.domain == MTRErrorDomain && error.code == MTRErrorCodeTimeout) { + MTR_LOG("%@ %p wait for attribute values timed out", self, self); + } else if (error.domain == MTRErrorDomain && error.code == MTRErrorCodeCancelled) { + MTR_LOG("%@ %p wait for attribute values canceled", self, self); + } else { + MTR_LOG("%@ %p wait for attribute values unknown error: %@", self, self, error); + } + + dispatch_async(queue, ^{ + completion(error); + }); +} + +- (void)_startTimerWithTimeout:(NSTimeInterval)timeout +{ + // Have the timer dispatch on the device queue, so we are not trying to do + // it on the API consumer queue (which might be blocked by the API + // consumer). + dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.device.queue); + + // Set a timer to go off after timeout, and not repeat. + dispatch_source_set_timer(timerSource, dispatch_time(DISPATCH_TIME_NOW, static_cast(timeout * static_cast(NSEC_PER_SEC))), DISPATCH_TIME_FOREVER, + // Allow .5 seconds of leeway; should be plenty, in practice. + static_cast(0.5 * static_cast(NSEC_PER_SEC))); + + mtr_weakify(self); + dispatch_source_set_event_handler(timerSource, ^{ + dispatch_source_cancel(timerSource); + mtr_strongify(self); + if (self != nil) { + [self.device _forgetAttributeWaiter:self]; + [self _notifyWithError:[MTRError errorForCHIPErrorCode:CHIP_ERROR_TIMEOUT]]; + } + }); + + { + std::lock_guard lock(_lock); + self.expirationTimer = timerSource; + } + + dispatch_resume(timerSource); +} + +- (NSString *)description +{ + return [NSString stringWithFormat:@"<%@: %@>", NSStringFromClass(self.class), self.UUID]; +} + +@end diff --git a/src/darwin/Framework/CHIP/MTRAttributeValueWaiter_Internal.h b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter_Internal.h new file mode 100644 index 00000000000000..a23af1d06da1e8 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter_Internal.h @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import // For MTRAttributePath. +#import +#import + +#import "MTRDefines_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +// Represents the state of a single attribute being waited for: has the path and +// value being waited for in the response-value and whether the value has been +// reached. +MTR_DIRECT_MEMBERS +@interface MTRAwaitedAttributeState : NSObject +@property (nonatomic, assign, readwrite) BOOL valueSatisfied; +@property (nonatomic, retain, readonly) MTRDeviceDataValueDictionary value; + +- (instancetype)initWithValue:(MTRDeviceDataValueDictionary)value; +@end + +@interface MTRAttributeValueWaiter () + +@property (nonatomic, readonly) BOOL allValuesSatisfied; + +- (instancetype)initWithDevice:(MTRDevice *)device values:(NSDictionary *)values queue:(dispatch_queue_t)queue completion:(MTRStatusCompletion)completion; + +// Returns YES if after this report the waiter might be done waiting, NO otherwise. +- (BOOL)_attributeValue:(MTRDeviceDataValueDictionary)value reportedForPath:(MTRAttributePath *)path byDevice:(MTRDevice *)device; + +- (void)_notifyWithError:(NSError * _Nullable)error; + +// Starts the timer for our timeout, using the device's queue as the dispatch +// queuue for the timer firing. +- (void)_startTimerWithTimeout:(NSTimeInterval)timeout; + +// Cancels the waiter without trying to remove it from the MTRDevice's +// collection of waiters (unlike "cancel", which does that removal). This is +// exposed so that MTRDevice can do it when invalidating. +- (void)_notifyCancellation; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRCertificates.mm b/src/darwin/Framework/CHIP/MTRCertificates.mm index b153cf4442b373..7dcec96cba695b 100644 --- a/src/darwin/Framework/CHIP/MTRCertificates.mm +++ b/src/darwin/Framework/CHIP/MTRCertificates.mm @@ -152,7 +152,24 @@ + (MTRCertificateDERBytes _Nullable)createOperationalCertificate:(id + (BOOL)keypair:(id)keypair matchesCertificate:(NSData *)certificate { P256PublicKey keypairPubKey; - CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(keypair.publicKey, &keypairPubKey); + SecKeyRef publicKey = NULL; + + if ([keypair respondsToSelector:@selector(copyPublicKey)]) { + publicKey = [keypair copyPublicKey]; + } else { + publicKey = [keypair publicKey]; + if (publicKey) { + CFRetain(publicKey); + } + } + + CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(publicKey, &keypairPubKey); + + if (publicKey != NULL) { + CFRelease(publicKey); + publicKey = NULL; + } + if (err != CHIP_NO_ERROR) { MTR_LOG_ERROR("Can't extract public key from keypair: %s", ErrorStr(err)); return NO; diff --git a/src/darwin/Framework/CHIP/MTRDevice.h b/src/darwin/Framework/CHIP/MTRDevice.h index 2055bf8a877690..247223cbe43fbb 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.h +++ b/src/darwin/Framework/CHIP/MTRDevice.h @@ -16,6 +16,8 @@ */ #import +#import +#import #import #import @@ -121,6 +123,11 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) */ @property (nonatomic, readonly, nullable, copy) NSNumber * productID MTR_NEWLY_AVAILABLE; +/** + * Network commissioning features supported by the device. + */ +@property (nonatomic, readonly) MTRNetworkCommissioningFeature networkCommissioningFeatures MTR_NEWLY_AVAILABLE; + /** * Set the delegate to receive asynchronous callbacks about the device. * @@ -337,6 +344,26 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) queue:(dispatch_queue_t)queue completion:(void (^)(NSURL * _Nullable url, NSError * _Nullable error))completion MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)); + +/** + * Sets up the provided completion to be called when any of the following + * happens: + * + * 1) A set of attributes reaches certain values: completion called with nil. + * 2) The provided timeout expires: completion called with MTRErrorCodeTimeout error. + * 3) The wait is canceled: completion called with MTRErrorCodeCancelled error. + * + * If the MTRAttributeValueWaiter is destroyed before the + * completion is called, that is treated the same as canceling the waiter. + * + * The attributes and values to wait for are represented as a dictionary which + * has the attribute paths as keys and the expected data-values as values. + */ +- (MTRAttributeValueWaiter *)waitForAttributeValues:(NSDictionary *> *)values + timeout:(NSTimeInterval)timeout + queue:(dispatch_queue_t)queue + completion:(void (^)(NSError * _Nullable error))completion MTR_NEWLY_AVAILABLE; + @end MTR_EXTERN NSString * const MTRPreviousDataKey MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)); diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index 2337d0eae625f5..7f273e26f03399 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -18,6 +18,7 @@ #import #import +#import "MTRAttributeValueWaiter_Internal.h" #import "MTRBaseClusters.h" #import "MTRBaseDevice_Internal.h" #import "MTRCluster.h" @@ -25,6 +26,7 @@ #import "MTRConversion.h" #import "MTRDefines_Internal.h" #import "MTRDeviceController_Internal.h" +#import "MTRDeviceDataValidation.h" #import "MTRDevice_Internal.h" #import "MTRError_Internal.h" #import "MTRLogging_Internal.h" @@ -96,6 +98,12 @@ - (BOOL)unitTestSuppressTimeBasedReachabilityChanges:(MTRDevice *)device; @end #endif +MTR_DIRECT_MEMBERS +@interface MTRDevice () +// nil until the first time we need it. Access guarded by our lock. +@property (nonatomic, readwrite, nullable) NSHashTable * attributeValueWaiters; +@end + @implementation MTRDevice - (instancetype)initForSubclassesWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller @@ -124,6 +132,10 @@ - (void)dealloc { // TODO: retain cycle and clean up https://github.com/project-chip/connectedhomeip/issues/34267 MTR_LOG("MTRDevice dealloc: %p", self); + + // Locking because _cancelAllAttributeValueWaiters has os_unfair_lock_assert_owner(&_lock) + std::lock_guard lock(_lock); + [self _cancelAllAttributeValueWaiters]; } + (MTRDevice *)deviceWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller @@ -228,6 +240,7 @@ - (void)invalidate std::lock_guard lock(_lock); [_delegates removeAllObjects]; + [self _cancelAllAttributeValueWaiters]; } - (BOOL)_delegateExists @@ -631,7 +644,19 @@ - (BOOL)_attributeDataValue:(MTRDeviceDataValueDictionary)observed satisfiesValu return NO; } - if (![self _attributeDataValue:observedEntry[MTRDataKey] satisfiesValueExpectation:expectedEntry[MTRDataKey]]) { + MTRDeviceDataValueDictionary observedDataValue = observedEntry[MTRDataKey]; + if (!MTR_SAFE_CAST(observedDataValue, NSDictionary)) { + MTR_LOG_ERROR("%@ observed data-value is not an NSDictionary: %@", self, observedDataValue); + return NO; + } + + MTRDeviceDataValueDictionary expectedDataValue = expectedEntry[MTRDataKey]; + if (!MTR_SAFE_CAST(expectedDataValue, NSDictionary)) { + MTR_LOG_ERROR("%@ expected data-value is not an NSDictionary: %@", self, expectedDataValue); + return NO; + } + + if (![self _attributeDataValue:observedDataValue satisfiesValueExpectation:expectedDataValue]) { return NO; } } @@ -661,7 +686,7 @@ - (BOOL)_attributeDataValue:(MTRDeviceDataValueDictionary)observed satisfiesValu } for (NSDictionary * expectedField in expectedArray) { - if (![expectedField[MTRContextTagKey] isKindOfClass:NSNumber.class] || ![expectedField[MTRDataKey] isKindOfClass:NSDictionary.class]) { + if (!MTR_SAFE_CAST(expectedField, NSDictionary) || !MTR_SAFE_CAST(expectedField[MTRContextTagKey], NSNumber) || !MTR_SAFE_CAST(expectedField[MTRDataKey], NSDictionary)) { MTR_LOG_ERROR("%@ expected structure-value contains invalid field %@", self, expectedField); return NO; } @@ -672,7 +697,7 @@ - (BOOL)_attributeDataValue:(MTRDeviceDataValueDictionary)observed satisfiesValu // pretty small arrays, so the O(N^2) behavior here is ok. BOOL found = NO; for (NSDictionary * observedField in observedArray) { - if (![observedField[MTRContextTagKey] isKindOfClass:NSNumber.class] || ![observedField[MTRDataKey] isKindOfClass:NSDictionary.class]) { + if (!MTR_SAFE_CAST(observedField, NSDictionary) || !MTR_SAFE_CAST(observedField[MTRContextTagKey], NSNumber) || !MTR_SAFE_CAST(observedField[MTRDataKey], NSDictionary)) { MTR_LOG_ERROR("%@ observed structure-value contains invalid field %@", self, observedField); return NO; } @@ -710,6 +735,92 @@ - (BOOL)_attributeDataValue:(MTRDeviceDataValueDictionary)observed satisfiesValu return YES; } +#pragma mark - Handling of waits for attribute values + +- (MTRAttributeValueWaiter *)waitForAttributeValues:(NSDictionary *)values timeout:(NSTimeInterval)timeout queue:(dispatch_queue_t)queue completion:(void (^)(NSError * _Nullable error))completion +{ + // Check whether the values coming in make sense. + for (MTRAttributePath * path in values) { + MTRVerifyArgumentOrDie(MTRDataValueDictionaryIsWellFormed(values[path]), + ([NSString stringWithFormat:@"waitForAttributeValues handed invalid data-value %@ for path %@", path, values[path]])); + } + + // Check whether we have all these values already. + NSMutableArray * requestPaths = [NSMutableArray arrayWithCapacity:values.count]; + for (MTRAttributePath * path in values) { + [requestPaths addObject:[MTRAttributeRequestPath requestPathWithEndpointID:path.endpoint clusterID:path.cluster attributeID:path.attribute]]; + } + + NSArray * currentValues = [self readAttributePaths:requestPaths]; + + auto * attributeWaiter = [[MTRAttributeValueWaiter alloc] initWithDevice:self values:values queue:queue completion:completion]; + + for (MTRDeviceResponseValueDictionary currentValue in currentValues) { + // Pretend as if this got reported, for purposes of the attribute + // waiter. + [attributeWaiter _attributeValue:currentValue[MTRDataKey] reportedForPath:currentValue[MTRAttributePathKey] byDevice:self]; + } + + if (attributeWaiter.allValuesSatisfied) { + MTR_LOG("%@ waitForAttributeValues no need to wait, values already match: %@", self, values); + // We haven't added this waiter to self.attributeValueWaiters yet, so + // no need to remove it before notifying. + [attributeWaiter _notifyWithError:nil]; + return attributeWaiter; + } + + // Otherwise, wait for one of our termination conditions. + { + std::lock_guard lock(_lock); + if (!self.attributeValueWaiters) { + self.attributeValueWaiters = [NSHashTable weakObjectsHashTable]; + } + [self.attributeValueWaiters addObject:attributeWaiter]; + } + + MTR_LOG("%@ waitForAttributeValues will wait up to %f seconds for %@", self, timeout, values); + [attributeWaiter _startTimerWithTimeout:timeout]; + return attributeWaiter; +} + +- (void)_attributeValue:(MTRDeviceDataValueDictionary)value reportedForPath:(MTRAttributePath *)path +{ + os_unfair_lock_assert_owner(&_lock); + + // Check whether anyone was waiting for this attribute. + NSMutableArray * satisfiedWaiters; + for (MTRAttributeValueWaiter * attributeValueWaiter in self.attributeValueWaiters) { + if ([attributeValueWaiter _attributeValue:value reportedForPath:path byDevice:self] && attributeValueWaiter.allValuesSatisfied) { + if (!satisfiedWaiters) { + satisfiedWaiters = [NSMutableArray array]; + } + [satisfiedWaiters addObject:attributeValueWaiter]; + } + } + + for (MTRAttributeValueWaiter * attributeValueWaiter in satisfiedWaiters) { + [self.attributeValueWaiters removeObject:attributeValueWaiter]; + [attributeValueWaiter _notifyWithError:nil]; + } +} + +- (void)_forgetAttributeWaiter:(MTRAttributeValueWaiter *)attributeValueWaiter +{ + std::lock_guard lock(_lock); + [self.attributeValueWaiters removeObject:attributeValueWaiter]; +} + +- (void)_cancelAllAttributeValueWaiters +{ + os_unfair_lock_assert_owner(&_lock); + + auto * attributeValueWaiters = self.attributeValueWaiters; + self.attributeValueWaiters = nil; + for (MTRAttributeValueWaiter * attributeValueWaiter in attributeValueWaiters) { + [attributeValueWaiter _notifyCancellation]; + } +} + @end /* BEGIN DRAGONS: Note methods here cannot be renamed, and are used by private callers, do not rename, remove or modify behavior here */ diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm index 9de51431bfe4f8..e287ef0446593f 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm @@ -819,7 +819,24 @@ - (BOOL)findMatchingFabric:(FabricTable &)fabricTable } else { // No root certificate means the nocSigner is using the root keys, because // consumers must provide a root certificate whenever an ICA is used. - CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(params.nocSigner.publicKey, &pubKey); + SecKeyRef publicKey = NULL; + + if ([params.nocSigner respondsToSelector:@selector(copyPublicKey)]) { + publicKey = [params.nocSigner copyPublicKey]; + } else { + publicKey = [params.nocSigner publicKey]; + if (publicKey) { + CFRetain(publicKey); + } + } + + CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(publicKey, &pubKey); + + if (publicKey != NULL) { + CFRelease(publicKey); + publicKey = NULL; + } + if (err != CHIP_NO_ERROR) { MTR_LOG_ERROR("Can't extract public key from MTRKeypair: %s", ErrorStr(err)); return NO; diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index 53a04b1e206b98..9b9a87bb97a5cc 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -467,7 +467,7 @@ - (oneway void)controller:(NSUUID *)controller controllerConfigurationUpdated:(N NSArray * deviceInfoList = MTR_SAFE_CAST(configuration[MTRDeviceControllerRegistrationNodeIDsKey], NSArray); - MTR_LOG("Received controllerConfigurationUpdated: controllerNode ID %@ deviceInfoList %@", self.controllerNodeID, deviceInfoList); + MTR_LOG("Received controllerConfigurationUpdated: controllerNodeID %@ compressedFabricID %016lluX deviceInfoList %@", self.controllerNodeID, self.compressedFabricID.unsignedLongLongValue, deviceInfoList); for (NSDictionary * deviceInfo in deviceInfoList) { if (!MTR_SAFE_CAST(deviceInfo, NSDictionary)) { diff --git a/src/darwin/Framework/CHIP/MTRDeviceDataValidation.mm b/src/darwin/Framework/CHIP/MTRDeviceDataValidation.mm index 55014b453132a3..cd4ebabf811b9b 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceDataValidation.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceDataValidation.mm @@ -207,7 +207,7 @@ BOOL MTRInvokeResponseIsWellFormed(NSArray * r // Now we know data is a dictionary (in fact a data-value). The only thing // we promise about it is that it has type MTRStructureValueType. - if (data[MTRTypeKey] != MTRStructureValueType) { + if (![MTRStructureValueType isEqual:data[MTRTypeKey]]) { MTR_LOG_ERROR("Invoke response data is not of structure type: %@", data); return NO; } diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index 437b1a0676b97b..35cfbcf7d8ceb1 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -219,7 +219,23 @@ @interface MTRDevice_Concrete () @property (nonatomic, readonly) os_unfair_lock timeSyncLock; @property (nonatomic) NSMutableArray *> * unreportedEvents; + +// The highest event number we have observed, if there was one at all. +@property (nonatomic, readwrite, nullable) NSNumber * highestObservedEventNumber; + +// receivingReport is true if we are receving a subscription report. In +// particular, this will be false if we're just getting an attribute value from +// a read-through. @property (nonatomic) BOOL receivingReport; + +// receivingPrimingReport is true if this subscription report is part of us +// establishing a new subscription to the device. When this is true, it is +// _not_ guaranteed that any particular set of attributes will be reported +// (e.g. everything could be filtered out by our DataVersion filters). +// Conversely, when this is false that tells us nothing about attributes _not_ +// being reported: a device could randomly decide to rev all data versions and +// report all attributes at any point in time, for example due to performing +// subscription resumption. @property (nonatomic) BOOL receivingPrimingReport; // TODO: instead of all the BOOL properties that are some facet of the state, move to internal state machine that has (at least): @@ -390,6 +406,7 @@ - (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceControlle } _clusterDataToPersist = nil; _persistedClusters = [NSMutableSet set]; + _highestObservedEventNumber = nil; // If there is a data store, make sure we have an observer to monitor system clock changes, so // NSDate-based write coalescing could be reset and not get into a bad state. @@ -514,6 +531,12 @@ - (nullable NSNumber *)productID return [_pid copy]; } +- (MTRNetworkCommissioningFeature)networkCommissioningFeatures +{ + std::lock_guard lock(_descriptionLock); + return [_allNetworkFeatures unsignedIntValue]; +} + - (void)_notifyDelegateOfPrivateInternalPropertiesChanges { os_unfair_lock_assert_owner(&self->_lock); @@ -1948,11 +1971,14 @@ - (void)_injectEventReport:(NSArray *)eventRep return; } - // [_deviceController asyncDispatchToMatterQueue:^{ // TODO: This wasn't used previously, not sure why, so keeping it here for thought, but preserving existing behavior + [self _injectPossiblyInvalidEventReport:eventReport]; +} + +- (void)_injectPossiblyInvalidEventReport:(NSArray *)eventReport +{ dispatch_async(self.queue, ^{ [self _handleEventReport:eventReport]; }); - // } errorHandler: nil]; } // END DRAGON: This is used by the XPC Server to inject attribute reports @@ -1960,7 +1986,9 @@ - (void)_injectEventReport:(NSArray *)eventRep #ifdef DEBUG - (void)unitTestInjectEventReport:(NSArray *> *)eventReport { - [self _injectEventReport:eventReport]; + // Don't validate incoming event reports for unit tests, because we want to + // allow incoming event reports without an MTREventIsHistoricalKey. + [self _injectPossiblyInvalidEventReport:eventReport]; } - (void)unitTestInjectAttributeReport:(NSArray *> *)attributeReport fromSubscription:(BOOL)isFromSubscription @@ -2096,11 +2124,33 @@ - (void)_handleEventReport:(NSArray *> *)eventRepor } } - NSMutableDictionary * eventToReturn = eventDict.mutableCopy; - if (_receivingPrimingReport) { - eventToReturn[MTREventIsHistoricalKey] = @(YES); + auto * eventNumber = MTR_SAFE_CAST(eventDict[MTREventNumberKey], NSNumber); + if (!eventNumber) { + MTR_LOG_ERROR("%@ Event %@ missing event number", self, eventDict); + continue; + } + + if (!self.highestObservedEventNumber || + [self.highestObservedEventNumber compare:eventNumber] == NSOrderedAscending) { + // This is an event we have not seen before. + self.highestObservedEventNumber = eventNumber; } else { - eventToReturn[MTREventIsHistoricalKey] = @(NO); + // We have seen this event already; just filter it out. But also, we must be getting + // some sort of priming report if we are getting events we have seen before. + if (_receivingReport) { + _receivingPrimingReport = YES; + } + continue; + } + + NSMutableDictionary * eventToReturn = eventDict.mutableCopy; + // If MTREventIsHistoricalKey is already present, do not mess with the value. + if (eventToReturn[MTREventIsHistoricalKey] == nil) { + if (_receivingPrimingReport) { + eventToReturn[MTREventIsHistoricalKey] = @(YES); + } else { + eventToReturn[MTREventIsHistoricalKey] = @(NO); + } } [reportToReturn addObject:eventToReturn]; @@ -2552,8 +2602,15 @@ - (void)_setupSubscriptionWithReason:(NSString *)reason // Set up a cluster state cache. We just want this for the logic it has for // tracking data versions and event numbers so we minimize the amount of data we // request on resubscribes, so tell it not to store data. + Optional highestObservedEventNumber; + { + std::lock_guard lock(self->_lock); + if (self.highestObservedEventNumber) { + highestObservedEventNumber = MakeOptional(self.highestObservedEventNumber.unsignedLongLongValue); + } + } auto clusterStateCache = std::make_unique(*callback.get(), - /* highestReceivedEventNumber = */ NullOptional, + highestObservedEventNumber, /* cacheData = */ false); auto readClient = std::make_unique(InteractionModelEngine::GetInstance(), exchangeManager, clusterStateCache->GetBufferedCallback(), ReadClient::InteractionType::Subscribe); @@ -2603,6 +2660,10 @@ - (void)_setupSubscriptionWithReason:(NSString *)reason attributePath.release(); eventPath.release(); + // NOTE: We don't set the event number field in readParams, and just let + // the ReadClient get the min event number information from the cluster + // state cache. + // TODO: Change from local filter list generation to rehydrating ClusterStateCache to take advantage of existing filter list sorting algorithm // SendAutoResubscribeRequest cleans up the params, even on failure. @@ -3581,11 +3642,6 @@ - (NSArray *)_getAttributesToReportWithReportedValues:(NSArray delegate) { [delegate device:self receivedAttributeReport:attributeReport]; }]; + + std::lock_guard lock(_lock); + for (NSDictionary * report in attributeReport) { + if (!MTR_SAFE_CAST(report, NSDictionary)) { + MTR_LOG_ERROR("%@ handed a response-value that is not a dictionary: %@", self, report); + continue; + } + + MTRAttributePath * path = MTR_SAFE_CAST(report[MTRAttributePathKey], MTRAttributePath); + if (!path) { + MTR_LOG_ERROR("%@ no valid path for attribute report %@", self, report); + continue; + } + + MTRDeviceDataValueDictionary value = report[MTRDataKey]; + if (!value) { + // This is normal; this could be an error report. + continue; + } + + if (!MTR_SAFE_CAST(value, NSDictionary)) { + MTR_LOG_ERROR("%@ invalid data-value reported: %@", self, report); + continue; + } + + [self _attributeValue:value reportedForPath:path]; + } } - (oneway void)device:(NSNumber *)nodeID receivedEventReport:(NSArray *)eventReport diff --git a/src/darwin/Framework/CHIP/MTRKeypair.h b/src/darwin/Framework/CHIP/MTRKeypair.h index a4e4521b2864a6..bf664e13aa6385 100644 --- a/src/darwin/Framework/CHIP/MTRKeypair.h +++ b/src/darwin/Framework/CHIP/MTRKeypair.h @@ -16,6 +16,7 @@ */ #import +#import #import NS_ASSUME_NONNULL_BEGIN @@ -31,13 +32,18 @@ NS_ASSUME_NONNULL_BEGIN * framework APIs. */ @protocol MTRKeypair -@required + +@optional /** - * @brief Return public key for the keypair. + * @brief Returns a copy of the public key for the keypair. */ -- (SecKeyRef)publicKey; +- (SecKeyRef)copyPublicKey MTR_NEWLY_AVAILABLE; + +/** + * @brief Returns public key for the keypair without adding a reference. DEPRECATED - please use copyPublicKey, otherwise this will leak. + */ +- (SecKeyRef)publicKey MTR_NEWLY_DEPRECATED("Please implement copyPublicKey, this will leak otherwise"); -@optional /** * @brief A function to sign a message using ECDSA * diff --git a/src/darwin/Framework/CHIP/MTRP256KeypairBridge.mm b/src/darwin/Framework/CHIP/MTRP256KeypairBridge.mm index d253baa8dbf95c..03a396e27dffe5 100644 --- a/src/darwin/Framework/CHIP/MTRP256KeypairBridge.mm +++ b/src/darwin/Framework/CHIP/MTRP256KeypairBridge.mm @@ -132,7 +132,17 @@ return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } -CHIP_ERROR MTRP256KeypairBridge::setPubkey() { return MatterPubKeyFromSecKeyRef([mKeypair publicKey], &mPubkey); } +CHIP_ERROR MTRP256KeypairBridge::setPubkey() +{ + if ([mKeypair respondsToSelector:@selector(copyPublicKey)]) { + SecKeyRef publicKey = [mKeypair copyPublicKey]; + auto copyResult = MatterPubKeyFromSecKeyRef(publicKey, &mPubkey); + CFRelease(publicKey); + return copyResult; + } else { + return MatterPubKeyFromSecKeyRef([mKeypair publicKey], &mPubkey); + } +} CHIP_ERROR MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(SecKeyRef pubkeyRef, P256PublicKey * matterPubKey) { diff --git a/src/darwin/Framework/CHIP/Matter.h b/src/darwin/Framework/CHIP/Matter.h index 9f57e4fb4e4285..85a87c4ba12c0c 100644 --- a/src/darwin/Framework/CHIP/Matter.h +++ b/src/darwin/Framework/CHIP/Matter.h @@ -21,6 +21,7 @@ #import #import +#import #import #import #import diff --git a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm index 35f602e0de2aeb..67d546b4636e98 100644 --- a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm +++ b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm @@ -26,6 +26,7 @@ #include #include +#include #include #include #include @@ -42,18 +43,12 @@ namespace { -class DeviceTypeResolver : public Access::AccessControl::DeviceTypeResolver { +class DeviceTypeResolver : public chip::Access::DynamicProviderDeviceTypeResolver { public: - bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) override + DeviceTypeResolver() + : chip::Access::DynamicProviderDeviceTypeResolver( + [] { return chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); }) { - app::DataModel::Provider * model = app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); - - for (auto type = model->FirstDeviceType(endpoint); type.has_value(); type = model->NextDeviceType(endpoint, *type)) { - if (type->deviceTypeId == deviceType) { - return true; - } - } - return false; } }; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeSpecifiedCheck.mm b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeSpecifiedCheck.mm index 43e0528c252c14..ce5c71d23f1d69 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeSpecifiedCheck.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeSpecifiedCheck.mm @@ -5565,7 +5565,7 @@ static BOOL AttributeIsSpecifiedInZoneManagementCluster(AttributeId aAttributeId case Attributes::Zones::Id: { return YES; } - case Attributes::TimeControl::Id: { + case Attributes::Triggers::Id: { return YES; } case Attributes::Sensitivity::Id: { @@ -5637,12 +5637,6 @@ static BOOL AttributeIsSpecifiedInCameraAVStreamManagementCluster(AttributeId aA case Attributes::HDRModeEnabled::Id: { return YES; } - case Attributes::CurrentVideoCodecs::Id: { - return YES; - } - case Attributes::CurrentSnapshotConfig::Id: { - return YES; - } case Attributes::FabricsUsingCamera::Id: { return YES; } @@ -5673,15 +5667,6 @@ static BOOL AttributeIsSpecifiedInCameraAVStreamManagementCluster(AttributeId aA case Attributes::NightVisionIllum::Id: { return YES; } - case Attributes::AWBEnabled::Id: { - return YES; - } - case Attributes::AutoShutterSpeedEnabled::Id: { - return YES; - } - case Attributes::AutoISOEnabled::Id: { - return YES; - } case Attributes::Viewport::Id: { return YES; } @@ -5733,9 +5718,6 @@ static BOOL AttributeIsSpecifiedInCameraAVStreamManagementCluster(AttributeId aA case Attributes::StatusLightBrightness::Id: { return YES; } - case Attributes::DepthSensorStatus::Id: { - return YES; - } case Attributes::GeneratedCommandList::Id: { return YES; } diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm index 16f882fe473a43..975c3b63f4a587 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm @@ -16853,8 +16853,8 @@ static id _Nullable DecodeAttributeValueForZoneManagementCluster(AttributeId aAt } return value; } - case Attributes::TimeControl::Id: { - using TypeInfo = Attributes::TimeControl::TypeInfo; + case Attributes::Triggers::Id: { + using TypeInfo = Attributes::Triggers::TypeInfo; TypeInfo::DecodableType cppValue; *aError = DataModel::Decode(aReader, cppValue); if (*aError != CHIP_NO_ERROR) { @@ -16866,12 +16866,17 @@ static id _Nullable DecodeAttributeValueForZoneManagementCluster(AttributeId aAt auto iter_0 = cppValue.begin(); while (iter_0.Next()) { auto & entry_0 = iter_0.GetValue(); - MTRZoneManagementClusterZoneTriggeringTimeControlStruct * newElement_0; - newElement_0 = [MTRZoneManagementClusterZoneTriggeringTimeControlStruct new]; + MTRZoneManagementClusterZoneTriggerControlStruct * newElement_0; + newElement_0 = [MTRZoneManagementClusterZoneTriggerControlStruct new]; newElement_0.initialDuration = [NSNumber numberWithUnsignedShort:entry_0.initialDuration]; newElement_0.augmentationDuration = [NSNumber numberWithUnsignedShort:entry_0.augmentationDuration]; newElement_0.maxDuration = [NSNumber numberWithUnsignedInt:entry_0.maxDuration]; newElement_0.blindDuration = [NSNumber numberWithUnsignedShort:entry_0.blindDuration]; + if (entry_0.sensitivity.HasValue()) { + newElement_0.sensitivity = [NSNumber numberWithUnsignedChar:entry_0.sensitivity.Value()]; + } else { + newElement_0.sensitivity = nil; + } [array_0 addObject:newElement_0]; } CHIP_ERROR err = iter_0.GetStatus(); @@ -17205,48 +17210,6 @@ static id _Nullable DecodeAttributeValueForCameraAVStreamManagementCluster(Attri value = [NSNumber numberWithBool:cppValue]; return value; } - case Attributes::CurrentVideoCodecs::Id: { - using TypeInfo = Attributes::CurrentVideoCodecs::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) { - return nil; - } - NSArray * _Nonnull value; - { // Scope for our temporary variables - auto * array_0 = [NSMutableArray new]; - auto iter_0 = cppValue.begin(); - while (iter_0.Next()) { - auto & entry_0 = iter_0.GetValue(); - NSNumber * newElement_0; - newElement_0 = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0)]; - [array_0 addObject:newElement_0]; - } - CHIP_ERROR err = iter_0.GetStatus(); - if (err != CHIP_NO_ERROR) { - *aError = err; - return nil; - } - value = array_0; - } - return value; - } - case Attributes::CurrentSnapshotConfig::Id: { - using TypeInfo = Attributes::CurrentSnapshotConfig::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) { - return nil; - } - MTRCameraAVStreamManagementClusterSnapshotParamsStruct * _Nonnull value; - value = [MTRCameraAVStreamManagementClusterSnapshotParamsStruct new]; - value.resolution = [MTRCameraAVStreamManagementClusterVideoResolutionStruct new]; - value.resolution.width = [NSNumber numberWithUnsignedShort:cppValue.resolution.width]; - value.resolution.height = [NSNumber numberWithUnsignedShort:cppValue.resolution.height]; - value.maxFrameRate = [NSNumber numberWithUnsignedShort:cppValue.maxFrameRate]; - value.imageCodec = [NSNumber numberWithUnsignedChar:chip::to_underlying(cppValue.imageCodec)]; - return value; - } case Attributes::FabricsUsingCamera::Id: { using TypeInfo = Attributes::FabricsUsingCamera::TypeInfo; TypeInfo::DecodableType cppValue; @@ -17478,39 +17441,6 @@ static id _Nullable DecodeAttributeValueForCameraAVStreamManagementCluster(Attri value = [NSNumber numberWithUnsignedChar:chip::to_underlying(cppValue)]; return value; } - case Attributes::AWBEnabled::Id: { - using TypeInfo = Attributes::AWBEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) { - return nil; - } - NSNumber * _Nonnull value; - value = [NSNumber numberWithBool:cppValue]; - return value; - } - case Attributes::AutoShutterSpeedEnabled::Id: { - using TypeInfo = Attributes::AutoShutterSpeedEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) { - return nil; - } - NSNumber * _Nonnull value; - value = [NSNumber numberWithBool:cppValue]; - return value; - } - case Attributes::AutoISOEnabled::Id: { - using TypeInfo = Attributes::AutoISOEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) { - return nil; - } - NSNumber * _Nonnull value; - value = [NSNumber numberWithBool:cppValue]; - return value; - } case Attributes::Viewport::Id: { using TypeInfo = Attributes::Viewport::TypeInfo; TypeInfo::DecodableType cppValue; @@ -17702,17 +17632,6 @@ static id _Nullable DecodeAttributeValueForCameraAVStreamManagementCluster(Attri value = [NSNumber numberWithUnsignedChar:chip::to_underlying(cppValue)]; return value; } - case Attributes::DepthSensorStatus::Id: { - using TypeInfo = Attributes::DepthSensorStatus::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) { - return nil; - } - NSNumber * _Nonnull value; - value = [NSNumber numberWithUnsignedChar:chip::to_underlying(cppValue)]; - return value; - } default: { break; } diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h index 73008bfde7f718..32c79ee20f13cf 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h @@ -14074,13 +14074,13 @@ MTR_PROVISIONALLY_AVAILABLE reportHandler:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeZonesWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)readAttributeTimeControlWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeTimeControlWithValue:(NSArray * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeTimeControlWithValue:(NSArray * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeTimeControlWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeTimeControlWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; +- (void)readAttributeTriggersWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeTriggersWithValue:(NSArray * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeTriggersWithValue:(NSArray * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; +- (void)subscribeAttributeTriggersWithParams:(MTRSubscribeParams *)params + subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished + reportHandler:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; ++ (void)readAttributeTriggersWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeSensitivityWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeSensitivityWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; @@ -14199,30 +14199,6 @@ MTR_PROVISIONALLY_AVAILABLE * This command SHALL return a Snapshot from the camera. */ - (void)captureSnapshotWithParams:(MTRCameraAVStreamManagementClusterCaptureSnapshotParams *)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -/** - * Command SetViewport - * - * This command sets the viewport in all video streams. - */ -- (void)setViewportWithParams:(MTRCameraAVStreamManagementClusterSetViewportParams *)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -/** - * Command SetImageRotation - * - * The data fields for this command SHALL be as follows: - */ -- (void)setImageRotationWithParams:(MTRCameraAVStreamManagementClusterSetImageRotationParams *)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -/** - * Command SetImageFlipHorizontal - * - * The data fields for this command SHALL be as follows: - */ -- (void)setImageFlipHorizontalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams *)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -/** - * Command SetImageFlipVertical - * - * The data fields for this command SHALL be as follows: - */ -- (void)setImageFlipVerticalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams *)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeMaxConcurrentVideoEncodersWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeMaxConcurrentVideoEncodersWithParams:(MTRSubscribeParams *)params @@ -14310,18 +14286,6 @@ MTR_PROVISIONALLY_AVAILABLE reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeHDRModeEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)readAttributeCurrentVideoCodecsWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeCurrentVideoCodecsWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeCurrentVideoCodecsWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - -- (void)readAttributeCurrentSnapshotConfigWithCompletion:(void (^)(MTRCameraAVStreamManagementClusterSnapshotParamsStruct * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeCurrentSnapshotConfigWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(MTRCameraAVStreamManagementClusterSnapshotParamsStruct * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeCurrentSnapshotConfigWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(MTRCameraAVStreamManagementClusterSnapshotParamsStruct * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - - (void)readAttributeFabricsUsingCameraWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeFabricsUsingCameraWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished @@ -14347,8 +14311,6 @@ MTR_PROVISIONALLY_AVAILABLE + (void)readAttributeAllocatedSnapshotStreamsWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeRankedVideoStreamPrioritiesListWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeRankedVideoStreamPrioritiesListWithValue:(NSArray * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeRankedVideoStreamPrioritiesListWithValue:(NSArray * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeRankedVideoStreamPrioritiesListWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; @@ -14392,31 +14354,9 @@ MTR_PROVISIONALLY_AVAILABLE reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeNightVisionIllumWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)readAttributeAWBEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeAWBEnabledWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeAWBEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - -- (void)readAttributeAutoShutterSpeedEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeAutoShutterSpeedEnabledWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeAutoShutterSpeedEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - -- (void)readAttributeAutoISOEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeAutoISOEnabledWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeAutoISOEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - - (void)readAttributeViewportWithCompletion:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeViewportWithValue:(MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeViewportWithValue:(MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeViewportWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; @@ -14439,16 +14379,12 @@ MTR_PROVISIONALLY_AVAILABLE + (void)readAttributeSpeakerVolumeLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeSpeakerMaxLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeSpeakerMaxLevelWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeSpeakerMaxLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeSpeakerMinLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMinLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMinLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeSpeakerMinLevelWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; @@ -14471,16 +14407,12 @@ MTR_PROVISIONALLY_AVAILABLE + (void)readAttributeMicrophoneVolumeLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeMicrophoneMaxLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeMicrophoneMaxLevelWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeMicrophoneMaxLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeMicrophoneMinLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeMicrophoneMinLevelWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; @@ -14495,18 +14427,24 @@ MTR_PROVISIONALLY_AVAILABLE + (void)readAttributeMicrophoneAGCEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeImageRotationWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageRotationWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageRotationWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeImageRotationWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeImageRotationWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeImageFlipHorizontalWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipHorizontalWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipHorizontalWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeImageFlipHorizontalWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeImageFlipHorizontalWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeImageFlipVerticalWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipVerticalWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipVerticalWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeImageFlipVerticalWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; @@ -14544,14 +14482,6 @@ MTR_PROVISIONALLY_AVAILABLE reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeStatusLightBrightnessWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)readAttributeDepthSensorStatusWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeDepthSensorStatusWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeDepthSensorStatusWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeDepthSensorStatusWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeDepthSensorStatusWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - - (void)readAttributeGeneratedCommandListWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeGeneratedCommandListWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished @@ -20150,6 +20080,7 @@ typedef NS_ENUM(uint8_t, MTRZoneManagementZoneUse) { typedef NS_OPTIONS(uint32_t, MTRZoneManagementFeature) { MTRZoneManagementFeatureTwoDimensionalCartesianZone MTR_PROVISIONALLY_AVAILABLE = 0x1, + MTRZoneManagementFeaturePerZoneSensitivity MTR_PROVISIONALLY_AVAILABLE = 0x2, } MTR_PROVISIONALLY_AVAILABLE; typedef NS_ENUM(uint8_t, MTRCameraAVStreamManagementAudioCodec) { @@ -20188,12 +20119,12 @@ typedef NS_ENUM(uint8_t, MTRCameraAVStreamManagementVideoCodec) { } MTR_PROVISIONALLY_AVAILABLE; typedef NS_OPTIONS(uint32_t, MTRCameraAVStreamManagementFeature) { - MTRCameraAVStreamManagementFeaturePrivacy MTR_PROVISIONALLY_AVAILABLE = 0x1, - MTRCameraAVStreamManagementFeatureAudio MTR_PROVISIONALLY_AVAILABLE = 0x2, - MTRCameraAVStreamManagementFeatureSpeaker MTR_PROVISIONALLY_AVAILABLE = 0x4, - MTRCameraAVStreamManagementFeatureImageControl MTR_PROVISIONALLY_AVAILABLE = 0x8, - MTRCameraAVStreamManagementFeatureVideo MTR_PROVISIONALLY_AVAILABLE = 0x10, - MTRCameraAVStreamManagementFeatureSnapshot MTR_PROVISIONALLY_AVAILABLE = 0x20, + MTRCameraAVStreamManagementFeatureAudio MTR_PROVISIONALLY_AVAILABLE = 0x1, + MTRCameraAVStreamManagementFeatureVideo MTR_PROVISIONALLY_AVAILABLE = 0x2, + MTRCameraAVStreamManagementFeatureSnapshot MTR_PROVISIONALLY_AVAILABLE = 0x4, + MTRCameraAVStreamManagementFeaturePrivacy MTR_PROVISIONALLY_AVAILABLE = 0x8, + MTRCameraAVStreamManagementFeatureSpeaker MTR_PROVISIONALLY_AVAILABLE = 0x10, + MTRCameraAVStreamManagementFeatureImageControl MTR_PROVISIONALLY_AVAILABLE = 0x20, MTRCameraAVStreamManagementFeatureWatermark MTR_PROVISIONALLY_AVAILABLE = 0x40, MTRCameraAVStreamManagementFeatureOnScreenDisplay MTR_PROVISIONALLY_AVAILABLE = 0x80, MTRCameraAVStreamManagementFeatureLocalStorage MTR_PROVISIONALLY_AVAILABLE = 0x100, diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm index 3c347c4472e132..ea02951aa50907 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm @@ -97778,9 +97778,9 @@ + (void)readAttributeZonesWithClusterStateCache:(MTRClusterStateCacheContainer * completion:completion]; } -- (void)readAttributeTimeControlWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion +- (void)readAttributeTriggersWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = ZoneManagement::Attributes::TimeControl::TypeInfo; + using TypeInfo = ZoneManagement::Attributes::Triggers::TypeInfo; [self.device _readKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -97789,11 +97789,11 @@ - (void)readAttributeTimeControlWithCompletion:(void (^)(NSArray * _Nullable val completion:completion]; } -- (void)writeAttributeTimeControlWithValue:(NSArray * _Nonnull)value completion:(MTRStatusCompletion)completion +- (void)writeAttributeTriggersWithValue:(NSArray * _Nonnull)value completion:(MTRStatusCompletion)completion { - [self writeAttributeTimeControlWithValue:(NSArray * _Nonnull) value params:nil completion:completion]; + [self writeAttributeTriggersWithValue:(NSArray * _Nonnull) value params:nil completion:completion]; } -- (void)writeAttributeTimeControlWithValue:(NSArray * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +- (void)writeAttributeTriggersWithValue:(NSArray * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion { // Make a copy of params before we go async. params = [params copy]; @@ -97808,7 +97808,7 @@ - (void)writeAttributeTimeControlWithValue:(NSArray * _Nonnull)value params:(MTR } ListFreer listFreer; - using TypeInfo = ZoneManagement::Attributes::TimeControl::TypeInfo; + using TypeInfo = ZoneManagement::Attributes::Triggers::TypeInfo; TypeInfo::Type cppValue; { using ListType_0 = std::remove_reference_t; @@ -97820,15 +97820,19 @@ - (void)writeAttributeTimeControlWithValue:(NSArray * _Nonnull)value params:(MTR } listFreer.add(listHolder_0); for (size_t i_0 = 0; i_0 < value.count; ++i_0) { - if ( ! [value[i_0] isKindOfClass: [MTRZoneManagementClusterZoneTriggeringTimeControlStruct class]] ) { + if ( ! [value[i_0] isKindOfClass: [MTRZoneManagementClusterZoneTriggerControlStruct class]] ) { // Wrong kind of value. return CHIP_ERROR_INVALID_ARGUMENT; } - auto element_0 = (MTRZoneManagementClusterZoneTriggeringTimeControlStruct *)value[i_0]; + auto element_0 = (MTRZoneManagementClusterZoneTriggerControlStruct *)value[i_0]; listHolder_0->mList[i_0].initialDuration = element_0.initialDuration.unsignedShortValue; listHolder_0->mList[i_0].augmentationDuration = element_0.augmentationDuration.unsignedShortValue; listHolder_0->mList[i_0].maxDuration = element_0.maxDuration.unsignedIntValue; listHolder_0->mList[i_0].blindDuration = element_0.blindDuration.unsignedShortValue; + if (element_0.sensitivity != nil) { + auto & definedValue_2 = listHolder_0->mList[i_0].sensitivity.Emplace(); + definedValue_2 = element_0.sensitivity.unsignedCharValue; + } } cppValue = ListType_0(listHolder_0->mList, value.count); } else { @@ -97841,11 +97845,11 @@ - (void)writeAttributeTimeControlWithValue:(NSArray * _Nonnull)value params:(MTR std::move(*bridge).DispatchAction(self.device); } -- (void)subscribeAttributeTimeControlWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))reportHandler +- (void)subscribeAttributeTriggersWithParams:(MTRSubscribeParams * _Nonnull)params + subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished + reportHandler:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))reportHandler { - using TypeInfo = ZoneManagement::Attributes::TimeControl::TypeInfo; + using TypeInfo = ZoneManagement::Attributes::Triggers::TypeInfo; [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -97855,9 +97859,9 @@ - (void)subscribeAttributeTimeControlWithParams:(MTRSubscribeParams * _Nonnull)p subscriptionEstablished:subscriptionEstablished]; } -+ (void)readAttributeTimeControlWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion ++ (void)readAttributeTriggersWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = ZoneManagement::Attributes::TimeControl::TypeInfo; + using TypeInfo = ZoneManagement::Attributes::Triggers::TypeInfo; [clusterStateCacheContainer _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) clusterID:TypeInfo::GetClusterId() @@ -98330,102 +98334,6 @@ - (void)captureSnapshotWithParams:(MTRCameraAVStreamManagementClusterCaptureSnap queue:self.callbackQueue completion:responseHandler]; } -- (void)setViewportWithParams:(MTRCameraAVStreamManagementClusterSetViewportParams *)params completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetViewportParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetViewport::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} -- (void)setImageRotationWithParams:(MTRCameraAVStreamManagementClusterSetImageRotationParams *)params completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageRotationParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageRotation::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} -- (void)setImageFlipHorizontalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams *)params completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} -- (void)setImageFlipVerticalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams *)params completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageFlipVertical::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} - (void)readAttributeMaxConcurrentVideoEncodersWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion { @@ -98959,78 +98867,6 @@ + (void)readAttributeHDRModeEnabledWithClusterStateCache:(MTRClusterStateCacheCo completion:completion]; } -- (void)readAttributeCurrentVideoCodecsWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::CurrentVideoCodecs::TypeInfo; - [self.device _readKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:nil - queue:self.callbackQueue - completion:completion]; -} - -- (void)subscribeAttributeCurrentVideoCodecsWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))reportHandler -{ - using TypeInfo = CameraAvStreamManagement::Attributes::CurrentVideoCodecs::TypeInfo; - [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:params - queue:self.callbackQueue - reportHandler:reportHandler - subscriptionEstablished:subscriptionEstablished]; -} - -+ (void)readAttributeCurrentVideoCodecsWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::CurrentVideoCodecs::TypeInfo; - [clusterStateCacheContainer - _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) - clusterID:TypeInfo::GetClusterId() - attributeID:TypeInfo::GetAttributeId() - queue:queue - completion:completion]; -} - -- (void)readAttributeCurrentSnapshotConfigWithCompletion:(void (^)(MTRCameraAVStreamManagementClusterSnapshotParamsStruct * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::CurrentSnapshotConfig::TypeInfo; - [self.device _readKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:nil - queue:self.callbackQueue - completion:completion]; -} - -- (void)subscribeAttributeCurrentSnapshotConfigWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(MTRCameraAVStreamManagementClusterSnapshotParamsStruct * _Nullable value, NSError * _Nullable error))reportHandler -{ - using TypeInfo = CameraAvStreamManagement::Attributes::CurrentSnapshotConfig::TypeInfo; - [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:params - queue:self.callbackQueue - reportHandler:reportHandler - subscriptionEstablished:subscriptionEstablished]; -} - -+ (void)readAttributeCurrentSnapshotConfigWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(MTRCameraAVStreamManagementClusterSnapshotParamsStruct * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::CurrentSnapshotConfig::TypeInfo; - [clusterStateCacheContainer - _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) - clusterID:TypeInfo::GetClusterId() - attributeID:TypeInfo::GetAttributeId() - queue:queue - completion:completion]; -} - - (void)readAttributeFabricsUsingCameraWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion { using TypeInfo = CameraAvStreamManagement::Attributes::FabricsUsingCamera::TypeInfo; @@ -99186,55 +99022,6 @@ - (void)readAttributeRankedVideoStreamPrioritiesListWithCompletion:(void (^)(NSA completion:completion]; } -- (void)writeAttributeRankedVideoStreamPrioritiesListWithValue:(NSArray * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeRankedVideoStreamPrioritiesListWithValue:(NSArray * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeRankedVideoStreamPrioritiesListWithValue:(NSArray * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::RankedVideoStreamPrioritiesList::TypeInfo; - TypeInfo::Type cppValue; - { - using ListType_0 = std::remove_reference_t; - using ListMemberType_0 = ListMemberTypeGetter::Type; - if (value.count != 0) { - auto * listHolder_0 = new ListHolder(value.count); - if (listHolder_0 == nullptr || listHolder_0->mList == nullptr) { - return CHIP_ERROR_INVALID_ARGUMENT; - } - listFreer.add(listHolder_0); - for (size_t i_0 = 0; i_0 < value.count; ++i_0) { - if ( ! [value[i_0] isKindOfClass: [NSNumber class]] ) { - // Wrong kind of value. - return CHIP_ERROR_INVALID_ARGUMENT; - } - auto element_0 = (NSNumber *)value[i_0]; - listHolder_0->mList[i_0] = static_castmList[i_0])>>(element_0.unsignedCharValue); - } - cppValue = ListType_0(listHolder_0->mList, value.count); - } else { - cppValue = ListType_0(); - } - } - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - - (void)subscribeAttributeRankedVideoStreamPrioritiesListWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))reportHandler @@ -99552,9 +99339,9 @@ + (void)readAttributeNightVisionIllumWithClusterStateCache:(MTRClusterStateCache completion:completion]; } -- (void)readAttributeAWBEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion +- (void)readAttributeViewportWithCompletion:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = CameraAvStreamManagement::Attributes::AWBEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::Viewport::TypeInfo; [self.device _readKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -99563,11 +99350,11 @@ - (void)readAttributeAWBEnabledWithCompletion:(void (^)(NSNumber * _Nullable val completion:completion]; } -- (void)writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion +- (void)writeAttributeViewportWithValue:(MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull)value completion:(MTRStatusCompletion)completion { - [self writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; + [self writeAttributeViewportWithValue:(MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull) value params:nil completion:completion]; } -- (void)writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +- (void)writeAttributeViewportWithValue:(MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion { // Make a copy of params before we go async. params = [params copy]; @@ -99582,20 +99369,23 @@ - (void)writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull)value params:(MTR } ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::AWBEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::Viewport::TypeInfo; TypeInfo::Type cppValue; - cppValue = value.boolValue; + cppValue.x1 = value.x1.unsignedShortValue; + cppValue.y1 = value.y1.unsignedShortValue; + cppValue.x2 = value.x2.unsignedShortValue; + cppValue.y2 = value.y2.unsignedShortValue; chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); std::move(*bridge).DispatchAction(self.device); } -- (void)subscribeAttributeAWBEnabledWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler +- (void)subscribeAttributeViewportWithParams:(MTRSubscribeParams * _Nonnull)params + subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished + reportHandler:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))reportHandler { - using TypeInfo = CameraAvStreamManagement::Attributes::AWBEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::Viewport::TypeInfo; [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -99605,9 +99395,9 @@ - (void)subscribeAttributeAWBEnabledWithParams:(MTRSubscribeParams * _Nonnull)pa subscriptionEstablished:subscriptionEstablished]; } -+ (void)readAttributeAWBEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion ++ (void)readAttributeViewportWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = CameraAvStreamManagement::Attributes::AWBEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::Viewport::TypeInfo; [clusterStateCacheContainer _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) clusterID:TypeInfo::GetClusterId() @@ -99616,9 +99406,9 @@ + (void)readAttributeAWBEnabledWithClusterStateCache:(MTRClusterStateCacheContai completion:completion]; } -- (void)readAttributeAutoShutterSpeedEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion +- (void)readAttributeSpeakerMutedWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMuted::TypeInfo; [self.device _readKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -99627,11 +99417,11 @@ - (void)readAttributeAutoShutterSpeedEnabledWithCompletion:(void (^)(NSNumber * completion:completion]; } -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion +- (void)writeAttributeSpeakerMutedWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion { - [self writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; + [self writeAttributeSpeakerMutedWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; } -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +- (void)writeAttributeSpeakerMutedWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion { // Make a copy of params before we go async. params = [params copy]; @@ -99646,7 +99436,7 @@ - (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull)valu } ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMuted::TypeInfo; TypeInfo::Type cppValue; cppValue = value.boolValue; @@ -99655,11 +99445,11 @@ - (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull)valu std::move(*bridge).DispatchAction(self.device); } -- (void)subscribeAttributeAutoShutterSpeedEnabledWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler +- (void)subscribeAttributeSpeakerMutedWithParams:(MTRSubscribeParams * _Nonnull)params + subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished + reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler { - using TypeInfo = CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMuted::TypeInfo; [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -99669,9 +99459,9 @@ - (void)subscribeAttributeAutoShutterSpeedEnabledWithParams:(MTRSubscribeParams subscriptionEstablished:subscriptionEstablished]; } -+ (void)readAttributeAutoShutterSpeedEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion ++ (void)readAttributeSpeakerMutedWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMuted::TypeInfo; [clusterStateCacheContainer _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) clusterID:TypeInfo::GetClusterId() @@ -99680,9 +99470,9 @@ + (void)readAttributeAutoShutterSpeedEnabledWithClusterStateCache:(MTRClusterSta completion:completion]; } -- (void)readAttributeAutoISOEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion +- (void)readAttributeSpeakerVolumeLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = CameraAvStreamManagement::Attributes::AutoISOEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::TypeInfo; [self.device _readKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -99691,11 +99481,11 @@ - (void)readAttributeAutoISOEnabledWithCompletion:(void (^)(NSNumber * _Nullable completion:completion]; } -- (void)writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion +- (void)writeAttributeSpeakerVolumeLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion { - [self writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; + [self writeAttributeSpeakerVolumeLevelWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; } -- (void)writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +- (void)writeAttributeSpeakerVolumeLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion { // Make a copy of params before we go async. params = [params copy]; @@ -99710,20 +99500,20 @@ - (void)writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull)value params: } ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::AutoISOEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::TypeInfo; TypeInfo::Type cppValue; - cppValue = value.boolValue; + cppValue = value.unsignedCharValue; chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); std::move(*bridge).DispatchAction(self.device); } -- (void)subscribeAttributeAutoISOEnabledWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler +- (void)subscribeAttributeSpeakerVolumeLevelWithParams:(MTRSubscribeParams * _Nonnull)params + subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished + reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler { - using TypeInfo = CameraAvStreamManagement::Attributes::AutoISOEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::TypeInfo; [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -99733,9 +99523,9 @@ - (void)subscribeAttributeAutoISOEnabledWithParams:(MTRSubscribeParams * _Nonnul subscriptionEstablished:subscriptionEstablished]; } -+ (void)readAttributeAutoISOEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion ++ (void)readAttributeSpeakerVolumeLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = CameraAvStreamManagement::Attributes::AutoISOEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::TypeInfo; [clusterStateCacheContainer _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) clusterID:TypeInfo::GetClusterId() @@ -99744,9 +99534,9 @@ + (void)readAttributeAutoISOEnabledWithClusterStateCache:(MTRClusterStateCacheCo completion:completion]; } -- (void)readAttributeViewportWithCompletion:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))completion +- (void)readAttributeSpeakerMaxLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = CameraAvStreamManagement::Attributes::Viewport::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMaxLevel::TypeInfo; [self.device _readKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -99755,11 +99545,11 @@ - (void)readAttributeViewportWithCompletion:(void (^)(MTRCameraAVStreamManagemen completion:completion]; } -- (void)subscribeAttributeViewportWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))reportHandler +- (void)subscribeAttributeSpeakerMaxLevelWithParams:(MTRSubscribeParams * _Nonnull)params + subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished + reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler { - using TypeInfo = CameraAvStreamManagement::Attributes::Viewport::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMaxLevel::TypeInfo; [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -99769,9 +99559,9 @@ - (void)subscribeAttributeViewportWithParams:(MTRSubscribeParams * _Nonnull)para subscriptionEstablished:subscriptionEstablished]; } -+ (void)readAttributeViewportWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))completion ++ (void)readAttributeSpeakerMaxLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = CameraAvStreamManagement::Attributes::Viewport::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMaxLevel::TypeInfo; [clusterStateCacheContainer _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) clusterID:TypeInfo::GetClusterId() @@ -99780,9 +99570,9 @@ + (void)readAttributeViewportWithClusterStateCache:(MTRClusterStateCacheContaine completion:completion]; } -- (void)readAttributeSpeakerMutedWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion +- (void)readAttributeSpeakerMinLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMuted::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMinLevel::TypeInfo; [self.device _readKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -99791,226 +99581,6 @@ - (void)readAttributeSpeakerMutedWithCompletion:(void (^)(NSNumber * _Nullable v completion:completion]; } -- (void)writeAttributeSpeakerMutedWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeSpeakerMutedWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeSpeakerMutedWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMuted::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.boolValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - -- (void)subscribeAttributeSpeakerMutedWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler -{ - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMuted::TypeInfo; - [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:params - queue:self.callbackQueue - reportHandler:reportHandler - subscriptionEstablished:subscriptionEstablished]; -} - -+ (void)readAttributeSpeakerMutedWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMuted::TypeInfo; - [clusterStateCacheContainer - _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) - clusterID:TypeInfo::GetClusterId() - attributeID:TypeInfo::GetAttributeId() - queue:queue - completion:completion]; -} - -- (void)readAttributeSpeakerVolumeLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::TypeInfo; - [self.device _readKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:nil - queue:self.callbackQueue - completion:completion]; -} - -- (void)writeAttributeSpeakerVolumeLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeSpeakerVolumeLevelWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeSpeakerVolumeLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.unsignedCharValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - -- (void)subscribeAttributeSpeakerVolumeLevelWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler -{ - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::TypeInfo; - [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:params - queue:self.callbackQueue - reportHandler:reportHandler - subscriptionEstablished:subscriptionEstablished]; -} - -+ (void)readAttributeSpeakerVolumeLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::TypeInfo; - [clusterStateCacheContainer - _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) - clusterID:TypeInfo::GetClusterId() - attributeID:TypeInfo::GetAttributeId() - queue:queue - completion:completion]; -} - -- (void)readAttributeSpeakerMaxLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMaxLevel::TypeInfo; - [self.device _readKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:nil - queue:self.callbackQueue - completion:completion]; -} - -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeSpeakerMaxLevelWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMaxLevel::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.unsignedCharValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - -- (void)subscribeAttributeSpeakerMaxLevelWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler -{ - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMaxLevel::TypeInfo; - [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:params - queue:self.callbackQueue - reportHandler:reportHandler - subscriptionEstablished:subscriptionEstablished]; -} - -+ (void)readAttributeSpeakerMaxLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMaxLevel::TypeInfo; - [clusterStateCacheContainer - _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) - clusterID:TypeInfo::GetClusterId() - attributeID:TypeInfo::GetAttributeId() - queue:queue - completion:completion]; -} - -- (void)readAttributeSpeakerMinLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMinLevel::TypeInfo; - [self.device _readKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:nil - queue:self.callbackQueue - completion:completion]; -} - -- (void)writeAttributeSpeakerMinLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeSpeakerMinLevelWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeSpeakerMinLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMinLevel::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.unsignedCharValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - - (void)subscribeAttributeSpeakerMinLevelWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100175,34 +99745,6 @@ - (void)readAttributeMicrophoneMaxLevelWithCompletion:(void (^)(NSNumber * _Null completion:completion]; } -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeMicrophoneMaxLevelWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::MicrophoneMaxLevel::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.unsignedCharValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - - (void)subscribeAttributeMicrophoneMaxLevelWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100239,34 +99781,6 @@ - (void)readAttributeMicrophoneMinLevelWithCompletion:(void (^)(NSNumber * _Null completion:completion]; } -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeMicrophoneMinLevelWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::MicrophoneMinLevel::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.unsignedCharValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - - (void)subscribeAttributeMicrophoneMinLevelWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100367,6 +99881,34 @@ - (void)readAttributeImageRotationWithCompletion:(void (^)(NSNumber * _Nullable completion:completion]; } +- (void)writeAttributeImageRotationWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion +{ + [self writeAttributeImageRotationWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; +} +- (void)writeAttributeImageRotationWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +{ + // Make a copy of params before we go async. + params = [params copy]; + value = [value copy]; + + auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { + chip::Optional timedWriteTimeout; + if (params != nil) { + if (params.timedWriteTimeout != nil){ + timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); + } + } + + ListFreer listFreer; + using TypeInfo = CameraAvStreamManagement::Attributes::ImageRotation::TypeInfo; + TypeInfo::Type cppValue; + cppValue = value.unsignedShortValue; + + chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); + return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); + std::move(*bridge).DispatchAction(self.device); +} + - (void)subscribeAttributeImageRotationWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100403,6 +99945,34 @@ - (void)readAttributeImageFlipHorizontalWithCompletion:(void (^)(NSNumber * _Nul completion:completion]; } +- (void)writeAttributeImageFlipHorizontalWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion +{ + [self writeAttributeImageFlipHorizontalWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; +} +- (void)writeAttributeImageFlipHorizontalWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +{ + // Make a copy of params before we go async. + params = [params copy]; + value = [value copy]; + + auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { + chip::Optional timedWriteTimeout; + if (params != nil) { + if (params.timedWriteTimeout != nil){ + timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); + } + } + + ListFreer listFreer; + using TypeInfo = CameraAvStreamManagement::Attributes::ImageFlipHorizontal::TypeInfo; + TypeInfo::Type cppValue; + cppValue = value.boolValue; + + chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); + return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); + std::move(*bridge).DispatchAction(self.device); +} + - (void)subscribeAttributeImageFlipHorizontalWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100439,6 +100009,34 @@ - (void)readAttributeImageFlipVerticalWithCompletion:(void (^)(NSNumber * _Nulla completion:completion]; } +- (void)writeAttributeImageFlipVerticalWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion +{ + [self writeAttributeImageFlipVerticalWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; +} +- (void)writeAttributeImageFlipVerticalWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +{ + // Make a copy of params before we go async. + params = [params copy]; + value = [value copy]; + + auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { + chip::Optional timedWriteTimeout; + if (params != nil) { + if (params.timedWriteTimeout != nil){ + timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); + } + } + + ListFreer listFreer; + using TypeInfo = CameraAvStreamManagement::Attributes::ImageFlipVertical::TypeInfo; + TypeInfo::Type cppValue; + cppValue = value.boolValue; + + chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); + return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); + std::move(*bridge).DispatchAction(self.device); +} + - (void)subscribeAttributeImageFlipVerticalWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100720,70 +100318,6 @@ + (void)readAttributeStatusLightBrightnessWithClusterStateCache:(MTRClusterState completion:completion]; } -- (void)readAttributeDepthSensorStatusWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::DepthSensorStatus::TypeInfo; - [self.device _readKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:nil - queue:self.callbackQueue - completion:completion]; -} - -- (void)writeAttributeDepthSensorStatusWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeDepthSensorStatusWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeDepthSensorStatusWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::DepthSensorStatus::TypeInfo; - TypeInfo::Type cppValue; - cppValue = static_cast>(value.unsignedCharValue); - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - -- (void)subscribeAttributeDepthSensorStatusWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler -{ - using TypeInfo = CameraAvStreamManagement::Attributes::DepthSensorStatus::TypeInfo; - [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:params - queue:self.callbackQueue - reportHandler:reportHandler - subscriptionEstablished:subscriptionEstablished]; -} - -+ (void)readAttributeDepthSensorStatusWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::DepthSensorStatus::TypeInfo; - [clusterStateCacheContainer - _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) - clusterID:TypeInfo::GetClusterId() - attributeID:TypeInfo::GetAttributeId() - queue:queue - completion:completion]; -} - - (void)readAttributeGeneratedCommandListWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion { using TypeInfo = CameraAvStreamManagement::Attributes::GeneratedCommandList::TypeInfo; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h b/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h index a5e2650097b105..e58a3a60d8eee1 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h @@ -4626,7 +4626,7 @@ typedef NS_ENUM(uint32_t, MTRAttributeIDType) { // Cluster ZoneManagement attributes MTRAttributeIDTypeClusterZoneManagementAttributeSupportedZoneSourcesID MTR_PROVISIONALLY_AVAILABLE = 0x00000000, MTRAttributeIDTypeClusterZoneManagementAttributeZonesID MTR_PROVISIONALLY_AVAILABLE = 0x00000001, - MTRAttributeIDTypeClusterZoneManagementAttributeTimeControlID MTR_PROVISIONALLY_AVAILABLE = 0x00000002, + MTRAttributeIDTypeClusterZoneManagementAttributeTriggersID MTR_PROVISIONALLY_AVAILABLE = 0x00000002, MTRAttributeIDTypeClusterZoneManagementAttributeSensitivityID MTR_PROVISIONALLY_AVAILABLE = 0x00000003, MTRAttributeIDTypeClusterZoneManagementAttributeGeneratedCommandListID MTR_PROVISIONALLY_AVAILABLE = MTRAttributeIDTypeGlobalAttributeGeneratedCommandListID, MTRAttributeIDTypeClusterZoneManagementAttributeAcceptedCommandListID MTR_PROVISIONALLY_AVAILABLE = MTRAttributeIDTypeGlobalAttributeAcceptedCommandListID, @@ -4649,39 +4649,33 @@ typedef NS_ENUM(uint32_t, MTRAttributeIDType) { MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMaxNetworkBandwidthID MTR_PROVISIONALLY_AVAILABLE = 0x0000000B, MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeCurrentFrameRateID MTR_PROVISIONALLY_AVAILABLE = 0x0000000C, MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeHDRModeEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000000D, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeCurrentVideoCodecsID MTR_PROVISIONALLY_AVAILABLE = 0x0000000E, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeCurrentSnapshotConfigID MTR_PROVISIONALLY_AVAILABLE = 0x0000000F, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeFabricsUsingCameraID MTR_PROVISIONALLY_AVAILABLE = 0x00000010, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAllocatedVideoStreamsID MTR_PROVISIONALLY_AVAILABLE = 0x00000011, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAllocatedAudioStreamsID MTR_PROVISIONALLY_AVAILABLE = 0x00000012, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAllocatedSnapshotStreamsID MTR_PROVISIONALLY_AVAILABLE = 0x00000013, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeRankedVideoStreamPrioritiesListID MTR_PROVISIONALLY_AVAILABLE = 0x00000014, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSoftRecordingPrivacyModeEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000015, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSoftLivestreamPrivacyModeEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000016, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeHardPrivacyModeOnID MTR_PROVISIONALLY_AVAILABLE = 0x00000017, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeNightVisionID MTR_PROVISIONALLY_AVAILABLE = 0x00000018, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeNightVisionIllumID MTR_PROVISIONALLY_AVAILABLE = 0x00000019, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAWBEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000001A, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoShutterSpeedEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000001B, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoISOEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000001C, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID MTR_PROVISIONALLY_AVAILABLE = 0x0000001D, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMutedID MTR_PROVISIONALLY_AVAILABLE = 0x0000001E, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerVolumeLevelID MTR_PROVISIONALLY_AVAILABLE = 0x0000001F, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMaxLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000020, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMinLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000021, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMutedID MTR_PROVISIONALLY_AVAILABLE = 0x00000022, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneVolumeLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000023, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMaxLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000024, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMinLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000025, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneAGCEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000026, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageRotationID MTR_PROVISIONALLY_AVAILABLE = 0x00000027, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipHorizontalID MTR_PROVISIONALLY_AVAILABLE = 0x00000028, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipVerticalID MTR_PROVISIONALLY_AVAILABLE = 0x00000029, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeLocalVideoRecordingEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000002A, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeLocalSnapshotRecordingEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000002B, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeStatusLightEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000002C, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeStatusLightBrightnessID MTR_PROVISIONALLY_AVAILABLE = 0x0000002D, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeDepthSensorStatusID MTR_PROVISIONALLY_AVAILABLE = 0x0000002E, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeFabricsUsingCameraID MTR_PROVISIONALLY_AVAILABLE = 0x0000000E, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAllocatedVideoStreamsID MTR_PROVISIONALLY_AVAILABLE = 0x0000000F, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAllocatedAudioStreamsID MTR_PROVISIONALLY_AVAILABLE = 0x00000010, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAllocatedSnapshotStreamsID MTR_PROVISIONALLY_AVAILABLE = 0x00000011, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeRankedVideoStreamPrioritiesListID MTR_PROVISIONALLY_AVAILABLE = 0x00000012, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSoftRecordingPrivacyModeEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000013, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSoftLivestreamPrivacyModeEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000014, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeHardPrivacyModeOnID MTR_PROVISIONALLY_AVAILABLE = 0x00000015, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeNightVisionID MTR_PROVISIONALLY_AVAILABLE = 0x00000016, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeNightVisionIllumID MTR_PROVISIONALLY_AVAILABLE = 0x00000017, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID MTR_PROVISIONALLY_AVAILABLE = 0x00000018, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMutedID MTR_PROVISIONALLY_AVAILABLE = 0x00000019, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerVolumeLevelID MTR_PROVISIONALLY_AVAILABLE = 0x0000001A, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMaxLevelID MTR_PROVISIONALLY_AVAILABLE = 0x0000001B, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMinLevelID MTR_PROVISIONALLY_AVAILABLE = 0x0000001C, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMutedID MTR_PROVISIONALLY_AVAILABLE = 0x0000001D, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneVolumeLevelID MTR_PROVISIONALLY_AVAILABLE = 0x0000001E, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMaxLevelID MTR_PROVISIONALLY_AVAILABLE = 0x0000001F, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMinLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000020, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneAGCEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000021, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageRotationID MTR_PROVISIONALLY_AVAILABLE = 0x00000022, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipHorizontalID MTR_PROVISIONALLY_AVAILABLE = 0x00000023, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipVerticalID MTR_PROVISIONALLY_AVAILABLE = 0x00000024, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeLocalVideoRecordingEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000025, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeLocalSnapshotRecordingEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000026, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeStatusLightEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000027, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeStatusLightBrightnessID MTR_PROVISIONALLY_AVAILABLE = 0x00000028, MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeGeneratedCommandListID MTR_PROVISIONALLY_AVAILABLE = MTRAttributeIDTypeGlobalAttributeGeneratedCommandListID, MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAcceptedCommandListID MTR_PROVISIONALLY_AVAILABLE = MTRAttributeIDTypeGlobalAttributeAcceptedCommandListID, MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAttributeListID MTR_PROVISIONALLY_AVAILABLE = MTRAttributeIDTypeGlobalAttributeAttributeListID, @@ -6925,10 +6919,6 @@ typedef NS_ENUM(uint32_t, MTRCommandIDType) { MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetStreamPrioritiesID MTR_PROVISIONALLY_AVAILABLE = 0x0000000A, MTRCommandIDTypeClusterCameraAVStreamManagementCommandCaptureSnapshotID MTR_PROVISIONALLY_AVAILABLE = 0x0000000B, MTRCommandIDTypeClusterCameraAVStreamManagementCommandCaptureSnapshotResponseID MTR_PROVISIONALLY_AVAILABLE = 0x0000000C, - MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetViewportID MTR_PROVISIONALLY_AVAILABLE = 0x0000000D, - MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageRotationID MTR_PROVISIONALLY_AVAILABLE = 0x0000000E, - MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageFlipHorizontalID MTR_PROVISIONALLY_AVAILABLE = 0x0000000F, - MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageFlipVerticalID MTR_PROVISIONALLY_AVAILABLE = 0x00000010, // Cluster WebRTCTransportProvider commands MTRCommandIDTypeClusterWebRTCTransportProviderCommandSolicitOfferID MTR_PROVISIONALLY_AVAILABLE = 0x00000001, diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRClusterNames.mm b/src/darwin/Framework/CHIP/zap-generated/MTRClusterNames.mm index ef41bc6487b379..96b2c0cd3bf3e6 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRClusterNames.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRClusterNames.mm @@ -7688,8 +7688,8 @@ result = @"Zones"; break; - case MTRAttributeIDTypeClusterZoneManagementAttributeTimeControlID: - result = @"TimeControl"; + case MTRAttributeIDTypeClusterZoneManagementAttributeTriggersID: + result = @"Triggers"; break; case MTRAttributeIDTypeClusterZoneManagementAttributeSensitivityID: @@ -7783,14 +7783,6 @@ result = @"HDRModeEnabled"; break; - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeCurrentVideoCodecsID: - result = @"CurrentVideoCodecs"; - break; - - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeCurrentSnapshotConfigID: - result = @"CurrentSnapshotConfig"; - break; - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeFabricsUsingCameraID: result = @"FabricsUsingCamera"; break; @@ -7831,18 +7823,6 @@ result = @"NightVisionIllum"; break; - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAWBEnabledID: - result = @"AWBEnabled"; - break; - - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoShutterSpeedEnabledID: - result = @"AutoShutterSpeedEnabled"; - break; - - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoISOEnabledID: - result = @"AutoISOEnabled"; - break; - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID: result = @"Viewport"; break; @@ -7911,10 +7891,6 @@ result = @"StatusLightBrightness"; break; - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeDepthSensorStatusID: - result = @"DepthSensorStatus"; - break; - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeGeneratedCommandListID: result = @"GeneratedCommandList"; break; @@ -10832,22 +10808,6 @@ result = @"CaptureSnapshot"; break; - case MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetViewportID: - result = @"SetViewport"; - break; - - case MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageRotationID: - result = @"SetImageRotation"; - break; - - case MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageFlipHorizontalID: - result = @"SetImageFlipHorizontal"; - break; - - case MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageFlipVerticalID: - result = @"SetImageFlipVertical"; - break; - default: result = [NSString stringWithFormat:@"", commandID]; break; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRClusters.h index 111cab13f8af49..9babe0a6251f1e 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRClusters.h @@ -6592,9 +6592,9 @@ MTR_PROVISIONALLY_AVAILABLE - (NSDictionary * _Nullable)readAttributeZonesWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (NSDictionary * _Nullable)readAttributeTimeControlWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeTimeControlWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeTimeControlWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; +- (NSDictionary * _Nullable)readAttributeTriggersWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeTriggersWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeTriggersWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeSensitivityWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeSensitivityWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; @@ -6643,10 +6643,6 @@ MTR_PROVISIONALLY_AVAILABLE - (void)snapshotStreamDeallocateWithParams:(MTRCameraAVStreamManagementClusterSnapshotStreamDeallocateParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)setStreamPrioritiesWithParams:(MTRCameraAVStreamManagementClusterSetStreamPrioritiesParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)captureSnapshotWithParams:(MTRCameraAVStreamManagementClusterCaptureSnapshotParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)setViewportWithParams:(MTRCameraAVStreamManagementClusterSetViewportParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)setImageRotationWithParams:(MTRCameraAVStreamManagementClusterSetImageRotationParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)setImageFlipHorizontalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)setImageFlipVerticalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeMaxConcurrentVideoEncodersWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; @@ -6678,10 +6674,6 @@ MTR_PROVISIONALLY_AVAILABLE - (void)writeAttributeHDRModeEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeHDRModeEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (NSDictionary * _Nullable)readAttributeCurrentVideoCodecsWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - -- (NSDictionary * _Nullable)readAttributeCurrentSnapshotConfigWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - - (NSDictionary * _Nullable)readAttributeFabricsUsingCameraWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeAllocatedVideoStreamsWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; @@ -6691,8 +6683,6 @@ MTR_PROVISIONALLY_AVAILABLE - (NSDictionary * _Nullable)readAttributeAllocatedSnapshotStreamsWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeRankedVideoStreamPrioritiesListWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeRankedVideoStreamPrioritiesListWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeRankedVideoStreamPrioritiesListWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeSoftRecordingPrivacyModeEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeSoftRecordingPrivacyModeEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; @@ -6712,19 +6702,9 @@ MTR_PROVISIONALLY_AVAILABLE - (void)writeAttributeNightVisionIllumWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeNightVisionIllumWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (NSDictionary * _Nullable)readAttributeAWBEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAWBEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAWBEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - -- (NSDictionary * _Nullable)readAttributeAutoShutterSpeedEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - -- (NSDictionary * _Nullable)readAttributeAutoISOEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoISOEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoISOEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - - (NSDictionary * _Nullable)readAttributeViewportWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeViewportWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeViewportWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeSpeakerMutedWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeSpeakerMutedWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; @@ -6735,12 +6715,8 @@ MTR_PROVISIONALLY_AVAILABLE - (void)writeAttributeSpeakerVolumeLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeSpeakerMaxLevelWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeSpeakerMinLevelWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeMicrophoneMutedWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeMicrophoneMutedWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; @@ -6751,22 +6727,24 @@ MTR_PROVISIONALLY_AVAILABLE - (void)writeAttributeMicrophoneVolumeLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeMicrophoneMaxLevelWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeMicrophoneMinLevelWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeMicrophoneAGCEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeMicrophoneAGCEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeMicrophoneAGCEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeImageRotationWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageRotationWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageRotationWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeImageFlipHorizontalWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipHorizontalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipHorizontalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeImageFlipVerticalWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipVerticalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipVerticalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeLocalVideoRecordingEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeLocalVideoRecordingEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; @@ -6784,10 +6762,6 @@ MTR_PROVISIONALLY_AVAILABLE - (void)writeAttributeStatusLightBrightnessWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeStatusLightBrightnessWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (NSDictionary * _Nullable)readAttributeDepthSensorStatusWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeDepthSensorStatusWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeDepthSensorStatusWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - - (NSDictionary * _Nullable)readAttributeGeneratedCommandListWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeAcceptedCommandListWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRClusters.mm b/src/darwin/Framework/CHIP/zap-generated/MTRClusters.mm index b473aed7020e46..1d6828deddb868 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRClusters.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRClusters.mm @@ -19012,20 +19012,20 @@ - (void)removeZoneWithParams:(MTRZoneManagementClusterRemoveZoneParams *)params return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeZoneManagementID) attributeID:@(MTRAttributeIDTypeClusterZoneManagementAttributeZonesID) params:params]; } -- (NSDictionary * _Nullable)readAttributeTimeControlWithParams:(MTRReadParams * _Nullable)params +- (NSDictionary * _Nullable)readAttributeTriggersWithParams:(MTRReadParams * _Nullable)params { - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeZoneManagementID) attributeID:@(MTRAttributeIDTypeClusterZoneManagementAttributeTimeControlID) params:params]; + return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeZoneManagementID) attributeID:@(MTRAttributeIDTypeClusterZoneManagementAttributeTriggersID) params:params]; } -- (void)writeAttributeTimeControlWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs +- (void)writeAttributeTriggersWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs { - [self writeAttributeTimeControlWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; + [self writeAttributeTriggersWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; } -- (void)writeAttributeTimeControlWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params +- (void)writeAttributeTriggersWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params { NSNumber * timedWriteTimeout = params.timedWriteTimeout; - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeZoneManagementID) attributeID:@(MTRAttributeIDTypeClusterZoneManagementAttributeTimeControlID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; + [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeZoneManagementID) attributeID:@(MTRAttributeIDTypeClusterZoneManagementAttributeTriggersID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; } - (NSDictionary * _Nullable)readAttributeSensitivityWithParams:(MTRReadParams * _Nullable)params @@ -19316,114 +19316,6 @@ - (void)captureSnapshotWithParams:(MTRCameraAVStreamManagementClusterCaptureSnap completion:responseHandler]; } -- (void)setViewportWithParams:(MTRCameraAVStreamManagementClusterSetViewportParams *)params expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetViewportParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetViewport::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - expectedValues:expectedValues - expectedValueInterval:expectedValueIntervalMs - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} - -- (void)setImageRotationWithParams:(MTRCameraAVStreamManagementClusterSetImageRotationParams *)params expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageRotationParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageRotation::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - expectedValues:expectedValues - expectedValueInterval:expectedValueIntervalMs - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} - -- (void)setImageFlipHorizontalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams *)params expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - expectedValues:expectedValues - expectedValueInterval:expectedValueIntervalMs - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} - -- (void)setImageFlipVerticalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams *)params expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageFlipVertical::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - expectedValues:expectedValues - expectedValueInterval:expectedValueIntervalMs - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} - - (NSDictionary * _Nullable)readAttributeMaxConcurrentVideoEncodersWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMaxConcurrentVideoEncodersID) params:params]; @@ -19505,16 +19397,6 @@ - (void)writeAttributeHDRModeEnabledWithValue:(NSDictionary *)da [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeHDRModeEnabledID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; } -- (NSDictionary * _Nullable)readAttributeCurrentVideoCodecsWithParams:(MTRReadParams * _Nullable)params -{ - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeCurrentVideoCodecsID) params:params]; -} - -- (NSDictionary * _Nullable)readAttributeCurrentSnapshotConfigWithParams:(MTRReadParams * _Nullable)params -{ - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeCurrentSnapshotConfigID) params:params]; -} - - (NSDictionary * _Nullable)readAttributeFabricsUsingCameraWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeFabricsUsingCameraID) params:params]; @@ -19540,17 +19422,6 @@ - (void)writeAttributeHDRModeEnabledWithValue:(NSDictionary *)da return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeRankedVideoStreamPrioritiesListID) params:params]; } -- (void)writeAttributeRankedVideoStreamPrioritiesListWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeRankedVideoStreamPrioritiesListWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeRankedVideoStreamPrioritiesListWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeRankedVideoStreamPrioritiesListID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeSoftRecordingPrivacyModeEnabledWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSoftRecordingPrivacyModeEnabledID) params:params]; @@ -19620,57 +19491,20 @@ - (void)writeAttributeNightVisionIllumWithValue:(NSDictionary *) [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeNightVisionIllumID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; } -- (NSDictionary * _Nullable)readAttributeAWBEnabledWithParams:(MTRReadParams * _Nullable)params -{ - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAWBEnabledID) params:params]; -} - -- (void)writeAttributeAWBEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeAWBEnabledWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeAWBEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAWBEnabledID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - -- (NSDictionary * _Nullable)readAttributeAutoShutterSpeedEnabledWithParams:(MTRReadParams * _Nullable)params -{ - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoShutterSpeedEnabledID) params:params]; -} - -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeAutoShutterSpeedEnabledWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoShutterSpeedEnabledID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - -- (NSDictionary * _Nullable)readAttributeAutoISOEnabledWithParams:(MTRReadParams * _Nullable)params +- (NSDictionary * _Nullable)readAttributeViewportWithParams:(MTRReadParams * _Nullable)params { - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoISOEnabledID) params:params]; + return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID) params:params]; } -- (void)writeAttributeAutoISOEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs +- (void)writeAttributeViewportWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs { - [self writeAttributeAutoISOEnabledWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; + [self writeAttributeViewportWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; } -- (void)writeAttributeAutoISOEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params +- (void)writeAttributeViewportWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params { NSNumber * timedWriteTimeout = params.timedWriteTimeout; - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoISOEnabledID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - -- (NSDictionary * _Nullable)readAttributeViewportWithParams:(MTRReadParams * _Nullable)params -{ - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID) params:params]; + [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; } - (NSDictionary * _Nullable)readAttributeSpeakerMutedWithParams:(MTRReadParams * _Nullable)params @@ -19710,33 +19544,11 @@ - (void)writeAttributeSpeakerVolumeLevelWithValue:(NSDictionary return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMaxLevelID) params:params]; } -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeSpeakerMaxLevelWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMaxLevelID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeSpeakerMinLevelWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMinLevelID) params:params]; } -- (void)writeAttributeSpeakerMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeSpeakerMinLevelWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeSpeakerMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMinLevelID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeMicrophoneMutedWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMutedID) params:params]; @@ -19774,33 +19586,11 @@ - (void)writeAttributeMicrophoneVolumeLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeMicrophoneMaxLevelWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMaxLevelID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeMicrophoneMinLevelWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMinLevelID) params:params]; } -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeMicrophoneMinLevelWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMinLevelID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeMicrophoneAGCEnabledWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneAGCEnabledID) params:params]; @@ -19822,16 +19612,49 @@ - (void)writeAttributeMicrophoneAGCEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs +{ + [self writeAttributeImageRotationWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; +} +- (void)writeAttributeImageRotationWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params +{ + NSNumber * timedWriteTimeout = params.timedWriteTimeout; + + [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageRotationID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; +} + - (NSDictionary * _Nullable)readAttributeImageFlipHorizontalWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipHorizontalID) params:params]; } +- (void)writeAttributeImageFlipHorizontalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs +{ + [self writeAttributeImageFlipHorizontalWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; +} +- (void)writeAttributeImageFlipHorizontalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params +{ + NSNumber * timedWriteTimeout = params.timedWriteTimeout; + + [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipHorizontalID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; +} + - (NSDictionary * _Nullable)readAttributeImageFlipVerticalWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipVerticalID) params:params]; } +- (void)writeAttributeImageFlipVerticalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs +{ + [self writeAttributeImageFlipVerticalWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; +} +- (void)writeAttributeImageFlipVerticalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params +{ + NSNumber * timedWriteTimeout = params.timedWriteTimeout; + + [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipVerticalID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; +} + - (NSDictionary * _Nullable)readAttributeLocalVideoRecordingEnabledWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeLocalVideoRecordingEnabledID) params:params]; @@ -19896,22 +19719,6 @@ - (void)writeAttributeStatusLightBrightnessWithValue:(NSDictionary * _Nullable)readAttributeDepthSensorStatusWithParams:(MTRReadParams * _Nullable)params -{ - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeDepthSensorStatusID) params:params]; -} - -- (void)writeAttributeDepthSensorStatusWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeDepthSensorStatusWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeDepthSensorStatusWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeDepthSensorStatusID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeGeneratedCommandListWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeGeneratedCommandListID) params:params]; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h index 6a5580c95b88db..573d6581ced8f0 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h @@ -11226,7 +11226,7 @@ MTR_PROVISIONALLY_AVAILABLE @property (nonatomic, copy) NSNumber * _Nonnull imageCodec MTR_PROVISIONALLY_AVAILABLE; -@property (nonatomic, copy) NSNumber * _Nonnull frameRate MTR_PROVISIONALLY_AVAILABLE; +@property (nonatomic, copy) NSNumber * _Nonnull maxFrameRate MTR_PROVISIONALLY_AVAILABLE; @property (nonatomic, copy) NSNumber * _Nonnull bitRate MTR_PROVISIONALLY_AVAILABLE; @@ -11395,126 +11395,6 @@ MTR_PROVISIONALLY_AVAILABLE error:(NSError * __autoreleasing *)error MTR_PROVISIONALLY_AVAILABLE; @end -MTR_PROVISIONALLY_AVAILABLE -@interface MTRCameraAVStreamManagementClusterSetViewportParams : NSObject - -@property (nonatomic, copy) MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull viewport MTR_PROVISIONALLY_AVAILABLE; -/** - * Controls whether the command is a timed command (using Timed Invoke). - * - * If nil (the default value), a regular invoke is done for commands that do - * not require a timed invoke and a timed invoke with some default timed request - * timeout is done for commands that require a timed invoke. - * - * If not nil, a timed invoke is done, with the provided value used as the timed - * request timeout. The value should be chosen small enough to provide the - * desired security properties but large enough that it will allow a round-trip - * from the sever to the client (for the status response and actual invoke - * request) within the timeout window. - * - */ -@property (nonatomic, copy, nullable) NSNumber * timedInvokeTimeoutMs; - -/** - * Controls how much time, in seconds, we will allow for the server to process the command. - * - * The command will then time out if that much time, plus an allowance for retransmits due to network failures, passes. - * - * If nil, the framework will try to select an appropriate timeout value itself. - */ -@property (nonatomic, copy, nullable) NSNumber * serverSideProcessingTimeout; -@end - -MTR_PROVISIONALLY_AVAILABLE -@interface MTRCameraAVStreamManagementClusterSetImageRotationParams : NSObject - -@property (nonatomic, copy) NSNumber * _Nonnull angle MTR_PROVISIONALLY_AVAILABLE; -/** - * Controls whether the command is a timed command (using Timed Invoke). - * - * If nil (the default value), a regular invoke is done for commands that do - * not require a timed invoke and a timed invoke with some default timed request - * timeout is done for commands that require a timed invoke. - * - * If not nil, a timed invoke is done, with the provided value used as the timed - * request timeout. The value should be chosen small enough to provide the - * desired security properties but large enough that it will allow a round-trip - * from the sever to the client (for the status response and actual invoke - * request) within the timeout window. - * - */ -@property (nonatomic, copy, nullable) NSNumber * timedInvokeTimeoutMs; - -/** - * Controls how much time, in seconds, we will allow for the server to process the command. - * - * The command will then time out if that much time, plus an allowance for retransmits due to network failures, passes. - * - * If nil, the framework will try to select an appropriate timeout value itself. - */ -@property (nonatomic, copy, nullable) NSNumber * serverSideProcessingTimeout; -@end - -MTR_PROVISIONALLY_AVAILABLE -@interface MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams : NSObject - -@property (nonatomic, copy) NSNumber * _Nonnull enabled MTR_PROVISIONALLY_AVAILABLE; -/** - * Controls whether the command is a timed command (using Timed Invoke). - * - * If nil (the default value), a regular invoke is done for commands that do - * not require a timed invoke and a timed invoke with some default timed request - * timeout is done for commands that require a timed invoke. - * - * If not nil, a timed invoke is done, with the provided value used as the timed - * request timeout. The value should be chosen small enough to provide the - * desired security properties but large enough that it will allow a round-trip - * from the sever to the client (for the status response and actual invoke - * request) within the timeout window. - * - */ -@property (nonatomic, copy, nullable) NSNumber * timedInvokeTimeoutMs; - -/** - * Controls how much time, in seconds, we will allow for the server to process the command. - * - * The command will then time out if that much time, plus an allowance for retransmits due to network failures, passes. - * - * If nil, the framework will try to select an appropriate timeout value itself. - */ -@property (nonatomic, copy, nullable) NSNumber * serverSideProcessingTimeout; -@end - -MTR_PROVISIONALLY_AVAILABLE -@interface MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams : NSObject - -@property (nonatomic, copy) NSNumber * _Nonnull enabled MTR_PROVISIONALLY_AVAILABLE; -/** - * Controls whether the command is a timed command (using Timed Invoke). - * - * If nil (the default value), a regular invoke is done for commands that do - * not require a timed invoke and a timed invoke with some default timed request - * timeout is done for commands that require a timed invoke. - * - * If not nil, a timed invoke is done, with the provided value used as the timed - * request timeout. The value should be chosen small enough to provide the - * desired security properties but large enough that it will allow a round-trip - * from the sever to the client (for the status response and actual invoke - * request) within the timeout window. - * - */ -@property (nonatomic, copy, nullable) NSNumber * timedInvokeTimeoutMs; - -/** - * Controls how much time, in seconds, we will allow for the server to process the command. - * - * The command will then time out if that much time, plus an allowance for retransmits due to network failures, passes. - * - * If nil, the framework will try to select an appropriate timeout value itself. - */ -@property (nonatomic, copy, nullable) NSNumber * serverSideProcessingTimeout; -@end - MTR_PROVISIONALLY_AVAILABLE @interface MTRWebRTCTransportProviderClusterSolicitOfferParams : NSObject diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm index 2010627d89e7db..6d8ddd60910f47 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm @@ -32619,7 +32619,7 @@ - (instancetype)init _imageCodec = @(0); - _frameRate = @(0); + _maxFrameRate = @(0); _bitRate = @(0); @@ -32639,7 +32639,7 @@ - (id)copyWithZone:(NSZone * _Nullable)zone; auto other = [[MTRCameraAVStreamManagementClusterSnapshotStreamAllocateParams alloc] init]; other.imageCodec = self.imageCodec; - other.frameRate = self.frameRate; + other.maxFrameRate = self.maxFrameRate; other.bitRate = self.bitRate; other.minResolution = self.minResolution; other.maxResolution = self.maxResolution; @@ -32652,7 +32652,7 @@ - (id)copyWithZone:(NSZone * _Nullable)zone; - (NSString *)description { - NSString * descriptionString = [NSString stringWithFormat:@"<%@: imageCodec:%@; frameRate:%@; bitRate:%@; minResolution:%@; maxResolution:%@; quality:%@; >", NSStringFromClass([self class]), _imageCodec, _frameRate, _bitRate, _minResolution, _maxResolution, _quality]; + NSString * descriptionString = [NSString stringWithFormat:@"<%@: imageCodec:%@; maxFrameRate:%@; bitRate:%@; minResolution:%@; maxResolution:%@; quality:%@; >", NSStringFromClass([self class]), _imageCodec, _maxFrameRate, _bitRate, _minResolution, _maxResolution, _quality]; return descriptionString; } @@ -32668,7 +32668,7 @@ - (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader encodableStruct.imageCodec = static_cast>(self.imageCodec.unsignedCharValue); } { - encodableStruct.frameRate = self.frameRate.unsignedShortValue; + encodableStruct.maxFrameRate = self.maxFrameRate.unsignedShortValue; } { encodableStruct.bitRate = self.bitRate.unsignedIntValue; @@ -33160,325 +33160,6 @@ - (CHIP_ERROR)_setFieldsFromDecodableStruct:(const chip::app::Clusters::CameraAv @end -@implementation MTRCameraAVStreamManagementClusterSetViewportParams -- (instancetype)init -{ - if (self = [super init]) { - - _viewport = [MTRCameraAVStreamManagementClusterViewportStruct new]; - _timedInvokeTimeoutMs = nil; - _serverSideProcessingTimeout = nil; - } - return self; -} - -- (id)copyWithZone:(NSZone * _Nullable)zone; -{ - auto other = [[MTRCameraAVStreamManagementClusterSetViewportParams alloc] init]; - - other.viewport = self.viewport; - other.timedInvokeTimeoutMs = self.timedInvokeTimeoutMs; - other.serverSideProcessingTimeout = self.serverSideProcessingTimeout; - - return other; -} - -- (NSString *)description -{ - NSString * descriptionString = [NSString stringWithFormat:@"<%@: viewport:%@; >", NSStringFromClass([self class]), _viewport]; - return descriptionString; -} - -@end - -@implementation MTRCameraAVStreamManagementClusterSetViewportParams (InternalMethods) - -- (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader -{ - chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Type encodableStruct; - ListFreer listFreer; - { - encodableStruct.viewport.x1 = self.viewport.x1.unsignedShortValue; - encodableStruct.viewport.y1 = self.viewport.y1.unsignedShortValue; - encodableStruct.viewport.x2 = self.viewport.x2.unsignedShortValue; - encodableStruct.viewport.y2 = self.viewport.y2.unsignedShortValue; - } - - auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); - if (buffer.IsNull()) { - return CHIP_ERROR_NO_MEMORY; - } - - chip::System::PacketBufferTLVWriter writer; - // Commands never need chained buffers, since they cannot be chunked. - writer.Init(std::move(buffer), /* useChainedBuffers = */ false); - - ReturnErrorOnFailure(chip::app::DataModel::Encode(writer, chip::TLV::AnonymousTag(), encodableStruct)); - - ReturnErrorOnFailure(writer.Finalize(&buffer)); - - reader.Init(std::move(buffer)); - return reader.Next(chip::TLV::kTLVType_Structure, chip::TLV::AnonymousTag()); -} - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error -{ - chip::System::PacketBufferTLVReader reader; - CHIP_ERROR err = [self _encodeToTLVReader:reader]; - if (err != CHIP_NO_ERROR) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:err]; - } - return nil; - } - - auto decodedObj = MTRDecodeDataValueDictionaryFromCHIPTLV(&reader); - if (decodedObj == nil) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; - } - } - return decodedObj; -} -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageRotationParams -- (instancetype)init -{ - if (self = [super init]) { - - _angle = @(0); - _timedInvokeTimeoutMs = nil; - _serverSideProcessingTimeout = nil; - } - return self; -} - -- (id)copyWithZone:(NSZone * _Nullable)zone; -{ - auto other = [[MTRCameraAVStreamManagementClusterSetImageRotationParams alloc] init]; - - other.angle = self.angle; - other.timedInvokeTimeoutMs = self.timedInvokeTimeoutMs; - other.serverSideProcessingTimeout = self.serverSideProcessingTimeout; - - return other; -} - -- (NSString *)description -{ - NSString * descriptionString = [NSString stringWithFormat:@"<%@: angle:%@; >", NSStringFromClass([self class]), _angle]; - return descriptionString; -} - -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageRotationParams (InternalMethods) - -- (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader -{ - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Type encodableStruct; - ListFreer listFreer; - { - encodableStruct.angle = self.angle.unsignedShortValue; - } - - auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); - if (buffer.IsNull()) { - return CHIP_ERROR_NO_MEMORY; - } - - chip::System::PacketBufferTLVWriter writer; - // Commands never need chained buffers, since they cannot be chunked. - writer.Init(std::move(buffer), /* useChainedBuffers = */ false); - - ReturnErrorOnFailure(chip::app::DataModel::Encode(writer, chip::TLV::AnonymousTag(), encodableStruct)); - - ReturnErrorOnFailure(writer.Finalize(&buffer)); - - reader.Init(std::move(buffer)); - return reader.Next(chip::TLV::kTLVType_Structure, chip::TLV::AnonymousTag()); -} - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error -{ - chip::System::PacketBufferTLVReader reader; - CHIP_ERROR err = [self _encodeToTLVReader:reader]; - if (err != CHIP_NO_ERROR) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:err]; - } - return nil; - } - - auto decodedObj = MTRDecodeDataValueDictionaryFromCHIPTLV(&reader); - if (decodedObj == nil) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; - } - } - return decodedObj; -} -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams -- (instancetype)init -{ - if (self = [super init]) { - - _enabled = @(0); - _timedInvokeTimeoutMs = nil; - _serverSideProcessingTimeout = nil; - } - return self; -} - -- (id)copyWithZone:(NSZone * _Nullable)zone; -{ - auto other = [[MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams alloc] init]; - - other.enabled = self.enabled; - other.timedInvokeTimeoutMs = self.timedInvokeTimeoutMs; - other.serverSideProcessingTimeout = self.serverSideProcessingTimeout; - - return other; -} - -- (NSString *)description -{ - NSString * descriptionString = [NSString stringWithFormat:@"<%@: enabled:%@; >", NSStringFromClass([self class]), _enabled]; - return descriptionString; -} - -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams (InternalMethods) - -- (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader -{ - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Type encodableStruct; - ListFreer listFreer; - { - encodableStruct.enabled = self.enabled.boolValue; - } - - auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); - if (buffer.IsNull()) { - return CHIP_ERROR_NO_MEMORY; - } - - chip::System::PacketBufferTLVWriter writer; - // Commands never need chained buffers, since they cannot be chunked. - writer.Init(std::move(buffer), /* useChainedBuffers = */ false); - - ReturnErrorOnFailure(chip::app::DataModel::Encode(writer, chip::TLV::AnonymousTag(), encodableStruct)); - - ReturnErrorOnFailure(writer.Finalize(&buffer)); - - reader.Init(std::move(buffer)); - return reader.Next(chip::TLV::kTLVType_Structure, chip::TLV::AnonymousTag()); -} - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error -{ - chip::System::PacketBufferTLVReader reader; - CHIP_ERROR err = [self _encodeToTLVReader:reader]; - if (err != CHIP_NO_ERROR) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:err]; - } - return nil; - } - - auto decodedObj = MTRDecodeDataValueDictionaryFromCHIPTLV(&reader); - if (decodedObj == nil) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; - } - } - return decodedObj; -} -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams -- (instancetype)init -{ - if (self = [super init]) { - - _enabled = @(0); - _timedInvokeTimeoutMs = nil; - _serverSideProcessingTimeout = nil; - } - return self; -} - -- (id)copyWithZone:(NSZone * _Nullable)zone; -{ - auto other = [[MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams alloc] init]; - - other.enabled = self.enabled; - other.timedInvokeTimeoutMs = self.timedInvokeTimeoutMs; - other.serverSideProcessingTimeout = self.serverSideProcessingTimeout; - - return other; -} - -- (NSString *)description -{ - NSString * descriptionString = [NSString stringWithFormat:@"<%@: enabled:%@; >", NSStringFromClass([self class]), _enabled]; - return descriptionString; -} - -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams (InternalMethods) - -- (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader -{ - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Type encodableStruct; - ListFreer listFreer; - { - encodableStruct.enabled = self.enabled.boolValue; - } - - auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); - if (buffer.IsNull()) { - return CHIP_ERROR_NO_MEMORY; - } - - chip::System::PacketBufferTLVWriter writer; - // Commands never need chained buffers, since they cannot be chunked. - writer.Init(std::move(buffer), /* useChainedBuffers = */ false); - - ReturnErrorOnFailure(chip::app::DataModel::Encode(writer, chip::TLV::AnonymousTag(), encodableStruct)); - - ReturnErrorOnFailure(writer.Finalize(&buffer)); - - reader.Init(std::move(buffer)); - return reader.Next(chip::TLV::kTLVType_Structure, chip::TLV::AnonymousTag()); -} - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error -{ - chip::System::PacketBufferTLVReader reader; - CHIP_ERROR err = [self _encodeToTLVReader:reader]; - if (err != CHIP_NO_ERROR) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:err]; - } - return nil; - } - - auto decodedObj = MTRDecodeDataValueDictionaryFromCHIPTLV(&reader); - if (decodedObj == nil) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; - } - } - return decodedObj; -} -@end - @implementation MTRWebRTCTransportProviderClusterSolicitOfferParams - (instancetype)init { diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloads_Internal.h b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloads_Internal.h index 70d8a461c6bf9e..89f78e7a2422fc 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloads_Internal.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloads_Internal.h @@ -2146,30 +2146,6 @@ NS_ASSUME_NONNULL_BEGIN @end -@interface MTRCameraAVStreamManagementClusterSetViewportParams (InternalMethods) - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error; - -@end - -@interface MTRCameraAVStreamManagementClusterSetImageRotationParams (InternalMethods) - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error; - -@end - -@interface MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams (InternalMethods) - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error; - -@end - -@interface MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams (InternalMethods) - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error; - -@end - @interface MTRWebRTCTransportProviderClusterSolicitOfferParams (InternalMethods) - (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRDeviceTypeMetadata.mm b/src/darwin/Framework/CHIP/zap-generated/MTRDeviceTypeMetadata.mm index fc9d8c7d930d88..cec53390010b33 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRDeviceTypeMetadata.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRDeviceTypeMetadata.mm @@ -87,7 +87,7 @@ { 0x00000307, MTRDeviceTypeClass::Simple, "Humidity Sensor" }, { 0x00000309, MTRDeviceTypeClass::Simple, "Heat Pump" }, { 0x0000050C, MTRDeviceTypeClass::Simple, "EVSE" }, - { 0x0000050D, MTRDeviceTypeClass::Simple, "Device Energy Management" }, + { 0x0000050D, MTRDeviceTypeClass::Utility, "Device Energy Management" }, { 0x0000050F, MTRDeviceTypeClass::Simple, "Water Heater" }, { 0x00000510, MTRDeviceTypeClass::Utility, "Electrical Sensor" }, { 0x00000840, MTRDeviceTypeClass::Simple, "Control Bridge" }, diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h index 02d36a82d710b9..9f679a7a305e8d 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h @@ -2139,11 +2139,12 @@ MTR_PROVISIONALLY_AVAILABLE @end MTR_PROVISIONALLY_AVAILABLE -@interface MTRZoneManagementClusterZoneTriggeringTimeControlStruct : NSObject +@interface MTRZoneManagementClusterZoneTriggerControlStruct : NSObject @property (nonatomic, copy) NSNumber * _Nonnull initialDuration MTR_PROVISIONALLY_AVAILABLE; @property (nonatomic, copy) NSNumber * _Nonnull augmentationDuration MTR_PROVISIONALLY_AVAILABLE; @property (nonatomic, copy) NSNumber * _Nonnull maxDuration MTR_PROVISIONALLY_AVAILABLE; @property (nonatomic, copy) NSNumber * _Nonnull blindDuration MTR_PROVISIONALLY_AVAILABLE; +@property (nonatomic, copy) NSNumber * _Nullable sensitivity MTR_PROVISIONALLY_AVAILABLE; @end MTR_PROVISIONALLY_AVAILABLE diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm index e38df789310a97..ddc22861202fc1 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm @@ -8867,7 +8867,7 @@ - (NSString *)description @end -@implementation MTRZoneManagementClusterZoneTriggeringTimeControlStruct +@implementation MTRZoneManagementClusterZoneTriggerControlStruct - (instancetype)init { if (self = [super init]) { @@ -8879,25 +8879,28 @@ - (instancetype)init _maxDuration = @(0); _blindDuration = @(0); + + _sensitivity = nil; } return self; } - (id)copyWithZone:(NSZone * _Nullable)zone { - auto other = [[MTRZoneManagementClusterZoneTriggeringTimeControlStruct alloc] init]; + auto other = [[MTRZoneManagementClusterZoneTriggerControlStruct alloc] init]; other.initialDuration = self.initialDuration; other.augmentationDuration = self.augmentationDuration; other.maxDuration = self.maxDuration; other.blindDuration = self.blindDuration; + other.sensitivity = self.sensitivity; return other; } - (NSString *)description { - NSString * descriptionString = [NSString stringWithFormat:@"<%@: initialDuration:%@; augmentationDuration:%@; maxDuration:%@; blindDuration:%@; >", NSStringFromClass([self class]), _initialDuration, _augmentationDuration, _maxDuration, _blindDuration]; + NSString * descriptionString = [NSString stringWithFormat:@"<%@: initialDuration:%@; augmentationDuration:%@; maxDuration:%@; blindDuration:%@; sensitivity:%@; >", NSStringFromClass([self class]), _initialDuration, _augmentationDuration, _maxDuration, _blindDuration, _sensitivity]; return descriptionString; } diff --git a/src/darwin/Framework/CHIPTests/MTRCertificateTests.m b/src/darwin/Framework/CHIPTests/MTRCertificateTests.m index fb6cfb9ecb7e67..d822028b5c8227 100644 --- a/src/darwin/Framework/CHIPTests/MTRCertificateTests.m +++ b/src/darwin/Framework/CHIPTests/MTRCertificateTests.m @@ -127,9 +127,13 @@ - (void)testGenerateIntermediateCert __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); + __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -155,13 +159,16 @@ - (void)testGenerateIntermediateCertWithValidityPeriod __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * startDate = [MTRCertificateTests startDateWithTimeIntervalSinceNow:300]; __auto_type * validityPeriod = [[NSDateInterval alloc] initWithStartDate:startDate duration:400]; __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil validityPeriod:validityPeriod @@ -192,13 +199,16 @@ - (void)testGenerateIntermediateCertWithInfiniteValidity __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * startDate = [MTRCertificateTests startDateWithTimeIntervalSinceNow:300]; __auto_type * validityPeriod = [[NSDateInterval alloc] initWithStartDate:startDate endDate:[NSDate distantFuture]]; __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil validityPeriod:validityPeriod @@ -229,6 +239,9 @@ - (void)testGenerateOperationalCertNoIntermediate __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * cats = [[NSMutableSet alloc] initWithCapacity:3]; // High bits are identifier, low bits are version. @@ -238,7 +251,7 @@ - (void)testGenerateOperationalCertNoIntermediate __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:cats @@ -265,6 +278,9 @@ - (void)testGenerateOperationalCertNoIntermediateWithValidityPeriod __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * cats = [[NSMutableSet alloc] initWithCapacity:3]; // High bits are identifier, low bits are version. @@ -277,7 +293,7 @@ - (void)testGenerateOperationalCertNoIntermediateWithValidityPeriod __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:cats @@ -309,6 +325,9 @@ - (void)testGenerateOperationalCertNoIntermediateWithInfiniteValidity __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * cats = [[NSMutableSet alloc] initWithCapacity:3]; // High bits are identifier, low bits are version. @@ -321,7 +340,7 @@ - (void)testGenerateOperationalCertNoIntermediateWithInfiniteValidity __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:cats @@ -353,10 +372,13 @@ - (void)testGenerateOperationalCertWithIntermediate __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -364,10 +386,13 @@ - (void)testGenerateOperationalCertWithIntermediate __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:intermediateKeys signingCertificate:intermediateCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:nil @@ -394,6 +419,9 @@ - (void)testGenerateOperationalCertErrorCases __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * longCats = [[NSMutableSet alloc] initWithCapacity:4]; [longCats addObject:@0x00010001]; @@ -415,7 +443,7 @@ - (void)testGenerateOperationalCertErrorCases // Check basic case works __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:nil @@ -425,7 +453,7 @@ - (void)testGenerateOperationalCertErrorCases // CATs too long operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:longCats @@ -435,7 +463,7 @@ - (void)testGenerateOperationalCertErrorCases // Multiple CATs with the same identifier but different versions operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:catsWithSameIdentifier @@ -445,7 +473,7 @@ - (void)testGenerateOperationalCertErrorCases // CAT with invalid version operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:catsWithInvalidVersion @@ -455,7 +483,7 @@ - (void)testGenerateOperationalCertErrorCases // Signing key mismatch operationalCert = [MTRCertificates createOperationalCertificate:operationalKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:nil @@ -465,7 +493,7 @@ - (void)testGenerateOperationalCertErrorCases // Invalid fabric id operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@0 nodeID:@1 caseAuthenticatedTags:nil @@ -475,7 +503,7 @@ - (void)testGenerateOperationalCertErrorCases // Undefined node id operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@0 caseAuthenticatedTags:nil @@ -485,7 +513,7 @@ - (void)testGenerateOperationalCertErrorCases // Non-operational node id operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@(0xFFFFFFFFFFFFFFFFLLU) caseAuthenticatedTags:nil @@ -504,7 +532,16 @@ - (void)testGenerateCSR __auto_type * publicKey = [MTRCertificates publicKeyFromCSR:csr error:nil]; XCTAssertNotNil(publicKey); - SecKeyRef originalKeyRef = [testKeys publicKey]; + SecKeyRef originalKeyRef; + if ([testKeys respondsToSelector:@selector(copyPublicKey)]) { + originalKeyRef = [testKeys copyPublicKey]; + if (originalKeyRef != NULL) { + CFAutorelease(originalKeyRef); + } + } else { + originalKeyRef = [testKeys publicKey]; + } + XCTAssertTrue(originalKeyRef != NULL); NSData * originalPublicKey = (__bridge_transfer NSData *) SecKeyCopyExternalRepresentation(originalKeyRef, nil); diff --git a/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m b/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m index ecc593e8432045..719be071063fbe 100644 --- a/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m +++ b/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m @@ -259,10 +259,13 @@ - (void)initStack:(MTRTestCertificateIssuer *)certificateIssuer __auto_type * controllerOperationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(controllerOperationalKeys); + __auto_type * controllerPublicKey = controllerOperationalKeys.copyPublicKey; + XCTAssert(controllerPublicKey != NULL); + CFAutorelease(controllerPublicKey); __auto_type * controllerOperationalCert = [certificateIssuer issueOperationalCertificateForNode:@(kControllerId) - operationalPublicKey:controllerOperationalKeys.publicKey]; + operationalPublicKey:controllerPublicKey]; XCTAssertNotNil(controllerOperationalCert); __auto_type * params = [[MTRDeviceControllerStartupParams alloc] initWithIPK:certificateIssuer.rootKey.ipk diff --git a/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m b/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m index 4092a38b56f84e..bee6ee90df3524 100644 --- a/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m +++ b/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m @@ -164,10 +164,13 @@ - (nullable MTRDeviceController *)startControllerWithRootKeys:(MTRTestKeys *)roo __auto_type * root = [MTRCertificates createRootCertificate:rootKeys issuerID:@(1) fabricID:nil error:error]; XCTAssertNil(*error); XCTAssertNotNil(root); + __auto_type * publicKey = operationalKeys.copyPublicKey; + XCTAssert(publicKey != NULL); + CFAutorelease(publicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:publicKey fabricID:fabricID nodeID:nodeID caseAuthenticatedTags:nil diff --git a/src/darwin/Framework/CHIPTests/MTRControllerTests.m b/src/darwin/Framework/CHIPTests/MTRControllerTests.m index 436a0df230e3d9..afd755f8e5e757 100644 --- a/src/darwin/Framework/CHIPTests/MTRControllerTests.m +++ b/src/darwin/Framework/CHIPTests/MTRControllerTests.m @@ -620,10 +620,13 @@ - (void)testControllerSignerKeyWithIntermediate __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -860,10 +863,12 @@ - (void)testControllerRotateToICA __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -922,10 +927,13 @@ - (void)testControllerRotateFromICA __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -986,10 +994,13 @@ - (void)testControllerRotateICA __auto_type * intermediateKeys1 = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys1); + __auto_type * intermediate1PublicKey = [intermediateKeys1 copyPublicKey]; + XCTAssert(intermediate1PublicKey != NULL); + CFAutorelease(intermediate1PublicKey); __auto_type * intermediate1 = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys1.publicKey + intermediatePublicKey:intermediate1PublicKey issuerID:nil fabricID:nil error:nil]; @@ -997,10 +1008,13 @@ - (void)testControllerRotateICA __auto_type * intermediateKeys2 = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys2); + __auto_type * intermediate2PublicKey = [intermediateKeys2 copyPublicKey]; + XCTAssert(intermediate2PublicKey != NULL); + CFAutorelease(intermediate2PublicKey); __auto_type * intermediate2 = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys2.publicKey + intermediatePublicKey:intermediate2PublicKey issuerID:nil fabricID:nil error:nil]; @@ -1061,10 +1075,13 @@ - (void)testControllerICAWithoutRoot __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -1104,10 +1121,13 @@ - (void)testControllerProvideFullCertChain __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -1115,10 +1135,13 @@ - (void)testControllerProvideFullCertChain __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:intermediateKeys signingCertificate:intermediate - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil @@ -1179,10 +1202,13 @@ - (void)testControllerProvideCertChainNoICA __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil @@ -1229,10 +1255,13 @@ - (void)testControllerCertChainFabricMismatchRoot __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil @@ -1273,10 +1302,13 @@ - (void)testControllerCertChainFabricMismatchIntermediate __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:@111 error:nil]; @@ -1284,10 +1316,13 @@ - (void)testControllerCertChainFabricMismatchIntermediate __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:intermediateKeys signingCertificate:intermediate - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil diff --git a/src/darwin/Framework/CHIPTests/MTRDeviceTests.m b/src/darwin/Framework/CHIPTests/MTRDeviceTests.m index d5faaec24b63b3..6cabe01cb567ed 100644 --- a/src/darwin/Framework/CHIPTests/MTRDeviceTests.m +++ b/src/darwin/Framework/CHIPTests/MTRDeviceTests.m @@ -1470,6 +1470,7 @@ - (void)test017_TestMTRDeviceBasics __block unsigned eventReportsReceived = 0; __block BOOL reportEnded = NO; __block BOOL gotOneNonPrimingEvent = NO; + __block NSNumber * lastObservedEventNumber = @(0); XCTestExpectation * gotNonPrimingEventExpectation = [self expectationWithDescription:@"Received event outside of priming report"]; delegate.onEventDataReceived = ^(NSArray *> * eventReport) { eventReportsReceived += eventReport.count; @@ -1489,6 +1490,7 @@ - (void)test017_TestMTRDeviceBasics if (!reportEnded) { NSNumber * reportIsHistorical = eventDict[MTREventIsHistoricalKey]; XCTAssertTrue(reportIsHistorical.boolValue); + lastObservedEventNumber = eventDict[MTREventNumberKey]; } else { if (!gotOneNonPrimingEvent) { NSNumber * reportIsHistorical = eventDict[MTREventIsHistoricalKey]; @@ -1509,7 +1511,7 @@ - (void)test017_TestMTRDeviceBasics MTREventTimestampDateKey : [NSDate date], MTREventIsHistoricalKey : @(NO), MTREventPriorityKey : @(MTREventPriorityInfo), - MTREventNumberKey : @(1), // Doesn't matter, in practice + MTREventNumberKey : @(lastObservedEventNumber.unsignedLongLongValue + 1), MTRDataKey : @ { MTRTypeKey : MTRStructureValueType, MTRValueKey : @[], @@ -1586,6 +1588,37 @@ - (void)test017_TestMTRDeviceBasics XCTAssertEqualObjects([NSSet setWithArray:variousThings], [[NSSet setWithArray:clusterRevisions] setByAddingObjectsFromSet:[NSSet setWithArray:basicInformationAllRootAttributes]]); + // Some quick tests for waitForAttributeValues. First, values that we know + // are already there: + XCTestExpectation * deviceTypesWaitExpectation = [self expectationWithDescription:@"deviceTypes is already the value we expect"]; + __auto_type * deviceTypesToWaitFor = [NSMutableDictionary dictionary]; + for (NSDictionary * deviceTypesValue in deviceTypes) { + deviceTypesToWaitFor[deviceTypesValue[MTRAttributePathKey]] = deviceTypesValue[MTRDataKey]; + } + __auto_type * waiter1 = [device waitForAttributeValues:deviceTypesToWaitFor timeout:200 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNil(error); + [deviceTypesWaitExpectation fulfill]; + }]; + XCTAssertNotNil(waiter1); + [self waitForExpectations:@[ deviceTypesWaitExpectation ] timeout:kTimeoutInSeconds]; + + // Now values that we know will never be there (the type is wrong). + __auto_type * bogusDeviceType = @{ + deviceTypes[0][MTRAttributePathKey] : @ { + MTRTypeKey : MTROctetStringValueType, + MTRValueKey : [@"abc" dataUsingEncoding:NSUTF8StringEncoding], + }, + }; + XCTestExpectation * bogusDeviceTypesWaitExpectation = [self expectationWithDescription:@"bogusDeviceTypes wait should time out"]; + __auto_type * waiter2 = [device waitForAttributeValues:bogusDeviceType timeout:0.5 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNotNil(error); + XCTAssertEqual(error.domain, MTRErrorDomain); + XCTAssertEqual(error.code, MTRErrorCodeTimeout); + [bogusDeviceTypesWaitExpectation fulfill]; + }]; + XCTAssertNotNil(waiter2); + [self waitForExpectations:@[ bogusDeviceTypesWaitExpectation ] timeout:kTimeoutInSeconds]; + // Before resubscribe, first test write failure and expected value effects NSNumber * testEndpointID = @(1); NSNumber * testClusterID = @(8); @@ -1610,6 +1643,23 @@ - (void)test017_TestMTRDeviceBasics NSDictionary * writeValue = [NSDictionary dictionaryWithObjectsAndKeys:@"UnsignedInteger", @"type", [NSNumber numberWithUnsignedInteger:200], @"value", nil]; + + // Also test that waitForAttributeValues does not pick up the transition to + // the expected value. + XCTestExpectation * nonexistentAttributeValueWaitExpectation = [self expectationWithDescription:@"waiting for a value for an attribute that does not exist should time out"]; + __auto_type * waiter3 = [device waitForAttributeValues:@{ + [MTRAttributePath attributePathWithEndpointID:testEndpointID clusterID:testClusterID attributeID:testAttributeID] : writeValue, + } + timeout:0.5 + queue:queue + completion:^(NSError * _Nullable error) { + XCTAssertNotNil(error); + XCTAssertEqual(error.domain, MTRErrorDomain); + XCTAssertEqual(error.code, MTRErrorCodeTimeout); + [nonexistentAttributeValueWaitExpectation fulfill]; + }]; + XCTAssertNotNil(waiter3); + [device writeAttributeWithEndpointID:testEndpointID clusterID:testClusterID attributeID:testAttributeID @@ -1619,10 +1669,20 @@ - (void)test017_TestMTRDeviceBasics // expected value interval is 20s but expect it get reverted immediately as the write fails because it's writing to a // nonexistent attribute - [self waitForExpectations:@[ expectedValueReportedExpectation, expectedValueRemovedExpectation ] timeout:5 enforceOrder:YES]; - - // Test if previous value is reported on a write - uint16_t testOnTimeValue = 10; + [self waitForExpectations:@[ expectedValueReportedExpectation, expectedValueRemovedExpectation, nonexistentAttributeValueWaitExpectation ] timeout:5 enforceOrder:YES]; + + // Get the current OnTime value, to make sure we are writing a different one. + __auto_type * currentOnTimeValueDictionary = [device readAttributeWithEndpointID:@(1) + clusterID:@(MTRClusterIDTypeOnOffID) + attributeID:@(MTRAttributeIDTypeClusterOnOffAttributeOnTimeID) + params:nil]; + XCTAssertNotNil(currentOnTimeValueDictionary); + XCTAssertEqualObjects(currentOnTimeValueDictionary[MTRTypeKey], MTRUnsignedIntegerValueType); + uint16_t currentOnTimeValue = [currentOnTimeValueDictionary[MTRValueKey] unsignedShortValue]; + + // Test if previous value is reported on a write. Make sure to write a + // value different from the current one. + uint16_t testOnTimeValue = currentOnTimeValue > 10 ? currentOnTimeValue - 1 : currentOnTimeValue + 1; XCTestExpectation * onTimeWriteSuccess = [self expectationWithDescription:@"OnTime write success"]; XCTestExpectation * onTimePreviousValue = [self expectationWithDescription:@"OnTime previous value"]; delegate.onAttributeDataReceived = ^(NSArray *> * data) { @@ -1643,7 +1703,63 @@ - (void)test017_TestMTRDeviceBasics } } }; - NSDictionary * writeOnTimeValue = @{ MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(testOnTimeValue) }; + __auto_type * writeOnTimeValue = @{ MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(testOnTimeValue) }; + + // Also set up a few attribute value waits to see what happens. + __auto_type * onTimeValueToWaitFor = @{ + [MTRAttributePath attributePathWithEndpointID:@(1) clusterID:@(MTRClusterIDTypeOnOffID) + attributeID:@(MTRAttributeIDTypeClusterOnOffAttributeOnTimeID)] : writeOnTimeValue, + }; + + XCTestExpectation * waitingForOnTimeValue1Expectation = [self expectationWithDescription:@"OnTime value is now the expected value"]; + __auto_type * waiter4 = [device waitForAttributeValues:onTimeValueToWaitFor timeout:200 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNil(error); + [waitingForOnTimeValue1Expectation fulfill]; + }]; + XCTAssertNotNil(waiter4); + + XCTestExpectation * waitingForOnTimeValue2Expectation = [self expectationWithDescription:@"OnTime value is now the expected value and first device type is the expected value"]; + __auto_type * onTimeAndDeviceTypeValuesToWaitFor = [NSMutableDictionary dictionaryWithDictionary:onTimeValueToWaitFor]; + onTimeAndDeviceTypeValuesToWaitFor[deviceTypes[0][MTRAttributePathKey]] = deviceTypes[0][MTRDataKey]; + + __auto_type * waiter5 = [device waitForAttributeValues:onTimeAndDeviceTypeValuesToWaitFor timeout:200 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNil(error); + [waitingForOnTimeValue2Expectation fulfill]; + }]; + XCTAssertNotNil(waiter5); + + XCTestExpectation * waitingForOnTimeValue3Expectation = [self expectationWithDescription:@"OnTime value is now the expected value and first device type is bogus, or we timed out"]; + __auto_type * onTimeAndBogusDeviceTypeValuesToWaitFor = [NSMutableDictionary dictionaryWithDictionary:onTimeValueToWaitFor]; + [onTimeAndBogusDeviceTypeValuesToWaitFor addEntriesFromDictionary:bogusDeviceType]; + __auto_type * waiter6 = [device waitForAttributeValues:onTimeAndBogusDeviceTypeValuesToWaitFor timeout:0.5 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNotNil(error); + XCTAssertEqual(error.domain, MTRErrorDomain); + XCTAssertEqual(error.code, MTRErrorCodeTimeout); + [waitingForOnTimeValue3Expectation fulfill]; + }]; + XCTAssertNotNil(waiter6); + + XCTestExpectation * waitingForOnTimeValue4Expectation = [self expectationWithDescription:@"Waiter should have been canceled"]; + __auto_type * waiter7 = [device waitForAttributeValues:onTimeValueToWaitFor timeout:200 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNotNil(error); + XCTAssertEqual(error.domain, MTRErrorDomain); + XCTAssertEqual(error.code, MTRErrorCodeCancelled); + [waitingForOnTimeValue4Expectation fulfill]; + }]; + XCTAssertNotNil(waiter7); + [waiter7 cancel]; + + XCTestExpectation * waitingForOnTimeValue5Expectation = [self expectationWithDescription:@"Waiter should have been canceled due to being destroyed"]; + @autoreleasepool { + // To force the waiter created here to die quickly. + [device waitForAttributeValues:onTimeValueToWaitFor timeout:200 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNotNil(error); + XCTAssertEqual(error.domain, MTRErrorDomain); + XCTAssertEqual(error.code, MTRErrorCodeCancelled); + [waitingForOnTimeValue5Expectation fulfill]; + }]; + } + [device writeAttributeWithEndpointID:@(1) clusterID:@(MTRClusterIDTypeOnOffID) attributeID:@(MTRAttributeIDTypeClusterOnOffAttributeOnTimeID) @@ -1651,7 +1767,16 @@ - (void)test017_TestMTRDeviceBasics expectedValueInterval:@(10000) timedWriteTimeout:nil]; - [self waitForExpectations:@[ onTimeWriteSuccess, onTimePreviousValue ] timeout:10]; + [self waitForExpectations:@[ + onTimeWriteSuccess, + onTimePreviousValue, + waitingForOnTimeValue1Expectation, + waitingForOnTimeValue2Expectation, + waitingForOnTimeValue3Expectation, + waitingForOnTimeValue4Expectation, + waitingForOnTimeValue5Expectation, + ] + timeout:10]; __auto_type getOnOffValue = ^{ return [device readAttributeWithEndpointID:@(1) @@ -3776,6 +3901,70 @@ - (void)test034_TestMTRDeviceHistoricalEvents // Must have gotten some events (at least StartUp!) XCTAssertTrue(eventReportsReceived > 0); + + // Now try doing some event injection. + __block uint64_t eventNumber = 0x1000000; // Should't have that many events on the device yet! + __block uint64_t firstNewEventNumber = eventNumber; + __auto_type createEventReport = ^{ + return @{ + MTREventPathKey : [MTREventPath eventPathWithEndpointID:@(1) clusterID:@(1) eventID:@(1)], + MTREventTimeTypeKey : @(MTREventTimeTypeTimestampDate), + MTREventTimestampDateKey : [NSDate date], + MTREventPriorityKey : @(MTREventPriorityInfo), + MTREventNumberKey : @(eventNumber++), + MTRDataKey : @ { + MTRTypeKey : MTRStructureValueType, + MTRValueKey : @[], + }, + }; + }; + + eventReportsReceived = 0; + const int eventReportsToInject = 5; + __block XCTestExpectation * eventReportsFinishedExpectation = [self expectationWithDescription:@"Injecting some new event reports"]; + __block int historicalEvents = 0; + __block int eventReportsToExpect = eventReportsToInject; + + delegate.onEventDataReceived = ^(NSArray *> * eventReport) { + eventReportsReceived += eventReport.count; + for (NSDictionary * eventDict in eventReport) { + NSNumber * reportIsHistorical = eventDict[MTREventIsHistoricalKey]; + NSNumber * eventNumber = eventDict[MTREventNumberKey]; + XCTAssertEqual(reportIsHistorical.boolValue, eventNumber.unsignedLongLongValue < firstNewEventNumber, + @"eventNumber: %@, firstNewEventNumber: %llu", eventNumber, firstNewEventNumber); + historicalEvents += reportIsHistorical.boolValue; + } + + if (eventReportsReceived >= eventReportsToExpect) { + [eventReportsFinishedExpectation fulfill]; + } + }; + + for (int i = 0; i < eventReportsToInject; ++i) { + [device unitTestInjectEventReport:@[ createEventReport() ]]; + } + + [self waitForExpectations:@[ eventReportsFinishedExpectation ] timeout:kTimeoutInSeconds]; + XCTAssertEqual(historicalEvents, 0); + + // Now inject some mix of historical and non-historical events. Since this + // includes events with old event numbers, those should get filtered out + // from reporting. + const uint64_t expectedHistoricalEvents = 2; + firstNewEventNumber = eventNumber; + eventNumber -= expectedHistoricalEvents; + eventReportsReceived = 0; + historicalEvents = 0; + // Events with already-observed event numbers do not get reported. + eventReportsToExpect = eventReportsToInject - expectedHistoricalEvents; + eventReportsFinishedExpectation = [self expectationWithDescription:@"Injecting a mix of old and new reports"]; + + for (int i = 0; i < eventReportsToInject; ++i) { + [device unitTestInjectEventReport:@[ createEventReport() ]]; + } + + [self waitForExpectations:@[ eventReportsFinishedExpectation ] timeout:kTimeoutInSeconds]; + XCTAssertEqual(historicalEvents, 0); } - (void)test035_TestMTRDeviceSubscriptionNotEstablishedOverXPC @@ -4143,13 +4332,17 @@ - (void)test037_MTRDeviceMultipleDelegatesGetReports - (NSDictionary *)_testEventResponseValueWithEndpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID eventID:(NSNumber *)eventID { + // Pick a large event number, so that in practice these event reports will + // all have larger event numbers than anything that might have been observed + // before. + static uint64_t eventNumber = 0x100000000llu; return @{ MTREventPathKey : [MTREventPath eventPathWithEndpointID:endpointID clusterID:clusterID eventID:eventID], MTREventTimeTypeKey : @(MTREventTimeTypeTimestampDate), MTREventTimestampDateKey : [NSDate date], MTREventIsHistoricalKey : @(NO), MTREventPriorityKey : @(MTREventPriorityInfo), - MTREventNumberKey : @(1), // Doesn't matter, in practice + MTREventNumberKey : @(eventNumber++), // Empty payload. MTRDataKey : @ { MTRTypeKey : MTRStructureValueType, @@ -5457,6 +5650,19 @@ - (void)test044_InvokeResponseWellFormedness ], @"valid" : @(YES), }, + @{ + @"input" : @[ + @{ + @"commandPath" : [MTRCommandPath commandPathWithEndpointID:@(0) clusterID:@(6) commandID:@(0)], + @"data" : @ { + @"type" : @"Structure", + @"value" : @[], // Empty structure, valid + }, + }, + ], + // Same as the previous test, but not using the SDK string constants + @"valid" : @(YES), + }, @{ @"input" : @[ @{ diff --git a/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m b/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m index a98067098688b5..acdc0ea45ff572 100644 --- a/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m +++ b/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m @@ -157,10 +157,13 @@ - (void)testFabricInfoTwoFabrics __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; diff --git a/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m b/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m index 1ead4692a2b335..3d91a64712e32f 100644 --- a/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m +++ b/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m @@ -403,13 +403,18 @@ - (nullable MTRDeviceController *)startControllerWithRootKeys:(MTRTestKeys *)roo XCTAssertNil(*error); XCTAssertNotNil(root); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:fabricID nodeID:nodeID caseAuthenticatedTags:caseAuthenticatedTags error:error]; + CFRelease(operationalPublicKey); + XCTAssertNil(*error); XCTAssertNotNil(operational); diff --git a/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m b/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m index e6a74f25bdeccf..090593a41babfb 100644 --- a/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m +++ b/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m @@ -31,6 +31,12 @@ - (NSData *)publicKeyData return (__bridge_transfer NSData *) SecKeyCopyExternalRepresentation([self publicKey], nil); } +- (SecKeyRef)copyPublicKey +{ + CFRetain(_publicKey); + return _publicKey; +} + - (instancetype)init { if (!(self = [super init])) { diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index 195dd8e2757316..fa1634da4b9267 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -161,6 +161,9 @@ 5143851E2A65885500EDC8E6 /* MTRSwiftPairingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5143851D2A65885500EDC8E6 /* MTRSwiftPairingTests.swift */; }; 514654492A72F9DF00904E61 /* MTRDemuxingStorage.mm in Sources */ = {isa = PBXBuildFile; fileRef = 514654482A72F9DF00904E61 /* MTRDemuxingStorage.mm */; }; 5146544B2A72F9F500904E61 /* MTRDemuxingStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 5146544A2A72F9F500904E61 /* MTRDemuxingStorage.h */; }; + 514A98AF2CD98C5E000EF4FD /* MTRAttributeValueWaiter.h in Headers */ = {isa = PBXBuildFile; fileRef = 514A98AC2CD98C5E000EF4FD /* MTRAttributeValueWaiter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 514A98B02CD98C5E000EF4FD /* MTRAttributeValueWaiter_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 514A98AE2CD98C5E000EF4FD /* MTRAttributeValueWaiter_Internal.h */; }; + 514A98B12CD98C5E000EF4FD /* MTRAttributeValueWaiter.mm in Sources */ = {isa = PBXBuildFile; fileRef = 514A98AD2CD98C5E000EF4FD /* MTRAttributeValueWaiter.mm */; }; 514C79F02B62ADDA00DD6D7B /* descriptor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79EF2B62ADDA00DD6D7B /* descriptor.cpp */; }; 514C79F12B62ADDA00DD6D7B /* descriptor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79EF2B62ADDA00DD6D7B /* descriptor.cpp */; }; 514C79F32B62ED5500DD6D7B /* attribute-storage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79F22B62ED5500DD6D7B /* attribute-storage.cpp */; }; @@ -639,6 +642,9 @@ 5143851D2A65885500EDC8E6 /* MTRSwiftPairingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MTRSwiftPairingTests.swift; sourceTree = ""; }; 514654482A72F9DF00904E61 /* MTRDemuxingStorage.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDemuxingStorage.mm; sourceTree = ""; }; 5146544A2A72F9F500904E61 /* MTRDemuxingStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRDemuxingStorage.h; sourceTree = ""; }; + 514A98AC2CD98C5E000EF4FD /* MTRAttributeValueWaiter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRAttributeValueWaiter.h; sourceTree = ""; }; + 514A98AD2CD98C5E000EF4FD /* MTRAttributeValueWaiter.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRAttributeValueWaiter.mm; sourceTree = ""; }; + 514A98AE2CD98C5E000EF4FD /* MTRAttributeValueWaiter_Internal.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRAttributeValueWaiter_Internal.h; sourceTree = ""; }; 514C79EF2B62ADDA00DD6D7B /* descriptor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = descriptor.cpp; path = clusters/descriptor/descriptor.cpp; sourceTree = ""; }; 514C79F22B62ED5500DD6D7B /* attribute-storage.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = "attribute-storage.cpp"; path = "util/attribute-storage.cpp"; sourceTree = ""; }; 514C79F52B62F0B900DD6D7B /* util.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = util.cpp; path = util/util.cpp; sourceTree = ""; }; @@ -1389,6 +1395,9 @@ 7596A84728762783004DAE0E /* MTRAsyncCallbackWorkQueue.mm */, 3DA1A3522ABAB3B4004F0BB9 /* MTRAsyncWorkQueue.h */, 3DA1A3532ABAB3B4004F0BB9 /* MTRAsyncWorkQueue.mm */, + 514A98AC2CD98C5E000EF4FD /* MTRAttributeValueWaiter.h */, + 514A98AD2CD98C5E000EF4FD /* MTRAttributeValueWaiter.mm */, + 514A98AE2CD98C5E000EF4FD /* MTRAttributeValueWaiter_Internal.h */, 3CF134AA289D8DF70017A19E /* MTRDeviceAttestationInfo.h */, 3CF134AC289D8E570017A19E /* MTRDeviceAttestationInfo.mm */, 27A53C1527FBC6920053F131 /* MTRAttestationTrustStoreBridge.h */, @@ -1831,6 +1840,8 @@ B2E0D7B1245B0B5C003C5B48 /* Matter.h in Headers */, 7596A84428762729004DAE0E /* MTRDevice.h in Headers */, B2E0D7B8245B0B5C003C5B48 /* MTRSetupPayload.h in Headers */, + 514A98AF2CD98C5E000EF4FD /* MTRAttributeValueWaiter.h in Headers */, + 514A98B02CD98C5E000EF4FD /* MTRAttributeValueWaiter_Internal.h in Headers */, 1E4D654F29C208DD00BC3478 /* MTRCommissionableBrowser.h in Headers */, 3D843756294AD25A0070D20A /* MTRCertificateInfo.h in Headers */, 7596A83E28751220004DAE0E /* MTRBaseClusters_Internal.h in Headers */, @@ -2195,6 +2206,7 @@ 88E6C9482B6334ED001A1FE0 /* MTRMetrics.mm in Sources */, 1ED276E226C5812A00547A89 /* MTRCluster.mm in Sources */, 9BFE5D512C6D3075007D4319 /* MTRDeviceController_XPC.mm in Sources */, + 514A98B12CD98C5E000EF4FD /* MTRAttributeValueWaiter.mm in Sources */, B2E0D7B3245B0B5C003C5B48 /* MTRError.mm in Sources */, 51E51FC1282AD37A00FC978D /* MTRDeviceControllerStartupParams.mm in Sources */, 51565CAE2A79D42100469F18 /* MTRConversion.mm in Sources */, diff --git a/src/darwin/Framework/chip_xcode_build_connector.sh b/src/darwin/Framework/chip_xcode_build_connector.sh index 0c08ab381b32f4..7e8e72d213d685 100755 --- a/src/darwin/Framework/chip_xcode_build_connector.sh +++ b/src/darwin/Framework/chip_xcode_build_connector.sh @@ -187,6 +187,12 @@ esac ) } +[[ $CHIP_USE_NETWORK_FRAMEWORK == YES ]] && { + args+=( + 'chip_system_config_use_network_framework=true' + ) +} + # search current (or $2) and its parent directories until # a name match is found, which is output on stdout find_in_ancestors() { diff --git a/src/inet/BUILD.gn b/src/inet/BUILD.gn index e30d417ffc0b39..ede5d383734566 100644 --- a/src/inet/BUILD.gn +++ b/src/inet/BUILD.gn @@ -158,11 +158,16 @@ static_library("inet") { "EndpointQueueFilter.h", "UDPEndPoint.cpp", "UDPEndPoint.h", - "UDPEndPointImpl${chip_system_config_inet}.cpp", "UDPEndPointImpl${chip_system_config_inet}.h", "UDPEndPointImpl.h", ] + if (chip_system_config_use_network_framework) { + sources += [ "UDPEndPointImpl${chip_system_config_inet}.mm" ] + } else { + sources += [ "UDPEndPointImpl${chip_system_config_inet}.cpp" ] + } + if (chip_system_config_inet == "Sockets") { # TODO: dependency on this one is not clear as it is only ever # enabled through CMakeLists.txt. Added here for completeness @@ -187,5 +192,7 @@ static_library("inet") { cflags = [ "-Wconversion" ] if (current_os == "nuttx") { cflags -= [ "-Wconversion" ] + } else if (chip_system_config_use_network_framework) { + cflags += [ "-fobjc-arc" ] } } diff --git a/src/inet/IPAddress-StringFuncts.cpp b/src/inet/IPAddress-StringFuncts.cpp index 7022b44a6aaf60..2a7ff008a3c552 100644 --- a/src/inet/IPAddress-StringFuncts.cpp +++ b/src/inet/IPAddress-StringFuncts.cpp @@ -32,7 +32,7 @@ #include #include -#if CHIP_SYSTEM_CONFIG_USE_POSIX_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK +#if CHIP_SYSTEM_CONFIG_USE_POSIX_SOCKETS #include #endif @@ -54,7 +54,7 @@ char * IPAddress::ToString(char * buf, uint32_t bufSize) const ip6_addr_t ip6_addr = ToIPv6(); ip6addr_ntoa_r(&ip6_addr, buf, (int) bufSize); } -#elif CHIP_SYSTEM_CONFIG_USE_SOCKETS +#elif CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK // socklen_t is sometimes signed, sometimes not, so the only safe way to do // this is to promote everything to an unsigned type that's known to be big // enough for everything, then cast back to uint32_t after taking the min. @@ -93,7 +93,7 @@ bool IPAddress::FromString(const char * str, IPAddress & output) ip4_addr_t ipv4Addr; if (!ip4addr_aton(str, &ipv4Addr)) return false; -#elif CHIP_SYSTEM_CONFIG_USE_SOCKETS +#elif CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK struct in_addr ipv4Addr; if (inet_pton(AF_INET, str, &ipv4Addr) < 1) return false; @@ -107,7 +107,7 @@ bool IPAddress::FromString(const char * str, IPAddress & output) ip6_addr_t ipv6Addr; if (!ip6addr_aton(str, &ipv6Addr)) return false; -#elif CHIP_SYSTEM_CONFIG_USE_SOCKETS +#elif CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK struct in6_addr ipv6Addr; if (inet_pton(AF_INET6, str, &ipv6Addr) < 1) return false; diff --git a/src/inet/IPAddress.h b/src/inet/IPAddress.h index 2b756ef5561b99..03a40394b5e80b 100644 --- a/src/inet/IPAddress.h +++ b/src/inet/IPAddress.h @@ -56,12 +56,9 @@ #include #endif // CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT -#if CHIP_SYSTEM_CONFIG_USE_POSIX_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK +#if CHIP_SYSTEM_CONFIG_USE_POSIX_SOCKETS #include #include -#endif // CHIP_SYSTEM_CONFIG_USE_POSIX_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK - -#if CHIP_SYSTEM_CONFIG_USE_POSIX_SOCKETS #include #endif // CHIP_SYSTEM_CONFIG_USE_POSIX_SOCKETS @@ -110,7 +107,7 @@ enum class IPv6MulticastFlag : uint8_t }; using IPv6MulticastFlags = BitFlags; -#if CHIP_SYSTEM_CONFIG_USE_SOCKETS +#if CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK /** * SockAddr should be used when calling any API that returns (by copying into * it) a sockaddr, because that will need enough storage that it can hold data @@ -139,7 +136,7 @@ union SockAddrWithoutStorage sockaddr_in in; sockaddr_in6 in6; }; -#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS +#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK /** * @brief Internet protocol address diff --git a/src/inet/InetInterface.cpp b/src/inet/InetInterface.cpp index af89de8cb96822..4595dfef449fe3 100644 --- a/src/inet/InetInterface.cpp +++ b/src/inet/InetInterface.cpp @@ -38,7 +38,7 @@ #include #endif // CHIP_SYSTEM_CONFIG_USE_LWIP -#if CHIP_SYSTEM_CONFIG_USE_SOCKETS && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS +#if (CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK) && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS #include #include #include @@ -50,7 +50,7 @@ #include #include #include -#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS +#endif // (CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK) && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS #if CHIP_SYSTEM_CONFIG_USE_ZEPHYR_NET_IF #include @@ -434,7 +434,7 @@ CHIP_ERROR InterfaceId::GetLinkLocalAddr(IPAddress * llAddr) const #endif // CHIP_SYSTEM_CONFIG_USE_LWIP -#if CHIP_SYSTEM_CONFIG_USE_SOCKETS && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS +#if (CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK) && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS CHIP_ERROR InterfaceId::GetInterfaceName(char * nameBuf, size_t nameBufSize) const { @@ -788,7 +788,7 @@ CHIP_ERROR InterfaceId::GetLinkLocalAddr(IPAddress * llAddr) const return (found) ? CHIP_NO_ERROR : INET_ERROR_ADDRESS_NOT_FOUND; } -#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS +#endif // (CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK) && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS #if CHIP_SYSTEM_CONFIG_USE_ZEPHYR_NET_IF diff --git a/src/inet/InetInterface.h b/src/inet/InetInterface.h index 9603ba80c3ed05..82f3797a8dc769 100644 --- a/src/inet/InetInterface.h +++ b/src/inet/InetInterface.h @@ -85,7 +85,7 @@ class InterfaceId static constexpr size_t kMaxIfNameLength = 13; // Names are formatted as %c%c%d #endif // CHIP_SYSTEM_CONFIG_USE_LWIP -#if CHIP_SYSTEM_CONFIG_USE_SOCKETS && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS +#if (CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK) && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS using PlatformType = unsigned int; static constexpr size_t kMaxIfNameLength = IF_NAMESIZE; #endif // CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS diff --git a/src/inet/InetInterfaceImpl.h b/src/inet/InetInterfaceImpl.h index 4d310c998c0107..00c29cff158e61 100644 --- a/src/inet/InetInterfaceImpl.h +++ b/src/inet/InetInterfaceImpl.h @@ -19,7 +19,7 @@ #include -#if CHIP_SYSTEM_CONFIG_USE_SOCKETS && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS +#if (CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK) && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS #include namespace chip { diff --git a/src/inet/InetInterfaceImplDefault.cpp b/src/inet/InetInterfaceImplDefault.cpp index 461cbe1b0a3ace..91eafed8001cf7 100644 --- a/src/inet/InetInterfaceImplDefault.cpp +++ b/src/inet/InetInterfaceImplDefault.cpp @@ -16,7 +16,7 @@ */ #include -#if CHIP_SYSTEM_CONFIG_USE_SOCKETS && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS +#if (CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK) && CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS #include namespace chip { namespace Inet { diff --git a/src/inet/UDPEndPointImplNetworkFramework.cpp b/src/inet/UDPEndPointImplNetworkFramework.cpp deleted file mode 100644 index 35f6d135a0fc08..00000000000000 --- a/src/inet/UDPEndPointImplNetworkFramework.cpp +++ /dev/null @@ -1,533 +0,0 @@ -/* - * - * Copyright (c) 2020-2021 Project CHIP Authors - * Copyright (c) 2018 Google LLC. - * Copyright (c) 2013-2018 Nest Labs, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * This file implements Inet::UDPEndPoint using Network Framework. - */ - -#define __APPLE_USE_RFC_3542 -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#define INET_PORTSTRLEN 6 - -namespace chip { -namespace Inet { - -CHIP_ERROR UDPEndPointImplNetworkFramework::BindImpl(IPAddressType addressType, const IPAddress & address, uint16_t port, - InterfaceId intfId) -{ - nw_parameters_configure_protocol_block_t configure_tls; - nw_parameters_t parameters; - - if (intfId.IsPresent()) - { - return CHIP_ERROR_NOT_IMPLEMENTED; - } - - configure_tls = NW_PARAMETERS_DISABLE_PROTOCOL; - parameters = nw_parameters_create_secure_udp(configure_tls, NW_PARAMETERS_DEFAULT_CONFIGURATION); - VerifyOrReturnError(parameters != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - - ReturnErrorOnFailure(ConfigureProtocol(addressType, parameters)); - - nw_endpoint_t endpoint = nullptr; - CHIP_ERROR res = GetEndPoint(endpoint, addressType, address, port); - nw_parameters_set_local_endpoint(parameters, endpoint); - nw_release(endpoint); - ReturnErrorOnFailure(res); - - mDispatchQueue = dispatch_queue_create("inet_dispatch_global", DISPATCH_QUEUE_CONCURRENT); - VerifyOrReturnError(mDispatchQueue != nullptr, CHIP_ERROR_NO_MEMORY); - dispatch_retain(mDispatchQueue); - - mConnectionSemaphore = dispatch_semaphore_create(0); - VerifyOrReturnError(mConnectionSemaphore != nullptr, CHIP_ERROR_NO_MEMORY); - dispatch_retain(mConnectionSemaphore); - - mSendSemaphore = dispatch_semaphore_create(0); - VerifyOrReturnError(mSendSemaphore != nullptr, CHIP_ERROR_NO_MEMORY); - dispatch_retain(mSendSemaphore); - - mAddrType = addressType; - mConnection = nullptr; - mParameters = parameters; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::BindInterfaceImpl(IPAddressType addrType, InterfaceId intfId) -{ - return INET_ERROR_UNKNOWN_INTERFACE; -} - -InterfaceId UDPEndPointImplNetworkFramework::GetBoundInterface() const -{ - return InterfaceId::Null(); -} - -uint16_t UDPEndPointImplNetworkFramework::GetBoundPort() const -{ - nw_endpoint_t endpoint = nw_parameters_copy_local_endpoint(mParameters); - return nw_endpoint_get_port(endpoint); -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::ListenImpl() -{ - return StartListener(); -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::SendMsgImpl(const IPPacketInfo * pktInfo, System::PacketBufferHandle && msg) -{ - dispatch_data_t content; - - // Ensure the destination address type is compatible with the endpoint address type. - VerifyOrReturnError(mAddrType == pktInfo->DestAddress.Type(), CHIP_ERROR_INVALID_ARGUMENT); - - // For now the entire message must fit within a single buffer. - VerifyOrReturnError(msg->Next() == nullptr, CHIP_ERROR_MESSAGE_TOO_LONG); - - ReturnErrorOnFailure(GetConnection(pktInfo)); - - // Send a message, and wait for it to be dispatched. - content = dispatch_data_create(msg->Start(), msg->DataLength(), mDispatchQueue, DISPATCH_DATA_DESTRUCTOR_DEFAULT); - - // If there is a current message pending and the state of the network connection change (e.g switch to a - // different network) the connection will enter a nw_connection_state_failed state and the completion handler - // will never be called. In such cases a signal is sent from the connection state change handler to release - // the semaphore. In this case the CHIP_ERROR will not update with the result of the completion handler. - // To make sure caller knows that sending a message has failed the following code consider there is an error - // _unless_ the completion handler says otherwise. - __block CHIP_ERROR res = CHIP_ERROR_UNEXPECTED_EVENT; - nw_connection_send(mConnection, content, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, ^(nw_error_t error) { - if (error) - { - res = CHIP_ERROR_POSIX(nw_error_get_error_code(error)); - } - else - { - res = CHIP_NO_ERROR; - } - dispatch_semaphore_signal(mSendSemaphore); - }); - dispatch_release(content); - - dispatch_semaphore_wait(mSendSemaphore, DISPATCH_TIME_FOREVER); - - return res; -} - -void UDPEndPointImplNetworkFramework::CloseImpl() -{ - ReleaseAll(); -} - -void UDPEndPointImplNetworkFramework::ReleaseAll() -{ - - OnMessageReceived = nullptr; - OnReceiveError = nullptr; - - ReleaseConnection(); - ReleaseListener(); - - if (mParameters) - { - nw_release(mParameters); - mParameters = nullptr; - } - - if (mDispatchQueue) - { - dispatch_suspend(mDispatchQueue); - dispatch_release(mDispatchQueue); - mDispatchQueue = nullptr; - } - - if (mConnectionSemaphore) - { - dispatch_release(mConnectionSemaphore); - mConnectionSemaphore = nullptr; - } - - if (mListenerQueue) - { - dispatch_suspend(mListenerQueue); - dispatch_release(mListenerQueue); - mListenerQueue = nullptr; - } - - if (mListenerSemaphore) - { - dispatch_release(mListenerSemaphore); - mListenerSemaphore = nullptr; - } - - if (mSendSemaphore) - { - dispatch_release(mSendSemaphore); - mSendSemaphore = nullptr; - } -} - -void UDPEndPointImplNetworkFramework::Free() -{ - Close(); - Release(); -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::SetMulticastLoopback(IPVersion aIPVersion, bool aLoopback) -{ - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -#if INET_CONFIG_ENABLE_IPV4 -CHIP_ERROR UDPEndPointImplNetworkFramework::IPv4JoinLeaveMulticastGroupImpl(InterfaceId aInterfaceId, const IPAddress & aAddress, - bool join) -{ - return CHIP_ERROR_NOT_IMPLEMENTED; -} -#endif // INET_CONFIG_ENABLE_IPV4 - -CHIP_ERROR UDPEndPointImplNetworkFramework::IPv6JoinLeaveMulticastGroupImpl(InterfaceId aInterfaceId, const IPAddress & aAddress, - bool join) -{ - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::ConfigureProtocol(IPAddressType aAddressType, const nw_parameters_t & aParameters) -{ - CHIP_ERROR res = CHIP_NO_ERROR; - - nw_protocol_stack_t protocolStack = nw_parameters_copy_default_protocol_stack(aParameters); - nw_protocol_options_t ipOptions = nw_protocol_stack_copy_internet_protocol(protocolStack); - - switch (aAddressType) - { - - case IPAddressType::kIPv6: - nw_ip_options_set_version(ipOptions, nw_ip_version_6); - break; - -#if INET_CONFIG_ENABLE_IPV4 - case IPAddressType::kIPv4: - nw_ip_options_set_version(ipOptions, nw_ip_version_4); - break; -#endif // INET_CONFIG_ENABLE_IPV4 - - default: - res = INET_ERROR_WRONG_ADDRESS_TYPE; - break; - } - nw_release(ipOptions); - nw_release(protocolStack); - - return res; -} - -void UDPEndPointImplNetworkFramework::GetPacketInfo(const nw_connection_t & aConnection, IPPacketInfo & aPacketInfo) -{ - nw_path_t path = nw_connection_copy_current_path(aConnection); - nw_endpoint_t dest_endpoint = nw_path_copy_effective_local_endpoint(path); - nw_endpoint_t src_endpoint = nw_path_copy_effective_remote_endpoint(path); - - aPacketInfo.Clear(); - aPacketInfo.SrcAddress = IPAddress::FromSockAddr(*nw_endpoint_get_address(src_endpoint)); - aPacketInfo.DestAddress = IPAddress::FromSockAddr(*nw_endpoint_get_address(dest_endpoint)); - aPacketInfo.SrcPort = nw_endpoint_get_port(src_endpoint); - aPacketInfo.DestPort = nw_endpoint_get_port(dest_endpoint); -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::GetEndPoint(nw_endpoint_t & aEndPoint, const IPAddressType aAddressType, - const IPAddress & aAddress, uint16_t aPort) -{ - char addrStr[INET6_ADDRSTRLEN]; - char portStr[INET_PORTSTRLEN]; - - // Note: aAddress.ToString will return the IPv6 Any address if the address type is Any, but that's not what - // we want if the locale endpoint is IPv4. - if (aAddressType == IPAddressType::kIPv4 && aAddress.Type() == IPAddressType::kAny) - { - const IPAddress anyAddr = IPAddress(aAddress.ToIPv4()); - anyAddr.ToString(addrStr, sizeof(addrStr)); - } - else - { - aAddress.ToString(addrStr, sizeof(addrStr)); - } - - snprintf(portStr, sizeof(portStr), "%u", aPort); - - aEndPoint = nw_endpoint_create_host(addrStr, portStr); - VerifyOrReturnError(aEndPoint != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::GetConnection(const IPPacketInfo * aPktInfo) -{ - VerifyOrReturnError(mParameters != nullptr, CHIP_ERROR_INCORRECT_STATE); - - nw_endpoint_t endpoint = nullptr; - nw_connection_t connection = nullptr; - - if (mConnection) - { - nw_path_t path = nw_connection_copy_current_path(mConnection); - nw_endpoint_t remote_endpoint = nw_path_copy_effective_remote_endpoint(path); - const IPAddress remote_address = IPAddress::FromSockAddr(*nw_endpoint_get_address(remote_endpoint)); - const uint16_t remote_port = nw_endpoint_get_port(remote_endpoint); - const bool isDifferentEndPoint = aPktInfo->DestPort != remote_port || aPktInfo->DestAddress != remote_address; - VerifyOrReturnError(isDifferentEndPoint, CHIP_NO_ERROR); - - ReturnErrorOnFailure(ReleaseConnection()); - } - - ReturnErrorOnFailure(GetEndPoint(endpoint, mAddrType, aPktInfo->DestAddress, aPktInfo->DestPort)); - - connection = nw_connection_create(endpoint, mParameters); - nw_release(endpoint); - - VerifyOrReturnError(connection != nullptr, CHIP_ERROR_INCORRECT_STATE); - - return StartConnection(connection); -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::StartListener() -{ - __block CHIP_ERROR res = CHIP_NO_ERROR; - nw_listener_t listener; - - VerifyOrReturnError(mListener == nullptr, CHIP_ERROR_INCORRECT_STATE); - VerifyOrReturnError(mListenerSemaphore == nullptr, CHIP_ERROR_INCORRECT_STATE); - VerifyOrReturnError(mListenerQueue == nullptr, CHIP_ERROR_INCORRECT_STATE); - - listener = nw_listener_create(mParameters); - VerifyOrReturnError(listener != nullptr, CHIP_ERROR_INCORRECT_STATE); - - mListenerSemaphore = dispatch_semaphore_create(0); - VerifyOrReturnError(mListenerSemaphore != nullptr, CHIP_ERROR_NO_MEMORY); - dispatch_retain(mListenerSemaphore); - - mListenerQueue = dispatch_queue_create("inet_dispatch_listener", DISPATCH_QUEUE_CONCURRENT); - VerifyOrReturnError(mListenerQueue != nullptr, CHIP_ERROR_NO_MEMORY); - dispatch_retain(mListenerQueue); - - nw_listener_set_queue(listener, mListenerQueue); - - nw_listener_set_new_connection_handler(listener, ^(nw_connection_t connection) { - ReleaseConnection(); - StartConnection(connection); - }); - - nw_listener_set_state_changed_handler(listener, ^(nw_listener_state_t state, nw_error_t error) { - switch (state) - { - - case nw_listener_state_invalid: - ChipLogDetail(Inet, "Listener: Invalid"); - res = CHIP_ERROR_INCORRECT_STATE; - nw_listener_cancel(listener); - break; - - case nw_listener_state_waiting: - ChipLogDetail(Inet, "Listener: Waiting"); - break; - - case nw_listener_state_failed: - ChipLogDetail(Inet, "Listener: Failed"); - res = CHIP_ERROR_POSIX(nw_error_get_error_code(error)); - break; - - case nw_listener_state_ready: - ChipLogDetail(Inet, "Listener: Ready"); - res = CHIP_NO_ERROR; - dispatch_semaphore_signal(mListenerSemaphore); - break; - - case nw_listener_state_cancelled: - ChipLogDetail(Inet, "Listener: Cancelled"); - if (res == CHIP_NO_ERROR) - { - res = CHIP_ERROR_CONNECTION_ABORTED; - } - - dispatch_semaphore_signal(mListenerSemaphore); - break; - } - }); - - nw_listener_start(listener); - dispatch_semaphore_wait(mListenerSemaphore, DISPATCH_TIME_FOREVER); - ReturnErrorOnFailure(res); - - mListener = listener; - nw_retain(mListener); - return res; -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::StartConnection(nw_connection_t & aConnection) -{ - __block CHIP_ERROR res = CHIP_NO_ERROR; - - nw_connection_set_queue(aConnection, mDispatchQueue); - - nw_connection_set_state_changed_handler(aConnection, ^(nw_connection_state_t state, nw_error_t error) { - switch (state) - { - - case nw_connection_state_invalid: - ChipLogDetail(Inet, "Connection: Invalid"); - res = CHIP_ERROR_INCORRECT_STATE; - nw_connection_cancel(aConnection); - break; - - case nw_connection_state_preparing: - ChipLogDetail(Inet, "Connection: Preparing"); - res = CHIP_ERROR_INCORRECT_STATE; - break; - - case nw_connection_state_waiting: - ChipLogDetail(Inet, "Connection: Waiting"); - nw_connection_cancel(aConnection); - break; - - case nw_connection_state_failed: - ChipLogDetail(Inet, "Connection: Failed"); - res = CHIP_ERROR_POSIX(nw_error_get_error_code(error)); - break; - - case nw_connection_state_ready: - ChipLogDetail(Inet, "Connection: Ready"); - res = CHIP_NO_ERROR; - dispatch_semaphore_signal(mConnectionSemaphore); - break; - - case nw_connection_state_cancelled: - ChipLogDetail(Inet, "Connection: Cancelled"); - if (res == CHIP_NO_ERROR) - { - res = CHIP_ERROR_CONNECTION_ABORTED; - } - - dispatch_semaphore_signal(mConnectionSemaphore); - break; - } - }); - - nw_connection_start(aConnection); - dispatch_semaphore_wait(mConnectionSemaphore, DISPATCH_TIME_FOREVER); - SuccessOrExit(res); - - mConnection = aConnection; - nw_retain(mConnection); - HandleDataReceived(mConnection); - - return res; -} - -void UDPEndPointImplNetworkFramework::HandleDataReceived(const nw_connection_t & aConnection) -{ - nw_connection_receive_completion_t handler = - ^(dispatch_data_t content, nw_content_context_t context, bool is_complete, nw_error_t receive_error) { - dispatch_block_t schedule_next_receive = ^{ - if (receive_error == nullptr) - { - HandleDataReceived(aConnection); - } - else if (OnReceiveError != nullptr) - { - nw_error_domain_t error_domain = nw_error_get_error_domain(receive_error); - errno = nw_error_get_error_code(receive_error); - if (!(error_domain == nw_error_domain_posix && errno == ECANCELED)) - { - CHIP_ERROR error = CHIP_ERROR_POSIX(errno); - IPPacketInfo packetInfo; - GetPacketInfo(aConnection, packetInfo); - dispatch_async(mDispatchQueue, ^{ - OnReceiveError((UDPEndPoint *) this, error, &packetInfo); - }); - } - } - }; - - if (content != nullptr && OnMessageReceived != nullptr) - { - size_t count = dispatch_data_get_size(content); - System::PacketBufferHandle * packetBuffer = System::PacketBufferHandle::New(count); - dispatch_data_apply(content, ^(dispatch_data_t data, size_t offset, const void * buffer, size_t size) { - memmove(packetBuffer->Start() + offset, buffer, size); - return true; - }); - packetBuffer->SetDataLength(count); - - IPPacketInfo packetInfo; - GetPacketInfo(aConnection, packetInfo); - dispatch_async(mDispatchQueue, ^{ - OnMessageReceived((UDPEndPoint *) this, packetBuffer, &packetInfo); - }); - } - - schedule_next_receive(); - }; - - nw_connection_receive_message(aConnection, handler); -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::ReleaseListener() -{ - VerifyOrReturnError(mListener, CHIP_ERROR_INCORRECT_STATE); - VerifyOrReturnError(mDispatchQueue, CHIP_ERROR_INCORRECT_STATE); - VerifyOrReturnError(mConnectionSemaphore, CHIP_ERROR_INCORRECT_STATE); - - nw_listener_cancel(mListener); - dispatch_semaphore_wait(mListenerSemaphore, DISPATCH_TIME_FOREVER); - nw_release(mListener); - mListener = nullptr; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR UDPEndPointImplNetworkFramework::ReleaseConnection() -{ - VerifyOrReturnError(mConnection, CHIP_ERROR_INCORRECT_STATE); - VerifyOrReturnError(mDispatchQueue, CHIP_ERROR_INCORRECT_STATE); - VerifyOrReturnError(mConnectionSemaphore, CHIP_ERROR_INCORRECT_STATE); - - nw_connection_cancel(mConnection); - dispatch_semaphore_wait(mConnectionSemaphore, DISPATCH_TIME_FOREVER); - nw_release(mConnection); - mConnection = nullptr; - - return CHIP_NO_ERROR; -} - -} // namespace Inet -} // namespace chip diff --git a/src/inet/UDPEndPointImplNetworkFramework.h b/src/inet/UDPEndPointImplNetworkFramework.h index 55c5ef181212e4..0e8f7dda68ebcb 100644 --- a/src/inet/UDPEndPointImplNetworkFramework.h +++ b/src/inet/UDPEndPointImplNetworkFramework.h @@ -56,14 +56,16 @@ class UDPEndPointImplNetworkFramework : public UDPEndPoint, public EndPointState dispatch_queue_t mListenerQueue; nw_connection_t mConnection; dispatch_semaphore_t mConnectionSemaphore; - dispatch_queue_t mDispatchQueue; + dispatch_queue_t mConnectionQueue; dispatch_semaphore_t mSendSemaphore; + dispatch_queue_t mSystemQueue; CHIP_ERROR ConfigureProtocol(IPAddressType aAddressType, const nw_parameters_t & aParameters); CHIP_ERROR StartListener(); CHIP_ERROR GetConnection(const IPPacketInfo * aPktInfo); - CHIP_ERROR GetEndPoint(nw_endpoint_t & aEndpoint, const IPAddressType aAddressType, const IPAddress & aAddress, uint16_t aPort); - CHIP_ERROR StartConnection(nw_connection_t & aConnection); + nw_endpoint_t GetEndPoint(const IPAddressType aAddressType, const IPAddress & aAddress, uint16_t aPort, + InterfaceId interfaceIndex = InterfaceId::Null()); + CHIP_ERROR StartConnection(nw_connection_t aConnection); void GetPacketInfo(const nw_connection_t & aConnection, IPPacketInfo & aPacketInfo); void HandleDataReceived(const nw_connection_t & aConnection); CHIP_ERROR ReleaseListener(); diff --git a/src/inet/UDPEndPointImplNetworkFramework.mm b/src/inet/UDPEndPointImplNetworkFramework.mm new file mode 100644 index 00000000000000..070048538c6f50 --- /dev/null +++ b/src/inet/UDPEndPointImplNetworkFramework.mm @@ -0,0 +1,655 @@ +/* + * + * Copyright (c) 2020-2024 Project CHIP Authors + * Copyright (c) 2018 Google LLC. + * Copyright (c) 2013-2018 Nest Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * This file implements Inet::UDPEndPoint using Network Framework. + */ + +#if !__has_feature(objc_arc) +#error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). +#endif + +#include +#include + +#include + +#define INET_PORTSTRLEN 6 + +#define NETWORK_FRAMEWORK_DEBUG 0 + +namespace { +#if !NETWORK_FRAMEWORK_DEBUG +void DebugPrintListenerState(nw_listener_state_t state) {}; +void DebugPrintConnectionState(nw_connection_state_t state) {}; +void DebugPrintConnection(const nw_connection_t aConnection) {}; +#else +constexpr const char * kNilConnection = "The connection is nil."; +constexpr const char * kNilPath = "The connection path is nil."; +constexpr const char * kNilPathSourceEndPoint = "The connection path source endpoint is nil."; +constexpr const char * kNilPathDestinationEndPoint = "The connection path destination endpoint is nil."; +constexpr const char * kPathStatusInvalid = "This path is not valid."; +constexpr const char * kPathStatusUnsatisfied = "The path is not available for use."; +constexpr const char * kPathStatusSatisfied = "The path is available to establish connections and send data."; +constexpr const char * kPathStatusSatisfiable = "The path is not currently available, but establishing a new connection may activate the path."; + +constexpr const char * kListenerStateInvalid = "Listener: Invalid"; +constexpr const char * kListenerStateWaiting = "Listener: Waiting"; +constexpr const char * kListenerStateFailed = "Listener: Failed"; +constexpr const char * kListenerStateReady = "Listener: Ready"; +constexpr const char * kListenerStateCancelled = "Listener: Cancelled"; + +constexpr const char * kConnectionStateInvalid = "Connection: Invalid"; +constexpr const char * kConnectionStateWaiting = "Connection: Waiting"; +constexpr const char * kConnectionStatePreparing = "Connection: Preparing"; +constexpr const char * kConnectionStateFailed = "Connection: Failed"; +constexpr const char * kConnectionStateReady = "Connection: Ready"; +constexpr const char * kConnectionStateCancelled = "Connection: Cancelled"; + +void DebugPrintConnectionState(nw_connection_state_t state) +{ + const char * str = nullptr; + + switch (state) { + case nw_connection_state_invalid: + str = kConnectionStateInvalid; + break; + case nw_connection_state_preparing: + str = kConnectionStatePreparing; + break; + case nw_connection_state_waiting: + str = kConnectionStateWaiting; + break; + case nw_connection_state_failed: + str = kConnectionStateFailed; + break; + case nw_connection_state_ready: + str = kConnectionStateReady; + break; + case nw_connection_state_cancelled: + str = kConnectionStateCancelled; + break; + default: + chipDie(); + } + + ChipLogDetail(Inet, "%s", str); +} + +void DebugPrintListenerState(nw_listener_state_t state) +{ + const char * str = nullptr; + + switch (state) { + case nw_listener_state_invalid: + str = kListenerStateInvalid; + break; + case nw_listener_state_waiting: + str = kListenerStateWaiting; + break; + case nw_listener_state_failed: + str = kListenerStateFailed; + break; + case nw_listener_state_ready: + str = kListenerStateReady; + break; + case nw_listener_state_cancelled: + str = kListenerStateCancelled; + break; + default: + chipDie(); + } + + ChipLogDetail(Inet, "%s", str); +} + +void DebugPrintConnectionPathStatus(nw_path_t path) +{ + const char * str = nullptr; + + __auto_type status = nw_path_get_status(path); + switch (status) { + case nw_path_status_invalid: + str = kPathStatusInvalid; + break; + case nw_path_status_unsatisfied: + str = kPathStatusUnsatisfied; + break; + case nw_path_status_satisfied: + str = kPathStatusSatisfied; + break; + case nw_path_status_satisfiable: + str = kPathStatusSatisfiable; + break; + default: + chipDie(); + } + + ChipLogError(Inet, "%s", str); +} + +void DebugPrintConnection(const nw_connection_t aConnection) +{ + VerifyOrReturn(nil != aConnection, ChipLogError(Inet, "%s", kNilConnection)); + + __auto_type path = nw_connection_copy_current_path(aConnection); + VerifyOrReturn(nil != path, ChipLogError(Inet, "%s", kNilPath)); + DebugPrintConnectionPathStatus(path); + + __auto_type srcEndPoint = nw_path_copy_effective_local_endpoint(path); + VerifyOrReturn(nil != srcEndPoint, ChipLogError(Inet, "%s", kNilPathSourceEndPoint)); + + __auto_type dstEndPoint = nw_path_copy_effective_remote_endpoint(path); + VerifyOrReturn(nil != dstEndPoint, ChipLogError(Inet, "%s", kNilPathDestinationEndPoint)); + + const __auto_type * srcAddress = nw_endpoint_copy_address_string(srcEndPoint); + const __auto_type srcPort = nw_endpoint_get_port(srcEndPoint); + const __auto_type * dstAddress = nw_endpoint_copy_address_string(dstEndPoint); + const __auto_type dstPort = nw_endpoint_get_port(dstEndPoint); + + ChipLogError(Inet, "Connection source: %s:%u destination: %s:%u", srcAddress, srcPort, dstAddress, dstPort); +} +#endif +} + +namespace chip { +namespace Inet { + + CHIP_ERROR UDPEndPointImplNetworkFramework::BindImpl(IPAddressType addressType, const IPAddress & address, uint16_t port, + InterfaceId intfId) + { +#if NETWORK_FRAMEWORK_DEBUG + ChipLogError(Inet, "%s (%p)", __func__, this); +#endif + + VerifyOrReturnError(!intfId.IsPresent(), CHIP_ERROR_NOT_IMPLEMENTED); + + __auto_type configure_tls = NW_PARAMETERS_DISABLE_PROTOCOL; + __auto_type parameters = nw_parameters_create_secure_udp(configure_tls, NW_PARAMETERS_DEFAULT_CONFIGURATION); + VerifyOrReturnError(nullptr != parameters, CHIP_ERROR_INVALID_ARGUMENT); + + // Note: The ConfigureProtocol function uses nw_ip_options_set_version to set the IP version for this endpoint. + // + // This works as expected when the IPAddress is specified. However, when using a wildcard address (chip::Inet::IPAddressType::kAny) + // for an IPv6 socket, the specified IP version (nw_ip_version_6) may be ignored, allowing both IPv4 and IPv6 connections. + ReturnErrorOnFailure(ConfigureProtocol(addressType, parameters)); + + // Note: Network.framework does not provide an API to set the SO_REUSEPORT socket option. + // This limitation is not an issue when the port is set to 0, as the platform will choose a random port. + // + // However, when both INET_CONFIG_ENABLE_IPV4 and CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY are enabled, + // the system attempts to create two endpoints—one over IPv6 and another over IPv4—both using the same port + // specified by CHIP_UDC_PORT. + // + // This results in a binding failure due to "Address already in use" since both IPv4 and IPv6 endpoints + // try to use the same port. + // + // A potential solution would be to define separate ports for IPv4 and IPv6 (e.g., CHIP_UDC_PORT_IPv4 and CHIP_UDC_PORT_IPv6). + // For now, as a workaround, we set the port to 0 for IPv4 when a specific port is needed, allowing the platform to + // auto-assign an available port and avoid the conflict. + if (IPAddressType::kIPv4 == addressType && port != 0) { + port = 0; + } + + __auto_type endpoint = GetEndPoint(addressType, address, port); + VerifyOrReturnError(nullptr != endpoint, CHIP_ERROR_INTERNAL); + nw_parameters_set_local_endpoint(parameters, endpoint); + + mConnectionQueue = dispatch_queue_create("inet_dispatch_global", DISPATCH_QUEUE_SERIAL); + VerifyOrReturnError(nullptr != mConnectionQueue, CHIP_ERROR_NO_MEMORY); + + mConnectionSemaphore = dispatch_semaphore_create(0); + VerifyOrReturnError(nullptr != mConnectionSemaphore, CHIP_ERROR_NO_MEMORY); + + mSendSemaphore = dispatch_semaphore_create(0); + VerifyOrReturnError(nullptr != mSendSemaphore, CHIP_ERROR_NO_MEMORY); + + mSystemQueue = static_cast(GetSystemLayer()).GetDispatchQueue(); + mAddrType = addressType; + mConnection = nullptr; + mParameters = parameters; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR UDPEndPointImplNetworkFramework::BindInterfaceImpl(IPAddressType addrType, InterfaceId intfId) + { + return INET_ERROR_UNKNOWN_INTERFACE; + } + + InterfaceId UDPEndPointImplNetworkFramework::GetBoundInterface() const + { + return InterfaceId::Null(); + } + + uint16_t UDPEndPointImplNetworkFramework::GetBoundPort() const + { + __auto_type endpoint = nw_parameters_copy_local_endpoint(mParameters); + return nw_endpoint_get_port(endpoint); + } + + CHIP_ERROR UDPEndPointImplNetworkFramework::ListenImpl() + { + return StartListener(); + } + + CHIP_ERROR UDPEndPointImplNetworkFramework::SendMsgImpl(const IPPacketInfo * pktInfo, System::PacketBufferHandle && msg) + { +#if NETWORK_FRAMEWORK_DEBUG + ChipLogError(Inet, "%s (%p)", __func__, this); +#endif + + // Ensure we have an actual message to send. + VerifyOrReturnError(!msg.IsNull(), CHIP_ERROR_INVALID_ARGUMENT); + + // Ensure the destination address type is compatible with the endpoint address type. + VerifyOrReturnError(mAddrType == pktInfo->DestAddress.Type(), CHIP_ERROR_INVALID_ARGUMENT); + + // For now the entire message must fit within a single buffer. + VerifyOrReturnError(msg->Next() == nullptr, CHIP_ERROR_MESSAGE_TOO_LONG); + + ReturnErrorOnFailure(GetConnection(pktInfo)); + + // Send a message, and wait for it to be dispatched. + __auto_type content = dispatch_data_create(msg->Start(), msg->DataLength(), mSystemQueue, DISPATCH_DATA_DESTRUCTOR_DEFAULT); + + // If there is a current message pending and the state of the network connection changes (e.g switch to a + // different network) the connection will enter a nw_connection_state_failed state and the completion handler + // will never be called. In such cases a signal is sent from the connection state change handler to release + // the semaphore. In this case the CHIP_ERROR will not update with the result of the completion handler. + // To make sure our caller knows that sending a message has failed the following code assumes there is an error + // _unless_ the completion handler says otherwise. + __block CHIP_ERROR err = CHIP_ERROR_UNEXPECTED_EVENT; + nw_connection_send(mConnection, content, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, ^(nw_error_t error) { + if (error) { + err = CHIP_ERROR_POSIX(nw_error_get_error_code(error)); + } else { + err = CHIP_NO_ERROR; + } + dispatch_semaphore_signal(mSendSemaphore); + }); + + dispatch_semaphore_wait(mSendSemaphore, DISPATCH_TIME_FOREVER); + + return err; + } + + void UDPEndPointImplNetworkFramework::CloseImpl() + { + ReleaseAll(); + } + + void UDPEndPointImplNetworkFramework::ReleaseAll() + { + + OnMessageReceived = nullptr; + OnReceiveError = nullptr; + + ReleaseConnection(); + ReleaseListener(); + + mParameters = nullptr; + + mConnectionQueue = nullptr; + mConnectionSemaphore = nullptr; + + mListenerQueue = nullptr; + mListenerSemaphore = nullptr; + + mSendSemaphore = nullptr; + } + + void UDPEndPointImplNetworkFramework::Free() + { + Close(); + Release(); + } + + CHIP_ERROR UDPEndPointImplNetworkFramework::SetMulticastLoopback(IPVersion aIPVersion, bool aLoopback) + { + return CHIP_ERROR_NOT_IMPLEMENTED; + } + +#if INET_CONFIG_ENABLE_IPV4 + CHIP_ERROR UDPEndPointImplNetworkFramework::IPv4JoinLeaveMulticastGroupImpl(InterfaceId aInterfaceId, const IPAddress & aAddress, + bool join) + { + return CHIP_ERROR_NOT_IMPLEMENTED; + } +#endif // INET_CONFIG_ENABLE_IPV4 + + CHIP_ERROR UDPEndPointImplNetworkFramework::IPv6JoinLeaveMulticastGroupImpl(InterfaceId aInterfaceId, const IPAddress & aAddress, + bool join) + { + return CHIP_ERROR_NOT_IMPLEMENTED; + } + + CHIP_ERROR UDPEndPointImplNetworkFramework::ConfigureProtocol(IPAddressType aAddressType, const nw_parameters_t & aParameters) + { + CHIP_ERROR err = CHIP_NO_ERROR; + + __auto_type protocolStack = nw_parameters_copy_default_protocol_stack(aParameters); + __auto_type ipOptions = nw_protocol_stack_copy_internet_protocol(protocolStack); + + switch (aAddressType) { + + case IPAddressType::kIPv6: + nw_ip_options_set_version(ipOptions, nw_ip_version_6); + break; + +#if INET_CONFIG_ENABLE_IPV4 + case IPAddressType::kIPv4: + nw_ip_options_set_version(ipOptions, nw_ip_version_4); + break; +#endif // INET_CONFIG_ENABLE_IPV4 + + default: + err = INET_ERROR_WRONG_ADDRESS_TYPE; + break; + } + + return err; + } + + void UDPEndPointImplNetworkFramework::GetPacketInfo(const nw_connection_t & aConnection, IPPacketInfo & aPacketInfo) + { + nw_path_t path = nw_connection_copy_current_path(aConnection); + nw_endpoint_t dest_endpoint = nw_path_copy_effective_local_endpoint(path); + nw_endpoint_t src_endpoint = nw_path_copy_effective_remote_endpoint(path); + + aPacketInfo.Clear(); + + // TODO Handle return value of IPAddress::GetIPAddressFromSockAdd + const auto * srcAddress = nw_endpoint_get_address(src_endpoint); + IPAddress::GetIPAddressFromSockAddr(*srcAddress, aPacketInfo.SrcAddress); + + // TODO Handle return value of IPAddress::GetIPAddressFromSockAdd + const auto * dstAddress = nw_endpoint_get_address(dest_endpoint); + IPAddress::GetIPAddressFromSockAddr(*dstAddress, aPacketInfo.DestAddress); + + aPacketInfo.SrcPort = nw_endpoint_get_port(src_endpoint); + aPacketInfo.DestPort = nw_endpoint_get_port(dest_endpoint); + +#if NETWORK_FRAMEWORK_DEBUG + char srcAddrStr[IPAddress::kMaxStringLength + 1 /*null terminator */]; + char dstAddrStr[IPAddress::kMaxStringLength + 1 /*null terminator */]; + aPacketInfo.SrcAddress.ToString(srcAddrStr); + aPacketInfo.DestAddress.ToString(dstAddrStr); + ChipLogError(Inet, "Packet received from %s to %s", srcAddrStr, dstAddrStr); +#endif + } + + nw_endpoint_t UDPEndPointImplNetworkFramework::GetEndPoint(const IPAddressType aAddressType, + const IPAddress & aAddress, uint16_t aPort, InterfaceId interfaceIndex) + { + char addrStr[IPAddress::kMaxStringLength + 1 /*%*/ + InterfaceId::kMaxIfNameLength + 1 /*null terminator */]; + char portStr[INET_PORTSTRLEN]; + + // Note: aAddress.ToString will return the IPv6 Any address if the address type is Any, but that's not what + // we want if the local endpoint is IPv4. +#if INET_CONFIG_ENABLE_IPV4 + if (aAddressType == IPAddressType::kIPv4 && aAddress.Type() == IPAddressType::kAny) { + const IPAddress anyAddr = IPAddress(aAddress.ToIPv4()); + anyAddr.ToString(addrStr); + } else +#endif // INET_CONFIG_ENABLE_IPV4 + { + aAddress.ToString(addrStr); + if (interfaceIndex != InterfaceId::Null()) { + char interface[InterfaceId::kMaxIfNameLength + 1] = {}; // +1 to prepend '%' + interface[0] = '%'; + interface[1] = 0; + CHIP_ERROR err = interfaceIndex.GetInterfaceName(interface + 1, sizeof(interface) - 1); + if (err != CHIP_NO_ERROR) { + Platform::CopyString(interface, sizeof(interface), "%(err)"); + } + strncat(addrStr, interface, sizeof(addrStr) - strlen(addrStr) - 1); + } + } + + snprintf(portStr, sizeof(portStr), "%u", aPort); + + char * target = addrStr; + +#if NETWORK_FRAMEWORK_DEBUG + ChipLogError(Inet, "Create endpoint for ip(%s) port(%s)", target, portStr); +#endif + return nw_endpoint_create_host(target, portStr); + } + + CHIP_ERROR UDPEndPointImplNetworkFramework::GetConnection(const IPPacketInfo * aPktInfo) + { + VerifyOrReturnError(nullptr != mParameters, CHIP_ERROR_INCORRECT_STATE); + + if (mConnection) { + __auto_type path = nw_connection_copy_current_path(mConnection); + __auto_type remote_endpoint = nw_path_copy_effective_remote_endpoint(path); + // TODO Handle return value of IPAddress::GetIPAddressFromSockAdd + IPAddress remote_address; + IPAddress::GetIPAddressFromSockAddr(*nw_endpoint_get_address(remote_endpoint), remote_address); + + const uint16_t remote_port = nw_endpoint_get_port(remote_endpoint); + const bool isDifferentEndPoint = aPktInfo->DestPort != remote_port || aPktInfo->DestAddress != remote_address; + // Return without doing anything if we are not changing our endpoint. + VerifyOrReturnError(isDifferentEndPoint, CHIP_NO_ERROR); + + ReturnErrorOnFailure(ReleaseConnection()); + } + + __auto_type endpoint = GetEndPoint(mAddrType, aPktInfo->DestAddress, aPktInfo->DestPort, aPktInfo->Interface); + VerifyOrReturnError(nullptr != endpoint, CHIP_ERROR_INCORRECT_STATE); + + __auto_type connection = nw_connection_create(endpoint, mParameters); + VerifyOrReturnError(nullptr != connection, CHIP_ERROR_INCORRECT_STATE); + + return StartConnection(connection); + } + + CHIP_ERROR UDPEndPointImplNetworkFramework::StartListener() + { + VerifyOrReturnError(nullptr == mListener, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(nullptr == mListenerSemaphore, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(nullptr == mListenerQueue, CHIP_ERROR_INCORRECT_STATE); + + __auto_type listener = nw_listener_create(mParameters); + VerifyOrReturnError(nullptr != listener, CHIP_ERROR_INCORRECT_STATE); + + mListenerSemaphore = dispatch_semaphore_create(0); + VerifyOrReturnError(nullptr != mListenerSemaphore, CHIP_ERROR_NO_MEMORY); + + mListenerQueue = dispatch_queue_create("inet_dispatch_listener", DISPATCH_QUEUE_CONCURRENT); + VerifyOrReturnError(nullptr != mListenerQueue, CHIP_ERROR_NO_MEMORY); + + nw_listener_set_queue(listener, mListenerQueue); + + nw_listener_set_new_connection_handler(listener, ^(nw_connection_t connection) { + ReleaseConnection(); + StartConnection(connection); + }); + + __block CHIP_ERROR err = CHIP_NO_ERROR; + nw_listener_set_state_changed_handler(listener, ^(nw_listener_state_t state, nw_error_t error) { + DebugPrintListenerState(state); + + switch (state) { + case nw_listener_state_invalid: + err = CHIP_ERROR_INCORRECT_STATE; + nw_listener_cancel(listener); + break; + + case nw_listener_state_waiting: + // Nothing to do. + break; + + case nw_listener_state_failed: + err = CHIP_ERROR_POSIX(nw_error_get_error_code(error)); + ChipLogError(Inet, "Error: %s", chip::ErrorStr(err)); + break; + + case nw_listener_state_ready: + err = CHIP_NO_ERROR; + dispatch_semaphore_signal(mListenerSemaphore); + break; + + case nw_listener_state_cancelled: + if (err == CHIP_NO_ERROR) { + err = CHIP_ERROR_CONNECTION_ABORTED; + } + + dispatch_semaphore_signal(mListenerSemaphore); + break; + } + }); + + nw_listener_start(listener); + dispatch_semaphore_wait(mListenerSemaphore, DISPATCH_TIME_FOREVER); + + if (CHIP_NO_ERROR == err) { + mListener = listener; + } + + return err; + } + + CHIP_ERROR UDPEndPointImplNetworkFramework::StartConnection(nw_connection_t aConnection) + { + __block CHIP_ERROR err = CHIP_NO_ERROR; + + nw_connection_set_queue(aConnection, mConnectionQueue); + + nw_connection_set_state_changed_handler(aConnection, ^(nw_connection_state_t state, nw_error_t error) { + DebugPrintConnectionState(state); + + switch (state) { + case nw_connection_state_invalid: + err = CHIP_ERROR_INCORRECT_STATE; + nw_connection_cancel(aConnection); + break; + + case nw_connection_state_preparing: + err = CHIP_ERROR_INCORRECT_STATE; + break; + + case nw_connection_state_waiting: + nw_connection_cancel(aConnection); + break; + + case nw_connection_state_failed: + err = CHIP_ERROR_POSIX(nw_error_get_error_code(error)); + break; + + case nw_connection_state_ready: + err = CHIP_NO_ERROR; + dispatch_semaphore_signal(mConnectionSemaphore); + break; + + case nw_connection_state_cancelled: + if (err == CHIP_NO_ERROR) { + err = CHIP_ERROR_CONNECTION_ABORTED; + } + + dispatch_semaphore_signal(mConnectionSemaphore); + break; + } + }); + + nw_connection_start(aConnection); + dispatch_semaphore_wait(mConnectionSemaphore, DISPATCH_TIME_FOREVER); + + if (CHIP_NO_ERROR == err) { + DebugPrintConnection(aConnection); + + mConnection = aConnection; + HandleDataReceived(mConnection); + } + return err; + } + + void UDPEndPointImplNetworkFramework::HandleDataReceived(const nw_connection_t & aConnection) + { + nw_connection_receive_completion_t handler = ^(dispatch_data_t content, nw_content_context_t context, bool is_complete, nw_error_t receive_error) { + dispatch_block_t schedule_next_receive = ^{ + if (receive_error == nullptr) { + HandleDataReceived(aConnection); + } else if (OnReceiveError != nullptr) { + __auto_type error_domain = nw_error_get_error_domain(receive_error); + errno = nw_error_get_error_code(receive_error); + if (!(error_domain == nw_error_domain_posix && errno == ECANCELED)) { + CHIP_ERROR error = CHIP_ERROR_POSIX(errno); + IPPacketInfo packetInfo; + GetPacketInfo(aConnection, packetInfo); + dispatch_async(mSystemQueue, ^{ + OnReceiveError((UDPEndPoint *) this, error, &packetInfo); + }); + } + } + }; + + if (content != nullptr && OnMessageReceived != nullptr) { + size_t count = dispatch_data_get_size(content); + auto packetBufferHandle = System::PacketBufferHandle::New(count); + auto * packetBuffer = std::move(packetBufferHandle).UnsafeRelease(); + dispatch_data_apply(content, ^(dispatch_data_t data, size_t offset, const void * buffer, size_t size) { + memmove(packetBuffer->Start() + offset, buffer, size); + return true; + }); + packetBuffer->SetDataLength(count); + + IPPacketInfo packetInfo; + GetPacketInfo(aConnection, packetInfo); + dispatch_async(mSystemQueue, ^{ + auto handle = System::PacketBufferHandle::Adopt(packetBuffer); + OnMessageReceived((UDPEndPoint *) this, std::move(handle), &packetInfo); + }); + } + + schedule_next_receive(); + }; + + nw_connection_receive_message(aConnection, handler); + } + + CHIP_ERROR UDPEndPointImplNetworkFramework::ReleaseListener() + { + VerifyOrReturnError(nullptr != mListener, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(nullptr != mConnectionQueue, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(nullptr != mConnectionSemaphore, CHIP_ERROR_INCORRECT_STATE); + + nw_listener_cancel(mListener); + dispatch_semaphore_wait(mListenerSemaphore, DISPATCH_TIME_FOREVER); + mListener = nullptr; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR UDPEndPointImplNetworkFramework::ReleaseConnection() + { + VerifyOrReturnError(nullptr != mConnection, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(nullptr != mConnectionQueue, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(nullptr != mConnectionSemaphore, CHIP_ERROR_INCORRECT_STATE); + + nw_connection_cancel(mConnection); + dispatch_semaphore_wait(mConnectionSemaphore, DISPATCH_TIME_FOREVER); + mConnection = nullptr; + + return CHIP_NO_ERROR; + } + +} // namespace Inet +} // namespace chip diff --git a/src/inet/inet.gni b/src/inet/inet.gni index 1c19551da374c6..ea66c3df3f11ef 100644 --- a/src/inet/inet.gni +++ b/src/inet/inet.gni @@ -26,11 +26,18 @@ declare_args() { # Enable TCP endpoint. chip_inet_config_enable_tcp_endpoint = true + # TODO: Set to false when using Network.framework until a Network.framework TCP endpoint backend is implemented. + if (chip_system_config_use_network_framework) { + chip_inet_config_enable_tcp_endpoint = false + } + # Inet implementation type. if (chip_system_config_use_open_thread_inet_endpoints) { chip_system_config_inet = "OpenThread" } else if (chip_system_config_use_lwip) { chip_system_config_inet = "LwIP" + } else if (chip_system_config_use_network_framework) { + chip_system_config_inet = "NetworkFramework" } else { chip_system_config_inet = "Sockets" } diff --git a/src/lib/core/BUILD.gn b/src/lib/core/BUILD.gn index 5a6e6e114e4aae..265f5fea7fc5b8 100644 --- a/src/lib/core/BUILD.gn +++ b/src/lib/core/BUILD.gn @@ -48,7 +48,6 @@ buildconfig_header("chip_buildconfig") { "CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE=${chip_log_message_max_size}", "CHIP_AUTOMATION_LOGGING=${chip_automation_logging}", "CHIP_PW_TOKENIZER_LOGGING=${chip_pw_tokenizer_logging}", - "CHIP_USE_PW_LOGGING=${chip_use_pw_logging}", "CHIP_EXCHANGE_NODE_ID_LOGGING=${chip_exchange_node_id_logging}", "CHIP_CONFIG_SHORT_ERROR_STR=${chip_config_short_error_str}", "CHIP_CONFIG_ENABLE_ARG_PARSER=${chip_config_enable_arg_parser}", diff --git a/src/lib/core/CHIPConfig.h b/src/lib/core/CHIPConfig.h index fca3472826a310..a775d2b58fc23f 100644 --- a/src/lib/core/CHIPConfig.h +++ b/src/lib/core/CHIPConfig.h @@ -618,13 +618,13 @@ #define _CHIP_CONFIG_IsPlatformLwIPErrorNonCritical(CODE) 0 #endif // !CHIP_SYSTEM_CONFIG_USE_LWIP -#if CHIP_SYSTEM_CONFIG_USE_SOCKETS +#if CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK #define _CHIP_CONFIG_IsPlatformPOSIXErrorNonCritical(CODE) \ ((CODE) == CHIP_ERROR_POSIX(EHOSTUNREACH) || (CODE) == CHIP_ERROR_POSIX(ENETUNREACH) || \ (CODE) == CHIP_ERROR_POSIX(EADDRNOTAVAIL) || (CODE) == CHIP_ERROR_POSIX(EPIPE)) -#else // !CHIP_SYSTEM_CONFIG_USE_SOCKETS +#else // !(CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK) #define _CHIP_CONFIG_IsPlatformPOSIXErrorNonCritical(CODE) 0 -#endif // !CHIP_SYSTEM_CONFIG_USE_SOCKETS +#endif // !(CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK) #define CHIP_CONFIG_IsPlatformErrorNonCritical(CODE) \ (_CHIP_CONFIG_IsPlatformPOSIXErrorNonCritical(CODE) || _CHIP_CONFIG_IsPlatformLwIPErrorNonCritical(CODE)) diff --git a/src/lib/core/ErrorStr.cpp b/src/lib/core/ErrorStr.cpp index 6d83bc015b21d2..b3cf968c674dd5 100644 --- a/src/lib/core/ErrorStr.cpp +++ b/src/lib/core/ErrorStr.cpp @@ -29,7 +29,7 @@ namespace chip { /** * Static buffer to store the formatted error string. */ -static char sErrorStr[CHIP_CONFIG_ERROR_STR_SIZE]; +static ErrorStrStorage sErrorStr; /** * Linked-list of error formatter functions. @@ -38,7 +38,7 @@ static ErrorFormatter * sErrorFormatterList = nullptr; /** * This routine returns a human-readable NULL-terminated C string - * describing the provided error. + * describing the provided error. This uses the global static storage. * * @param[in] err The error for format and describe. * @param[in] withSourceLocation Whether or not to include the source @@ -50,8 +50,26 @@ static ErrorFormatter * sErrorFormatterList = nullptr; */ DLL_EXPORT const char * ErrorStr(CHIP_ERROR err, bool withSourceLocation) { - char * formattedError = sErrorStr; - uint16_t formattedSpace = sizeof(sErrorStr); + return ErrorStr(err, withSourceLocation, sErrorStr); +} + +/** + * This routine writess a human-readable NULL-terminated C string into the buf + * which describes the provided error. + * + * @param[in] err The error for format and describe. + * @param[in] withSourceLocation Whether or not to include the source + * @param[in] storage ErrorStrStorage to write into + * location in the output string. Only used if CHIP_CONFIG_ERROR_SOURCE && + * !CHIP_CONFIG_SHORT_ERROR_STR. Defaults to true. + * + * @return A pointer to a NULL-terminated C string describing the + * provided error. + */ +DLL_EXPORT const char * ErrorStr(CHIP_ERROR err, bool withSourceLocation, ErrorStrStorage & storage) +{ + char * formattedError = storage.buff; + uint16_t formattedSpace = storage.kBufferSize; #if CHIP_CONFIG_ERROR_SOURCE && !CHIP_CONFIG_SHORT_ERROR_STR @@ -65,34 +83,27 @@ DLL_EXPORT const char * ErrorStr(CHIP_ERROR err, bool withSourceLocation) formattedError += n; formattedSpace = static_cast(formattedSpace - n); } - if (err == CHIP_NO_ERROR) - { - (void) snprintf(formattedError, formattedSpace, CHIP_NO_ERROR_STRING); - return sErrorStr; - } - -#else // CHIP_CONFIG_ERROR_SOURCE && !CHIP_CONFIG_SHORT_ERROR_STR +#endif // CHIP_CONFIG_ERROR_SOURCE && !CHIP_CONFIG_SHORT_ERROR_STR if (err == CHIP_NO_ERROR) { - return CHIP_NO_ERROR_STRING; + (void) snprintf(formattedError, formattedSpace, CHIP_NO_ERROR_STRING); + return storage.buff; } -#endif // CHIP_CONFIG_ERROR_SOURCE && !CHIP_CONFIG_SHORT_ERROR_STR - // Search the registered error formatter for one that will format the given // error code. for (const ErrorFormatter * errFormatter = sErrorFormatterList; errFormatter != nullptr; errFormatter = errFormatter->Next) { if (errFormatter->FormatError(formattedError, formattedSpace, err)) { - return sErrorStr; + return storage.buff; } } // Use a default formatting if no formatter found. FormatError(formattedError, formattedSpace, nullptr, err, nullptr); - return sErrorStr; + return storage.buff; } /** diff --git a/src/lib/core/ErrorStr.h b/src/lib/core/ErrorStr.h index d67680c2151b1e..f1365a6bfb25f3 100644 --- a/src/lib/core/ErrorStr.h +++ b/src/lib/core/ErrorStr.h @@ -48,7 +48,14 @@ struct ErrorFormatter ErrorFormatter * Next; }; +struct ErrorStrStorage +{ + char buff[CHIP_CONFIG_ERROR_STR_SIZE]; + constexpr static uint16_t kBufferSize = sizeof(buff); +}; + extern const char * ErrorStr(CHIP_ERROR err, bool withSourceLocation = true); +extern const char * ErrorStr(CHIP_ERROR err, bool withSourceLocation, ErrorStrStorage & storage); extern void RegisterErrorFormatter(ErrorFormatter * errFormatter); extern void DeregisterErrorFormatter(ErrorFormatter * errFormatter); extern void FormatError(char * buf, uint16_t bufSize, const char * subsys, CHIP_ERROR err, const char * desc); diff --git a/src/lib/core/core.gni b/src/lib/core/core.gni index eea73a5c56f7b3..6dd71cf64f5a57 100644 --- a/src/lib/core/core.gni +++ b/src/lib/core/core.gni @@ -50,9 +50,6 @@ declare_args() { # Enable pigweed tokenizer logging. chip_pw_tokenizer_logging = false - # Configure chip logging to output through pigweed logging. - chip_use_pw_logging = false - # Enable logging of node Id in exchange context log messages. # Will cause increase in code size and is therefore disabled by default. chip_exchange_node_id_logging = false diff --git a/src/lib/core/tests/TestCHIPErrorStr.cpp b/src/lib/core/tests/TestCHIPErrorStr.cpp index 01130aca4261d7..1ce158cc8594ae 100644 --- a/src/lib/core/tests/TestCHIPErrorStr.cpp +++ b/src/lib/core/tests/TestCHIPErrorStr.cpp @@ -170,6 +170,31 @@ static const CHIP_ERROR kTestElements[] = }; // clang-format on +void CheckCoreErrorStrHelper(const char * errStr, CHIP_ERROR err) +{ + char expectedText[9]; + + // Assert that the error string contains the error number in hex. + snprintf(expectedText, sizeof(expectedText), "%08" PRIX32, static_cast(err.AsInteger())); + EXPECT_TRUE((strstr(errStr, expectedText) != nullptr)); + +#if !CHIP_CONFIG_SHORT_ERROR_STR + // Assert that the error string contains a description, which is signaled + // by a presence of a colon proceeding the description. + EXPECT_TRUE((strchr(errStr, ':') != nullptr)); +#endif // !CHIP_CONFIG_SHORT_ERROR_STR + +#if CHIP_CONFIG_ERROR_SOURCE + // GetFile() should be relative to ${chip_root} + char const * const file = err.GetFile(); + ASSERT_NE(file, nullptr); + EXPECT_EQ(strstr(file, "src/lib/core/"), file); + + // File should be included in the error. + EXPECT_NE(strstr(errStr, file), nullptr); +#endif // CHIP_CONFIG_ERROR_SOURCE +} + TEST(TestCHIPErrorStr, CheckCoreErrorStr) { // Register the layer error formatter @@ -179,29 +204,46 @@ TEST(TestCHIPErrorStr, CheckCoreErrorStr) // For each defined error... for (const auto & err : kTestElements) { - const char * errStr = ErrorStr(err); - char expectedText[9]; + // ErrorStr with static char array. + CheckCoreErrorStrHelper(ErrorStr(err, /*withSourceLocation=*/true), err); + } +} + +TEST(TestCHIPErrorStr, CheckCoreErrorStrStorage) +{ + // Register the layer error formatter + + RegisterCHIPLayerErrorFormatter(); + + // For each defined error... + for (const auto & err : kTestElements) + { + // ErrorStr with given storage. + ErrorStrStorage storage; + CheckCoreErrorStrHelper(ErrorStr(err, /*withSourceLocation=*/true, storage), err); + } +} + +void CheckCoreErrorStrWithoutSourceLocationHelper(const char * errStr, CHIP_ERROR err) +{ + char expectedText[9]; - // Assert that the error string contains the error number in hex. - snprintf(expectedText, sizeof(expectedText), "%08" PRIX32, static_cast(err.AsInteger())); - EXPECT_TRUE((strstr(errStr, expectedText) != nullptr)); + // Assert that the error string contains the error number in hex. + snprintf(expectedText, sizeof(expectedText), "%08" PRIX32, static_cast(err.AsInteger())); + EXPECT_TRUE((strstr(errStr, expectedText) != nullptr)); #if !CHIP_CONFIG_SHORT_ERROR_STR - // Assert that the error string contains a description, which is signaled - // by a presence of a colon proceeding the description. - EXPECT_TRUE((strchr(errStr, ':') != nullptr)); + // Assert that the error string contains a description, which is signaled + // by a presence of a colon proceeding the description. + EXPECT_TRUE((strchr(errStr, ':') != nullptr)); #endif // !CHIP_CONFIG_SHORT_ERROR_STR #if CHIP_CONFIG_ERROR_SOURCE - // GetFile() should be relative to ${chip_root} - char const * const file = err.GetFile(); - ASSERT_NE(file, nullptr); - EXPECT_EQ(strstr(file, "src/lib/core/"), file); - - // File should be included in the error. - EXPECT_NE(strstr(errStr, file), nullptr); + char const * const file = err.GetFile(); + ASSERT_NE(file, nullptr); + // File should not be included in the error. + EXPECT_EQ(strstr(errStr, file), nullptr); #endif // CHIP_CONFIG_ERROR_SOURCE - } } TEST(TestCHIPErrorStr, CheckCoreErrorStrWithoutSourceLocation) @@ -213,24 +255,22 @@ TEST(TestCHIPErrorStr, CheckCoreErrorStrWithoutSourceLocation) // For each defined error... for (const auto & err : kTestElements) { - const char * errStr = ErrorStr(err, /*withSourceLocation=*/false); - char expectedText[9]; + // ErrorStr with static char array. + CheckCoreErrorStrWithoutSourceLocationHelper(ErrorStr(err, /*withSourceLocation=*/false), err); + } +} - // Assert that the error string contains the error number in hex. - snprintf(expectedText, sizeof(expectedText), "%08" PRIX32, static_cast(err.AsInteger())); - EXPECT_TRUE((strstr(errStr, expectedText) != nullptr)); +TEST(TestCHIPErrorStr, CheckCoreErrorStrStorageWithoutSourceLocation) +{ + // Register the layer error formatter -#if !CHIP_CONFIG_SHORT_ERROR_STR - // Assert that the error string contains a description, which is signaled - // by a presence of a colon proceeding the description. - EXPECT_TRUE((strchr(errStr, ':') != nullptr)); -#endif // !CHIP_CONFIG_SHORT_ERROR_STR + RegisterCHIPLayerErrorFormatter(); -#if CHIP_CONFIG_ERROR_SOURCE - char const * const file = err.GetFile(); - ASSERT_NE(file, nullptr); - // File should not be included in the error. - EXPECT_EQ(strstr(errStr, file), nullptr); -#endif // CHIP_CONFIG_ERROR_SOURCE + // For each defined error... + for (const auto & err : kTestElements) + { + // ErrorStr with given storage. + ErrorStrStorage storage; + CheckCoreErrorStrWithoutSourceLocationHelper(ErrorStr(err, /*withSourceLocation=*/false, storage), err); } } diff --git a/src/lib/support/BufferWriter.h b/src/lib/support/BufferWriter.h index 64c22af21b43cf..ad474251516421 100644 --- a/src/lib/support/BufferWriter.h +++ b/src/lib/support/BufferWriter.h @@ -87,28 +87,8 @@ class BufferWriter uint8_t * Buffer() { return mBuf; } const uint8_t * Buffer() const { return mBuf; } - BufferWriter & Format(const char * format, ...) ENFORCE_FORMAT(2, 3) - { - va_list args; - va_start(args, format); - VFormat(format, args); - va_end(args); - return *this; - } - void Reset() { mNeeded = 0; } - /// Since this uses vsnprintf internally, on overflow - /// this will write one less byte that strictly can be - /// written (since null terminator will be in the binary data) - BufferWriter & VFormat(const char * format, va_list args) ENFORCE_FORMAT(2, 0); - - /// Assume a specific size for the buffer instead of mSize - /// - /// This is to allow avoiding off-by-one overflow truncation - /// when we know the underlying buffer size is larger. - BufferWriter & VFormatWithSize(size_t size, const char * format, va_list args) ENFORCE_FORMAT(3, 0); - protected: uint8_t * mBuf; size_t mSize; diff --git a/src/lib/support/FunctionTraits.h b/src/lib/support/FunctionTraits.h index 17853a50af8c28..17f02e983a4592 100644 --- a/src/lib/support/FunctionTraits.h +++ b/src/lib/support/FunctionTraits.h @@ -17,6 +17,7 @@ #pragma once +#include #include namespace chip { diff --git a/src/lib/support/pw_log_chip/BUILD.gn b/src/lib/support/pw_log_chip/BUILD.gn deleted file mode 100644 index 23695fa505add0..00000000000000 --- a/src/lib/support/pw_log_chip/BUILD.gn +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2020 The Pigweed 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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -import("//build_overrides/chip.gni") -import("//build_overrides/pigweed.gni") - -import("$dir_pw_build/target_types.gni") - -config("config") { - include_dirs = [ - "public", - "public_overrides", - ] -} - -pw_source_set("pw_log_chip") { - public_configs = [ ":config" ] - public_deps = [ ":pw_log_chip.impl" ] - public = [ "public_overrides/pw_log_backend/log_backend.h" ] - sources = [ "public/pw_log_chip/log_chip.h" ] -} - -pw_source_set("pw_log_chip.impl") { - public_deps = [ "${chip_root}/src/lib/support" ] -} diff --git a/src/lib/support/pw_log_chip/public/pw_log_chip/log_chip.h b/src/lib/support/pw_log_chip/public/pw_log_chip/log_chip.h deleted file mode 100644 index 6550ec707057da..00000000000000 --- a/src/lib/support/pw_log_chip/public/pw_log_chip/log_chip.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2020 Project CHIP Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * This header redirects Pigweed logging prints to chip. - */ -#pragma once - -#include - -#include "pw_preprocessor/arguments.h" - -/** - * Redirect pigweed log prints to chip logging. - * Currently does not use a log module, but this could be added when needed. - * pigweed debug and info level logs are mapped to chip's kLogCategory_Detail. - * All other log levels are mapped to chip's kLogCategory_Error. - * - * Note: This function should not be called directly, instead call the functions - * in pw_log/log.h. - * - * @param[in] level Pigweed log level. - * @param[in] flags Pigweed logging flags, currently these are ignored. - * @param[in] message The printf style log string. - */ -#define PW_LOG(level, flags, message, ...) \ - do \ - { \ - if (level >= PW_LOG_LEVEL_INFO) \ - { \ - ::chip::Logging::Log(::chip::Logging::kLogModule_NotSpecified, \ - (level <= PW_LOG_LEVEL_INFO) ? ::chip::Logging::kLogCategory_Detail \ - : ::chip::Logging::kLogCategory_Error, \ - message PW_COMMA_ARGS(__VA_ARGS__)); \ - } \ - } while (0) diff --git a/src/lib/support/tests/TestErrorStr.cpp b/src/lib/support/tests/TestErrorStr.cpp index 809d69b302af0b..ac8a9f5e9e3469 100644 --- a/src/lib/support/tests/TestErrorStr.cpp +++ b/src/lib/support/tests/TestErrorStr.cpp @@ -121,6 +121,13 @@ TEST(TestErrorStr, CheckNoError) EXPECT_STREQ(CHECK_AND_SKIP_SOURCE(ErrorStr(CHIP_NO_ERROR)), CHIP_NO_ERROR_STRING); } +TEST(TestErrorStr, CheckErrorWithProvidedStorage) +{ + ErrorStrStorage storage; + EXPECT_STREQ(CHECK_AND_SKIP_SOURCE(ErrorStr(CHIP_NO_ERROR, true, storage)), CHIP_NO_ERROR_STRING); + EXPECT_STREQ(CHECK_AND_SKIP_SOURCE(ErrorStr(CHIP_ERROR_INTERNAL, true, storage)), "Error 0x000000AC"); +} + TEST(TestErrorStr, CheckFormatErr) { #if CHIP_CONFIG_SHORT_ERROR_STR diff --git a/src/platform/ESP32/ConfigurationManagerImpl.cpp b/src/platform/ESP32/ConfigurationManagerImpl.cpp index a12750c6a45e57..653d523970369a 100644 --- a/src/platform/ESP32/ConfigurationManagerImpl.cpp +++ b/src/platform/ESP32/ConfigurationManagerImpl.cpp @@ -36,7 +36,9 @@ #include "esp_mac.h" #endif #include "esp_ota_ops.h" +#ifndef CONFIG_IDF_TARGET_ESP32P4 #include "esp_phy_init.h" +#endif #include "esp_wifi.h" #include "nvs.h" #include "nvs_flash.h" diff --git a/src/platform/ESP32/OpenthreadLauncher.cpp b/src/platform/ESP32/OpenthreadLauncher.cpp index 63f1bac825214f..0ab3dadf6862cb 100644 --- a/src/platform/ESP32/OpenthreadLauncher.cpp +++ b/src/platform/ESP32/OpenthreadLauncher.cpp @@ -40,12 +40,14 @@ #include #endif -static esp_netif_t * openthread_netif = NULL; -static esp_openthread_platform_config_t * s_platform_config = NULL; -static TaskHandle_t cli_transmit_task = NULL; -static QueueHandle_t cli_transmit_task_queue = NULL; +static esp_netif_t * openthread_netif = nullptr; +static esp_openthread_platform_config_t * s_platform_config = nullptr; +static TaskHandle_t cli_transmit_task = nullptr; +static QueueHandle_t cli_transmit_task_queue = nullptr; +static TaskHandle_t openthread_task = nullptr; static constexpr uint16_t OTCLI_TRANSMIT_TASK_STACK_SIZE = 1024; static constexpr UBaseType_t OTCLI_TRANSMIT_TASK_PRIORITY = 5; +static const char * TAG = "OpenThread"; CHIP_ERROR cli_transmit_task_post(std::unique_ptr && cli_str) { @@ -116,6 +118,14 @@ static esp_err_t cli_command_transmit_task(void) return ESP_OK; } +static void cli_command_transmit_task_delete(void) +{ + if (cli_transmit_task) + { + vTaskDelete(cli_transmit_task); + } +} + static esp_netif_t * init_openthread_netif(const esp_openthread_platform_config_t * config) { esp_netif_config_t cfg = ESP_NETIF_DEFAULT_OPENTHREAD(); @@ -141,7 +151,6 @@ static void ot_task_worker(void * context) #if defined(CONFIG_OPENTHREAD_BORDER_ROUTER) && defined(CONFIG_AUTO_UPDATE_RCP) static constexpr size_t kRcpVersionMaxSize = 100; -static const char * TAG = "RCP_UPDATE"; static void update_rcp(void) { @@ -230,7 +239,15 @@ esp_err_t openthread_init_stack(void) }; ESP_ERROR_CHECK(esp_netif_init()); - ESP_ERROR_CHECK(esp_vfs_eventfd_register(&eventfd_config)); + esp_err_t err = esp_vfs_eventfd_register(&eventfd_config); + if (err == ESP_ERR_INVALID_STATE) + { + ESP_LOGW(TAG, "eventfd is already registered"); + } + else if (err != ESP_OK) + { + return err; + } assert(s_platform_config); // Initialize the OpenThread stack ESP_ERROR_CHECK(esp_openthread_init(s_platform_config)); @@ -248,6 +265,24 @@ esp_err_t openthread_init_stack(void) esp_err_t openthread_launch_task(void) { - xTaskCreate(ot_task_worker, "ot_task", CONFIG_THREAD_TASK_STACK_SIZE, xTaskGetCurrentTaskHandle(), 5, NULL); + xTaskCreate(ot_task_worker, "ot_task", CONFIG_THREAD_TASK_STACK_SIZE, xTaskGetCurrentTaskHandle(), 5, &openthread_task); return ESP_OK; } + +esp_err_t openthread_deinit_stack(void) +{ + esp_openthread_netif_glue_deinit(); + esp_netif_destroy(openthread_netif); +#ifdef CONFIG_OPENTHREAD_CLI + cli_command_transmit_task_delete(); +#endif + return esp_openthread_deinit(); +} + +void openthread_delete_task(void) +{ + if (openthread_task) + { + vTaskDelete(openthread_task); + } +} diff --git a/src/platform/ESP32/OpenthreadLauncher.h b/src/platform/ESP32/OpenthreadLauncher.h index a15125f948d1dc..daeebd153c6698 100644 --- a/src/platform/ESP32/OpenthreadLauncher.h +++ b/src/platform/ESP32/OpenthreadLauncher.h @@ -29,4 +29,6 @@ esp_err_t openthread_init_br_rcp(const esp_rcp_update_config_t * update_config); esp_err_t set_openthread_platform_config(esp_openthread_platform_config_t * config); esp_err_t openthread_init_stack(void); esp_err_t openthread_launch_task(void); +esp_err_t openthread_deinit_stack(void); +void openthread_delete_task(void); CHIP_ERROR cli_transmit_task_post(std::unique_ptr && cli_str); diff --git a/src/platform/ESP32/nimble/BLEManagerImpl.cpp b/src/platform/ESP32/nimble/BLEManagerImpl.cpp index ff48f5d9d6aa78..176fd81ee9f2c9 100644 --- a/src/platform/ESP32/nimble/BLEManagerImpl.cpp +++ b/src/platform/ESP32/nimble/BLEManagerImpl.cpp @@ -48,7 +48,9 @@ #include #include +#ifndef CONFIG_IDF_TARGET_ESP32P4 #include "esp_bt.h" +#endif #include "esp_log.h" #if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) @@ -1021,6 +1023,11 @@ CHIP_ERROR BLEManagerImpl::DeinitBLE() return MapBLEError(err); } +#ifdef CONFIG_IDF_TARGET_ESP32P4 +// Stub function to avoid link error +extern "C" void ble_transport_ll_deinit(void) {} +#endif + CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) { CHIP_ERROR err; diff --git a/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHost.cpp b/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHost.cpp index f33058f8e9af99..0332b687fcdfde 100644 --- a/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHost.cpp +++ b/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHost.cpp @@ -838,7 +838,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -854,7 +854,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); + result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1sin), w1sin_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); diff --git a/src/platform/Linux/BUILD.gn b/src/platform/Linux/BUILD.gn index 35b5047c9f4c00..7961b3d648da8f 100644 --- a/src/platform/Linux/BUILD.gn +++ b/src/platform/Linux/BUILD.gn @@ -22,10 +22,6 @@ import("${chip_root}/src/platform/device.gni") assert(chip_device_platform == "linux") -if (chip_use_pw_logging) { - import("//build_overrides/pigweed.gni") -} - if (chip_enable_openthread) { import("//build_overrides/openthread.gni") import("//build_overrides/ot_br_posix.gni") @@ -141,10 +137,6 @@ static_library("Linux") { public_deps += [ "dbus/openthread" ] } - if (chip_use_pw_logging) { - deps += [ "$dir_pw_log" ] - } - if (chip_enable_wifi) { sources += [ "NetworkCommissioningWiFiDriver.cpp" ] @@ -162,9 +154,5 @@ source_set("logging") { "${chip_root}/src/platform/logging:headers", ] - if (chip_use_pw_logging) { - deps += [ "$dir_pw_log" ] - } - sources = [ "Logging.cpp" ] } diff --git a/src/platform/Linux/Logging.cpp b/src/platform/Linux/Logging.cpp index 25e132e1a12b76..8a247f5e848495 100644 --- a/src/platform/Linux/Logging.cpp +++ b/src/platform/Linux/Logging.cpp @@ -12,10 +12,6 @@ #include #include -#if CHIP_USE_PW_LOGGING -#include -#endif // CHIP_USE_PW_LOGGING - namespace chip { namespace DeviceLayer { @@ -43,7 +39,6 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) // indicate the error occurred during getting time. gettimeofday(&tv, nullptr); -#if !CHIP_USE_PW_LOGGING // Lock standard output, so a single log line will not be corrupted in case // where multiple threads are using logging subsystem at the same time. flockfile(stdout); @@ -55,30 +50,6 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) fflush(stdout); funlockfile(stdout); -#else // !CHIP_USE_PW_LOGGING - char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; - snprintf(formattedMsg, sizeof(formattedMsg), - "[%" PRIu64 ".%06" PRIu64 "][%lld:%lld] CHIP:%s: ", static_cast(tv.tv_sec), - static_cast(tv.tv_usec), static_cast(syscall(SYS_getpid)), - static_cast(syscall(SYS_gettid)), module); - size_t len = strnlen(formattedMsg, sizeof(formattedMsg)); - vsnprintf(formattedMsg + len, sizeof(formattedMsg) - len, msg, v); - - switch (static_cast(category)) - { - case kLogCategory_Error: - PW_LOG_ERROR("%s", formattedMsg); - break; - case kLogCategory_Progress: - PW_LOG_INFO("%s", formattedMsg); - break; - case kLogCategory_Detail: - case kLogCategory_None: - case kLogCategory_Automation: - PW_LOG_DEBUG("%s", formattedMsg); - break; - } -#endif // !CHIP_USE_PW_LOGGING // Let the application know that a log message has been emitted. DeviceLayer::OnLogOutput(); diff --git a/src/platform/Linux/PlatformManagerImpl.cpp b/src/platform/Linux/PlatformManagerImpl.cpp index dba3cb447d30d8..ce33209e7429ac 100644 --- a/src/platform/Linux/PlatformManagerImpl.cpp +++ b/src/platform/Linux/PlatformManagerImpl.cpp @@ -274,9 +274,13 @@ void PlatformManagerImpl::_Shutdown() Internal::GenericPlatformManagerImpl_POSIX::_Shutdown(); #if CHIP_DEVICE_CONFIG_WITH_GLIB_MAIN_LOOP - g_main_loop_quit(mGLibMainLoop); - g_thread_join(mGLibMainLoopThread); - g_main_loop_unref(mGLibMainLoop); + if (mGLibMainLoop != nullptr) + { + g_main_loop_quit(mGLibMainLoop); + g_thread_join(mGLibMainLoopThread); + g_main_loop_unref(mGLibMainLoop); + mGLibMainLoop = nullptr; + } #endif } diff --git a/src/platform/NuttX/BUILD.gn b/src/platform/NuttX/BUILD.gn index 346c7d60ed0bdf..65113454ee06fb 100644 --- a/src/platform/NuttX/BUILD.gn +++ b/src/platform/NuttX/BUILD.gn @@ -22,10 +22,6 @@ import("${chip_root}/src/platform/device.gni") assert(chip_device_platform == "linux" || chip_device_platform == "nuttx") -if (chip_use_pw_logging) { - import("//build_overrides/pigweed.gni") -} - if (chip_enable_openthread) { import("//build_overrides/openthread.gni") import("//build_overrides/ot_br_posix.gni") @@ -156,9 +152,5 @@ source_set("logging") { "${chip_root}/src/platform/logging:headers", ] - if (chip_use_pw_logging) { - deps += [ "$dir_pw_log" ] - } - sources = [ "Logging.cpp" ] } diff --git a/src/platform/NuttX/Logging.cpp b/src/platform/NuttX/Logging.cpp index ea95fdc4fbc7ef..6d92a2ba54eb5a 100644 --- a/src/platform/NuttX/Logging.cpp +++ b/src/platform/NuttX/Logging.cpp @@ -12,10 +12,6 @@ #include #include -#if CHIP_USE_PW_LOGGING -#include -#endif // CHIP_USE_PW_LOGGING - namespace chip { namespace DeviceLayer { @@ -43,7 +39,6 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) // indicate the error occurred during getting time. gettimeofday(&tv, nullptr); -#if !CHIP_USE_PW_LOGGING // Lock standard output, so a single log line will not be corrupted in case // where multiple threads are using logging subsystem at the same time. flockfile(stdout); @@ -55,30 +50,6 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) fflush(stdout); funlockfile(stdout); -#else // !CHIP_USE_PW_LOGGING - char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; - snprintf(formattedMsg, sizeof(formattedMsg), - "[%" PRIu64 ".%06" PRIu64 "][%lld:%lld] CHIP:%s: ", static_cast(tv.tv_sec), - static_cast(tv.tv_usec), static_cast(syscall(SYS_getpid)), - static_cast(syscall(SYS_gettid)), module); - size_t len = strnlen(formattedMsg, sizeof(formattedMsg)); - vsnprintf(formattedMsg + len, sizeof(formattedMsg) - len, msg, v); - - switch (static_cast(category)) - { - case kLogCategory_Error: - PW_LOG_ERROR("%s", formattedMsg); - break; - case kLogCategory_Progress: - PW_LOG_INFO("%s", formattedMsg); - break; - case kLogCategory_Detail: - case kLogCategory_None: - case kLogCategory_Automation: - PW_LOG_DEBUG("%s", formattedMsg); - break; - } -#endif // !CHIP_USE_PW_LOGGING // Let the application know that a log message has been emitted. DeviceLayer::OnLogOutput(); diff --git a/src/platform/logging/BUILD.gn b/src/platform/logging/BUILD.gn index eb3c62154ce436..e415448a7f12d1 100644 --- a/src/platform/logging/BUILD.gn +++ b/src/platform/logging/BUILD.gn @@ -12,10 +12,6 @@ group("default") { if (chip_logging_backend == "platform") { deps = [] - if (chip_use_pw_logging) { - deps += [ "$dir_pw_log" ] - } - if (chip_device_platform == "cyw30739") { deps += [ "${chip_root}/src/platform/Infineon/CYW30739:logging" ] } else if (chip_device_platform == "psoc6") { diff --git a/src/platform/nxp/common/CHIPDeviceNXPPlatformDefaultConfig.h b/src/platform/nxp/common/CHIPDeviceNXPPlatformDefaultConfig.h index c4e77e87b4b9ad..5d8825bc8a6e6d 100644 --- a/src/platform/nxp/common/CHIPDeviceNXPPlatformDefaultConfig.h +++ b/src/platform/nxp/common/CHIPDeviceNXPPlatformDefaultConfig.h @@ -27,6 +27,26 @@ // ==================== Platform Adaptations ==================== +#ifdef CONFIG_CHIP_USE_GENERATED_CONFIG +#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID CONFIG_CHIP_DEVICE_VENDOR_ID +#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME CONFIG_CHIP_DEVICE_VENDOR_NAME +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID CONFIG_CHIP_DEVICE_PRODUCT_ID +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME CONFIG_CHIP_DEVICE_PRODUCT_NAME +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION CONFIG_CHIP_DEVICE_HARDWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING CONFIG_CHIP_DEVICE_HARDWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION CONFIG_CHIP_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING CONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_TEST_MANUFACTURING_DATE CONFIG_CHIP_DEVICE_MANUFACTURING_DATE +#define CHIP_DEVICE_CONFIG_DEVICE_TYPE CONFIG_CHIP_DEVICE_TYPE + +#if !CONFIG_CHIP_PLAT_LOAD_REAL_FACTORY_DATA +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR CONFIG_CHIP_DEVICE_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE CONFIG_CHIP_DEVICE_SPAKE2_PASSCODE +#define CHIP_DEVICE_CONFIG_USE_TEST_PAIRING_CODE CONFIG_CHIP_DEVICE_USE_TEST_PAIRING_CODE +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER CONFIG_CHIP_DEVICE_SERIAL_NUMBER +#endif // CONFIG_CHIP_PLAT_LOAD_REAL_FACTORY_DATA +#endif // CONFIG_CHIP_USE_GENERATED_CONFIG + #ifndef CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION #if CONFIG_CHIP_WIFI || CHIP_DEVICE_CONFIG_ENABLE_WPA #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 1 @@ -39,12 +59,16 @@ #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP -#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD -#define CHIP_DEVICE_CONFIG_ENABLE_UNPROVISIONED_MDNS 1 -#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD - #ifndef CHIP_DEVICE_CONFIG_ENABLE_THREAD +#ifdef CONFIG_NET_L2_OPENTHREAD +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD CONFIG_NET_L2_OPENTHREAD +#else #define CHIP_DEVICE_CONFIG_ENABLE_THREAD 0 +#endif // CONFIG_NET_L2_OPENTHREAD +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD + +#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD +#define CHIP_DEVICE_CONFIG_ENABLE_UNPROVISIONED_MDNS 1 #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD #ifndef CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/nxp/common/CHIPNXPPlatformDefaultConfig.h b/src/platform/nxp/common/CHIPNXPPlatformDefaultConfig.h index c90619bdddc040..5bbc7ef7c593b1 100644 --- a/src/platform/nxp/common/CHIPNXPPlatformDefaultConfig.h +++ b/src/platform/nxp/common/CHIPNXPPlatformDefaultConfig.h @@ -254,6 +254,15 @@ #define CHIP_CONFIG_RMP_DEFAULT_MAX_RETRANS 10 #endif +/* Increasing the retransmission interval of the MRP messages after subsequent failures */ +#ifndef CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL +#ifdef CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL +#define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL +#else +#define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL (2000_ms32) +#endif // CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL +#endif // CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL + #ifndef NXP_USE_MML /* Do not use Memory Manager Light for dynamic memory allocation by default. */ #define NXP_USE_MML 0 diff --git a/src/platform/nxp/common/NetworkCommissioningWiFiDriver.cpp b/src/platform/nxp/common/NetworkCommissioningWiFiDriver.cpp index f1f35937d8b24e..ca93f091cf9661 100644 --- a/src/platform/nxp/common/NetworkCommissioningWiFiDriver.cpp +++ b/src/platform/nxp/common/NetworkCommissioningWiFiDriver.cpp @@ -144,6 +144,8 @@ Status NXPWiFiDriver::RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDeb { outDebugText.reduce_size(0); outNetworkIndex = 0; + VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); + // Use empty ssid for representing invalid network mStagingNetwork.ssidLen = 0; diff --git a/src/platform/nxp/common/ble/BLEManagerCommon.cpp b/src/platform/nxp/common/ble/BLEManagerCommon.cpp index e970dab55cc232..baba33ecdab48c 100644 --- a/src/platform/nxp/common/ble/BLEManagerCommon.cpp +++ b/src/platform/nxp/common/ble/BLEManagerCommon.cpp @@ -1190,7 +1190,7 @@ void BLEManagerCommon::blekw_gap_connection_cb(deviceId_t deviceId, gapConnectio if (pConnectionEvent->eventType == gConnEvtConnected_c) { -#if CHIP_DEVICE_K32W1 +#if NXP_DEVICE_K32W1_MCXW7X #if defined(nxp_use_low_power) && (nxp_use_low_power == 1) /* Disallow must be called here for K32W1, otherwise an assert will be reached. * Disclaimer: this is a workaround until a better cross platform solution is found. */ diff --git a/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp b/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp index 9c6334bded2da6..e23453eb97b1df 100644 --- a/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp +++ b/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp @@ -1051,7 +1051,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -1061,7 +1061,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le uECC_word_t w1_bn[NUM_ECC_WORDS]; uECC_word_t L_tmp[2 * NUM_ECC_WORDS]; - uECC_vli_bytesToNative(tmp, w1in, NUM_ECC_BYTES); + uECC_vli_bytesToNative(tmp, w1sin, NUM_ECC_BYTES); uECC_vli_mmod(w1_bn, tmp, curve_n); diff --git a/src/platform/nxp/common/crypto/CHIPCryptoPalS200.cpp b/src/platform/nxp/common/crypto/CHIPCryptoPalS200.cpp index 6e9342658c7ddd..21e76c69d79b92 100644 --- a/src/platform/nxp/common/crypto/CHIPCryptoPalS200.cpp +++ b/src/platform/nxp/common/crypto/CHIPCryptoPalS200.cpp @@ -1138,13 +1138,13 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { secEcp256Status_t result; ecp256Point_t gen_point; uint32_t W1[SEC_ECP256_COORDINATE_WLEN]; - result = ECP256_ModularReductionN(W1, w1in, w1in_len); + result = ECP256_ModularReductionN(W1, w1sin, w1sin_len); VerifyOrReturnError(result == gSecEcp256Success_c, CHIP_ERROR_INTERNAL); result = ECP256_GeneratePublicKey((uint8_t *) &gen_point, (uint8_t *) &W1, NULL); diff --git a/src/platform/nxp/crypto/se05x/CHIPCryptoPALHost.cpp b/src/platform/nxp/crypto/se05x/CHIPCryptoPALHost.cpp index ffc626c201d373..68a38a98f405d6 100644 --- a/src/platform/nxp/crypto/se05x/CHIPCryptoPALHost.cpp +++ b/src/platform/nxp/crypto/se05x/CHIPCryptoPALHost.cpp @@ -712,7 +712,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -728,7 +728,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); + result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1sin), w1sin_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); diff --git a/src/platform/nxp/crypto/se05x/CHIPCryptoPALHsm_se05x_spake2p.cpp b/src/platform/nxp/crypto/se05x/CHIPCryptoPALHsm_se05x_spake2p.cpp index 84216185a68f6e..ee2bb79b1a02d0 100644 --- a/src/platform/nxp/crypto/se05x/CHIPCryptoPALHsm_se05x_spake2p.cpp +++ b/src/platform/nxp/crypto/se05x/CHIPCryptoPALHsm_se05x_spake2p.cpp @@ -283,8 +283,8 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginVerifier(const uint8_t * my_id #if ENABLE_SE05X_SPAKE_PROVER CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, size_t peer_identity_len, - const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, - size_t w1in_len) + const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin, + size_t w1sin_len) { smStatus_t smstatus = SM_NOT_OK; uint8_t w0in_mod[32] = { @@ -296,8 +296,8 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_iden }; size_t w1in_mod_len = 32; - VerifyOrReturnError(w0in != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(w1in != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(w0sin != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(w1sin != nullptr, CHIP_ERROR_INVALID_ARGUMENT); if (my_identity_len > 0) { VerifyOrReturnError(my_identity != nullptr, CHIP_ERROR_INVALID_ARGUMENT); @@ -311,9 +311,9 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_iden ChipLogProgress(Crypto, "SE05x: HSM - BeginProver"); - ReturnErrorOnFailure(FELoad(w0in, w0in_len, w0)); + ReturnErrorOnFailure(FELoad(w0sin, w0sin_len, w0)); ReturnErrorOnFailure(FEWrite(w0, w0in_mod, w0in_mod_len)); - ReturnErrorOnFailure(FELoad(w1in, w1in_len, w1)); + ReturnErrorOnFailure(FELoad(w1sin, w1sin_len, w1)); ReturnErrorOnFailure(FEWrite(w1, w1in_mod, w1in_mod_len)); ReturnErrorOnFailure(create_init_crypto_obj(chip::Crypto::CHIP_SPAKE2P_ROLE::PROVER, &hsm_pake_context)); diff --git a/src/platform/nxp/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp b/src/platform/nxp/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp index 8b30cdd0ce7b78..25aa5313ec1e5e 100644 --- a/src/platform/nxp/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp +++ b/src/platform/nxp/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp @@ -1017,7 +1017,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; @@ -1026,7 +1026,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le uint32_t W1[SEC_ECP256_COORDINATE_WLEN]; do { - result = ECP256_ModularReductionN(W1, w1in, w1in_len); + result = ECP256_ModularReductionN(W1, w1sin, w1sin_len); if (result != gSecEcp256Success_c) break; ecp256Point_t gen_point; diff --git a/src/platform/nxp/mcxw71_k32w1/BUILD.gn b/src/platform/nxp/mcxw71_k32w1/BUILD.gn index 9de3c0e5b3c7e0..865475d1e43e22 100644 --- a/src/platform/nxp/mcxw71_k32w1/BUILD.gn +++ b/src/platform/nxp/mcxw71_k32w1/BUILD.gn @@ -89,7 +89,7 @@ config("nxp_platform_config") { static_library("nxp_platform") { deps = [] defines = [ - "CHIP_DEVICE_K32W1=1", + "NXP_DEVICE_K32W1_MCXW7X=1", "NXP_USE_MML=1", ] diff --git a/src/platform/silabs/BLEManagerImpl.h b/src/platform/silabs/BLEManagerImpl.h index 9ebf113c4f8afa..6c639a7a777faf 100644 --- a/src/platform/silabs/BLEManagerImpl.h +++ b/src/platform/silabs/BLEManagerImpl.h @@ -27,13 +27,7 @@ #include "FreeRTOS.h" #include "timers.h" #if (SLI_SI91X_ENABLE_BLE || RSI_BLE_ENABLE) -#ifdef __cplusplus -extern "C" { -#endif // __cplusplus #include "wfx_sl_ble_init.h" -#ifdef __cplusplus -} -#endif // __cplusplus #else #include "gatt_db.h" #include "sl_bgapi.h" diff --git a/src/platform/silabs/CHIPDevicePlatformEvent.h b/src/platform/silabs/CHIPDevicePlatformEvent.h index 8ab1e21b4573bb..090ada64037c6f 100644 --- a/src/platform/silabs/CHIPDevicePlatformEvent.h +++ b/src/platform/silabs/CHIPDevicePlatformEvent.h @@ -26,7 +26,7 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION -#include "wfx_host_events.h" +#include #endif namespace chip { diff --git a/src/platform/silabs/ConfigurationManagerImpl.cpp b/src/platform/silabs/ConfigurationManagerImpl.cpp index 0219852813f28e..3a144eb1160370 100644 --- a/src/platform/silabs/ConfigurationManagerImpl.cpp +++ b/src/platform/silabs/ConfigurationManagerImpl.cpp @@ -31,7 +31,7 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION -#include "wfx_host_events.h" +#include #endif namespace chip { diff --git a/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp b/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp index 2dd946feb12a6d..0d9d63317ef637 100644 --- a/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp +++ b/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp @@ -40,7 +40,7 @@ #endif #include "CHIPDevicePlatformConfig.h" -#include "wfx_host_events.h" +#include using namespace ::chip; using namespace ::chip::Inet; diff --git a/src/platform/silabs/NetworkCommissioningWiFiDriver.h b/src/platform/silabs/NetworkCommissioningWiFiDriver.h index f152edb343cbf2..12986b998736be 100644 --- a/src/platform/silabs/NetworkCommissioningWiFiDriver.h +++ b/src/platform/silabs/NetworkCommissioningWiFiDriver.h @@ -18,7 +18,7 @@ #pragma once #if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION #include -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/silabs/PlatformManagerImpl.cpp b/src/platform/silabs/PlatformManagerImpl.cpp index 20d7b94ada5edf..b3d7f80052dd3a 100644 --- a/src/platform/silabs/PlatformManagerImpl.cpp +++ b/src/platform/silabs/PlatformManagerImpl.cpp @@ -135,9 +135,17 @@ void PlatformManagerImpl::_Shutdown() Internal::GenericPlatformManagerImpl_CMSISOS::_Shutdown(); } +} // namespace DeviceLayer +} // namespace chip + #if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION -void PlatformManagerImpl::HandleWFXSystemEvent(wfx_event_base_t eventBase, sl_wfx_generic_message_t * eventData) +// This function needs to be global so it can be used from the platform implementation without depending on the platfrom itself. +// This is a workaround to avoid a circular dependency. +void HandleWFXSystemEvent(wfx_event_base_t eventBase, sl_wfx_generic_message_t * eventData) { + using namespace chip; + using namespace chip::DeviceLayer; + ChipDeviceEvent event; memset(&event, 0, sizeof(event)); event.Type = DeviceEventType::kWFXSystemEvent; @@ -200,9 +208,7 @@ void PlatformManagerImpl::HandleWFXSystemEvent(wfx_event_base_t eventBase, sl_wf } } - (void) sInstance.PostEvent(&event); + // TODO: We should add error processing here + (void) PlatformMgr().PostEvent(&event); } #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/silabs/PlatformManagerImpl.h b/src/platform/silabs/PlatformManagerImpl.h index 1abbb9f07f5e7b..dddc491384a86f 100644 --- a/src/platform/silabs/PlatformManagerImpl.h +++ b/src/platform/silabs/PlatformManagerImpl.h @@ -26,10 +26,14 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION -#include "wfx_host_events.h" +#include #endif #include +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION +void HandleWFXSystemEvent(wfx_event_base_t eventBase, sl_wfx_generic_message_t * eventData); +#endif + namespace chip { namespace DeviceLayer { @@ -62,9 +66,6 @@ class PlatformManagerImpl final : public PlatformManager, public Internal::Gener public: // ===== Platform-specific members that may be accessed directly by the application. -#if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION - void HandleWFXSystemEvent(wfx_event_base_t eventBase, sl_wfx_generic_message_t * eventData); -#endif System::Clock::Timestamp GetStartTime() { return mStartTime; } diff --git a/src/platform/silabs/SiWx917/BUILD.gn b/src/platform/silabs/SiWx917/BUILD.gn index 0c2f9032e4bc81..826d8accd974d7 100644 --- a/src/platform/silabs/SiWx917/BUILD.gn +++ b/src/platform/silabs/SiWx917/BUILD.gn @@ -18,7 +18,7 @@ import("${chip_root}/src/platform/device.gni") import("${chip_root}/build/chip/buildconfig_header.gni") import("${chip_root}/src/crypto/crypto.gni") -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") import("${chip_root}/third_party/silabs/silabs_board.gni") @@ -30,10 +30,14 @@ if (chip_crypto == "platform") { import("//build_overrides/mbedtls.gni") } -config("siwx917-platform-wifi-config") { - include_dirs = [ "wifi" ] - defines = [] +source_set("logging") { + sources = [ "${chip_root}/src/platform/silabs/Logging.cpp" ] + deps = [ + "${chip_root}/src/platform:platform_base", + "${chip_root}/src/platform/logging:headers", + ] } + static_library("SiWx917") { sources = [ "${silabs_platform_dir}/BLEManagerImpl.h", @@ -45,6 +49,7 @@ static_library("SiWx917") { "${silabs_platform_dir}/ConfigurationManagerImpl.cpp", "${silabs_platform_dir}/ConfigurationManagerImpl.h", "${silabs_platform_dir}/ConnectivityManagerImpl.h", + "${silabs_platform_dir}/ConnectivityManagerImpl_WIFI.cpp", "${silabs_platform_dir}/DiagnosticDataProviderImpl.cpp", "${silabs_platform_dir}/DiagnosticDataProviderImpl.h", "${silabs_platform_dir}/InetPlatformConfig.h", @@ -52,6 +57,8 @@ static_library("SiWx917") { "${silabs_platform_dir}/KeyValueStoreManagerImpl.h", "${silabs_platform_dir}/MigrationManager.cpp", "${silabs_platform_dir}/MigrationManager.h", + "${silabs_platform_dir}/NetworkCommissioningWiFiDriver.cpp", + "${silabs_platform_dir}/NetworkCommissioningWiFiDriver.h", "${silabs_platform_dir}/PlatformManagerImpl.cpp", "${silabs_platform_dir}/PlatformManagerImpl.h", "${silabs_platform_dir}/SilabsConfig.cpp", @@ -66,6 +73,7 @@ static_library("SiWx917") { "../rs911x/rsi_ble_config.h", "../rs911x/wfx_sl_ble_init.cpp", "../rs911x/wfx_sl_ble_init.h", + "SiWxPlatformInterface.h", ] if (chip_enable_ota_requestor) { @@ -94,23 +102,7 @@ static_library("SiWx917") { public_deps += [ "${chip_root}/src/crypto", "${mbedtls_root}:mbedtls", + "${silabs_platform_dir}/wifi:wifi-platform", ] } - - sources += [ - "${silabs_platform_dir}/ConnectivityManagerImpl_WIFI.cpp", - "${silabs_platform_dir}/NetworkCommissioningWiFiDriver.cpp", - "${silabs_platform_dir}/NetworkCommissioningWiFiDriver.h", - "${silabs_platform_dir}/wifi/wfx_host_events.h", - "wifi/wfx_msgs.h", - ] - public_configs = [ ":siwx917-platform-wifi-config" ] -} - -source_set("logging") { - sources = [ "${chip_root}/src/platform/silabs/Logging.cpp" ] - deps = [ - "${chip_root}/src/platform:platform_base", - "${chip_root}/src/platform/logging:headers", - ] } diff --git a/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp b/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp index 05fa10c5832ac2..b8278b359d5233 100644 --- a/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp +++ b/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp @@ -1070,7 +1070,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -1080,7 +1080,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le uECC_word_t w1_bn[NUM_ECC_WORDS]; uECC_word_t L_tmp[2 * NUM_ECC_WORDS]; - uECC_vli_bytesToNative(tmp, w1in, NUM_ECC_BYTES); + uECC_vli_bytesToNative(tmp, w1sin, NUM_ECC_BYTES); uECC_vli_mmod(w1_bn, tmp, curve_n); diff --git a/src/platform/silabs/SiWx917/OTAImageProcessorImpl.cpp b/src/platform/silabs/SiWx917/OTAImageProcessorImpl.cpp index bccb704ad18cab..bce64cbac87ff9 100644 --- a/src/platform/silabs/SiWx917/OTAImageProcessorImpl.cpp +++ b/src/platform/silabs/SiWx917/OTAImageProcessorImpl.cpp @@ -20,8 +20,8 @@ #include #include -#include "wfx_host_events.h" #include +#include #ifdef __cplusplus extern "C" { #endif diff --git a/src/platform/silabs/SiWx917/SiWxPlatformInterface.h b/src/platform/silabs/SiWx917/SiWxPlatformInterface.h new file mode 100644 index 00000000000000..8589db3b3f4484 --- /dev/null +++ b/src/platform/silabs/SiWx917/SiWxPlatformInterface.h @@ -0,0 +1,111 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif +#if CHIP_CONFIG_ENABLE_ICD_SERVER +#if SLI_SI91X_MCU_INTERFACE +#include "sl_si91x_button.h" +#include "sl_si91x_button_pin_config.h" +#include "sl_si91x_driver_gpio.h" + +/** + * @brief invoked when button press event is received when in sleep + * @param[in] pin_intr GPIO pin interrupt number. + * @return none. + * @note this is a callback from the Wiseconnect SDK + */ +void gpio_uulp_pin_interrupt_callback(uint32_t pin_intr) +{ + // UULP_GPIO_2 is used to detect the button 0 press + VerifyOrReturn(pin_intr == RTE_UULP_GPIO_2_PIN, ChipLogError(DeviceLayer, "invalid pin interrupt: %ld", pin_intr)); + sl_status_t status = SL_STATUS_OK; + uint8_t pin_intr_status = sl_si91x_gpio_get_uulp_npss_pin(pin_intr); + if (pin_intr_status == LOW) + { + // BTN_0 is pressed + // NOTE: the GPIO is masked since the interrupt is invoked before scheduler is started, thus this is required to hand over + // control to scheduler, the PIN is unmasked in the power manager flow before going to sleep + status = sl_si91x_gpio_driver_mask_uulp_npss_interrupt(BIT(pin_intr)); + VerifyOrReturn(status == SL_STATUS_OK, ChipLogError(DeviceLayer, "failed to mask interrupt: %ld", status)); + } +} + +#endif // SLI_SI91X_MCU_INTERFACE +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER +#ifdef __cplusplus +} +#endif + +namespace chip { +namespace DeviceLayer { +namespace Silabs { +namespace SiWxPlatformInterface { + +#if CHIP_CONFIG_ENABLE_ICD_SERVER +#if SLI_SI91X_MCU_INTERFACE +/** + * @brief Required to invoke button press event during sleep as falling edge is not detected + * @param[in] none. + * @note flow is GPIO wakeup due to BTN0 press -> check button state in idle task required as the GPIO interrupt is not + * detected during sleep for BUTTON RELEASED + */ +inline void sl_si91x_btn_event_handler() +{ + sl_button_on_change(SL_BUTTON_BTN0_NUMBER, + (sl_si91x_gpio_get_uulp_npss_pin(SL_BUTTON_BTN0_PIN) == LOW) ? BUTTON_PRESSED : BUTTON_RELEASED); +} + +/** + * @brief Required to enable MATTER shell UART with ICD feature flag + * @param[in] none. + * @note this requires hardware jumping of the GPIO PINs to work with the baseboard. + */ +void sl_si91x_uart_power_requirement_handler() +{ +#ifdef ENABLE_CHIP_SHELL + // Checking the UULP PIN 1 status to reinit the UART and not allow the device to go to sleep + if (sl_si91x_gpio_get_uulp_npss_pin(RTE_UULP_GPIO_1_PIN)) + { + if (!ps_requirement_added) + { + sl_si91x_power_manager_add_ps_requirement(SL_SI91X_POWER_MANAGER_PS4); + ps_requirement_added = true; + } + } + else + { + if (ps_requirement_added) + { + sl_si91x_power_manager_remove_ps_requirement(SL_SI91X_POWER_MANAGER_PS4); + ps_requirement_added = false; + } + } +#endif // ENABLE_CHIP_SHELL +} + +#endif // SLI_SI91X_MCU_INTERFACE +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER +} // namespace SiWxPlatformInterface +} // namespace Silabs +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/silabs/efr32/BLEManagerImpl.cpp b/src/platform/silabs/efr32/BLEManagerImpl.cpp index 1f8704896f71cb..44956572a68f91 100644 --- a/src/platform/silabs/efr32/BLEManagerImpl.cpp +++ b/src/platform/silabs/efr32/BLEManagerImpl.cpp @@ -343,7 +343,7 @@ CHIP_ERROR BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const C void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) { - // Nothing to do + CloseConnection(conId); } CHIP_ERROR BLEManagerImpl::MapBLEError(int bleErr) diff --git a/src/platform/silabs/efr32/BUILD.gn b/src/platform/silabs/efr32/BUILD.gn index b1e50faafca0e0..f39628d4845726 100644 --- a/src/platform/silabs/efr32/BUILD.gn +++ b/src/platform/silabs/efr32/BUILD.gn @@ -20,8 +20,6 @@ import("${chip_root}/src/platform/device.gni") import("${chip_root}/third_party/silabs/efr32_sdk.gni") import("${chip_root}/third_party/silabs/silabs_board.gni") -silabs_platform_dir = "${chip_root}/src/platform/silabs" - assert(chip_device_platform == "efr32") if (chip_enable_openthread) { @@ -32,9 +30,12 @@ if (chip_crypto == "platform") { import("//build_overrides/mbedtls.gni") } -config("efr32-platform-wifi-config") { - include_dirs = [ "wifi" ] - defines = [] +source_set("logging") { + sources = [ "${chip_root}/src/platform/silabs/Logging.cpp" ] + deps = [ + "${chip_root}/src/platform:platform_base", + "${chip_root}/src/platform/logging:headers", + ] } static_library("efr32") { @@ -159,27 +160,8 @@ static_library("efr32") { "${silabs_platform_dir}/ConnectivityManagerImpl_WIFI.cpp", "${silabs_platform_dir}/NetworkCommissioningWiFiDriver.cpp", "${silabs_platform_dir}/NetworkCommissioningWiFiDriver.h", - "${silabs_platform_dir}/wifi/wfx_host_events.h", - "wifi/wfx_msgs.h", ] - if (use_wf200 || use_rs9116) { - sources += [ - "${silabs_platform_dir}/wifi/dhcp_client.cpp", - "wifi/ethernetif.cpp", - "wifi/ethernetif.h", - "wifi/lwip_netif.cpp", - ] - } - - public_configs += [ ":efr32-platform-wifi-config" ] + public_deps += [ "${silabs_platform_dir}/wifi:wifi-platform" ] } } - -source_set("logging") { - sources = [ "${chip_root}/src/platform/silabs/Logging.cpp" ] - deps = [ - "${chip_root}/src/platform:platform_base", - "${chip_root}/src/platform/logging:headers", - ] -} diff --git a/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp b/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp index 8028d84d92c40c..a1811a1093337a 100644 --- a/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp +++ b/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp @@ -1406,7 +1406,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -1418,7 +1418,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le mbedtls_mpi_init(&w1_bn); mbedtls_ecp_point_init(&Ltemp); - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); + result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1sin), w1sin_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &context->curve.N); diff --git a/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp b/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp index 4fc7f8d7424cdd..a884071560fb59 100644 --- a/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp +++ b/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp @@ -19,17 +19,17 @@ #include #include #include +#include + +#if SL_WIFI +#include +#endif // SL_WIFI extern "C" { #include "btl_interface.h" #include "sl_core.h" -#if SL_WIFI -#include "spi_multiplex.h" -#endif // SL_WIFI } -#include - /// No error, operation OK #define SL_BOOTLOADER_OK 0L diff --git a/src/platform/silabs/efr32/wifi/wfx_msgs.h b/src/platform/silabs/efr32/wifi/wfx_msgs.h deleted file mode 100644 index edf0aec5828fa7..00000000000000 --- a/src/platform/silabs/efr32/wifi/wfx_msgs.h +++ /dev/null @@ -1,182 +0,0 @@ -/* - * - * 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. - */ - -#ifndef _WFX_MSGS_H_ -#define _WFX_MSGS_H_ -/* - * Taken from sl_wfx firmware - so I can re-use. - * I need to do a better job than to use this stuff - * in the CPP files of Matter - */ -typedef struct -{ - uint8_t octet[6]; ///< Table to store a MAC address -} sl_wfx_mac_address_t; -/** - * @brief General Message header structure - * - */ -typedef struct __attribute__((__packed__)) sl_wfx_header_s -{ - uint16_t length; ///< Message length in bytes including this uint16_t. - ///< Maximum value is 8188 but maximum Request size is FW dependent and reported in the - ///< ::sl_wfx_startup_ind_body_t::size_inp_ch_buf. - uint8_t id; ///< Contains the message Id indexed by sl_wfx_general_commands_ids_t or sl_wfx_message_ids_t. - uint8_t info; ///< TODO comment missing -} sl_wfx_header_t; - -/** - * @brief Generic message structure for all requests, confirmations and indications - * - */ -typedef struct __attribute__((__packed__)) sl_wfx_generic_message_s -{ - sl_wfx_header_t header; ///< 4 bytes header - uint8_t body[]; ///< variable size payload of the message -} sl_wfx_generic_message_t; -#define SL_WFX_OPN_SIZE 14 -#define SL_WFX_UID_SIZE 8 -#define SL_WFX_DISABLED_CHANNEL_LIST_SIZE 2 -#define SL_WFX_FIRMWARE_LABEL_SIZE 128 -/** - * @brief Startup Indication message. - * This is the first message sent to the host to confirm boot success. - * It gives detailed information on the HW and FW versions and capabilities - */ -typedef struct __attribute__((__packed__)) sl_wfx_startup_ind_body_s -{ - uint32_t - status; ///< Initialization status. A value of zero indicates the boot is completed successfully (see enum sl_wfx_status_t) - uint16_t hardware_id; ///<=RO misc_read_reg7 register value -#if 0 /* Not used in RS911x for now - use stuff here for the port */ - uint8_t opn[SL_WFX_OPN_SIZE]; ///<=OTP part_OPN - uint8_t uid[SL_WFX_UID_SIZE]; ///<=OTP UID - uint16_t num_inp_ch_bufs; ///WFM_STATUS_SUCCESS: the connection request was completed successfully. - *
any other value: the connection request failed. - *
See sl_wfx_fmac_status_t for enumeration values. - */ - uint32_t status; - /** - * @brief MAC address of the connected access point. - */ - uint8_t mac[6]; - /** - * @brief Channel of the connected access point. - * @details 1 - 13: Channel number. - */ - uint16_t channel; - /** - * @brief Beacon Interval of the connected access point. - */ - uint8_t beacon_interval; - /** - * @brief DTIM period of the connected access point. - * @details 1 - 255: DTIM period. - */ - uint8_t dtim_period; - /** - * @brief Maximum PHY data rate supported by the connection. - * @details See sl_wfx_rate_index_t for enumeration values. - */ - uint16_t max_phy_rate; -} sl_wfx_connect_ind_body_t; - -/** - * @brief Indication message used to signal the completion of a connection operation. - * @details The device will send this indication to signal the connection request initiated - * with sl_wfx_connect_req_t has been completed. The indication is also sent when - * the device autonomously roams to another access point. - * @ingroup WFM_GROUP_MODE_IDLE - */ -typedef struct __attribute__((__packed__)) sl_wfx_connect_ind_s -{ - /** Common message header. */ - sl_wfx_header_t header; - /** Indication message body. */ - sl_wfx_connect_ind_body_t body; -} sl_wfx_connect_ind_t; -/** - * @brief Indication message body for sl_wfx_disconnect_ind_t. - */ -typedef struct __attribute__((__packed__)) sl_wfx_disconnect_ind_body_s -{ - /** - * @brief MAC address of the access point. - */ - uint8_t mac[6]; - /** - * @brief Reason for disconnection. - * @details WFM_DISCONNECTED_REASON_UNSPECIFIED: The device disconnected because of an internal error. - *
WFM_DISCONNECTED_REASON_AP_LOST: The device lost the AP beacons for too long. - *
WFM_DISCONNECTED_REASON_REJECTED: The device was disconnected by the AP. - *
WFM_DISCONNECTED_REASON_LEAVING_BSS: Disconnection was requested through the device API. - *
WFM_DISCONNECTED_REASON_WPA_COUNTERMEASURES: WPA countermeasures triggered a disconnection - *
See sl_wfx_disconnected_reason_t for enumeration values. - */ - uint16_t reason; -} sl_wfx_disconnect_ind_body_t; - -/** - * @brief Indication message used to signal the completion of a disconnection operation. - * @details The device will send this indication to signal the disconnection request initiated - * with sl_wfx_disconnect_req_t has been completed. The indication is also sent when - * the device has lost the connection to an access point and has been unable to regain it. - * @ingroup WFM_GROUP_MODE_STA - */ -typedef struct __attribute__((__packed__)) sl_wfx_disconnect_ind_s -{ - /** Common message header. */ - sl_wfx_header_t header; - /** Indication message body. */ - sl_wfx_disconnect_ind_body_t body; -} sl_wfx_disconnect_ind_t; - -#endif /* _WFX_MSGS_H_ */ diff --git a/src/platform/silabs/platformAbstraction/GsdkSpam.cpp b/src/platform/silabs/platformAbstraction/GsdkSpam.cpp index 92ddd281f8fe55..361dfa93a44aa2 100644 --- a/src/platform/silabs/platformAbstraction/GsdkSpam.cpp +++ b/src/platform/silabs/platformAbstraction/GsdkSpam.cpp @@ -15,12 +15,17 @@ * limitations under the License. */ +#include +#include #include - #if defined(_SILICON_LABS_32B_SERIES_2) +#include "em_msc.h" #include "em_rmu.h" -#else +#elif defined(_SILICON_LABS_32B_SERIES_3) #include "sl_hal_emu.h" +#include "sl_se_manager.h" +#include "sl_se_manager_types.h" +#include #endif // _SILICON_LABS_32B_SERIES_2 #include "sl_system_kernel.h" @@ -65,6 +70,18 @@ extern "C" { #include "silabs_utils.h" #endif +#if defined(_SILICON_LABS_32B_SERIES_3) +// To remove any ambiguities regarding the Flash aliases, use the below macro to ignore the 8 MSB. +#define FLASH_GENERIC_MASK 0x00FFFFFF +#define GENERIC_ADDRESS(addr) ((addr) &FLASH_GENERIC_MASK) + +// Transforms any address into an address using the same alias as FLASH_BASE from the CMSIS. +#define CMSIS_CONVERTED_ADDRESS(addr) (GENERIC_ADDRESS(addr) | FLASH_BASE) +namespace { +sl_se_command_context_t cmd_ctx; +} +#endif // _SILICON_LABS_32B_SERIES_3 + namespace chip { namespace DeviceLayer { namespace Silabs { @@ -107,6 +124,56 @@ CHIP_ERROR SilabsPlatform::Init(void) return CHIP_NO_ERROR; } +CHIP_ERROR SilabsPlatform::FlashInit() +{ +#if defined(_SILICON_LABS_32B_SERIES_2) + MSC_Init(); +#elif defined(_SILICON_LABS_32B_SERIES_3) + sl_status_t status; + status = sl_se_init(); + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); + status = sl_se_init_command_context(&cmd_ctx); + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); +#endif + return CHIP_NO_ERROR; +} + +CHIP_ERROR SilabsPlatform::FlashErasePage(uint32_t addr) +{ +#if defined(_SILICON_LABS_32B_SERIES_2) + MSC_ErasePage((uint32_t *) addr); +#elif defined(_SILICON_LABS_32B_SERIES_3) + sl_status_t status; + uint32_t * data_start = NULL; + size_t data_size; + + status = sl_se_data_region_get_location(&cmd_ctx, (void **) &data_start, &data_size); + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); + VerifyOrReturnError(GENERIC_ADDRESS(addr) > GENERIC_ADDRESS((uint32_t) data_start), CHIP_ERROR_INVALID_ADDRESS); + status = sl_se_data_region_erase(&cmd_ctx, (void *) addr, 1); // Erase one page + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); +#endif + return CHIP_NO_ERROR; +} + +CHIP_ERROR SilabsPlatform::FlashWritePage(uint32_t addr, const uint8_t * data, size_t size) +{ +#if defined(_SILICON_LABS_32B_SERIES_2) + MSC_WriteWord((uint32_t *) addr, data, size); +#elif defined(_SILICON_LABS_32B_SERIES_3) + sl_status_t status; + uint32_t * data_start = NULL; + size_t data_size; + + status = sl_se_data_region_get_location(&cmd_ctx, (void **) &data_start, &data_size); + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); + VerifyOrReturnError(GENERIC_ADDRESS(addr) > GENERIC_ADDRESS((uint32_t) data_start), CHIP_ERROR_INVALID_ADDRESS); + status = sl_se_data_region_write(&cmd_ctx, (void *) addr, data, size); + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); +#endif + return CHIP_NO_ERROR; +} + #ifdef ENABLE_WSTK_LEDS void SilabsPlatform::InitLed(void) { @@ -151,8 +218,7 @@ void SilabsPlatform::StartScheduler() } #ifdef SL_CATALOG_SIMPLE_BUTTON_PRESENT -extern "C" { -void sl_button_on_change(const sl_button_t * handle) +extern "C" void sl_button_on_change(const sl_button_t * handle) { if (Silabs::GetPlatform().mButtonCallback == nullptr) { @@ -168,7 +234,6 @@ void sl_button_on_change(const sl_button_t * handle) } } } -} uint8_t SilabsPlatform::GetButtonState(uint8_t button) { diff --git a/src/platform/silabs/platformAbstraction/SilabsPlatform.h b/src/platform/silabs/platformAbstraction/SilabsPlatform.h index 49f5264cac0550..df84224c50da35 100644 --- a/src/platform/silabs/platformAbstraction/SilabsPlatform.h +++ b/src/platform/silabs/platformAbstraction/SilabsPlatform.h @@ -57,6 +57,10 @@ class SilabsPlatform : virtual public SilabsPlatformAbstractionBase void StartScheduler(void) override; + CHIP_ERROR FlashInit() override; + CHIP_ERROR FlashErasePage(uint32_t addr) override; + CHIP_ERROR FlashWritePage(uint32_t addr, const uint8_t * data, size_t size) override; + private: friend SilabsPlatform & GetPlatform(void); diff --git a/src/platform/silabs/platformAbstraction/SilabsPlatformBase.h b/src/platform/silabs/platformAbstraction/SilabsPlatformBase.h index 12f87c07ea7e0d..818463ecfb9d12 100644 --- a/src/platform/silabs/platformAbstraction/SilabsPlatformBase.h +++ b/src/platform/silabs/platformAbstraction/SilabsPlatformBase.h @@ -51,6 +51,11 @@ class SilabsPlatformAbstractionBase virtual bool GetLedState(uint8_t led) { return 0; } virtual CHIP_ERROR ToggleLed(uint8_t led) { return CHIP_ERROR_NOT_IMPLEMENTED; } + // Flash + virtual CHIP_ERROR FlashInit() { return CHIP_ERROR_NOT_IMPLEMENTED; } + virtual CHIP_ERROR FlashErasePage(uint32_t addr) { return CHIP_ERROR_NOT_IMPLEMENTED; } + virtual CHIP_ERROR FlashWritePage(uint32_t addr, const uint8_t * data, size_t size) { return CHIP_ERROR_NOT_IMPLEMENTED; } + // BLE Specific Method protected: diff --git a/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp b/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp index cf60cf5c5892fe..1b03de76f37de2 100644 --- a/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp +++ b/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp @@ -17,11 +17,13 @@ #include #include +#include #include #include #include +#include #include #if SILABS_LOG_ENABLED @@ -150,8 +152,7 @@ void SilabsPlatform::StartScheduler() vTaskStartScheduler(); } -extern "C" { -void sl_button_on_change(uint8_t btn, uint8_t btnAction) +extern "C" void sl_button_on_change(uint8_t btn, uint8_t btnAction) { #if SL_ICD_ENABLED // This is to make sure we get a one-press and one-release event for the button @@ -159,21 +160,21 @@ void sl_button_on_change(uint8_t btn, uint8_t btnAction) // Currently the btn0 is pull-up resistor due to which is sends a release event on every wakeup if (btn == SL_BUTTON_BTN0_NUMBER) { - if (btnAction == BUTTON_PRESSED) + // if the btn was not pressed and only a release event came, ignore it + // if the btn was already pressed and another press event came, ignore it + // essentially, if both of them are in the same state then ignore it. + VerifyOrReturn(btnAction != btn0_pressed); + + if ((btnAction == BUTTON_PRESSED) && (btn0_pressed == false)) { btn0_pressed = true; } - else if ((btnAction == BUTTON_RELEASED) && (btn0_pressed == false)) - { - // if the btn was not pressed and only a release event came, ignore it - return; - } else if ((btnAction == BUTTON_RELEASED) && (btn0_pressed == true)) { btn0_pressed = false; } } -#endif /* SL_ICD_ENABLED */ +#endif // SL_ICD_ENABLED if (Silabs::GetPlatform().mButtonCallback == nullptr) { return; @@ -185,13 +186,29 @@ void sl_button_on_change(uint8_t btn, uint8_t btnAction) } Silabs::GetPlatform().mButtonCallback(btn, btnAction); } -} uint8_t SilabsPlatform::GetButtonState(uint8_t button) { return (button < SL_SI91x_BUTTON_COUNT) ? sButtonStates[button] : 0; } +CHIP_ERROR SilabsPlatform::FlashInit() +{ + return CHIP_NO_ERROR; +} + +CHIP_ERROR SilabsPlatform::FlashErasePage(uint32_t addr) +{ + rsi_flash_erase_sector((uint32_t *) addr); + return CHIP_NO_ERROR; +} + +CHIP_ERROR SilabsPlatform::FlashWritePage(uint32_t addr, const uint8_t * data, size_t size) +{ + rsi_flash_write((uint32_t *) addr, (unsigned char *) data, size); + return CHIP_NO_ERROR; +} + } // namespace Silabs } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/silabs/rs911x/BLEManagerImpl.cpp b/src/platform/silabs/rs911x/BLEManagerImpl.cpp index 176f396f44cd1f..75f118b38a99a4 100644 --- a/src/platform/silabs/rs911x/BLEManagerImpl.cpp +++ b/src/platform/silabs/rs911x/BLEManagerImpl.cpp @@ -26,30 +26,25 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include - +#include "wfx_sl_ble_init.h" #include +#include #include #include #include #include +#include #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING #include #endif -#include -#ifdef __cplusplus extern "C" { -#endif -#include "wfx_sl_ble_init.h" #if !(SLI_SI91X_MCU_INTERFACE | EXP_BOARD) #include #endif #include -#ifdef __cplusplus } -#endif #define BLE_MIN_CONNECTION_INTERVAL_MS 24 #define BLE_MAX_CONNECTION_INTERVAL_MS 40 diff --git a/src/platform/silabs/rs911x/rsi_ble_config.h b/src/platform/silabs/rs911x/rsi_ble_config.h index f508c3396f4e09..b28c810679081a 100644 --- a/src/platform/silabs/rs911x/rsi_ble_config.h +++ b/src/platform/silabs/rs911x/rsi_ble_config.h @@ -16,6 +16,10 @@ ******************************************************************************/ #pragma once +#ifdef __cplusplus +extern "C" { +#endif + #include "rsi_ble_apis.h" #if (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) #include "rsi_bt_common_apis.h" @@ -24,6 +28,10 @@ #include #endif +#ifdef __cplusplus +} +#endif + #if SL_MATTER_GN_BUILD == 0 #include "sl_matter_wifi_config.h" #endif // SL_MATTER_GN_BUILD diff --git a/src/platform/silabs/rs911x/wfx_sl_ble_init.cpp b/src/platform/silabs/rs911x/wfx_sl_ble_init.cpp index 971852592c3e2e..89169993810ef7 100644 --- a/src/platform/silabs/rs911x/wfx_sl_ble_init.cpp +++ b/src/platform/silabs/rs911x/wfx_sl_ble_init.cpp @@ -20,9 +20,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include #include #include +#include using namespace chip::DeviceLayer::Internal; diff --git a/src/platform/silabs/rs911x/wfx_sl_ble_init.h b/src/platform/silabs/rs911x/wfx_sl_ble_init.h index 7fd9fc94b9d58e..4eaff9c0677444 100644 --- a/src/platform/silabs/rs911x/wfx_sl_ble_init.h +++ b/src/platform/silabs/rs911x/wfx_sl_ble_init.h @@ -25,15 +25,17 @@ // BLE include file to refer BLE APIs #include "ble_config.h" #include "cmsis_os2.h" -#include "wfx_host_events.h" +#include +#include + +extern "C" { #include #include #include #include #include #include -#include -#include +} #define ATT_REC_IN_HOST (0) #define WFX_QUEUE_SIZE 10 diff --git a/src/platform/silabs/wifi/BUILD.gn b/src/platform/silabs/wifi/BUILD.gn new file mode 100644 index 00000000000000..882a66deb4fa9f --- /dev/null +++ b/src/platform/silabs/wifi/BUILD.gn @@ -0,0 +1,150 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/lwip.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/silabs/efr32_sdk.gni") +import("${chip_root}/third_party/silabs/silabs_board.gni") + +declare_args() { + # Wifi related stuff - they are overridden by gn -args="use_wf200=true" + sl_wfx_config_softap = false + sl_wfx_config_scan = true + + # Argument to force enable WPA3 security on rs91x + rs91x_wpa3_transition = true + + #default WiFi SSID + chip_default_wifi_ssid = "" + + #default Wifi Password + chip_default_wifi_psk = "" +} + +if (chip_enable_wifi && !wifi_soc) { + assert(use_rs9116 || use_wf200 || use_SiWx917) + import("${chip_root}/src/platform/silabs/wifi/args.gni") + + if (use_rs9116) { + import("${silabs_platform_dir}/wifi/rs911x/rs911x.gni") + } else if (use_SiWx917) { + import("${silabs_platform_dir}/wifi/rs911x/rs9117.gni") + } + if (use_wf200) { + import("${silabs_platform_dir}/wifi/wf200/wf200.gni") + } +} + +config("wifi-platform-config") { + defines = [] + include_dirs = [] + + if (use_rs9116) { + # All the stuff from wiseconnect + include_dirs += rs911x_inc_plat + } else if (use_SiWx917) { + # All the stuff from wiseconnect + include_dirs += rs9117_inc_plat + } + + if (chip_default_wifi_ssid != "") { + defines += [ + "SL_ONNETWORK_PAIRING=1", + "SL_WIFI_SSID=\"${chip_default_wifi_ssid}\"", + ] + } + if (chip_default_wifi_psk != "") { + assert(chip_default_wifi_ssid != "", + "ssid can't be null if psk is provided") + defines += [ "SL_WIFI_PSK=\"${chip_default_wifi_psk}\"" ] + } + + if (sl_wfx_config_softap) { + defines += [ "SL_WFX_CONFIG_SOFTAP" ] + } + + if (sl_wfx_config_scan) { + defines += [ "SL_WFX_CONFIG_SCAN" ] + } + + if (chip_enable_wifi_ipv4) { + defines += [ "CHIP_DEVICE_CONFIG_ENABLE_IPV4" ] + } + + if (rs91x_wpa3_transition) { + # TODO: Change this macro once WF200 support is provided + defines += [ "WIFI_ENABLE_SECURITY_WPA3_TRANSITION=1" ] + } + + # TODO: This defines needs to be here for the spi_multiplex.h configuration header. + # We need to find a better way to handle this. + if (!disable_lcd) { + defines += [ "DISPLAY_ENABLED" ] + } +} + +source_set("wifi-platform") { + sources = [ + "${silabs_platform_dir}/wifi/WifiInterfaceAbstraction.cpp", + "${silabs_platform_dir}/wifi/WifiInterfaceAbstraction.h", + "${silabs_platform_dir}/wifi/wfx_msgs.h", + ] + + public_configs = [ ":wifi-platform-config" ] + + public_deps = [ + "${chip_root}/src/app/icd/server:icd-server-config", + "${chip_root}/src/inet", + "${chip_root}/src/lib/support", + ] + + if (use_rs9116) { + sources += rs911x_src_plat + + # All the stuff from wiseconnect + sources += rs911x_src_sapi + } else if (use_SiWx917) { + sources += rs911x_src_plat + + # All the stuff from wiseconnect + sources += rs9117_src_sapi + + #add compilation flags for rs991x build. This will be addressed directly in wiseconnect sdk in the next version release of that sdk + } else if (use_wf200) { + sources += wf200_plat_src + } + + if (wifi_soc) { + sources += [ + "${silabs_platform_dir}/wifi/SiWx/WifiInterface.cpp", + "${silabs_platform_dir}/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.cpp", + "${silabs_platform_dir}/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.h", + + # Wi-Fi Config - Using the file sdk support until the wiseconnect file is fixed + "${sdk_support_root}/components/service/network_manager/src/sl_net_for_lwip.c", + ] + + public_deps += [ "${lwip_root}:lwip" ] + } + + if (use_wf200 || use_rs9116) { + sources += [ + "${silabs_platform_dir}/wifi/lwip-support/dhcp_client.cpp", + "${silabs_platform_dir}/wifi/lwip-support/ethernetif.cpp", + "${silabs_platform_dir}/wifi/lwip-support/ethernetif.h", + "${silabs_platform_dir}/wifi/lwip-support/lwip_netif.cpp", + ] + } +} diff --git a/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp b/src/platform/silabs/wifi/SiWx/WifiInterface.cpp similarity index 87% rename from examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp rename to src/platform/silabs/wifi/SiWx/WifiInterface.cpp index 26a16f9aa87f8f..0b4135a50a7fd1 100644 --- a/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp +++ b/src/platform/silabs/wifi/SiWx/WifiInterface.cpp @@ -28,24 +28,21 @@ #endif // SL_MATTER_GN_BUILD #include "FreeRTOS.h" -#include "WifiInterfaceAbstraction.h" #include "ble_config.h" -#include "dhcp_client.h" #include "event_groups.h" -#include "sl_board_configuration.h" #include "sl_status.h" #include "sl_wifi_device.h" #include "task.h" -#include "wfx_host_events.h" #include #include #include #include #include #include +#include +#include extern "C" { -#include "sl_net.h" #include "sl_si91x_driver.h" #include "sl_si91x_host_interface.h" #include "sl_si91x_types.h" @@ -53,7 +50,6 @@ extern "C" { #include "sl_wifi_callback_framework.h" #include "sl_wifi_constants.h" #include "sl_wifi_types.h" -#include "wfx_host_events.h" #if SL_MBEDTLS_USE_TINYCRYPT #include "sl_si91x_constants.h" #include "sl_si91x_trng.h" @@ -71,11 +67,13 @@ extern "C" { #if (EXP_BOARD) #include "rsi_bt_common_apis.h" +#include #endif #if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE #include "rsi_rom_power_save.h" -#include "sl_si91x_button_pin_config.h" +#include "sl_gpio_board.h" +#include "sl_si91x_driver_gpio.h" #include "sl_si91x_power_manager.h" #endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE @@ -201,8 +199,8 @@ constexpr uint16_t kWifiScanTimeoutTicks = 10000; void DHCPTimerEventHandler(void * arg) { - WfxEvent_t event = { .eventType = WFX_EVT_DHCP_POLL }; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kStationDhcpPoll; + sl_matter_wifi_post_event(event); } void CancelDHCPTimer(void) @@ -280,7 +278,7 @@ sl_status_t sl_wifi_siwx917_init(void) ChipLogError(DeviceLayer, "sl_si91x_trng_program_key failed: 0x%lx", static_cast(status))); #endif // SL_MBEDTLS_USE_TINYCRYPT - wfx_rsi.dev_state |= WFX_RSI_ST_DEV_READY; + wfx_rsi.dev_state.Set(WifiState::kStationInit); osSemaphoreRelease(sl_rs_ble_init_sem); return status; } @@ -401,11 +399,12 @@ sl_status_t SetWifiConfigurations() sl_status_t JoinWifiNetwork(void) { - VerifyOrReturnError(!(wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)), SL_STATUS_IN_PROGRESS); + VerifyOrReturnError(!wfx_rsi.dev_state.HasAny(WifiState::kStationConnecting, WifiState::kStationConnected), + SL_STATUS_IN_PROGRESS); sl_status_t status = SL_STATUS_OK; // Start Join Network - wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTING; + wfx_rsi.dev_state.Set(WifiState::kStationConnecting); status = SetWifiConfigurations(); VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "Failure to set the Wifi Configurations!")); @@ -414,9 +413,8 @@ sl_status_t JoinWifiNetwork(void) if (status == SL_STATUS_OK || status == SL_STATUS_IN_PROGRESS) { - WfxEvent_t event; - event.eventType = WFX_EVT_STA_CONN; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kStationConnect; + sl_matter_wifi_post_event(event); return status; } @@ -424,19 +422,51 @@ sl_status_t JoinWifiNetwork(void) ChipLogError(DeviceLayer, "sl_wifi_connect failed: 0x%lx", static_cast(status)); VerifyOrReturnError((wfx_rsi.join_retries <= MAX_JOIN_RETRIES_COUNT), status); - wfx_rsi.dev_state &= ~(WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED); + wfx_rsi.dev_state.Clear(WifiState::kStationConnecting).Clear(WifiState::kStationConnected); + ChipLogProgress(DeviceLayer, "Connection retry attempt %d", wfx_rsi.join_retries); wfx_retry_connection(++wfx_rsi.join_retries); - WfxEvent_t event; - event.eventType = WFX_EVT_STA_START_JOIN; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kStationStartJoin; + sl_matter_wifi_post_event(event); return status; } } // namespace +/** + * @brief Wifi initialization called from app main + * + * @return sl_status_t Returns underlying Wi-Fi initialization error + */ +sl_status_t sl_matter_wifi_platform_init(void) +{ + sl_status_t status = SL_STATUS_OK; + + status = sl_net_init((sl_net_interface_t) SL_NET_WIFI_CLIENT_INTERFACE, &config, &wifi_client_context, nullptr); + VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "sl_net_init failed: %lx", status)); + + // Create Sempaphore for scan completion + sScanCompleteSemaphore = osSemaphoreNew(1, 0, nullptr); + VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); + + // Create Semaphore for scan in-progress protection + sScanInProgressSemaphore = osSemaphoreNew(1, 1, nullptr); + VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); + + // Create the message queue + sWifiEventQueue = osMessageQueueNew(kWfxQueueSize, sizeof(WifiEvent), nullptr); + VerifyOrReturnError(sWifiEventQueue != nullptr, SL_STATUS_ALLOCATION_FAILED); + + // Create timer for DHCP polling + // TODO: Use LWIP timer instead of creating a new one here + sDHCPTimer = osTimerNew(DHCPTimerEventHandler, osTimerPeriodic, nullptr, nullptr); + VerifyOrReturnError(sDHCPTimer != nullptr, SL_STATUS_ALLOCATION_FAILED); + + return status; +} + /****************************************************************** * @fn int32_t wfx_rsi_get_ap_info(wfx_wifi_scan_result_t *ap) * @brief @@ -520,44 +550,6 @@ int32_t sl_wifi_platform_disconnect(void) return sl_net_down((sl_net_interface_t) SL_NET_WIFI_CLIENT_INTERFACE); } -#if CHIP_CONFIG_ENABLE_ICD_SERVER -#if SLI_SI91X_MCU_INTERFACE -// Required to invoke button press event during sleep as falling edge is not detected -void sl_si91x_invoke_btn_press_event(void) -{ - // TODO: should be removed once we are getting the press interrupt for button 0 with sleep - if (!RSI_NPSSGPIO_GetPin(SL_BUTTON_BTN0_PIN) && !btn0_pressed) - { - sl_button_on_change(SL_BUTTON_BTN0_NUMBER, 1 /* Button Pressed */); - btn0_pressed = true; - } - if (RSI_NPSSGPIO_GetPin(SL_BUTTON_BTN0_PIN)) - { - btn0_pressed = false; - } - -#ifdef ENABLE_CHIP_SHELL - // Checking the UULP PIN 1 status to reinit the UART and not allow the device to go to sleep - if (RSI_NPSSGPIO_GetPin(RTE_UULP_GPIO_1_PIN)) - { - if (!ps_requirement_added) - { - sl_si91x_power_manager_add_ps_requirement(SL_SI91X_POWER_MANAGER_PS4); - ps_requirement_added = true; - } - } - else - { - if (ps_requirement_added) - { - sl_si91x_power_manager_remove_ps_requirement(SL_SI91X_POWER_MANAGER_PS4); - ps_requirement_added = false; - } - } -#endif // ENABLE_CHIP_SHELL -} -#endif // SLI_SI91X_MCU_INTERFACE - /****************************************************************** * @fn wfx_rsi_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t sl_si91x_wifi_state) * @brief @@ -588,7 +580,6 @@ int32_t wfx_rsi_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_ return status; } -#endif /* CHIP_CONFIG_ENABLE_ICD_SERVER */ sl_status_t show_scan_results(sl_wifi_scan_result_t * scan_result) { @@ -607,7 +598,7 @@ sl_status_t show_scan_results(sl_wifi_scan_result_t * scan_result) // if user has provided ssid, then check if the current scan result ssid matches the user provided ssid if (wfx_rsi.scan_ssid != nullptr && (strncmp(wfx_rsi.scan_ssid, cur_scan_result.ssid, std::min(strlen(wfx_rsi.scan_ssid), strlen(cur_scan_result.ssid))) == - CMP_SUCCESS)) + 0)) { continue; } @@ -625,7 +616,7 @@ sl_status_t show_scan_results(sl_wifi_scan_result_t * scan_result) } // cleanup and return - wfx_rsi.dev_state &= ~WFX_RSI_ST_SCANSTARTED; + wfx_rsi.dev_state.Clear(WifiState::kScanStarted); wfx_rsi.scan_cb((wfx_wifi_scan_result_t *) 0); wfx_rsi.scan_cb = nullptr; if (wfx_rsi.scan_ssid) @@ -655,7 +646,7 @@ void NotifyConnectivity(void) void HandleDHCPPolling(void) { - WfxEvent_t event; + WifiEvent event; // TODO: Notify the application that the interface is not set up or Chipdie here because we are in an unkonwn state struct netif * sta_netif = &wifi_client_context.netif; @@ -667,8 +658,8 @@ void HandleDHCPPolling(void) { wfx_dhcp_got_ipv4((uint32_t) sta_netif->ip_addr.u_addr.ip4.addr); hasNotifiedIPV4 = true; - event.eventType = WFX_EVT_STA_DHCP_DONE; - sl_matter_wifi_post_event(&event); + event = WifiEvent::kStationDhcpDone; + sl_matter_wifi_post_event(event); NotifyConnectivity(); } else if (dhcp_state == DHCP_OFF) @@ -687,27 +678,27 @@ void HandleDHCPPolling(void) ChipLogProgress(DeviceLayer, "SLAAC OK: linklocal addr: %s", addrStr); wfx_ipv6_notify(GET_IPV6_SUCCESS); hasNotifiedIPV6 = true; - event.eventType = WFX_EVT_STA_DHCP_DONE; - sl_matter_wifi_post_event(&event); + event = WifiEvent::kStationDhcpDone; + sl_matter_wifi_post_event(event); NotifyConnectivity(); } } - -void sl_matter_wifi_post_event(WfxEvent_t * event) +void sl_matter_wifi_post_event(WifiEvent event) { - if (osMessageQueuePut(sWifiEventQueue, event, 0, 0) != osOK) + sl_status_t status = osMessageQueuePut(sWifiEventQueue, &event, 0, 0); + + if (status != osOK) { - ChipLogError(DeviceLayer, "sl_matter_wifi_post_event: failed to post event.") - // TODO: Handle error, requeue event depending on queue size or notify relevant task, Chipdie, etc. + ChipLogError(DeviceLayer, "sl_matter_wifi_post_event: failed to post event with status: %ld", status); + // TODO: Handle error, requeue event depending on queue size or notify relevant task, + // Chipdie, etc. } } - /// ResetDHCPNotificationFlags /// @brief Reset the flags that are used to notify the application about DHCP connectivity -/// and emits a WFX_EVT_STA_DO_DHCP event to trigger DHCP polling checks. Helper function for ProcessEvent. +/// and emits a WifiEvent::kStationDoDhcp event to trigger DHCP polling checks. Helper function for ProcessEvent. void ResetDHCPNotificationFlags(void) { - WfxEvent_t outEvent; #if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) hasNotifiedIPV4 = false; @@ -715,27 +706,30 @@ void ResetDHCPNotificationFlags(void) hasNotifiedIPV6 = false; hasNotifiedWifiConnectivity = false; - outEvent.eventType = WFX_EVT_STA_DO_DHCP; - sl_matter_wifi_post_event(&outEvent); + WifiEvent event = WifiEvent::kStationDoDhcp; + sl_matter_wifi_post_event(event); } -void ProcessEvent(WfxEvent_t inEvent) +void ProcessEvent(WifiEvent event) { // Process event - switch (inEvent.eventType) + switch (event) { - case WFX_EVT_STA_CONN: - ChipLogDetail(DeviceLayer, "WFX_EVT_STA_CONN"); - wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTED; + case WifiEvent::kStationConnect: + ChipLogDetail(DeviceLayer, "WifiEvent::kStationConnect"); + wfx_rsi.dev_state.Set(WifiState::kStationConnected); ResetDHCPNotificationFlags(); - break; - case WFX_EVT_STA_DISCONN: - ChipLogDetail(DeviceLayer, "WFX_EVT_STA_DISCONN"); + case WifiEvent::kStationDisconnect: { + ChipLogDetail(DeviceLayer, "WifiEvent::kStationDisconnect"); // TODO: This event is not being posted anywhere, seems to be a dead code or we are missing something - wfx_rsi.dev_state &= - ~(WFX_RSI_ST_STA_READY | WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED | WFX_RSI_ST_STA_DHCP_DONE); + + wfx_rsi.dev_state.Clear(WifiState::kStationReady) + .Clear(WifiState::kStationConnecting) + .Clear(WifiState::kStationConnected) + .Clear(WifiState::kStationDhcpDone); + /* TODO: Implement disconnect notify */ ResetDHCPNotificationFlags(); #if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) @@ -743,22 +737,20 @@ void ProcessEvent(WfxEvent_t inEvent) wfx_ip_changed_notify(IP_STATUS_FAIL); #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ wfx_ipv6_notify(GET_IPV6_FAIL); - break; + } + break; - case WFX_EVT_AP_START: - // TODO: Currently unimplemented - break; - case WFX_EVT_AP_STOP: + case WifiEvent::kAPStart: // TODO: Currently unimplemented break; - case WFX_EVT_SCAN: - ChipLogDetail(DeviceLayer, "WFX_EVT_SCAN"); + case WifiEvent::kScan: + ChipLogDetail(DeviceLayer, "WifiEvent::kScan"); #ifdef SL_WFX_CONFIG_SCAN - if (!(wfx_rsi.dev_state & WFX_RSI_ST_SCANSTARTED)) + if (!(wfx_rsi.dev_state.Has(WifiState::kScanStarted))) { - ChipLogDetail(DeviceLayer, "WFX_EVT_SCAN"); + ChipLogDetail(DeviceLayer, "WifiEvent::kScan"); sl_wifi_scan_configuration_t wifi_scan_configuration; memset(&wifi_scan_configuration, 0, sizeof(wifi_scan_configuration)); @@ -778,7 +770,7 @@ void ProcessEvent(WfxEvent_t inEvent) return; } - if (wfx_rsi.dev_state & WFX_RSI_ST_STA_CONNECTED) + if (wfx_rsi.dev_state.Has(WifiState::kStationConnected)) { /* Terminate with end of scan which is no ap sent back */ wifi_scan_configuration.type = SL_WIFI_SCAN_TYPE_ADV_SCAN; @@ -789,7 +781,7 @@ void ProcessEvent(WfxEvent_t inEvent) wifi_scan_configuration = default_wifi_scan_configuration; } sl_wifi_set_scan_callback(bg_scan_callback_handler, nullptr); - wfx_rsi.dev_state |= WFX_RSI_ST_SCANSTARTED; + wfx_rsi.dev_state.Set(WifiState::kScanStarted); osSemaphoreAcquire(sScanInProgressSemaphore, osWaitForever); status = sl_wifi_start_scan(SL_WIFI_CLIENT_2_4GHZ_INTERFACE, nullptr, &wifi_scan_configuration); @@ -802,64 +794,34 @@ void ProcessEvent(WfxEvent_t inEvent) } #endif /* SL_WFX_CONFIG_SCAN */ break; - case WFX_EVT_STA_START_JOIN: - ChipLogDetail(DeviceLayer, "WFX_EVT_STA_START_JOIN"); - // Trigger Netwrok scan - InitiateScan(); + case WifiEvent::kStationStartJoin: + ChipLogDetail(DeviceLayer, "WifiEvent::kStationStartJoin"); - // Joining to the network + InitiateScan(); JoinWifiNetwork(); break; - case WFX_EVT_STA_DO_DHCP: - ChipLogDetail(DeviceLayer, "WFX_EVT_STA_DO_DHCP"); + case WifiEvent::kStationDoDhcp: + ChipLogDetail(DeviceLayer, "WifiEvent::kStationDoDhcp"); StartDHCPTimer(WFX_RSI_DHCP_POLL_INTERVAL); break; - case WFX_EVT_STA_DHCP_DONE: - ChipLogDetail(DeviceLayer, "WFX_EVT_STA_DHCP_DONE"); + + case WifiEvent::kStationDhcpDone: + ChipLogDetail(DeviceLayer, "WifiEvent::kStationDhcpDone"); CancelDHCPTimer(); break; - case WFX_EVT_DHCP_POLL: - ChipLogDetail(DeviceLayer, "WFX_EVT_DHCP_POLL"); + + case WifiEvent::kStationDhcpPoll: + ChipLogDetail(DeviceLayer, "WifiEvent::kStationDhcpPoll"); HandleDHCPPolling(); + break; + default: break; } } -/** - * @brief Wifi initialization called from app main - * - * @return sl_status_t Returns underlying Wi-Fi initialization error - */ -sl_status_t sl_matter_wifi_platform_init(void) -{ - sl_status_t status = SL_STATUS_OK; - - status = sl_net_init((sl_net_interface_t) SL_NET_WIFI_CLIENT_INTERFACE, &config, &wifi_client_context, nullptr); - VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "sl_net_init failed: %lx", status)); - - // Create Sempaphore for scan completion - sScanCompleteSemaphore = osSemaphoreNew(1, 0, nullptr); - VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); - - // Create Semaphore for scan in-progress protection - sScanInProgressSemaphore = osSemaphoreNew(1, 1, nullptr); - VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); - - // Create the message queue - sWifiEventQueue = osMessageQueueNew(kWfxQueueSize, sizeof(WfxEvent_t), nullptr); - VerifyOrReturnError(sWifiEventQueue != nullptr, SL_STATUS_ALLOCATION_FAILED); - - // Create timer for DHCP polling - // TODO: Use LWIP timer instead of creating a new one here - sDHCPTimer = osTimerNew(DHCPTimerEventHandler, osTimerPeriodic, nullptr, nullptr); - VerifyOrReturnError(sDHCPTimer != nullptr, SL_STATUS_ALLOCATION_FAILED); - - return status; -} - /********************************************************************************* * @fn void sl_matter_wifi_task(void *arg) * @brief @@ -874,7 +836,7 @@ sl_status_t sl_matter_wifi_platform_init(void) void sl_matter_wifi_task(void * arg) { (void) arg; - WfxEvent_t wfxEvent; + WifiEvent event; sl_status_t status = SL_STATUS_OK; status = sl_wifi_siwx917_init(); @@ -887,9 +849,9 @@ void sl_matter_wifi_task(void * arg) ChipLogDetail(DeviceLayer, "sl_matter_wifi_task: starting event loop"); for (;;) { - if (osMessageQueueGet(sWifiEventQueue, &wfxEvent, nullptr, osWaitForever) == osOK) + if (osMessageQueueGet(sWifiEventQueue, &event, nullptr, osWaitForever) == osOK) { - ProcessEvent(wfxEvent); + ProcessEvent(event); } else { @@ -912,15 +874,32 @@ void wfx_dhcp_got_ipv4(uint32_t ip) /* * Acquire the new IP address */ - wfx_rsi.ip4_addr[0] = (ip) &HEX_VALUE_FF; - wfx_rsi.ip4_addr[1] = (ip >> 8) & HEX_VALUE_FF; - wfx_rsi.ip4_addr[2] = (ip >> 16) & HEX_VALUE_FF; - wfx_rsi.ip4_addr[3] = (ip >> 24) & HEX_VALUE_FF; + wfx_rsi.ip4_addr[0] = (ip) &0xFF; + wfx_rsi.ip4_addr[1] = (ip >> 8) & 0xFF; + wfx_rsi.ip4_addr[2] = (ip >> 16) & 0xFF; + wfx_rsi.ip4_addr[3] = (ip >> 24) & 0xFF; ChipLogDetail(DeviceLayer, "DHCP OK: IP=%d.%d.%d.%d", wfx_rsi.ip4_addr[0], wfx_rsi.ip4_addr[1], wfx_rsi.ip4_addr[2], wfx_rsi.ip4_addr[3]); /* Notify the Connectivity Manager - via the app */ - wfx_rsi.dev_state |= WFX_RSI_ST_STA_DHCP_DONE; + wfx_rsi.dev_state.Set(WifiState::kStationDhcpDone).Set(WifiState::kStationReady); wfx_ip_changed_notify(IP_STATUS_SUCCESS); - wfx_rsi.dev_state |= WFX_RSI_ST_STA_READY; } #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ + +#if SL_ICD_ENABLED +/********************************************************************* + * @fn sl_status_t wfx_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t + sl_si91x_wifi_state) + * @brief + * Implements the power save in sleepy application + * @param[in] sl_si91x_ble_state : State to set for the BLE + sl_si91x_wifi_state : State to set for the WiFi + * @return SL_STATUS_OK if successful, + * SL_STATUS_FAIL otherwise + ***********************************************************************/ +sl_status_t wfx_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, + sl_si91x_performance_profile_t sl_si91x_wifi_state) // TODO : Figure out why the extern C is necessary +{ + return (wfx_rsi_power_save(sl_si91x_ble_state, sl_si91x_wifi_state) ? SL_STATUS_FAIL : SL_STATUS_OK); +} +#endif diff --git a/src/platform/silabs/wifi/WifiInterfaceAbstraction.cpp b/src/platform/silabs/wifi/WifiInterfaceAbstraction.cpp new file mode 100644 index 00000000000000..430b9bbddb7d38 --- /dev/null +++ b/src/platform/silabs/wifi/WifiInterfaceAbstraction.cpp @@ -0,0 +1,231 @@ +/* + * + * 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. + */ + +// SL MATTER WI-FI INTERFACE + +#include "silabs_utils.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace chip; +using namespace chip::DeviceLayer; + +#define CONVERT_SEC_TO_MS(TimeInS) (TimeInS * 1000) + +// TODO: This is a workaround because we depend on the platform lib which depends on the platform implementation. +// As such we can't depend on the platform here as well +extern void HandleWFXSystemEvent(wfx_event_base_t eventBase, sl_wfx_generic_message_t * eventData); + +namespace { + +constexpr uint8_t kWlanMinRetryIntervalsInSec = 1; +constexpr uint8_t kWlanMaxRetryIntervalsInSec = 60; +constexpr uint8_t kWlanRetryIntervalInSec = 5; +uint8_t retryInterval = kWlanMinRetryIntervalsInSec; +osTimerId_t sRetryTimer; + +/* + * Notifications to the upper-layer + * All done in the context of the RSI/WiFi task (rsi_if.c) + */ +void RetryConnectionTimerHandler(void * arg) +{ +#if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE + wfx_rsi_power_save(RSI_ACTIVE, HIGH_PERFORMANCE); +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE + if (wfx_connect_to_ap() != SL_STATUS_OK) + { + ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); + } +} + +} // namespace + +/*********************************************************************************** + * @fn sl_matter_wifi_task_started(void) + * @brief + * Wifi device started notification + * @param[in]: None + * @return None + *************************************************************************************/ +void sl_matter_wifi_task_started(void) +{ + sl_wfx_startup_ind_t evt; + sl_wfx_mac_address_t mac; + + // Creating a timer which will be used to retry connection with AP + sRetryTimer = osTimerNew(RetryConnectionTimerHandler, osTimerOnce, NULL, NULL); + VerifyOrReturn(sRetryTimer != NULL); + + memset(&evt, 0, sizeof(evt)); + evt.header.id = SL_WFX_STARTUP_IND_ID; + evt.header.length = sizeof evt; + evt.body.status = 0; + wfx_get_wifi_mac_addr(SL_WFX_STA_INTERFACE, &mac); + memcpy(&evt.body.mac_addr[0], &mac.octet[0], MAC_ADDRESS_FIRST_OCTET); + + HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); +} + +/*********************************************************************************** + * @fn void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t *ap) + * @brief + * For now we are not notifying anything other than AP Mac - + * Other stuff such as DTIM etc. may be required for later + * @param[in] status: + * @param[in] ap: access point + * @return None + *************************************************************************************/ +void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t * ap) +{ + sl_wfx_connect_ind_t evt; + + VerifyOrReturn(status == SUCCESS_STATUS); + + memset(&evt, 0, sizeof(evt)); + evt.header.id = SL_WFX_CONNECT_IND_ID; + evt.header.length = sizeof evt; + +#ifdef RS911X_WIFI + evt.body.channel = wfx_rsi.ap_chan; +#endif + memcpy(&evt.body.mac[0], &ap->octet[0], MAC_ADDRESS_FIRST_OCTET); + + HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); +} + +/************************************************************************************** + * @fn void wfx_disconnected_notify(int32_t status) + * @brief + * notification of disconnection + * @param[in] status: + * @return None + *************************************************************************************/ +void wfx_disconnected_notify(int32_t status) +{ + sl_wfx_disconnect_ind_t evt; + + memset(&evt, 0, sizeof(evt)); + evt.header.id = SL_WFX_DISCONNECT_IND_ID; + evt.header.length = sizeof evt; + evt.body.reason = status; + HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); +} + +/************************************************************************************** + * @fn void wfx_ipv6_notify(int got_ip) + * @brief + * notification of ipv6 + * @param[in] got_ip: + * @return None + *************************************************************************************/ +void wfx_ipv6_notify(int got_ip) +{ + sl_wfx_generic_message_t eventData; + + memset(&eventData, 0, sizeof(eventData)); + eventData.header.id = got_ip ? IP_EVENT_GOT_IP6 : IP_EVENT_STA_LOST_IP; + eventData.header.length = sizeof(eventData.header); + HandleWFXSystemEvent(IP_EVENT, &eventData); +} + +/************************************************************************************** + * @fn void wfx_ip_changed_notify(int got_ip) + * @brief + * notification of ip change + * @param[in] got_ip: + * @return None + *************************************************************************************/ +void wfx_ip_changed_notify(int got_ip) +{ + sl_wfx_generic_message_t eventData; + + memset(&eventData, 0, sizeof(eventData)); + eventData.header.id = got_ip ? IP_EVENT_STA_GOT_IP : IP_EVENT_STA_LOST_IP; + eventData.header.length = sizeof(eventData.header); + HandleWFXSystemEvent(IP_EVENT, &eventData); +} + +/************************************************************************************** + * @fn void wfx_retry_connection(uint16_t retryAttempt) + * @brief + * During commissioning, we retry to join the network MAX_JOIN_RETRIES_COUNT times. + * If DUT is disconnected from the AP or device is power cycled, then retry connection + * with AP continously after a certain time interval. + * @param[in] retryAttempt + * @return None + *************************************************************************************/ +void wfx_retry_connection(uint16_t retryAttempt) +{ + // During commissioning, we retry to join the network MAX_JOIN_RETRIES_COUNT + if (/*BaseApplication::sAppDelegate.isCommissioningInProgress()*/ true) + { + if (retryAttempt < MAX_JOIN_RETRIES_COUNT) + { + ChipLogProgress(DeviceLayer, "wfx_retry_connection : Next attempt after %d Seconds", kWlanRetryIntervalInSec); + if (osTimerStart(sRetryTimer, pdMS_TO_TICKS(CONVERT_SEC_TO_MS(kWlanRetryIntervalInSec))) != osOK) + { + ChipLogProgress(DeviceLayer, "Failed to start retry timer"); + // Sending the join command if retry timer failed to start + if (wfx_connect_to_ap() != SL_STATUS_OK) + { + ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); + } + return; + } + } + else + { + ChipLogProgress(DeviceLayer, "Connect failed after max %d tries", retryAttempt); + } + } + else + { + /* After disconnection or power cycle the DUT + * At the telescopic time interval device try to reconnect with AP, upto WLAN_MAX_RETRY_TIMER_MS intervals + * are telescopic. If interval exceed WLAN_MAX_RETRY_TIMER_MS then it will try to reconnect at + * WLAN_MAX_RETRY_TIMER_MS intervals. + */ + if (retryInterval > kWlanMaxRetryIntervalsInSec) + { + retryInterval = kWlanMaxRetryIntervalsInSec; + } + if (osTimerStart(sRetryTimer, pdMS_TO_TICKS(CONVERT_SEC_TO_MS(retryInterval))) != osOK) + { + ChipLogProgress(DeviceLayer, "Failed to start retry timer"); + // Sending the join command if retry timer failed to start + if (wfx_connect_to_ap() != SL_STATUS_OK) + { + ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); + } + return; + } +#if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE + wfx_rsi_power_save(RSI_SLEEP_MODE_8, STANDBY_POWER_SAVE_WITH_RAM_RETENTION); +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE + ChipLogProgress(DeviceLayer, "wfx_retry_connection : Next attempt after %d Seconds", retryInterval); + retryInterval += retryInterval; + return; + } +} diff --git a/src/platform/silabs/wifi/wfx_host_events.h b/src/platform/silabs/wifi/WifiInterfaceAbstraction.h similarity index 56% rename from src/platform/silabs/wifi/wfx_host_events.h rename to src/platform/silabs/wifi/WifiInterfaceAbstraction.h index d3d8de6ec78569..f6364d040e5189 100644 --- a/src/platform/silabs/wifi/wfx_host_events.h +++ b/src/platform/silabs/wifi/WifiInterfaceAbstraction.h @@ -14,9 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #pragma once +#include +#include +#include +#include +#include + #include "sl_status.h" #include @@ -32,6 +37,12 @@ #include "sl_wifi_constants.h" #include "sl_wifi_device.h" +/* + * Interface to RSI Sapis + */ + +#define WFX_RSI_DHCP_POLL_INTERVAL (250) /* Poll interval in ms for DHCP */ + // MAX SSID LENGTH excluding NULL character #define WFX_MAX_SSID_LENGTH (32) // MAX PASSKEY LENGTH including NULL character @@ -44,106 +55,56 @@ #define WFX_MAX_PASSKEY_LENGTH (64) #endif // (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) -#define CONVERT_SEC_TO_MS(TimeInS) (TimeInS * 1000) - -/* Wi-Fi bitmask events - for the task */ -#define SL_WFX_CONNECT (1 << 1) -#define SL_WFX_DISCONNECT (1 << 2) -#define SL_WFX_START_AP (1 << 3) -#define SL_WFX_STOP_AP (1 << 4) -#define SL_WFX_SCAN_START (1 << 5) -#define SL_WFX_SCAN_COMPLETE (1 << 6) -#define SL_WFX_RETRY_CONNECT (1 << 7) - -// WLAN MAX retry #define MAX_JOIN_RETRIES_COUNT (5) - -#define WLAN_TASK_STACK_SIZE (1024) - -// WLAN related Macros -#define ETH_FRAME (0) -#define CMP_SUCCESS (0) #define BSSID_LEN (6) #define MAC_ADDRESS_FIRST_OCTET (6) -#define AP_START_SUCCESS (0) -#define BITS_TO_WAIT (0) #define CONNECTION_STATUS_SUCCESS (1) #define IP_STATUS_FAIL (0) -#define GET_IPV6_SUCCESS (1) #define GET_IPV6_FAIL (0) -#define BEACON_1 (0) -#define CHANNEL_LIST ((const uint8_t *) 0) -#define CHANNEL_COUNT (0) -#define IE_DATA ((const uint8_t *) 0) -#define IE_DATA_LENGTH (0) -#define BSSID_SCAN ((const uint8_t *) 0) -#define CHANNEL_0 (0) -#define PREVENT_ROAMING (1) -#define DISABLE_PMF_MODE (0) -#define STA_IP_FAIL (0) #define IP_STATUS_SUCCESS (1) -#define ACTIVE_CHANNEL_TIME_100 (100) -#define PASSIVE_CHANNEL_TIME_0 (0) -#define PROBE_NUM_REQ_1 (1) -#define PINOUT_CLEAR_STATUS (0) -#define TICKS_TO_WAIT_0 (0) -#define TICKS_TO_WAIT_3 (3) -#define TICKS_TO_WAIT_1 (1) -#define TICKS_TO_WAIT_500 (500) +#define SL_WFX_STARTUP_IND_ID (1) +#define SL_WFX_CONNECT_IND_ID (2) +#define SL_WFX_DISCONNECT_IND_ID (3) +#define SL_WFX_SCAN_COMPLETE_ID (4) // TASK and Interrupt Macros #define SUCCESS_STATUS (1) -#define LINK_UP (1) -#define LINK_DOWN (0) -#define MAC_48_BIT_SET (1) -#define STRUCT_PBUF ((struct pbuf *) 0) -#define PRIORITY_0 (0) -#define HEX_VALUE_FF (0XFF) - -// Timer Delay -#define MAX_XLEN (16) -#define MIN_XLEN (0) -#define PINOUT_CLEAR (0) -#define PINOUT_SET (1) -#define WFX_SPI_NVIC_PRIORITY (5) -#define WFX_GPIO_NVIC_PRIORITY (5) -#define CB_VALUE ((DMADRV_Callback_t) 0) - -/* TIMER_TICKS_TO_WAIT Specifies the time, in ticks, that the calling task should - * be held in the Blocked state to wait for the start command to be successfully - * sent to the timer command queue. - */ -#define TIMER_TICKS_TO_WAIT_0 pdMS_TO_TICKS(0) - -#define CONVERT_SEC_TO_MSEC (1000) -#define CONVERT_USEC_TO_MSEC (1 / 1000) - -#define RSI_RESPONSE_MAX_SIZE (28) -#define RSI_RESPONSE_HOLD_BUFF_SIZE (128) -#define RSI_DRIVER_STATUS (0) -#define OPER_MODE_0 (0) -#define COEX_MODE_0 (0) -#define RESP_BUFF_SIZE (6) -#define AP_CHANNEL_NO_0 (0) -#define SCAN_BITMAP_OPTN_1 (1) -#define IP_CONF_RSP_BUFF_LENGTH_4 (4) -#define STATION (0) - -#define SPI_CONFIG_SUCCESS (0) + +enum class WifiState : uint16_t +{ + kStationInit = (1 << 0), + kAPReady = (1 << 1), + kStationProvisioned = (1 << 2), + kStationConnecting = (1 << 3), + kStationConnected = (1 << 4), + kStationDhcpDone = (1 << 6), /* Requested to do DHCP after conn */ + kStationMode = (1 << 7), /* Enable Station Mode */ + kAPMode = (1 << 8), /* Enable AP Mode */ + kStationReady = (kStationConnected | kStationDhcpDone), + kStationStarted = (1 << 9), /* RSI task started */ + kScanStarted = (1 << 10), /* Scan Started */ +}; + +enum class WifiEvent : uint8_t +{ + kStationConnect = 0, + kStationDisconnect = 1, + kAPStart = 2, + kAPStop = 3, + kScan = 4, /* This is used as scan result and start */ + kStationStartJoin = 5, + kStationDoDhcp = 6, + kStationDhcpDone = 7, + kStationDhcpPoll = 8 +}; + typedef enum { WIFI_EVENT, IP_EVENT, } wfx_event_base_t; -typedef enum -{ - IP_EVENT_STA_GOT_IP, - IP_EVENT_GOT_IP6, - IP_EVENT_STA_LOST_IP, -} ip_event_id_t; - /* Note that these are same as RSI_security */ typedef enum { @@ -195,6 +156,13 @@ typedef struct wfx_wifi_scan_ext uint32_t overrun_count; } wfx_wifi_scan_ext_t; +typedef enum +{ + IP_EVENT_STA_GOT_IP, + IP_EVENT_GOT_IP6, + IP_EVENT_STA_LOST_IP, +} ip_event_id_t; + #ifdef RS911X_WIFI /* * This Sh%t is here to support WFXUtils - and the Matter stuff that uses it @@ -205,121 +173,50 @@ typedef enum SL_WFX_STA_INTERFACE = 0, ///< Interface 0, linked to the station SL_WFX_SOFTAP_INTERFACE = 1, ///< Interface 1, linked to the softap } sl_wfx_interface_t; -#endif /* RS911X_WIFI */ - -#ifdef WF200_WIFI -#include "FreeRTOS.h" -#include "event_groups.h" -#include "semphr.h" -#include "sl_wfx_cmd_api.h" -#include "sl_wfx_constants.h" -#include "task.h" -#include "timers.h" - -#define WLAN_TASK_PRIORITY (1) -typedef struct __attribute__((__packed__)) sl_wfx_get_counters_cnf_body_s -{ - uint32_t status; - uint16_t mib_id; - uint16_t length; - uint32_t rcpi; - uint32_t count_plcp_errors; - uint32_t count_fcs_errors; - uint32_t count_tx_packets; - uint32_t count_rx_packets; - uint32_t count_rx_packet_errors; - uint32_t count_rx_decryption_failures; - uint32_t count_rx_mic_failures; - uint32_t count_rx_no_key_failures; - uint32_t count_tx_multicast_frames; - uint32_t count_tx_frames_success; - uint32_t count_tx_frame_failures; - uint32_t count_tx_frames_retried; - uint32_t count_tx_frames_multi_retried; - uint32_t count_rx_frame_duplicates; - uint32_t count_rts_success; - uint32_t count_rts_failures; - uint32_t count_ack_failures; - uint32_t count_rx_multicast_frames; - uint32_t count_rx_frames_success; - uint32_t count_rx_cmacicv_errors; - uint32_t count_rx_cmac_replays; - uint32_t count_rx_mgmt_ccmp_replays; - uint32_t count_rx_bipmic_errors; - uint32_t count_rx_beacon; - uint32_t count_miss_beacon; - uint32_t reserved[15]; -} sl_wfx_get_counters_cnf_body_t; - -typedef struct __attribute__((__packed__)) sl_wfx_get_counters_cnf_s -{ - /** Common message header. */ - sl_wfx_header_t header; - /** Confirmation message body. */ - sl_wfx_get_counters_cnf_body_t body; -} sl_wfx_get_counters_cnf_t; - -typedef struct __attribute__((__packed__)) sl_wfx_mib_req_body_s -{ - uint16_t mib_id; ///< ID of the MIB to be read. - uint16_t reserved; -} sl_wfx_mib_req_body_t; +#endif -typedef struct __attribute__((__packed__)) sl_wfx_header_mib_s -{ - uint16_t length; ///< Message length in bytes including this uint16_t. - ///< Maximum value is 8188 but maximum Request size is FW dependent and reported in the - ///< ::sl_wfx_startup_ind_body_t::size_inp_ch_buf. - uint8_t id; ///< Contains the message Id indexed by sl_wfx_general_commands_ids_t or sl_wfx_message_ids_t. - uint8_t reserved : 1; - uint8_t interface : 2; - uint8_t seqnum : 3; - uint8_t encrypted : 2; -} sl_wfx_header_mib_t; - -typedef struct __attribute__((__packed__)) sl_wfx_mib_req_s +typedef struct wfx_rsi_s { - /** Common message header. */ - sl_wfx_header_mib_t header; - /** Request message body. */ - sl_wfx_mib_req_body_t body; -} sl_wfx_mib_req_t; - -#else /* End WF200 else RS9116,917 NCP and 917 SoC */ - -#include "wfx_msgs.h" -/* Wi-Fi events*/ -#define SL_WFX_STARTUP_IND_ID (1) -#define SL_WFX_CONNECT_IND_ID (2) -#define SL_WFX_DISCONNECT_IND_ID (3) -#define SL_WFX_SCAN_COMPLETE_ID (4) -#endif /* WF200_WIFI */ - -#ifdef __cplusplus -extern "C" { + chip::BitFlags dev_state; + uint16_t ap_chan; /* The chan our STA is using */ + wfx_wifi_provision_t sec; +#ifdef SL_WFX_CONFIG_SCAN + void (*scan_cb)(wfx_wifi_scan_result_t *); + char * scan_ssid; /* Which one are we scanning for */ + size_t scan_ssid_length; +#endif +#ifdef SL_WFX_CONFIG_SOFTAP + sl_wfx_mac_address_t softap_mac; #endif + sl_wfx_mac_address_t sta_mac; + sl_wfx_mac_address_t ap_mac; /* To which our STA is connected */ + sl_wfx_mac_address_t ap_bssid; /* To which our STA is connected */ + uint16_t join_retries; + uint8_t ip4_addr[4]; /* Not sure if this is enough */ +} WfxRsi_t; + +// TODO: We shouldn't need to have access to a global variable in the interface here +extern WfxRsi_t wfx_rsi; -void sl_wfx_host_gpio_init(void); sl_status_t wfx_wifi_start(void); void wfx_enable_sta_mode(void); - void wfx_get_wifi_mac_addr(sl_wfx_interface_t interface, sl_wfx_mac_address_t * addr); void wfx_set_wifi_provision(wfx_wifi_provision_t * wifiConfig); bool wfx_get_wifi_provision(wfx_wifi_provision_t * wifiConfig); - bool wfx_is_sta_mode_enabled(void); int32_t wfx_get_ap_info(wfx_wifi_scan_result_t * ap); int32_t wfx_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); int32_t wfx_reset_counts(); - void wfx_clear_wifi_provision(void); sl_status_t wfx_connect_to_ap(void); void wfx_setup_ip6_link_local(sl_wfx_interface_t); bool wfx_is_sta_connected(void); sl_status_t sl_matter_wifi_disconnect(void); + #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 bool wfx_have_ipv4_addr(sl_wfx_interface_t); #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ + bool wfx_have_ipv6_addr(sl_wfx_interface_t); wifi_mode_t wfx_get_wifi_mode(void); bool wfx_start_scan(char * ssid, void (*scan_cb)(wfx_wifi_scan_result_t *)); /* true returned if successfully started */ @@ -338,7 +235,6 @@ void wfx_lwip_set_sta_link_down(void); void sl_matter_lwip_start(void); struct netif * wfx_get_netif(sl_wfx_interface_t interface); -bool wfx_hw_ready(void); #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 void wfx_dhcp_got_ipv4(uint32_t); void wfx_ip_changed_notify(int got_ip); @@ -355,6 +251,8 @@ int32_t wfx_rsi_send_data(void * p, uint16_t len); #endif //!(EXP_BOARD) #endif // RS911X_WIFI +bool wfx_hw_ready(void); + #ifdef RS911X_WIFI // for RS9116, 917 NCP and 917 SoC /* RSI Power Save */ #if SL_ICD_ENABLED @@ -366,21 +264,49 @@ sl_status_t wfx_power_save(); #endif /* SL_ICD_ENABLED */ #endif /* RS911X_WIFI */ -#ifdef WF200_WIFI -bool wfx_is_sta_provisioned(void); -sl_wfx_state_t wfx_get_wifi_state(void); -void wfx_bus_start(void); -sl_status_t get_all_counters(void); -void sl_wfx_host_gpio_init(void); -sl_status_t sl_wfx_host_process_event(sl_wfx_generic_message_t * event_payload); -#endif /* WF200_WIFI */ +void sl_matter_wifi_task(void * arg); + +#if CHIP_DEVICE_CONFIG_ENABLE_IPV4 +void wfx_ip_changed_notify(int got_ip); +#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ + +int32_t wfx_rsi_get_ap_info(wfx_wifi_scan_result_t * ap); +int32_t wfx_rsi_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); +int32_t wfx_rsi_reset_count(); +int32_t sl_wifi_platform_disconnect(); + +#if CHIP_CONFIG_ENABLE_ICD_SERVER +#if SLI_SI917 +int32_t wfx_rsi_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t sl_si91x_wifi_state); +#else +int32_t wfx_rsi_power_save(); +#endif /* SLI_SI917 */ +#endif /* SL_ICD_ENABLED */ + +/** + * @brief Posts an event to the Wi-Fi task + * + * @param[in] event Event to process. + */ +void sl_matter_wifi_post_event(WifiEvent event); + +#ifdef __cplusplus +extern "C" { +#endif #if (SLI_SI91X_MCU_INTERFACE) #if SL_ICD_ENABLED +// TODO : This should be moved outside of the Wifi interface functions void sl_button_on_change(uint8_t btn, uint8_t btnAction); #endif /* SL_ICD_ENABLED */ #endif /* SLI_SI91X_MCU_INTERFACE */ +#ifdef WF200_WIFI +void sl_wfx_host_gpio_init(void); +void wfx_bus_start(void); +sl_status_t sl_wfx_host_process_event(sl_wfx_generic_message_t * event_payload); +#endif /* WF200_WIFI */ + #ifdef __cplusplus } #endif diff --git a/src/platform/silabs/wifi_args.gni b/src/platform/silabs/wifi/args.gni similarity index 100% rename from src/platform/silabs/wifi_args.gni rename to src/platform/silabs/wifi/args.gni diff --git a/src/platform/silabs/wifi/dhcp_client.cpp b/src/platform/silabs/wifi/lwip-support/dhcp_client.cpp similarity index 98% rename from src/platform/silabs/wifi/dhcp_client.cpp rename to src/platform/silabs/wifi/lwip-support/dhcp_client.cpp index a219430762cf50..a16064eb1d8b08 100644 --- a/src/platform/silabs/wifi/dhcp_client.cpp +++ b/src/platform/silabs/wifi/lwip-support/dhcp_client.cpp @@ -23,10 +23,7 @@ #include "dhcp_client.h" #include "lwip/dhcp.h" -#include "wfx_host_events.h" - -#include "FreeRTOS.h" -#include "event_groups.h" +#include #include diff --git a/src/platform/silabs/wifi/dhcp_client.h b/src/platform/silabs/wifi/lwip-support/dhcp_client.h similarity index 100% rename from src/platform/silabs/wifi/dhcp_client.h rename to src/platform/silabs/wifi/lwip-support/dhcp_client.h diff --git a/src/platform/silabs/efr32/wifi/ethernetif.cpp b/src/platform/silabs/wifi/lwip-support/ethernetif.cpp similarity index 98% rename from src/platform/silabs/efr32/wifi/ethernetif.cpp rename to src/platform/silabs/wifi/lwip-support/ethernetif.cpp index 5993cf90cc631a..7e880f62e9a36b 100644 --- a/src/platform/silabs/efr32/wifi/ethernetif.cpp +++ b/src/platform/silabs/wifi/lwip-support/ethernetif.cpp @@ -21,12 +21,6 @@ #include #include -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" - #ifndef WF200_WIFI #include "FreeRTOS.h" #include "event_groups.h" @@ -50,7 +44,7 @@ extern "C" { #endif // (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) #endif // WF200_WIFI -#include "wfx_host_events.h" +#include #ifdef WF200_WIFI #include "sl_wfx.h" #endif @@ -162,7 +156,7 @@ static void low_level_input(struct netif * netif, uint8_t * b, uint16_t len) /* We allocate a pbuf chain of pbufs from the Lwip buffer pool * and copy the data to the pbuf chain */ - if ((p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL)) != STRUCT_PBUF) + if ((p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL)) != NULL) { for (q = p, bufferoffset = 0; q != NULL; q = q->next) { @@ -268,7 +262,7 @@ static err_t low_level_output(struct netif * netif, struct pbuf * p) /* send the generated frame over Wifi network */ while ((result != SL_STATUS_OK) && (i++ < 10)) { - result = sl_wfx_send_ethernet_frame(tx_buffer, framelength, SL_WFX_STA_INTERFACE, PRIORITY_0); + result = sl_wfx_send_ethernet_frame(tx_buffer, framelength, SL_WFX_STA_INTERFACE, 0 /* priority */); } sl_wfx_host_free_buffer(tx_buffer, SL_WFX_TX_FRAME_BUFFER); diff --git a/src/platform/silabs/efr32/wifi/ethernetif.h b/src/platform/silabs/wifi/lwip-support/ethernetif.h similarity index 94% rename from src/platform/silabs/efr32/wifi/ethernetif.h rename to src/platform/silabs/wifi/lwip-support/ethernetif.h index dfea1ea6ad3540..56e564d30b6767 100644 --- a/src/platform/silabs/efr32/wifi/ethernetif.h +++ b/src/platform/silabs/wifi/lwip-support/ethernetif.h @@ -19,9 +19,16 @@ #include "lwip/err.h" #include "lwip/netif.h" + +#ifdef WF200_WIFI +#include "sl_wfx_api.h" +#include "sl_wfx_constants.h" +#endif // WF200_WIFI + #ifdef __cplusplus extern "C" { #endif + /*************************************************************************** * @fn err_t sta_ethernetif_init(struct netif *netif) * @brief @@ -47,6 +54,7 @@ void sl_wfx_host_received_frame_callback(sl_wfx_received_ind_t * rx_buffer); #else void wfx_host_received_sta_frame_cb(uint8_t * buf, int len); #endif /* WF200_WIFI */ + #ifdef __cplusplus } #endif diff --git a/src/platform/silabs/efr32/wifi/lwip_netif.cpp b/src/platform/silabs/wifi/lwip-support/lwip_netif.cpp similarity index 94% rename from src/platform/silabs/efr32/wifi/lwip_netif.cpp rename to src/platform/silabs/wifi/lwip-support/lwip_netif.cpp index f8d719b387fb09..3b8dea41ccab09 100644 --- a/src/platform/silabs/efr32/wifi/lwip_netif.cpp +++ b/src/platform/silabs/wifi/lwip-support/lwip_netif.cpp @@ -19,31 +19,26 @@ #include #include -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" - -#include "wfx_host_events.h" +#include #include "dhcp_client.h" #include "ethernetif.h" -#include "FreeRTOS.h" -#include "event_groups.h" -#include "task.h" - #include -#include + using namespace ::chip; using namespace ::chip::DeviceLayer; + static struct netif sta_netif; #ifdef SL_WFX_CONFIG_SOFTAP static struct netif ap_netif; #endif +#define LINK_UP (1) +#define LINK_DOWN (0) +#define MAC_48_BIT_SET (1) + /**************************************************************************** * @fn static void netif_config(struct netif *sta_if, struct netif *ap_if) * @brief diff --git a/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp b/src/platform/silabs/wifi/rs911x/WifiInterface.cpp similarity index 88% rename from examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp rename to src/platform/silabs/wifi/rs911x/WifiInterface.cpp index 233230b3698265..c918b3af362196 100644 --- a/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp +++ b/src/platform/silabs/wifi/rs911x/WifiInterface.cpp @@ -15,24 +15,20 @@ * limitations under the License. */ -#include -#include -#include - -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" - +#include "lwip/nd6.h" +#include "silabs_utils.h" #include "sl_status.h" #include -// TODO Fix include order issue #33120 -#include "wfx_host_events.h" +#include +#include +#include +#include +#include +#include +#include +#include -#ifdef __cplusplus extern "C" { -#endif #include "rsi_bootup_config.h" #include "rsi_common_apis.h" #include "rsi_data_types.h" @@ -45,22 +41,22 @@ extern "C" { #include "rsi_wlan_apis.h" #include "rsi_wlan_config.h" #include "rsi_wlan_non_rom.h" -#ifdef __cplusplus } -#endif - -#include "WifiInterfaceAbstraction.h" -#include "dhcp_client.h" -#include "ethernetif.h" -#include "lwip/nd6.h" -#include "silabs_utils.h" -#include -#include -#include -#include +using WifiStateFlags = chip::BitFlags; #define WFX_QUEUE_SIZE 10 +#define WFX_RSI_BUF_SZ (1024 * 10) +#define RSI_RESPONSE_MAX_SIZE (28) +#define RSI_RESPONSE_HOLD_BUFF_SIZE (128) +#define RSI_DRIVER_STATUS (0) +#define OPER_MODE_0 (0) +#define COEX_MODE_0 (0) +#define RESP_BUFF_SIZE (6) +#define AP_CHANNEL_NO_0 (0) +#define SCAN_BITMAP_OPTN_1 (1) + +WfxRsi_t wfx_rsi; static osThreadId_t sDrvThread; constexpr uint32_t kDrvTaskSize = 1792; @@ -108,9 +104,8 @@ static void rsi_wireless_driver_task_wrapper(void * argument) static void DHCPTimerEventHandler(void * arg) { - WfxEvent_t event; - event.eventType = WFX_EVT_DHCP_POLL; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kStationDhcpPoll; + sl_matter_wifi_post_event(event); } static void CancelDHCPTimer(void) @@ -284,8 +279,7 @@ int32_t wfx_rsi_power_save(void) *********************************************************************/ static void wfx_rsi_join_cb(uint16_t status, const uint8_t * buf, const uint16_t len) { - WfxEvent_t WfxEvent; - wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTING; + wfx_rsi.dev_state.Clear(WifiState::kStationConnecting); if (status != RSI_SUCCESS) { /* @@ -301,8 +295,8 @@ static void wfx_rsi_join_cb(uint16_t status, const uint8_t * buf, const uint16_t */ ChipLogProgress(DeviceLayer, "wfx_rsi_join_cb: success"); memset(&temp_reset, 0, sizeof(wfx_wifi_scan_ext_t)); - WfxEvent.eventType = WFX_EVT_STA_CONN; - sl_matter_wifi_post_event(&WfxEvent); + WifiEvent event = WifiEvent::kStationConnect; + sl_matter_wifi_post_event(event); wfx_rsi.join_retries = 0; } @@ -319,11 +313,12 @@ static void wfx_rsi_join_cb(uint16_t status, const uint8_t * buf, const uint16_t static void wfx_rsi_join_fail_cb(uint16_t status, uint8_t * buf, uint32_t len) { ChipLogError(DeviceLayer, "wfx_rsi_join_fail_cb: status: %d", status); - WfxEvent_t WfxEvent; wfx_rsi.join_retries += 1; - wfx_rsi.dev_state &= ~(WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED); - WfxEvent.eventType = WFX_EVT_STA_START_JOIN; - sl_matter_wifi_post_event(&WfxEvent); + + wfx_rsi.dev_state.Clear(WifiState::kStationConnecting).Clear(WifiState::kStationConnected); + + WifiEvent event = WifiEvent::kStationStartJoin; + sl_matter_wifi_post_event(event); } /************************************************************************************* * @fn wfx_rsi_wlan_pkt_cb(uint16_t status, uint8_t *buf, uint32_t len) @@ -423,7 +418,7 @@ static int32_t sl_matter_wifi_init(void) wfx_rsi.sta_mac.octet[2], wfx_rsi.sta_mac.octet[3], wfx_rsi.sta_mac.octet[4], wfx_rsi.sta_mac.octet[5]); // Create the message queue - sWifiEventQueue = osMessageQueueNew(WFX_QUEUE_SIZE, sizeof(WfxEvent_t), NULL); + sWifiEventQueue = osMessageQueueNew(WFX_QUEUE_SIZE, sizeof(WifiEvent), NULL); if (sWifiEventQueue == NULL) { return SL_STATUS_ALLOCATION_FAILED; @@ -455,7 +450,7 @@ static int32_t sl_matter_wifi_init(void) rsi_semaphore_post(&sl_rs_ble_init_sem); #endif - wfx_rsi.dev_state |= WFX_RSI_ST_DEV_READY; + wfx_rsi.dev_state.Set(WifiState::kStationInit); return RSI_SUCCESS; } @@ -536,14 +531,10 @@ static void wfx_rsi_save_ap_info(void) // translation **********************************************************************************************/ static void sl_wifi_platform_join_network(void) { - int32_t status = SL_STATUS_OK; + sl_status_t status = SL_STATUS_OK; rsi_security_mode_t connect_security_mode; - if (wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)) - { - ChipLogProgress(DeviceLayer, "sl_wifi_platform_join_network: already in progress"); - return; - } + VerifyOrReturn(!wfx_rsi.dev_state.HasAny(WifiState::kStationConnecting, WifiState::kStationConnected)); switch (wfx_rsi.sec.security) { @@ -577,7 +568,7 @@ static void sl_wifi_platform_join_network(void) /* TODO - make the WFX_SECURITY_xxx - same as RSI_xxx * Right now it's done by hand - we need something better */ - wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTING; + wfx_rsi.dev_state.Set(WifiState::kStationConnecting); if ((status = rsi_wlan_register_callbacks(RSI_JOIN_FAIL_CB, wfx_rsi_join_fail_cb)) != RSI_SUCCESS) { @@ -590,7 +581,7 @@ static void sl_wifi_platform_join_network(void) if ((status = rsi_wlan_connect_async((int8_t *) &wfx_rsi.sec.ssid[0], connect_security_mode, &wfx_rsi.sec.passkey[0], wfx_rsi_join_cb)) != RSI_SUCCESS) { - wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTING; + wfx_rsi.dev_state.Clear(WifiState::kStationConnecting); ChipLogProgress(DeviceLayer, "sl_wifi_platform_join_network: rsi_wlan_connect_async failed: %ld on try %d", status, wfx_rsi.join_retries); wfx_retry_connection(++wfx_rsi.join_retries); @@ -613,7 +604,6 @@ void NotifyConnectivity(void) void HandleDHCPPolling(void) { struct netif * sta_netif; - WfxEvent_t event; sta_netif = wfx_get_netif(SL_WFX_STA_INTERFACE); if (sta_netif == NULL) @@ -644,19 +634,19 @@ void HandleDHCPPolling(void) { wfx_ipv6_notify(GET_IPV6_SUCCESS); hasNotifiedIPV6 = true; - event.eventType = WFX_EVT_STA_DHCP_DONE; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kStationDhcpDone; + sl_matter_wifi_post_event(event); NotifyConnectivity(); } } /** ResetDHCPNotificationFlags * @brief Reset the flags that are used to notify the application about DHCP connectivity - * and emits a WFX_EVT_STA_DO_DHCP event to trigger DHCP polling checks. Helper function for ProcessEvent. + * and emits a WifiEvent::kStationDoDhcp event to trigger DHCP polling checks. Helper function for ProcessEvent. */ void ResetDHCPNotificationFlags(void) { - WfxEvent_t outEvent; + WifiEvent outEvent; #if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) hasNotifiedIPV4 = false; @@ -664,13 +654,13 @@ void ResetDHCPNotificationFlags(void) hasNotifiedIPV6 = false; hasNotifiedWifiConnectivity = false; - outEvent.eventType = WFX_EVT_STA_DO_DHCP; - sl_matter_wifi_post_event(&outEvent); + outEvent = WifiEvent::kStationDoDhcp; + sl_matter_wifi_post_event(outEvent); } -void sl_matter_wifi_post_event(WfxEvent_t * event) +void sl_matter_wifi_post_event(WifiEvent event) { - sl_status_t status = osMessageQueuePut(sWifiEventQueue, event, 0, 0); + sl_status_t status = osMessageQueuePut(sWifiEventQueue, &event, 0, 0); if (status != osOK) { @@ -686,16 +676,16 @@ void sl_matter_wifi_post_event(WfxEvent_t * event) * This function is responsible for processing different types of Wi-Fi events and taking appropriate actions based on the event * type. * - * @param inEvent The input Wi-Fi event to be processed. + * @param event The input Wi-Fi event to be processed. */ -void ProcessEvent(WfxEvent_t inEvent) +void ProcessEvent(WifiEvent event) { // Process event - switch (inEvent.eventType) + switch (event) { - case WFX_EVT_STA_CONN: { - ChipLogDetail(DeviceLayer, "_onWFXEvent: WFX_EVT_STA_CONN"); - wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTED; + case WifiEvent::kStationConnect: { + ChipLogDetail(DeviceLayer, "WifiEvent::kStationConnect"); + wfx_rsi.dev_state.Set(WifiState::kStationConnected); ResetDHCPNotificationFlags(); wfx_lwip_set_sta_link_up(); /* We need to get AP Mac - TODO */ @@ -705,11 +695,12 @@ void ProcessEvent(WfxEvent_t inEvent) // is independant of IP connectivity. } break; - case WFX_EVT_STA_DISCONN: { - ChipLogDetail(DeviceLayer, "_onWFXEvent: WFX_EVT_STA_DISCONN"); + case WifiEvent::kStationDisconnect: { + ChipLogDetail(DeviceLayer, "WifiEvent::kStationDisconnect"); // TODO: This event is not being posted anywhere, seems to be a dead code or we are missing something - wfx_rsi.dev_state &= - ~(WFX_RSI_ST_STA_READY | WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED | WFX_RSI_ST_STA_DHCP_DONE); + WifiStateFlags flagsToClear = WifiStateFlags(WifiState::kStationReady, WifiState::kStationConnecting, + WifiState::kStationConnected, WifiState::kStationDhcpDone); + wfx_rsi.dev_state.Clear(flagsToClear); /* TODO: Implement disconnect notify */ ResetDHCPNotificationFlags(); wfx_lwip_set_sta_link_down(); // Internally dhcpclient_poll(netif) -> @@ -720,13 +711,10 @@ void ProcessEvent(WfxEvent_t inEvent) wfx_ipv6_notify(GET_IPV6_FAIL); } break; - case WFX_EVT_AP_START: - // TODO: Currently unimplemented - break; - case WFX_EVT_AP_STOP: + case WifiEvent::kAPStart: // TODO: Currently unimplemented break; - case WFX_EVT_SCAN: { + case WifiEvent::kScan: { #ifdef SL_WFX_CONFIG_SCAN rsi_rsp_scan_t scan_rsp = { 0 }; memset(&scan_rsp, 0, sizeof(scan_rsp)); @@ -757,7 +745,7 @@ void ProcessEvent(WfxEvent_t inEvent) chip::Platform::CopyString(ap.ssid, ap.ssid_length, reinterpret_cast(scan->ssid)); // check if the scanned ssid is the one we are looking for - if (wfx_rsi.scan_ssid_length != 0 && strncmp(wfx_rsi.scan_ssid, ap.ssid, WFX_MAX_SSID_LENGTH) != CMP_SUCCESS) + if (wfx_rsi.scan_ssid_length != 0 && strncmp(wfx_rsi.scan_ssid, ap.ssid, WFX_MAX_SSID_LENGTH) != 0) { continue; // we found the targeted ssid. } @@ -791,22 +779,22 @@ void ProcessEvent(WfxEvent_t inEvent) #endif /* SL_WFX_CONFIG_SCAN */ } break; - case WFX_EVT_STA_START_JOIN: { + case WifiEvent::kStationStartJoin: { // saving the AP related info wfx_rsi_save_ap_info(); // Joining to the network sl_wifi_platform_join_network(); } break; - case WFX_EVT_STA_DO_DHCP: { + case WifiEvent::kStationDoDhcp: { StartDHCPTimer(WFX_RSI_DHCP_POLL_INTERVAL); } break; - case WFX_EVT_STA_DHCP_DONE: { + case WifiEvent::kStationDhcpDone: { CancelDHCPTimer(); } break; - case WFX_EVT_DHCP_POLL: { + case WifiEvent::kStationDhcpPoll: { HandleDHCPPolling(); } break; @@ -835,17 +823,17 @@ void sl_matter_wifi_task(void * arg) ChipLogError(DeviceLayer, "sl_matter_wifi_task: sl_matter_wifi_init failed: %ld", rsi_status); return; } - WfxEvent_t wfxEvent; + WifiEvent event; sl_matter_lwip_start(); sl_matter_wifi_task_started(); ChipLogProgress(DeviceLayer, "sl_matter_wifi_task: starting event loop"); for (;;) { - osStatus_t status = osMessageQueueGet(sWifiEventQueue, &wfxEvent, NULL, osWaitForever); + osStatus_t status = osMessageQueueGet(sWifiEventQueue, &event, NULL, osWaitForever); if (status == osOK) { - ProcessEvent(wfxEvent); + ProcessEvent(event); } else { @@ -868,16 +856,15 @@ void wfx_dhcp_got_ipv4(uint32_t ip) /* * Acquire the new IP address */ - wfx_rsi.ip4_addr[0] = (ip) &HEX_VALUE_FF; - wfx_rsi.ip4_addr[1] = (ip >> 8) & HEX_VALUE_FF; - wfx_rsi.ip4_addr[2] = (ip >> 16) & HEX_VALUE_FF; - wfx_rsi.ip4_addr[3] = (ip >> 24) & HEX_VALUE_FF; + wfx_rsi.ip4_addr[0] = (ip) &0xFF; + wfx_rsi.ip4_addr[1] = (ip >> 8) & 0xFF; + wfx_rsi.ip4_addr[2] = (ip >> 16) & 0xFF; + wfx_rsi.ip4_addr[3] = (ip >> 24) & 0xFF; ChipLogProgress(DeviceLayer, "DHCP OK: IP=%d.%d.%d.%d", wfx_rsi.ip4_addr[0], wfx_rsi.ip4_addr[1], wfx_rsi.ip4_addr[2], wfx_rsi.ip4_addr[3]); /* Notify the Connectivity Manager - via the app */ - wfx_rsi.dev_state |= WFX_RSI_ST_STA_DHCP_DONE; + wfx_rsi.dev_state.Set(WifiState::kStationDhcpDone, WifiState::kStationReady); wfx_ip_changed_notify(IP_STATUS_SUCCESS); - wfx_rsi.dev_state |= WFX_RSI_ST_STA_READY; } #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ @@ -968,4 +955,17 @@ int32_t wfx_rsi_send_data(void * p, uint16_t len) return status; } -WfxRsi_t wfx_rsi; +#if SL_ICD_ENABLED +/********************************************************************* + * @fn sl_status_t wfx_power_save(void) + * @brief + * Implements the power save in sleepy application + * @param[in] None + * @return SL_STATUS_OK if successful, + * SL_STATUS_FAIL otherwise + ***********************************************************************/ +sl_status_t wfx_power_save(void) // TODO : Figure out why the extern C is necessary +{ + return (wfx_rsi_power_save() ? SL_STATUS_FAIL : SL_STATUS_OK); +} +#endif /* SL_ICD_ENABLED */ diff --git a/examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c b/src/platform/silabs/wifi/rs911x/platform/efx32_ncp_host.c similarity index 96% rename from examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c rename to src/platform/silabs/wifi/rs911x/platform/efx32_ncp_host.c index 0a2fad7d0deb6c..c7173763d5f96c 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/efx32_ncp_host.c +++ b/src/platform/silabs/wifi/rs911x/platform/efx32_ncp_host.c @@ -26,9 +26,11 @@ #include "sl_constants.h" #include "sl_rsi_utility.h" #include "sl_si91x_host_interface.h" +#include "sl_si91x_ncp_utility.h" #include "sl_si91x_status.h" #include "sl_status.h" #include "sl_wifi_constants.h" +#include #include #include @@ -40,9 +42,6 @@ #include "sl_board_control.h" #endif // SL_BOARD_NAME -#include "sl_si91x_ncp_utility.h" -#include "spi_multiplex.h" - static bool dma_callback(unsigned int channel, unsigned int sequenceNo, void * userParam); uint32_t rx_ldma_channel; diff --git a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c b/src/platform/silabs/wifi/rs911x/platform/efx_spi.c similarity index 95% rename from examples/platform/silabs/efr32/rs911x/hal/efx_spi.c rename to src/platform/silabs/wifi/rs911x/platform/efx_spi.c index b1e4468cfb06e8..a339f711a41f35 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c +++ b/src/platform/silabs/wifi/rs911x/platform/efx_spi.c @@ -18,33 +18,23 @@ /** * Includes */ -#include -#include -#include #include "FreeRTOS.h" -#include "event_groups.h" -#include "semphr.h" -#include "task.h" - -#include "dmadrv.h" -#include "em_chip.h" #include "em_cmu.h" -#include "em_core.h" -#include "em_device.h" -#include "em_gpio.h" -#include "em_ldma.h" +#include "em_eusart.h" #include "gpiointerrupt.h" +#include "rsi_board_configuration.h" +#include "rsi_driver.h" +#include "semphr.h" +#include "silabs_utils.h" #include "sl_device_init_clocks.h" #include "sl_device_init_hfxo.h" +#include "sl_spidrv_eusart_exp_config.h" #include "sl_spidrv_instances.h" #include "sl_status.h" #include "spidrv.h" - -#include "WifiInterfaceAbstraction.h" -#include "silabs_utils.h" -#include "spi_multiplex.h" -#include "wfx_host_events.h" +#include "task.h" +#include #ifdef SL_BOARD_NAME #include "sl_board_control.h" @@ -54,9 +44,6 @@ #include "sl_power_manager.h" #endif -#include "rsi_board_configuration.h" -#include "rsi_driver.h" - #if SL_BTLCTRL_MUX #include "btl_interface.h" #endif // SL_BTLCTRL_MUX @@ -68,13 +55,12 @@ #include "sl_mx25_flash_shutdown_usart_config.h" #endif // SL_MX25CTRL_MUX -#include "em_eusart.h" -#include "sl_spidrv_eusart_exp_config.h" -#include "spi_multiplex.h" - #define SL_SPIDRV_HANDLE sl_spidrv_eusart_exp_handle #define SL_SPIDRV_EXP_BITRATE_MULTIPLEXED SL_SPIDRV_EUSART_EXP_BITRATE +#define MIN_XLEN (0) +#define WFX_SPI_NVIC_PRIORITY (5) + #define CONCAT(A, B) (A##B) #define SPI_CLOCK(N) CONCAT(cmuClock_USART, N) // Macro to drive semaphore block minimun timer in milli seconds @@ -111,16 +97,16 @@ void sl_wfx_host_gpio_init(void) CMU_ClockEnable(cmuClock_GPIO, true); // Set CS pin to high/inactive - GPIO_PinModeSet(SL_SPIDRV_EUSART_EXP_CS_PORT, SL_SPIDRV_EUSART_EXP_CS_PIN, gpioModePushPull, PINOUT_SET); + GPIO_PinModeSet(SL_SPIDRV_EUSART_EXP_CS_PORT, SL_SPIDRV_EUSART_EXP_CS_PIN, gpioModePushPull, 1); - GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModePushPull, PINOUT_SET); - GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModePushPull, PINOUT_CLEAR); + GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModePushPull, 1); + GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModePushPull, 0); CMU_OscillatorEnable(cmuOsc_LFXO, true, true); // Set up interrupt based callback function - trigger on both edges. GPIOINT_Init(); - GPIO_PinModeSet(WFX_INTERRUPT_PIN.port, WFX_INTERRUPT_PIN.pin, gpioModeInputPull, PINOUT_CLEAR); + GPIO_PinModeSet(WFX_INTERRUPT_PIN.port, WFX_INTERRUPT_PIN.pin, gpioModeInputPull, 0); GPIO_ExtIntConfig(WFX_INTERRUPT_PIN.port, WFX_INTERRUPT_PIN.pin, SL_WFX_HOST_PINOUT_SPI_IRQ, true, false, true); GPIOINT_CallbackRegister(SL_WFX_HOST_PINOUT_SPI_IRQ, rsi_gpio_irq_cb); GPIO_IntDisable(1 << SL_WFX_HOST_PINOUT_SPI_IRQ); /* Will be enabled by RSI */ @@ -205,7 +191,7 @@ sl_status_t sl_wfx_host_spi_cs_deassert(void) if (SL_STATUS_OK == status) { GPIO_PinOutSet(SL_SPIDRV_EUSART_EXP_CS_PORT, SL_SPIDRV_EUSART_EXP_CS_PIN); - GPIO->EUSARTROUTE[SL_SPIDRV_EUSART_EXP_PERIPHERAL_NO].ROUTEEN = PINOUT_CLEAR; + GPIO->EUSARTROUTE[SL_SPIDRV_EUSART_EXP_PERIPHERAL_NO].ROUTEEN = 0; spi_enabled = false; } } @@ -268,7 +254,7 @@ sl_status_t sl_wfx_host_post_bootloader_spi_transfer(void) #endif // SL_SPICTRL_MUX return SL_STATUS_FAIL; } - GPIO->USARTROUTE[SL_MX25_FLASH_SHUTDOWN_PERIPHERAL_NO].ROUTEEN = PINOUT_CLEAR; + GPIO->USARTROUTE[SL_MX25_FLASH_SHUTDOWN_PERIPHERAL_NO].ROUTEEN = 0; #if SL_MX25CTRL_MUX sl_wfx_host_spiflash_cs_deassert(); #endif // SL_MX25CTRL_MUX @@ -301,7 +287,7 @@ sl_status_t sl_wfx_host_post_lcd_spi_transfer(void) { USART_Enable(SL_MEMLCD_SPI_PERIPHERAL, usartDisable); CMU_ClockEnable(SPI_CLOCK(SL_MEMLCD_SPI_PERIPHERAL_NO), false); - GPIO->USARTROUTE[SL_MEMLCD_SPI_PERIPHERAL_NO].ROUTEEN = PINOUT_CLEAR; + GPIO->USARTROUTE[SL_MEMLCD_SPI_PERIPHERAL_NO].ROUTEEN = 0; sl_status_t status = sl_board_disable_display(); #if SL_SPICTRL_MUX xSemaphoreGive(spi_sem_sync_hdl); diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_board_configuration.h b/src/platform/silabs/wifi/rs911x/platform/rsi_board_configuration.h similarity index 100% rename from examples/platform/silabs/efr32/rs911x/hal/rsi_board_configuration.h rename to src/platform/silabs/wifi/rs911x/platform/rsi_board_configuration.h diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal.h b/src/platform/silabs/wifi/rs911x/platform/rsi_hal.h similarity index 100% rename from examples/platform/silabs/efr32/rs911x/hal/rsi_hal.h rename to src/platform/silabs/wifi/rs911x/platform/rsi_hal.h diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c b/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_interrupt.c similarity index 98% rename from examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c rename to src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_interrupt.c index fb6a947f95a40c..8bd277e6242c4d 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c +++ b/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_interrupt.c @@ -35,9 +35,6 @@ #include "event_groups.h" #include "task.h" -#include "WifiInterfaceAbstraction.h" -#include "wfx_host_events.h" - #if (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) #include "sl_board_configuration.h" diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c b/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_ioports.c similarity index 92% rename from examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c rename to src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_ioports.c index bb7dcf4a70498d..ba517b417bdff7 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c +++ b/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_ioports.c @@ -35,9 +35,6 @@ #include "event_groups.h" #include "task.h" -#include "WifiInterfaceAbstraction.h" -#include "wfx_host_events.h" - #include "rsi_board_configuration.h" #include "rsi_driver.h" /*===========================================================*/ @@ -64,17 +61,17 @@ void rsi_hal_config_gpio(uint8_t gpio_number, uint8_t mode, uint8_t value) { case RSI_HAL_SLEEP_CONFIRM_PIN: case RSI_HAL_LP_SLEEP_CONFIRM_PIN: - GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModeWiredOrPullDown, PINOUT_SET); + GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModeWiredOrPullDown, 1); break; case RSI_HAL_WAKEUP_INDICATION_PIN: #ifndef LOGGING_STATS - GPIO_PinModeSet(WAKE_INDICATOR_PIN.port, WAKE_INDICATOR_PIN.pin, gpioModeWiredOrPullDown, PINOUT_CLEAR); + GPIO_PinModeSet(WAKE_INDICATOR_PIN.port, WAKE_INDICATOR_PIN.pin, gpioModeWiredOrPullDown, 0); #else - GPIO_PinModeSet(LOGGING_WAKE_INDICATOR_PIN.port, LOGGING_WAKE_INDICATOR_PIN.pin, gpioModeWiredOrPullDown, PINOUT_CLEAR); + GPIO_PinModeSet(LOGGING_WAKE_INDICATOR_PIN.port, LOGGING_WAKE_INDICATOR_PIN.pin, gpioModeWiredOrPullDown, 0); #endif break; case RSI_HAL_RESET_PIN: - GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModePushPull, PINOUT_SET); + GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModePushPull, 1); break; default: break; @@ -96,17 +93,17 @@ void rsi_hal_set_gpio(uint8_t gpio_number) { case RSI_HAL_SLEEP_CONFIRM_PIN: case RSI_HAL_LP_SLEEP_CONFIRM_PIN: - GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModeWiredOrPullDown, PINOUT_SET); + GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModeWiredOrPullDown, 1); break; case RSI_HAL_WAKEUP_INDICATION_PIN: #ifndef LOGGING_STATS - GPIO_PinModeSet(WAKE_INDICATOR_PIN.port, WAKE_INDICATOR_PIN.pin, gpioModeInput, PINOUT_SET); + GPIO_PinModeSet(WAKE_INDICATOR_PIN.port, WAKE_INDICATOR_PIN.pin, gpioModeInput, 1); #else - GPIO_PinModeSet(LOGGING_WAKE_INDICATOR_PIN.port, LOGGING_WAKE_INDICATOR_PIN.pin, gpioModeInput, PINOUT_SET); + GPIO_PinModeSet(LOGGING_WAKE_INDICATOR_PIN.port, LOGGING_WAKE_INDICATOR_PIN.pin, gpioModeInput, 1); #endif break; case RSI_HAL_RESET_PIN: - GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModeWiredOrPullDown, PINOUT_SET); + GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModeWiredOrPullDown, 1); break; default: break; diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_rtc.c b/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_rtc.c similarity index 100% rename from examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_rtc.c rename to src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_rtc.c diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c b/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_timer.c similarity index 97% rename from examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c rename to src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_timer.c index b8ffea83f97b35..9c1b1377487a75 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c +++ b/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_timer.c @@ -34,12 +34,9 @@ extern void SysTick_Handler(void); extern void xPortSysTickHandler(void); #endif /* SysTick */ #endif /* RSI_WITH_OS */ -#include "wfx_host_events.h" - /* RSI Driver include file */ #include "rsi_driver.h" /* RSI WLAN Config include file */ -#include "WifiInterfaceAbstraction.h" #include "rsi_bootup_config.h" #include "rsi_common_apis.h" #include "rsi_data_types.h" @@ -51,6 +48,10 @@ extern void xPortSysTickHandler(void); #include "rsi_wlan_apis.h" #include "rsi_wlan_config.h" +#define WFX_RSI_NUM_TIMERS (2) /* Number of RSI timers to alloc */ +#define CONVERT_SEC_TO_MSEC (1000) +#define CONVERT_USEC_TO_MSEC (1 / 1000) + #ifndef _use_the_rsi_defined_functions StaticTimer_t sRsiTimerBuffer; @@ -134,7 +135,7 @@ int32_t rsi_timer_start(uint8_t timer_node, uint8_t mode, uint8_t type, uint32_t return RSI_ERROR_INSUFFICIENT_BUFFER; } - (void) xTimerStart(tp->handle, TIMER_TICKS_TO_WAIT_0); + (void) xTimerStart(tp->handle, pdMS_TO_TICKS(0)); return RSI_ERROR_NONE; } diff --git a/examples/platform/silabs/efr32/rs911x/hal/sl_board_configuration.h b/src/platform/silabs/wifi/rs911x/platform/sl_board_configuration.h similarity index 100% rename from examples/platform/silabs/efr32/rs911x/hal/sl_board_configuration.h rename to src/platform/silabs/wifi/rs911x/platform/sl_board_configuration.h diff --git a/examples/platform/silabs/efr32/rs911x/hal/sl_board_configuration_SiWx917.h b/src/platform/silabs/wifi/rs911x/platform/sl_board_configuration_SiWx917.h similarity index 100% rename from examples/platform/silabs/efr32/rs911x/hal/sl_board_configuration_SiWx917.h rename to src/platform/silabs/wifi/rs911x/platform/sl_board_configuration_SiWx917.h diff --git a/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c b/src/platform/silabs/wifi/rs911x/platform/sl_si91x_ncp_utility.c similarity index 95% rename from examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c rename to src/platform/silabs/wifi/rs911x/platform/sl_si91x_ncp_utility.c index 4db0470538027f..1d1ab1409c4161 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c +++ b/src/platform/silabs/wifi/rs911x/platform/sl_si91x_ncp_utility.c @@ -44,10 +44,8 @@ #include "sl_device_init_hfxo.h" #include "sl_status.h" -#include "WifiInterfaceAbstraction.h" #include "silabs_utils.h" #include "sl_si91x_ncp_utility.h" -#include "wfx_host_events.h" #if SL_MX25CTRL_MUX sl_status_t sl_wfx_host_spiflash_cs_assert(void); @@ -221,7 +219,7 @@ sl_status_t sl_wfx_host_post_bootloader_spi_transfer(void) #endif // SL_SPICTRL_MUX return SL_STATUS_FAIL; } - GPIO->USARTROUTE[SL_MX25_FLASH_SHUTDOWN_PERIPHERAL_NO].ROUTEEN = PINOUT_CLEAR; + GPIO->USARTROUTE[SL_MX25_FLASH_SHUTDOWN_PERIPHERAL_NO].ROUTEEN = 0; #if SL_MX25CTRL_MUX sl_wfx_host_spiflash_cs_deassert(); #endif // SL_MX25CTRL_MUX diff --git a/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.h b/src/platform/silabs/wifi/rs911x/platform/sl_si91x_ncp_utility.h similarity index 84% rename from examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.h rename to src/platform/silabs/wifi/rs911x/platform/sl_si91x_ncp_utility.h index 0bd8dae7641807..b434e35f82dbbd 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.h +++ b/src/platform/silabs/wifi/rs911x/platform/sl_si91x_ncp_utility.h @@ -29,7 +29,9 @@ #include "semphr.h" #include "silabs_utils.h" #include "sl_status.h" -#include "spi_multiplex.h" + +// TODO: This is a WF200 specific include. It is not clear why we need this in the 917 NCP files. +#include #if defined(CHIP_9117) #include "em_usart.h" @@ -46,4 +48,4 @@ sl_status_t spi_board_init(void); extern uint32_t rx_ldma_channel; extern uint32_t tx_ldma_channel; -#endif // SL_SI91X_NCP_UTILITY_H \ No newline at end of file +#endif // SL_SI91X_NCP_UTILITY_H diff --git a/examples/platform/silabs/efr32/rs911x/rs9117.gni b/src/platform/silabs/wifi/rs911x/rs9117.gni similarity index 74% rename from examples/platform/silabs/efr32/rs911x/rs9117.gni rename to src/platform/silabs/wifi/rs911x/rs9117.gni index 63f027e59f9087..cbeaf98698c705 100644 --- a/examples/platform/silabs/efr32/rs911x/rs9117.gni +++ b/src/platform/silabs/wifi/rs911x/rs9117.gni @@ -17,21 +17,22 @@ import("//build_overrides/efr32_sdk.gni") import("${silabs_sdk_build_root}/efr32_sdk.gni") rs911x_src_plat = [ - "${chip_root}/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp", - "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_interrupt.c", - "${examples_plat_dir}/rs911x/hal/sl_si91x_ncp_utility.c", - "${examples_plat_dir}/rs911x/hal/efx32_ncp_host.c", - "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", -] + "${chip_root}/src/platform/silabs/wifi/SiWx/WifiInterface.cpp", + "${chip_root}/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_interrupt.c", + "${chip_root}/src/platform/silabs/wifi/rs911x/platform/sl_si91x_ncp_utility.c", + "${chip_root}/src/platform/silabs/wifi/rs911x/platform/sl_board_configuration.h", + "${chip_root}/src/platform/silabs/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.cpp", + "${chip_root}/src/platform/silabs/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.h", + + # TODO: We shouldn't need a file form the WF200 for the SiWx917 NCP builds + "${chip_root}/src/platform/silabs/wifi/wf200/platform/spi_multiplex.h", -rs9117_inc_plat = [ - "${examples_plat_dir}/rs911x", - "${examples_plat_dir}/rs911x/hal", - "${wifi_sdk_root}/components/si91x/ble/inc", - "${silabs_common_plat_dir}/wifi", + # TODO : We should be using the file from the Wiseconnect SDK and not our copy of it. + "${chip_root}/src/platform/silabs/wifi/rs911x/platform/efx32_ncp_host.c", ] -rs911x_cflags = [ "-Wno-empty-body" ] +rs9117_inc_plat = [ "${wifi_sdk_root}/components/si91x/ble/inc" ] + rs9117_src_sapi = [ # sl_si91x_wireless component "${wifi_sdk_root}/components/device/silabs/si91x/wireless/src/sl_si91x_driver.c", diff --git a/examples/platform/silabs/efr32/rs911x/rs911x.gni b/src/platform/silabs/wifi/rs911x/rs911x.gni similarity index 80% rename from examples/platform/silabs/efr32/rs911x/rs911x.gni rename to src/platform/silabs/wifi/rs911x/rs911x.gni index 4aedb66dca9f0c..3daba8b049c802 100644 --- a/examples/platform/silabs/efr32/rs911x/rs911x.gni +++ b/src/platform/silabs/wifi/rs911x/rs911x.gni @@ -17,12 +17,14 @@ import("//build_overrides/efr32_sdk.gni") import("${silabs_sdk_build_root}/efr32_sdk.gni") rs911x_src_plat = [ - "${examples_plat_dir}/rs911x/Rsi91xWifiInterface.cpp", - "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_interrupt.c", - "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_ioports.c", - "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_timer.c", - "${examples_plat_dir}/rs911x/hal/efx_spi.c", - "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", + "${chip_root}/src/platform/silabs/wifi/rs911x/WifiInterface.cpp", + "${chip_root}/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_interrupt.c", + "${chip_root}/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_ioports.c", + "${chip_root}/src/platform/silabs/wifi/rs911x/platform/rsi_hal_mcu_timer.c", + "${chip_root}/src/platform/silabs/wifi/rs911x/platform/efx_spi.c", + "${chip_root}/src/platform/silabs/wifi/rs911x/platform/rsi_board_configuration.h", + "${chip_root}/src/platform/silabs/wifi/rs911x/platform/rsi_hal.h", + "${chip_root}/src/platform/silabs/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.cpp", ] # @@ -66,11 +68,4 @@ rs911x_src_sapi = [ "${wiseconnect_sdk_root}/sapi/network/socket/rsi_socket_rom.c", ] -rs911x_cflags = [ "-Wno-empty-body" ] - -rs911x_inc_plat = [ - "${examples_plat_dir}/rs911x", - "${examples_plat_dir}/rs911x/hal", - "${wiseconnect_sdk_root}/sapi/include", - "${silabs_common_plat_dir}/wifi", -] +rs911x_inc_plat = [ "${wiseconnect_sdk_root}/sapi/include" ] diff --git a/examples/platform/silabs/efr32/rs911x/rsi_wlan_config.h b/src/platform/silabs/wifi/rs911x/rsi_wlan_config.h similarity index 100% rename from examples/platform/silabs/efr32/rs911x/rsi_wlan_config.h rename to src/platform/silabs/wifi/rs911x/rsi_wlan_config.h diff --git a/examples/platform/silabs/efr32/wf200/Wf200WifiInterface.cpp b/src/platform/silabs/wifi/wf200/WifiInterface.cpp similarity index 91% rename from examples/platform/silabs/efr32/wf200/Wf200WifiInterface.cpp rename to src/platform/silabs/wifi/wf200/WifiInterface.cpp index e38f4c43a27e67..fef3cb3a63a022 100644 --- a/examples/platform/silabs/efr32/wf200/Wf200WifiInterface.cpp +++ b/src/platform/silabs/wifi/wf200/WifiInterface.cpp @@ -15,39 +15,37 @@ * limitations under the License. */ -/* Includes */ - -#include -#include -#include - +#include "FreeRTOS.h" #include "em_bus.h" #include "em_cmu.h" #include "em_gpio.h" #include "em_ldma.h" #include "em_usart.h" -#include "gpiointerrupt.h" - -#include "AppConfig.h" -#include "sl_wfx_board.h" -#include "sl_wfx_host.h" -#include "sl_wfx_task.h" -#include "wfx_host_events.h" - -#include "FreeRTOS.h" #include "event_groups.h" +#include "gpiointerrupt.h" +#include "sl_wfx_cmd_api.h" +#include "sl_wfx_constants.h" #include "task.h" - -#include "dhcp_client.h" -#include "ethernetif.h" #include #include #include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include using namespace ::chip; using namespace ::chip::DeviceLayer; +// TODO: This is a workaround because we depend on the platform lib which depends on the platform implementation. +// As such we can't depend on the platform here as well +extern void HandleWFXSystemEvent(wfx_event_base_t eventBase, sl_wfx_generic_message_t * eventData); + /* wfxRsi Task will use as its stack */ StackType_t wfxEventTaskStack[1024] = { 0 }; @@ -68,9 +66,30 @@ static wfx_wifi_scan_result_t ap_info; #define PASSIVE_CHANNEL_TIME 0 #define NUM_PROBE_REQUEST 2 -// wfx_fmac_driver context -sl_wfx_context_t wifiContext; -static uint8_t wifi_extra; +/* Wi-Fi bitmask events - for the task */ +#define SL_WFX_CONNECT (1 << 1) +#define SL_WFX_DISCONNECT (1 << 2) +#define SL_WFX_START_AP (1 << 3) +#define SL_WFX_STOP_AP (1 << 4) +#define SL_WFX_SCAN_START (1 << 5) +#define SL_WFX_SCAN_COMPLETE (1 << 6) +#define SL_WFX_RETRY_CONNECT (1 << 7) + +#define WLAN_TASK_STACK_SIZE (1024) +#define ETH_FRAME (0) +#define AP_START_SUCCESS (0) +#define BITS_TO_WAIT (0) +#define BEACON_1 (0) +#define CHANNEL_LIST ((const uint8_t *) 0) +#define CHANNEL_COUNT (0) +#define IE_DATA ((const uint8_t *) 0) +#define IE_DATA_LENGTH (0) +#define BSSID_SCAN ((const uint8_t *) 0) +#define CHANNEL_0 (0) +#define PREVENT_ROAMING (1) +#define DISABLE_PMF_MODE (0) +#define STA_IP_FAIL (0) +#define WLAN_TASK_PRIORITY (1) /***************************************************************************** * macros @@ -90,8 +109,6 @@ uint8_t softap_channel = SOFTAP_CHANNEL_DEFAULT; /* station network interface structures */ struct netif * sta_netif; wfx_wifi_provision_t wifi_provision; -sl_wfx_get_counters_cnf_t * counters; -sl_wfx_get_counters_cnf_t * Tempcounters; #define PUT_COUNTER(name) ChipLogDetail(DeviceLayer, "%-24s %lu", #name, (unsigned long) counters->body.count_##name); bool hasNotifiedIPV6 = false; @@ -131,6 +148,162 @@ static void sl_wfx_ap_client_rejected_callback(uint32_t status, uint8_t * mac); extern uint32_t gOverrunCount; +namespace { + +// wfx_fmac_driver context +sl_wfx_context_t wifiContext; +uint8_t wifi_extra; + +typedef struct __attribute__((__packed__)) sl_wfx_get_counters_cnf_body_s +{ + uint32_t status; + uint16_t mib_id; + uint16_t length; + uint32_t rcpi; + uint32_t count_plcp_errors; + uint32_t count_fcs_errors; + uint32_t count_tx_packets; + uint32_t count_rx_packets; + uint32_t count_rx_packet_errors; + uint32_t count_rx_decryption_failures; + uint32_t count_rx_mic_failures; + uint32_t count_rx_no_key_failures; + uint32_t count_tx_multicast_frames; + uint32_t count_tx_frames_success; + uint32_t count_tx_frame_failures; + uint32_t count_tx_frames_retried; + uint32_t count_tx_frames_multi_retried; + uint32_t count_rx_frame_duplicates; + uint32_t count_rts_success; + uint32_t count_rts_failures; + uint32_t count_ack_failures; + uint32_t count_rx_multicast_frames; + uint32_t count_rx_frames_success; + uint32_t count_rx_cmacicv_errors; + uint32_t count_rx_cmac_replays; + uint32_t count_rx_mgmt_ccmp_replays; + uint32_t count_rx_bipmic_errors; + uint32_t count_rx_beacon; + uint32_t count_miss_beacon; + uint32_t reserved[15]; +} sl_wfx_get_counters_cnf_body_t; + +typedef struct __attribute__((__packed__)) sl_wfx_get_counters_cnf_s +{ + /** Common message header. */ + sl_wfx_header_t header; + /** Confirmation message body. */ + sl_wfx_get_counters_cnf_body_t body; +} sl_wfx_get_counters_cnf_t; + +typedef struct __attribute__((__packed__)) sl_wfx_mib_req_body_s +{ + uint16_t mib_id; ///< ID of the MIB to be read. + uint16_t reserved; +} sl_wfx_mib_req_body_t; + +typedef struct __attribute__((__packed__)) sl_wfx_header_mib_s +{ + uint16_t length; ///< Message length in bytes including this uint16_t. + ///< Maximum value is 8188 but maximum Request size is FW dependent and reported in the + ///< ::sl_wfx_startup_ind_body_t::size_inp_ch_buf. + uint8_t id; ///< Contains the message Id indexed by sl_wfx_general_commands_ids_t or sl_wfx_message_ids_t. + uint8_t reserved : 1; + uint8_t interface : 2; + uint8_t seqnum : 3; + uint8_t encrypted : 2; +} sl_wfx_header_mib_t; + +typedef struct __attribute__((__packed__)) sl_wfx_mib_req_s +{ + /** Common message header. */ + sl_wfx_header_mib_t header; + /** Request message body. */ + sl_wfx_mib_req_body_t body; +} sl_wfx_mib_req_t; + +sl_wfx_get_counters_cnf_t * counters; + +/**************************************************************************** + * @brief + * get the wifi state + * @return returns wificonetext state + *****************************************************************************/ +sl_wfx_state_t wfx_get_wifi_state(void) +{ + return wifiContext.state; +} + +sl_status_t get_all_counters(void) +{ + sl_status_t result; + uint8_t command_id = 0x05; + uint16_t mib_id = 0x2035; + sl_wfx_mib_req_t * request = nullptr; + uint32_t request_length = SL_WFX_ROUND_UP_EVEN(sizeof(sl_wfx_header_mib_t) + sizeof(sl_wfx_mib_req_body_t)); + + result = + sl_wfx_allocate_command_buffer((sl_wfx_generic_message_t **) &request, command_id, SL_WFX_CONTROL_BUFFER, request_length); + + VerifyOrReturnError(request != nullptr, SL_STATUS_NULL_POINTER); + + request->body.mib_id = mib_id; + request->header.interface = 0x2; + request->header.encrypted = 0x0; + + result = sl_wfx_send_request(command_id, (sl_wfx_generic_message_t *) request, request_length); + SL_WFX_ERROR_CHECK(result); + + result = sl_wfx_host_wait_for_confirmation(command_id, SL_WFX_DEFAULT_REQUEST_TIMEOUT_MS, (void **) &counters); + SL_WFX_ERROR_CHECK(result); + + ChipLogDetail(DeviceLayer, "%-24s %12s ", "", "Debug Counters Content"); + ChipLogDetail(DeviceLayer, "%-24s %lu", "rcpi", (unsigned long) counters->body.rcpi); + PUT_COUNTER(plcp_errors); + PUT_COUNTER(fcs_errors); + PUT_COUNTER(tx_packets); + PUT_COUNTER(rx_packets); + PUT_COUNTER(rx_packet_errors); + PUT_COUNTER(rx_decryption_failures); + PUT_COUNTER(rx_mic_failures); + PUT_COUNTER(rx_no_key_failures); + PUT_COUNTER(tx_multicast_frames); + PUT_COUNTER(tx_frames_success); + PUT_COUNTER(tx_frame_failures); + PUT_COUNTER(tx_frames_retried); + PUT_COUNTER(tx_frames_multi_retried); + PUT_COUNTER(rx_frame_duplicates); + PUT_COUNTER(rts_success); + PUT_COUNTER(rts_failures); + PUT_COUNTER(ack_failures); + PUT_COUNTER(rx_multicast_frames); + PUT_COUNTER(rx_frames_success); + PUT_COUNTER(rx_cmacicv_errors); + PUT_COUNTER(rx_cmac_replays); + PUT_COUNTER(rx_mgmt_ccmp_replays); + PUT_COUNTER(rx_bipmic_errors); + PUT_COUNTER(rx_beacon); + PUT_COUNTER(miss_beacon); + +error_handler: + + if (result == SL_STATUS_TIMEOUT) + { + if (sl_wfx_context->used_buffers > 0) + { + sl_wfx_context->used_buffers--; + } + } + if (request != nullptr) + { + sl_wfx_free_command_buffer((sl_wfx_generic_message_t *) request, command_id, SL_WFX_CONTROL_BUFFER); + } + + return result; +} + +} // namespace + /*************************************************************************** * @brief * Creates WFX events processing task. @@ -162,7 +335,7 @@ sl_status_t sl_wfx_host_process_event(sl_wfx_generic_message_t * event_payload) /******** INDICATION ********/ case SL_WFX_STARTUP_IND_ID: { ChipLogProgress(DeviceLayer, "startup completed."); - PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, event_payload); + HandleWFXSystemEvent(WIFI_EVENT, event_payload); break; } case SL_WFX_CONNECT_IND_ID: { @@ -278,7 +451,7 @@ static void sl_wfx_scan_result_callback(sl_wfx_scan_result_ind_body_t * scan_res /* don't save if filter only wants specific ssid */ if (scan_ssid != nullptr) { - if (strcmp(scan_ssid, (char *) &scan_result->ssid_def.ssid[0]) != CMP_SUCCESS) + if (strcmp(scan_ssid, (char *) &scan_result->ssid_def.ssid[0]) != 0) return; } if ((ap = (struct scan_result_holder *) (chip::Platform::MemoryAlloc(sizeof(*ap)))) == (struct scan_result_holder *) 0) @@ -779,74 +952,6 @@ int32_t wfx_get_ap_ext(wfx_wifi_scan_ext_t * extra_info) return status; } -sl_status_t get_all_counters(void) -{ - sl_status_t result; - uint8_t command_id = 0x05; - uint16_t mib_id = 0x2035; - sl_wfx_mib_req_t * request = nullptr; - uint32_t request_length = SL_WFX_ROUND_UP_EVEN(sizeof(sl_wfx_header_mib_t) + sizeof(sl_wfx_mib_req_body_t)); - - result = - sl_wfx_allocate_command_buffer((sl_wfx_generic_message_t **) &request, command_id, SL_WFX_CONTROL_BUFFER, request_length); - - VerifyOrReturnError(request != nullptr, SL_STATUS_NULL_POINTER); - - request->body.mib_id = mib_id; - request->header.interface = 0x2; - request->header.encrypted = 0x0; - - result = sl_wfx_send_request(command_id, (sl_wfx_generic_message_t *) request, request_length); - SL_WFX_ERROR_CHECK(result); - - result = sl_wfx_host_wait_for_confirmation(command_id, SL_WFX_DEFAULT_REQUEST_TIMEOUT_MS, (void **) &counters); - SL_WFX_ERROR_CHECK(result); - - ChipLogDetail(DeviceLayer, "%-24s %12s ", "", "Debug Counters Content"); - ChipLogDetail(DeviceLayer, "%-24s %lu", "rcpi", (unsigned long) counters->body.rcpi); - PUT_COUNTER(plcp_errors); - PUT_COUNTER(fcs_errors); - PUT_COUNTER(tx_packets); - PUT_COUNTER(rx_packets); - PUT_COUNTER(rx_packet_errors); - PUT_COUNTER(rx_decryption_failures); - PUT_COUNTER(rx_mic_failures); - PUT_COUNTER(rx_no_key_failures); - PUT_COUNTER(tx_multicast_frames); - PUT_COUNTER(tx_frames_success); - PUT_COUNTER(tx_frame_failures); - PUT_COUNTER(tx_frames_retried); - PUT_COUNTER(tx_frames_multi_retried); - PUT_COUNTER(rx_frame_duplicates); - PUT_COUNTER(rts_success); - PUT_COUNTER(rts_failures); - PUT_COUNTER(ack_failures); - PUT_COUNTER(rx_multicast_frames); - PUT_COUNTER(rx_frames_success); - PUT_COUNTER(rx_cmacicv_errors); - PUT_COUNTER(rx_cmac_replays); - PUT_COUNTER(rx_mgmt_ccmp_replays); - PUT_COUNTER(rx_bipmic_errors); - PUT_COUNTER(rx_beacon); - PUT_COUNTER(miss_beacon); - -error_handler: - - if (result == SL_STATUS_TIMEOUT) - { - if (sl_wfx_context->used_buffers > 0) - { - sl_wfx_context->used_buffers--; - } - } - if (request != nullptr) - { - sl_wfx_free_command_buffer((sl_wfx_generic_message_t *) request, command_id, SL_WFX_CONTROL_BUFFER); - } - - return result; -} - /************************************************************************ * @brief * reset the count @@ -877,16 +982,6 @@ sl_status_t wfx_wifi_start(void) return SL_STATUS_OK; } -/**************************************************************************** - * @brief - * get the wifi state - * @return returns wificonetext state - *****************************************************************************/ -sl_wfx_state_t wfx_get_wifi_state(void) -{ - return wifiContext.state; -} - /**************************************************************************** * @brief * getnetif using interface @@ -909,19 +1004,6 @@ struct netif * wfx_GetNetif(sl_wfx_interface_t interface) return SelectedNetif; } -/**************************************************************************** - * @brief - * get the wifi mac address using interface - * @param[in] interface: - * @return returns wificontext.mac_addr_o if successful, - * wificontext.mac_addr_1 otherwise - *****************************************************************************/ -sl_wfx_mac_address_t wfx_get_wifi_mac_addr(sl_wfx_interface_t interface) -{ - // return Mac address used by WFX SL_WFX_STA_INTERFACE or SL_WFX_SOFTAP_INTERFACE, - return (interface == SL_WFX_STA_INTERFACE) ? wifiContext.mac_addr_0 : wifiContext.mac_addr_1; -} - /**************************************************************************** * @brief * set the wifi provision @@ -960,17 +1042,6 @@ void wfx_clear_wifi_provision(void) memset(&wifi_provision, 0, sizeof(wifi_provision)); } -/**************************************************************************** - * @brief - * driver STA provisioned - * @return returns true if successful, - * false otherwise - *****************************************************************************/ -bool wfx_is_sta_provisioned(void) -{ - return (wifi_provision.ssid[0]) ? true : false; -} - /**************************************************************************** * @fn sl_status_t wfx_connect_to_ap(void) * @brief @@ -1147,10 +1218,10 @@ void wfx_dhcp_got_ipv4(uint32_t ip) */ uint8_t ip4_addr[4]; - ip4_addr[0] = (ip) &HEX_VALUE_FF; - ip4_addr[1] = (ip >> 8) & HEX_VALUE_FF; - ip4_addr[2] = (ip >> 16) & HEX_VALUE_FF; - ip4_addr[3] = (ip >> 24) & HEX_VALUE_FF; + ip4_addr[0] = (ip) &0xFF; + ip4_addr[1] = (ip >> 8) & 0xFF; + ip4_addr[2] = (ip >> 16) & 0xFF; + ip4_addr[3] = (ip >> 24) & 0xFF; ChipLogDetail(DeviceLayer, "DHCP IP=%d.%d.%d.%d", ip4_addr[0], ip4_addr[1], ip4_addr[2], ip4_addr[3]); sta_ip = ip; diff --git a/examples/platform/silabs/efr32/wf200/efr_spi.c b/src/platform/silabs/wifi/wf200/platform/efr_spi.c similarity index 99% rename from examples/platform/silabs/efr32/wf200/efr_spi.c rename to src/platform/silabs/wifi/wf200/platform/efr_spi.c index 3ef34c928e0363..6f80fc83d90984 100644 --- a/examples/platform/silabs/efr32/wf200/efr_spi.c +++ b/src/platform/silabs/wifi/wf200/platform/efr_spi.c @@ -14,14 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include -#include - -#include "AppConfig.h" #include "FreeRTOS.h" -#include "semphr.h" - #include "dmadrv.h" #include "em_bus.h" #include "em_cmu.h" @@ -29,6 +22,7 @@ #include "em_ldma.h" #include "em_usart.h" #include "gpiointerrupt.h" +#include "semphr.h" #include "sl_spidrv_exp_config.h" #include "sl_spidrv_instances.h" #include "sl_wfx.h" @@ -38,9 +32,10 @@ #include "sl_wfx_host_api.h" #include "sl_wfx_task.h" #include "spidrv.h" - -#include "spi_multiplex.h" -#include "wfx_host_events.h" +#include +#include +#include +#include #if defined(SL_CATALOG_POWER_MANAGER_PRESENT) #include "sl_power_manager.h" @@ -442,6 +437,8 @@ sl_status_t sl_wfx_host_post_lcd_spi_transfer(void) #endif // SL_SPICTRL_MUX return SL_STATUS_OK; } +#else +#error still not working #endif // SL_LCDCTRL_MUX #if SL_UARTCTRL_MUX diff --git a/examples/platform/silabs/efr32/sl_custom_board.h b/src/platform/silabs/wifi/wf200/platform/sl_custom_board.h similarity index 100% rename from examples/platform/silabs/efr32/sl_custom_board.h rename to src/platform/silabs/wifi/wf200/platform/sl_custom_board.h diff --git a/examples/platform/silabs/efr32/wf200/sl_wfx_board.h b/src/platform/silabs/wifi/wf200/platform/sl_wfx_board.h similarity index 100% rename from examples/platform/silabs/efr32/wf200/sl_wfx_board.h rename to src/platform/silabs/wifi/wf200/platform/sl_wfx_board.h diff --git a/examples/platform/silabs/efr32/wf200/sl_wfx_host.h b/src/platform/silabs/wifi/wf200/platform/sl_wfx_host.h similarity index 100% rename from examples/platform/silabs/efr32/wf200/sl_wfx_host.h rename to src/platform/silabs/wifi/wf200/platform/sl_wfx_host.h diff --git a/examples/platform/silabs/efr32/wf200/sl_wfx_task.c b/src/platform/silabs/wifi/wf200/platform/sl_wfx_task.c similarity index 100% rename from examples/platform/silabs/efr32/wf200/sl_wfx_task.c rename to src/platform/silabs/wifi/wf200/platform/sl_wfx_task.c diff --git a/examples/platform/silabs/efr32/wf200/sl_wfx_task.h b/src/platform/silabs/wifi/wf200/platform/sl_wfx_task.h similarity index 100% rename from examples/platform/silabs/efr32/wf200/sl_wfx_task.h rename to src/platform/silabs/wifi/wf200/platform/sl_wfx_task.h diff --git a/examples/platform/silabs/efr32/spi_multiplex.h b/src/platform/silabs/wifi/wf200/platform/spi_multiplex.h similarity index 100% rename from examples/platform/silabs/efr32/spi_multiplex.h rename to src/platform/silabs/wifi/wf200/platform/spi_multiplex.h diff --git a/examples/platform/silabs/efr32/wf200/wf200_init.c b/src/platform/silabs/wifi/wf200/platform/wf200_init.c similarity index 97% rename from examples/platform/silabs/efr32/wf200/wf200_init.c rename to src/platform/silabs/wifi/wf200/platform/wf200_init.c index 3631216e767a0c..40f1aaf08af6bb 100644 --- a/examples/platform/silabs/efr32/wf200/wf200_init.c +++ b/src/platform/silabs/wifi/wf200/platform/wf200_init.c @@ -40,7 +40,6 @@ #include "AppConfig.h" #include "sl_wfx_host.h" #include "sl_wfx_task.h" -#include "wfx_host_events.h" #include "sl_spidrv_instances.h" #include "spidrv.h" @@ -258,7 +257,7 @@ sl_status_t sl_wfx_host_set_wake_up_pin(uint8_t state) CORE_DECLARE_IRQ_STATE; CORE_ENTER_ATOMIC(); - if (state > PINOUT_CLEAR_STATUS) + if (state > 0) { #ifdef SLEEP_ENABLED #ifdef SL_WFX_USE_SDIO @@ -320,8 +319,7 @@ sl_status_t sl_wfx_host_reset_chip(void) *****************************************************************************/ sl_status_t sl_wfx_host_wait_for_wake_up(void) { - xSemaphoreTake(wfx_wakeup_sem, pdMS_TO_TICKS(TICKS_TO_WAIT_0)); - xSemaphoreTake(wfx_wakeup_sem, pdMS_TO_TICKS(TICKS_TO_WAIT_3)); + xSemaphoreTake(wfx_wakeup_sem, pdMS_TO_TICKS(3)); return SL_STATUS_OK; } @@ -388,7 +386,7 @@ sl_status_t sl_wfx_host_wait_for_confirmation(uint8_t confirmation_id, uint32_t for (uint32_t i = 0; i < timeout; i++) { /* Wait for an event posted by the function sl_wfx_host_post_event() */ - if (xQueueReceive(wfx_event_Q, &posted_event_id, TICKS_TO_WAIT_1) == pdTRUE) + if (xQueueReceive(wfx_event_Q, &posted_event_id, 1) == pdTRUE) { /* Once a message is received, check if it is the expected ID */ if (confirmation_id == posted_event_id) @@ -418,7 +416,7 @@ sl_status_t sl_wfx_host_lock(void) sl_status_t status = SL_STATUS_OK; - if (xSemaphoreTake(wfx_mutex, pdMS_TO_TICKS(TICKS_TO_WAIT_500)) != pdTRUE) + if (xSemaphoreTake(wfx_mutex, pdMS_TO_TICKS(500)) != pdTRUE) { SILABS_LOG("*ERR*Wi-Fi driver mutex timo"); status = SL_STATUS_TIMEOUT; diff --git a/src/platform/silabs/wifi/wf200/wf200.gni b/src/platform/silabs/wifi/wf200/wf200.gni new file mode 100644 index 00000000000000..437f9def5d47bb --- /dev/null +++ b/src/platform/silabs/wifi/wf200/wf200.gni @@ -0,0 +1,30 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/efr32_sdk.gni") +import("${silabs_sdk_build_root}/efr32_sdk.gni") + +wf200_plat_src = [ + "${chip_root}/src/platform/silabs/wifi/wf200/WifiInterface.cpp", + "${chip_root}/src/platform/silabs/wifi/wf200/platform/sl_wfx_task.c", + "${chip_root}/src/platform/silabs/wifi/wf200/platform/wf200_init.c", + "${chip_root}/src/platform/silabs/wifi/wf200/platform/efr_spi.c", + "${chip_root}/src/platform/silabs/wifi/wf200/platform/sl_wfx_board.h", + "${chip_root}/src/platform/silabs/wifi/wf200/platform/sl_wfx_host.h", + "${chip_root}/src/platform/silabs/wifi/wf200/platform/sl_wfx_task.h", + "${chip_root}/src/platform/silabs/wifi/wf200/platform/sl_custom_board.h", + "${chip_root}/src/platform/silabs/wifi/wf200/platform/spi_multiplex.h", + "${chip_root}/src/platform/silabs/wifi/wf200/platform/sl_wfx_board.h", +] diff --git a/src/platform/silabs/SiWx917/wifi/wfx_msgs.h b/src/platform/silabs/wifi/wfx_msgs.h similarity index 95% rename from src/platform/silabs/SiWx917/wifi/wfx_msgs.h rename to src/platform/silabs/wifi/wfx_msgs.h index b87a7c070716a2..af167a1f2c2f95 100644 --- a/src/platform/silabs/SiWx917/wifi/wfx_msgs.h +++ b/src/platform/silabs/wifi/wfx_msgs.h @@ -15,15 +15,17 @@ * limitations under the License. */ +// TODO: Delete this file after moving the wifi abstraction files to the src directory. +// Nothing should be added to this file anymore. +// File is kept due to the current header inclusion structure. + #ifndef _WFX_MSGS_H_ #define _WFX_MSGS_H_ -#include -/* - * Taken from sl_wfx firmware - so I can re-use. - * I need to do a better job than to use this stuff - * in the CPP files of Matter - */ +#ifdef WF200_WIFI +#include "sl_wfx_api.h" +#include "sl_wfx_constants.h" +#else typedef struct { uint8_t octet[6]; ///< Table to store a MAC address @@ -158,5 +160,6 @@ typedef struct __attribute__((__packed__)) sl_wfx_disconnect_ind_s /** Indication message body. */ sl_wfx_disconnect_ind_body_t body; } sl_wfx_disconnect_ind_t; +#endif #endif /* _WFX_MSGS_H_ */ diff --git a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp b/src/platform/silabs/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.cpp similarity index 51% rename from examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp rename to src/platform/silabs/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.cpp index 0a21244f342194..2266989b906f79 100644 --- a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp +++ b/src/platform/silabs/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2022 Project CHIP Authors + * Copyright (c) 2024 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. @@ -10,40 +10,16 @@ * * 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. */ -// SL MATTER WI-FI INTERFACE - -#include "WifiInterfaceAbstraction.h" -#include "silabs_utils.h" -#include "wfx_host_events.h" -#include -#include #include -#include #include -#include -#include -#include -#include -#include - -using namespace chip; -using namespace chip::DeviceLayer; +#include namespace { -constexpr uint8_t kWlanMinRetryIntervalsInSec = 1; -constexpr uint8_t kWlanMaxRetryIntervalsInSec = 60; -constexpr uint8_t kWlanRetryIntervalInSec = 5; -uint8_t retryInterval = kWlanMinRetryIntervalsInSec; -osTimerId_t sRetryTimer; - -// TODO: Remove this when the full abstraction is implemented -#ifdef RS911X_WIFI // Thread for the WLAN RSI osThreadId_t sWlanThread; constexpr uint32_t kWlanTaskSize = 2048; @@ -56,27 +32,9 @@ constexpr osThreadAttr_t kWlanTaskAttr = { .name = "wlan_rsi", .stack_mem = wlanStack, .stack_size = kWlanTaskSize, .priority = osPriorityAboveNormal7 }; -#endif // RS911X_WIFI - -/* - * Notifications to the upper-layer - * All done in the context of the RSI/WiFi task (rsi_if.c) - */ -void RetryConnectionTimerHandler(void * arg) -{ -#if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE - wfx_rsi_power_save(RSI_ACTIVE, HIGH_PERFORMANCE); -#endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE - if (wfx_connect_to_ap() != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); - } -} } // namespace -// TODO: Remove this when the full abstraction is implemented -#ifdef RS911X_WIFI /********************************************************************* * @fn sl_status_t wfx_wifi_start(void) * @brief @@ -88,8 +46,8 @@ void RetryConnectionTimerHandler(void * arg) ***********************************************************************/ sl_status_t wfx_wifi_start(void) { - VerifyOrReturnError(!(wfx_rsi.dev_state & WFX_RSI_ST_STARTED), SL_STATUS_OK); - wfx_rsi.dev_state |= WFX_RSI_ST_STARTED; + VerifyOrReturnError(!(wfx_rsi.dev_state.Has(WifiState::kStationStarted)), SL_STATUS_OK); + wfx_rsi.dev_state.Set(WifiState::kStationStarted); // Creating a Wi-Fi driver thread sWlanThread = osThreadNew(sl_matter_wifi_task, NULL, &kWlanTaskAttr); @@ -109,7 +67,7 @@ sl_status_t wfx_wifi_start(void) ***********************************************************************/ void wfx_enable_sta_mode(void) { - wfx_rsi.dev_state |= WFX_RSI_ST_STA_MODE; + wfx_rsi.dev_state.Set(WifiState::kStationMode); } /********************************************************************* @@ -121,9 +79,7 @@ void wfx_enable_sta_mode(void) ***********************************************************************/ bool wfx_is_sta_mode_enabled(void) { - bool mode; - mode = !!(wfx_rsi.dev_state & WFX_RSI_ST_STA_MODE); - return mode; + return wfx_rsi.dev_state.Has(WifiState::kStationMode); } /********************************************************************* @@ -157,7 +113,7 @@ void wfx_set_wifi_provision(wfx_wifi_provision_t * cfg) { VerifyOrReturn(cfg != nullptr); wfx_rsi.sec = *cfg; - wfx_rsi.dev_state |= WFX_RSI_ST_STA_PROVISIONED; + wfx_rsi.dev_state.Set(WifiState::kStationProvisioned); } /********************************************************************* @@ -171,7 +127,7 @@ void wfx_set_wifi_provision(wfx_wifi_provision_t * cfg) bool wfx_get_wifi_provision(wfx_wifi_provision_t * wifiConfig) { VerifyOrReturnError(wifiConfig != nullptr, false); - VerifyOrReturnError(wfx_rsi.dev_state & WFX_RSI_ST_STA_PROVISIONED, false); + VerifyOrReturnError(wfx_rsi.dev_state.Has(WifiState::kStationProvisioned), false); *wifiConfig = wfx_rsi.sec; return true; } @@ -186,7 +142,7 @@ bool wfx_get_wifi_provision(wfx_wifi_provision_t * wifiConfig) void wfx_clear_wifi_provision(void) { memset(&wfx_rsi.sec, 0, sizeof(wfx_rsi.sec)); - wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_PROVISIONED; + wfx_rsi.dev_state.Clear(WifiState::kStationProvisioned); ChipLogProgress(DeviceLayer, "Clear WiFi Provision"); } @@ -199,47 +155,15 @@ void wfx_clear_wifi_provision(void) ****************************************************************************/ sl_status_t wfx_connect_to_ap(void) { - VerifyOrReturnError(wfx_rsi.dev_state & WFX_RSI_ST_STA_PROVISIONED, SL_STATUS_INVALID_CONFIGURATION); + VerifyOrReturnError(wfx_rsi.dev_state.Has(WifiState::kStationProvisioned), SL_STATUS_INVALID_CONFIGURATION); VerifyOrReturnError(wfx_rsi.sec.ssid_length, SL_STATUS_INVALID_CREDENTIALS); VerifyOrReturnError(wfx_rsi.sec.ssid_length <= WFX_MAX_SSID_LENGTH, SL_STATUS_HAS_OVERFLOWED); ChipLogProgress(DeviceLayer, "connect to access point: %s", wfx_rsi.sec.ssid); - WfxEvent_t event; - event.eventType = WFX_EVT_STA_START_JOIN; - sl_matter_wifi_post_event(&event); - return SL_STATUS_OK; -} -#if SL_ICD_ENABLED -#if SLI_SI917 -/********************************************************************* - * @fn sl_status_t wfx_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t - sl_si91x_wifi_state) - * @brief - * Implements the power save in sleepy application - * @param[in] sl_si91x_ble_state : State to set for the BLE - sl_si91x_wifi_state : State to set for the WiFi - * @return SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - ***********************************************************************/ -sl_status_t wfx_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t sl_si91x_wifi_state) -{ - return (wfx_rsi_power_save(sl_si91x_ble_state, sl_si91x_wifi_state) ? SL_STATUS_FAIL : SL_STATUS_OK); -} -#else // For RS9116 -/********************************************************************* - * @fn sl_status_t wfx_power_save(void) - * @brief - * Implements the power save in sleepy application - * @param[in] None - * @return SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - ***********************************************************************/ -sl_status_t wfx_power_save(void) -{ - return (wfx_rsi_power_save() ? SL_STATUS_FAIL : SL_STATUS_OK); + WifiEvent event = WifiEvent::kStationStartJoin; + sl_matter_wifi_post_event(event); + return SL_STATUS_OK; } -#endif /* SLI_SI917 */ -#endif /* SL_ICD_ENABLED */ /********************************************************************* * @fn void wfx_setup_ip6_link_local(sl_wfx_interface_t whichif) @@ -266,8 +190,7 @@ void wfx_setup_ip6_link_local(sl_wfx_interface_t whichif) ***********************************************************************/ bool wfx_is_sta_connected(void) { - bool status = (wfx_rsi.dev_state & WFX_RSI_ST_STA_CONNECTED) > 0; - return status; + return wfx_rsi.dev_state.Has(WifiState::kStationConnected); } /********************************************************************* @@ -280,7 +203,7 @@ bool wfx_is_sta_connected(void) ***********************************************************************/ wifi_mode_t wfx_get_wifi_mode(void) { - if (wfx_rsi.dev_state & WFX_RSI_ST_DEV_READY) + if (wfx_rsi.dev_state.Has(WifiState::kStationInit)) return WIFI_MODE_STA; return WIFI_MODE_NULL; } @@ -297,7 +220,7 @@ sl_status_t sl_matter_wifi_disconnect(void) { sl_status_t status; status = sl_wifi_platform_disconnect(); - wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTED; + wfx_rsi.dev_state.Clear(WifiState::kStationConnected); return status; } #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 @@ -312,7 +235,7 @@ sl_status_t sl_matter_wifi_disconnect(void) bool wfx_have_ipv4_addr(sl_wfx_interface_t which_if) { VerifyOrReturnError(which_if == SL_WFX_STA_INTERFACE, false); - return ((wfx_rsi.dev_state & WFX_RSI_ST_STA_DHCP_DONE) > 0); + return wfx_rsi.dev_state.Has(WifiState::kStationDhcpDone); } #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ @@ -327,8 +250,8 @@ bool wfx_have_ipv4_addr(sl_wfx_interface_t which_if) bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) { VerifyOrReturnError(which_if == SL_WFX_STA_INTERFACE, false); - // TODO: WFX_RSI_ST_STA_CONNECTED does not guarantee SLAAC IPv6 LLA, maybe use a different FLAG - return ((wfx_rsi.dev_state & WFX_RSI_ST_STA_CONNECTED) > 0); + // TODO: WifiState::kStationConnected does not guarantee SLAAC IPv6 LLA, maybe use a different FLAG + return wfx_rsi.dev_state.Has(WifiState::kStationConnected); } /********************************************************************* @@ -341,7 +264,7 @@ bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) ***********************************************************************/ bool wfx_hw_ready(void) { - return (wfx_rsi.dev_state & WFX_RSI_ST_DEV_READY) ? true : false; + return wfx_rsi.dev_state.Has(WifiState::kStationInit); } /********************************************************************* @@ -404,9 +327,8 @@ bool wfx_start_scan(char * ssid, void (*callback)(wfx_wifi_scan_result_t *)) VerifyOrReturnError(wfx_rsi.scan_ssid != nullptr, false); chip::Platform::CopyString(wfx_rsi.scan_ssid, wfx_rsi.scan_ssid_length, ssid); - WfxEvent_t event; - event.eventType = WFX_EVT_SCAN; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kScan; + sl_matter_wifi_post_event(event); return true; } @@ -425,172 +347,3 @@ void wfx_cancel_scan(void) ChipLogError(DeviceLayer, "cannot cancel scan"); } #endif /* SL_WFX_CONFIG_SCAN */ -#endif // RS911X_WIFI - -/*********************************************************************************** - * @fn sl_matter_wifi_task_started(void) - * @brief - * Wifi device started notification - * @param[in]: None - * @return None - *************************************************************************************/ -void sl_matter_wifi_task_started(void) -{ - sl_wfx_startup_ind_t evt; - sl_wfx_mac_address_t mac; - - // Creating a timer which will be used to retry connection with AP - sRetryTimer = osTimerNew(RetryConnectionTimerHandler, osTimerOnce, NULL, NULL); - VerifyOrReturn(sRetryTimer != NULL); - - memset(&evt, 0, sizeof(evt)); - evt.header.id = SL_WFX_STARTUP_IND_ID; - evt.header.length = sizeof evt; - evt.body.status = 0; - wfx_get_wifi_mac_addr(SL_WFX_STA_INTERFACE, &mac); - memcpy(&evt.body.mac_addr[0], &mac.octet[0], MAC_ADDRESS_FIRST_OCTET); - - PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); -} - -/*********************************************************************************** - * @fn void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t *ap) - * @brief - * For now we are not notifying anything other than AP Mac - - * Other stuff such as DTIM etc. may be required for later - * @param[in] status: - * @param[in] ap: access point - * @return None - *************************************************************************************/ -void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t * ap) -{ - sl_wfx_connect_ind_t evt; - - VerifyOrReturn(status == SUCCESS_STATUS); - - memset(&evt, 0, sizeof(evt)); - evt.header.id = SL_WFX_CONNECT_IND_ID; - evt.header.length = sizeof evt; - -#ifdef RS911X_WIFI - evt.body.channel = wfx_rsi.ap_chan; -#endif - memcpy(&evt.body.mac[0], &ap->octet[0], MAC_ADDRESS_FIRST_OCTET); - - PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); -} - -/************************************************************************************** - * @fn void wfx_disconnected_notify(int32_t status) - * @brief - * notification of disconnection - * @param[in] status: - * @return None - ********************************************************************************************/ -void wfx_disconnected_notify(int32_t status) -{ - sl_wfx_disconnect_ind_t evt; - - memset(&evt, 0, sizeof(evt)); - evt.header.id = SL_WFX_DISCONNECT_IND_ID; - evt.header.length = sizeof evt; - evt.body.reason = status; - PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); -} - -/************************************************************************************** - * @fn void wfx_ipv6_notify(int got_ip) - * @brief - * notification of ipv6 - * @param[in] got_ip: - * @return None - ********************************************************************************************/ -void wfx_ipv6_notify(int got_ip) -{ - sl_wfx_generic_message_t eventData; - - memset(&eventData, 0, sizeof(eventData)); - eventData.header.id = got_ip ? IP_EVENT_GOT_IP6 : IP_EVENT_STA_LOST_IP; - eventData.header.length = sizeof(eventData.header); - PlatformMgrImpl().HandleWFXSystemEvent(IP_EVENT, &eventData); -} - -/************************************************************************************** - * @fn void wfx_ip_changed_notify(int got_ip) - * @brief - * notification of ip change - * @param[in] got_ip: - * @return None - ********************************************************************************************/ -void wfx_ip_changed_notify(int got_ip) -{ - sl_wfx_generic_message_t eventData; - - memset(&eventData, 0, sizeof(eventData)); - eventData.header.id = got_ip ? IP_EVENT_STA_GOT_IP : IP_EVENT_STA_LOST_IP; - eventData.header.length = sizeof(eventData.header); - PlatformMgrImpl().HandleWFXSystemEvent(IP_EVENT, &eventData); -} - -/************************************************************************************** - * @fn void wfx_retry_connection(uint16_t retryAttempt) - * @brief - * During commissioning, we retry to join the network MAX_JOIN_RETRIES_COUNT times. - * If DUT is disconnected from the AP or device is power cycled, then retry connection - * with AP continously after a certain time interval. - * @param[in] retryAttempt - * @return None - ********************************************************************************************/ -void wfx_retry_connection(uint16_t retryAttempt) -{ - // During commissioning, we retry to join the network MAX_JOIN_RETRIES_COUNT - if (/*BaseApplication::sAppDelegate.isCommissioningInProgress()*/ true) - { - if (retryAttempt < MAX_JOIN_RETRIES_COUNT) - { - ChipLogProgress(DeviceLayer, "wfx_retry_connection : Next attempt after %d Seconds", kWlanRetryIntervalInSec); - if (osTimerStart(sRetryTimer, pdMS_TO_TICKS(CONVERT_SEC_TO_MS(kWlanRetryIntervalInSec))) != osOK) - { - ChipLogProgress(DeviceLayer, "Failed to start retry timer"); - // Sending the join command if retry timer failed to start - if (wfx_connect_to_ap() != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); - } - return; - } - } - else - { - ChipLogProgress(DeviceLayer, "Connect failed after max %d tries", retryAttempt); - } - } - else - { - /* After disconnection or power cycle the DUT - * At the telescopic time interval device try to reconnect with AP, upto WLAN_MAX_RETRY_TIMER_MS intervals - * are telescopic. If interval exceed WLAN_MAX_RETRY_TIMER_MS then it will try to reconnect at - * WLAN_MAX_RETRY_TIMER_MS intervals. - */ - if (retryInterval > kWlanMaxRetryIntervalsInSec) - { - retryInterval = kWlanMaxRetryIntervalsInSec; - } - if (osTimerStart(sRetryTimer, pdMS_TO_TICKS(CONVERT_SEC_TO_MS(retryInterval))) != osOK) - { - ChipLogProgress(DeviceLayer, "Failed to start retry timer"); - // Sending the join command if retry timer failed to start - if (wfx_connect_to_ap() != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); - } - return; - } -#if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE - wfx_rsi_power_save(RSI_SLEEP_MODE_8, STANDBY_POWER_SAVE_WITH_RAM_RETENTION); -#endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE - ChipLogProgress(DeviceLayer, "wfx_retry_connection : Next attempt after %d Seconds", retryInterval); - retryInterval += retryInterval; - return; - } -} diff --git a/src/platform/silabs/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.h b/src/platform/silabs/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.h new file mode 100644 index 00000000000000..9073a02ef64b5b --- /dev/null +++ b/src/platform/silabs/wifi/wiseconnect-abstraction/WiseconnectInterfaceAbstraction.h @@ -0,0 +1,47 @@ +/* + * + * Copyright (c) 2024 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, + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include +#include +#include +#include +#include + +#define WFX_RSI_DHCP_POLL_INTERVAL (250) /* Poll interval in ms for DHCP */ +#define GET_IPV6_SUCCESS (1) + +extern WfxRsi_t wfx_rsi; + +void sl_matter_wifi_task(void * arg); + +#if CHIP_DEVICE_CONFIG_ENABLE_IPV4 +void wfx_ip_changed_notify(int got_ip); +#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ + +int32_t wfx_rsi_get_ap_info(wfx_wifi_scan_result_t * ap); +int32_t wfx_rsi_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); +int32_t wfx_rsi_reset_count(); +int32_t sl_wifi_platform_disconnect(); + +sl_status_t sl_matter_wifi_platform_init(void); + +/** + * @brief Posts an event to the Wi-Fi task + * + * @param[in] event Event to process. + */ +void sl_matter_wifi_post_event(WifiEvent event); diff --git a/src/protocols/secure_channel/PASESession.cpp b/src/protocols/secure_channel/PASESession.cpp index 4bf1aa55217c57..ceeaaa60531b73 100644 --- a/src/protocols/secure_channel/PASESession.cpp +++ b/src/protocols/secure_channel/PASESession.cpp @@ -54,9 +54,7 @@ using namespace Crypto; using namespace Messaging; using namespace Protocols::SecureChannel; -const char kSpake2pContext[] = "CHIP PAKE V1 Commissioning"; -const char kSpake2pI2RSessionInfo[] = "Commissioning I2R Key"; -const char kSpake2pR2ISessionInfo[] = "Commissioning R2I Key"; +const char kSpake2pContext[] = "CHIP PAKE V1 Commissioning"; // Amounts of time to allow for server-side processing of messages. // diff --git a/src/protocols/secure_channel/PASESession.h b/src/protocols/secure_channel/PASESession.h index 92b4ee3d8b991c..a24539eaf508e7 100644 --- a/src/protocols/secure_channel/PASESession.h +++ b/src/protocols/secure_channel/PASESession.h @@ -43,7 +43,9 @@ #include namespace chip { - +namespace Testing { +class TestPASESession; +} extern const char kSpake2pI2RSessionInfo[]; extern const char kSpake2pR2ISessionInfo[]; @@ -174,6 +176,7 @@ class DLL_EXPORT PASESession : public Messaging::UnsolicitedMessageHandler, kInvalidKeyConfirmation = 0x00, kUnexpected = 0xff, }; + friend class Testing::TestPASESession; CHIP_ERROR Init(SessionManager & sessionManager, uint32_t setupCode, SessionEstablishmentDelegate * delegate); diff --git a/src/protocols/secure_channel/tests/FuzzPASE_PW.cpp b/src/protocols/secure_channel/tests/FuzzPASE_PW.cpp index d3dc5998112f2a..0ce3d2d1817857 100644 --- a/src/protocols/secure_channel/tests/FuzzPASE_PW.cpp +++ b/src/protocols/secure_channel/tests/FuzzPASE_PW.cpp @@ -15,16 +15,17 @@ #include #include #include +#include -namespace { +namespace chip { +namespace Testing { -using namespace chip; using namespace std; -using namespace chip::Crypto; +using namespace Crypto; using namespace fuzztest; -using namespace chip::Transport; -using namespace chip::Messaging; +using namespace Transport; +using namespace Messaging; using namespace System::Clock::Literals; // TODO: #35369 Refactor the classes below to Fixtures once Errors related to FuzzTest Fixtures are resolved @@ -113,6 +114,27 @@ class TestPASESession : public FuzzLoopbackMessagingContext TestSecurePairingDelegate & delegateCommissioner, TestSecurePairingDelegate & delegateAccessory, const Spake2pVerifier & verifier, uint32_t pbkdf2IterCount, const ByteSpan & salt, uint32_t SetUpPINCode); + + void FuzzHandlePBKDFParamRequest(vector fuzzPBKDFLocalRandomData, uint32_t fuzzInitiatorSessionId, + bool fuzzHavePBKDFParameters); + + void FuzzHandlePBKDFParamResponse(vector fuzzPBKDFLocalRandomDataInitiator, + vector fuzzPBKDFLocalRandomDataResponder, uint32_t fuzzResponderSessionId, + const vector & fuzzedSalt, uint32_t fuzzedPBKDF2Iter, bool fuzzHavePBKDFParameters); + + void FuzzHandlePake1(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, uint32_t fuzzedPBKDF2Iter, + const vector & pA); + + void FuzzHandlePake2(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, uint32_t fuzzedPBKDF2Iter, + const vector & pB, const vector & cB); + + void FuzzHandlePake3(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, uint32_t fuzzedPBKDF2Iter, + const vector & cA); + + CHIP_ERROR CallAllocateSecureSession(SessionManager & sessionManager, PASESession & pairing) + { + return pairing.AllocateSecureSession(sessionManager); + } }; class TemporarySessionManager @@ -217,8 +239,11 @@ void PASESession_Bounded(const uint32_t fuzzedSetupPasscode, const vector>().WithMinSize(kSpake2p_Min_PBKDF_Salt_Length).WithMaxSize(kSpake2p_Max_PBKDF_Salt_Length), + // fuzzedPBKDF2Iter InRange(kSpake2p_Min_PBKDF_Iterations, kSpake2p_Max_PBKDF_Iterations)); /* -------------------------------------------------------------------------------------------*/ @@ -245,7 +270,13 @@ void PASESession_Unbounded(const uint32_t fuzzedSetupPasscode, const vector(), Arbitrary>(), Arbitrary()); + .WithDomains( + // fuzzedSetupPasscode + Arbitrary(), + // fuzzedSalt + Arbitrary>(), + // fuzzedPBKDF2Iter + Arbitrary()); /* -------------------------------------------------------------------------------------------*/ // In This FuzzTest, the Spake2pVerifier is fuzzed. @@ -271,9 +302,17 @@ void FuzzSpake2pVerifier(const vector & aW0, const vector & aL fuzzedSpake2pVerifier, fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode); } FUZZ_TEST(FuzzPASE_PW, FuzzSpake2pVerifier) - .WithDomains(Arbitrary>().WithMaxSize(kP256_FE_Length), - Arbitrary>().WithMaxSize(kP256_Point_Length), Arbitrary>(), - Arbitrary(), Arbitrary()); + .WithDomains( + // aW0 + Arbitrary>().WithMaxSize(kP256_FE_Length), + // aL + Arbitrary>().WithMaxSize(kP256_Point_Length), + // aSalt + Arbitrary>(), + // fuzzedPBKDF2Iter + Arbitrary(), + // fuzzedSetupPasscode + Arbitrary()); /* -------------------------------------------------------------------------------------------*/ // In This FuzzTest, Fuzzed Serialized Verifier is deserialized and Serialized Again, comparing the original with RoundTrip result. @@ -301,4 +340,598 @@ void Spake2pVerifier_Serialize_RoundTrip(const vector & FuzzedSerialize FUZZ_TEST(FuzzPASE_PW, Spake2pVerifier_Serialize_RoundTrip) .WithDomains(Arbitrary>().WithSize(kSpake2p_VerifierSerialized_Length)); -} // namespace +/* -------------------------------------------------------------------------------------------*/ +// In This Test a Fuzzed PBKDFParamRequest Message is fuzzed, which is then injected into a PASE Session to test the behaviour of +// PASESession::HandlePBKDFParamRequest(); which will be called by the Accessory/Commissionee. +void TestPASESession::FuzzHandlePBKDFParamRequest(vector fuzzPBKDFLocalRandomData, uint32_t fuzzInitiatorSessionId, + bool fuzzHavePBKDFParameters) +{ + TemporarySessionManager sessionManager(*this); + + // Commissioner: The Sender of PBKDFParamRequest + PASESession pairingCommissioner; + // Accessory: The Receiver of PBKDFParamRequest + PASESession pairingAccessory; + + /*************************** Preparing Commissioner ***************************/ + + CallAllocateSecureSession(sessionManager, pairingCommissioner); + + ReliableMessageProtocolConfig LocalMRPConfig(System::Clock::Milliseconds32(100), System::Clock::Milliseconds32(200), + System::Clock::Milliseconds16(4000)); + + // After the Accessory Handles PBKDFParamRequest, it will send a PBKDFParamResponse back to pairingCommissioner, which should be + // expecting it. + pairingCommissioner.mNextExpectedMsg.SetValue(Protocols::SecureChannel::MsgType::PBKDFParamResponse); + + /**************************Constructing PBKDFParamRequest Message***************************************** */ + + const size_t max_msg_len = TLV::EstimateStructOverhead(fuzzPBKDFLocalRandomData.size(), // initiatorRandom, + sizeof(fuzzInitiatorSessionId), // initiatorSessionId + sizeof(PasscodeId), // passcodeId, + sizeof(bool), // hasPBKDFParameters + SessionParameters::kEstimatedTLVSize // Session Parameters + ); + + System::PacketBufferHandle req = System::PacketBufferHandle::New(max_msg_len); + EXPECT_FALSE(req.IsNull()); + + System::PacketBufferTLVWriter tlvWriter; + tlvWriter.Init(std::move(req)); + + TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified; + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType)); + EXPECT_EQ(CHIP_NO_ERROR, + tlvWriter.PutBytes(TLV::ContextTag(1), fuzzPBKDFLocalRandomData.data(), fuzzPBKDFLocalRandomData.size())); + + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Put(TLV::ContextTag(2), fuzzInitiatorSessionId)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Put(TLV::ContextTag(3), kDefaultCommissioningPasscodeId)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.PutBoolean(TLV::ContextTag(4), fuzzHavePBKDFParameters)); + + EXPECT_EQ(CHIP_NO_ERROR, PASESession::EncodeSessionParameters(TLV::ContextTag(5), LocalMRPConfig, tlvWriter)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.EndContainer(outerContainerType)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Finalize(&req)); + + /*************************** Preparing Accessory for Receiving PBKDFParamRequest Message ***************************/ + + PASETestLoopbackTransportDelegate delegate; + auto & loopback = GetLoopback(); + loopback.SetLoopbackTransportDelegate(&delegate); + loopback.mSentMessageCount = 0; + + TestSecurePairingDelegate delegateAccessory; + + PayloadHeader payloadHeaderAccessory; + + // One Limitation of using this is that contextAccessory will automatically be an Initiator, while in real-life it should be a + // responder. + ExchangeContext * contextAccessory = NewUnauthenticatedExchangeToBob(&pairingAccessory); + + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::PBKDFParamRequest, + &pairingAccessory), + CHIP_NO_ERROR); + + // Adding PASESession::Init in order to AllocateSecureSession and have a localsessionID generated for pairingAccessory + pairingAccessory.Init(sessionManager, 0, &delegateAccessory); + + // This was done to have an exchange context + pairingAccessory.mExchangeCtxt.Emplace(*contextAccessory); + + pairingAccessory.mLocalMRPConfig = MakeOptional(LocalMRPConfig); + + payloadHeaderAccessory.SetMessageType(Protocols::SecureChannel::MsgType::PBKDFParamRequest); + pairingAccessory.mNextExpectedMsg.SetValue(Protocols::SecureChannel::MsgType::PBKDFParamRequest); + + pairingAccessory.OnMessageReceived(&pairingAccessory.mExchangeCtxt.Value().Get(), payloadHeaderAccessory, std::move(req)); + + DrainAndServiceIO(); +} + +void HandlePBKDFParamRequest(vector fuzzPBKDFLocalRandomData, uint32_t fuzzInitiatorSessionId, + bool fuzzHavePBKDFParameters) +{ + // TODO: #35369 Move this to a Fixture once Errors related to FuzzTest Fixtures are resolved + TestPASESession PASELoopBack; + PASELoopBack.FuzzHandlePBKDFParamRequest(fuzzPBKDFLocalRandomData, fuzzInitiatorSessionId, fuzzHavePBKDFParameters); +} + +FUZZ_TEST(FuzzPASE_PW, HandlePBKDFParamRequest) + .WithDomains( + // PBKDFLocalRandomData + Arbitrary>(), + // InitiatorSessionId + Arbitrary(), + // mHavePBKDFParameters + Arbitrary()); + +/* -------------------------------------------------------------------------------------------*/ +// In This Test a Fuzzed PBKDFParamResponse Message is fuzzed, which is then injected into a PASE Session to test the behaviour of +// PASESession::HandlePBKDFParamResponse(); which will be called by the Commissioner. +void TestPASESession::FuzzHandlePBKDFParamResponse(vector fuzzPBKDFLocalRandomDataInitiator, + vector fuzzPBKDFLocalRandomDataResponder, + uint32_t fuzzResponderSessionId, const vector & fuzzedSalt, + uint32_t fuzzedPBKDF2Iter, bool fuzzHavePBKDFParameters) +{ + TemporarySessionManager sessionManager(*this); + + // Commissioner: The Receiver of PBKDFParamResponse + PASESession pairingCommissioner; + // Accessory: The Sender of PBKDFParamResponse + PASESession pairingAccessory; + + /*************************** Preparing Commissioner ***************************/ + + CallAllocateSecureSession(sessionManager, pairingCommissioner); + + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); + + // This was done to have an exchange context + pairingCommissioner.mExchangeCtxt.Emplace(*contextCommissioner); + + ReliableMessageProtocolConfig LocalMRPConfig(System::Clock::Milliseconds32(100), System::Clock::Milliseconds32(200), + System::Clock::Milliseconds16(4000)); + + pairingCommissioner.mLocalMRPConfig = MakeOptional(LocalMRPConfig); + + // preparing CommissioningHash needed for SetupSpake2p() + pairingCommissioner.mCommissioningHash.Begin(); + pairingCommissioner.mCommissioningHash.AddData(ByteSpan(fuzzedSalt.data(), fuzzedSalt.size())); + + // The Commissioner will check if the PBKDFLocalRandomData it received in TLV is same as the stored mPBKDFLocalRandomData. So we + // inject it here to be able to pass that check + memcpy(&pairingCommissioner.mPBKDFLocalRandomData[0], fuzzPBKDFLocalRandomDataInitiator.data(), + fuzzPBKDFLocalRandomDataInitiator.size()); + + // In order to cover the Code path where the Commissioner has PBKDF Parameters before Starting PASE, as such, the Accessory will + // not send the PBKDF Parameters in the Response message + bool initiatorHasPBKDFParams = fuzzHavePBKDFParameters; + pairingCommissioner.mHavePBKDFParameters = fuzzHavePBKDFParameters; + + /**************************Constructing PBKDFParamResponse Message***************************************** */ + + const size_t max_msg_len = + TLV::EstimateStructOverhead(fuzzPBKDFLocalRandomDataInitiator.size(), // initiatorRandom + fuzzPBKDFLocalRandomDataResponder.size(), // responderRandom + sizeof(fuzzResponderSessionId), // responderSessionId + TLV::EstimateStructOverhead(sizeof(fuzzedPBKDF2Iter), fuzzedSalt.size()), // pbkdf_parameters + SessionParameters::kEstimatedTLVSize // Session Parameters + ); + + System::PacketBufferHandle resp = System::PacketBufferHandle::New(max_msg_len); + EXPECT_FALSE(resp.IsNull()); + + System::PacketBufferTLVWriter tlvWriter; + tlvWriter.Init(std::move(resp)); + + TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified; + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType)); + EXPECT_EQ( + CHIP_NO_ERROR, + tlvWriter.PutBytes(TLV::ContextTag(1), fuzzPBKDFLocalRandomDataInitiator.data(), fuzzPBKDFLocalRandomDataInitiator.size())); + EXPECT_EQ( + CHIP_NO_ERROR, + tlvWriter.PutBytes(TLV::ContextTag(2), fuzzPBKDFLocalRandomDataResponder.data(), fuzzPBKDFLocalRandomDataResponder.size())); + + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Put(TLV::ContextTag(3), fuzzResponderSessionId)); + + if (!initiatorHasPBKDFParams) + { + TLV::TLVType pbkdfParamContainer; + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.StartContainer(TLV::ContextTag(4), TLV::kTLVType_Structure, pbkdfParamContainer)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Put(TLV::ContextTag(1), fuzzedPBKDF2Iter)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.PutBytes(TLV::ContextTag(2), fuzzedSalt.data(), fuzzedSalt.size())); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.EndContainer(pbkdfParamContainer)); + } + + EXPECT_EQ(CHIP_NO_ERROR, PASESession::EncodeSessionParameters(TLV::ContextTag(5), LocalMRPConfig, tlvWriter)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.EndContainer(outerContainerType)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Finalize(&resp)); + + /*************************** Preparing Commissioner for Receiving PBKDFParamResponse Message ***************************/ + + PayloadHeader payloadHeaderCommissioner; + + payloadHeaderCommissioner.SetMessageType(Protocols::SecureChannel::MsgType::PBKDFParamResponse); + pairingCommissioner.mNextExpectedMsg.SetValue(Protocols::SecureChannel::MsgType::PBKDFParamResponse); + + pairingCommissioner.OnMessageReceived(&pairingCommissioner.mExchangeCtxt.Value().Get(), payloadHeaderCommissioner, + std::move(resp)); + + DrainAndServiceIO(); +} + +void HandlePBKDFParamResponse(vector fuzzPBKDFLocalRandomDataInitiator, vector fuzzPBKDFLocalRandomDataResponder, + uint32_t fuzzResponderSessionId, const vector & fuzzedSalt, uint32_t fuzzedPBKDF2Iter, + bool fuzzHavePBKDFParameters) +{ + // TODO: #35369 Move this to a Fixture once Errors related to FuzzTest Fixtures are resolved + TestPASESession PASELoopBack; + PASELoopBack.FuzzHandlePBKDFParamResponse(fuzzPBKDFLocalRandomDataInitiator, fuzzPBKDFLocalRandomDataResponder, + fuzzResponderSessionId, fuzzedSalt, fuzzedPBKDF2Iter, fuzzHavePBKDFParameters); +} + +FUZZ_TEST(FuzzPASE_PW, HandlePBKDFParamResponse) + .WithDomains( + // fuzzPBKDFLocalRandomDataInitiator + Arbitrary>().WithMaxSize(32), + // fuzzPBKDFLocalRandomDataResponder + Arbitrary>(), + // fuzzResponderSessionId + Arbitrary(), + // fuzzedSalt + Arbitrary>(), + // fuzzedPBKDF2Iter + Arbitrary(), + // mHavePBKDFParameters + Arbitrary()); + +/*------------------------------------------------------------------------------------------------------------------------------------*/ +// In This Test we start by constructing a Fuzzed Pake1 Message, by fuzzing the payload pA. the Fuzzed Pake1 Message is then +// injected into a PASE Session to test the behaviour of PASESession::HandleMsg1_and_SendMsg2(); which will be called by the +// Accessory/Commissionee. +void TestPASESession::FuzzHandlePake1(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, + uint32_t fuzzedPBKDF2Iter, const vector & fuzzed_pA) +{ + + ByteSpan fuzzedSaltSpan(fuzzedSalt.data(), fuzzedSalt.size()); + + TemporarySessionManager sessionManager(*this); + + // Commissioner: The Sender of PAKE1 + PASESession pairingCommissioner; + // Accessory: The Receiver of PAKE1 + PASESession pairingAccessory; + + /*************************** Preparing Commissioner ***************************/ + + // preparing CommissioningHash needed for SetupSpake2p() + pairingCommissioner.mCommissioningHash.Begin(); + pairingCommissioner.mCommissioningHash.AddData(fuzzedSaltSpan); + EXPECT_EQ(CHIP_NO_ERROR, pairingCommissioner.SetupSpake2p()); + + uint8_t serializedWS[kSpake2p_WS_Length * 2] = { 0 }; + + // Compute serializedWS, to be used in BeginProver() + + Spake2pVerifier::ComputeWS(fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode, serializedWS, sizeof(serializedWS)); + + EXPECT_EQ(CHIP_NO_ERROR, + pairingCommissioner.mSpake2p.BeginProver(nullptr, 0, nullptr, 0, &serializedWS[0], kSpake2p_WS_Length, + &serializedWS[kSpake2p_WS_Length], kSpake2p_WS_Length)); + + /*********************** Constructing Fuzzed Pake1 Message, to later inject it into PASE Session *********************/ + + constexpr uint8_t kPake1_pA = 1; + + const size_t max_msg_len = TLV::EstimateStructOverhead(fuzzed_pA.size()); + System::PacketBufferHandle msg = System::PacketBufferHandle::New(max_msg_len); + EXPECT_FALSE(msg.IsNull()); + + System::PacketBufferTLVWriter tlvWriter; + tlvWriter.Init(std::move(msg)); + + TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified; + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Put(TLV::ContextTag(kPake1_pA), ByteSpan(fuzzed_pA.data(), fuzzed_pA.size()))); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.EndContainer(outerContainerType)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Finalize(&msg)); + + /*************************** Preparing Accessory for Receiving Pake1 Message ***************************/ + + // One Limitation of using this is that contextAccessory will automatically be an Initiator, while in real-life it should be a + // responder. + ExchangeContext * contextAccessory = NewUnauthenticatedExchangeToBob(&pairingAccessory); + + pairingAccessory.mExchangeCtxt.Emplace(*contextAccessory); + + pairingAccessory.mLocalMRPConfig = MakeOptional(ReliableMessageProtocolConfig( + System::Clock::Milliseconds32(100), System::Clock::Milliseconds32(200), System::Clock::Milliseconds16(4000))); + + // preparing CommissioningHash needed for SetupSpake2p() + pairingAccessory.mCommissioningHash.Begin(); + pairingAccessory.mCommissioningHash.AddData(fuzzedSaltSpan); + EXPECT_EQ(CHIP_NO_ERROR, pairingAccessory.SetupSpake2p()); + + // Compute mPASEVerifier (in order for mSpake2p.BeginVerifier() to use it, once it is called by the pairingAccessory through + // HandleMsg1_and_SendMsg2) + pairingAccessory.mPASEVerifier.Generate(fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode); + + /************************Injecting Fuzzed Pake1 Message into PaseSession::OnMessageReceived*************************/ + + PayloadHeader payloadHeaderAccessory; + + // Below two lines are needed to trigger PASESession::OnMessageReceived to call HandleMsg1_and_SendMsg2 + payloadHeaderAccessory.SetMessageType(Protocols::SecureChannel::MsgType::PASE_Pake1); + pairingAccessory.mNextExpectedMsg.SetValue(Protocols::SecureChannel::MsgType::PASE_Pake1); + + pairingAccessory.OnMessageReceived(&pairingAccessory.mExchangeCtxt.Value().Get(), payloadHeaderAccessory, std::move(msg)); + + DrainAndServiceIO(); +} + +void HandlePake1(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, uint32_t fuzzedPBKDF2Iter, + const vector & fuzzed_pA) +{ + // TODO: #35369 Move this to a Fixture once Errors related to FuzzTest Fixtures are resolved + TestPASESession PASELoopBack; + + // pA is an uncompressed public key format, it should start with 0x04. + // Appending 0x04 to the fuzzed input to increase the likelihood of having a valid point format during fuzzing. + vector pA_appended = { 0x04 }; + pA_appended.insert(pA_appended.end(), fuzzed_pA.begin(), fuzzed_pA.end()); + PASELoopBack.FuzzHandlePake1(fuzzedSetupPasscode, fuzzedSalt, fuzzedPBKDF2Iter, pA_appended); +} + +// In This FuzzTest, we will construct a PAKE1 Message with a fuzzed TLV length, and send it through a PASESession +FUZZ_TEST(FuzzPASE_PW, HandlePake1) + .WithDomains( + // Setup Code Range (covers the full 27-bit range, plus 16 additional values) + InRange(00000000, 0x800000F), + // Salt length range (extending min and max by 4 bytes) + Arbitrary>() + .WithMinSize(kSpake2p_Min_PBKDF_Salt_Length - 4) + .WithMaxSize(kSpake2p_Max_PBKDF_Salt_Length + 4), + // PBKDF2Iterations count range (extending min and max by 10 iterations) + InRange(kSpake2p_Min_PBKDF_Iterations - 10, kSpake2p_Max_PBKDF_Iterations + 10), + // Fuzzed pA (Original size = kMAX_Point_Length) + Arbitrary>()); + +/*------------------------------------------------------------------------------------------------------------------------------------*/ +// In this FuzzTest we start by constructing a Fuzzed PAKE2 Message, by fuzzing the payloads pB and cB. the fuzzed message is then +// injected into a PASE Session to test the behavior of PASESession::HandleMsg2_and_SendMsg3(), which will be called by Commissioner +void TestPASESession::FuzzHandlePake2(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, + uint32_t fuzzedPBKDF2Iter, const vector & fuzzed_pB, + const vector & fuzzed_cB) +{ + + ByteSpan fuzzedSaltSpan(fuzzedSalt.data(), fuzzedSalt.size()); + + TemporarySessionManager sessionManager(*this); + + // Commissioner: The Receiver of PAKE2 + PASESession pairingCommissioner; + // Accessory: The Sender of PAKE2 + PASESession pairingAccessory; + + /*************************** Preparing Commissioner ***************************/ + + CallAllocateSecureSession(sessionManager, pairingCommissioner); + + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); + + // This was done to have an exchange context + pairingCommissioner.mExchangeCtxt.Emplace(*contextCommissioner); + + pairingCommissioner.mLocalMRPConfig = MakeOptional(ReliableMessageProtocolConfig( + System::Clock::Milliseconds32(100), System::Clock::Milliseconds32(200), System::Clock::Milliseconds16(4000))); + + // preparing CommissioningHash needed for SetupSpake2p() + pairingCommissioner.mCommissioningHash.Begin(); + pairingCommissioner.mCommissioningHash.AddData(fuzzedSaltSpan); + EXPECT_EQ(CHIP_NO_ERROR, pairingCommissioner.SetupSpake2p()); + + uint8_t serializedWS[kSpake2p_WS_Length * 2] = { 0 }; + + // Compute serializedWS, to be used in BeginProver() + Spake2pVerifier::ComputeWS(fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode, serializedWS, sizeof(serializedWS)); + + EXPECT_EQ(CHIP_NO_ERROR, + pairingCommissioner.mSpake2p.BeginProver(nullptr, 0, nullptr, 0, &serializedWS[0], kSpake2p_WS_Length, + &serializedWS[kSpake2p_WS_Length], kSpake2p_WS_Length)); + + // The Commissioner should have alread called ComputeRoundOne As part of the PASE Session Exchange (and consequently have + // mSpake2p.state = CHIP_SPAKE2P_STATE::R1), the computed values are not used in the test. + uint8_t X[kMAX_Point_Length]; + size_t X_len = sizeof(X); + pairingCommissioner.mSpake2p.ComputeRoundOne(nullptr, 0, X, &X_len); + + /*************************** Preparing Accessory ***************************/ + + // Init mCommissioningHash; needed for SetupSpake2p() + pairingAccessory.mCommissioningHash.Begin(); + pairingAccessory.mCommissioningHash.AddData(fuzzedSaltSpan); + EXPECT_EQ(CHIP_NO_ERROR, pairingAccessory.SetupSpake2p()); + + // Below Steps take place in HandleMsg1 + // Compute mPASEVerifier to be able to pass it to BeginVerifier() + pairingAccessory.mPASEVerifier.Generate(fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode); + + pairingAccessory.mSpake2p.BeginVerifier(nullptr, 0, nullptr, 0, pairingAccessory.mPASEVerifier.mW0, kP256_FE_Length, + pairingAccessory.mPASEVerifier.mL, kP256_Point_Length); + + /*********************** Constructing Fuzzed PAKE2 Message, to later inject it into PASE Session *********************/ + + constexpr uint8_t kPake2_pB = 1; + constexpr uint8_t kPake2_cB = 2; + + const size_t max_msg_len = TLV::EstimateStructOverhead(fuzzed_pB.size(), fuzzed_cB.size()); + System::PacketBufferHandle msg2 = System::PacketBufferHandle::New(max_msg_len); + EXPECT_FALSE(msg2.IsNull()); + + System::PacketBufferTLVWriter tlvWriter; + tlvWriter.Init(std::move(msg2)); + + TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified; + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Put(TLV::ContextTag(kPake2_pB), ByteSpan(fuzzed_pB.data(), fuzzed_pB.size()))); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Put(TLV::ContextTag(kPake2_cB), ByteSpan(fuzzed_cB.data(), fuzzed_cB.size()))); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.EndContainer(outerContainerType)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Finalize(&msg2)); + + // After PAKE2 is sent, the pairingAccessory will expect a a Pake3 Message + pairingAccessory.mNextExpectedMsg.SetValue(Protocols::SecureChannel::MsgType::PASE_Pake3); + + /************************Injecting Fuzzed PAKE2 Message into PaseSession::OnMessageReceived*************************/ + + PayloadHeader payloadHeaderCommissioner; + + // Below two lines are needed to trigger PASESession::OnMessageReceived to call HandleMsg2_and_SendMsg3 + payloadHeaderCommissioner.SetMessageType(Protocols::SecureChannel::MsgType::PASE_Pake2); + pairingCommissioner.mNextExpectedMsg.SetValue(Protocols::SecureChannel::MsgType::PASE_Pake2); + + pairingCommissioner.OnMessageReceived(&pairingCommissioner.mExchangeCtxt.Value().Get(), payloadHeaderCommissioner, + std::move(msg2)); + + DrainAndServiceIO(); +} + +void HandlePake2(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, uint32_t fuzzedPBKDF2Iter, + const vector & pB, const vector & cB) +{ + TestPASESession PASELoopBack; + // pB is an uncompressed public key format, it should start with 0x04. + // Appending 0x04 to the fuzzed input to increase the likelihood of having a valid point format during fuzzing. + vector pB_appended = { 0x04 }; + pB_appended.insert(pB_appended.end(), pB.begin(), pB.end()); + + PASELoopBack.FuzzHandlePake2(fuzzedSetupPasscode, fuzzedSalt, fuzzedPBKDF2Iter, pB_appended, cB); +} + +FUZZ_TEST(FuzzPASE_PW, HandlePake2) + .WithDomains( + // Setup Code Range (covers the full 27-bit range, plus 16 additional values) + InRange(00000000, 0x800000F), + // Salt length range (extending min and max by 4 bytes) + Arbitrary>() + .WithMinSize(kSpake2p_Min_PBKDF_Salt_Length - 4) + .WithMaxSize(kSpake2p_Max_PBKDF_Salt_Length + 4), + // PBKDF2Iterations count range (extending min and max by 10 iterations) + InRange(kSpake2p_Min_PBKDF_Iterations - 10, kSpake2p_Max_PBKDF_Iterations + 10), + // Fuzzed pB (Original size = kMAX_Point_Length), + Arbitrary>(), + // Fuzzed cB (Original size = kMAX_Hash_Length) + Arbitrary>()); + +/*------------------------------------------------------------------------------------------------------------------------------------*/ +// In This Test we start by constructing a Fuzzed Pake3 Message, by fuzzing the payload cA. The Fuzzed message is then injected into +// a PASE Session to test the behavior of PASESession::HandleMsg3(); which will be called by the Accessory/Commissionee. +void TestPASESession::FuzzHandlePake3(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, + uint32_t fuzzedPBKDF2Iter, const vector & fuzzed_cA) +{ + + ByteSpan fuzzedSaltSpan(fuzzedSalt.data(), fuzzedSalt.size()); + + TemporarySessionManager sessionManager(*this); + + // Commissioner: The Sender of PAKE3 + PASESession pairingCommissioner; + // Accessory: The Receiver of PAKE3 + PASESession pairingAccessory; + + /*************************** Preparing Commissioner ***************************/ + + // preparing CommissioningHash needed for SetupSpake2p() + pairingCommissioner.mCommissioningHash.Begin(); + pairingCommissioner.mCommissioningHash.AddData(fuzzedSaltSpan); + EXPECT_EQ(CHIP_NO_ERROR, pairingCommissioner.SetupSpake2p()); + + uint8_t serializedWS[kSpake2p_WS_Length * 2] = { 0 }; + + // Compute serializedWS, to be used in BeginProver() + + Spake2pVerifier::ComputeWS(fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode, serializedWS, sizeof(serializedWS)); + + EXPECT_EQ(CHIP_NO_ERROR, + pairingCommissioner.mSpake2p.BeginProver(nullptr, 0, nullptr, 0, &serializedWS[0], kSpake2p_WS_Length, + &serializedWS[kSpake2p_WS_Length], kSpake2p_WS_Length)); + + // The Commissioner should have already called ComputeRoundOne As part of the Exchange (and consequently have state = + // CHIP_SPAKE2P_STATE::R1), the computed values are not used. + uint8_t X[kMAX_Point_Length]; + size_t X_len = sizeof(X); + pairingCommissioner.mSpake2p.ComputeRoundOne(nullptr, 0, X, &X_len); + + /*************************** Preparing Accessory ***************************/ + + CallAllocateSecureSession(sessionManager, pairingAccessory); + + // One Limitation of using this is that contextAccessory will automatically be an Initiator, while in real-life it should be a + // responder. + ExchangeContext * contextAccessory = NewUnauthenticatedExchangeToBob(&pairingAccessory); + + // This was done to have an exchange context + pairingAccessory.mExchangeCtxt.Emplace(*contextAccessory); + + pairingAccessory.mLocalMRPConfig = MakeOptional(ReliableMessageProtocolConfig( + System::Clock::Milliseconds32(100), System::Clock::Milliseconds32(200), System::Clock::Milliseconds16(4000))); + + // preparing CommissioningHash needed for SetupSpake2p() + pairingAccessory.mCommissioningHash.Begin(); + pairingAccessory.mCommissioningHash.AddData(fuzzedSaltSpan); + EXPECT_EQ(CHIP_NO_ERROR, pairingAccessory.SetupSpake2p()); + + // Below Steps take place in HandleMsg1 + // compute mPASEVerifier to be able to pass it to BeginVerifier() + pairingAccessory.mPASEVerifier.Generate(fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode); + + pairingAccessory.mSpake2p.BeginVerifier(nullptr, 0, nullptr, 0, pairingAccessory.mPASEVerifier.mW0, kP256_FE_Length, + pairingAccessory.mPASEVerifier.mL, kP256_Point_Length); + + /*************************** Preparing Accessory for Receiving PAKE3 Message ***************************/ + + uint8_t Y[kMAX_Point_Length]; + size_t Y_len = sizeof(Y); + + uint8_t verifier[kMAX_Hash_Length]; + size_t verifier_len = kMAX_Hash_Length; + + // These calls are usually done on the Accessory before sending Pake2. They are needed to make sure that the Accessory is at the + // correct Spake2p state (CHIP_SPAKE2P_STATE::R2) to handle Pake3 Messages. + pairingAccessory.mSpake2p.ComputeRoundOne(X, X_len, Y, &Y_len); + pairingAccessory.mSpake2p.ComputeRoundTwo(X, X_len, verifier, &verifier_len); + + /*********************** Constructing Fuzzed PAKE3 Message, to later inject it into PASE Session *********************/ + + constexpr uint8_t kPake3_cA = 1; + + const size_t max_msg_len = TLV::EstimateStructOverhead(fuzzed_cA.size()); + System::PacketBufferHandle msg3 = System::PacketBufferHandle::New(max_msg_len); + EXPECT_FALSE(msg3.IsNull()); + + System::PacketBufferTLVWriter tlvWriter; + tlvWriter.Init(std::move(msg3)); + + TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified; + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Put(TLV::ContextTag(kPake3_cA), ByteSpan(fuzzed_cA.data(), fuzzed_cA.size()))); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.EndContainer(outerContainerType)); + EXPECT_EQ(CHIP_NO_ERROR, tlvWriter.Finalize(&msg3)); + + // After PAKE3 is sent, the pairingCommissioner will expect a StatusReport + pairingCommissioner.mNextExpectedMsg.SetValue(Protocols::SecureChannel::MsgType::StatusReport); + + /************************Injecting Fuzzed PAKE3 Message into PaseSession::OnMessageReceived*************************/ + + PayloadHeader payloadHeaderAccessory; + + // Below two lines are needed to trigger PASESession::OnMessageReceived to call HandleMsg3 + payloadHeaderAccessory.SetMessageType(Protocols::SecureChannel::MsgType::PASE_Pake3); + pairingAccessory.mNextExpectedMsg.SetValue(Protocols::SecureChannel::MsgType::PASE_Pake3); + + pairingAccessory.OnMessageReceived(&pairingAccessory.mExchangeCtxt.Value().Get(), payloadHeaderAccessory, std::move(msg3)); + + DrainAndServiceIO(); +} + +void HandlePake3(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, uint32_t fuzzedPBKDF2Iter, + const vector & fuzzedcA) +{ + TestPASESession PASELoopBack; + PASELoopBack.FuzzHandlePake3(fuzzedSetupPasscode, fuzzedSalt, fuzzedPBKDF2Iter, fuzzedcA); +} + +FUZZ_TEST(FuzzPASE_PW, HandlePake3) + .WithDomains( + // Setup Code Range (covers the full 27-bit range, plus 16 additional values) + InRange(00000000, 0x800000F), + // Salt length range (extending min and max by 4 bytes) + Arbitrary>() + .WithMinSize(kSpake2p_Min_PBKDF_Salt_Length - 4) + .WithMaxSize(kSpake2p_Max_PBKDF_Salt_Length + 4), + // PBKDF2Iterations count range (extending min and max by 10 iterations) + InRange(kSpake2p_Min_PBKDF_Iterations - 10, kSpake2p_Max_PBKDF_Iterations + 10), + // Fuzzed cA (Original size = kMAX_Hash_Length) + Arbitrary>()); + +} // namespace Testing +} // namespace chip diff --git a/src/pw_backends/assert/BUILD.gn b/src/pw_backends/assert/BUILD.gn new file mode 100644 index 00000000000000..5da1b7836b23a8 --- /dev/null +++ b/src/pw_backends/assert/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") + +import("$dir_pw_build/facade.gni") + +config("public_include_path") { + include_dirs = [ "public" ] + visibility = [ ":*" ] +} + +config("backend_config") { + include_dirs = [ "public_overrides" ] + visibility = [ ":*" ] +} + +pw_facade("handler") { + backend = "${chip_root}/src/pw_backends/assert:assert.impl" + public_configs = [ ":public_include_path" ] + public_deps = [ "$dir_pw_preprocessor" ] + public = [ "public/pw_assert_matter/handler.h" ] +} + +pw_source_set("assert") { + public_configs = [ + ":backend_config", + ":public_include_path", + ] + public = [ + "public/pw_assert_matter/handler.h", + "public_overrides/pw_assert_backend/check_backend.h", + ] + public_deps = [ ":handler.facade" ] +} + +# A basic handler backend using pw_sys_io. +pw_source_set("assert.impl") { + # Turn off GN check since this target intentionally leaves out deps to avoid + # circular dependencies. + check_includes = false + + configs = [ + "$dir_pw_string:public_include_path", + "$dir_pw_result:public_include_path", + ] + + deps = [ + ":handler.facade", + "$dir_pw_assert:config", + "$dir_pw_preprocessor", + "$dir_pw_string:builder", + "${chip_root}/src/lib/support", + ] + sources = [ "handler.cpp" ] +} diff --git a/src/pw_backends/assert/handler.cpp b/src/pw_backends/assert/handler.cpp new file mode 100644 index 00000000000000..b776cb892d1e64 --- /dev/null +++ b/src/pw_backends/assert/handler.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include + +#include +#include +#include + +void pw_assert_matter_HandleFailure(const char * file_name, int line_number, const char * function_name, const char * format, ...) +{ + + pw::StringBuffer<64> builder; + + builder.Format("Assertion failed: %s:%d (in %s):", file_name, line_number, function_name); + + va_list args; + va_start(args, format); + builder.FormatVaList(format, args); + va_end(args); + + ChipLogError(Support, "%s", builder.c_str()); + chipDie(); +} + +extern "C" void pw_assert_HandleFailure(void) +{ + pw_assert_matter_HandleFailure("", -1, "", "Crash: PW_ASSERT() or PW_DASSERT() failure"); +} diff --git a/src/pw_backends/assert/public/pw_assert_matter/handler.h b/src/pw_backends/assert/public/pw_assert_matter/handler.h new file mode 100644 index 00000000000000..efeac9a1c71d4b --- /dev/null +++ b/src/pw_backends/assert/public/pw_assert_matter/handler.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2024 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 "pw_preprocessor/compiler.h" +#include "pw_preprocessor/util.h" + +PW_EXTERN_C_START + +// Application-defined assert failure handler for pw_assert_basic. +// file_name - may be nullptr if not available +// line_number - may be -1 if not available +// function_name - may be nullptr if not available +// format & varags - The assert reason can be built using the format string and +// the varargs. +// +// Applications must define this function; it is not defined by pw_assert_basic. +void pw_assert_matter_HandleFailure(const char * file_name, int line_number, const char * function_name, const char * format, ...) + PW_PRINTF_FORMAT(4, 5) PW_NO_RETURN; + +PW_EXTERN_C_END diff --git a/src/pw_backends/assert/public_overrides/pw_assert_backend/check_backend.h b/src/pw_backends/assert/public_overrides/pw_assert_backend/check_backend.h new file mode 100644 index 00000000000000..af6c76aa0db302 --- /dev/null +++ b/src/pw_backends/assert/public_overrides/pw_assert_backend/check_backend.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024 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 "pw_assert_matter/handler.h" + +// Use __PRETTY_FUNCTION__, a GNU extension, in place of the __func__ macro when +// supported. __PRETTY_FUNCTION__ expands to the full C++ function name. +#ifdef __GNUC__ +#define _PW_ASSERT_MATTER_FUNCTION_NAME __PRETTY_FUNCTION__ +#else +#define _PW_ASSERT_MATTER_FUNCTION_NAME __func__ +#endif // __GNUC__ + +// Die with a message with many attributes included. This is the crash macro +// frontend that funnels everything into the C handler provided by the user, +// pw_assert_MATTER_HandleFailure(). +#define PW_HANDLE_CRASH(...) \ + pw_assert_matter_HandleFailure(__FILE__, __LINE__, _PW_ASSERT_MATTER_FUNCTION_NAME PW_COMMA_ARGS(__VA_ARGS__)) + +// Die with a message with many attributes included. This is the crash macro +// frontend that funnels everything into the C handler provided by the user, +// pw_assert_matter_HandleFailure(). +#define PW_HANDLE_ASSERT_FAILURE(condition_string, message, ...) \ + pw_assert_matter_HandleFailure(__FILE__, __LINE__, _PW_ASSERT_MATTER_FUNCTION_NAME, \ + "Check failed: " condition_string ". " message PW_COMMA_ARGS(__VA_ARGS__)) + +// Sample assert failure message produced by the below implementation: +// +// Check failed: current_sensor (=610) < new_sensor (=50). More details! +// +// Putting the value next to the operand makes the string easier to read. + +// clang-format off +// This is too hairy for clang format to handle and retain readability. +#define PW_HANDLE_ASSERT_BINARY_COMPARE_FAILURE(arg_a_str, \ + arg_a_val, \ + comparison_op_str, \ + arg_b_str, \ + arg_b_val, \ + type_fmt, \ + message, ...) \ + pw_assert_matter_HandleFailure( \ + __FILE__, \ + __LINE__, \ + _PW_ASSERT_MATTER_FUNCTION_NAME, \ + "Check failed: " \ + arg_a_str " (=" type_fmt ") " \ + comparison_op_str " " \ + arg_b_str " (=" type_fmt ")" \ + ". " message, \ + arg_a_val, arg_b_val PW_COMMA_ARGS(__VA_ARGS__)) diff --git a/src/pw_backends/log/BUILD.gn b/src/pw_backends/log/BUILD.gn new file mode 100644 index 00000000000000..b935a686506fcf --- /dev/null +++ b/src/pw_backends/log/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") + +import("$dir_pw_build/facade.gni") + +config("public_include_path") { + include_dirs = [ "public" ] + visibility = [ ":*" ] +} + +config("backend_config") { + include_dirs = [ "public_overrides" ] + visibility = [ ":*" ] +} + +pw_facade("handler") { + backend = "${chip_root}/src/pw_backends/log:log.impl" + public_configs = [ ":public_include_path" ] + public_deps = [ + "$dir_pw_preprocessor", + "${chip_root}/src/lib/support:text_only_logging", + ] + public = [ + "public/pw_log_matter/log_matter.h", + "public_overrides/pw_log_backend/log_backend.h", + ] +} + +pw_source_set("log") { + public_configs = [ + ":backend_config", + ":public_include_path", + ] + public = [ "public/pw_log_matter/log_matter.h" ] + public_deps = [ + ":handler.facade", + "${chip_root}/src/lib/support:text_only_logging", + ] +} + +# A basic handler backend using pw_sys_io. +pw_source_set("log.impl") { + # Turn off GN check since this target intentionally leaves out deps to avoid + # circular dependencies. + check_includes = false + + configs = [ + "$dir_pw_string:public_include_path", + "$dir_pw_result:public_include_path", + ] + + deps = [ + ":handler.facade", + "$dir_pw_log:config", + "$dir_pw_preprocessor", + "$dir_pw_string:builder", + "${chip_root}/src/lib/support", + ] + sources = [] +} diff --git a/src/pw_backends/log/public/pw_log_matter/log_matter.h b/src/pw_backends/log/public/pw_log_matter/log_matter.h new file mode 100644 index 00000000000000..c956bcadb7aa68 --- /dev/null +++ b/src/pw_backends/log/public/pw_log_matter/log_matter.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 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 "lib/support/logging/Constants.h" +#include +#include + +// Pigweed defines more granular logging than CHIP. +// we match the following: +// - Detail == DEBUG +// - Progress == INFO +// - ERROR = WARN, ERROR, CRITICAL + +constexpr chip::Logging::LogCategory PwLogLevelToChipLogCategory(int level) +{ + switch (level) + { + case PW_LOG_LEVEL_DEBUG: + return chip::Logging::kLogCategory_Detail; + case PW_LOG_LEVEL_INFO: + return chip::Logging::kLogCategory_Progress; + default: + return chip::Logging::kLogCategory_Error; + } +} + +#define PW_LOG_DEBUG(...) ChipLogDetail(NotSpecified, __VA_ARGS__) +#define PW_LOG_INFO(...) ChipLogProgress(NotSpecified, __VA_ARGS__) +#define PW_LOG_WARN(...) ChipLogError(NotSpecified, __VA_ARGS__) +#define PW_LOG_ERROR(...) ChipLogError(NotSpecified, __VA_ARGS__) +#define PW_LOG_CRITICAL(...) ChipLogError(NotSpecified, __VA_ARGS__) + +// Log a message with many attributes included. +// +// This is the main macro that functions not included above will use +#define PW_HANDLE_LOG(level, module, flags, message, ...) \ + ChipInternalLogImpl(NotSpecified, PwLogLevelToChipLogCategory(level), message, __VA_ARGS__) diff --git a/src/lib/support/pw_log_chip/public_overrides/pw_log_backend/log_backend.h b/src/pw_backends/log/public_overrides/pw_log_backend/log_backend.h similarity index 74% rename from src/lib/support/pw_log_chip/public_overrides/pw_log_backend/log_backend.h rename to src/pw_backends/log/public_overrides/pw_log_backend/log_backend.h index aee9d4abff0403..8e9e15947ab0d9 100644 --- a/src/lib/support/pw_log_chip/public_overrides/pw_log_backend/log_backend.h +++ b/src/pw_backends/log/public_overrides/pw_log_backend/log_backend.h @@ -1,5 +1,6 @@ /* - * Copyright (c) 2020 Project CHIP Authors. + * Copyright (c) 2024 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. @@ -13,12 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/** - * @file - * This header interfaces with the Pigweed logging facade by overriding - * the backend header. - */ #pragma once -#include "pw_log_chip/log_chip.h" +#include "pw_log_matter/log_matter.h" diff --git a/src/python_testing/TC_EEVSE_2_3.py b/src/python_testing/TC_EEVSE_2_3.py index eb4e43d0b50105..54c5baa1a7ddff 100644 --- a/src/python_testing/TC_EEVSE_2_3.py +++ b/src/python_testing/TC_EEVSE_2_3.py @@ -194,8 +194,10 @@ def compute_expected_target_time_as_epoch_s(self, minutes_past_midnight): f"{int(minutes_past_midnight/60)}:{int(minutes_past_midnight%60)}" f" Expected target_time = {target_time}") - target_time_delta = target_time - \ - datetime(2000, 1, 1, 0, 0, 0, 0).astimezone(timezone.utc) + matter_base_time = datetime(2000, 1, 1, 0, 0, 0, 0, tzinfo=timezone.utc) + + target_time_delta = target_time - matter_base_time + expected_target_time_epoch_s = int(target_time_delta.total_seconds()) return expected_target_time_epoch_s diff --git a/src/python_testing/TC_MCORE_FS_1_3.py b/src/python_testing/TC_MCORE_FS_1_3.py index 2ac1556199a0c7..4b732a1b3a8995 100644 --- a/src/python_testing/TC_MCORE_FS_1_3.py +++ b/src/python_testing/TC_MCORE_FS_1_3.py @@ -34,7 +34,7 @@ # --commissioning-method on-network # --discriminator 1234 # --passcode 20202021 -# --string-arg th_server_no_uid_app_path:${LIGHTING_APP_NO_UNIQUE_ID} +# --string-arg th_server_no_uid_app_path:${LIGHTING_APP_NO_UNIQUE_ID} dut_fsa_stdin_pipe:dut-fsa-stdin # --trace-to json:${TRACE_TEST_JSON}.json # --trace-to perfetto:${TRACE_TEST_PERFETTO}.perfetto # factory-reset: true @@ -81,6 +81,13 @@ def setup_class(self): self.storage = tempfile.TemporaryDirectory(prefix=self.__class__.__name__) logging.info("Temporary storage directory: %s", self.storage.name) + if self.is_pics_sdk_ci_only: + # Get the named pipe path for the DUT_FSA app input from the user params. + dut_fsa_stdin_pipe = self.user_params.get("dut_fsa_stdin_pipe") + if not dut_fsa_stdin_pipe: + asserts.fail("CI setup requires --string-arg dut_fsa_stdin_pipe:") + self.dut_fsa_stdin = open(dut_fsa_stdin_pipe, "w") + self.th_server_port = 5544 self.th_server_discriminator = random.randint(0, 4095) self.th_server_passcode = 20202021 @@ -111,60 +118,6 @@ def steps_TC_MCORE_FS_1_3(self) -> list[TestStep]: "TH verifies a value is visible for the UniqueID from the DUT_FSA's Bridged Device Basic Information Cluster."), ] - async def commission_via_commissioner_control(self, controller_node_id: int, device_node_id: int, endpoint_id: int): - """Commission device_node_id to controller_node_id using CommissionerControl cluster.""" - - request_id = random.randint(0, 0xFFFFFFFFFFFFFFFF) - - vendor_id = await self.read_single_attribute_check_success( - node_id=device_node_id, - cluster=Clusters.BasicInformation, - attribute=Clusters.BasicInformation.Attributes.VendorID, - ) - - product_id = await self.read_single_attribute_check_success( - node_id=device_node_id, - cluster=Clusters.BasicInformation, - attribute=Clusters.BasicInformation.Attributes.ProductID, - ) - - await self.send_single_cmd( - node_id=controller_node_id, - endpoint=endpoint_id, - cmd=Clusters.CommissionerControl.Commands.RequestCommissioningApproval( - requestID=request_id, - vendorID=vendor_id, - productID=product_id, - ), - ) - - if not self.is_pics_sdk_ci_only: - self.wait_for_user_input("Approve Commissioning Approval Request on DUT using manufacturer specified mechanism") - - resp = await self.send_single_cmd( - node_id=controller_node_id, - endpoint=endpoint_id, - cmd=Clusters.CommissionerControl.Commands.CommissionNode( - requestID=request_id, - responseTimeoutSeconds=30, - ), - ) - - asserts.assert_equal(type(resp), Clusters.CommissionerControl.Commands.ReverseOpenCommissioningWindow, - "Incorrect response type") - - await self.send_single_cmd( - node_id=device_node_id, - cmd=Clusters.AdministratorCommissioning.Commands.OpenCommissioningWindow( - commissioningTimeout=3*60, - PAKEPasscodeVerifier=resp.PAKEPasscodeVerifier, - discriminator=resp.discriminator, - iterations=resp.iterations, - salt=resp.salt, - ), - timedRequestTimeoutMs=5000, - ) - @async_test_body async def test_TC_MCORE_FS_1_3(self): @@ -218,13 +171,35 @@ async def test_TC_MCORE_FS_1_3(self): asserts.assert_not_equal(aggregator_endpoint, 0, "Invalid aggregator endpoint. Cannot proceed with commissioning.") - await self.commission_via_commissioner_control( - controller_node_id=self.dut_node_id, - device_node_id=th_server_th_node_id, - endpoint_id=aggregator_endpoint) + # Open commissioning window on TH_SERVER_NO_UID. + discriminator = random.randint(0, 4095) + params = await self.default_controller.OpenCommissioningWindow( + nodeid=th_server_th_node_id, + option=self.default_controller.CommissioningWindowPasscode.kTokenWithRandomPin, + discriminator=discriminator, + iteration=10000, + timeout=600) + + # Commissioning TH_SERVER_NO_UID to DUT_FSA fabric. + if not self.is_pics_sdk_ci_only: + self.wait_for_user_input( + f"Commission TH_SERVER_NO_UID on DUT using manufacturer specified mechanism.\n" + f"Use the following parameters:\n" + f"- discriminator: {discriminator}\n" + f"- setupPinCode: {params.setupPinCode}\n" + f"- setupQRCode: {params.setupQRCode}\n" + f"- setupManualCode: {params.setupManualCode}\n" + f"If using FabricSync Admin, you may type:\n" + f">>> pairing onnetwork {params.setupPinCode}") + else: + self.dut_fsa_stdin.write( + f"pairing onnetwork 10 {params.setupPinCode}\n") + self.dut_fsa_stdin.flush() + # Wait for the commissioning to complete. + await asyncio.sleep(5) # Wait for the device to appear on the DUT_FSA_BRIDGE. - await asyncio.sleep(2 if self.is_pics_sdk_ci_only else 30) + await asyncio.sleep(1) # Get the list of endpoints on the DUT_FSA_BRIDGE after adding the TH_SERVER_NO_UID. dut_fsa_bridge_endpoints_new = set(await self.read_single_attribute_check_success( diff --git a/src/python_testing/TC_MCORE_FS_1_5.py b/src/python_testing/TC_MCORE_FS_1_5.py index 59549fd0bcdc9b..e8d6b3e6784a90 100755 --- a/src/python_testing/TC_MCORE_FS_1_5.py +++ b/src/python_testing/TC_MCORE_FS_1_5.py @@ -212,7 +212,7 @@ async def test_TC_MCORE_FS_1_5(self): time_remaining = report_waiting_timeout_delay_sec parts_list_endpoint_count_from_step_1 = len(step_1_dut_parts_list) - step_3_dut_parts_list = None + step_3_dut_parts_list = [] while time_remaining > 0: try: item = parts_list_queue.get(block=True, timeout=time_remaining) @@ -304,16 +304,20 @@ async def test_TC_MCORE_FS_1_5(self): endpoint, attribute, value = item['endpoint'], item['attribute'], item['value'] # Record arrival of an expected subscription change when seen - if endpoint == newly_added_endpoint and attribute == Clusters.AdministratorCommissioning.Attributes.WindowStatus: + if endpoint == newly_added_endpoint and attribute == cadmin_attr.WindowStatus: + if value != th_server_direct_cadmin[cadmin_attr.WindowStatus]: + logging.info("Window status is %r, waiting for %r", value, + th_server_direct_cadmin[cadmin_attr.WindowStatus]) + continue cadmin_sub_new_data = True break - except queue.Empty: # No error, we update timeouts and keep going pass - - elapsed = time.time() - start_time - time_remaining = report_waiting_timeout_delay_sec - elapsed + finally: + # each iteration will alter timing + elapsed = time.time() - start_time + time_remaining = report_waiting_timeout_delay_sec - elapsed asserts.assert_true(cadmin_sub_new_data, "Timed out waiting for DUT to reflect AdministratorCommissioning attributes for bridged device") diff --git a/src/python_testing/execute_python_tests.py b/src/python_testing/execute_python_tests.py index 34a391873b3101..c85a02bc40952e 100644 --- a/src/python_testing/execute_python_tests.py +++ b/src/python_testing/execute_python_tests.py @@ -20,6 +20,8 @@ import os import subprocess +import yaml + # Function to load --app argument environment variables from a file @@ -36,11 +38,8 @@ def load_env_from_yaml(file_path): Args: file_path (str): The path to the YAML file containing the environment variables. """ - with open(file_path, 'r') as file: - for line in file: - if line.strip(): # Skip empty lines - key, value = line.strip().split(': ', 1) - os.environ[key] = value + for key, value in yaml.full_load(open(file_path, 'r')).items(): + os.environ[key] = value def main(search_directory, env_file): @@ -53,38 +52,8 @@ def main(search_directory, env_file): # Define the base command to run tests base_command = os.path.join(chip_root, "scripts/tests/run_python_test.py") - # Define the test python script files and patterns to exclude - excluded_patterns = { - "MinimalRepresentation.py", # Code/Test not being used or not shared code for any other tests - "TC_CNET_4_4.py", # It has no CI execution block, is not executed in CI - "TC_DGGEN_3_2.py", # src/python_testing/test_testing/test_TC_DGGEN_3_2.py is the Unit test of this test - "TC_EEVSE_Utils.py", # Shared code for TC_EEVSE, not a standalone test - "TC_EWATERHTRBase.py", # Shared code for TC_EWATERHTR, not a standalone test - "TC_EnergyReporting_Utils.py", # Shared code for TC_EEM and TC_EPM, not a standalone test - "TC_OpstateCommon.py", # Shared code for TC_OPSTATE, not a standalone test - "TC_pics_checker.py", # Currently isn't enabled because we don't have any examples with conformant PICS - "TC_TMP_2_1.py", # src/python_testing/test_testing/test_TC_TMP_2_1.py is the Unit test of this test - "TC_OCC_3_1.py", # There are CI issues for the test cases that implements manually controlling sensor device for the occupancy state ON/OFF change - "TC_OCC_3_2.py", # There are CI issues for the test cases that implements manually controlling sensor device for the occupancy state ON/OFF change - "TestCommissioningTimeSync.py", # Code/Test not being used or not shared code for any other tests - "TestConformanceSupport.py", # Unit test - does not run against an app - "TestChoiceConformanceSupport.py", # Unit test - does not run against an app - "TC_DEMTestBase.py", # Shared code for TC_DEM, not a standalone test - "TestConformanceTest.py", # Unit test of the conformance test (TC_DeviceConformance) - does not run against an app - "TestIdChecks.py", # Unit test - does not run against an app - "TestSpecParsingDeviceType.py", # Unit test - does not run against an app - "TestConformanceTest.py", # Unit test - does not run against an app - "TestMatterTestingSupport.py", # Unit test - does not run against an app - "TestSpecParsingSupport.py", # Unit test - does not run against an app - "TestTimeSyncTrustedTimeSource.py", # Unit test and shared code for scripts/tests/TestTimeSyncTrustedTimeSourceRunner.py - "drlk_2_x_common.py", # Shared code for TC_DRLK, not a standalone test - # Python code that runs all the python tests from src/python_testing (This code itself run via tests.yaml) - "execute_python_tests.py", - "hello_external_runner.py", # Code/Test not being used or not shared code for any other tests - "hello_test.py", # Is a template for tests - "test_plan_support.py", # Shared code for TC_*, not a standalone test - "test_plan_table_generator.py", # Code/Test not being used or not shared code for any other tests - } + metadata = yaml.full_load(open(os.path.join(chip_root, "src/python_testing/test_metadata.yaml"))) + excluded_patterns = set([item["name"] for item in metadata["not_automated"]]) # Get all .py files in the directory all_python_files = glob.glob(os.path.join(search_directory, "*.py")) diff --git a/src/python_testing/matter_testing_infrastructure/BUILD.gn b/src/python_testing/matter_testing_infrastructure/BUILD.gn index 19c7aee68defd9..64e27b47bb0a5d 100644 --- a/src/python_testing/matter_testing_infrastructure/BUILD.gn +++ b/src/python_testing/matter_testing_infrastructure/BUILD.gn @@ -14,16 +14,21 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") - import("//build_overrides/pigweed.gni") +import("//src/python_testing/matter_testing_infrastructure/data_model_xmls.gni") import("$dir_pw_build/python.gni") +import("$dir_pw_build/python_dist.gni") -pw_python_package("chip-testing") { - setup = [ - "setup.py", - "setup.cfg", - "pyproject.toml", - ] +pw_python_package("chip-testing-module") { + generate_setup = { + metadata = { + name = "chip-testing-module" + version = "1.4.0" + author = "Project CHIP Authors" + license_expression = "Apache-2.0" # Consistent license format + url = "https://github.com/project-chip/connectedhomeip" + } + } inputs = [ "env_test.yaml" ] @@ -41,9 +46,25 @@ pw_python_package("chip-testing") { "chip/testing/taglist_and_topology_test.py", "chip/testing/tasks.py", ] - tests = [ "chip/testing/test_metadata.py", "chip/testing/test_tasks.py", ] } + +pw_python_distribution("chip-testing") { + packages = [ ":chip-testing-module" ] + + generate_setup_cfg = { + name = "chip-testing" + version = "1.4.0" + include_default_pyproject_file = true + include_extra_files_in_package_data = true + } + + # Use the imported data_model_XMLS directly + extra_files = [] + foreach(file, data_model_XMLS) { + extra_files += [ "${file} > chip/testing/${file}" ] + } +} diff --git a/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py b/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py index 39d1be3ec872e6..01351cb987dcc9 100644 --- a/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py +++ b/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py @@ -14,10 +14,11 @@ import logging import re +import shlex import subprocess import sys import threading -from typing import BinaryIO, Callable, List, Optional, Union +from typing import BinaryIO, Callable, Optional, Union def forward_f(f_in: BinaryIO, @@ -29,6 +30,8 @@ def forward_f(f_in: BinaryIO, This function can optionally post-process received lines using a callback function. """ + + # NOTE: readlines would block here, so read line by line instead while line := f_in.readline(): if cb is not None: line = cb(line, is_stderr) @@ -39,7 +42,7 @@ def forward_f(f_in: BinaryIO, class Subprocess(threading.Thread): """Run a subprocess in a thread.""" - def __init__(self, program: str, *args: List[str], + def __init__(self, program: str, *args, output_cb: Optional[Callable[[bytes, bool], bytes]] = None, f_stdout: BinaryIO = sys.stdout.buffer, f_stderr: BinaryIO = sys.stderr.buffer): @@ -62,7 +65,7 @@ def __init__(self, program: str, *args: List[str], self.output_cb = output_cb self.f_stdout = f_stdout self.f_stderr = f_stderr - self.output_match = None + self.output_match: Optional[re.Pattern] = None self.returncode = None def _set_output_match(self, pattern: Union[str, re.Pattern]): @@ -81,11 +84,14 @@ def _check_output(self, line: bytes, is_stderr: bool): def run(self): """Thread entry point.""" - logging.info("RUN: %s %s", self.program, " ".join(self.args)) - self.p = subprocess.Popen([self.program] + list(self.args), + command = [self.program] + list(self.args) + + logging.info("RUN: %s", shlex.join(command)) + self.p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=subprocess.PIPE) + stderr=subprocess.PIPE, + bufsize=0) self.event_started.set() # Forward stdout and stderr with a tag attached. @@ -123,7 +129,7 @@ def start(self, # hang on the join call in our thread entry point in case of # Python process termination (not-caught exception). self.p.terminate() - raise TimeoutError("Expected output not found") + raise TimeoutError("Expected output '%r' not found within %s seconds" % (expected_output, timeout)) self.expected_output = None def send(self, message: str, end: str = "\n", diff --git a/src/python_testing/matter_testing_infrastructure/data_model_xmls.gni b/src/python_testing/matter_testing_infrastructure/data_model_xmls.gni new file mode 100644 index 00000000000000..066537816a5c9a --- /dev/null +++ b/src/python_testing/matter_testing_infrastructure/data_model_xmls.gni @@ -0,0 +1,564 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") + +data_model_XMLS = [ + "${chip_root}/data_model/1.3/clusters/ACL-Cluster.xml", + "${chip_root}/data_model/1.3/clusters/AccountLogin.xml", + "${chip_root}/data_model/1.3/clusters/AdminCommissioningCluster.xml", + "${chip_root}/data_model/1.3/clusters/AirQuality.xml", + "${chip_root}/data_model/1.3/clusters/AlarmBase.xml", + "${chip_root}/data_model/1.3/clusters/ApplicationBasic.xml", + "${chip_root}/data_model/1.3/clusters/ApplicationLauncher.xml", + "${chip_root}/data_model/1.3/clusters/AudioOutput.xml", + "${chip_root}/data_model/1.3/clusters/BallastConfiguration.xml", + "${chip_root}/data_model/1.3/clusters/BasicInformationCluster.xml", + "${chip_root}/data_model/1.3/clusters/Binding-Cluster.xml", + "${chip_root}/data_model/1.3/clusters/BooleanState.xml", + "${chip_root}/data_model/1.3/clusters/BooleanStateConfiguration.xml", + "${chip_root}/data_model/1.3/clusters/Channel.xml", + "${chip_root}/data_model/1.3/clusters/ColorControl.xml", + "${chip_root}/data_model/1.3/clusters/ConcentrationMeasurement.xml", + "${chip_root}/data_model/1.3/clusters/ContentAppObserver.xml", + "${chip_root}/data_model/1.3/clusters/ContentControl.xml", + "${chip_root}/data_model/1.3/clusters/ContentLauncher.xml", + "${chip_root}/data_model/1.3/clusters/Descriptor-Cluster.xml", + "${chip_root}/data_model/1.3/clusters/DeviceEnergyManagement.xml", + "${chip_root}/data_model/1.3/clusters/DiagnosticLogsCluster.xml", + "${chip_root}/data_model/1.3/clusters/DiagnosticsEthernet.xml", + "${chip_root}/data_model/1.3/clusters/DiagnosticsGeneral.xml", + "${chip_root}/data_model/1.3/clusters/DiagnosticsSoftware.xml", + "${chip_root}/data_model/1.3/clusters/DiagnosticsThread.xml", + "${chip_root}/data_model/1.3/clusters/DiagnosticsWiFi.xml", + "${chip_root}/data_model/1.3/clusters/DishwasherAlarm.xml", + "${chip_root}/data_model/1.3/clusters/DoorLock.xml", + "${chip_root}/data_model/1.3/clusters/ElectricalEnergyMeasurement.xml", + "${chip_root}/data_model/1.3/clusters/ElectricalPowerMeasurement.xml", + "${chip_root}/data_model/1.3/clusters/EnergyEVSE.xml", + "${chip_root}/data_model/1.3/clusters/EnergyPreference.xml", + "${chip_root}/data_model/1.3/clusters/FanControl.xml", + "${chip_root}/data_model/1.3/clusters/FlowMeasurement.xml", + "${chip_root}/data_model/1.3/clusters/GeneralCommissioningCluster.xml", + "${chip_root}/data_model/1.3/clusters/Group-Key-Management-Cluster.xml", + "${chip_root}/data_model/1.3/clusters/Groups.xml", + "${chip_root}/data_model/1.3/clusters/ICDManagement.xml", + "${chip_root}/data_model/1.3/clusters/Identify.xml", + "${chip_root}/data_model/1.3/clusters/IlluminanceMeasurement.xml", + "${chip_root}/data_model/1.3/clusters/KeypadInput.xml", + "${chip_root}/data_model/1.3/clusters/Label-Cluster-FixedLabelCluster.xml", + "${chip_root}/data_model/1.3/clusters/Label-Cluster-LabelCluster.xml", + "${chip_root}/data_model/1.3/clusters/Label-Cluster-UserLabelCluster.xml", + "${chip_root}/data_model/1.3/clusters/LaundryDryerControls.xml", + "${chip_root}/data_model/1.3/clusters/LaundryWasherControls.xml", + "${chip_root}/data_model/1.3/clusters/LevelControl.xml", + "${chip_root}/data_model/1.3/clusters/LocalizationConfiguration.xml", + "${chip_root}/data_model/1.3/clusters/LocalizationTimeFormat.xml", + "${chip_root}/data_model/1.3/clusters/LocalizationUnit.xml", + "${chip_root}/data_model/1.3/clusters/LowPower.xml", + "${chip_root}/data_model/1.3/clusters/MediaInput.xml", + "${chip_root}/data_model/1.3/clusters/MediaPlayback.xml", + "${chip_root}/data_model/1.3/clusters/Messages.xml", + "${chip_root}/data_model/1.3/clusters/MicrowaveOvenControl.xml", + "${chip_root}/data_model/1.3/clusters/ModeBase.xml", + "${chip_root}/data_model/1.3/clusters/ModeSelect.xml", + "${chip_root}/data_model/1.3/clusters/Mode_DeviceEnergyManagement.xml", + "${chip_root}/data_model/1.3/clusters/Mode_Dishwasher.xml", + "${chip_root}/data_model/1.3/clusters/Mode_EVSE.xml", + "${chip_root}/data_model/1.3/clusters/Mode_LaundryWasher.xml", + "${chip_root}/data_model/1.3/clusters/Mode_MicrowaveOven.xml", + "${chip_root}/data_model/1.3/clusters/Mode_Oven.xml", + "${chip_root}/data_model/1.3/clusters/Mode_RVCClean.xml", + "${chip_root}/data_model/1.3/clusters/Mode_RVCRun.xml", + "${chip_root}/data_model/1.3/clusters/Mode_Refrigerator.xml", + "${chip_root}/data_model/1.3/clusters/NetworkCommissioningCluster.xml", + "${chip_root}/data_model/1.3/clusters/OTAProvider.xml", + "${chip_root}/data_model/1.3/clusters/OTARequestor.xml", + "${chip_root}/data_model/1.3/clusters/OccupancySensing.xml", + "${chip_root}/data_model/1.3/clusters/OnOff.xml", + "${chip_root}/data_model/1.3/clusters/OperationalCredentialCluster.xml", + "${chip_root}/data_model/1.3/clusters/OperationalState.xml", + "${chip_root}/data_model/1.3/clusters/OperationalState_Oven.xml", + "${chip_root}/data_model/1.3/clusters/OperationalState_RVC.xml", + "${chip_root}/data_model/1.3/clusters/PowerSourceCluster.xml", + "${chip_root}/data_model/1.3/clusters/PowerSourceConfigurationCluster.xml", + "${chip_root}/data_model/1.3/clusters/PowerTopology.xml", + "${chip_root}/data_model/1.3/clusters/PressureMeasurement.xml", + "${chip_root}/data_model/1.3/clusters/ProxyConfiguration-Cluster.xml", + "${chip_root}/data_model/1.3/clusters/ProxyDiscovery-Cluster.xml", + "${chip_root}/data_model/1.3/clusters/PumpConfigurationControl.xml", + "${chip_root}/data_model/1.3/clusters/RefrigeratorAlarm.xml", + "${chip_root}/data_model/1.3/clusters/ResourceMonitoring.xml", + "${chip_root}/data_model/1.3/clusters/Scenes.xml", + "${chip_root}/data_model/1.3/clusters/SmokeCOAlarm.xml", + "${chip_root}/data_model/1.3/clusters/Switch.xml", + "${chip_root}/data_model/1.3/clusters/TargetNavigator.xml", + "${chip_root}/data_model/1.3/clusters/TemperatureControl.xml", + "${chip_root}/data_model/1.3/clusters/TemperatureMeasurement.xml", + "${chip_root}/data_model/1.3/clusters/Thermostat.xml", + "${chip_root}/data_model/1.3/clusters/ThermostatUserInterfaceConfiguration.xml", + "${chip_root}/data_model/1.3/clusters/TimeSync.xml", + "${chip_root}/data_model/1.3/clusters/ValidProxies-Cluster.xml", + "${chip_root}/data_model/1.3/clusters/ValveConfigurationControl.xml", + "${chip_root}/data_model/1.3/clusters/WakeOnLAN.xml", + "${chip_root}/data_model/1.3/clusters/WaterContentMeasurement.xml", + "${chip_root}/data_model/1.3/clusters/WindowCovering.xml", + "${chip_root}/data_model/1.3/clusters/bridge-clusters-ActionsCluster.xml", + "${chip_root}/data_model/1.3/clusters/bridge-clusters-BridgedDeviceBasicInformationCluster.xml", + "${chip_root}/data_model/1.3/clusters/cluster_ids.json", + "${chip_root}/data_model/1.3/device_types/Aggregator.xml", + "${chip_root}/data_model/1.3/device_types/AirPurifier.xml", + "${chip_root}/data_model/1.3/device_types/AirQualitySensor.xml", + "${chip_root}/data_model/1.3/device_types/BaseDeviceType.xml", + "${chip_root}/data_model/1.3/device_types/BasicVideoPlayer.xml", + "${chip_root}/data_model/1.3/device_types/BridgedNode.xml", + "${chip_root}/data_model/1.3/device_types/CastingVideoClient.xml", + "${chip_root}/data_model/1.3/device_types/CastingVideoPlayer.xml", + "${chip_root}/data_model/1.3/device_types/ColorDimmerSwitch.xml", + "${chip_root}/data_model/1.3/device_types/ColorTemperatureLight.xml", + "${chip_root}/data_model/1.3/device_types/ContactSensor.xml", + "${chip_root}/data_model/1.3/device_types/ContentApp.xml", + "${chip_root}/data_model/1.3/device_types/ControlBridge.xml", + "${chip_root}/data_model/1.3/device_types/CookSurface.xml", + "${chip_root}/data_model/1.3/device_types/Cooktop.xml", + "${chip_root}/data_model/1.3/device_types/DeviceEnergyManagement.xml", + "${chip_root}/data_model/1.3/device_types/DimmableLight.xml", + "${chip_root}/data_model/1.3/device_types/DimmablePlug-InUnit.xml", + "${chip_root}/data_model/1.3/device_types/DimmerSwitch.xml", + "${chip_root}/data_model/1.3/device_types/Dishwasher.xml", + "${chip_root}/data_model/1.3/device_types/DoorLock.xml", + "${chip_root}/data_model/1.3/device_types/DoorLockController.xml", + "${chip_root}/data_model/1.3/device_types/EVSE.xml", + "${chip_root}/data_model/1.3/device_types/ElectricalSensor.xml", + "${chip_root}/data_model/1.3/device_types/ExtendedColorLight.xml", + "${chip_root}/data_model/1.3/device_types/ExtractorHood.xml", + "${chip_root}/data_model/1.3/device_types/Fan.xml", + "${chip_root}/data_model/1.3/device_types/FlowSensor.xml", + "${chip_root}/data_model/1.3/device_types/GenericSwitch.xml", + "${chip_root}/data_model/1.3/device_types/HumiditySensor.xml", + "${chip_root}/data_model/1.3/device_types/LaundryDryer.xml", + "${chip_root}/data_model/1.3/device_types/LaundryWasher.xml", + "${chip_root}/data_model/1.3/device_types/LightSensor.xml", + "${chip_root}/data_model/1.3/device_types/MicrowaveOven.xml", + "${chip_root}/data_model/1.3/device_types/ModeSelectDeviceType.xml", + "${chip_root}/data_model/1.3/device_types/OccupancySensor.xml", + "${chip_root}/data_model/1.3/device_types/OnOffLight.xml", + "${chip_root}/data_model/1.3/device_types/OnOffLightSwitch.xml", + "${chip_root}/data_model/1.3/device_types/OnOffPlug-inUnit.xml", + "${chip_root}/data_model/1.3/device_types/OnOffSensor.xml", + "${chip_root}/data_model/1.3/device_types/OtaProvider.xml", + "${chip_root}/data_model/1.3/device_types/OtaRequestor.xml", + "${chip_root}/data_model/1.3/device_types/Oven.xml", + "${chip_root}/data_model/1.3/device_types/PowerSource.xml", + "${chip_root}/data_model/1.3/device_types/PressureSensor.xml", + "${chip_root}/data_model/1.3/device_types/Pump.xml", + "${chip_root}/data_model/1.3/device_types/PumpController.xml", + "${chip_root}/data_model/1.3/device_types/RainSensor.xml", + "${chip_root}/data_model/1.3/device_types/Refrigerator.xml", + "${chip_root}/data_model/1.3/device_types/RoboticVacuumCleaner.xml", + "${chip_root}/data_model/1.3/device_types/RoomAirConditioner.xml", + "${chip_root}/data_model/1.3/device_types/RootNodeDeviceType.xml", + "${chip_root}/data_model/1.3/device_types/SmokeCOAlarm.xml", + "${chip_root}/data_model/1.3/device_types/Speaker.xml", + "${chip_root}/data_model/1.3/device_types/TemperatureControlledCabinet.xml", + "${chip_root}/data_model/1.3/device_types/TemperatureSensor.xml", + "${chip_root}/data_model/1.3/device_types/Thermostat.xml", + "${chip_root}/data_model/1.3/device_types/VideoRemoteControl.xml", + "${chip_root}/data_model/1.3/device_types/WaterFreezeDetector.xml", + "${chip_root}/data_model/1.3/device_types/WaterLeakDetector.xml", + "${chip_root}/data_model/1.3/device_types/WaterValve.xml", + "${chip_root}/data_model/1.3/device_types/WindowCovering.xml", + "${chip_root}/data_model/1.3/device_types/WindowCoveringController.xml", + "${chip_root}/data_model/1.4/clusters/ACL-Cluster.xml", + "${chip_root}/data_model/1.4/clusters/AccountLogin.xml", + "${chip_root}/data_model/1.4/clusters/AdminCommissioningCluster.xml", + "${chip_root}/data_model/1.4/clusters/AirQuality.xml", + "${chip_root}/data_model/1.4/clusters/AlarmBase.xml", + "${chip_root}/data_model/1.4/clusters/ApplicationBasic.xml", + "${chip_root}/data_model/1.4/clusters/ApplicationLauncher.xml", + "${chip_root}/data_model/1.4/clusters/AudioOutput.xml", + "${chip_root}/data_model/1.4/clusters/BallastConfiguration.xml", + "${chip_root}/data_model/1.4/clusters/BasicInformationCluster.xml", + "${chip_root}/data_model/1.4/clusters/Binding-Cluster.xml", + "${chip_root}/data_model/1.4/clusters/BooleanState.xml", + "${chip_root}/data_model/1.4/clusters/BooleanStateConfiguration.xml", + "${chip_root}/data_model/1.4/clusters/Channel.xml", + "${chip_root}/data_model/1.4/clusters/ColorControl.xml", + "${chip_root}/data_model/1.4/clusters/CommissionerControlCluster.xml", + "${chip_root}/data_model/1.4/clusters/ConcentrationMeasurement.xml", + "${chip_root}/data_model/1.4/clusters/ContentAppObserver.xml", + "${chip_root}/data_model/1.4/clusters/ContentControl.xml", + "${chip_root}/data_model/1.4/clusters/ContentLauncher.xml", + "${chip_root}/data_model/1.4/clusters/Descriptor-Cluster.xml", + "${chip_root}/data_model/1.4/clusters/DeviceEnergyManagement.xml", + "${chip_root}/data_model/1.4/clusters/DiagnosticLogsCluster.xml", + "${chip_root}/data_model/1.4/clusters/DiagnosticsEthernet.xml", + "${chip_root}/data_model/1.4/clusters/DiagnosticsGeneral.xml", + "${chip_root}/data_model/1.4/clusters/DiagnosticsSoftware.xml", + "${chip_root}/data_model/1.4/clusters/DiagnosticsThread.xml", + "${chip_root}/data_model/1.4/clusters/DiagnosticsWiFi.xml", + "${chip_root}/data_model/1.4/clusters/DishwasherAlarm.xml", + "${chip_root}/data_model/1.4/clusters/DoorLock.xml", + "${chip_root}/data_model/1.4/clusters/EcosystemInformationCluster.xml", + "${chip_root}/data_model/1.4/clusters/ElectricalEnergyMeasurement.xml", + "${chip_root}/data_model/1.4/clusters/ElectricalPowerMeasurement.xml", + "${chip_root}/data_model/1.4/clusters/EnergyEVSE.xml", + "${chip_root}/data_model/1.4/clusters/EnergyPreference.xml", + "${chip_root}/data_model/1.4/clusters/FanControl.xml", + "${chip_root}/data_model/1.4/clusters/FlowMeasurement.xml", + "${chip_root}/data_model/1.4/clusters/GeneralCommissioningCluster.xml", + "${chip_root}/data_model/1.4/clusters/Group-Key-Management-Cluster.xml", + "${chip_root}/data_model/1.4/clusters/Groups.xml", + "${chip_root}/data_model/1.4/clusters/ICDManagement.xml", + "${chip_root}/data_model/1.4/clusters/Identify.xml", + "${chip_root}/data_model/1.4/clusters/IlluminanceMeasurement.xml", + "${chip_root}/data_model/1.4/clusters/JointFabricDatastoreCluster.xml", + "${chip_root}/data_model/1.4/clusters/JointFabricPKICluster.xml", + "${chip_root}/data_model/1.4/clusters/KeypadInput.xml", + "${chip_root}/data_model/1.4/clusters/Label-Cluster-FixedLabelCluster.xml", + "${chip_root}/data_model/1.4/clusters/Label-Cluster-LabelCluster.xml", + "${chip_root}/data_model/1.4/clusters/Label-Cluster-UserLabelCluster.xml", + "${chip_root}/data_model/1.4/clusters/LaundryDryerControls.xml", + "${chip_root}/data_model/1.4/clusters/LaundryWasherControls.xml", + "${chip_root}/data_model/1.4/clusters/LevelControl.xml", + "${chip_root}/data_model/1.4/clusters/LocalizationConfiguration.xml", + "${chip_root}/data_model/1.4/clusters/LocalizationTimeFormat.xml", + "${chip_root}/data_model/1.4/clusters/LocalizationUnit.xml", + "${chip_root}/data_model/1.4/clusters/LowPower.xml", + "${chip_root}/data_model/1.4/clusters/MediaInput.xml", + "${chip_root}/data_model/1.4/clusters/MediaPlayback.xml", + "${chip_root}/data_model/1.4/clusters/Messages.xml", + "${chip_root}/data_model/1.4/clusters/MicrowaveOvenControl.xml", + "${chip_root}/data_model/1.4/clusters/ModeBase.xml", + "${chip_root}/data_model/1.4/clusters/ModeSelect.xml", + "${chip_root}/data_model/1.4/clusters/Mode_DeviceEnergyManagement.xml", + "${chip_root}/data_model/1.4/clusters/Mode_Dishwasher.xml", + "${chip_root}/data_model/1.4/clusters/Mode_EVSE.xml", + "${chip_root}/data_model/1.4/clusters/Mode_LaundryWasher.xml", + "${chip_root}/data_model/1.4/clusters/Mode_MicrowaveOven.xml", + "${chip_root}/data_model/1.4/clusters/Mode_Oven.xml", + "${chip_root}/data_model/1.4/clusters/Mode_RVCClean.xml", + "${chip_root}/data_model/1.4/clusters/Mode_RVCRun.xml", + "${chip_root}/data_model/1.4/clusters/Mode_Refrigerator.xml", + "${chip_root}/data_model/1.4/clusters/Mode_WaterHeater.xml", + "${chip_root}/data_model/1.4/clusters/NetworkCommissioningCluster.xml", + "${chip_root}/data_model/1.4/clusters/OTAProvider.xml", + "${chip_root}/data_model/1.4/clusters/OTARequestor.xml", + "${chip_root}/data_model/1.4/clusters/OccupancySensing.xml", + "${chip_root}/data_model/1.4/clusters/OnOff.xml", + "${chip_root}/data_model/1.4/clusters/OperationalCredentialCluster.xml", + "${chip_root}/data_model/1.4/clusters/OperationalState.xml", + "${chip_root}/data_model/1.4/clusters/OperationalState_Oven.xml", + "${chip_root}/data_model/1.4/clusters/OperationalState_RVC.xml", + "${chip_root}/data_model/1.4/clusters/PowerSourceCluster.xml", + "${chip_root}/data_model/1.4/clusters/PowerSourceConfigurationCluster.xml", + "${chip_root}/data_model/1.4/clusters/PowerTopology.xml", + "${chip_root}/data_model/1.4/clusters/PressureMeasurement.xml", + "${chip_root}/data_model/1.4/clusters/ProxyConfiguration-Cluster.xml", + "${chip_root}/data_model/1.4/clusters/ProxyDiscovery-Cluster.xml", + "${chip_root}/data_model/1.4/clusters/PumpConfigurationControl.xml", + "${chip_root}/data_model/1.4/clusters/RefrigeratorAlarm.xml", + "${chip_root}/data_model/1.4/clusters/ResourceMonitoring.xml", + "${chip_root}/data_model/1.4/clusters/Scenes.xml", + "${chip_root}/data_model/1.4/clusters/ServiceArea.xml", + "${chip_root}/data_model/1.4/clusters/SmokeCOAlarm.xml", + "${chip_root}/data_model/1.4/clusters/Switch.xml", + "${chip_root}/data_model/1.4/clusters/TargetNavigator.xml", + "${chip_root}/data_model/1.4/clusters/TemperatureControl.xml", + "${chip_root}/data_model/1.4/clusters/TemperatureMeasurement.xml", + "${chip_root}/data_model/1.4/clusters/Thermostat.xml", + "${chip_root}/data_model/1.4/clusters/ThermostatUserInterfaceConfiguration.xml", + "${chip_root}/data_model/1.4/clusters/ThreadBorderRouterManagement.xml", + "${chip_root}/data_model/1.4/clusters/ThreadNetworkDirectory.xml", + "${chip_root}/data_model/1.4/clusters/TimeSync.xml", + "${chip_root}/data_model/1.4/clusters/ValidProxies-Cluster.xml", + "${chip_root}/data_model/1.4/clusters/ValveConfigurationControl.xml", + "${chip_root}/data_model/1.4/clusters/WakeOnLAN.xml", + "${chip_root}/data_model/1.4/clusters/WaterContentMeasurement.xml", + "${chip_root}/data_model/1.4/clusters/WaterHeaterManagement.xml", + "${chip_root}/data_model/1.4/clusters/WiFiNetworkManagement.xml", + "${chip_root}/data_model/1.4/clusters/WindowCovering.xml", + "${chip_root}/data_model/1.4/clusters/bridge-clusters-ActionsCluster.xml", + "${chip_root}/data_model/1.4/clusters/bridge-clusters-BridgedDeviceBasicInformationCluster.xml", + "${chip_root}/data_model/1.4/clusters/cluster_ids.json", + "${chip_root}/data_model/1.4/device_types/Aggregator.xml", + "${chip_root}/data_model/1.4/device_types/AirPurifier.xml", + "${chip_root}/data_model/1.4/device_types/AirQualitySensor.xml", + "${chip_root}/data_model/1.4/device_types/BaseDeviceType.xml", + "${chip_root}/data_model/1.4/device_types/BasicVideoPlayer.xml", + "${chip_root}/data_model/1.4/device_types/BatteryStorage.xml", + "${chip_root}/data_model/1.4/device_types/BridgedNode.xml", + "${chip_root}/data_model/1.4/device_types/CastingVideoClient.xml", + "${chip_root}/data_model/1.4/device_types/CastingVideoPlayer.xml", + "${chip_root}/data_model/1.4/device_types/ColorDimmerSwitch.xml", + "${chip_root}/data_model/1.4/device_types/ColorTemperatureLight.xml", + "${chip_root}/data_model/1.4/device_types/ContactSensor.xml", + "${chip_root}/data_model/1.4/device_types/ContentApp.xml", + "${chip_root}/data_model/1.4/device_types/ControlBridge.xml", + "${chip_root}/data_model/1.4/device_types/CookSurface.xml", + "${chip_root}/data_model/1.4/device_types/Cooktop.xml", + "${chip_root}/data_model/1.4/device_types/DeviceEnergyManagement.xml", + "${chip_root}/data_model/1.4/device_types/DimmableLight.xml", + "${chip_root}/data_model/1.4/device_types/DimmablePlug-InUnit.xml", + "${chip_root}/data_model/1.4/device_types/DimmerSwitch.xml", + "${chip_root}/data_model/1.4/device_types/Dishwasher.xml", + "${chip_root}/data_model/1.4/device_types/DoorLock.xml", + "${chip_root}/data_model/1.4/device_types/DoorLockController.xml", + "${chip_root}/data_model/1.4/device_types/EVSE.xml", + "${chip_root}/data_model/1.4/device_types/ElectricalSensor.xml", + "${chip_root}/data_model/1.4/device_types/ExtendedColorLight.xml", + "${chip_root}/data_model/1.4/device_types/ExtractorHood.xml", + "${chip_root}/data_model/1.4/device_types/Fan.xml", + "${chip_root}/data_model/1.4/device_types/FlowSensor.xml", + "${chip_root}/data_model/1.4/device_types/GenericSwitch.xml", + "${chip_root}/data_model/1.4/device_types/HeatPump.xml", + "${chip_root}/data_model/1.4/device_types/HumiditySensor.xml", + "${chip_root}/data_model/1.4/device_types/JointFabricAdmin.xml", + "${chip_root}/data_model/1.4/device_types/LaundryDryer.xml", + "${chip_root}/data_model/1.4/device_types/LaundryWasher.xml", + "${chip_root}/data_model/1.4/device_types/LightSensor.xml", + "${chip_root}/data_model/1.4/device_types/MicrowaveOven.xml", + "${chip_root}/data_model/1.4/device_types/ModeSelectDeviceType.xml", + "${chip_root}/data_model/1.4/device_types/MountedDimmableLoadControl.xml", + "${chip_root}/data_model/1.4/device_types/MountedOnOffControl.xml", + "${chip_root}/data_model/1.4/device_types/NetworkInfraIntro.xml", + "${chip_root}/data_model/1.4/device_types/NetworkInfraManager.xml", + "${chip_root}/data_model/1.4/device_types/OccupancySensor.xml", + "${chip_root}/data_model/1.4/device_types/OnOffLight.xml", + "${chip_root}/data_model/1.4/device_types/OnOffLightSwitch.xml", + "${chip_root}/data_model/1.4/device_types/OnOffPlug-inUnit.xml", + "${chip_root}/data_model/1.4/device_types/OnOffSensor.xml", + "${chip_root}/data_model/1.4/device_types/OtaProvider.xml", + "${chip_root}/data_model/1.4/device_types/OtaRequestor.xml", + "${chip_root}/data_model/1.4/device_types/Oven.xml", + "${chip_root}/data_model/1.4/device_types/PowerSource.xml", + "${chip_root}/data_model/1.4/device_types/PressureSensor.xml", + "${chip_root}/data_model/1.4/device_types/Pump.xml", + "${chip_root}/data_model/1.4/device_types/PumpController.xml", + "${chip_root}/data_model/1.4/device_types/RainSensor.xml", + "${chip_root}/data_model/1.4/device_types/Refrigerator.xml", + "${chip_root}/data_model/1.4/device_types/RoboticVacuumCleaner.xml", + "${chip_root}/data_model/1.4/device_types/RoomAirConditioner.xml", + "${chip_root}/data_model/1.4/device_types/RootNodeDeviceType.xml", + "${chip_root}/data_model/1.4/device_types/SecondaryNetworkInterface.xml", + "${chip_root}/data_model/1.4/device_types/SmokeCOAlarm.xml", + "${chip_root}/data_model/1.4/device_types/SolarPower.xml", + "${chip_root}/data_model/1.4/device_types/Speaker.xml", + "${chip_root}/data_model/1.4/device_types/TemperatureControlledCabinet.xml", + "${chip_root}/data_model/1.4/device_types/TemperatureSensor.xml", + "${chip_root}/data_model/1.4/device_types/Thermostat.xml", + "${chip_root}/data_model/1.4/device_types/ThreadBorderRouter.xml", + "${chip_root}/data_model/1.4/device_types/VideoRemoteControl.xml", + "${chip_root}/data_model/1.4/device_types/WaterFreezeDetector.xml", + "${chip_root}/data_model/1.4/device_types/WaterHeater.xml", + "${chip_root}/data_model/1.4/device_types/WaterLeakDetector.xml", + "${chip_root}/data_model/1.4/device_types/WaterValve.xml", + "${chip_root}/data_model/1.4/device_types/WindowCovering.xml", + "${chip_root}/data_model/1.4/device_types/WindowCoveringController.xml", + "${chip_root}/data_model/master/clusters/ACL-Cluster.xml", + "${chip_root}/data_model/master/clusters/AccountLogin.xml", + "${chip_root}/data_model/master/clusters/AdminCommissioningCluster.xml", + "${chip_root}/data_model/master/clusters/AirQuality.xml", + "${chip_root}/data_model/master/clusters/AlarmBase.xml", + "${chip_root}/data_model/master/clusters/ApplicationBasic.xml", + "${chip_root}/data_model/master/clusters/ApplicationLauncher.xml", + "${chip_root}/data_model/master/clusters/AudioOutput.xml", + "${chip_root}/data_model/master/clusters/BallastConfiguration.xml", + "${chip_root}/data_model/master/clusters/BasicInformationCluster.xml", + "${chip_root}/data_model/master/clusters/Binding-Cluster.xml", + "${chip_root}/data_model/master/clusters/BooleanState.xml", + "${chip_root}/data_model/master/clusters/BooleanStateConfiguration.xml", + "${chip_root}/data_model/master/clusters/Channel.xml", + "${chip_root}/data_model/master/clusters/ColorControl.xml", + "${chip_root}/data_model/master/clusters/CommissionerControlCluster.xml", + "${chip_root}/data_model/master/clusters/ConcentrationMeasurement.xml", + "${chip_root}/data_model/master/clusters/ContentAppObserver.xml", + "${chip_root}/data_model/master/clusters/ContentControl.xml", + "${chip_root}/data_model/master/clusters/ContentLauncher.xml", + "${chip_root}/data_model/master/clusters/DemandResponseLoadControl.xml", + "${chip_root}/data_model/master/clusters/Descriptor-Cluster.xml", + "${chip_root}/data_model/master/clusters/DeviceEnergyManagement.xml", + "${chip_root}/data_model/master/clusters/DiagnosticLogsCluster.xml", + "${chip_root}/data_model/master/clusters/DiagnosticsEthernet.xml", + "${chip_root}/data_model/master/clusters/DiagnosticsGeneral.xml", + "${chip_root}/data_model/master/clusters/DiagnosticsSoftware.xml", + "${chip_root}/data_model/master/clusters/DiagnosticsThread.xml", + "${chip_root}/data_model/master/clusters/DiagnosticsWiFi.xml", + "${chip_root}/data_model/master/clusters/DishwasherAlarm.xml", + "${chip_root}/data_model/master/clusters/DoorLock.xml", + "${chip_root}/data_model/master/clusters/ElectricalEnergyMeasurement.xml", + "${chip_root}/data_model/master/clusters/ElectricalPowerMeasurement.xml", + "${chip_root}/data_model/master/clusters/EnergyCalendar.xml", + "${chip_root}/data_model/master/clusters/EnergyEVSE.xml", + "${chip_root}/data_model/master/clusters/EnergyPreference.xml", + "${chip_root}/data_model/master/clusters/EnergyPrice.xml", + "${chip_root}/data_model/master/clusters/FanControl.xml", + "${chip_root}/data_model/master/clusters/FlowMeasurement.xml", + "${chip_root}/data_model/master/clusters/GeneralCommissioningCluster.xml", + "${chip_root}/data_model/master/clusters/Group-Key-Management-Cluster.xml", + "${chip_root}/data_model/master/clusters/Groups.xml", + "${chip_root}/data_model/master/clusters/Humidistat.xml", + "${chip_root}/data_model/master/clusters/ICDManagement.xml", + "${chip_root}/data_model/master/clusters/Identify.xml", + "${chip_root}/data_model/master/clusters/IlluminanceMeasurement.xml", + "${chip_root}/data_model/master/clusters/JointFabricDatastoreCluster.xml", + "${chip_root}/data_model/master/clusters/JointFabricPKICluster.xml", + "${chip_root}/data_model/master/clusters/KeypadInput.xml", + "${chip_root}/data_model/master/clusters/Label-Cluster-FixedLabelCluster.xml", + "${chip_root}/data_model/master/clusters/Label-Cluster-LabelCluster.xml", + "${chip_root}/data_model/master/clusters/Label-Cluster-UserLabelCluster.xml", + "${chip_root}/data_model/master/clusters/LaundryDryerControls.xml", + "${chip_root}/data_model/master/clusters/LaundryWasherControls.xml", + "${chip_root}/data_model/master/clusters/LevelControl.xml", + "${chip_root}/data_model/master/clusters/LocalizationConfiguration.xml", + "${chip_root}/data_model/master/clusters/LocalizationTimeFormat.xml", + "${chip_root}/data_model/master/clusters/LocalizationUnit.xml", + "${chip_root}/data_model/master/clusters/LowPower.xml", + "${chip_root}/data_model/master/clusters/MediaInput.xml", + "${chip_root}/data_model/master/clusters/MediaPlayback.xml", + "${chip_root}/data_model/master/clusters/Messages.xml", + "${chip_root}/data_model/master/clusters/MeterIdentification.xml", + "${chip_root}/data_model/master/clusters/MicrowaveOvenControl.xml", + "${chip_root}/data_model/master/clusters/ModeBase.xml", + "${chip_root}/data_model/master/clusters/ModeSelect.xml", + "${chip_root}/data_model/master/clusters/Mode_DeviceEnergyManagement.xml", + "${chip_root}/data_model/master/clusters/Mode_Dishwasher.xml", + "${chip_root}/data_model/master/clusters/Mode_EVSE.xml", + "${chip_root}/data_model/master/clusters/Mode_LaundryWasher.xml", + "${chip_root}/data_model/master/clusters/Mode_MicrowaveOven.xml", + "${chip_root}/data_model/master/clusters/Mode_Oven.xml", + "${chip_root}/data_model/master/clusters/Mode_RVCClean.xml", + "${chip_root}/data_model/master/clusters/Mode_RVCRun.xml", + "${chip_root}/data_model/master/clusters/Mode_Refrigerator.xml", + "${chip_root}/data_model/master/clusters/Mode_WaterHeater.xml", + "${chip_root}/data_model/master/clusters/NetworkCommissioningCluster.xml", + "${chip_root}/data_model/master/clusters/NetworkIdentityManagement.xml", + "${chip_root}/data_model/master/clusters/OTAProvider.xml", + "${chip_root}/data_model/master/clusters/OTARequestor.xml", + "${chip_root}/data_model/master/clusters/OccupancySensing.xml", + "${chip_root}/data_model/master/clusters/OnOff.xml", + "${chip_root}/data_model/master/clusters/OperationalCredentialCluster.xml", + "${chip_root}/data_model/master/clusters/OperationalState.xml", + "${chip_root}/data_model/master/clusters/OperationalState_Oven.xml", + "${chip_root}/data_model/master/clusters/OperationalState_RVC.xml", + "${chip_root}/data_model/master/clusters/PowerSourceCluster.xml", + "${chip_root}/data_model/master/clusters/PowerSourceConfigurationCluster.xml", + "${chip_root}/data_model/master/clusters/PowerTopology.xml", + "${chip_root}/data_model/master/clusters/PressureMeasurement.xml", + "${chip_root}/data_model/master/clusters/ProxyConfiguration-Cluster.xml", + "${chip_root}/data_model/master/clusters/ProxyDiscovery-Cluster.xml", + "${chip_root}/data_model/master/clusters/PumpConfigurationControl.xml", + "${chip_root}/data_model/master/clusters/RefrigeratorAlarm.xml", + "${chip_root}/data_model/master/clusters/ResourceMonitoring.xml", + "${chip_root}/data_model/master/clusters/Scenes.xml", + "${chip_root}/data_model/master/clusters/ServiceArea.xml", + "${chip_root}/data_model/master/clusters/SmokeCOAlarm.xml", + "${chip_root}/data_model/master/clusters/Switch.xml", + "${chip_root}/data_model/master/clusters/TargetNavigator.xml", + "${chip_root}/data_model/master/clusters/TemperatureControl.xml", + "${chip_root}/data_model/master/clusters/TemperatureMeasurement.xml", + "${chip_root}/data_model/master/clusters/Thermostat.xml", + "${chip_root}/data_model/master/clusters/ThermostatUserInterfaceConfiguration.xml", + "${chip_root}/data_model/master/clusters/ThreadBorderRouterManagement.xml", + "${chip_root}/data_model/master/clusters/ThreadNetworkDirectory.xml", + "${chip_root}/data_model/master/clusters/TimeSync.xml", + "${chip_root}/data_model/master/clusters/ValidProxies-Cluster.xml", + "${chip_root}/data_model/master/clusters/ValveConfigurationControl.xml", + "${chip_root}/data_model/master/clusters/WakeOnLAN.xml", + "${chip_root}/data_model/master/clusters/WaterContentMeasurement.xml", + "${chip_root}/data_model/master/clusters/WaterHeaterManagement.xml", + "${chip_root}/data_model/master/clusters/WiFiNetworkManagement.xml", + "${chip_root}/data_model/master/clusters/WindowCovering.xml", + "${chip_root}/data_model/master/clusters/bridge-clusters-ActionsCluster.xml", + "${chip_root}/data_model/master/clusters/bridge-clusters-BridgedDeviceBasicInformationCluster.xml", + "${chip_root}/data_model/master/clusters/bridge-clusters-EcosystemInformationCluster.xml", + "${chip_root}/data_model/master/clusters/cluster_ids.json", + "${chip_root}/data_model/master/device_types/Aggregator.xml", + "${chip_root}/data_model/master/device_types/AirPurifier.xml", + "${chip_root}/data_model/master/device_types/AirQualitySensor.xml", + "${chip_root}/data_model/master/device_types/BaseDeviceType.xml", + "${chip_root}/data_model/master/device_types/BasicVideoPlayer.xml", + "${chip_root}/data_model/master/device_types/BatteryStorage.xml", + "${chip_root}/data_model/master/device_types/BridgedNode.xml", + "${chip_root}/data_model/master/device_types/CastingVideoClient.xml", + "${chip_root}/data_model/master/device_types/CastingVideoPlayer.xml", + "${chip_root}/data_model/master/device_types/ColorDimmerSwitch.xml", + "${chip_root}/data_model/master/device_types/ColorTemperatureLight.xml", + "${chip_root}/data_model/master/device_types/ContactSensor.xml", + "${chip_root}/data_model/master/device_types/ContentApp.xml", + "${chip_root}/data_model/master/device_types/ControlBridge.xml", + "${chip_root}/data_model/master/device_types/CookSurface.xml", + "${chip_root}/data_model/master/device_types/Cooktop.xml", + "${chip_root}/data_model/master/device_types/DeviceEnergyManagement.xml", + "${chip_root}/data_model/master/device_types/DimmableLight.xml", + "${chip_root}/data_model/master/device_types/DimmablePlug-InUnit.xml", + "${chip_root}/data_model/master/device_types/DimmerSwitch.xml", + "${chip_root}/data_model/master/device_types/Dishwasher.xml", + "${chip_root}/data_model/master/device_types/DoorLock.xml", + "${chip_root}/data_model/master/device_types/DoorLockController.xml", + "${chip_root}/data_model/master/device_types/EVSE.xml", + "${chip_root}/data_model/master/device_types/ElectricalSensor.xml", + "${chip_root}/data_model/master/device_types/EnergyTariff.xml", + "${chip_root}/data_model/master/device_types/EnergyTariffCalendar.xml", + "${chip_root}/data_model/master/device_types/ExtendedColorLight.xml", + "${chip_root}/data_model/master/device_types/ExtractorHood.xml", + "${chip_root}/data_model/master/device_types/Fan.xml", + "${chip_root}/data_model/master/device_types/FlowSensor.xml", + "${chip_root}/data_model/master/device_types/GenericSwitch.xml", + "${chip_root}/data_model/master/device_types/HeatPump.xml", + "${chip_root}/data_model/master/device_types/HumidifierDehumidifier.xml", + "${chip_root}/data_model/master/device_types/HumiditySensor.xml", + "${chip_root}/data_model/master/device_types/JointFabricAdmin.xml", + "${chip_root}/data_model/master/device_types/LaundryDryer.xml", + "${chip_root}/data_model/master/device_types/LaundryWasher.xml", + "${chip_root}/data_model/master/device_types/LightSensor.xml", + "${chip_root}/data_model/master/device_types/MicrowaveOven.xml", + "${chip_root}/data_model/master/device_types/ModeSelectDeviceType.xml", + "${chip_root}/data_model/master/device_types/MountedDimmableLoadControl.xml", + "${chip_root}/data_model/master/device_types/MountedOnOffControl.xml", + "${chip_root}/data_model/master/device_types/NetworkInfraIntro.xml", + "${chip_root}/data_model/master/device_types/NetworkInfraManager.xml", + "${chip_root}/data_model/master/device_types/OccupancySensor.xml", + "${chip_root}/data_model/master/device_types/OnOffLight.xml", + "${chip_root}/data_model/master/device_types/OnOffLightSwitch.xml", + "${chip_root}/data_model/master/device_types/OnOffPlug-inUnit.xml", + "${chip_root}/data_model/master/device_types/OnOffSensor.xml", + "${chip_root}/data_model/master/device_types/OtaProvider.xml", + "${chip_root}/data_model/master/device_types/OtaRequestor.xml", + "${chip_root}/data_model/master/device_types/Oven.xml", + "${chip_root}/data_model/master/device_types/PowerSource.xml", + "${chip_root}/data_model/master/device_types/PressureSensor.xml", + "${chip_root}/data_model/master/device_types/Pump.xml", + "${chip_root}/data_model/master/device_types/PumpController.xml", + "${chip_root}/data_model/master/device_types/RainSensor.xml", + "${chip_root}/data_model/master/device_types/Refrigerator.xml", + "${chip_root}/data_model/master/device_types/RoboticVacuumCleaner.xml", + "${chip_root}/data_model/master/device_types/RoomAirConditioner.xml", + "${chip_root}/data_model/master/device_types/RootNodeDeviceType.xml", + "${chip_root}/data_model/master/device_types/SecondaryNetworkInterface.xml", + "${chip_root}/data_model/master/device_types/SmokeCOAlarm.xml", + "${chip_root}/data_model/master/device_types/SolarPower.xml", + "${chip_root}/data_model/master/device_types/Speaker.xml", + "${chip_root}/data_model/master/device_types/TemperatureControlledCabinet.xml", + "${chip_root}/data_model/master/device_types/TemperatureSensor.xml", + "${chip_root}/data_model/master/device_types/Thermostat.xml", + "${chip_root}/data_model/master/device_types/ThreadBorderRouter.xml", + "${chip_root}/data_model/master/device_types/VideoRemoteControl.xml", + "${chip_root}/data_model/master/device_types/WaterFreezeDetector.xml", + "${chip_root}/data_model/master/device_types/WaterHeater.xml", + "${chip_root}/data_model/master/device_types/WaterLeakDetector.xml", + "${chip_root}/data_model/master/device_types/WaterValve.xml", + "${chip_root}/data_model/master/device_types/WindowCovering.xml", + "${chip_root}/data_model/master/device_types/WindowCoveringController.xml", +] diff --git a/src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py b/src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py new file mode 100644 index 00000000000000..76179797f5fe8c --- /dev/null +++ b/src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py @@ -0,0 +1,112 @@ +# Copyright (c) 2024 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. + +""" +Generates a gni file containing all data_model files (generally XML and JSON files) +that are typically used by matter_testing_infrastructure. + +These files are to be bundled with whl packages of the matter_testing_infrastructure +so that methods requiring data model files work just by installing the python +package without requiring a full chip SDK checkout. +""" +import os + +import jinja2 + +# Set chip_root to be dynamically based on the script's location +chip_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../..")) + +# Directories to search for .xml and .json files relative to chip_root +directories = [ + os.path.join(chip_root, "data_model/1.3/clusters/"), + os.path.join(chip_root, "data_model/1.3/device_types/"), + os.path.join(chip_root, "data_model/1.4/clusters/"), + os.path.join(chip_root, "data_model/1.4/device_types/"), + os.path.join(chip_root, "data_model/master/clusters/"), + os.path.join(chip_root, "data_model/master/device_types/"), +] + +# Template for generating the GNI file content with proper indentation +GNI_TEMPLATE = """\ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") + +data_model_XMLS = [ +{% for name in file_list %} + "{{ name }}", +{% endfor %} +] +""" + +# Function to find and collect all .xml and .json files + + +def get_data_model_file_names(): + file_list = [] + for directory in directories: + for root, _, files in os.walk(directory): + for file in files: + if file.endswith(".xml") or file.endswith(".json"): + # Replace absolute path with `${chip_root}` for GNI compatibility + relative_path = os.path.join("${chip_root}", os.path.relpath(root, chip_root), file) + file_list.append(relative_path) + # Sort files alphabetically + file_list.sort() + return file_list + +# Main function to generate the data_model_xmls.gni file + + +def generate_gni_file(): + # Step 1: Find all files and create the sorted file list + file_list = get_data_model_file_names() + + # Step 2: Render the template with the file list + environment = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) + template = environment.from_string(GNI_TEMPLATE) + output_content = template.render(file_list=file_list) + + # Step 3: Dynamically generate the output file path + # Get the script's directory (where this script is located) + script_dir = os.path.dirname(os.path.realpath(__file__)) # Directory of the current script + + # Step 4: Ensure we are in the correct `src/python_testing/` directory + base_dir = os.path.abspath(os.path.join(script_dir, "../..")) # Go up two levels to src/python_testing/ + # Now append `matter_testing_infrastructure` + output_dir = os.path.join(base_dir, "python_testing", "matter_testing_infrastructure") + output_file = os.path.join(output_dir, "data_model_xmls.gni") + + # Step 5: Write the rendered content to the output file + os.makedirs(output_dir, exist_ok=True) # Ensure the output directory exists + with open(output_file, "wt") as f: + f.write(output_content) + print(f"{output_file} has been generated successfully.") + + +# Run the function to generate the .gni file +if __name__ == "__main__": + generate_gni_file() diff --git a/src/python_testing/matter_testing_infrastructure/pyproject.toml b/src/python_testing/matter_testing_infrastructure/pyproject.toml deleted file mode 100644 index f62115ec75168a..00000000000000 --- a/src/python_testing/matter_testing_infrastructure/pyproject.toml +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright (c) 2024 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. - -[build-system] -requires = ['setuptools', 'wheel'] -build-backend = 'setuptools.build_meta' diff --git a/src/python_testing/matter_testing_infrastructure/setup.cfg b/src/python_testing/matter_testing_infrastructure/setup.cfg deleted file mode 100644 index 862236aa038746..00000000000000 --- a/src/python_testing/matter_testing_infrastructure/setup.cfg +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) 2024 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. - -[metadata] -name = chip-testing -version = 1.0.0 -author = Project CHIP Authors -license-expression = Apache-2.0 -description = Various helpers associated with the python_testing scripts -url = https://github.com/project-chip/connectedhomeip diff --git a/src/python_testing/matter_testing_infrastructure/setup.py b/src/python_testing/matter_testing_infrastructure/setup.py deleted file mode 100644 index ab0a7f39adca20..00000000000000 --- a/src/python_testing/matter_testing_infrastructure/setup.py +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright (c) 2024 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import setuptools # type: ignore - -setuptools.setup() # Package definition in setup.cfg diff --git a/src/python_testing/test_metadata.yaml b/src/python_testing/test_metadata.yaml new file mode 100644 index 00000000000000..3ff104a1a51f6b --- /dev/null +++ b/src/python_testing/test_metadata.yaml @@ -0,0 +1,102 @@ +# Tests that are NOT executed in CI, along with the reason on +# why they are not. +not_automated: + - name: MinimalRepresentation.py + reason: Code/Test not being used or not shared code for any other tests + - name: TC_CNET_4_4.py + reason: It has no CI execution block, is not executed in CI + - name: TC_DGGEN_3_2.py + reason: + src/python_testing/test_testing/test_TC_DGGEN_3_2.py is the Unit test + of this test + - name: TC_EEVSE_Utils.py + reason: Shared code for TC_EEVSE, not a standalone test + - name: TC_EWATERHTRBase.py + reason: Shared code for TC_EWATERHTR, not a standalone test + - name: TC_EnergyReporting_Utils.py + reason: Shared code for TC_EEM and TC_EPM, not a standalone test + - name: TC_OpstateCommon.py + reason: Shared code for TC_OPSTATE, not a standalone test + - name: TC_pics_checker.py + reason: + Currently isn't enabled because we don't have any examples with + conformant PICS + - name: TC_TMP_2_1.py + reason: + src/python_testing/test_testing/test_TC_TMP_2_1.py is the Unit test of + this test + - name: TC_OCC_3_1.py + reason: + There are CI issues for the test cases that implements manually + controlling sensor device for the occupancy state ON/OFF change + - name: TC_OCC_3_2.py + reason: + There are CI issues for the test cases that implements manually + controlling sensor device for the occupancy state ON/OFF change + - name: TestCommissioningTimeSync.py + reason: Code/Test not being used or not shared code for any other tests + - name: TestConformanceSupport.py + reason: Unit test - does not run against an app + - name: TestChoiceConformanceSupport.py + reason: Unit test - does not run against an app + - name: TC_DEMTestBase.py + reason: Shared code for TC_DEM, not a standalone test + - name: TestConformanceTest.py + reason: + Unit test of the conformance test (TC_DeviceConformance) - does not + run against an app + - name: TestIdChecks.py + reason: Unit test - does not run against an app + - name: TestSpecParsingDeviceType.py + reason: Unit test - does not run against an app + - name: TestConformanceTest.py + reason: Unit test - does not run against an app + - name: TestMatterTestingSupport.py + reason: Unit test - does not run against an app + - name: TestSpecParsingSupport.py + reason: Unit test - does not run against an app + - name: TestTimeSyncTrustedTimeSource.py + reason: + Unit test and shared code for + scripts/tests/TestTimeSyncTrustedTimeSourceRunner.py + - name: drlk_2_x_common.py + reason: Shared code for TC_DRLK, not a standalone test + - name: execute_python_tests.py + reason: + Python code that runs all the python tests from src/python_testing + (This code itself run via tests.yaml) + - name: hello_external_runner.py + reason: Code/Test not being used or not shared code for any other tests + - name: hello_test.py + reason: Is a template for tests + - name: test_plan_support.py + reason: Shared code for TC_*, not a standalone test + - name: test_plan_table_generator.py + reason: Code/Test not being used or not shared code for any other tests + +# This is a list of slow tests (just arbitrarely picked around 20 seconds) +# used in some script reporting for "be patient" messages as well as potentially +# to consider improving. May not be exhaustive +slow_tests: + - { name: mobile-device-test.py, duration: 3 minutes } + - { name: TC_AccessChecker.py, duration: 1.5 minutes } + - { name: TC_BRBINFO_4_1.py, duration: 2 minutes } + - { name: TC_CADMIN_1_9.py, duration: 40 seconds } + - { name: TC_CC_2_2.py, duration: 1.5 minutes } + - { name: TC_DEM_2_10.py, duration: 40 seconds } + - { name: TC_DeviceBasicComposition.py, duration: 25 seconds } + - { name: TC_DRLK_2_12.py, duration: 30 seconds } + - { name: TC_DRLK_2_3.py, duration: 30 seconds } + - { name: TC_EEVSE_2_6.py, duration: 30 seconds } + - { name: TC_FAN_3_1.py, duration: 15 seconds } + - { name: TC_MCORE_FS_1_4.py, duration: 20 seconds } + - { name: TC_OPSTATE_2_5.py, duration: 1.25 minutes } + - { name: TC_OPSTATE_2_6.py, duration: 35 seconds } + - { name: TC_PS_2_3.py, duration: 30 seconds } + - { name: TC_RR_1_1.py, duration: 25 seconds } + - { name: TC_SWTCH.py, duration: 1 minute } + - { name: TC_TIMESYNC_2_10.py, duration: 20 seconds } + - { name: TC_TIMESYNC_2_11.py, duration: 30 seconds } + - { name: TC_TIMESYNC_2_12.py, duration: 20 seconds } + - { name: TC_TIMESYNC_2_7.py, duration: 20 seconds } + - { name: TC_TIMESYNC_2_8.py, duration: 1.5 minutes } diff --git a/src/system/BUILD.gn b/src/system/BUILD.gn index a8d15cf83f4223..3de5ea84be11f5 100644 --- a/src/system/BUILD.gn +++ b/src/system/BUILD.gn @@ -99,7 +99,7 @@ buildconfig_header("system_buildconfig") { "CHIP_SYSTEM_CONFIG_USE_LWIP=${chip_system_config_use_lwip}", "CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT=${chip_system_config_use_open_thread_inet_endpoints}", "CHIP_SYSTEM_CONFIG_USE_SOCKETS=${chip_system_config_use_sockets}", - "CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK=false", + "CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK=${chip_system_config_use_network_framework}", "CHIP_SYSTEM_CONFIG_POSIX_LOCKING=${chip_system_config_posix_locking}", "CHIP_SYSTEM_CONFIG_FREERTOS_LOCKING=${chip_system_config_freertos_locking}", "CHIP_SYSTEM_CONFIG_MBED_LOCKING=${chip_system_config_mbed_locking}", diff --git a/src/system/SystemConfig.h b/src/system/SystemConfig.h index 58339df4be1e47..2fe0823922467e 100644 --- a/src/system/SystemConfig.h +++ b/src/system/SystemConfig.h @@ -768,7 +768,7 @@ struct LwIPEvent; * Defaults to enabled on platforms that use sockets other than Zephyr sockets. */ #ifndef CHIP_SYSTEM_CONFIG_USE_POSIX_SOCKETS -#if CHIP_SYSTEM_CONFIG_USE_SOCKETS && !CHIP_SYSTEM_CONFIG_USE_ZEPHYR_SOCKETS +#if (CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK) && !CHIP_SYSTEM_CONFIG_USE_ZEPHYR_SOCKETS #define CHIP_SYSTEM_CONFIG_USE_POSIX_SOCKETS 1 #else #define CHIP_SYSTEM_CONFIG_USE_POSIX_SOCKETS 0 diff --git a/src/system/SystemLayer.h b/src/system/SystemLayer.h index 75878ce6a81f50..9314ccd5609786 100644 --- a/src/system/SystemLayer.h +++ b/src/system/SystemLayer.h @@ -40,10 +40,10 @@ #include #include -#if CHIP_SYSTEM_CONFIG_USE_SOCKETS +#if CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK #include #include -#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS +#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_USE_NETWORK_FRAMEWORK #if CHIP_SYSTEM_CONFIG_USE_DISPATCH #include @@ -235,7 +235,7 @@ class LayerFreeRTOS : public Layer #endif // CHIP_SYSTEM_CONFIG_USE_LWIP -#if CHIP_SYSTEM_CONFIG_USE_SOCKETS +#if CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK class LayerSockets : public Layer { @@ -356,7 +356,7 @@ class LayerSocketsLoop : public LayerSockets decltype(EventLoopHandler::mState) & LoopHandlerState(EventLoopHandler & handler) { return handler.mState; } }; -#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS +#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK } // namespace System } // namespace chip diff --git a/src/system/SystemLayerImplSelect.cpp b/src/system/SystemLayerImplSelect.cpp index fe025a5765e659..52354f99d82ff0 100644 --- a/src/system/SystemLayerImplSelect.cpp +++ b/src/system/SystemLayerImplSelect.cpp @@ -67,10 +67,10 @@ CHIP_ERROR LayerImplSelect::Init() mHandleSelectThread = PTHREAD_NULL; #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING -#if !CHIP_SYSTEM_CONFIG_USE_LIBEV +#if !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK // Create an event to allow an arbitrary thread to wake the thread in the select loop. ReturnErrorOnFailure(mWakeEvent.Open(*this)); -#endif // !CHIP_SYSTEM_CONFIG_USE_LIBEV +#endif // !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK VerifyOrReturnError(mLayerState.SetInitialized(), CHIP_ERROR_INCORRECT_STATE); return CHIP_NO_ERROR; @@ -116,9 +116,9 @@ void LayerImplSelect::Shutdown() mTimerPool.ReleaseAll(); #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH/LIBEV -#if !CHIP_SYSTEM_CONFIG_USE_LIBEV +#if !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK mWakeEvent.Close(*this); -#endif // !CHIP_SYSTEM_CONFIG_USE_LIBEV +#endif // !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK mLayerState.ResetFromShuttingDown(); // Return to uninitialized state to permit re-initialization. } @@ -127,6 +127,8 @@ void LayerImplSelect::Signal() { #if CHIP_SYSTEM_CONFIG_USE_LIBEV ChipLogError(DeviceLayer, "Signal() should not be called in CHIP_SYSTEM_CONFIG_USE_LIBEV builds (might be ok in tests)"); +#elif CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK + ChipLogError(DeviceLayer, "Signal() should not be called in CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK builds"); #else /* * Wake up the I/O thread by writing a single byte to the wake pipe. @@ -151,7 +153,7 @@ void LayerImplSelect::Signal() ChipLogError(chipSystemLayer, "System wake event notify failed: %" CHIP_ERROR_FORMAT, status.Format()); } -#endif // !CHIP_SYSTEM_CONFIG_USE_LIBEV +#endif // !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK } CHIP_ERROR LayerImplSelect::StartTimer(Clock::Timeout delay, TimerCompleteCallback onComplete, void * appState) @@ -188,6 +190,9 @@ CHIP_ERROR LayerImplSelect::StartTimer(Clock::Timeout delay, TimerCompleteCallba dispatch_resume(timerSource); return CHIP_NO_ERROR; } +#if CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK + return CHIP_ERROR_INTERNAL; +#endif // CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK #elif CHIP_SYSTEM_CONFIG_USE_LIBEV VerifyOrDie(mLibEvLoopP != nullptr); ev_timer_init(&timer->mLibEvTimer, &LayerImplSelect::HandleLibEvTimer, 1, 0); @@ -205,15 +210,18 @@ CHIP_ERROR LayerImplSelect::StartTimer(Clock::Timeout delay, TimerCompleteCallba ev_timer_start(mLibEvLoopP, &timer->mLibEvTimer); return CHIP_NO_ERROR; #endif -#if !CHIP_SYSTEM_CONFIG_USE_LIBEV - // Note: dispatch based implementation needs this as fallback, but not LIBEV (and dead code is not allowed with -Werror) +#if !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK + // Note: The dispatch-based implementation (using sockets but not Network.framework) requires this as a fallback + // for testing purposes. However, it is not needed for LIBEV or when using Network.framework (which lacks a testing + // configuration). Since dead code is also not allowed with -Werror, we need to ifdef this code out + // in those configurations. if (mTimerList.Add(timer) == timer) { // The new timer is the earliest, so the time until the next event has probably changed. Signal(); } return CHIP_NO_ERROR; -#endif // !CHIP_SYSTEM_CONFIG_USE_LIBEV +#endif // !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK } CHIP_ERROR LayerImplSelect::ExtendTimerTo(Clock::Timeout delay, TimerCompleteCallback onComplete, void * appState) @@ -290,8 +298,8 @@ void LayerImplSelect::CancelTimer(TimerCompleteCallback onComplete, void * appSt #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH/LIBEV mTimerPool.Release(timer); -#if !CHIP_SYSTEM_CONFIG_USE_LIBEV - // LIBEV has no I/O wakeup thread, so must not call Signal() +#if !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK + // Neither LIBEV nor CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK builds include an I/O wakeup thread, so must not call Signal(). Signal(); #endif } @@ -311,6 +319,9 @@ CHIP_ERROR LayerImplSelect::ScheduleWork(TimerCompleteCallback onComplete, void }); return CHIP_NO_ERROR; } +#if CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK + return CHIP_ERROR_INTERNAL; +#endif // CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK #elif CHIP_SYSTEM_CONFIG_USE_LIBEV // schedule as timer with no delay, but do NOT cancel previous timers with same onComplete/appState! TimerList::Node * timer = mTimerPool.Create(*this, SystemClock().GetMonotonicTimestamp(), onComplete, appState); @@ -324,8 +335,11 @@ CHIP_ERROR LayerImplSelect::ScheduleWork(TimerCompleteCallback onComplete, void ev_timer_start(mLibEvLoopP, &timer->mLibEvTimer); return CHIP_NO_ERROR; #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH/LIBEV -#if !CHIP_SYSTEM_CONFIG_USE_LIBEV - // Note: dispatch based implementation needs this as fallback, but not LIBEV (and dead code is not allowed with -Werror) +#if !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK + // Note: The dispatch-based implementation (using sockets but not Network.framework) requires this as a fallback + // for testing purposes. However, it is not needed for LIBEV or when using Network.framework (which lacks a testing + // configuration). Since dead code is also not allowed with -Werror, we need to ifdef this code out + // in those configurations. // Ideally we would not use a timer here at all, but if we try to just // ScheduleLambda the lambda needs to capture the following: // 1) onComplete @@ -360,7 +374,7 @@ CHIP_ERROR LayerImplSelect::ScheduleWork(TimerCompleteCallback onComplete, void Signal(); } return CHIP_NO_ERROR; -#endif // !CHIP_SYSTEM_CONFIG_USE_LIBEV +#endif // !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK } CHIP_ERROR LayerImplSelect::StartWatchingSocket(int fd, SocketWatchToken * tokenOut) diff --git a/src/system/SystemLayerImplSelect.h b/src/system/SystemLayerImplSelect.h index ce34ece0115b9b..d2f8c880ee50da 100644 --- a/src/system/SystemLayerImplSelect.h +++ b/src/system/SystemLayerImplSelect.h @@ -158,7 +158,7 @@ class LayerImplSelect : public LayerSocketsLoop int mSelectResult; ObjectLifeCycle mLayerState; -#if !CHIP_SYSTEM_CONFIG_USE_LIBEV +#if !CHIP_SYSTEM_CONFIG_USE_LIBEV && !CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK WakeEvent mWakeEvent; #endif diff --git a/src/system/SystemPacketBuffer.cpp b/src/system/SystemPacketBuffer.cpp index 79e1bd25a67d8a..f644d1a23eb323 100644 --- a/src/system/SystemPacketBuffer.cpp +++ b/src/system/SystemPacketBuffer.cpp @@ -620,7 +620,6 @@ PacketBufferHandle PacketBufferHandle::New(size_t aAvailableSize, uint16_t aRese // checked to fit in a size_t. const size_t lBlockSize = static_cast(sumOfSizes); lPacket = reinterpret_cast(chip::Platform::MemoryAlloc(lBlockSize)); - SYSTEM_STATS_INCREMENT(chip::System::Stats::kSystemLayer_NumPacketBufs); #else #error "Unimplemented PacketBuffer storage case" @@ -632,6 +631,8 @@ PacketBufferHandle PacketBufferHandle::New(size_t aAvailableSize, uint16_t aRese return PacketBufferHandle(); } + SYSTEM_STATS_INCREMENT(chip::System::Stats::kSystemLayer_NumPacketBufs); + lPacket->payload = lPacket->ReserveStart() + aReservedSize; lPacket->len = lPacket->tot_len = 0; lPacket->next = nullptr; diff --git a/src/system/system.gni b/src/system/system.gni index 61cd52fa320245..e58f32914695b6 100644 --- a/src/system/system.gni +++ b/src/system/system.gni @@ -20,8 +20,8 @@ declare_args() { # Use the lwIP library. chip_system_config_use_lwip = chip_with_lwip && current_os == "freertos" - # Use BSD/POSIX socket API. - chip_system_config_use_sockets = current_os != "freertos" + # Use Network.framework API + chip_system_config_use_network_framework = false # Mutex implementation: posix, freertos, none. chip_system_config_locking = "" @@ -36,13 +36,21 @@ declare_args() { chip_system_config_use_open_thread_inet_endpoints = false } +declare_args() { + # Use BSD/POSIX socket API. + chip_system_config_use_sockets = + current_os != "freertos" && !chip_system_config_use_network_framework +} + declare_args() { # do not use libev by default chip_system_config_use_libev = false # use the dispatch library on darwin targets - chip_system_config_use_dispatch = chip_system_config_use_sockets && - (current_os == "mac" || current_os == "ios") + chip_system_config_use_dispatch = + (chip_system_config_use_sockets || + chip_system_config_use_network_framework) && + (current_os == "mac" || current_os == "ios") } declare_args() { diff --git a/src/test_driver/efr32/args.gni b/src/test_driver/efr32/args.gni index c4bc72c2a3cd97..0cdcbbf8df1050 100644 --- a/src/test_driver/efr32/args.gni +++ b/src/test_driver/efr32/args.gni @@ -30,8 +30,8 @@ openthread_external_platform = pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" -pw_assert_BACKEND = "$dir_pw_assert_log" -pw_log_BACKEND = "$dir_pw_log_basic" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" pw_unit_test_BACKEND = "$dir_pw_unit_test:light" diff --git a/src/test_driver/linux-cirque/IcdWaitForActiveTest.py b/src/test_driver/linux-cirque/IcdDeviceTest.py similarity index 93% rename from src/test_driver/linux-cirque/IcdWaitForActiveTest.py rename to src/test_driver/linux-cirque/IcdDeviceTest.py index bb2c1cb8384a3c..b4786897423bd6 100755 --- a/src/test_driver/linux-cirque/IcdWaitForActiveTest.py +++ b/src/test_driver/linux-cirque/IcdDeviceTest.py @@ -43,6 +43,8 @@ TEST_DISCOVERY_TYPE = [0, 1, 2] MATTER_DEVELOPMENT_PAA_ROOT_CERTS = "credentials/development/paa-root-certs" +TEST_EVENT_KEY_HEX = "00112233445566778899aabbccddeeff" + DEVICE_CONFIG = { 'device0': { 'type': 'MobileDevice', @@ -88,8 +90,8 @@ def run_controller_test(self): self.execute_device_cmd( server, ("CHIPCirqueDaemon.py -- run gdb -batch -return-child-result -q -ex \"set pagination off\" " - "-ex run -ex \"thread apply all bt\" --args {} --thread --discriminator {}").format( - os.path.join(CHIP_REPO, "out/debug/lit_icd/lit-icd-app"), TEST_DISCRIMINATOR)) + "-ex run -ex \"thread apply all bt\" --args {} --thread --discriminator {} --enable-key {}").format( + os.path.join(CHIP_REPO, "out/debug/lit_icd/lit-icd-app"), TEST_DISCRIMINATOR, TEST_EVENT_KEY_HEX)) self.reset_thread_devices(server_ids) @@ -103,10 +105,10 @@ def run_controller_test(self): CHIP_REPO, "out/debug/linux_x64_gcc/controller/python/chip_repl-0.0-py3-none-any.whl"))) command = ("gdb -batch -return-child-result -q -ex run -ex \"thread apply all bt\" " - "--args python3 {} -t 300 -a {} --paa-trust-store-path {}").format( + "--args python3 {} -t 300 -a {} --paa-trust-store-path {} --test-event-key {}").format( os.path.join( - CHIP_REPO, "src/controller/python/test/test_scripts/icd_wait_for_device_test.py"), ethernet_ip, - os.path.join(CHIP_REPO, MATTER_DEVELOPMENT_PAA_ROOT_CERTS)) + CHIP_REPO, "src/controller/python/test/test_scripts/icd_device_test.py"), ethernet_ip, + os.path.join(CHIP_REPO, MATTER_DEVELOPMENT_PAA_ROOT_CERTS), TEST_EVENT_KEY_HEX) ret = self.execute_device_cmd(req_device_id, command) self.assertEqual(ret['return_code'], '0', diff --git a/src/test_driver/linux-cirque/helper/CHIPTestBase.py b/src/test_driver/linux-cirque/helper/CHIPTestBase.py index ea45a62221e7e5..a6756b4800ee24 100644 --- a/src/test_driver/linux-cirque/helper/CHIPTestBase.py +++ b/src/test_driver/linux-cirque/helper/CHIPTestBase.py @@ -143,7 +143,7 @@ def reset_thread_devices(self, devices: Union[List[str], str]): for device_id in devices: # Wait for otbr-agent and CHIP server start self.assertTrue(self.wait_for_device_output( - device_id, "Thread Border Router started on AIL", 10)) + device_id, "Thread interface: wpan0", 10)) self.assertTrue(self.wait_for_device_output( device_id, "[SVR] Server Listening...", 15)) # Clear default Thread network commissioning data diff --git a/src/tracing/perfetto/perfetto_tracing.cpp b/src/tracing/perfetto/perfetto_tracing.cpp index f9b00cc7ad96d3..d83007826f6e39 100644 --- a/src/tracing/perfetto/perfetto_tracing.cpp +++ b/src/tracing/perfetto/perfetto_tracing.cpp @@ -133,19 +133,19 @@ void PerfettoBackend::LogMetricEvent(const MetricEvent & event) switch (event.ValueType()) { case ValueType::kInt32: - TRACE_EVENT_INSTANT("Matter", event.key(), "value", event.ValueInt32()); + TRACE_EVENT_INSTANT("Matter", perfetto::DynamicString(event.key()), "value", event.ValueInt32()); break; case ValueType::kUInt32: - TRACE_EVENT_INSTANT("Matter", event.key(), "value", event.ValueUInt32()); + TRACE_EVENT_INSTANT("Matter", perfetto::DynamicString(event.key()), "value", event.ValueUInt32()); break; case ValueType::kChipErrorCode: - TRACE_EVENT_INSTANT("Matter", event.key(), "error", event.ValueErrorCode()); + TRACE_EVENT_INSTANT("Matter", perfetto::DynamicString(event.key()), "error", event.ValueErrorCode()); break; case ValueType::kUndefined: - TRACE_EVENT_INSTANT("Matter", event.key()); + TRACE_EVENT_INSTANT("Matter", perfetto::DynamicString(event.key())); break; default: - TRACE_EVENT_INSTANT("Matter", event.key(), "type", "UNKNOWN"); + TRACE_EVENT_INSTANT("Matter", perfetto::DynamicString(event.key()), "type", "UNKNOWN"); break; } } diff --git a/third_party/silabs/SiWx917_sdk.gni b/third_party/silabs/SiWx917_sdk.gni index ab94c6372d18e0..0bc8c7c69318c4 100644 --- a/third_party/silabs/SiWx917_sdk.gni +++ b/third_party/silabs/SiWx917_sdk.gni @@ -19,7 +19,7 @@ import("//build_overrides/mbedtls.gni") import("${chip_root}/src/app/icd/icd.gni") import("${chip_root}/src/crypto/crypto.gni") import("${chip_root}/src/lib/lib.gni") -import("${chip_root}/src/platform/silabs/wifi_args.gni") +import("${chip_root}/src/platform/silabs/wifi/args.gni") import("${silabs_sdk_build_root}/efr32_sdk.gni") import("silabs_board.gni") @@ -321,9 +321,12 @@ template("siwx917_sdk") { "SL_ACTIVE_MODE_DURATION_MS=${sl_active_mode_duration_ms}", "SL_IDLE_MODE_DURATION_S=${sl_idle_mode_duration_s}", "SL_ICD_SUPPORTED_CLIENTS_PER_FABRIC=${sl_icd_supported_clients_per_fabric}", - "SL_SI91X_NPSS_GPIO_BTN_HANDLER=1", "SL_SI91X_POWER_MANAGER_UC_AVAILABLE=1", "SL_SI91X_TICKLESS_MODE=1", + + # Enable Wakeup source for ICD + "SL_ENABLE_GPIO_WAKEUP_SOURCE=1", + "ENABLE_NPSS_GPIO_2=1", ] } diff --git a/third_party/silabs/efr32_sdk.gni b/third_party/silabs/efr32_sdk.gni index 146077372f4cc6..9ca85baa47bf5b 100644 --- a/third_party/silabs/efr32_sdk.gni +++ b/third_party/silabs/efr32_sdk.gni @@ -96,6 +96,7 @@ declare_args() { examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" silabs_plat_efr32_wifi_dir = "${chip_root}/src/platform/silabs/efr32/wifi" silabs_common_plat_dir = "${chip_root}/examples/platform/silabs" +silabs_platform_dir = "${chip_root}/src/platform/silabs" is_series_2 = silabs_family == "mgm24" || silabs_family == "efr32mg24" || silabs_family == "efr32mg26" @@ -333,6 +334,7 @@ template("efr32_sdk") { "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/firmware", "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/pds/brd8022a", "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/secure_link", + "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/config", ] } @@ -365,12 +367,23 @@ template("efr32_sdk") { "${wifi_sdk_root}/components/protocol/wifi/si91x", ] } + + if (use_rs9116) { + # TODO: we should create a seperate directory for headers that are necessary for the underlying sdks + _include_dirs += [ + "${chip_root}/src/platform/silabs/wifi/rs911x/platform", + "${chip_root}/src/platform/silabs/wifi/rs911x", + ] + } + if (use_rs9116 || use_SiWx917) { _include_dirs += [ "${chip_root}/src/platform/silabs/rs911x" ] } + if (use_wf200 || use_rs9116 || use_SiWx917) { _include_dirs += [ "${chip_root}/src/platform/silabs/wifi" ] } + if (silabs_family != "mgm24") { _include_dirs += [ "${efr32_sdk_root}/platform/radio/rail_lib/hal", @@ -583,7 +596,7 @@ template("efr32_sdk") { } if (use_wf200 || use_rs9116 || use_SiWx917) { - import("${chip_root}/src/platform/silabs/wifi_args.gni") + import("${chip_root}/src/platform/silabs/wifi/args.gni") defines += [ "LWIP_NETIF_API=1" ] if (chip_enable_wifi_ipv4) { diff --git a/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.cpp b/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.cpp index a1caa8052ae71e..afb3da76dc8bc3 100644 --- a/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.cpp +++ b/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.cpp @@ -37487,147 +37487,6 @@ Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters } // namespace NightVisionIllum -namespace AWBEnabled { - -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value) -{ - using Traits = NumericAttributeTraits; - Traits::StorageType temp; - uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); - Protocols::InteractionModel::Status status = - emberAfReadAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, readable, sizeof(temp)); - VerifyOrReturnError(Protocols::InteractionModel::Status::Success == status, status); - if (!Traits::CanRepresentValue(/* isNullable = */ false, temp)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - *value = Traits::StorageToWorking(temp); - return status; -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(ConcreteAttributePath(endpoint, Clusters::CameraAvStreamManagement::Id, Id), - EmberAfWriteDataInput(writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE).SetMarkDirty(markDirty)); -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE); -} - -} // namespace AWBEnabled - -namespace AutoShutterSpeedEnabled { - -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value) -{ - using Traits = NumericAttributeTraits; - Traits::StorageType temp; - uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); - Protocols::InteractionModel::Status status = - emberAfReadAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, readable, sizeof(temp)); - VerifyOrReturnError(Protocols::InteractionModel::Status::Success == status, status); - if (!Traits::CanRepresentValue(/* isNullable = */ false, temp)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - *value = Traits::StorageToWorking(temp); - return status; -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(ConcreteAttributePath(endpoint, Clusters::CameraAvStreamManagement::Id, Id), - EmberAfWriteDataInput(writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE).SetMarkDirty(markDirty)); -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE); -} - -} // namespace AutoShutterSpeedEnabled - -namespace AutoISOEnabled { - -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value) -{ - using Traits = NumericAttributeTraits; - Traits::StorageType temp; - uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); - Protocols::InteractionModel::Status status = - emberAfReadAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, readable, sizeof(temp)); - VerifyOrReturnError(Protocols::InteractionModel::Status::Success == status, status); - if (!Traits::CanRepresentValue(/* isNullable = */ false, temp)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - *value = Traits::StorageToWorking(temp); - return status; -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(ConcreteAttributePath(endpoint, Clusters::CameraAvStreamManagement::Id, Id), - EmberAfWriteDataInput(writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE).SetMarkDirty(markDirty)); -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE); -} - -} // namespace AutoISOEnabled - namespace SpeakerMuted { Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value) @@ -38381,55 +38240,6 @@ Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters } // namespace StatusLightBrightness -namespace DepthSensorStatus { - -Protocols::InteractionModel::Status Get(EndpointId endpoint, - chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum * value) -{ - using Traits = NumericAttributeTraits; - Traits::StorageType temp; - uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); - Protocols::InteractionModel::Status status = - emberAfReadAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, readable, sizeof(temp)); - VerifyOrReturnError(Protocols::InteractionModel::Status::Success == status, status); - if (!Traits::CanRepresentValue(/* isNullable = */ false, temp)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - *value = Traits::StorageToWorking(temp); - return status; -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum value, - MarkAttributeDirty markDirty) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(ConcreteAttributePath(endpoint, Clusters::CameraAvStreamManagement::Id, Id), - EmberAfWriteDataInput(writable, ZCL_ENUM8_ATTRIBUTE_TYPE).SetMarkDirty(markDirty)); -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum value) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, writable, ZCL_ENUM8_ATTRIBUTE_TYPE); -} - -} // namespace DepthSensorStatus - namespace FeatureMap { Protocols::InteractionModel::Status Get(EndpointId endpoint, uint32_t * value) diff --git a/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.h b/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.h index bb11fdf51607d1..c79c0657c5b11b 100644 --- a/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.h +++ b/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.h @@ -5683,24 +5683,6 @@ Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters MarkAttributeDirty markDirty); } // namespace NightVisionIllum -namespace AWBEnabled { -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value); // boolean -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value); -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty); -} // namespace AWBEnabled - -namespace AutoShutterSpeedEnabled { -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value); // boolean -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value); -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty); -} // namespace AutoShutterSpeedEnabled - -namespace AutoISOEnabled { -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value); // boolean -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value); -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty); -} // namespace AutoISOEnabled - namespace SpeakerMuted { Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value); // boolean Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value); @@ -5799,14 +5781,6 @@ Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters MarkAttributeDirty markDirty); } // namespace StatusLightBrightness -namespace DepthSensorStatus { -Protocols::InteractionModel::Status -Get(EndpointId endpoint, chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum * value); // TriStateAutoEnum -Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum value); -Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum value, - MarkAttributeDirty markDirty); -} // namespace DepthSensorStatus - namespace FeatureMap { Protocols::InteractionModel::Status Get(EndpointId endpoint, uint32_t * value); // bitmap32 Protocols::InteractionModel::Status Set(EndpointId endpoint, uint32_t value); diff --git a/zzz_generated/app-common/app-common/zap-generated/callback.h b/zzz_generated/app-common/app-common/zap-generated/callback.h index 430eb0bd3821fd..1c8cccc476c6dd 100644 --- a/zzz_generated/app-common/app-common/zap-generated/callback.h +++ b/zzz_generated/app-common/app-common/zap-generated/callback.h @@ -6852,30 +6852,6 @@ bool emberAfCameraAvStreamManagementClusterSetStreamPrioritiesCallback( bool emberAfCameraAvStreamManagementClusterCaptureSnapshotCallback( chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, const chip::app::Clusters::CameraAvStreamManagement::Commands::CaptureSnapshot::DecodableType & commandData); -/** - * @brief Camera AV Stream Management Cluster SetViewport Command callback (from client) - */ -bool emberAfCameraAvStreamManagementClusterSetViewportCallback( - chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::DecodableType & commandData); -/** - * @brief Camera AV Stream Management Cluster SetImageRotation Command callback (from client) - */ -bool emberAfCameraAvStreamManagementClusterSetImageRotationCallback( - chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::DecodableType & commandData); -/** - * @brief Camera AV Stream Management Cluster SetImageFlipHorizontal Command callback (from client) - */ -bool emberAfCameraAvStreamManagementClusterSetImageFlipHorizontalCallback( - chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::DecodableType & commandData); -/** - * @brief Camera AV Stream Management Cluster SetImageFlipVertical Command callback (from client) - */ -bool emberAfCameraAvStreamManagementClusterSetImageFlipVerticalCallback( - chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::DecodableType & commandData); /** * @brief WebRTC Transport Provider Cluster SolicitOffer Command callback (from client) */ diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h b/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h index 586eeb91aff695..aae67302e404a0 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h @@ -5526,6 +5526,7 @@ enum class ZoneUseEnum : uint8_t enum class Feature : uint32_t { kTwoDimensionalCartesianZone = 0x1, + kPerZoneSensitivity = 0x2, }; } // namespace ZoneManagement @@ -5599,12 +5600,12 @@ enum class VideoCodecEnum : uint8_t // Bitmap for Feature enum class Feature : uint32_t { - kPrivacy = 0x1, - kAudio = 0x2, - kSpeaker = 0x4, - kImageControl = 0x8, - kVideo = 0x10, - kSnapshot = 0x20, + kAudio = 0x1, + kVideo = 0x2, + kSnapshot = 0x4, + kPrivacy = 0x8, + kSpeaker = 0x10, + kImageControl = 0x20, kWatermark = 0x40, kOnScreenDisplay = 0x80, kLocalStorage = 0x100, diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp index 111324e9cb51ae..4879ae5213c65d 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp @@ -28541,7 +28541,7 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } // namespace ZoneInformationStruct -namespace ZoneTriggeringTimeControlStruct { +namespace ZoneTriggerControlStruct { CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; @@ -28549,6 +28549,7 @@ CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const encoder.Encode(to_underlying(Fields::kAugmentationDuration), augmentationDuration); encoder.Encode(to_underlying(Fields::kMaxDuration), maxDuration); encoder.Encode(to_underlying(Fields::kBlindDuration), blindDuration); + encoder.Encode(to_underlying(Fields::kSensitivity), sensitivity); return encoder.Finalize(); } @@ -28582,6 +28583,10 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) { err = DataModel::Decode(reader, blindDuration); } + else if (__context_tag == to_underlying(Fields::kSensitivity)) + { + err = DataModel::Decode(reader, sensitivity); + } else { } @@ -28590,7 +28595,7 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } -} // namespace ZoneTriggeringTimeControlStruct +} // namespace ZoneTriggerControlStruct } // namespace Structs namespace Commands { @@ -28814,8 +28819,8 @@ CHIP_ERROR TypeInfo::DecodableType::Decode(TLV::TLVReader & reader, const Concre return DataModel::Decode(reader, supportedZoneSources); case Attributes::Zones::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, zones); - case Attributes::TimeControl::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, timeControl); + case Attributes::Triggers::TypeInfo::GetAttributeId(): + return DataModel::Decode(reader, triggers); case Attributes::Sensitivity::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, sensitivity); case Attributes::GeneratedCommandList::TypeInfo::GetAttributeId(): @@ -29744,7 +29749,7 @@ CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const { DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; encoder.Encode(to_underlying(Fields::kImageCodec), imageCodec); - encoder.Encode(to_underlying(Fields::kFrameRate), frameRate); + encoder.Encode(to_underlying(Fields::kMaxFrameRate), maxFrameRate); encoder.Encode(to_underlying(Fields::kBitRate), bitRate); encoder.Encode(to_underlying(Fields::kMinResolution), minResolution); encoder.Encode(to_underlying(Fields::kMaxResolution), maxResolution); @@ -29770,9 +29775,9 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) { err = DataModel::Decode(reader, imageCodec); } - else if (__context_tag == to_underlying(Fields::kFrameRate)) + else if (__context_tag == to_underlying(Fields::kMaxFrameRate)) { - err = DataModel::Decode(reader, frameRate); + err = DataModel::Decode(reader, maxFrameRate); } else if (__context_tag == to_underlying(Fields::kBitRate)) { @@ -29983,142 +29988,6 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } } // namespace CaptureSnapshotResponse. -namespace SetViewport { -CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const -{ - DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; - encoder.Encode(to_underlying(Fields::kViewport), viewport); - return encoder.Finalize(); -} - -CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) -{ - detail::StructDecodeIterator __iterator(reader); - while (true) - { - auto __element = __iterator.Next(); - if (std::holds_alternative(__element)) - { - return std::get(__element); - } - - CHIP_ERROR err = CHIP_NO_ERROR; - const uint8_t __context_tag = std::get(__element); - - if (__context_tag == to_underlying(Fields::kViewport)) - { - err = DataModel::Decode(reader, viewport); - } - else - { - } - - ReturnErrorOnFailure(err); - } -} -} // namespace SetViewport. -namespace SetImageRotation { -CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const -{ - DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; - encoder.Encode(to_underlying(Fields::kAngle), angle); - return encoder.Finalize(); -} - -CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) -{ - detail::StructDecodeIterator __iterator(reader); - while (true) - { - auto __element = __iterator.Next(); - if (std::holds_alternative(__element)) - { - return std::get(__element); - } - - CHIP_ERROR err = CHIP_NO_ERROR; - const uint8_t __context_tag = std::get(__element); - - if (__context_tag == to_underlying(Fields::kAngle)) - { - err = DataModel::Decode(reader, angle); - } - else - { - } - - ReturnErrorOnFailure(err); - } -} -} // namespace SetImageRotation. -namespace SetImageFlipHorizontal { -CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const -{ - DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; - encoder.Encode(to_underlying(Fields::kEnabled), enabled); - return encoder.Finalize(); -} - -CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) -{ - detail::StructDecodeIterator __iterator(reader); - while (true) - { - auto __element = __iterator.Next(); - if (std::holds_alternative(__element)) - { - return std::get(__element); - } - - CHIP_ERROR err = CHIP_NO_ERROR; - const uint8_t __context_tag = std::get(__element); - - if (__context_tag == to_underlying(Fields::kEnabled)) - { - err = DataModel::Decode(reader, enabled); - } - else - { - } - - ReturnErrorOnFailure(err); - } -} -} // namespace SetImageFlipHorizontal. -namespace SetImageFlipVertical { -CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const -{ - DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; - encoder.Encode(to_underlying(Fields::kEnabled), enabled); - return encoder.Finalize(); -} - -CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) -{ - detail::StructDecodeIterator __iterator(reader); - while (true) - { - auto __element = __iterator.Next(); - if (std::holds_alternative(__element)) - { - return std::get(__element); - } - - CHIP_ERROR err = CHIP_NO_ERROR; - const uint8_t __context_tag = std::get(__element); - - if (__context_tag == to_underlying(Fields::kEnabled)) - { - err = DataModel::Decode(reader, enabled); - } - else - { - } - - ReturnErrorOnFailure(err); - } -} -} // namespace SetImageFlipVertical. } // namespace Commands namespace Attributes { @@ -30154,10 +30023,6 @@ CHIP_ERROR TypeInfo::DecodableType::Decode(TLV::TLVReader & reader, const Concre return DataModel::Decode(reader, currentFrameRate); case Attributes::HDRModeEnabled::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, HDRModeEnabled); - case Attributes::CurrentVideoCodecs::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, currentVideoCodecs); - case Attributes::CurrentSnapshotConfig::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, currentSnapshotConfig); case Attributes::FabricsUsingCamera::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, fabricsUsingCamera); case Attributes::AllocatedVideoStreams::TypeInfo::GetAttributeId(): @@ -30178,12 +30043,6 @@ CHIP_ERROR TypeInfo::DecodableType::Decode(TLV::TLVReader & reader, const Concre return DataModel::Decode(reader, nightVision); case Attributes::NightVisionIllum::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, nightVisionIllum); - case Attributes::AWBEnabled::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, AWBEnabled); - case Attributes::AutoShutterSpeedEnabled::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, autoShutterSpeedEnabled); - case Attributes::AutoISOEnabled::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, autoISOEnabled); case Attributes::Viewport::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, viewport); case Attributes::SpeakerMuted::TypeInfo::GetAttributeId(): @@ -30218,8 +30077,6 @@ CHIP_ERROR TypeInfo::DecodableType::Decode(TLV::TLVReader & reader, const Concre return DataModel::Decode(reader, statusLightEnabled); case Attributes::StatusLightBrightness::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, statusLightBrightness); - case Attributes::DepthSensorStatus::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, depthSensorStatus); case Attributes::GeneratedCommandList::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, generatedCommandList); case Attributes::AcceptedCommandList::TypeInfo::GetAttributeId(): @@ -35101,5 +34958,20 @@ bool CommandIsFabricScoped(ClusterId aCluster, CommandId aCommand) return false; } +bool CommandHasLargePayload(ClusterId aCluster, CommandId aCommand) +{ + if ((aCluster == Clusters::CameraAvStreamManagement::Id) && + (aCommand == Clusters::CameraAvStreamManagement::Commands::CaptureSnapshot::Id)) + { + return true; + } + if ((aCluster == Clusters::CameraAvStreamManagement::Id) && + (aCommand == Clusters::CameraAvStreamManagement::Commands::CaptureSnapshotResponse::Id)) + { + return true; + } + return false; +} + } // namespace app } // namespace chip diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h index d7f69cc3818e3e..2357a87dd9d9fa 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h @@ -40482,13 +40482,14 @@ struct Type using DecodableType = Type; } // namespace ZoneInformationStruct -namespace ZoneTriggeringTimeControlStruct { +namespace ZoneTriggerControlStruct { enum class Fields : uint8_t { kInitialDuration = 0, kAugmentationDuration = 1, kMaxDuration = 2, kBlindDuration = 3, + kSensitivity = 4, }; struct Type @@ -40498,6 +40499,7 @@ struct Type uint16_t augmentationDuration = static_cast(0); uint32_t maxDuration = static_cast(0); uint16_t blindDuration = static_cast(0); + Optional sensitivity; CHIP_ERROR Decode(TLV::TLVReader & reader); @@ -40508,7 +40510,7 @@ struct Type using DecodableType = Type; -} // namespace ZoneTriggeringTimeControlStruct +} // namespace ZoneTriggerControlStruct } // namespace Structs namespace Commands { @@ -40772,21 +40774,20 @@ struct TypeInfo static constexpr bool MustUseTimedWrite() { return false; } }; } // namespace Zones -namespace TimeControl { +namespace Triggers { struct TypeInfo { - using Type = - chip::app::DataModel::List; - using DecodableType = chip::app::DataModel::DecodableList< - chip::app::Clusters::ZoneManagement::Structs::ZoneTriggeringTimeControlStruct::DecodableType>; + using Type = chip::app::DataModel::List; + using DecodableType = + chip::app::DataModel::DecodableList; using DecodableArgType = const chip::app::DataModel::DecodableList< - chip::app::Clusters::ZoneManagement::Structs::ZoneTriggeringTimeControlStruct::DecodableType> &; + chip::app::Clusters::ZoneManagement::Structs::ZoneTriggerControlStruct::DecodableType> &; static constexpr ClusterId GetClusterId() { return Clusters::ZoneManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::TimeControl::Id; } + static constexpr AttributeId GetAttributeId() { return Attributes::Triggers::Id; } static constexpr bool MustUseTimedWrite() { return false; } }; -} // namespace TimeControl +} // namespace Triggers namespace Sensitivity { struct TypeInfo { @@ -40840,7 +40841,7 @@ struct TypeInfo Attributes::SupportedZoneSources::TypeInfo::DecodableType supportedZoneSources; Attributes::Zones::TypeInfo::DecodableType zones; - Attributes::TimeControl::TypeInfo::DecodableType timeControl; + Attributes::Triggers::TypeInfo::DecodableType triggers; Attributes::Sensitivity::TypeInfo::DecodableType sensitivity = static_cast(0); Attributes::GeneratedCommandList::TypeInfo::DecodableType generatedCommandList; Attributes::AcceptedCommandList::TypeInfo::DecodableType acceptedCommandList; @@ -41253,26 +41254,6 @@ struct Type; struct DecodableType; } // namespace CaptureSnapshotResponse -namespace SetViewport { -struct Type; -struct DecodableType; -} // namespace SetViewport - -namespace SetImageRotation { -struct Type; -struct DecodableType; -} // namespace SetImageRotation - -namespace SetImageFlipHorizontal { -struct Type; -struct DecodableType; -} // namespace SetImageFlipHorizontal - -namespace SetImageFlipVertical { -struct Type; -struct DecodableType; -} // namespace SetImageFlipVertical - } // namespace Commands namespace Commands { @@ -41561,7 +41542,7 @@ namespace SnapshotStreamAllocate { enum class Fields : uint8_t { kImageCodec = 0, - kFrameRate = 1, + kMaxFrameRate = 1, kBitRate = 2, kMinResolution = 3, kMaxResolution = 4, @@ -41576,7 +41557,7 @@ struct Type static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } ImageCodecEnum imageCodec = static_cast(0); - uint16_t frameRate = static_cast(0); + uint16_t maxFrameRate = static_cast(0); uint32_t bitRate = static_cast(0); Structs::VideoResolutionStruct::Type minResolution; Structs::VideoResolutionStruct::Type maxResolution; @@ -41596,7 +41577,7 @@ struct DecodableType static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } ImageCodecEnum imageCodec = static_cast(0); - uint16_t frameRate = static_cast(0); + uint16_t maxFrameRate = static_cast(0); uint32_t bitRate = static_cast(0); Structs::VideoResolutionStruct::DecodableType minResolution; Structs::VideoResolutionStruct::DecodableType maxResolution; @@ -41773,134 +41754,6 @@ struct DecodableType CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace CaptureSnapshotResponse -namespace SetViewport { -enum class Fields : uint8_t -{ - kViewport = 0, -}; - -struct Type -{ -public: - // Use GetCommandId instead of commandId directly to avoid naming conflict with CommandIdentification in ExecutionOfACommand - static constexpr CommandId GetCommandId() { return Commands::SetViewport::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - Structs::ViewportStruct::Type viewport; - - CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; - - using ResponseType = DataModel::NullObjectType; - - static constexpr bool MustUseTimedInvoke() { return false; } -}; - -struct DecodableType -{ -public: - static constexpr CommandId GetCommandId() { return Commands::SetViewport::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - Structs::ViewportStruct::DecodableType viewport; - CHIP_ERROR Decode(TLV::TLVReader & reader); -}; -}; // namespace SetViewport -namespace SetImageRotation { -enum class Fields : uint8_t -{ - kAngle = 0, -}; - -struct Type -{ -public: - // Use GetCommandId instead of commandId directly to avoid naming conflict with CommandIdentification in ExecutionOfACommand - static constexpr CommandId GetCommandId() { return Commands::SetImageRotation::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - uint16_t angle = static_cast(0); - - CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; - - using ResponseType = DataModel::NullObjectType; - - static constexpr bool MustUseTimedInvoke() { return false; } -}; - -struct DecodableType -{ -public: - static constexpr CommandId GetCommandId() { return Commands::SetImageRotation::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - uint16_t angle = static_cast(0); - CHIP_ERROR Decode(TLV::TLVReader & reader); -}; -}; // namespace SetImageRotation -namespace SetImageFlipHorizontal { -enum class Fields : uint8_t -{ - kEnabled = 0, -}; - -struct Type -{ -public: - // Use GetCommandId instead of commandId directly to avoid naming conflict with CommandIdentification in ExecutionOfACommand - static constexpr CommandId GetCommandId() { return Commands::SetImageFlipHorizontal::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - bool enabled = static_cast(0); - - CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; - - using ResponseType = DataModel::NullObjectType; - - static constexpr bool MustUseTimedInvoke() { return false; } -}; - -struct DecodableType -{ -public: - static constexpr CommandId GetCommandId() { return Commands::SetImageFlipHorizontal::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - bool enabled = static_cast(0); - CHIP_ERROR Decode(TLV::TLVReader & reader); -}; -}; // namespace SetImageFlipHorizontal -namespace SetImageFlipVertical { -enum class Fields : uint8_t -{ - kEnabled = 0, -}; - -struct Type -{ -public: - // Use GetCommandId instead of commandId directly to avoid naming conflict with CommandIdentification in ExecutionOfACommand - static constexpr CommandId GetCommandId() { return Commands::SetImageFlipVertical::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - bool enabled = static_cast(0); - - CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; - - using ResponseType = DataModel::NullObjectType; - - static constexpr bool MustUseTimedInvoke() { return false; } -}; - -struct DecodableType -{ -public: - static constexpr CommandId GetCommandId() { return Commands::SetImageFlipVertical::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - bool enabled = static_cast(0); - CHIP_ERROR Decode(TLV::TLVReader & reader); -}; -}; // namespace SetImageFlipVertical } // namespace Commands namespace Attributes { @@ -42079,31 +41932,6 @@ struct TypeInfo static constexpr bool MustUseTimedWrite() { return false; } }; } // namespace HDRModeEnabled -namespace CurrentVideoCodecs { -struct TypeInfo -{ - using Type = chip::app::DataModel::List; - using DecodableType = chip::app::DataModel::DecodableList; - using DecodableArgType = - const chip::app::DataModel::DecodableList &; - - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::CurrentVideoCodecs::Id; } - static constexpr bool MustUseTimedWrite() { return false; } -}; -} // namespace CurrentVideoCodecs -namespace CurrentSnapshotConfig { -struct TypeInfo -{ - using Type = chip::app::Clusters::CameraAvStreamManagement::Structs::SnapshotParamsStruct::Type; - using DecodableType = chip::app::Clusters::CameraAvStreamManagement::Structs::SnapshotParamsStruct::DecodableType; - using DecodableArgType = const chip::app::Clusters::CameraAvStreamManagement::Structs::SnapshotParamsStruct::DecodableType &; - - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::CurrentSnapshotConfig::Id; } - static constexpr bool MustUseTimedWrite() { return false; } -}; -} // namespace CurrentSnapshotConfig namespace FabricsUsingCamera { struct TypeInfo { @@ -42232,42 +42060,6 @@ struct TypeInfo static constexpr bool MustUseTimedWrite() { return false; } }; } // namespace NightVisionIllum -namespace AWBEnabled { -struct TypeInfo -{ - using Type = bool; - using DecodableType = bool; - using DecodableArgType = bool; - - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::AWBEnabled::Id; } - static constexpr bool MustUseTimedWrite() { return false; } -}; -} // namespace AWBEnabled -namespace AutoShutterSpeedEnabled { -struct TypeInfo -{ - using Type = bool; - using DecodableType = bool; - using DecodableArgType = bool; - - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::AutoShutterSpeedEnabled::Id; } - static constexpr bool MustUseTimedWrite() { return false; } -}; -} // namespace AutoShutterSpeedEnabled -namespace AutoISOEnabled { -struct TypeInfo -{ - using Type = bool; - using DecodableType = bool; - using DecodableArgType = bool; - - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::AutoISOEnabled::Id; } - static constexpr bool MustUseTimedWrite() { return false; } -}; -} // namespace AutoISOEnabled namespace Viewport { struct TypeInfo { @@ -42472,18 +42264,6 @@ struct TypeInfo static constexpr bool MustUseTimedWrite() { return false; } }; } // namespace StatusLightBrightness -namespace DepthSensorStatus { -struct TypeInfo -{ - using Type = chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum; - using DecodableType = chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum; - using DecodableArgType = chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum; - - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::DepthSensorStatus::Id; } - static constexpr bool MustUseTimedWrite() { return false; } -}; -} // namespace DepthSensorStatus namespace GeneratedCommandList { struct TypeInfo : public Clusters::Globals::Attributes::GeneratedCommandList::TypeInfo { @@ -42538,8 +42318,6 @@ struct TypeInfo Attributes::MaxNetworkBandwidth::TypeInfo::DecodableType maxNetworkBandwidth = static_cast(0); Attributes::CurrentFrameRate::TypeInfo::DecodableType currentFrameRate = static_cast(0); Attributes::HDRModeEnabled::TypeInfo::DecodableType HDRModeEnabled = static_cast(0); - Attributes::CurrentVideoCodecs::TypeInfo::DecodableType currentVideoCodecs; - Attributes::CurrentSnapshotConfig::TypeInfo::DecodableType currentSnapshotConfig; Attributes::FabricsUsingCamera::TypeInfo::DecodableType fabricsUsingCamera; Attributes::AllocatedVideoStreams::TypeInfo::DecodableType allocatedVideoStreams; Attributes::AllocatedAudioStreams::TypeInfo::DecodableType allocatedAudioStreams; @@ -42553,9 +42331,6 @@ struct TypeInfo static_cast(0); Attributes::NightVisionIllum::TypeInfo::DecodableType nightVisionIllum = static_cast(0); - Attributes::AWBEnabled::TypeInfo::DecodableType AWBEnabled = static_cast(0); - Attributes::AutoShutterSpeedEnabled::TypeInfo::DecodableType autoShutterSpeedEnabled = static_cast(0); - Attributes::AutoISOEnabled::TypeInfo::DecodableType autoISOEnabled = static_cast(0); Attributes::Viewport::TypeInfo::DecodableType viewport; Attributes::SpeakerMuted::TypeInfo::DecodableType speakerMuted = static_cast(0); Attributes::SpeakerVolumeLevel::TypeInfo::DecodableType speakerVolumeLevel = static_cast(0); @@ -42574,8 +42349,6 @@ struct TypeInfo Attributes::StatusLightEnabled::TypeInfo::DecodableType statusLightEnabled = static_cast(0); Attributes::StatusLightBrightness::TypeInfo::DecodableType statusLightBrightness = static_cast(0); - Attributes::DepthSensorStatus::TypeInfo::DecodableType depthSensorStatus = - static_cast(0); Attributes::GeneratedCommandList::TypeInfo::DecodableType generatedCommandList; Attributes::AcceptedCommandList::TypeInfo::DecodableType acceptedCommandList; Attributes::AttributeList::TypeInfo::DecodableType attributeList; @@ -47768,6 +47541,7 @@ struct DecodableType bool CommandNeedsTimedInvoke(ClusterId aCluster, CommandId aCommand); bool CommandIsFabricScoped(ClusterId aCluster, CommandId aCommand); +bool CommandHasLargePayload(ClusterId aCluster, CommandId aCommand); } // namespace app } // namespace chip diff --git a/zzz_generated/app-common/app-common/zap-generated/ids/Attributes.h b/zzz_generated/app-common/app-common/zap-generated/ids/Attributes.h index e9375f5dad786a..5d12daa8564976 100644 --- a/zzz_generated/app-common/app-common/zap-generated/ids/Attributes.h +++ b/zzz_generated/app-common/app-common/zap-generated/ids/Attributes.h @@ -6832,9 +6832,9 @@ namespace Zones { static constexpr AttributeId Id = 0x00000001; } // namespace Zones -namespace TimeControl { +namespace Triggers { static constexpr AttributeId Id = 0x00000002; -} // namespace TimeControl +} // namespace Triggers namespace Sensitivity { static constexpr AttributeId Id = 0x00000003; @@ -6922,138 +6922,114 @@ namespace HDRModeEnabled { static constexpr AttributeId Id = 0x0000000D; } // namespace HDRModeEnabled -namespace CurrentVideoCodecs { -static constexpr AttributeId Id = 0x0000000E; -} // namespace CurrentVideoCodecs - -namespace CurrentSnapshotConfig { -static constexpr AttributeId Id = 0x0000000F; -} // namespace CurrentSnapshotConfig - namespace FabricsUsingCamera { -static constexpr AttributeId Id = 0x00000010; +static constexpr AttributeId Id = 0x0000000E; } // namespace FabricsUsingCamera namespace AllocatedVideoStreams { -static constexpr AttributeId Id = 0x00000011; +static constexpr AttributeId Id = 0x0000000F; } // namespace AllocatedVideoStreams namespace AllocatedAudioStreams { -static constexpr AttributeId Id = 0x00000012; +static constexpr AttributeId Id = 0x00000010; } // namespace AllocatedAudioStreams namespace AllocatedSnapshotStreams { -static constexpr AttributeId Id = 0x00000013; +static constexpr AttributeId Id = 0x00000011; } // namespace AllocatedSnapshotStreams namespace RankedVideoStreamPrioritiesList { -static constexpr AttributeId Id = 0x00000014; +static constexpr AttributeId Id = 0x00000012; } // namespace RankedVideoStreamPrioritiesList namespace SoftRecordingPrivacyModeEnabled { -static constexpr AttributeId Id = 0x00000015; +static constexpr AttributeId Id = 0x00000013; } // namespace SoftRecordingPrivacyModeEnabled namespace SoftLivestreamPrivacyModeEnabled { -static constexpr AttributeId Id = 0x00000016; +static constexpr AttributeId Id = 0x00000014; } // namespace SoftLivestreamPrivacyModeEnabled namespace HardPrivacyModeOn { -static constexpr AttributeId Id = 0x00000017; +static constexpr AttributeId Id = 0x00000015; } // namespace HardPrivacyModeOn namespace NightVision { -static constexpr AttributeId Id = 0x00000018; +static constexpr AttributeId Id = 0x00000016; } // namespace NightVision namespace NightVisionIllum { -static constexpr AttributeId Id = 0x00000019; +static constexpr AttributeId Id = 0x00000017; } // namespace NightVisionIllum -namespace AWBEnabled { -static constexpr AttributeId Id = 0x0000001A; -} // namespace AWBEnabled - -namespace AutoShutterSpeedEnabled { -static constexpr AttributeId Id = 0x0000001B; -} // namespace AutoShutterSpeedEnabled - -namespace AutoISOEnabled { -static constexpr AttributeId Id = 0x0000001C; -} // namespace AutoISOEnabled - namespace Viewport { -static constexpr AttributeId Id = 0x0000001D; +static constexpr AttributeId Id = 0x00000018; } // namespace Viewport namespace SpeakerMuted { -static constexpr AttributeId Id = 0x0000001E; +static constexpr AttributeId Id = 0x00000019; } // namespace SpeakerMuted namespace SpeakerVolumeLevel { -static constexpr AttributeId Id = 0x0000001F; +static constexpr AttributeId Id = 0x0000001A; } // namespace SpeakerVolumeLevel namespace SpeakerMaxLevel { -static constexpr AttributeId Id = 0x00000020; +static constexpr AttributeId Id = 0x0000001B; } // namespace SpeakerMaxLevel namespace SpeakerMinLevel { -static constexpr AttributeId Id = 0x00000021; +static constexpr AttributeId Id = 0x0000001C; } // namespace SpeakerMinLevel namespace MicrophoneMuted { -static constexpr AttributeId Id = 0x00000022; +static constexpr AttributeId Id = 0x0000001D; } // namespace MicrophoneMuted namespace MicrophoneVolumeLevel { -static constexpr AttributeId Id = 0x00000023; +static constexpr AttributeId Id = 0x0000001E; } // namespace MicrophoneVolumeLevel namespace MicrophoneMaxLevel { -static constexpr AttributeId Id = 0x00000024; +static constexpr AttributeId Id = 0x0000001F; } // namespace MicrophoneMaxLevel namespace MicrophoneMinLevel { -static constexpr AttributeId Id = 0x00000025; +static constexpr AttributeId Id = 0x00000020; } // namespace MicrophoneMinLevel namespace MicrophoneAGCEnabled { -static constexpr AttributeId Id = 0x00000026; +static constexpr AttributeId Id = 0x00000021; } // namespace MicrophoneAGCEnabled namespace ImageRotation { -static constexpr AttributeId Id = 0x00000027; +static constexpr AttributeId Id = 0x00000022; } // namespace ImageRotation namespace ImageFlipHorizontal { -static constexpr AttributeId Id = 0x00000028; +static constexpr AttributeId Id = 0x00000023; } // namespace ImageFlipHorizontal namespace ImageFlipVertical { -static constexpr AttributeId Id = 0x00000029; +static constexpr AttributeId Id = 0x00000024; } // namespace ImageFlipVertical namespace LocalVideoRecordingEnabled { -static constexpr AttributeId Id = 0x0000002A; +static constexpr AttributeId Id = 0x00000025; } // namespace LocalVideoRecordingEnabled namespace LocalSnapshotRecordingEnabled { -static constexpr AttributeId Id = 0x0000002B; +static constexpr AttributeId Id = 0x00000026; } // namespace LocalSnapshotRecordingEnabled namespace StatusLightEnabled { -static constexpr AttributeId Id = 0x0000002C; +static constexpr AttributeId Id = 0x00000027; } // namespace StatusLightEnabled namespace StatusLightBrightness { -static constexpr AttributeId Id = 0x0000002D; +static constexpr AttributeId Id = 0x00000028; } // namespace StatusLightBrightness -namespace DepthSensorStatus { -static constexpr AttributeId Id = 0x0000002E; -} // namespace DepthSensorStatus - namespace GeneratedCommandList { static constexpr AttributeId Id = Globals::Attributes::GeneratedCommandList::Id; } // namespace GeneratedCommandList diff --git a/zzz_generated/app-common/app-common/zap-generated/ids/Commands.h b/zzz_generated/app-common/app-common/zap-generated/ids/Commands.h index 5a07d8ac1bd191..d46b8ae0765467 100644 --- a/zzz_generated/app-common/app-common/zap-generated/ids/Commands.h +++ b/zzz_generated/app-common/app-common/zap-generated/ids/Commands.h @@ -1888,22 +1888,6 @@ namespace CaptureSnapshotResponse { static constexpr CommandId Id = 0x0000000C; } // namespace CaptureSnapshotResponse -namespace SetViewport { -static constexpr CommandId Id = 0x0000000D; -} // namespace SetViewport - -namespace SetImageRotation { -static constexpr CommandId Id = 0x0000000E; -} // namespace SetImageRotation - -namespace SetImageFlipHorizontal { -static constexpr CommandId Id = 0x0000000F; -} // namespace SetImageFlipHorizontal - -namespace SetImageFlipVertical { -static constexpr CommandId Id = 0x00000010; -} // namespace SetImageFlipVertical - } // namespace Commands } // namespace CameraAvStreamManagement diff --git a/zzz_generated/chip-tool/zap-generated/cluster/Commands.h b/zzz_generated/chip-tool/zap-generated/cluster/Commands.h index 4ee3c3e1f98afa..b0c00980d3e42d 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/Commands.h +++ b/zzz_generated/chip-tool/zap-generated/cluster/Commands.h @@ -13540,7 +13540,7 @@ class ContentAppObserverContentAppMessage : public ClusterCommand | Attributes: | | | * SupportedZoneSources | 0x0000 | | * Zones | 0x0001 | -| * TimeControl | 0x0002 | +| * Triggers | 0x0002 | | * Sensitivity | 0x0003 | | * GeneratedCommandList | 0xFFF8 | | * AcceptedCommandList | 0xFFF9 | @@ -13720,10 +13720,6 @@ class ZoneManagementRemoveZone : public ClusterCommand | * SnapshotStreamDeallocate | 0x09 | | * SetStreamPriorities | 0x0A | | * CaptureSnapshot | 0x0B | -| * SetViewport | 0x0D | -| * SetImageRotation | 0x0E | -| * SetImageFlipHorizontal | 0x0F | -| * SetImageFlipVertical | 0x10 | |------------------------------------------------------------------------------| | Attributes: | | | * MaxConcurrentVideoEncoders | 0x0000 | @@ -13740,39 +13736,33 @@ class ZoneManagementRemoveZone : public ClusterCommand | * MaxNetworkBandwidth | 0x000B | | * CurrentFrameRate | 0x000C | | * HDRModeEnabled | 0x000D | -| * CurrentVideoCodecs | 0x000E | -| * CurrentSnapshotConfig | 0x000F | -| * FabricsUsingCamera | 0x0010 | -| * AllocatedVideoStreams | 0x0011 | -| * AllocatedAudioStreams | 0x0012 | -| * AllocatedSnapshotStreams | 0x0013 | -| * RankedVideoStreamPrioritiesList | 0x0014 | -| * SoftRecordingPrivacyModeEnabled | 0x0015 | -| * SoftLivestreamPrivacyModeEnabled | 0x0016 | -| * HardPrivacyModeOn | 0x0017 | -| * NightVision | 0x0018 | -| * NightVisionIllum | 0x0019 | -| * AWBEnabled | 0x001A | -| * AutoShutterSpeedEnabled | 0x001B | -| * AutoISOEnabled | 0x001C | -| * Viewport | 0x001D | -| * SpeakerMuted | 0x001E | -| * SpeakerVolumeLevel | 0x001F | -| * SpeakerMaxLevel | 0x0020 | -| * SpeakerMinLevel | 0x0021 | -| * MicrophoneMuted | 0x0022 | -| * MicrophoneVolumeLevel | 0x0023 | -| * MicrophoneMaxLevel | 0x0024 | -| * MicrophoneMinLevel | 0x0025 | -| * MicrophoneAGCEnabled | 0x0026 | -| * ImageRotation | 0x0027 | -| * ImageFlipHorizontal | 0x0028 | -| * ImageFlipVertical | 0x0029 | -| * LocalVideoRecordingEnabled | 0x002A | -| * LocalSnapshotRecordingEnabled | 0x002B | -| * StatusLightEnabled | 0x002C | -| * StatusLightBrightness | 0x002D | -| * DepthSensorStatus | 0x002E | +| * FabricsUsingCamera | 0x000E | +| * AllocatedVideoStreams | 0x000F | +| * AllocatedAudioStreams | 0x0010 | +| * AllocatedSnapshotStreams | 0x0011 | +| * RankedVideoStreamPrioritiesList | 0x0012 | +| * SoftRecordingPrivacyModeEnabled | 0x0013 | +| * SoftLivestreamPrivacyModeEnabled | 0x0014 | +| * HardPrivacyModeOn | 0x0015 | +| * NightVision | 0x0016 | +| * NightVisionIllum | 0x0017 | +| * Viewport | 0x0018 | +| * SpeakerMuted | 0x0019 | +| * SpeakerVolumeLevel | 0x001A | +| * SpeakerMaxLevel | 0x001B | +| * SpeakerMinLevel | 0x001C | +| * MicrophoneMuted | 0x001D | +| * MicrophoneVolumeLevel | 0x001E | +| * MicrophoneMaxLevel | 0x001F | +| * MicrophoneMinLevel | 0x0020 | +| * MicrophoneAGCEnabled | 0x0021 | +| * ImageRotation | 0x0022 | +| * ImageFlipHorizontal | 0x0023 | +| * ImageFlipVertical | 0x0024 | +| * LocalVideoRecordingEnabled | 0x0025 | +| * LocalSnapshotRecordingEnabled | 0x0026 | +| * StatusLightEnabled | 0x0027 | +| * StatusLightBrightness | 0x0028 | | * GeneratedCommandList | 0xFFF8 | | * AcceptedCommandList | 0xFFF9 | | * AttributeList | 0xFFFB | @@ -14012,7 +14002,7 @@ class CameraAvStreamManagementSnapshotStreamAllocate : public ClusterCommand mComplex_MaxResolution(&mRequest.maxResolution) { AddArgument("ImageCodec", 0, UINT8_MAX, &mRequest.imageCodec); - AddArgument("FrameRate", 0, UINT16_MAX, &mRequest.frameRate); + AddArgument("MaxFrameRate", 0, UINT16_MAX, &mRequest.maxFrameRate); AddArgument("BitRate", 0, UINT32_MAX, &mRequest.bitRate); AddArgument("MinResolution", &mComplex_MinResolution); AddArgument("MaxResolution", &mComplex_MaxResolution); @@ -14168,159 +14158,6 @@ class CameraAvStreamManagementCaptureSnapshot : public ClusterCommand mComplex_RequestedResolution; }; -/* - * Command SetViewport - */ -class CameraAvStreamManagementSetViewport : public ClusterCommand -{ -public: - CameraAvStreamManagementSetViewport(CredentialIssuerCommands * credsIssuerConfig) : - ClusterCommand("set-viewport", credsIssuerConfig), mComplex_Viewport(&mRequest.viewport) - { - AddArgument("Viewport", &mComplex_Viewport); - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(chip::DeviceProxy * device, std::vector endpointIds) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, - commandId, endpointIds.at(0)); - return ClusterCommand::SendCommand(device, endpointIds.at(0), clusterId, commandId, mRequest); - } - - CHIP_ERROR SendGroupCommand(chip::GroupId groupId, chip::FabricIndex fabricIndex) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on Group %u", clusterId, commandId, - groupId); - - return ClusterCommand::SendGroupCommand(groupId, fabricIndex, clusterId, commandId, mRequest); - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Type mRequest; - TypedComplexArgument mComplex_Viewport; -}; - -/* - * Command SetImageRotation - */ -class CameraAvStreamManagementSetImageRotation : public ClusterCommand -{ -public: - CameraAvStreamManagementSetImageRotation(CredentialIssuerCommands * credsIssuerConfig) : - ClusterCommand("set-image-rotation", credsIssuerConfig) - { - AddArgument("Angle", 0, UINT16_MAX, &mRequest.angle); - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(chip::DeviceProxy * device, std::vector endpointIds) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, - commandId, endpointIds.at(0)); - return ClusterCommand::SendCommand(device, endpointIds.at(0), clusterId, commandId, mRequest); - } - - CHIP_ERROR SendGroupCommand(chip::GroupId groupId, chip::FabricIndex fabricIndex) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on Group %u", clusterId, commandId, - groupId); - - return ClusterCommand::SendGroupCommand(groupId, fabricIndex, clusterId, commandId, mRequest); - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Type mRequest; -}; - -/* - * Command SetImageFlipHorizontal - */ -class CameraAvStreamManagementSetImageFlipHorizontal : public ClusterCommand -{ -public: - CameraAvStreamManagementSetImageFlipHorizontal(CredentialIssuerCommands * credsIssuerConfig) : - ClusterCommand("set-image-flip-horizontal", credsIssuerConfig) - { - AddArgument("Enabled", 0, 1, &mRequest.enabled); - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(chip::DeviceProxy * device, std::vector endpointIds) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, - commandId, endpointIds.at(0)); - return ClusterCommand::SendCommand(device, endpointIds.at(0), clusterId, commandId, mRequest); - } - - CHIP_ERROR SendGroupCommand(chip::GroupId groupId, chip::FabricIndex fabricIndex) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on Group %u", clusterId, commandId, - groupId); - - return ClusterCommand::SendGroupCommand(groupId, fabricIndex, clusterId, commandId, mRequest); - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Type mRequest; -}; - -/* - * Command SetImageFlipVertical - */ -class CameraAvStreamManagementSetImageFlipVertical : public ClusterCommand -{ -public: - CameraAvStreamManagementSetImageFlipVertical(CredentialIssuerCommands * credsIssuerConfig) : - ClusterCommand("set-image-flip-vertical", credsIssuerConfig) - { - AddArgument("Enabled", 0, 1, &mRequest.enabled); - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(chip::DeviceProxy * device, std::vector endpointIds) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, - commandId, endpointIds.at(0)); - return ClusterCommand::SendCommand(device, endpointIds.at(0), clusterId, commandId, mRequest); - } - - CHIP_ERROR SendGroupCommand(chip::GroupId groupId, chip::FabricIndex fabricIndex) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on Group %u", clusterId, commandId, - groupId); - - return ClusterCommand::SendGroupCommand(groupId, fabricIndex, clusterId, commandId, mRequest); - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Type mRequest; -}; - /*----------------------------------------------------------------------------*\ | Cluster WebRTCTransportProvider | 0x0553 | |------------------------------------------------------------------------------| @@ -26836,7 +26673,7 @@ void registerClusterZoneManagement(Commands & commands, CredentialIssuerCommands make_unique(Id, credsIssuerConfig), // make_unique(Id, "supported-zone-sources", Attributes::SupportedZoneSources::Id, credsIssuerConfig), // make_unique(Id, "zones", Attributes::Zones::Id, credsIssuerConfig), // - make_unique(Id, "time-control", Attributes::TimeControl::Id, credsIssuerConfig), // + make_unique(Id, "triggers", Attributes::Triggers::Id, credsIssuerConfig), // make_unique(Id, "sensitivity", Attributes::Sensitivity::Id, credsIssuerConfig), // make_unique(Id, "generated-command-list", Attributes::GeneratedCommandList::Id, credsIssuerConfig), // make_unique(Id, "accepted-command-list", Attributes::AcceptedCommandList::Id, credsIssuerConfig), // @@ -26851,8 +26688,8 @@ void registerClusterZoneManagement(Commands & commands, CredentialIssuerCommands chip::app::DataModel::List>>( Id, "zones", Attributes::Zones::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>>( - Id, "time-control", Attributes::TimeControl::Id, WriteCommandType::kWrite, credsIssuerConfig), // + chip::app::DataModel::List>>( + Id, "triggers", Attributes::Triggers::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "sensitivity", 0, UINT8_MAX, Attributes::Sensitivity::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>>( @@ -26869,7 +26706,7 @@ void registerClusterZoneManagement(Commands & commands, CredentialIssuerCommands make_unique(Id, credsIssuerConfig), // make_unique(Id, "supported-zone-sources", Attributes::SupportedZoneSources::Id, credsIssuerConfig), // make_unique(Id, "zones", Attributes::Zones::Id, credsIssuerConfig), // - make_unique(Id, "time-control", Attributes::TimeControl::Id, credsIssuerConfig), // + make_unique(Id, "triggers", Attributes::Triggers::Id, credsIssuerConfig), // make_unique(Id, "sensitivity", Attributes::Sensitivity::Id, credsIssuerConfig), // make_unique(Id, "generated-command-list", Attributes::GeneratedCommandList::Id, credsIssuerConfig), // make_unique(Id, "accepted-command-list", Attributes::AcceptedCommandList::Id, credsIssuerConfig), // @@ -26909,10 +26746,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique(credsIssuerConfig), // make_unique(credsIssuerConfig), // make_unique(credsIssuerConfig), // - make_unique(credsIssuerConfig), // - make_unique(credsIssuerConfig), // - make_unique(credsIssuerConfig), // - make_unique(credsIssuerConfig), // // // Attributes // @@ -26933,8 +26766,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique(Id, "max-network-bandwidth", Attributes::MaxNetworkBandwidth::Id, credsIssuerConfig), // make_unique(Id, "current-frame-rate", Attributes::CurrentFrameRate::Id, credsIssuerConfig), // make_unique(Id, "hdrmode-enabled", Attributes::HDRModeEnabled::Id, credsIssuerConfig), // - make_unique(Id, "current-video-codecs", Attributes::CurrentVideoCodecs::Id, credsIssuerConfig), // - make_unique(Id, "current-snapshot-config", Attributes::CurrentSnapshotConfig::Id, credsIssuerConfig), // make_unique(Id, "fabrics-using-camera", Attributes::FabricsUsingCamera::Id, credsIssuerConfig), // make_unique(Id, "allocated-video-streams", Attributes::AllocatedVideoStreams::Id, credsIssuerConfig), // make_unique(Id, "allocated-audio-streams", Attributes::AllocatedAudioStreams::Id, credsIssuerConfig), // @@ -26945,33 +26776,29 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique(Id, "soft-recording-privacy-mode-enabled", Attributes::SoftRecordingPrivacyModeEnabled::Id, credsIssuerConfig), // make_unique(Id, "soft-livestream-privacy-mode-enabled", Attributes::SoftLivestreamPrivacyModeEnabled::Id, - credsIssuerConfig), // - make_unique(Id, "hard-privacy-mode-on", Attributes::HardPrivacyModeOn::Id, credsIssuerConfig), // - make_unique(Id, "night-vision", Attributes::NightVision::Id, credsIssuerConfig), // - make_unique(Id, "night-vision-illum", Attributes::NightVisionIllum::Id, credsIssuerConfig), // - make_unique(Id, "awbenabled", Attributes::AWBEnabled::Id, credsIssuerConfig), // - make_unique(Id, "auto-shutter-speed-enabled", Attributes::AutoShutterSpeedEnabled::Id, credsIssuerConfig), // - make_unique(Id, "auto-isoenabled", Attributes::AutoISOEnabled::Id, credsIssuerConfig), // - make_unique(Id, "viewport", Attributes::Viewport::Id, credsIssuerConfig), // - make_unique(Id, "speaker-muted", Attributes::SpeakerMuted::Id, credsIssuerConfig), // - make_unique(Id, "speaker-volume-level", Attributes::SpeakerVolumeLevel::Id, credsIssuerConfig), // - make_unique(Id, "speaker-max-level", Attributes::SpeakerMaxLevel::Id, credsIssuerConfig), // - make_unique(Id, "speaker-min-level", Attributes::SpeakerMinLevel::Id, credsIssuerConfig), // - make_unique(Id, "microphone-muted", Attributes::MicrophoneMuted::Id, credsIssuerConfig), // - make_unique(Id, "microphone-volume-level", Attributes::MicrophoneVolumeLevel::Id, credsIssuerConfig), // - make_unique(Id, "microphone-max-level", Attributes::MicrophoneMaxLevel::Id, credsIssuerConfig), // - make_unique(Id, "microphone-min-level", Attributes::MicrophoneMinLevel::Id, credsIssuerConfig), // - make_unique(Id, "microphone-agcenabled", Attributes::MicrophoneAGCEnabled::Id, credsIssuerConfig), // - make_unique(Id, "image-rotation", Attributes::ImageRotation::Id, credsIssuerConfig), // - make_unique(Id, "image-flip-horizontal", Attributes::ImageFlipHorizontal::Id, credsIssuerConfig), // - make_unique(Id, "image-flip-vertical", Attributes::ImageFlipVertical::Id, credsIssuerConfig), // + credsIssuerConfig), // + make_unique(Id, "hard-privacy-mode-on", Attributes::HardPrivacyModeOn::Id, credsIssuerConfig), // + make_unique(Id, "night-vision", Attributes::NightVision::Id, credsIssuerConfig), // + make_unique(Id, "night-vision-illum", Attributes::NightVisionIllum::Id, credsIssuerConfig), // + make_unique(Id, "viewport", Attributes::Viewport::Id, credsIssuerConfig), // + make_unique(Id, "speaker-muted", Attributes::SpeakerMuted::Id, credsIssuerConfig), // + make_unique(Id, "speaker-volume-level", Attributes::SpeakerVolumeLevel::Id, credsIssuerConfig), // + make_unique(Id, "speaker-max-level", Attributes::SpeakerMaxLevel::Id, credsIssuerConfig), // + make_unique(Id, "speaker-min-level", Attributes::SpeakerMinLevel::Id, credsIssuerConfig), // + make_unique(Id, "microphone-muted", Attributes::MicrophoneMuted::Id, credsIssuerConfig), // + make_unique(Id, "microphone-volume-level", Attributes::MicrophoneVolumeLevel::Id, credsIssuerConfig), // + make_unique(Id, "microphone-max-level", Attributes::MicrophoneMaxLevel::Id, credsIssuerConfig), // + make_unique(Id, "microphone-min-level", Attributes::MicrophoneMinLevel::Id, credsIssuerConfig), // + make_unique(Id, "microphone-agcenabled", Attributes::MicrophoneAGCEnabled::Id, credsIssuerConfig), // + make_unique(Id, "image-rotation", Attributes::ImageRotation::Id, credsIssuerConfig), // + make_unique(Id, "image-flip-horizontal", Attributes::ImageFlipHorizontal::Id, credsIssuerConfig), // + make_unique(Id, "image-flip-vertical", Attributes::ImageFlipVertical::Id, credsIssuerConfig), // make_unique(Id, "local-video-recording-enabled", Attributes::LocalVideoRecordingEnabled::Id, credsIssuerConfig), // make_unique(Id, "local-snapshot-recording-enabled", Attributes::LocalSnapshotRecordingEnabled::Id, credsIssuerConfig), // make_unique(Id, "status-light-enabled", Attributes::StatusLightEnabled::Id, credsIssuerConfig), // make_unique(Id, "status-light-brightness", Attributes::StatusLightBrightness::Id, credsIssuerConfig), // - make_unique(Id, "depth-sensor-status", Attributes::DepthSensorStatus::Id, credsIssuerConfig), // make_unique(Id, "generated-command-list", Attributes::GeneratedCommandList::Id, credsIssuerConfig), // make_unique(Id, "accepted-command-list", Attributes::AcceptedCommandList::Id, credsIssuerConfig), // make_unique(Id, "attribute-list", Attributes::AttributeList::Id, credsIssuerConfig), // @@ -27013,12 +26840,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "hdrmode-enabled", 0, 1, Attributes::HDRModeEnabled::Id, WriteCommandType::kWrite, credsIssuerConfig), // - make_unique>>( - Id, "current-video-codecs", Attributes::CurrentVideoCodecs::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // - make_unique>( - Id, "current-snapshot-config", Attributes::CurrentSnapshotConfig::Id, WriteCommandType::kForceWrite, - credsIssuerConfig), // make_unique>>( Id, "fabrics-using-camera", Attributes::FabricsUsingCamera::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>>( - Id, "ranked-video-stream-priorities-list", Attributes::RankedVideoStreamPrioritiesList::Id, WriteCommandType::kWrite, - credsIssuerConfig), // + Id, "ranked-video-stream-priorities-list", Attributes::RankedVideoStreamPrioritiesList::Id, + WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "soft-recording-privacy-mode-enabled", 0, 1, Attributes::SoftRecordingPrivacyModeEnabled::Id, WriteCommandType::kWrite, credsIssuerConfig), // @@ -27050,38 +26871,32 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique>( Id, "night-vision-illum", 0, UINT8_MAX, Attributes::NightVisionIllum::Id, WriteCommandType::kWrite, credsIssuerConfig), // - make_unique>(Id, "awbenabled", 0, 1, Attributes::AWBEnabled::Id, WriteCommandType::kWrite, - credsIssuerConfig), // - make_unique>(Id, "auto-shutter-speed-enabled", 0, 1, Attributes::AutoShutterSpeedEnabled::Id, - WriteCommandType::kWrite, credsIssuerConfig), // - make_unique>(Id, "auto-isoenabled", 0, 1, Attributes::AutoISOEnabled::Id, WriteCommandType::kWrite, - credsIssuerConfig), // make_unique>( - Id, "viewport", Attributes::Viewport::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // + Id, "viewport", Attributes::Viewport::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "speaker-muted", 0, 1, Attributes::SpeakerMuted::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "speaker-volume-level", 0, UINT8_MAX, Attributes::SpeakerVolumeLevel::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "speaker-max-level", 0, UINT8_MAX, Attributes::SpeakerMaxLevel::Id, - WriteCommandType::kWrite, credsIssuerConfig), // + WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "speaker-min-level", 0, UINT8_MAX, Attributes::SpeakerMinLevel::Id, - WriteCommandType::kWrite, credsIssuerConfig), // + WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "microphone-muted", 0, 1, Attributes::MicrophoneMuted::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "microphone-volume-level", 0, UINT8_MAX, Attributes::MicrophoneVolumeLevel::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "microphone-max-level", 0, UINT8_MAX, Attributes::MicrophoneMaxLevel::Id, - WriteCommandType::kWrite, credsIssuerConfig), // + WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "microphone-min-level", 0, UINT8_MAX, Attributes::MicrophoneMinLevel::Id, - WriteCommandType::kWrite, credsIssuerConfig), // + WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "microphone-agcenabled", 0, 1, Attributes::MicrophoneAGCEnabled::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "image-rotation", 0, UINT16_MAX, Attributes::ImageRotation::Id, - WriteCommandType::kForceWrite, credsIssuerConfig), // + WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "image-flip-horizontal", 0, 1, Attributes::ImageFlipHorizontal::Id, - WriteCommandType::kForceWrite, credsIssuerConfig), // + WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "image-flip-vertical", 0, 1, Attributes::ImageFlipVertical::Id, - WriteCommandType::kForceWrite, credsIssuerConfig), // + WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "local-video-recording-enabled", 0, 1, Attributes::LocalVideoRecordingEnabled::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "local-snapshot-recording-enabled", 0, 1, @@ -27092,9 +26907,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique>( Id, "status-light-brightness", 0, UINT8_MAX, Attributes::StatusLightBrightness::Id, WriteCommandType::kWrite, credsIssuerConfig), // - make_unique>( - Id, "depth-sensor-status", 0, UINT8_MAX, Attributes::DepthSensorStatus::Id, WriteCommandType::kWrite, - credsIssuerConfig), // make_unique>>( Id, "generated-command-list", Attributes::GeneratedCommandList::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // @@ -27125,8 +26937,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique(Id, "max-network-bandwidth", Attributes::MaxNetworkBandwidth::Id, credsIssuerConfig), // make_unique(Id, "current-frame-rate", Attributes::CurrentFrameRate::Id, credsIssuerConfig), // make_unique(Id, "hdrmode-enabled", Attributes::HDRModeEnabled::Id, credsIssuerConfig), // - make_unique(Id, "current-video-codecs", Attributes::CurrentVideoCodecs::Id, credsIssuerConfig), // - make_unique(Id, "current-snapshot-config", Attributes::CurrentSnapshotConfig::Id, credsIssuerConfig), // make_unique(Id, "fabrics-using-camera", Attributes::FabricsUsingCamera::Id, credsIssuerConfig), // make_unique(Id, "allocated-video-streams", Attributes::AllocatedVideoStreams::Id, credsIssuerConfig), // make_unique(Id, "allocated-audio-streams", Attributes::AllocatedAudioStreams::Id, credsIssuerConfig), // @@ -27137,14 +26947,10 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique(Id, "soft-recording-privacy-mode-enabled", Attributes::SoftRecordingPrivacyModeEnabled::Id, credsIssuerConfig), // make_unique(Id, "soft-livestream-privacy-mode-enabled", - Attributes::SoftLivestreamPrivacyModeEnabled::Id, credsIssuerConfig), // - make_unique(Id, "hard-privacy-mode-on", Attributes::HardPrivacyModeOn::Id, credsIssuerConfig), // - make_unique(Id, "night-vision", Attributes::NightVision::Id, credsIssuerConfig), // - make_unique(Id, "night-vision-illum", Attributes::NightVisionIllum::Id, credsIssuerConfig), // - make_unique(Id, "awbenabled", Attributes::AWBEnabled::Id, credsIssuerConfig), // - make_unique(Id, "auto-shutter-speed-enabled", Attributes::AutoShutterSpeedEnabled::Id, - credsIssuerConfig), // - make_unique(Id, "auto-isoenabled", Attributes::AutoISOEnabled::Id, credsIssuerConfig), // + Attributes::SoftLivestreamPrivacyModeEnabled::Id, credsIssuerConfig), // + make_unique(Id, "hard-privacy-mode-on", Attributes::HardPrivacyModeOn::Id, credsIssuerConfig), // + make_unique(Id, "night-vision", Attributes::NightVision::Id, credsIssuerConfig), // + make_unique(Id, "night-vision-illum", Attributes::NightVisionIllum::Id, credsIssuerConfig), // make_unique(Id, "viewport", Attributes::Viewport::Id, credsIssuerConfig), // make_unique(Id, "speaker-muted", Attributes::SpeakerMuted::Id, credsIssuerConfig), // make_unique(Id, "speaker-volume-level", Attributes::SpeakerVolumeLevel::Id, credsIssuerConfig), // @@ -27164,7 +26970,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu credsIssuerConfig), // make_unique(Id, "status-light-enabled", Attributes::StatusLightEnabled::Id, credsIssuerConfig), // make_unique(Id, "status-light-brightness", Attributes::StatusLightBrightness::Id, credsIssuerConfig), // - make_unique(Id, "depth-sensor-status", Attributes::DepthSensorStatus::Id, credsIssuerConfig), // make_unique(Id, "generated-command-list", Attributes::GeneratedCommandList::Id, credsIssuerConfig), // make_unique(Id, "accepted-command-list", Attributes::AcceptedCommandList::Id, credsIssuerConfig), // make_unique(Id, "attribute-list", Attributes::AttributeList::Id, credsIssuerConfig), // diff --git a/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp b/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp index 670d306354f37f..0c3abfbc83a89d 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.cpp @@ -5939,23 +5939,22 @@ void ComplexArgumentParser::Finalize(chip::app::Clusters::ZoneManagement::Struct ComplexArgumentParser::Finalize(request.zoneSource); } -CHIP_ERROR -ComplexArgumentParser::Setup(const char * label, - chip::app::Clusters::ZoneManagement::Structs::ZoneTriggeringTimeControlStruct::Type & request, - Json::Value & value) +CHIP_ERROR ComplexArgumentParser::Setup(const char * label, + chip::app::Clusters::ZoneManagement::Structs::ZoneTriggerControlStruct::Type & request, + Json::Value & value) { VerifyOrReturnError(value.isObject(), CHIP_ERROR_INVALID_ARGUMENT); // Copy to track which members we already processed. Json::Value valueCopy(value); - ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("ZoneTriggeringTimeControlStruct.initialDuration", - "initialDuration", value.isMember("initialDuration"))); - ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("ZoneTriggeringTimeControlStruct.augmentationDuration", + ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("ZoneTriggerControlStruct.initialDuration", "initialDuration", + value.isMember("initialDuration"))); + ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("ZoneTriggerControlStruct.augmentationDuration", "augmentationDuration", value.isMember("augmentationDuration"))); - ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("ZoneTriggeringTimeControlStruct.maxDuration", "maxDuration", + ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("ZoneTriggerControlStruct.maxDuration", "maxDuration", value.isMember("maxDuration"))); - ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("ZoneTriggeringTimeControlStruct.blindDuration", "blindDuration", + ReturnErrorOnFailure(ComplexArgumentParser::EnsureMemberExist("ZoneTriggerControlStruct.blindDuration", "blindDuration", value.isMember("blindDuration"))); char labelWithMember[kMaxLabelLength]; @@ -5976,15 +5975,23 @@ ComplexArgumentParser::Setup(const char * label, ReturnErrorOnFailure(ComplexArgumentParser::Setup(labelWithMember, request.blindDuration, value["blindDuration"])); valueCopy.removeMember("blindDuration"); + if (value.isMember("sensitivity")) + { + snprintf(labelWithMember, sizeof(labelWithMember), "%s.%s", label, "sensitivity"); + ReturnErrorOnFailure(ComplexArgumentParser::Setup(labelWithMember, request.sensitivity, value["sensitivity"])); + } + valueCopy.removeMember("sensitivity"); + return ComplexArgumentParser::EnsureNoMembersRemaining(label, valueCopy); } -void ComplexArgumentParser::Finalize(chip::app::Clusters::ZoneManagement::Structs::ZoneTriggeringTimeControlStruct::Type & request) +void ComplexArgumentParser::Finalize(chip::app::Clusters::ZoneManagement::Structs::ZoneTriggerControlStruct::Type & request) { ComplexArgumentParser::Finalize(request.initialDuration); ComplexArgumentParser::Finalize(request.augmentationDuration); ComplexArgumentParser::Finalize(request.maxDuration); ComplexArgumentParser::Finalize(request.blindDuration); + ComplexArgumentParser::Finalize(request.sensitivity); } CHIP_ERROR diff --git a/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.h b/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.h index 38b3aee08f9859..869fcb855a142a 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.h +++ b/zzz_generated/chip-tool/zap-generated/cluster/ComplexArgumentParser.h @@ -688,11 +688,10 @@ static CHIP_ERROR Setup(const char * label, chip::app::Clusters::ZoneManagement: static void Finalize(chip::app::Clusters::ZoneManagement::Structs::ZoneInformationStruct::Type & request); -static CHIP_ERROR Setup(const char * label, - chip::app::Clusters::ZoneManagement::Structs::ZoneTriggeringTimeControlStruct::Type & request, +static CHIP_ERROR Setup(const char * label, chip::app::Clusters::ZoneManagement::Structs::ZoneTriggerControlStruct::Type & request, Json::Value & value); -static void Finalize(chip::app::Clusters::ZoneManagement::Structs::ZoneTriggeringTimeControlStruct::Type & request); +static void Finalize(chip::app::Clusters::ZoneManagement::Structs::ZoneTriggerControlStruct::Type & request); static CHIP_ERROR Setup(const char * label, chip::app::Clusters::CameraAvStreamManagement::Structs::VideoResolutionStruct::Type & request, diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp index ac4e3adbbbebc3..1ea513ea1d3f95 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp @@ -5246,9 +5246,9 @@ DataModelLogger::LogValue(const char * label, size_t indent, return CHIP_NO_ERROR; } -CHIP_ERROR DataModelLogger::LogValue( - const char * label, size_t indent, - const chip::app::Clusters::ZoneManagement::Structs::ZoneTriggeringTimeControlStruct::DecodableType & value) +CHIP_ERROR +DataModelLogger::LogValue(const char * label, size_t indent, + const chip::app::Clusters::ZoneManagement::Structs::ZoneTriggerControlStruct::DecodableType & value) { DataModelLogger::LogString(label, indent, "{"); { @@ -5283,6 +5283,14 @@ CHIP_ERROR DataModelLogger::LogValue( return err; } } + { + CHIP_ERROR err = LogValue("Sensitivity", indent + 1, value.sensitivity); + if (err != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "Struct truncated due to invalid value for 'Sensitivity'"); + return err; + } + } DataModelLogger::LogString(indent, "}"); return CHIP_NO_ERROR; @@ -18438,12 +18446,12 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("Zones", 1, value); } - case ZoneManagement::Attributes::TimeControl::Id: { + case ZoneManagement::Attributes::Triggers::Id: { chip::app::DataModel::DecodableList< - chip::app::Clusters::ZoneManagement::Structs::ZoneTriggeringTimeControlStruct::DecodableType> + chip::app::Clusters::ZoneManagement::Structs::ZoneTriggerControlStruct::DecodableType> value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("TimeControl", 1, value); + return DataModelLogger::LogValue("Triggers", 1, value); } case ZoneManagement::Attributes::Sensitivity::Id: { uint8_t value; @@ -18555,16 +18563,6 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("HDRModeEnabled", 1, value); } - case CameraAvStreamManagement::Attributes::CurrentVideoCodecs::Id: { - chip::app::DataModel::DecodableList value; - ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("CurrentVideoCodecs", 1, value); - } - case CameraAvStreamManagement::Attributes::CurrentSnapshotConfig::Id: { - chip::app::Clusters::CameraAvStreamManagement::Structs::SnapshotParamsStruct::DecodableType value; - ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("CurrentSnapshotConfig", 1, value); - } case CameraAvStreamManagement::Attributes::FabricsUsingCamera::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); @@ -18621,21 +18619,6 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("NightVisionIllum", 1, value); } - case CameraAvStreamManagement::Attributes::AWBEnabled::Id: { - bool value; - ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AWBEnabled", 1, value); - } - case CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::Id: { - bool value; - ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AutoShutterSpeedEnabled", 1, value); - } - case CameraAvStreamManagement::Attributes::AutoISOEnabled::Id: { - bool value; - ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AutoISOEnabled", 1, value); - } case CameraAvStreamManagement::Attributes::Viewport::Id: { chip::app::Clusters::CameraAvStreamManagement::Structs::ViewportStruct::DecodableType value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); @@ -18721,11 +18704,6 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("StatusLightBrightness", 1, value); } - case CameraAvStreamManagement::Attributes::DepthSensorStatus::Id: { - chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum value; - ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("DepthSensorStatus", 1, value); - } case CameraAvStreamManagement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h index c9833ccb6c8d7f..dd53dfabc6a6eb 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h @@ -422,9 +422,8 @@ static CHIP_ERROR LogValue(const char * label, size_t indent, static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::Clusters::ZoneManagement::Structs::ZoneInformationStruct::DecodableType & value); -static CHIP_ERROR -LogValue(const char * label, size_t indent, - const chip::app::Clusters::ZoneManagement::Structs::ZoneTriggeringTimeControlStruct::DecodableType & value); +static CHIP_ERROR LogValue(const char * label, size_t indent, + const chip::app::Clusters::ZoneManagement::Structs::ZoneTriggerControlStruct::DecodableType & value); static CHIP_ERROR LogValue(const char * label, size_t indent, diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp b/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp index caa60d3532e401..3977ee180be1e2 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp @@ -4148,8 +4148,8 @@ char const * AttributeIdToText(chip::ClusterId cluster, chip::AttributeId id) return "SupportedZoneSources"; case chip::app::Clusters::ZoneManagement::Attributes::Zones::Id: return "Zones"; - case chip::app::Clusters::ZoneManagement::Attributes::TimeControl::Id: - return "TimeControl"; + case chip::app::Clusters::ZoneManagement::Attributes::Triggers::Id: + return "Triggers"; case chip::app::Clusters::ZoneManagement::Attributes::Sensitivity::Id: return "Sensitivity"; case chip::app::Clusters::ZoneManagement::Attributes::GeneratedCommandList::Id: @@ -4197,10 +4197,6 @@ char const * AttributeIdToText(chip::ClusterId cluster, chip::AttributeId id) return "CurrentFrameRate"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::HDRModeEnabled::Id: return "HDRModeEnabled"; - case chip::app::Clusters::CameraAvStreamManagement::Attributes::CurrentVideoCodecs::Id: - return "CurrentVideoCodecs"; - case chip::app::Clusters::CameraAvStreamManagement::Attributes::CurrentSnapshotConfig::Id: - return "CurrentSnapshotConfig"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::FabricsUsingCamera::Id: return "FabricsUsingCamera"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedVideoStreams::Id: @@ -4221,12 +4217,6 @@ char const * AttributeIdToText(chip::ClusterId cluster, chip::AttributeId id) return "NightVision"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVisionIllum::Id: return "NightVisionIllum"; - case chip::app::Clusters::CameraAvStreamManagement::Attributes::AWBEnabled::Id: - return "AWBEnabled"; - case chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::Id: - return "AutoShutterSpeedEnabled"; - case chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoISOEnabled::Id: - return "AutoISOEnabled"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::Viewport::Id: return "Viewport"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMuted::Id: @@ -4261,8 +4251,6 @@ char const * AttributeIdToText(chip::ClusterId cluster, chip::AttributeId id) return "StatusLightEnabled"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::StatusLightBrightness::Id: return "StatusLightBrightness"; - case chip::app::Clusters::CameraAvStreamManagement::Attributes::DepthSensorStatus::Id: - return "DepthSensorStatus"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::GeneratedCommandList::Id: return "GeneratedCommandList"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::AcceptedCommandList::Id: @@ -5690,14 +5678,6 @@ char const * AcceptedCommandIdToText(chip::ClusterId cluster, chip::CommandId id return "SetStreamPriorities"; case chip::app::Clusters::CameraAvStreamManagement::Commands::CaptureSnapshot::Id: return "CaptureSnapshot"; - case chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Id: - return "SetViewport"; - case chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Id: - return "SetImageRotation"; - case chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Id: - return "SetImageFlipHorizontal"; - case chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Id: - return "SetImageFlipVertical"; default: return "Unknown"; } diff --git a/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h b/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h index bf6bff38ba079b..2d9b737038535e 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h @@ -149469,7 +149469,7 @@ class SubscribeAttributeContentAppObserverClusterRevision : public SubscribeAttr | Attributes: | | | * SupportedZoneSources | 0x0000 | | * Zones | 0x0001 | -| * TimeControl | 0x0002 | +| * Triggers | 0x0002 | | * Sensitivity | 0x0003 | | * GeneratedCommandList | 0xFFF8 | | * AcceptedCommandList | 0xFFF9 | @@ -149934,34 +149934,34 @@ class SubscribeAttributeZoneManagementZones : public SubscribeAttribute { #if MTR_ENABLE_PROVISIONAL /* - * Attribute TimeControl + * Attribute Triggers */ -class ReadZoneManagementTimeControl : public ReadAttribute { +class ReadZoneManagementTriggers : public ReadAttribute { public: - ReadZoneManagementTimeControl() - : ReadAttribute("time-control") + ReadZoneManagementTriggers() + : ReadAttribute("triggers") { } - ~ReadZoneManagementTimeControl() + ~ReadZoneManagementTriggers() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::ZoneManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::ZoneManagement::Attributes::TimeControl::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::ZoneManagement::Attributes::Triggers::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); __auto_type * cluster = [[MTRBaseClusterZoneManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeTimeControlWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable error) { - NSLog(@"ZoneManagement.TimeControl response %@", [value description]); + [cluster readAttributeTriggersWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable error) { + NSLog(@"ZoneManagement.Triggers response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { - LogNSError("ZoneManagement TimeControl read Error", error); + LogNSError("ZoneManagement Triggers read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -149970,25 +149970,25 @@ class ReadZoneManagementTimeControl : public ReadAttribute { } }; -class WriteZoneManagementTimeControl : public WriteAttribute { +class WriteZoneManagementTriggers : public WriteAttribute { public: - WriteZoneManagementTimeControl() - : WriteAttribute("time-control") + WriteZoneManagementTriggers() + : WriteAttribute("triggers") , mComplex(&mValue) { - AddArgument("attr-name", "time-control"); + AddArgument("attr-name", "triggers"); AddArgument("attr-value", &mComplex); WriteAttribute::AddArguments(); } - ~WriteZoneManagementTimeControl() + ~WriteZoneManagementTriggers() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::ZoneManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::ZoneManagement::Attributes::TimeControl::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::ZoneManagement::Attributes::Triggers::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -150000,20 +150000,25 @@ class WriteZoneManagementTimeControl : public WriteAttribute { { // Scope for our temporary variables auto * array_0 = [NSMutableArray new]; for (auto & entry_0 : mValue) { - MTRZoneManagementClusterZoneTriggeringTimeControlStruct * newElement_0; - newElement_0 = [MTRZoneManagementClusterZoneTriggeringTimeControlStruct new]; + MTRZoneManagementClusterZoneTriggerControlStruct * newElement_0; + newElement_0 = [MTRZoneManagementClusterZoneTriggerControlStruct new]; newElement_0.initialDuration = [NSNumber numberWithUnsignedShort:entry_0.initialDuration]; newElement_0.augmentationDuration = [NSNumber numberWithUnsignedShort:entry_0.augmentationDuration]; newElement_0.maxDuration = [NSNumber numberWithUnsignedInt:entry_0.maxDuration]; newElement_0.blindDuration = [NSNumber numberWithUnsignedShort:entry_0.blindDuration]; + if (entry_0.sensitivity.HasValue()) { + newElement_0.sensitivity = [NSNumber numberWithUnsignedChar:entry_0.sensitivity.Value()]; + } else { + newElement_0.sensitivity = nil; + } [array_0 addObject:newElement_0]; } value = array_0; } - [cluster writeAttributeTimeControlWithValue:value params:params completion:^(NSError * _Nullable error) { + [cluster writeAttributeTriggersWithValue:value params:params completion:^(NSError * _Nullable error) { if (error != nil) { - LogNSError("ZoneManagement TimeControl write Error", error); + LogNSError("ZoneManagement Triggers write Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -150022,25 +150027,25 @@ class WriteZoneManagementTimeControl : public WriteAttribute { } private: - chip::app::DataModel::List mValue; - TypedComplexArgument> mComplex; + chip::app::DataModel::List mValue; + TypedComplexArgument> mComplex; }; -class SubscribeAttributeZoneManagementTimeControl : public SubscribeAttribute { +class SubscribeAttributeZoneManagementTriggers : public SubscribeAttribute { public: - SubscribeAttributeZoneManagementTimeControl() - : SubscribeAttribute("time-control") + SubscribeAttributeZoneManagementTriggers() + : SubscribeAttribute("triggers") { } - ~SubscribeAttributeZoneManagementTimeControl() + ~SubscribeAttributeZoneManagementTriggers() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::ZoneManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::ZoneManagement::Attributes::TimeControl::Id; + constexpr chip::CommandId attributeId = chip::app::Clusters::ZoneManagement::Attributes::Triggers::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -150055,10 +150060,10 @@ class SubscribeAttributeZoneManagementTimeControl : public SubscribeAttribute { if (mAutoResubscribe.HasValue()) { params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [cluster subscribeAttributeTimeControlWithParams:params + [cluster subscribeAttributeTriggersWithParams:params subscriptionEstablished:^() { mSubscriptionEstablished = YES; } reportHandler:^(NSArray * _Nullable value, NSError * _Nullable error) { - NSLog(@"ZoneManagement.TimeControl response %@", [value description]); + NSLog(@"ZoneManagement.Triggers response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { @@ -150638,10 +150643,6 @@ class SubscribeAttributeZoneManagementClusterRevision : public SubscribeAttribut | * SnapshotStreamDeallocate | 0x09 | | * SetStreamPriorities | 0x0A | | * CaptureSnapshot | 0x0B | -| * SetViewport | 0x0D | -| * SetImageRotation | 0x0E | -| * SetImageFlipHorizontal | 0x0F | -| * SetImageFlipVertical | 0x10 | |------------------------------------------------------------------------------| | Attributes: | | | * MaxConcurrentVideoEncoders | 0x0000 | @@ -150658,39 +150659,33 @@ class SubscribeAttributeZoneManagementClusterRevision : public SubscribeAttribut | * MaxNetworkBandwidth | 0x000B | | * CurrentFrameRate | 0x000C | | * HDRModeEnabled | 0x000D | -| * CurrentVideoCodecs | 0x000E | -| * CurrentSnapshotConfig | 0x000F | -| * FabricsUsingCamera | 0x0010 | -| * AllocatedVideoStreams | 0x0011 | -| * AllocatedAudioStreams | 0x0012 | -| * AllocatedSnapshotStreams | 0x0013 | -| * RankedVideoStreamPrioritiesList | 0x0014 | -| * SoftRecordingPrivacyModeEnabled | 0x0015 | -| * SoftLivestreamPrivacyModeEnabled | 0x0016 | -| * HardPrivacyModeOn | 0x0017 | -| * NightVision | 0x0018 | -| * NightVisionIllum | 0x0019 | -| * AWBEnabled | 0x001A | -| * AutoShutterSpeedEnabled | 0x001B | -| * AutoISOEnabled | 0x001C | -| * Viewport | 0x001D | -| * SpeakerMuted | 0x001E | -| * SpeakerVolumeLevel | 0x001F | -| * SpeakerMaxLevel | 0x0020 | -| * SpeakerMinLevel | 0x0021 | -| * MicrophoneMuted | 0x0022 | -| * MicrophoneVolumeLevel | 0x0023 | -| * MicrophoneMaxLevel | 0x0024 | -| * MicrophoneMinLevel | 0x0025 | -| * MicrophoneAGCEnabled | 0x0026 | -| * ImageRotation | 0x0027 | -| * ImageFlipHorizontal | 0x0028 | -| * ImageFlipVertical | 0x0029 | -| * LocalVideoRecordingEnabled | 0x002A | -| * LocalSnapshotRecordingEnabled | 0x002B | -| * StatusLightEnabled | 0x002C | -| * StatusLightBrightness | 0x002D | -| * DepthSensorStatus | 0x002E | +| * FabricsUsingCamera | 0x000E | +| * AllocatedVideoStreams | 0x000F | +| * AllocatedAudioStreams | 0x0010 | +| * AllocatedSnapshotStreams | 0x0011 | +| * RankedVideoStreamPrioritiesList | 0x0012 | +| * SoftRecordingPrivacyModeEnabled | 0x0013 | +| * SoftLivestreamPrivacyModeEnabled | 0x0014 | +| * HardPrivacyModeOn | 0x0015 | +| * NightVision | 0x0016 | +| * NightVisionIllum | 0x0017 | +| * Viewport | 0x0018 | +| * SpeakerMuted | 0x0019 | +| * SpeakerVolumeLevel | 0x001A | +| * SpeakerMaxLevel | 0x001B | +| * SpeakerMinLevel | 0x001C | +| * MicrophoneMuted | 0x001D | +| * MicrophoneVolumeLevel | 0x001E | +| * MicrophoneMaxLevel | 0x001F | +| * MicrophoneMinLevel | 0x0020 | +| * MicrophoneAGCEnabled | 0x0021 | +| * ImageRotation | 0x0022 | +| * ImageFlipHorizontal | 0x0023 | +| * ImageFlipVertical | 0x0024 | +| * LocalVideoRecordingEnabled | 0x0025 | +| * LocalSnapshotRecordingEnabled | 0x0026 | +| * StatusLightEnabled | 0x0027 | +| * StatusLightBrightness | 0x0028 | | * GeneratedCommandList | 0xFFF8 | | * AcceptedCommandList | 0xFFF9 | | * AttributeList | 0xFFFB | @@ -151141,7 +151136,7 @@ class CameraAvStreamManagementSnapshotStreamAllocate : public ClusterCommand { AddArgument("ImageCodec", 0, UINT8_MAX, &mRequest.imageCodec); #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL - AddArgument("FrameRate", 0, UINT16_MAX, &mRequest.frameRate); + AddArgument("MaxFrameRate", 0, UINT16_MAX, &mRequest.maxFrameRate); #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL AddArgument("BitRate", 0, UINT32_MAX, &mRequest.bitRate); @@ -151173,7 +151168,7 @@ class CameraAvStreamManagementSnapshotStreamAllocate : public ClusterCommand { params.imageCodec = [NSNumber numberWithUnsignedChar:chip::to_underlying(mRequest.imageCodec)]; #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL - params.frameRate = [NSNumber numberWithUnsignedShort:mRequest.frameRate]; + params.maxFrameRate = [NSNumber numberWithUnsignedShort:mRequest.maxFrameRate]; #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL params.bitRate = [NSNumber numberWithUnsignedInt:mRequest.bitRate]; @@ -151401,224 +151396,6 @@ class CameraAvStreamManagementCaptureSnapshot : public ClusterCommand { TypedComplexArgument mComplex_RequestedResolution; }; -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL -/* - * Command SetViewport - */ -class CameraAvStreamManagementSetViewport : public ClusterCommand { -public: - CameraAvStreamManagementSetViewport() - : ClusterCommand("set-viewport") - , mComplex_Viewport(&mRequest.viewport) - { -#if MTR_ENABLE_PROVISIONAL - AddArgument("Viewport", &mComplex_Viewport); -#endif // MTR_ENABLE_PROVISIONAL - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, commandId, endpointId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRCameraAVStreamManagementClusterSetViewportParams alloc] init]; - params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; -#if MTR_ENABLE_PROVISIONAL - params.viewport = [MTRCameraAVStreamManagementClusterViewportStruct new]; - params.viewport.x1 = [NSNumber numberWithUnsignedShort:mRequest.viewport.x1]; - params.viewport.y1 = [NSNumber numberWithUnsignedShort:mRequest.viewport.y1]; - params.viewport.x2 = [NSNumber numberWithUnsignedShort:mRequest.viewport.x2]; - params.viewport.y2 = [NSNumber numberWithUnsignedShort:mRequest.viewport.y2]; -#endif // MTR_ENABLE_PROVISIONAL - uint16_t repeatCount = mRepeatCount.ValueOr(1); - uint16_t __block responsesNeeded = repeatCount; - while (repeatCount--) { - [cluster setViewportWithParams:params completion: - ^(NSError * _Nullable error) { - responsesNeeded--; - if (error != nil) { - mError = error; - LogNSError("Error", error); - RemoteDataModelLogger::LogCommandErrorAsJSON(@(endpointId), @(clusterId), @(commandId), error); - } - if (responsesNeeded == 0) { - SetCommandExitStatus(mError); - } - }]; - } - return CHIP_NO_ERROR; - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Type mRequest; - TypedComplexArgument mComplex_Viewport; -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL -/* - * Command SetImageRotation - */ -class CameraAvStreamManagementSetImageRotation : public ClusterCommand { -public: - CameraAvStreamManagementSetImageRotation() - : ClusterCommand("set-image-rotation") - { -#if MTR_ENABLE_PROVISIONAL - AddArgument("Angle", 0, UINT16_MAX, &mRequest.angle); -#endif // MTR_ENABLE_PROVISIONAL - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, commandId, endpointId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRCameraAVStreamManagementClusterSetImageRotationParams alloc] init]; - params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; -#if MTR_ENABLE_PROVISIONAL - params.angle = [NSNumber numberWithUnsignedShort:mRequest.angle]; -#endif // MTR_ENABLE_PROVISIONAL - uint16_t repeatCount = mRepeatCount.ValueOr(1); - uint16_t __block responsesNeeded = repeatCount; - while (repeatCount--) { - [cluster setImageRotationWithParams:params completion: - ^(NSError * _Nullable error) { - responsesNeeded--; - if (error != nil) { - mError = error; - LogNSError("Error", error); - RemoteDataModelLogger::LogCommandErrorAsJSON(@(endpointId), @(clusterId), @(commandId), error); - } - if (responsesNeeded == 0) { - SetCommandExitStatus(mError); - } - }]; - } - return CHIP_NO_ERROR; - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Type mRequest; -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL -/* - * Command SetImageFlipHorizontal - */ -class CameraAvStreamManagementSetImageFlipHorizontal : public ClusterCommand { -public: - CameraAvStreamManagementSetImageFlipHorizontal() - : ClusterCommand("set-image-flip-horizontal") - { -#if MTR_ENABLE_PROVISIONAL - AddArgument("Enabled", 0, 1, &mRequest.enabled); -#endif // MTR_ENABLE_PROVISIONAL - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, commandId, endpointId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams alloc] init]; - params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; -#if MTR_ENABLE_PROVISIONAL - params.enabled = [NSNumber numberWithBool:mRequest.enabled]; -#endif // MTR_ENABLE_PROVISIONAL - uint16_t repeatCount = mRepeatCount.ValueOr(1); - uint16_t __block responsesNeeded = repeatCount; - while (repeatCount--) { - [cluster setImageFlipHorizontalWithParams:params completion: - ^(NSError * _Nullable error) { - responsesNeeded--; - if (error != nil) { - mError = error; - LogNSError("Error", error); - RemoteDataModelLogger::LogCommandErrorAsJSON(@(endpointId), @(clusterId), @(commandId), error); - } - if (responsesNeeded == 0) { - SetCommandExitStatus(mError); - } - }]; - } - return CHIP_NO_ERROR; - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Type mRequest; -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL -/* - * Command SetImageFlipVertical - */ -class CameraAvStreamManagementSetImageFlipVertical : public ClusterCommand { -public: - CameraAvStreamManagementSetImageFlipVertical() - : ClusterCommand("set-image-flip-vertical") - { -#if MTR_ENABLE_PROVISIONAL - AddArgument("Enabled", 0, 1, &mRequest.enabled); -#endif // MTR_ENABLE_PROVISIONAL - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, commandId, endpointId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams alloc] init]; - params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; -#if MTR_ENABLE_PROVISIONAL - params.enabled = [NSNumber numberWithBool:mRequest.enabled]; -#endif // MTR_ENABLE_PROVISIONAL - uint16_t repeatCount = mRepeatCount.ValueOr(1); - uint16_t __block responsesNeeded = repeatCount; - while (repeatCount--) { - [cluster setImageFlipVerticalWithParams:params completion: - ^(NSError * _Nullable error) { - responsesNeeded--; - if (error != nil) { - mError = error; - LogNSError("Error", error); - RemoteDataModelLogger::LogCommandErrorAsJSON(@(endpointId), @(clusterId), @(commandId), error); - } - if (responsesNeeded == 0) { - SetCommandExitStatus(mError); - } - }]; - } - return CHIP_NO_ERROR; - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Type mRequest; -}; - #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -152855,34 +152632,34 @@ class SubscribeAttributeCameraAvStreamManagementHDRModeEnabled : public Subscrib #if MTR_ENABLE_PROVISIONAL /* - * Attribute CurrentVideoCodecs + * Attribute FabricsUsingCamera */ -class ReadCameraAvStreamManagementCurrentVideoCodecs : public ReadAttribute { +class ReadCameraAvStreamManagementFabricsUsingCamera : public ReadAttribute { public: - ReadCameraAvStreamManagementCurrentVideoCodecs() - : ReadAttribute("current-video-codecs") + ReadCameraAvStreamManagementFabricsUsingCamera() + : ReadAttribute("fabrics-using-camera") { } - ~ReadCameraAvStreamManagementCurrentVideoCodecs() + ~ReadCameraAvStreamManagementFabricsUsingCamera() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::CurrentVideoCodecs::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::FabricsUsingCamera::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeCurrentVideoCodecsWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.CurrentVideoCodecs response %@", [value description]); + [cluster readAttributeFabricsUsingCameraWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.FabricsUsingCamera response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { - LogNSError("CameraAVStreamManagement CurrentVideoCodecs read Error", error); + LogNSError("CameraAVStreamManagement FabricsUsingCamera read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -152891,21 +152668,21 @@ class ReadCameraAvStreamManagementCurrentVideoCodecs : public ReadAttribute { } }; -class SubscribeAttributeCameraAvStreamManagementCurrentVideoCodecs : public SubscribeAttribute { +class SubscribeAttributeCameraAvStreamManagementFabricsUsingCamera : public SubscribeAttribute { public: - SubscribeAttributeCameraAvStreamManagementCurrentVideoCodecs() - : SubscribeAttribute("current-video-codecs") + SubscribeAttributeCameraAvStreamManagementFabricsUsingCamera() + : SubscribeAttribute("fabrics-using-camera") { } - ~SubscribeAttributeCameraAvStreamManagementCurrentVideoCodecs() + ~SubscribeAttributeCameraAvStreamManagementFabricsUsingCamera() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::CurrentVideoCodecs::Id; + constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::FabricsUsingCamera::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -152920,10 +152697,10 @@ class SubscribeAttributeCameraAvStreamManagementCurrentVideoCodecs : public Subs if (mAutoResubscribe.HasValue()) { params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [cluster subscribeAttributeCurrentVideoCodecsWithParams:params + [cluster subscribeAttributeFabricsUsingCameraWithParams:params subscriptionEstablished:^() { mSubscriptionEstablished = YES; } reportHandler:^(NSArray * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.CurrentVideoCodecs response %@", [value description]); + NSLog(@"CameraAVStreamManagement.FabricsUsingCamera response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { @@ -152940,34 +152717,34 @@ class SubscribeAttributeCameraAvStreamManagementCurrentVideoCodecs : public Subs #if MTR_ENABLE_PROVISIONAL /* - * Attribute CurrentSnapshotConfig + * Attribute AllocatedVideoStreams */ -class ReadCameraAvStreamManagementCurrentSnapshotConfig : public ReadAttribute { +class ReadCameraAvStreamManagementAllocatedVideoStreams : public ReadAttribute { public: - ReadCameraAvStreamManagementCurrentSnapshotConfig() - : ReadAttribute("current-snapshot-config") + ReadCameraAvStreamManagementAllocatedVideoStreams() + : ReadAttribute("allocated-video-streams") { } - ~ReadCameraAvStreamManagementCurrentSnapshotConfig() + ~ReadCameraAvStreamManagementAllocatedVideoStreams() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::CurrentSnapshotConfig::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedVideoStreams::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeCurrentSnapshotConfigWithCompletion:^(MTRCameraAVStreamManagementClusterSnapshotParamsStruct * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.CurrentSnapshotConfig response %@", [value description]); + [cluster readAttributeAllocatedVideoStreamsWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.AllocatedVideoStreams response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { - LogNSError("CameraAVStreamManagement CurrentSnapshotConfig read Error", error); + LogNSError("CameraAVStreamManagement AllocatedVideoStreams read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -152976,21 +152753,21 @@ class ReadCameraAvStreamManagementCurrentSnapshotConfig : public ReadAttribute { } }; -class SubscribeAttributeCameraAvStreamManagementCurrentSnapshotConfig : public SubscribeAttribute { +class SubscribeAttributeCameraAvStreamManagementAllocatedVideoStreams : public SubscribeAttribute { public: - SubscribeAttributeCameraAvStreamManagementCurrentSnapshotConfig() - : SubscribeAttribute("current-snapshot-config") + SubscribeAttributeCameraAvStreamManagementAllocatedVideoStreams() + : SubscribeAttribute("allocated-video-streams") { } - ~SubscribeAttributeCameraAvStreamManagementCurrentSnapshotConfig() + ~SubscribeAttributeCameraAvStreamManagementAllocatedVideoStreams() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::CurrentSnapshotConfig::Id; + constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedVideoStreams::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -153005,10 +152782,10 @@ class SubscribeAttributeCameraAvStreamManagementCurrentSnapshotConfig : public S if (mAutoResubscribe.HasValue()) { params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [cluster subscribeAttributeCurrentSnapshotConfigWithParams:params + [cluster subscribeAttributeAllocatedVideoStreamsWithParams:params subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(MTRCameraAVStreamManagementClusterSnapshotParamsStruct * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.CurrentSnapshotConfig response %@", [value description]); + reportHandler:^(NSArray * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.AllocatedVideoStreams response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { @@ -153025,34 +152802,34 @@ class SubscribeAttributeCameraAvStreamManagementCurrentSnapshotConfig : public S #if MTR_ENABLE_PROVISIONAL /* - * Attribute FabricsUsingCamera + * Attribute AllocatedAudioStreams */ -class ReadCameraAvStreamManagementFabricsUsingCamera : public ReadAttribute { +class ReadCameraAvStreamManagementAllocatedAudioStreams : public ReadAttribute { public: - ReadCameraAvStreamManagementFabricsUsingCamera() - : ReadAttribute("fabrics-using-camera") + ReadCameraAvStreamManagementAllocatedAudioStreams() + : ReadAttribute("allocated-audio-streams") { } - ~ReadCameraAvStreamManagementFabricsUsingCamera() + ~ReadCameraAvStreamManagementAllocatedAudioStreams() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::FabricsUsingCamera::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedAudioStreams::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeFabricsUsingCameraWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.FabricsUsingCamera response %@", [value description]); + [cluster readAttributeAllocatedAudioStreamsWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.AllocatedAudioStreams response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { - LogNSError("CameraAVStreamManagement FabricsUsingCamera read Error", error); + LogNSError("CameraAVStreamManagement AllocatedAudioStreams read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -153061,21 +152838,21 @@ class ReadCameraAvStreamManagementFabricsUsingCamera : public ReadAttribute { } }; -class SubscribeAttributeCameraAvStreamManagementFabricsUsingCamera : public SubscribeAttribute { +class SubscribeAttributeCameraAvStreamManagementAllocatedAudioStreams : public SubscribeAttribute { public: - SubscribeAttributeCameraAvStreamManagementFabricsUsingCamera() - : SubscribeAttribute("fabrics-using-camera") + SubscribeAttributeCameraAvStreamManagementAllocatedAudioStreams() + : SubscribeAttribute("allocated-audio-streams") { } - ~SubscribeAttributeCameraAvStreamManagementFabricsUsingCamera() + ~SubscribeAttributeCameraAvStreamManagementAllocatedAudioStreams() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::FabricsUsingCamera::Id; + constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedAudioStreams::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -153090,10 +152867,10 @@ class SubscribeAttributeCameraAvStreamManagementFabricsUsingCamera : public Subs if (mAutoResubscribe.HasValue()) { params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [cluster subscribeAttributeFabricsUsingCameraWithParams:params + [cluster subscribeAttributeAllocatedAudioStreamsWithParams:params subscriptionEstablished:^() { mSubscriptionEstablished = YES; } reportHandler:^(NSArray * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.FabricsUsingCamera response %@", [value description]); + NSLog(@"CameraAVStreamManagement.AllocatedAudioStreams response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { @@ -153110,193 +152887,23 @@ class SubscribeAttributeCameraAvStreamManagementFabricsUsingCamera : public Subs #if MTR_ENABLE_PROVISIONAL /* - * Attribute AllocatedVideoStreams + * Attribute AllocatedSnapshotStreams */ -class ReadCameraAvStreamManagementAllocatedVideoStreams : public ReadAttribute { +class ReadCameraAvStreamManagementAllocatedSnapshotStreams : public ReadAttribute { public: - ReadCameraAvStreamManagementAllocatedVideoStreams() - : ReadAttribute("allocated-video-streams") + ReadCameraAvStreamManagementAllocatedSnapshotStreams() + : ReadAttribute("allocated-snapshot-streams") { } - ~ReadCameraAvStreamManagementAllocatedVideoStreams() + ~ReadCameraAvStreamManagementAllocatedSnapshotStreams() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedVideoStreams::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeAllocatedVideoStreamsWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AllocatedVideoStreams response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement AllocatedVideoStreams read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class SubscribeAttributeCameraAvStreamManagementAllocatedVideoStreams : public SubscribeAttribute { -public: - SubscribeAttributeCameraAvStreamManagementAllocatedVideoStreams() - : SubscribeAttribute("allocated-video-streams") - { - } - - ~SubscribeAttributeCameraAvStreamManagementAllocatedVideoStreams() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedVideoStreams::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; - if (mKeepSubscriptions.HasValue()) { - params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); - } - if (mFabricFiltered.HasValue()) { - params.filterByFabric = mFabricFiltered.Value(); - } - if (mAutoResubscribe.HasValue()) { - params.resubscribeAutomatically = mAutoResubscribe.Value(); - } - [cluster subscribeAttributeAllocatedVideoStreamsWithParams:params - subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(NSArray * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AllocatedVideoStreams response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - -/* - * Attribute AllocatedAudioStreams - */ -class ReadCameraAvStreamManagementAllocatedAudioStreams : public ReadAttribute { -public: - ReadCameraAvStreamManagementAllocatedAudioStreams() - : ReadAttribute("allocated-audio-streams") - { - } - - ~ReadCameraAvStreamManagementAllocatedAudioStreams() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedAudioStreams::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeAllocatedAudioStreamsWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AllocatedAudioStreams response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement AllocatedAudioStreams read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class SubscribeAttributeCameraAvStreamManagementAllocatedAudioStreams : public SubscribeAttribute { -public: - SubscribeAttributeCameraAvStreamManagementAllocatedAudioStreams() - : SubscribeAttribute("allocated-audio-streams") - { - } - - ~SubscribeAttributeCameraAvStreamManagementAllocatedAudioStreams() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedAudioStreams::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; - if (mKeepSubscriptions.HasValue()) { - params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); - } - if (mFabricFiltered.HasValue()) { - params.filterByFabric = mFabricFiltered.Value(); - } - if (mAutoResubscribe.HasValue()) { - params.resubscribeAutomatically = mAutoResubscribe.Value(); - } - [cluster subscribeAttributeAllocatedAudioStreamsWithParams:params - subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(NSArray * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AllocatedAudioStreams response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - -/* - * Attribute AllocatedSnapshotStreams - */ -class ReadCameraAvStreamManagementAllocatedSnapshotStreams : public ReadAttribute { -public: - ReadCameraAvStreamManagementAllocatedSnapshotStreams() - : ReadAttribute("allocated-snapshot-streams") - { - } - - ~ReadCameraAvStreamManagementAllocatedSnapshotStreams() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedSnapshotStreams::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AllocatedSnapshotStreams::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); @@ -153401,58 +153008,6 @@ class ReadCameraAvStreamManagementRankedVideoStreamPrioritiesList : public ReadA } }; -class WriteCameraAvStreamManagementRankedVideoStreamPrioritiesList : public WriteAttribute { -public: - WriteCameraAvStreamManagementRankedVideoStreamPrioritiesList() - : WriteAttribute("ranked-video-stream-priorities-list") - , mComplex(&mValue) - { - AddArgument("attr-name", "ranked-video-stream-priorities-list"); - AddArgument("attr-value", &mComplex); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementRankedVideoStreamPrioritiesList() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::RankedVideoStreamPrioritiesList::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSArray * _Nonnull value; - { // Scope for our temporary variables - auto * array_0 = [NSMutableArray new]; - for (auto & entry_0 : mValue) { - NSNumber * newElement_0; - newElement_0 = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0)]; - [array_0 addObject:newElement_0]; - } - value = array_0; - } - - [cluster writeAttributeRankedVideoStreamPrioritiesListWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement RankedVideoStreamPrioritiesList write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - chip::app::DataModel::List mValue; - TypedComplexArgument> mComplex; -}; - class SubscribeAttributeCameraAvStreamManagementRankedVideoStreamPrioritiesList : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementRankedVideoStreamPrioritiesList() @@ -153772,417 +153327,39 @@ class ReadCameraAvStreamManagementHardPrivacyModeOn : public ReadAttribute { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::HardPrivacyModeOn::Id; - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeHardPrivacyModeOnWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.HardPrivacyModeOn response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement HardPrivacyModeOn read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class SubscribeAttributeCameraAvStreamManagementHardPrivacyModeOn : public SubscribeAttribute { -public: - SubscribeAttributeCameraAvStreamManagementHardPrivacyModeOn() - : SubscribeAttribute("hard-privacy-mode-on") - { - } - - ~SubscribeAttributeCameraAvStreamManagementHardPrivacyModeOn() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::HardPrivacyModeOn::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; - if (mKeepSubscriptions.HasValue()) { - params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); - } - if (mFabricFiltered.HasValue()) { - params.filterByFabric = mFabricFiltered.Value(); - } - if (mAutoResubscribe.HasValue()) { - params.resubscribeAutomatically = mAutoResubscribe.Value(); - } - [cluster subscribeAttributeHardPrivacyModeOnWithParams:params - subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.HardPrivacyModeOn response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - -/* - * Attribute NightVision - */ -class ReadCameraAvStreamManagementNightVision : public ReadAttribute { -public: - ReadCameraAvStreamManagementNightVision() - : ReadAttribute("night-vision") - { - } - - ~ReadCameraAvStreamManagementNightVision() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVision::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeNightVisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.NightVision response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement NightVision read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class WriteCameraAvStreamManagementNightVision : public WriteAttribute { -public: - WriteCameraAvStreamManagementNightVision() - : WriteAttribute("night-vision") - { - AddArgument("attr-name", "night-vision"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementNightVision() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVision::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeNightVisionWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement NightVision write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - -class SubscribeAttributeCameraAvStreamManagementNightVision : public SubscribeAttribute { -public: - SubscribeAttributeCameraAvStreamManagementNightVision() - : SubscribeAttribute("night-vision") - { - } - - ~SubscribeAttributeCameraAvStreamManagementNightVision() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVision::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; - if (mKeepSubscriptions.HasValue()) { - params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); - } - if (mFabricFiltered.HasValue()) { - params.filterByFabric = mFabricFiltered.Value(); - } - if (mAutoResubscribe.HasValue()) { - params.resubscribeAutomatically = mAutoResubscribe.Value(); - } - [cluster subscribeAttributeNightVisionWithParams:params - subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.NightVision response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - -/* - * Attribute NightVisionIllum - */ -class ReadCameraAvStreamManagementNightVisionIllum : public ReadAttribute { -public: - ReadCameraAvStreamManagementNightVisionIllum() - : ReadAttribute("night-vision-illum") - { - } - - ~ReadCameraAvStreamManagementNightVisionIllum() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVisionIllum::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeNightVisionIllumWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.NightVisionIllum response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement NightVisionIllum read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class WriteCameraAvStreamManagementNightVisionIllum : public WriteAttribute { -public: - WriteCameraAvStreamManagementNightVisionIllum() - : WriteAttribute("night-vision-illum") - { - AddArgument("attr-name", "night-vision-illum"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementNightVisionIllum() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVisionIllum::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeNightVisionIllumWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement NightVisionIllum write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - -class SubscribeAttributeCameraAvStreamManagementNightVisionIllum : public SubscribeAttribute { -public: - SubscribeAttributeCameraAvStreamManagementNightVisionIllum() - : SubscribeAttribute("night-vision-illum") - { - } - - ~SubscribeAttributeCameraAvStreamManagementNightVisionIllum() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVisionIllum::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; - if (mKeepSubscriptions.HasValue()) { - params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); - } - if (mFabricFiltered.HasValue()) { - params.filterByFabric = mFabricFiltered.Value(); - } - if (mAutoResubscribe.HasValue()) { - params.resubscribeAutomatically = mAutoResubscribe.Value(); - } - [cluster subscribeAttributeNightVisionIllumWithParams:params - subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.NightVisionIllum response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - -/* - * Attribute AWBEnabled - */ -class ReadCameraAvStreamManagementAWBEnabled : public ReadAttribute { -public: - ReadCameraAvStreamManagementAWBEnabled() - : ReadAttribute("awbenabled") - { - } - - ~ReadCameraAvStreamManagementAWBEnabled() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AWBEnabled::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeAWBEnabledWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AWBEnabled response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement AWBEnabled read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class WriteCameraAvStreamManagementAWBEnabled : public WriteAttribute { -public: - WriteCameraAvStreamManagementAWBEnabled() - : WriteAttribute("awbenabled") - { - AddArgument("attr-name", "awbenabled"); - AddArgument("attr-value", 0, 1, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementAWBEnabled() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AWBEnabled::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; + ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - [cluster writeAttributeAWBEnabledWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement AWBEnabled write Error", error); + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; + [cluster readAttributeHardPrivacyModeOnWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.HardPrivacyModeOn response %@", [value description]); + if (error == nil) { + RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); + } else { + LogNSError("CameraAVStreamManagement HardPrivacyModeOn read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); }]; return CHIP_NO_ERROR; } - -private: - bool mValue; }; -class SubscribeAttributeCameraAvStreamManagementAWBEnabled : public SubscribeAttribute { +class SubscribeAttributeCameraAvStreamManagementHardPrivacyModeOn : public SubscribeAttribute { public: - SubscribeAttributeCameraAvStreamManagementAWBEnabled() - : SubscribeAttribute("awbenabled") + SubscribeAttributeCameraAvStreamManagementHardPrivacyModeOn() + : SubscribeAttribute("hard-privacy-mode-on") { } - ~SubscribeAttributeCameraAvStreamManagementAWBEnabled() + ~SubscribeAttributeCameraAvStreamManagementHardPrivacyModeOn() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AWBEnabled::Id; + constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::HardPrivacyModeOn::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154197,10 +153374,10 @@ class SubscribeAttributeCameraAvStreamManagementAWBEnabled : public SubscribeAtt if (mAutoResubscribe.HasValue()) { params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [cluster subscribeAttributeAWBEnabledWithParams:params + [cluster subscribeAttributeHardPrivacyModeOnWithParams:params subscriptionEstablished:^() { mSubscriptionEstablished = YES; } reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AWBEnabled response %@", [value description]); + NSLog(@"CameraAVStreamManagement.HardPrivacyModeOn response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { @@ -154217,34 +153394,34 @@ class SubscribeAttributeCameraAvStreamManagementAWBEnabled : public SubscribeAtt #if MTR_ENABLE_PROVISIONAL /* - * Attribute AutoShutterSpeedEnabled + * Attribute NightVision */ -class ReadCameraAvStreamManagementAutoShutterSpeedEnabled : public ReadAttribute { +class ReadCameraAvStreamManagementNightVision : public ReadAttribute { public: - ReadCameraAvStreamManagementAutoShutterSpeedEnabled() - : ReadAttribute("auto-shutter-speed-enabled") + ReadCameraAvStreamManagementNightVision() + : ReadAttribute("night-vision") { } - ~ReadCameraAvStreamManagementAutoShutterSpeedEnabled() + ~ReadCameraAvStreamManagementNightVision() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVision::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeAutoShutterSpeedEnabledWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AutoShutterSpeedEnabled response %@", [value description]); + [cluster readAttributeNightVisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.NightVision response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { - LogNSError("CameraAVStreamManagement AutoShutterSpeedEnabled read Error", error); + LogNSError("CameraAVStreamManagement NightVision read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -154253,24 +153430,24 @@ class ReadCameraAvStreamManagementAutoShutterSpeedEnabled : public ReadAttribute } }; -class WriteCameraAvStreamManagementAutoShutterSpeedEnabled : public WriteAttribute { +class WriteCameraAvStreamManagementNightVision : public WriteAttribute { public: - WriteCameraAvStreamManagementAutoShutterSpeedEnabled() - : WriteAttribute("auto-shutter-speed-enabled") + WriteCameraAvStreamManagementNightVision() + : WriteAttribute("night-vision") { - AddArgument("attr-name", "auto-shutter-speed-enabled"); - AddArgument("attr-value", 0, 1, &mValue); + AddArgument("attr-name", "night-vision"); + AddArgument("attr-value", 0, UINT8_MAX, &mValue); WriteAttribute::AddArguments(); } - ~WriteCameraAvStreamManagementAutoShutterSpeedEnabled() + ~WriteCameraAvStreamManagementNightVision() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVision::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154278,11 +153455,11 @@ class WriteCameraAvStreamManagementAutoShutterSpeedEnabled : public WriteAttribu __auto_type * params = [[MTRWriteParams alloc] init]; params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; + NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - [cluster writeAttributeAutoShutterSpeedEnabledWithValue:value params:params completion:^(NSError * _Nullable error) { + [cluster writeAttributeNightVisionWithValue:value params:params completion:^(NSError * _Nullable error) { if (error != nil) { - LogNSError("CameraAVStreamManagement AutoShutterSpeedEnabled write Error", error); + LogNSError("CameraAVStreamManagement NightVision write Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -154291,24 +153468,24 @@ class WriteCameraAvStreamManagementAutoShutterSpeedEnabled : public WriteAttribu } private: - bool mValue; + uint8_t mValue; }; -class SubscribeAttributeCameraAvStreamManagementAutoShutterSpeedEnabled : public SubscribeAttribute { +class SubscribeAttributeCameraAvStreamManagementNightVision : public SubscribeAttribute { public: - SubscribeAttributeCameraAvStreamManagementAutoShutterSpeedEnabled() - : SubscribeAttribute("auto-shutter-speed-enabled") + SubscribeAttributeCameraAvStreamManagementNightVision() + : SubscribeAttribute("night-vision") { } - ~SubscribeAttributeCameraAvStreamManagementAutoShutterSpeedEnabled() + ~SubscribeAttributeCameraAvStreamManagementNightVision() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::Id; + constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVision::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154323,10 +153500,10 @@ class SubscribeAttributeCameraAvStreamManagementAutoShutterSpeedEnabled : public if (mAutoResubscribe.HasValue()) { params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [cluster subscribeAttributeAutoShutterSpeedEnabledWithParams:params + [cluster subscribeAttributeNightVisionWithParams:params subscriptionEstablished:^() { mSubscriptionEstablished = YES; } reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AutoShutterSpeedEnabled response %@", [value description]); + NSLog(@"CameraAVStreamManagement.NightVision response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { @@ -154343,34 +153520,34 @@ class SubscribeAttributeCameraAvStreamManagementAutoShutterSpeedEnabled : public #if MTR_ENABLE_PROVISIONAL /* - * Attribute AutoISOEnabled + * Attribute NightVisionIllum */ -class ReadCameraAvStreamManagementAutoISOEnabled : public ReadAttribute { +class ReadCameraAvStreamManagementNightVisionIllum : public ReadAttribute { public: - ReadCameraAvStreamManagementAutoISOEnabled() - : ReadAttribute("auto-isoenabled") + ReadCameraAvStreamManagementNightVisionIllum() + : ReadAttribute("night-vision-illum") { } - ~ReadCameraAvStreamManagementAutoISOEnabled() + ~ReadCameraAvStreamManagementNightVisionIllum() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoISOEnabled::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVisionIllum::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeAutoISOEnabledWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AutoISOEnabled response %@", [value description]); + [cluster readAttributeNightVisionIllumWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.NightVisionIllum response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { - LogNSError("CameraAVStreamManagement AutoISOEnabled read Error", error); + LogNSError("CameraAVStreamManagement NightVisionIllum read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -154379,24 +153556,24 @@ class ReadCameraAvStreamManagementAutoISOEnabled : public ReadAttribute { } }; -class WriteCameraAvStreamManagementAutoISOEnabled : public WriteAttribute { +class WriteCameraAvStreamManagementNightVisionIllum : public WriteAttribute { public: - WriteCameraAvStreamManagementAutoISOEnabled() - : WriteAttribute("auto-isoenabled") + WriteCameraAvStreamManagementNightVisionIllum() + : WriteAttribute("night-vision-illum") { - AddArgument("attr-name", "auto-isoenabled"); - AddArgument("attr-value", 0, 1, &mValue); + AddArgument("attr-name", "night-vision-illum"); + AddArgument("attr-value", 0, UINT8_MAX, &mValue); WriteAttribute::AddArguments(); } - ~WriteCameraAvStreamManagementAutoISOEnabled() + ~WriteCameraAvStreamManagementNightVisionIllum() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoISOEnabled::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVisionIllum::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154404,11 +153581,11 @@ class WriteCameraAvStreamManagementAutoISOEnabled : public WriteAttribute { __auto_type * params = [[MTRWriteParams alloc] init]; params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; + NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - [cluster writeAttributeAutoISOEnabledWithValue:value params:params completion:^(NSError * _Nullable error) { + [cluster writeAttributeNightVisionIllumWithValue:value params:params completion:^(NSError * _Nullable error) { if (error != nil) { - LogNSError("CameraAVStreamManagement AutoISOEnabled write Error", error); + LogNSError("CameraAVStreamManagement NightVisionIllum write Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -154417,24 +153594,24 @@ class WriteCameraAvStreamManagementAutoISOEnabled : public WriteAttribute { } private: - bool mValue; + uint8_t mValue; }; -class SubscribeAttributeCameraAvStreamManagementAutoISOEnabled : public SubscribeAttribute { +class SubscribeAttributeCameraAvStreamManagementNightVisionIllum : public SubscribeAttribute { public: - SubscribeAttributeCameraAvStreamManagementAutoISOEnabled() - : SubscribeAttribute("auto-isoenabled") + SubscribeAttributeCameraAvStreamManagementNightVisionIllum() + : SubscribeAttribute("night-vision-illum") { } - ~SubscribeAttributeCameraAvStreamManagementAutoISOEnabled() + ~SubscribeAttributeCameraAvStreamManagementNightVisionIllum() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoISOEnabled::Id; + constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVisionIllum::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154449,10 +153626,10 @@ class SubscribeAttributeCameraAvStreamManagementAutoISOEnabled : public Subscrib if (mAutoResubscribe.HasValue()) { params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [cluster subscribeAttributeAutoISOEnabledWithParams:params + [cluster subscribeAttributeNightVisionIllumWithParams:params subscriptionEstablished:^() { mSubscriptionEstablished = YES; } reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AutoISOEnabled response %@", [value description]); + NSLog(@"CameraAVStreamManagement.NightVisionIllum response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { @@ -154505,6 +153682,54 @@ class ReadCameraAvStreamManagementViewport : public ReadAttribute { } }; +class WriteCameraAvStreamManagementViewport : public WriteAttribute { +public: + WriteCameraAvStreamManagementViewport() + : WriteAttribute("viewport") + , mComplex(&mValue) + { + AddArgument("attr-name", "viewport"); + AddArgument("attr-value", &mComplex); + WriteAttribute::AddArguments(); + } + + ~WriteCameraAvStreamManagementViewport() + { + } + + CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override + { + constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::Viewport::Id; + + ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; + __auto_type * params = [[MTRWriteParams alloc] init]; + params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; + params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; + MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull value; + value = [MTRCameraAVStreamManagementClusterViewportStruct new]; + value.x1 = [NSNumber numberWithUnsignedShort:mValue.x1]; + value.y1 = [NSNumber numberWithUnsignedShort:mValue.y1]; + value.x2 = [NSNumber numberWithUnsignedShort:mValue.x2]; + value.y2 = [NSNumber numberWithUnsignedShort:mValue.y2]; + + [cluster writeAttributeViewportWithValue:value params:params completion:^(NSError * _Nullable error) { + if (error != nil) { + LogNSError("CameraAVStreamManagement Viewport write Error", error); + RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); + } + SetCommandExitStatus(error); + }]; + return CHIP_NO_ERROR; + } + +private: + chip::app::Clusters::CameraAvStreamManagement::Structs::ViewportStruct::Type mValue; + TypedComplexArgument mComplex; +}; + class SubscribeAttributeCameraAvStreamManagementViewport : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementViewport() @@ -154842,47 +154067,6 @@ class ReadCameraAvStreamManagementSpeakerMaxLevel : public ReadAttribute { } }; -class WriteCameraAvStreamManagementSpeakerMaxLevel : public WriteAttribute { -public: - WriteCameraAvStreamManagementSpeakerMaxLevel() - : WriteAttribute("speaker-max-level") - { - AddArgument("attr-name", "speaker-max-level"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementSpeakerMaxLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMaxLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeSpeakerMaxLevelWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement SpeakerMaxLevel write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - class SubscribeAttributeCameraAvStreamManagementSpeakerMaxLevel : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementSpeakerMaxLevel() @@ -154968,47 +154152,6 @@ class ReadCameraAvStreamManagementSpeakerMinLevel : public ReadAttribute { } }; -class WriteCameraAvStreamManagementSpeakerMinLevel : public WriteAttribute { -public: - WriteCameraAvStreamManagementSpeakerMinLevel() - : WriteAttribute("speaker-min-level") - { - AddArgument("attr-name", "speaker-min-level"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementSpeakerMinLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMinLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeSpeakerMinLevelWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement SpeakerMinLevel write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - class SubscribeAttributeCameraAvStreamManagementSpeakerMinLevel : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementSpeakerMinLevel() @@ -155346,47 +154489,6 @@ class ReadCameraAvStreamManagementMicrophoneMaxLevel : public ReadAttribute { } }; -class WriteCameraAvStreamManagementMicrophoneMaxLevel : public WriteAttribute { -public: - WriteCameraAvStreamManagementMicrophoneMaxLevel() - : WriteAttribute("microphone-max-level") - { - AddArgument("attr-name", "microphone-max-level"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementMicrophoneMaxLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::MicrophoneMaxLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeMicrophoneMaxLevelWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement MicrophoneMaxLevel write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - class SubscribeAttributeCameraAvStreamManagementMicrophoneMaxLevel : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementMicrophoneMaxLevel() @@ -155426,63 +154528,26 @@ class SubscribeAttributeCameraAvStreamManagementMicrophoneMaxLevel : public Subs RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - -/* - * Attribute MicrophoneMinLevel - */ -class ReadCameraAvStreamManagementMicrophoneMinLevel : public ReadAttribute { -public: - ReadCameraAvStreamManagementMicrophoneMinLevel() - : ReadAttribute("microphone-min-level") - { - } - - ~ReadCameraAvStreamManagementMicrophoneMinLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::MicrophoneMinLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeMicrophoneMinLevelWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.MicrophoneMinLevel response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement MicrophoneMinLevel read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; + }]; + return CHIP_NO_ERROR; } }; -class WriteCameraAvStreamManagementMicrophoneMinLevel : public WriteAttribute { +#endif // MTR_ENABLE_PROVISIONAL +#if MTR_ENABLE_PROVISIONAL + +/* + * Attribute MicrophoneMinLevel + */ +class ReadCameraAvStreamManagementMicrophoneMinLevel : public ReadAttribute { public: - WriteCameraAvStreamManagementMicrophoneMinLevel() - : WriteAttribute("microphone-min-level") + ReadCameraAvStreamManagementMicrophoneMinLevel() + : ReadAttribute("microphone-min-level") { - AddArgument("attr-name", "microphone-min-level"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); } - ~WriteCameraAvStreamManagementMicrophoneMinLevel() + ~ReadCameraAvStreamManagementMicrophoneMinLevel() { } @@ -155491,26 +154556,22 @@ class WriteCameraAvStreamManagementMicrophoneMinLevel : public WriteAttribute { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::MicrophoneMinLevel::Id; - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); + ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeMicrophoneMinLevelWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement MicrophoneMinLevel write Error", error); + [cluster readAttributeMicrophoneMinLevelWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.MicrophoneMinLevel response %@", [value description]); + if (error == nil) { + RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); + } else { + LogNSError("CameraAVStreamManagement MicrophoneMinLevel read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); }]; return CHIP_NO_ERROR; } - -private: - uint8_t mValue; }; class SubscribeAttributeCameraAvStreamManagementMicrophoneMinLevel : public SubscribeAttribute { @@ -155724,6 +154785,47 @@ class ReadCameraAvStreamManagementImageRotation : public ReadAttribute { } }; +class WriteCameraAvStreamManagementImageRotation : public WriteAttribute { +public: + WriteCameraAvStreamManagementImageRotation() + : WriteAttribute("image-rotation") + { + AddArgument("attr-name", "image-rotation"); + AddArgument("attr-value", 0, UINT16_MAX, &mValue); + WriteAttribute::AddArguments(); + } + + ~WriteCameraAvStreamManagementImageRotation() + { + } + + CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override + { + constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::ImageRotation::Id; + + ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; + __auto_type * params = [[MTRWriteParams alloc] init]; + params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; + params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; + NSNumber * _Nonnull value = [NSNumber numberWithUnsignedShort:mValue]; + + [cluster writeAttributeImageRotationWithValue:value params:params completion:^(NSError * _Nullable error) { + if (error != nil) { + LogNSError("CameraAVStreamManagement ImageRotation write Error", error); + RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); + } + SetCommandExitStatus(error); + }]; + return CHIP_NO_ERROR; + } + +private: + uint16_t mValue; +}; + class SubscribeAttributeCameraAvStreamManagementImageRotation : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementImageRotation() @@ -155809,6 +154911,47 @@ class ReadCameraAvStreamManagementImageFlipHorizontal : public ReadAttribute { } }; +class WriteCameraAvStreamManagementImageFlipHorizontal : public WriteAttribute { +public: + WriteCameraAvStreamManagementImageFlipHorizontal() + : WriteAttribute("image-flip-horizontal") + { + AddArgument("attr-name", "image-flip-horizontal"); + AddArgument("attr-value", 0, 1, &mValue); + WriteAttribute::AddArguments(); + } + + ~WriteCameraAvStreamManagementImageFlipHorizontal() + { + } + + CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override + { + constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::ImageFlipHorizontal::Id; + + ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; + __auto_type * params = [[MTRWriteParams alloc] init]; + params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; + params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; + NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; + + [cluster writeAttributeImageFlipHorizontalWithValue:value params:params completion:^(NSError * _Nullable error) { + if (error != nil) { + LogNSError("CameraAVStreamManagement ImageFlipHorizontal write Error", error); + RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); + } + SetCommandExitStatus(error); + }]; + return CHIP_NO_ERROR; + } + +private: + bool mValue; +}; + class SubscribeAttributeCameraAvStreamManagementImageFlipHorizontal : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementImageFlipHorizontal() @@ -155894,6 +155037,47 @@ class ReadCameraAvStreamManagementImageFlipVertical : public ReadAttribute { } }; +class WriteCameraAvStreamManagementImageFlipVertical : public WriteAttribute { +public: + WriteCameraAvStreamManagementImageFlipVertical() + : WriteAttribute("image-flip-vertical") + { + AddArgument("attr-name", "image-flip-vertical"); + AddArgument("attr-value", 0, 1, &mValue); + WriteAttribute::AddArguments(); + } + + ~WriteCameraAvStreamManagementImageFlipVertical() + { + } + + CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override + { + constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::ImageFlipVertical::Id; + + ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; + __auto_type * params = [[MTRWriteParams alloc] init]; + params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; + params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; + NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; + + [cluster writeAttributeImageFlipVerticalWithValue:value params:params completion:^(NSError * _Nullable error) { + if (error != nil) { + LogNSError("CameraAVStreamManagement ImageFlipVertical write Error", error); + RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); + } + SetCommandExitStatus(error); + }]; + return CHIP_NO_ERROR; + } + +private: + bool mValue; +}; + class SubscribeAttributeCameraAvStreamManagementImageFlipVertical : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementImageFlipVertical() @@ -156446,132 +155630,6 @@ class SubscribeAttributeCameraAvStreamManagementStatusLightBrightness : public S #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL -/* - * Attribute DepthSensorStatus - */ -class ReadCameraAvStreamManagementDepthSensorStatus : public ReadAttribute { -public: - ReadCameraAvStreamManagementDepthSensorStatus() - : ReadAttribute("depth-sensor-status") - { - } - - ~ReadCameraAvStreamManagementDepthSensorStatus() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::DepthSensorStatus::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeDepthSensorStatusWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.DepthSensorStatus response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement DepthSensorStatus read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class WriteCameraAvStreamManagementDepthSensorStatus : public WriteAttribute { -public: - WriteCameraAvStreamManagementDepthSensorStatus() - : WriteAttribute("depth-sensor-status") - { - AddArgument("attr-name", "depth-sensor-status"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementDepthSensorStatus() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::DepthSensorStatus::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeDepthSensorStatusWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement DepthSensorStatus write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - -class SubscribeAttributeCameraAvStreamManagementDepthSensorStatus : public SubscribeAttribute { -public: - SubscribeAttributeCameraAvStreamManagementDepthSensorStatus() - : SubscribeAttribute("depth-sensor-status") - { - } - - ~SubscribeAttributeCameraAvStreamManagementDepthSensorStatus() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::DepthSensorStatus::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; - if (mKeepSubscriptions.HasValue()) { - params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); - } - if (mFabricFiltered.HasValue()) { - params.filterByFabric = mFabricFiltered.Value(); - } - if (mAutoResubscribe.HasValue()) { - params.resubscribeAutomatically = mAutoResubscribe.Value(); - } - [cluster subscribeAttributeDepthSensorStatusWithParams:params - subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.DepthSensorStatus response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - /* * Attribute GeneratedCommandList */ @@ -181872,9 +180930,9 @@ void registerClusterZoneManagement(Commands & commands) make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // - make_unique(), // + make_unique(), // + make_unique(), // + make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // @@ -181943,18 +181001,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands) #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // #endif // MTR_ENABLE_PROVISIONAL make_unique(Id), // make_unique(Id), // @@ -182016,14 +181062,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands) make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // make_unique(), // @@ -182042,7 +181080,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands) #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // - make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -182069,23 +181106,9 @@ void registerClusterCameraAvStreamManagement(Commands & commands) make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // + make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -182100,12 +181123,10 @@ void registerClusterCameraAvStreamManagement(Commands & commands) #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // - make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // - make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -182120,12 +181141,10 @@ void registerClusterCameraAvStreamManagement(Commands & commands) #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // - make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // - make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -182135,14 +181154,17 @@ void registerClusterCameraAvStreamManagement(Commands & commands) #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // + make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // + make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // + make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -182165,11 +181187,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands) make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // make_unique(), //