From 50654bff8deeca8e8de98e267c058776b31acbfe Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Fri, 9 Jun 2023 09:21:03 -0400 Subject: [PATCH 01/15] Fix method return type (strict python noticed we return None here) (#27156) * Fix method return type (strict python noticed we return None here) * Fix typo * Fix a typo * Revert unintended repo change --------- Co-authored-by: Andrei Litvin --- scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py | 4 ++-- src/lib/support/StringSplitter.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py b/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py index 81a6158f13f542..9499e360399230 100755 --- a/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py +++ b/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py @@ -5,7 +5,7 @@ import xml.etree.ElementTree from dataclasses import dataclass from enum import Enum, auto -from typing import List, MutableMapping, Tuple, Union +from typing import List, MutableMapping, Optional, Tuple, Union from lark import Lark from lark.visitors import Discard, Transformer, v_args @@ -167,7 +167,7 @@ def GetLinterRules(self): def RequireAttribute(self, r: AttributeRequirement): self._required_attributes_rule.RequireAttribute(r) - def FindClusterCode(self, name: str) -> Tuple[str, int]: + def FindClusterCode(self, name: str) -> Optional[Tuple[str, int]]: if name not in self._cluster_codes: # Name may be a number. If this can be parsed as a number, accept it anyway try: diff --git a/src/lib/support/StringSplitter.h b/src/lib/support/StringSplitter.h index abeed6fa4567f9..8434f2b02c90dc 100644 --- a/src/lib/support/StringSplitter.h +++ b/src/lib/support/StringSplitter.h @@ -44,7 +44,7 @@ class StringSplitter } } - /// Returns the next character san + /// Returns the next character span /// /// out - contains the next element or a nullptr/0 sized span if /// no elements available From 7f6723f0a3b947297636143959fb8fc3c94a0fcd Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 9 Jun 2023 12:57:25 -0400 Subject: [PATCH 02/15] Pin the checkout action to v3.5.2 for now. (#27178) 3.5.3 sparse checkout support seems to break in our CI. See https://github.com/actions/checkout/issues/1378 --- .github/workflows/bloat_check.yaml | 2 +- .github/workflows/build.yaml | 10 +++++----- .github/workflows/chef.yaml | 6 +++--- .github/workflows/cherry-picks.yaml | 2 +- .github/workflows/cirque.yaml | 2 +- .github/workflows/darwin-tests.yaml | 2 +- .github/workflows/darwin.yaml | 2 +- .github/workflows/docbuild.yaml | 2 +- .github/workflows/docker_img.yaml | 2 +- .github/workflows/doxygen.yaml | 2 +- .github/workflows/examples-ameba.yaml | 2 +- .github/workflows/examples-asr.yaml | 2 +- .github/workflows/examples-bouffalolab.yaml | 2 +- .github/workflows/examples-cc13x2x7_26x2x7.yaml | 2 +- .github/workflows/examples-cc32xx.yaml | 2 +- .github/workflows/examples-efr32.yaml | 2 +- .github/workflows/examples-esp32.yaml | 4 ++-- .github/workflows/examples-infineon.yaml | 2 +- .github/workflows/examples-k32w.yaml | 2 +- .github/workflows/examples-linux-arm.yaml | 2 +- .github/workflows/examples-linux-imx.yaml | 2 +- .github/workflows/examples-linux-standalone.yaml | 2 +- .github/workflows/examples-mbed.yaml | 2 +- .github/workflows/examples-mw320.yaml | 2 +- .github/workflows/examples-nrfconnect.yaml | 2 +- .github/workflows/examples-openiotsdk.yaml | 2 +- .github/workflows/examples-qpg.yaml | 2 +- .github/workflows/examples-telink.yaml | 2 +- .github/workflows/examples-tizen.yaml | 2 +- .github/workflows/fixit_rotation.yaml | 2 +- .github/workflows/full-android.yaml | 4 ++-- .github/workflows/fuzzing-build.yaml | 4 ++-- .github/workflows/gradle-wrapper-validation.yml | 2 +- .github/workflows/java-tests.yaml | 2 +- .github/workflows/lint.yml | 4 ++-- .github/workflows/minimal-build.yaml | 2 +- .github/workflows/qemu.yaml | 4 ++-- .github/workflows/release_artifacts.yaml | 4 ++-- .github/workflows/smoketest-android.yaml | 2 +- .github/workflows/smoketest-darwin.yaml | 2 +- .github/workflows/spell.yml | 4 ++-- .github/workflows/tests.yaml | 10 +++++----- .github/workflows/todos.yaml | 2 +- .github/workflows/unit_integration_test.yaml | 2 +- .github/workflows/zap_regeneration.yaml | 2 +- .github/workflows/zap_templates.yaml | 2 +- 46 files changed, 63 insertions(+), 63 deletions(-) diff --git a/.github/workflows/bloat_check.yaml b/.github/workflows/bloat_check.yaml index 01f041cdd0a506..f68127b364711d 100644 --- a/.github/workflows/bloat_check.yaml +++ b/.github/workflows/bloat_check.yaml @@ -39,7 +39,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index e4c4b5d337e06e..9774faa586efbe 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -56,7 +56,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -168,7 +168,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -340,7 +340,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -391,7 +391,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -499,7 +499,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/chef.yaml b/.github/workflows/chef.yaml index 671eb2a7c5a47f..c426996c187054 100644 --- a/.github/workflows/chef.yaml +++ b/.github/workflows/chef.yaml @@ -42,7 +42,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -78,7 +78,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -114,7 +114,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/cherry-picks.yaml b/.github/workflows/cherry-picks.yaml index d7ef371214f890..0fd7802dc461f4 100644 --- a/.github/workflows/cherry-picks.yaml +++ b/.github/workflows/cherry-picks.yaml @@ -20,7 +20,7 @@ jobs: ) steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v3.5.2 with: fetch-depth: 0 - name: Cherry-Pick into sve branch diff --git a/.github/workflows/cirque.yaml b/.github/workflows/cirque.yaml index ba6938efb7e19e..98baf36f6d61f3 100644 --- a/.github/workflows/cirque.yaml +++ b/.github/workflows/cirque.yaml @@ -57,7 +57,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/darwin-tests.yaml b/.github/workflows/darwin-tests.yaml index 825e7257851363..29f34356e5f607 100644 --- a/.github/workflows/darwin-tests.yaml +++ b/.github/workflows/darwin-tests.yaml @@ -50,7 +50,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/darwin.yaml b/.github/workflows/darwin.yaml index a7d8f31a819124..a78ab07cf02b68 100644 --- a/.github/workflows/darwin.yaml +++ b/.github/workflows/darwin.yaml @@ -41,7 +41,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/docbuild.yaml b/.github/workflows/docbuild.yaml index f49a9e660b4d12..ac2a8072c8045e 100644 --- a/.github/workflows/docbuild.yaml +++ b/.github/workflows/docbuild.yaml @@ -22,7 +22,7 @@ jobs: steps: - name: Checkout the code - uses: actions/checkout@v3 + uses: actions/checkout@v3.5.2 with: path: matter fetch-depth: 0 diff --git a/.github/workflows/docker_img.yaml b/.github/workflows/docker_img.yaml index b7d93bc49279ce..776a9539579585 100644 --- a/.github/workflows/docker_img.yaml +++ b/.github/workflows/docker_img.yaml @@ -62,7 +62,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/doxygen.yaml b/.github/workflows/doxygen.yaml index 3a0dc4a9d9f8b1..15c5477c848c57 100644 --- a/.github/workflows/doxygen.yaml +++ b/.github/workflows/doxygen.yaml @@ -90,7 +90,7 @@ jobs: - name: "Print Actor" run: echo ${{github.actor}} - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v3.5.2 - name: Generate run: scripts/helpers/doxygen.sh - name: Extract branch name diff --git a/.github/workflows/examples-ameba.yaml b/.github/workflows/examples-ameba.yaml index 175261cef97618..e188826740668f 100644 --- a/.github/workflows/examples-ameba.yaml +++ b/.github/workflows/examples-ameba.yaml @@ -45,7 +45,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-asr.yaml b/.github/workflows/examples-asr.yaml index 08dc3095ca5d7e..7a5722cf2918c7 100644 --- a/.github/workflows/examples-asr.yaml +++ b/.github/workflows/examples-asr.yaml @@ -43,7 +43,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index e548aa4259b929..3441ad51d2bc2a 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -45,7 +45,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-cc13x2x7_26x2x7.yaml b/.github/workflows/examples-cc13x2x7_26x2x7.yaml index ff03ba8ff93f34..0ebe1b067dbd49 100644 --- a/.github/workflows/examples-cc13x2x7_26x2x7.yaml +++ b/.github/workflows/examples-cc13x2x7_26x2x7.yaml @@ -49,7 +49,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-cc32xx.yaml b/.github/workflows/examples-cc32xx.yaml index f31cf1e8a20c28..712648d99870fe 100644 --- a/.github/workflows/examples-cc32xx.yaml +++ b/.github/workflows/examples-cc32xx.yaml @@ -47,7 +47,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-efr32.yaml b/.github/workflows/examples-efr32.yaml index d8961dde06c5a1..0f5db5783411e4 100644 --- a/.github/workflows/examples-efr32.yaml +++ b/.github/workflows/examples-efr32.yaml @@ -48,7 +48,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-esp32.yaml b/.github/workflows/examples-esp32.yaml index 637c797fe5ad90..5d36782b23f599 100644 --- a/.github/workflows/examples-esp32.yaml +++ b/.github/workflows/examples-esp32.yaml @@ -45,7 +45,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -170,7 +170,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-infineon.yaml b/.github/workflows/examples-infineon.yaml index b48aafbf4937da..e05a56b215a693 100644 --- a/.github/workflows/examples-infineon.yaml +++ b/.github/workflows/examples-infineon.yaml @@ -45,7 +45,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-k32w.yaml b/.github/workflows/examples-k32w.yaml index d5d31eddbdaba0..855f0ea88fa34b 100644 --- a/.github/workflows/examples-k32w.yaml +++ b/.github/workflows/examples-k32w.yaml @@ -47,7 +47,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-linux-arm.yaml b/.github/workflows/examples-linux-arm.yaml index b8af253b4923aa..3b293599b00787 100644 --- a/.github/workflows/examples-linux-arm.yaml +++ b/.github/workflows/examples-linux-arm.yaml @@ -45,7 +45,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-linux-imx.yaml b/.github/workflows/examples-linux-imx.yaml index 3dd30ed119a7a0..bb633d23f9ad8c 100644 --- a/.github/workflows/examples-linux-imx.yaml +++ b/.github/workflows/examples-linux-imx.yaml @@ -43,7 +43,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-linux-standalone.yaml b/.github/workflows/examples-linux-standalone.yaml index c291943771c827..8504087a83455e 100644 --- a/.github/workflows/examples-linux-standalone.yaml +++ b/.github/workflows/examples-linux-standalone.yaml @@ -45,7 +45,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-mbed.yaml b/.github/workflows/examples-mbed.yaml index 5f04e7eac1a26d..e32c75300ec63a 100644 --- a/.github/workflows/examples-mbed.yaml +++ b/.github/workflows/examples-mbed.yaml @@ -51,7 +51,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-mw320.yaml b/.github/workflows/examples-mw320.yaml index 9d64805bcb3b64..0d1a285f0de841 100755 --- a/.github/workflows/examples-mw320.yaml +++ b/.github/workflows/examples-mw320.yaml @@ -47,7 +47,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-nrfconnect.yaml b/.github/workflows/examples-nrfconnect.yaml index cb1c94f5915eae..034a532a93f25d 100644 --- a/.github/workflows/examples-nrfconnect.yaml +++ b/.github/workflows/examples-nrfconnect.yaml @@ -48,7 +48,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-openiotsdk.yaml b/.github/workflows/examples-openiotsdk.yaml index d2f2e904c70827..08f46969daee9b 100644 --- a/.github/workflows/examples-openiotsdk.yaml +++ b/.github/workflows/examples-openiotsdk.yaml @@ -50,7 +50,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-qpg.yaml b/.github/workflows/examples-qpg.yaml index bf97acb89b13ba..ab7d33b5ccab90 100644 --- a/.github/workflows/examples-qpg.yaml +++ b/.github/workflows/examples-qpg.yaml @@ -47,7 +47,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-telink.yaml b/.github/workflows/examples-telink.yaml index 8bddf9aa69b81c..74e050bb05f438 100644 --- a/.github/workflows/examples-telink.yaml +++ b/.github/workflows/examples-telink.yaml @@ -46,7 +46,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/examples-tizen.yaml b/.github/workflows/examples-tizen.yaml index dc6240fe45cbd6..a0f33c521040cd 100644 --- a/.github/workflows/examples-tizen.yaml +++ b/.github/workflows/examples-tizen.yaml @@ -46,7 +46,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/fixit_rotation.yaml b/.github/workflows/fixit_rotation.yaml index ac5383f789630a..c7ffed5302fae3 100644 --- a/.github/workflows/fixit_rotation.yaml +++ b/.github/workflows/fixit_rotation.yaml @@ -26,7 +26,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | submodules: true token: ${{ github.token }} diff --git a/.github/workflows/full-android.yaml b/.github/workflows/full-android.yaml index 7239575c686d4b..3b39c71b58a836 100644 --- a/.github/workflows/full-android.yaml +++ b/.github/workflows/full-android.yaml @@ -48,7 +48,7 @@ jobs: if: ${{ !env.ACT }} name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -59,7 +59,7 @@ jobs: # Note you likely still need to have non submodules setup for the # local machine, like: # git submodule deinit --all - - uses: actions/checkout@v3 + - uses: actions/checkout@v3.5.2 if: ${{ env.ACT }} name: Checkout (ACT for local build) - name: Checkout submodules diff --git a/.github/workflows/fuzzing-build.yaml b/.github/workflows/fuzzing-build.yaml index 68b62b88d87e12..4e589a98460b2b 100644 --- a/.github/workflows/fuzzing-build.yaml +++ b/.github/workflows/fuzzing-build.yaml @@ -44,7 +44,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | submodules: true token: ${{ github.token }} @@ -104,7 +104,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | submodules: true token: ${{ github.token }} diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml index 8bfd0dcf51f572..913c5672e3c09e 100644 --- a/.github/workflows/gradle-wrapper-validation.yml +++ b/.github/workflows/gradle-wrapper-validation.yml @@ -6,5 +6,5 @@ jobs: name: "Validation" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v3.5.2 - uses: gradle/wrapper-validation-action@v1 diff --git a/.github/workflows/java-tests.yaml b/.github/workflows/java-tests.yaml index 911c11ddbef771..37ebeeea0a01fa 100644 --- a/.github/workflows/java-tests.yaml +++ b/.github/workflows/java-tests.yaml @@ -49,7 +49,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v3.5.2 - name: Checkout submodules run: scripts/checkout_submodules.py --allow-changing-global-git-config --shallow --platform linux - name: Try to ensure the directories for core dumping exist and we diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 8a770ecb46b6f0..da846e5939ea0a 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -40,7 +40,7 @@ jobs: if: ${{ !env.ACT }} name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -51,7 +51,7 @@ jobs: # Note you likely still need to have non submodules setup for the # local machine, like: # git submodule deinit --all - - uses: actions/checkout@v3 + - uses: actions/checkout@v3.5.2 if: ${{ env.ACT }} name: Checkout (ACT for local build) diff --git a/.github/workflows/minimal-build.yaml b/.github/workflows/minimal-build.yaml index 67d9bbfdd642f8..77b801a749fb3a 100644 --- a/.github/workflows/minimal-build.yaml +++ b/.github/workflows/minimal-build.yaml @@ -36,7 +36,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v3.5.2 - name: Checkout submodules run: scripts/checkout_submodules.py --allow-changing-global-git-config --shallow --platform linux - name: Configure and build All Clusters App diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index b8d68f4a3a243e..2459ecbcaa5576 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -49,7 +49,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -113,7 +113,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/release_artifacts.yaml b/.github/workflows/release_artifacts.yaml index fc371f695ab25e..a525a97db0742d 100644 --- a/.github/workflows/release_artifacts.yaml +++ b/.github/workflows/release_artifacts.yaml @@ -40,7 +40,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | submodules: true token: ${{ github.token }} @@ -95,7 +95,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | submodules: true token: ${{ github.token }} diff --git a/.github/workflows/smoketest-android.yaml b/.github/workflows/smoketest-android.yaml index de1d5ab89e8cfb..cce15a04079562 100644 --- a/.github/workflows/smoketest-android.yaml +++ b/.github/workflows/smoketest-android.yaml @@ -48,7 +48,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/smoketest-darwin.yaml b/.github/workflows/smoketest-darwin.yaml index 0ab19f6dd92d44..13f328b02988e8 100644 --- a/.github/workflows/smoketest-darwin.yaml +++ b/.github/workflows/smoketest-darwin.yaml @@ -41,7 +41,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/spell.yml b/.github/workflows/spell.yml index f073c203385e53..3de0afa566469d 100644 --- a/.github/workflows/spell.yml +++ b/.github/workflows/spell.yml @@ -32,7 +32,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -47,7 +47,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 14146339d5844b..2d641bb21a0e53 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -59,7 +59,7 @@ jobs: if: ${{ !env.ACT }} name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -70,7 +70,7 @@ jobs: # Note you likely still need to have non submodules setup for the # local machine, like: # git submodule deinit --all - - uses: actions/checkout@v3 + - uses: actions/checkout@v3.5.2 if: ${{ env.ACT }} name: Checkout (ACT for local build) - name: Checkout submodules @@ -332,7 +332,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 @@ -463,7 +463,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v3.5.2 - name: Checkout submodules run: scripts/checkout_submodules.py --allow-changing-global-git-config --shallow --platform linux - name: Try to ensure the directories for core dumping exist and we @@ -551,7 +551,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v3.5.2 - name: Checkout submodules run: scripts/checkout_submodules.py --allow-changing-global-git-config --shallow --platform darwin - name: Setup Environment diff --git a/.github/workflows/todos.yaml b/.github/workflows/todos.yaml index 4381b3ca9d7638..f7e82d5f217eca 100644 --- a/.github/workflows/todos.yaml +++ b/.github/workflows/todos.yaml @@ -26,7 +26,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/unit_integration_test.yaml b/.github/workflows/unit_integration_test.yaml index c42595e1c98129..9a22f6bc0d6d71 100644 --- a/.github/workflows/unit_integration_test.yaml +++ b/.github/workflows/unit_integration_test.yaml @@ -47,7 +47,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 diff --git a/.github/workflows/zap_regeneration.yaml b/.github/workflows/zap_regeneration.yaml index 22cdb0430bc494..f30714c2a6bf65 100644 --- a/.github/workflows/zap_regeneration.yaml +++ b/.github/workflows/zap_regeneration.yaml @@ -43,7 +43,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | submodules: true token: ${{ github.token }} diff --git a/.github/workflows/zap_templates.yaml b/.github/workflows/zap_templates.yaml index 60513c863eec92..04cb6b8990af72 100644 --- a/.github/workflows/zap_templates.yaml +++ b/.github/workflows/zap_templates.yaml @@ -45,7 +45,7 @@ jobs: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout with: - action: actions/checkout@v3 + action: actions/checkout@v3.5.2 with: | token: ${{ github.token }} attempt_limit: 3 From d676bae2cb26636928a90ba23162db8cbe4f0e58 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 9 Jun 2023 13:12:53 -0400 Subject: [PATCH 03/15] Fix darwin-framework-tool build. (#27177) A merge conflict between #26882 and #27152 led to it not building. --- .../templates/tests/ciTests.json | 36 +- .../zap-generated/test/Commands.h | 6986 +---------------- 2 files changed, 117 insertions(+), 6905 deletions(-) diff --git a/examples/darwin-framework-tool/templates/tests/ciTests.json b/examples/darwin-framework-tool/templates/tests/ciTests.json index 109ffe2c10e07c..4d33395f379753 100644 --- a/examples/darwin-framework-tool/templates/tests/ciTests.json +++ b/examples/darwin-framework-tool/templates/tests/ciTests.json @@ -1,7 +1,6 @@ { "include": "../../../../src/app/tests/suites/ciTests.json", "disable": [ - "TestIcdManagementCluster", "Test_TC_SC_4_2", "Test_TC_SC_5_2", "TestClusterComplexTypes", @@ -32,6 +31,39 @@ "Test_TC_ACL_2_9", "Test_TC_ACL_2_10", "DL_LockUnlock", - "Test_TC_TIMESYNC_1_1" + "Disabled due to using ICD Management (ICDManagement) cluster, which is provisional on Darwin for now:", + "TestIcdManagementCluster", + "Disabled due to using Time Synchronization (TimeSynchronization) cluster, which is provisional on Darwin for now:", + "Test_TC_TIMESYNC_1_1", + "Disabled due to using provisional Ceramic Filter Monitoring (CeramicFilterMonitoring) cluster:", + "Test_TC_CFREMON_1_1", + "Test_TC_CFREMON_2_1", + "Disabled due to using provisional Electrostatic Filter Monitoring (ElectrostaticFilterMonitoring) cluster:", + "Test_TC_ESFREMON_1_1", + "Test_TC_ESFREMON_2_1", + "Disabled due to using provisional Fuel Tank Monitoring (FuelTankMonitoring) cluster:", + "Test_TC_FTREMON_1_1", + "Test_TC_FTREMON_2_1", + "Disabled due to using provisional Ink Cartridge Monitoring (InkCartridgeMonitoring) cluster:", + "Test_TC_INKCREMON_1_1", + "Test_TC_INKCREMON_2_1", + "Disabled due to using provisional Ionizing Filter Monitoring (IonizingFilterMonitoring) cluster:", + "Test_TC_IONFREMON_1_1", + "Test_TC_IONFREMON_2_1", + "Disabled due to using provisional Ozone Filter Monitoring (OzoneFilterMonitoring) cluster:", + "Test_TC_OZFREMON_1_1", + "Test_TC_OZFREMON_2_1", + "Disabled due to using provisional Toner Cartridge Monitoring (TonerCartridgeMonitoring) cluster:", + "Test_TC_TCREMON_1_1", + "Test_TC_TCREMON_2_1", + "Disabled due to using provisional UV Filter Monitoring (UVFilterMonitoring) cluster:", + "Test_TC_UVFREMON_1_1", + "Test_TC_UVFREMON_2_1", + "Disabled due to using provisional Water Tank Monitoring (WaterTankMonitoring) cluster:", + "Test_TC_WTREMON_1_1", + "Test_TC_WTREMON_2_1", + "Disabled due to using provisional Zeolite Filter Monitoring (ZeoliteFilterMonitoring) cluster:", + "Test_TC_ZEOFREMON_1_1", + "Test_TC_ZEOFREMON_2_1" ] } diff --git a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h index 54567b27ed5ba4..025c152bed88cc 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h @@ -247,28 +247,8 @@ class TestList : public Command { printf("Test_TC_G_1_1\n"); printf("Test_TC_ACFREMON_1_1\n"); printf("Test_TC_ACFREMON_2_1\n"); - printf("Test_TC_CFREMON_1_1\n"); - printf("Test_TC_CFREMON_2_1\n"); - printf("Test_TC_ESFREMON_1_1\n"); - printf("Test_TC_ESFREMON_2_1\n"); - printf("Test_TC_FTREMON_1_1\n"); - printf("Test_TC_FTREMON_2_1\n"); printf("Test_TC_HEPAFREMON_1_1\n"); printf("Test_TC_HEPAFREMON_2_1\n"); - printf("Test_TC_INKCREMON_1_1\n"); - printf("Test_TC_INKCREMON_2_1\n"); - printf("Test_TC_IONFREMON_1_1\n"); - printf("Test_TC_IONFREMON_2_1\n"); - printf("Test_TC_OZFREMON_1_1\n"); - printf("Test_TC_OZFREMON_2_1\n"); - printf("Test_TC_TCREMON_1_1\n"); - printf("Test_TC_TCREMON_2_1\n"); - printf("Test_TC_UVFREMON_1_1\n"); - printf("Test_TC_UVFREMON_2_1\n"); - printf("Test_TC_WTREMON_1_1\n"); - printf("Test_TC_WTREMON_2_1\n"); - printf("Test_TC_ZEOFREMON_1_1\n"); - printf("Test_TC_ZEOFREMON_2_1\n"); return CHIP_NO_ERROR; } @@ -147238,6791 +147218,11 @@ class Test_TC_ACFREMON_2_1 : public TestCommandBridge { } }; -class Test_TC_CFREMON_1_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_CFREMON_1_1() - : TestCommandBridge("Test_TC_CFREMON_1_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_CFREMON_1_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_CFREMON_1_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_CFREMON_1_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : Read the global attribute: ClusterRevision\n"); - err = TestReadTheGlobalAttributeClusterRevision_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!CFREMON.S.F00 && !CFREMON.S.F01")) { - NextTest(); - return; - } - err = TestReadTheGlobalAttributeFeatureMap_2(); - break; - case 3: - ChipLogProgress( - chipTool, " ***** Test Step 3 : Given CFREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("CFREMON.S.F00")) { - NextTest(); - return; - } - err = TestGivenCFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); - break; - case 4: - ChipLogProgress( - chipTool, " ***** Test Step 4 : Given CFREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("CFREMON.S.F01")) { - NextTest(); - return; - } - err = TestGivenCFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); - break; - case 5: - ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); - err = TestReadTheGlobalAttributeAttributeList_5(); - break; - case 6: - ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(CFREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("CFREMON.S.F00")) { - NextTest(); - return; - } - err = TestReadTheFeatureDependentCFREMONSF00AttributeInAttributeList_6(); - break; - case 7: - ChipLogProgress( - chipTool, " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (CFREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("CFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestReadTheOptionalAttributeInPlaceIndicatorCfremonsa0002InAttributeList_7(); - break; - case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); - err = TestReadTheGlobalAttributeAcceptedCommandList_8(); - break; - case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("CFREMON.S.C00.Rsp")) { - NextTest(); - return; - } - err = TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9(); - break; - case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Read the global attribute: GeneratedCommandList\n"); - err = TestReadTheGlobalAttributeGeneratedCommandList_10(); - break; - case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : TH reads EventList attribute from DUT\n"); - err = TestThReadsEventListAttributeFromDut_11(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 5: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 6: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 7: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 8: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 9: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 10: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 11: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 12; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestReadTheGlobalAttributeClusterRevision_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: ClusterRevision Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("ClusterRevision", actualValue, 1U)); - } - - VerifyOrReturn(CheckConstraintType("clusterRevision", "int16u", "int16u")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeFeatureMap_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: FeatureMap Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("FeatureMap", actualValue, 0UL)); - } - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenCFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given CFREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenCFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given CFREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAttributeList_5() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 2UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65528UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65529UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65530UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65531UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65532UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65533UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheFeatureDependentCFREMONSF00AttributeInAttributeList_6() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(CFREMON.S.F00) attribute in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 0UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 1UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorCfremonsa0002InAttributeList_7() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (CFREMON.S.A0002) in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 3UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAcceptedCommandList_8() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional command (ResetCondition) in AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("acceptedCommandList", value, 0UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeGeneratedCommandList_10() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: GeneratedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("GeneratedCommandList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("generatedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsEventListAttributeFromDut_11() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads EventList attribute from DUT Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("EventList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("eventList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_CFREMON_2_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_CFREMON_2_1() - : TestCommandBridge("Test_TC_CFREMON_2_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_CFREMON_2_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_CFREMON_2_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_CFREMON_2_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("CFREMON.S.A0000")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheConditionAttribute_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("CFREMON.S.A0001")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheDegradationDirectionAttribute_2(); - break; - case 3: - ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("CFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheChangeIndicationAttribute_3(); - break; - case 4: - ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("CFREMON.S.A0003")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 5; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestThReadsFromTheDutTheConditionAttribute_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the Condition attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("condition", "percent", "percent")); - VerifyOrReturn(CheckConstraintMinValue("condition", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("condition", [value unsignedCharValue], 100U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheDegradationDirectionAttribute_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the DegradationDirection attribute.. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("degradationDirection", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("degradationDirection", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("degradationDirection", [value unsignedCharValue], 1U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheChangeIndicationAttribute_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the ChangeIndication attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("changeIndication", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("changeIndication", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("changeIndication", [value unsignedCharValue], 2U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterCeramicFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the InPlaceIndicator attribute Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("inPlaceIndicator", "boolean", "boolean")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_ESFREMON_1_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_ESFREMON_1_1() - : TestCommandBridge("Test_TC_ESFREMON_1_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_ESFREMON_1_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_ESFREMON_1_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_ESFREMON_1_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : Read the global attribute: ClusterRevision\n"); - err = TestReadTheGlobalAttributeClusterRevision_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!ESFREMON.S.F00 && !ESFREMON.S.F01")) { - NextTest(); - return; - } - err = TestReadTheGlobalAttributeFeatureMap_2(); - break; - case 3: - ChipLogProgress( - chipTool, " ***** Test Step 3 : Given ESFREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("ESFREMON.S.F00")) { - NextTest(); - return; - } - err = TestGivenESFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); - break; - case 4: - ChipLogProgress( - chipTool, " ***** Test Step 4 : Given ESFREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("ESFREMON.S.F01")) { - NextTest(); - return; - } - err = TestGivenESFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); - break; - case 5: - ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); - err = TestReadTheGlobalAttributeAttributeList_5(); - break; - case 6: - ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(ESFREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("ESFREMON.S.F00")) { - NextTest(); - return; - } - err = TestReadTheFeatureDependentESFREMONSF00AttributeInAttributeList_6(); - break; - case 7: - ChipLogProgress(chipTool, - " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (ESFREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("ESFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestReadTheOptionalAttributeInPlaceIndicatorEsfremonsa0002InAttributeList_7(); - break; - case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); - err = TestReadTheGlobalAttributeAcceptedCommandList_8(); - break; - case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("ESFREMON.S.C00.Rsp")) { - NextTest(); - return; - } - err = TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9(); - break; - case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Read the global attribute: GeneratedCommandList\n"); - err = TestReadTheGlobalAttributeGeneratedCommandList_10(); - break; - case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : TH reads EventList attribute from DUT\n"); - err = TestThReadsEventListAttributeFromDut_11(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 5: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 6: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 7: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 8: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 9: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 10: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 11: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 12; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestReadTheGlobalAttributeClusterRevision_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: ClusterRevision Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("ClusterRevision", actualValue, 1U)); - } - - VerifyOrReturn(CheckConstraintType("clusterRevision", "int16u", "int16u")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeFeatureMap_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: FeatureMap Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("FeatureMap", actualValue, 0UL)); - } - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenESFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given ESFREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenESFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given ESFREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAttributeList_5() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 2UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65528UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65529UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65530UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65531UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65532UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65533UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheFeatureDependentESFREMONSF00AttributeInAttributeList_6() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(ESFREMON.S.F00) attribute in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 0UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 1UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorEsfremonsa0002InAttributeList_7() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (ESFREMON.S.A0002) in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 3UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAcceptedCommandList_8() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional command (ResetCondition) in AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("acceptedCommandList", value, 0UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeGeneratedCommandList_10() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: GeneratedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("GeneratedCommandList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("generatedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsEventListAttributeFromDut_11() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads EventList attribute from DUT Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("EventList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("eventList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_ESFREMON_2_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_ESFREMON_2_1() - : TestCommandBridge("Test_TC_ESFREMON_2_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_ESFREMON_2_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_ESFREMON_2_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_ESFREMON_2_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("ESFREMON.S.A0000")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheConditionAttribute_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("ESFREMON.S.A0001")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheDegradationDirectionAttribute_2(); - break; - case 3: - ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("ESFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheChangeIndicationAttribute_3(); - break; - case 4: - ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("ESFREMON.S.A0003")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 5; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestThReadsFromTheDutTheConditionAttribute_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the Condition attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("condition", "percent", "percent")); - VerifyOrReturn(CheckConstraintMinValue("condition", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("condition", [value unsignedCharValue], 100U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheDegradationDirectionAttribute_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the DegradationDirection attribute.. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("degradationDirection", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("degradationDirection", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("degradationDirection", [value unsignedCharValue], 1U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheChangeIndicationAttribute_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the ChangeIndication attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("changeIndication", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("changeIndication", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("changeIndication", [value unsignedCharValue], 2U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterElectrostaticFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the InPlaceIndicator attribute Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("inPlaceIndicator", "boolean", "boolean")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_FTREMON_1_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_FTREMON_1_1() - : TestCommandBridge("Test_TC_FTREMON_1_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_FTREMON_1_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_FTREMON_1_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_FTREMON_1_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : Read the global attribute: ClusterRevision\n"); - err = TestReadTheGlobalAttributeClusterRevision_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!FTREMON.S.F00 && !FTREMON.S.F01")) { - NextTest(); - return; - } - err = TestReadTheGlobalAttributeFeatureMap_2(); - break; - case 3: - ChipLogProgress( - chipTool, " ***** Test Step 3 : Given FTREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("FTREMON.S.F00")) { - NextTest(); - return; - } - err = TestGivenFTREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); - break; - case 4: - ChipLogProgress( - chipTool, " ***** Test Step 4 : Given FTREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("FTREMON.S.F01")) { - NextTest(); - return; - } - err = TestGivenFTREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); - break; - case 5: - ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); - err = TestReadTheGlobalAttributeAttributeList_5(); - break; - case 6: - ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(FTREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("FTREMON.S.F00")) { - NextTest(); - return; - } - err = TestReadTheFeatureDependentFTREMONSF00AttributeInAttributeList_6(); - break; - case 7: - ChipLogProgress( - chipTool, " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (FTREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("FTREMON.S.A0002")) { - NextTest(); - return; - } - err = TestReadTheOptionalAttributeInPlaceIndicatorFtremonsa0002InAttributeList_7(); - break; - case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); - err = TestReadTheGlobalAttributeAcceptedCommandList_8(); - break; - case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("FTREMON.S.C00.Rsp")) { - NextTest(); - return; - } - err = TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9(); - break; - case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Read the global attribute: GeneratedCommandList\n"); - err = TestReadTheGlobalAttributeGeneratedCommandList_10(); - break; - case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : TH reads EventList attribute from DUT\n"); - err = TestThReadsEventListAttributeFromDut_11(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 5: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 6: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 7: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 8: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 9: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 10: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 11: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 12; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestReadTheGlobalAttributeClusterRevision_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: ClusterRevision Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("ClusterRevision", actualValue, 1U)); - } - - VerifyOrReturn(CheckConstraintType("clusterRevision", "int16u", "int16u")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeFeatureMap_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: FeatureMap Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("FeatureMap", actualValue, 0UL)); - } - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenFTREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given FTREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenFTREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given FTREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAttributeList_5() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 2UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65528UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65529UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65530UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65531UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65532UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65533UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheFeatureDependentFTREMONSF00AttributeInAttributeList_6() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(FTREMON.S.F00) attribute in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 0UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 1UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorFtremonsa0002InAttributeList_7() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (FTREMON.S.A0002) in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 3UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAcceptedCommandList_8() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional command (ResetCondition) in AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("acceptedCommandList", value, 0UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeGeneratedCommandList_10() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: GeneratedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("GeneratedCommandList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("generatedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsEventListAttributeFromDut_11() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads EventList attribute from DUT Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("EventList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("eventList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_FTREMON_2_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_FTREMON_2_1() - : TestCommandBridge("Test_TC_FTREMON_2_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_FTREMON_2_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_FTREMON_2_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_FTREMON_2_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("FTREMON.S.A0000")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheConditionAttribute_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("FTREMON.S.A0001")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheDegradationDirectionAttribute_2(); - break; - case 3: - ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("FTREMON.S.A0002")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheChangeIndicationAttribute_3(); - break; - case 4: - ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("FTREMON.S.A0003")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 5; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestThReadsFromTheDutTheConditionAttribute_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the Condition attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("condition", "percent", "percent")); - VerifyOrReturn(CheckConstraintMinValue("condition", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("condition", [value unsignedCharValue], 100U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheDegradationDirectionAttribute_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the DegradationDirection attribute.. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("degradationDirection", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("degradationDirection", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("degradationDirection", [value unsignedCharValue], 1U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheChangeIndicationAttribute_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the ChangeIndication attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("changeIndication", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("changeIndication", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("changeIndication", [value unsignedCharValue], 2U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterFuelTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the InPlaceIndicator attribute Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("inPlaceIndicator", "boolean", "boolean")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_HEPAFREMON_1_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_HEPAFREMON_1_1() - : TestCommandBridge("Test_TC_HEPAFREMON_1_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_HEPAFREMON_1_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_HEPAFREMON_1_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_HEPAFREMON_1_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : Read the global attribute: ClusterRevision\n"); - err = TestReadTheGlobalAttributeClusterRevision_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!HEPAFREMON.S.F00 && !HEPAFREMON.S.F01")) { - NextTest(); - return; - } - err = TestReadTheGlobalAttributeFeatureMap_2(); - break; - case 3: - ChipLogProgress( - chipTool, " ***** Test Step 3 : Given HEPAFREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("HEPAFREMON.S.F00")) { - NextTest(); - return; - } - err = TestGivenHEPAFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); - break; - case 4: - ChipLogProgress( - chipTool, " ***** Test Step 4 : Given HEPAFREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("HEPAFREMON.S.F01")) { - NextTest(); - return; - } - err = TestGivenHEPAFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); - break; - case 5: - ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); - err = TestReadTheGlobalAttributeAttributeList_5(); - break; - case 6: - ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(HEPAFREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("HEPAFREMON.S.F00")) { - NextTest(); - return; - } - err = TestReadTheFeatureDependentHEPAFREMONSF00AttributeInAttributeList_6(); - break; - case 7: - ChipLogProgress(chipTool, - " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (HEPAFREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("HEPAFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestReadTheOptionalAttributeInPlaceIndicatorHepafremonsa0002InAttributeList_7(); - break; - case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); - err = TestReadTheGlobalAttributeAcceptedCommandList_8(); - break; - case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("HEPAFREMON.S.C00.Rsp")) { - NextTest(); - return; - } - err = TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9(); - break; - case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Read the global attribute: GeneratedCommandList\n"); - err = TestReadTheGlobalAttributeGeneratedCommandList_10(); - break; - case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : TH reads EventList attribute from DUT\n"); - err = TestThReadsEventListAttributeFromDut_11(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 5: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 6: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 7: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 8: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 9: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 10: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 11: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 12; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestReadTheGlobalAttributeClusterRevision_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: ClusterRevision Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("ClusterRevision", actualValue, 1U)); - } - - VerifyOrReturn(CheckConstraintType("clusterRevision", "int16u", "int16u")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeFeatureMap_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: FeatureMap Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("FeatureMap", actualValue, 0UL)); - } - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenHEPAFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given HEPAFREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenHEPAFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given HEPAFREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAttributeList_5() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 2UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65528UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65529UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65530UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65531UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65532UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65533UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheFeatureDependentHEPAFREMONSF00AttributeInAttributeList_6() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(HEPAFREMON.S.F00) attribute in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 0UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 1UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorHepafremonsa0002InAttributeList_7() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (HEPAFREMON.S.A0002) in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 3UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAcceptedCommandList_8() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional command (ResetCondition) in AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("acceptedCommandList", value, 0UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeGeneratedCommandList_10() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: GeneratedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("GeneratedCommandList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("generatedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsEventListAttributeFromDut_11() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads EventList attribute from DUT Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("EventList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("eventList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_HEPAFREMON_2_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_HEPAFREMON_2_1() - : TestCommandBridge("Test_TC_HEPAFREMON_2_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_HEPAFREMON_2_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_HEPAFREMON_2_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_HEPAFREMON_2_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("HEPAFREMON.S.A0000")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheConditionAttribute_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("HEPAFREMON.S.A0001")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheDegradationDirectionAttribute_2(); - break; - case 3: - ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("HEPAFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheChangeIndicationAttribute_3(); - break; - case 4: - ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("HEPAFREMON.S.A0003")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 5; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestThReadsFromTheDutTheConditionAttribute_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the Condition attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("condition", "percent", "percent")); - VerifyOrReturn(CheckConstraintMinValue("condition", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("condition", [value unsignedCharValue], 100U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheDegradationDirectionAttribute_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the DegradationDirection attribute.. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("degradationDirection", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("degradationDirection", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("degradationDirection", [value unsignedCharValue], 1U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheChangeIndicationAttribute_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the ChangeIndication attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("changeIndication", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("changeIndication", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("changeIndication", [value unsignedCharValue], 2U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the InPlaceIndicator attribute Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("inPlaceIndicator", "boolean", "boolean")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_INKCREMON_1_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_INKCREMON_1_1() - : TestCommandBridge("Test_TC_INKCREMON_1_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_INKCREMON_1_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_INKCREMON_1_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_INKCREMON_1_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : Read the global attribute: ClusterRevision\n"); - err = TestReadTheGlobalAttributeClusterRevision_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!INKCREMON.S.F00 && !INKCREMON.S.F01")) { - NextTest(); - return; - } - err = TestReadTheGlobalAttributeFeatureMap_2(); - break; - case 3: - ChipLogProgress( - chipTool, " ***** Test Step 3 : Given INKCREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("INKCREMON.S.F00")) { - NextTest(); - return; - } - err = TestGivenINKCREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); - break; - case 4: - ChipLogProgress( - chipTool, " ***** Test Step 4 : Given INKCREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("INKCREMON.S.F01")) { - NextTest(); - return; - } - err = TestGivenINKCREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); - break; - case 5: - ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); - err = TestReadTheGlobalAttributeAttributeList_5(); - break; - case 6: - ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(INKCREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("INKCREMON.S.F00")) { - NextTest(); - return; - } - err = TestReadTheFeatureDependentINKCREMONSF00AttributeInAttributeList_6(); - break; - case 7: - ChipLogProgress(chipTool, - " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (INKCREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("INKCREMON.S.A0002")) { - NextTest(); - return; - } - err = TestReadTheOptionalAttributeInPlaceIndicatorInkcremonsa0002InAttributeList_7(); - break; - case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); - err = TestReadTheGlobalAttributeAcceptedCommandList_8(); - break; - case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("INKCREMON.S.C00.Rsp")) { - NextTest(); - return; - } - err = TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9(); - break; - case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Read the global attribute: GeneratedCommandList\n"); - err = TestReadTheGlobalAttributeGeneratedCommandList_10(); - break; - case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : TH reads EventList attribute from DUT\n"); - err = TestThReadsEventListAttributeFromDut_11(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 5: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 6: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 7: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 8: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 9: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 10: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 11: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 12; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestReadTheGlobalAttributeClusterRevision_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: ClusterRevision Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("ClusterRevision", actualValue, 1U)); - } - - VerifyOrReturn(CheckConstraintType("clusterRevision", "int16u", "int16u")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeFeatureMap_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: FeatureMap Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("FeatureMap", actualValue, 0UL)); - } - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenINKCREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given INKCREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenINKCREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given INKCREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAttributeList_5() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 2UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65528UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65529UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65530UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65531UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65532UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65533UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheFeatureDependentINKCREMONSF00AttributeInAttributeList_6() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(INKCREMON.S.F00) attribute in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 0UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 1UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorInkcremonsa0002InAttributeList_7() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (INKCREMON.S.A0002) in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 3UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAcceptedCommandList_8() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional command (ResetCondition) in AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("acceptedCommandList", value, 0UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeGeneratedCommandList_10() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: GeneratedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("GeneratedCommandList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("generatedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsEventListAttributeFromDut_11() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads EventList attribute from DUT Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("EventList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("eventList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_INKCREMON_2_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_INKCREMON_2_1() - : TestCommandBridge("Test_TC_INKCREMON_2_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_INKCREMON_2_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_INKCREMON_2_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_INKCREMON_2_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("INKCREMON.S.A0000")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheConditionAttribute_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("INKCREMON.S.A0001")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheDegradationDirectionAttribute_2(); - break; - case 3: - ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("INKCREMON.S.A0002")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheChangeIndicationAttribute_3(); - break; - case 4: - ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("INKCREMON.S.A0003")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 5; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestThReadsFromTheDutTheConditionAttribute_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the Condition attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("condition", "percent", "percent")); - VerifyOrReturn(CheckConstraintMinValue("condition", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("condition", [value unsignedCharValue], 100U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheDegradationDirectionAttribute_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the DegradationDirection attribute.. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("degradationDirection", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("degradationDirection", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("degradationDirection", [value unsignedCharValue], 1U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheChangeIndicationAttribute_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the ChangeIndication attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("changeIndication", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("changeIndication", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("changeIndication", [value unsignedCharValue], 2U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterInkCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the InPlaceIndicator attribute Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("inPlaceIndicator", "boolean", "boolean")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_IONFREMON_1_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_IONFREMON_1_1() - : TestCommandBridge("Test_TC_IONFREMON_1_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_IONFREMON_1_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_IONFREMON_1_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_IONFREMON_1_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : Read the global attribute: ClusterRevision\n"); - err = TestReadTheGlobalAttributeClusterRevision_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!IONFREMON.S.F00 && !IONFREMON.S.F01")) { - NextTest(); - return; - } - err = TestReadTheGlobalAttributeFeatureMap_2(); - break; - case 3: - ChipLogProgress( - chipTool, " ***** Test Step 3 : Given IONFREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("IONFREMON.S.F00")) { - NextTest(); - return; - } - err = TestGivenIONFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); - break; - case 4: - ChipLogProgress( - chipTool, " ***** Test Step 4 : Given IONFREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("IONFREMON.S.F01")) { - NextTest(); - return; - } - err = TestGivenIONFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); - break; - case 5: - ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); - err = TestReadTheGlobalAttributeAttributeList_5(); - break; - case 6: - ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(IONFREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("IONFREMON.S.F00")) { - NextTest(); - return; - } - err = TestReadTheFeatureDependentIONFREMONSF00AttributeInAttributeList_6(); - break; - case 7: - ChipLogProgress(chipTool, - " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (IONFREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("IONFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestReadTheOptionalAttributeInPlaceIndicatorIonfremonsa0002InAttributeList_7(); - break; - case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); - err = TestReadTheGlobalAttributeAcceptedCommandList_8(); - break; - case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("IONFREMON.S.C00.Rsp")) { - NextTest(); - return; - } - err = TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9(); - break; - case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Read the global attribute: GeneratedCommandList\n"); - err = TestReadTheGlobalAttributeGeneratedCommandList_10(); - break; - case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : TH reads EventList attribute from DUT\n"); - err = TestThReadsEventListAttributeFromDut_11(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 5: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 6: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 7: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 8: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 9: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 10: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 11: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 12; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestReadTheGlobalAttributeClusterRevision_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: ClusterRevision Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("ClusterRevision", actualValue, 1U)); - } - - VerifyOrReturn(CheckConstraintType("clusterRevision", "int16u", "int16u")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeFeatureMap_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: FeatureMap Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("FeatureMap", actualValue, 0UL)); - } - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenIONFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given IONFREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenIONFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given IONFREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAttributeList_5() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 2UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65528UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65529UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65530UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65531UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65532UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65533UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheFeatureDependentIONFREMONSF00AttributeInAttributeList_6() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(IONFREMON.S.F00) attribute in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 0UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 1UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorIonfremonsa0002InAttributeList_7() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (IONFREMON.S.A0002) in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 3UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAcceptedCommandList_8() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional command (ResetCondition) in AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("acceptedCommandList", value, 0UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeGeneratedCommandList_10() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: GeneratedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("GeneratedCommandList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("generatedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsEventListAttributeFromDut_11() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads EventList attribute from DUT Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("EventList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("eventList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_IONFREMON_2_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_IONFREMON_2_1() - : TestCommandBridge("Test_TC_IONFREMON_2_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_IONFREMON_2_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_IONFREMON_2_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_IONFREMON_2_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("IONFREMON.S.A0000")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheConditionAttribute_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("IONFREMON.S.A0001")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheDegradationDirectionAttribute_2(); - break; - case 3: - ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("IONFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheChangeIndicationAttribute_3(); - break; - case 4: - ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("IONFREMON.S.A0003")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 5; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestThReadsFromTheDutTheConditionAttribute_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the Condition attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("condition", "percent", "percent")); - VerifyOrReturn(CheckConstraintMinValue("condition", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("condition", [value unsignedCharValue], 100U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheDegradationDirectionAttribute_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the DegradationDirection attribute.. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("degradationDirection", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("degradationDirection", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("degradationDirection", [value unsignedCharValue], 1U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheChangeIndicationAttribute_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the ChangeIndication attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("changeIndication", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("changeIndication", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("changeIndication", [value unsignedCharValue], 2U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterIonizingFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the InPlaceIndicator attribute Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("inPlaceIndicator", "boolean", "boolean")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_OZFREMON_1_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_OZFREMON_1_1() - : TestCommandBridge("Test_TC_OZFREMON_1_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_OZFREMON_1_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_OZFREMON_1_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_OZFREMON_1_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : Read the global attribute: ClusterRevision\n"); - err = TestReadTheGlobalAttributeClusterRevision_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!OZFREMON.S.F00 && !OZFREMON.S.F01")) { - NextTest(); - return; - } - err = TestReadTheGlobalAttributeFeatureMap_2(); - break; - case 3: - ChipLogProgress( - chipTool, " ***** Test Step 3 : Given OZFREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("OZFREMON.S.F00")) { - NextTest(); - return; - } - err = TestGivenOZFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); - break; - case 4: - ChipLogProgress( - chipTool, " ***** Test Step 4 : Given OZFREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("OZFREMON.S.F01")) { - NextTest(); - return; - } - err = TestGivenOZFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); - break; - case 5: - ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); - err = TestReadTheGlobalAttributeAttributeList_5(); - break; - case 6: - ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(OZFREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("OZFREMON.S.F00")) { - NextTest(); - return; - } - err = TestReadTheFeatureDependentOZFREMONSF00AttributeInAttributeList_6(); - break; - case 7: - ChipLogProgress(chipTool, - " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (OZFREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("OZFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestReadTheOptionalAttributeInPlaceIndicatorOzfremonsa0002InAttributeList_7(); - break; - case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); - err = TestReadTheGlobalAttributeAcceptedCommandList_8(); - break; - case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("OZFREMON.S.C00.Rsp")) { - NextTest(); - return; - } - err = TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9(); - break; - case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Read the global attribute: GeneratedCommandList\n"); - err = TestReadTheGlobalAttributeGeneratedCommandList_10(); - break; - case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : TH reads EventList attribute from DUT\n"); - err = TestThReadsEventListAttributeFromDut_11(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 5: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 6: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 7: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 8: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 9: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 10: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 11: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 12; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestReadTheGlobalAttributeClusterRevision_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: ClusterRevision Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("ClusterRevision", actualValue, 1U)); - } - - VerifyOrReturn(CheckConstraintType("clusterRevision", "int16u", "int16u")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeFeatureMap_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: FeatureMap Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("FeatureMap", actualValue, 0UL)); - } - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenOZFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given OZFREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenOZFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given OZFREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAttributeList_5() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 2UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65528UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65529UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65530UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65531UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65532UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65533UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheFeatureDependentOZFREMONSF00AttributeInAttributeList_6() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(OZFREMON.S.F00) attribute in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 0UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 1UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorOzfremonsa0002InAttributeList_7() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (OZFREMON.S.A0002) in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 3UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAcceptedCommandList_8() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional command (ResetCondition) in AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("acceptedCommandList", value, 0UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeGeneratedCommandList_10() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: GeneratedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("GeneratedCommandList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("generatedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsEventListAttributeFromDut_11() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads EventList attribute from DUT Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("EventList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("eventList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_OZFREMON_2_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_OZFREMON_2_1() - : TestCommandBridge("Test_TC_OZFREMON_2_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_OZFREMON_2_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_OZFREMON_2_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_OZFREMON_2_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("OZFREMON.S.A0000")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheConditionAttribute_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("OZFREMON.S.A0001")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheDegradationDirectionAttribute_2(); - break; - case 3: - ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("OZFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheChangeIndicationAttribute_3(); - break; - case 4: - ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("OZFREMON.S.A0003")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 5; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestThReadsFromTheDutTheConditionAttribute_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the Condition attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("condition", "percent", "percent")); - VerifyOrReturn(CheckConstraintMinValue("condition", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("condition", [value unsignedCharValue], 100U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheDegradationDirectionAttribute_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the DegradationDirection attribute.. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("degradationDirection", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("degradationDirection", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("degradationDirection", [value unsignedCharValue], 1U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheChangeIndicationAttribute_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the ChangeIndication attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("changeIndication", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("changeIndication", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("changeIndication", [value unsignedCharValue], 2U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterOzoneFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the InPlaceIndicator attribute Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("inPlaceIndicator", "boolean", "boolean")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_TCREMON_1_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_TCREMON_1_1() - : TestCommandBridge("Test_TC_TCREMON_1_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_TCREMON_1_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_TCREMON_1_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_TCREMON_1_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : Read the global attribute: ClusterRevision\n"); - err = TestReadTheGlobalAttributeClusterRevision_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!TCREMON.S.F00 && !TCREMON.S.F01")) { - NextTest(); - return; - } - err = TestReadTheGlobalAttributeFeatureMap_2(); - break; - case 3: - ChipLogProgress( - chipTool, " ***** Test Step 3 : Given TCREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("TCREMON.S.F00")) { - NextTest(); - return; - } - err = TestGivenTCREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); - break; - case 4: - ChipLogProgress( - chipTool, " ***** Test Step 4 : Given TCREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("TCREMON.S.F01")) { - NextTest(); - return; - } - err = TestGivenTCREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); - break; - case 5: - ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); - err = TestReadTheGlobalAttributeAttributeList_5(); - break; - case 6: - ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(TCREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("TCREMON.S.F00")) { - NextTest(); - return; - } - err = TestReadTheFeatureDependentTCREMONSF00AttributeInAttributeList_6(); - break; - case 7: - ChipLogProgress( - chipTool, " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (TCREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("TCREMON.S.A0002")) { - NextTest(); - return; - } - err = TestReadTheOptionalAttributeInPlaceIndicatorTcremonsa0002InAttributeList_7(); - break; - case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); - err = TestReadTheGlobalAttributeAcceptedCommandList_8(); - break; - case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("TCREMON.S.C00.Rsp")) { - NextTest(); - return; - } - err = TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9(); - break; - case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Read the global attribute: GeneratedCommandList\n"); - err = TestReadTheGlobalAttributeGeneratedCommandList_10(); - break; - case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : TH reads EventList attribute from DUT\n"); - err = TestThReadsEventListAttributeFromDut_11(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 5: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 6: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 7: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 8: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 9: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 10: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 11: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 12; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestReadTheGlobalAttributeClusterRevision_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: ClusterRevision Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("ClusterRevision", actualValue, 1U)); - } - - VerifyOrReturn(CheckConstraintType("clusterRevision", "int16u", "int16u")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeFeatureMap_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: FeatureMap Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("FeatureMap", actualValue, 0UL)); - } - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenTCREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given TCREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenTCREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given TCREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAttributeList_5() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 2UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65528UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65529UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65530UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65531UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65532UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65533UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheFeatureDependentTCREMONSF00AttributeInAttributeList_6() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(TCREMON.S.F00) attribute in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 0UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 1UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorTcremonsa0002InAttributeList_7() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (TCREMON.S.A0002) in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 3UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAcceptedCommandList_8() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional command (ResetCondition) in AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("acceptedCommandList", value, 0UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeGeneratedCommandList_10() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: GeneratedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("GeneratedCommandList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("generatedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsEventListAttributeFromDut_11() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads EventList attribute from DUT Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("EventList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("eventList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_TCREMON_2_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_TCREMON_2_1() - : TestCommandBridge("Test_TC_TCREMON_2_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_TCREMON_2_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_TCREMON_2_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_TCREMON_2_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("TCREMON.S.A0000")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheConditionAttribute_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("TCREMON.S.A0001")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheDegradationDirectionAttribute_2(); - break; - case 3: - ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("TCREMON.S.A0002")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheChangeIndicationAttribute_3(); - break; - case 4: - ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("TCREMON.S.A0003")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 5; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestThReadsFromTheDutTheConditionAttribute_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the Condition attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("condition", "percent", "percent")); - VerifyOrReturn(CheckConstraintMinValue("condition", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("condition", [value unsignedCharValue], 100U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheDegradationDirectionAttribute_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the DegradationDirection attribute.. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("degradationDirection", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("degradationDirection", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("degradationDirection", [value unsignedCharValue], 1U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheChangeIndicationAttribute_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the ChangeIndication attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("changeIndication", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("changeIndication", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("changeIndication", [value unsignedCharValue], 2U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterTonerCartridgeMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the InPlaceIndicator attribute Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("inPlaceIndicator", "boolean", "boolean")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_UVFREMON_1_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_UVFREMON_1_1() - : TestCommandBridge("Test_TC_UVFREMON_1_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_UVFREMON_1_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_UVFREMON_1_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_UVFREMON_1_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : Read the global attribute: ClusterRevision\n"); - err = TestReadTheGlobalAttributeClusterRevision_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!UVFREMON.S.F00 && !UVFREMON.S.F01")) { - NextTest(); - return; - } - err = TestReadTheGlobalAttributeFeatureMap_2(); - break; - case 3: - ChipLogProgress( - chipTool, " ***** Test Step 3 : Given UVFREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("UVFREMON.S.F00")) { - NextTest(); - return; - } - err = TestGivenUVFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); - break; - case 4: - ChipLogProgress( - chipTool, " ***** Test Step 4 : Given UVFREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("UVFREMON.S.F01")) { - NextTest(); - return; - } - err = TestGivenUVFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); - break; - case 5: - ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); - err = TestReadTheGlobalAttributeAttributeList_5(); - break; - case 6: - ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(UVFREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("UVFREMON.S.F00")) { - NextTest(); - return; - } - err = TestReadTheFeatureDependentUVFREMONSF00AttributeInAttributeList_6(); - break; - case 7: - ChipLogProgress(chipTool, - " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (UVFREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("UVFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestReadTheOptionalAttributeInPlaceIndicatorUvfremonsa0002InAttributeList_7(); - break; - case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); - err = TestReadTheGlobalAttributeAcceptedCommandList_8(); - break; - case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("UVFREMON.S.C00.Rsp")) { - NextTest(); - return; - } - err = TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9(); - break; - case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Read the global attribute: GeneratedCommandList\n"); - err = TestReadTheGlobalAttributeGeneratedCommandList_10(); - break; - case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : TH reads EventList attribute from DUT\n"); - err = TestThReadsEventListAttributeFromDut_11(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 5: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 6: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 7: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 8: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 9: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 10: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 11: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 12; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestReadTheGlobalAttributeClusterRevision_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: ClusterRevision Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("ClusterRevision", actualValue, 1U)); - } - - VerifyOrReturn(CheckConstraintType("clusterRevision", "int16u", "int16u")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeFeatureMap_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: FeatureMap Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("FeatureMap", actualValue, 0UL)); - } - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenUVFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given UVFREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenUVFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given UVFREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAttributeList_5() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 2UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65528UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65529UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65530UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65531UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65532UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65533UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheFeatureDependentUVFREMONSF00AttributeInAttributeList_6() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(UVFREMON.S.F00) attribute in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 0UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 1UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorUvfremonsa0002InAttributeList_7() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (UVFREMON.S.A0002) in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 3UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAcceptedCommandList_8() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional command (ResetCondition) in AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("acceptedCommandList", value, 0UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeGeneratedCommandList_10() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: GeneratedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("GeneratedCommandList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("generatedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsEventListAttributeFromDut_11() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads EventList attribute from DUT Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("EventList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("eventList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_UVFREMON_2_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_UVFREMON_2_1() - : TestCommandBridge("Test_TC_UVFREMON_2_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_UVFREMON_2_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_UVFREMON_2_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_UVFREMON_2_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("UVFREMON.S.A0000")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheConditionAttribute_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("UVFREMON.S.A0001")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheDegradationDirectionAttribute_2(); - break; - case 3: - ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("UVFREMON.S.A0002")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheChangeIndicationAttribute_3(); - break; - case 4: - ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("UVFREMON.S.A0003")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 5; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestThReadsFromTheDutTheConditionAttribute_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the Condition attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("condition", "percent", "percent")); - VerifyOrReturn(CheckConstraintMinValue("condition", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("condition", [value unsignedCharValue], 100U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheDegradationDirectionAttribute_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the DegradationDirection attribute.. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("degradationDirection", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("degradationDirection", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("degradationDirection", [value unsignedCharValue], 1U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheChangeIndicationAttribute_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the ChangeIndication attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("changeIndication", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("changeIndication", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("changeIndication", [value unsignedCharValue], 2U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterUVFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the InPlaceIndicator attribute Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("inPlaceIndicator", "boolean", "boolean")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_WTREMON_1_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_WTREMON_1_1() - : TestCommandBridge("Test_TC_WTREMON_1_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_WTREMON_1_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_WTREMON_1_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_WTREMON_1_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : Read the global attribute: ClusterRevision\n"); - err = TestReadTheGlobalAttributeClusterRevision_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!WTREMON.S.F00 && !WTREMON.S.F01")) { - NextTest(); - return; - } - err = TestReadTheGlobalAttributeFeatureMap_2(); - break; - case 3: - ChipLogProgress( - chipTool, " ***** Test Step 3 : Given WTREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("WTREMON.S.F00")) { - NextTest(); - return; - } - err = TestGivenWTREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); - break; - case 4: - ChipLogProgress( - chipTool, " ***** Test Step 4 : Given WTREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("WTREMON.S.F01")) { - NextTest(); - return; - } - err = TestGivenWTREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); - break; - case 5: - ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); - err = TestReadTheGlobalAttributeAttributeList_5(); - break; - case 6: - ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(WTREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("WTREMON.S.F00")) { - NextTest(); - return; - } - err = TestReadTheFeatureDependentWTREMONSF00AttributeInAttributeList_6(); - break; - case 7: - ChipLogProgress( - chipTool, " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (WTREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("WTREMON.S.A0002")) { - NextTest(); - return; - } - err = TestReadTheOptionalAttributeInPlaceIndicatorWtremonsa0002InAttributeList_7(); - break; - case 8: - ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); - err = TestReadTheGlobalAttributeAcceptedCommandList_8(); - break; - case 9: - ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("WTREMON.S.C00.Rsp")) { - NextTest(); - return; - } - err = TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9(); - break; - case 10: - ChipLogProgress(chipTool, " ***** Test Step 10 : Read the global attribute: GeneratedCommandList\n"); - err = TestReadTheGlobalAttributeGeneratedCommandList_10(); - break; - case 11: - ChipLogProgress(chipTool, " ***** Test Step 11 : TH reads EventList attribute from DUT\n"); - err = TestThReadsEventListAttributeFromDut_11(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 5: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 6: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 7: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 8: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 9: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 10: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 11: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 12; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestReadTheGlobalAttributeClusterRevision_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: ClusterRevision Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("ClusterRevision", actualValue, 1U)); - } - - VerifyOrReturn(CheckConstraintType("clusterRevision", "int16u", "int16u")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeFeatureMap_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: FeatureMap Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("FeatureMap", actualValue, 0UL)); - } - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenWTREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given WTREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestGivenWTREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given WTREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("featureMap", "bitmap32", "bitmap32")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAttributeList_5() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 2UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65528UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65529UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65530UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65531UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65532UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 65533UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheFeatureDependentWTREMONSF00AttributeInAttributeList_6() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(WTREMON.S.F00) attribute in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 0UL)); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 1UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorWtremonsa0002InAttributeList_7() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (WTREMON.S.A0002) in AttributeList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("attributeList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("attributeList", value, 3UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeAcceptedCommandList_8() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheOptionalCommandResetConditionInAcceptedCommandList_9() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional command (ResetCondition) in AcceptedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("acceptedCommandList", "list", "list")); - VerifyOrReturn(CheckConstraintContains("acceptedCommandList", value, 0UL)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestReadTheGlobalAttributeGeneratedCommandList_10() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the global attribute: GeneratedCommandList Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("GeneratedCommandList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("generatedCommandList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsEventListAttributeFromDut_11() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads EventList attribute from DUT Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - { - id actualValue = value; - VerifyOrReturn(CheckValue("EventList", [actualValue count], static_cast(0))); - } - - VerifyOrReturn(CheckConstraintType("eventList", "list", "list")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_WTREMON_2_1 : public TestCommandBridge { -public: - // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_WTREMON_2_1() - : TestCommandBridge("Test_TC_WTREMON_2_1") - , mTestIndex(0) - { - AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); - AddArgument("cluster", &mCluster); - AddArgument("endpoint", 0, UINT16_MAX, &mEndpoint); - AddArgument("timeout", 0, UINT16_MAX, &mTimeout); - } - // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - - ~Test_TC_WTREMON_2_1() {} - - /////////// TestCommand Interface ///////// - void NextTest() override - { - CHIP_ERROR err = CHIP_NO_ERROR; - - if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_WTREMON_2_1\n"); - } - - if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_WTREMON_2_1\n"); - SetCommandExitStatus(CHIP_NO_ERROR); - return; - } - - Wait(); - - // Ensure we increment mTestIndex before we start running the relevant - // command. That way if we lose the timeslice after we send the message - // but before our function call returns, we won't end up with an - // incorrect mTestIndex value observed when we get the response. - switch (mTestIndex++) { - case 0: - ChipLogProgress(chipTool, " ***** Test Step 0 : Wait for the commissioned device to be retrieved\n"); - err = TestWaitForTheCommissionedDeviceToBeRetrieved_0(); - break; - case 1: - ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("WTREMON.S.A0000")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheConditionAttribute_1(); - break; - case 2: - ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("WTREMON.S.A0001")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheDegradationDirectionAttribute_2(); - break; - case 3: - ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("WTREMON.S.A0002")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheChangeIndicationAttribute_3(); - break; - case 4: - ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("WTREMON.S.A0003")) { - NextTest(); - return; - } - err = TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4(); - break; - } - - if (CHIP_NO_ERROR != err) { - ChipLogError(chipTool, " ***** Test Failure: %s\n", chip::ErrorStr(err)); - SetCommandExitStatus(err); - } - } - - void OnStatusUpdate(const chip::app::StatusIB & status) override - { - switch (mTestIndex - 1) { - case 0: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 1: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 2: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 3: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - case 4: - VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); - break; - } - - // Go on to the next test. - ContinueOnChipMainThread(CHIP_NO_ERROR); - } - - chip::System::Clock::Timeout GetWaitDuration() const override - { - return chip::System::Clock::Seconds16(mTimeout.ValueOr(kTimeoutInSeconds)); - } - -private: - std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 5; - - chip::Optional mNodeId; - chip::Optional mCluster; - chip::Optional mEndpoint; - chip::Optional mTimeout; - - CHIP_ERROR TestWaitForTheCommissionedDeviceToBeRetrieved_0() - { - - chip::app::Clusters::DelayCommands::Commands::WaitForCommissionee::Type value; - value.nodeId = mNodeId.HasValue() ? mNodeId.Value() : 305414945ULL; - return WaitForCommissionee("alpha", value); - } - - CHIP_ERROR TestThReadsFromTheDutTheConditionAttribute_1() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the Condition attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("condition", "percent", "percent")); - VerifyOrReturn(CheckConstraintMinValue("condition", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("condition", [value unsignedCharValue], 100U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheDegradationDirectionAttribute_2() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the DegradationDirection attribute.. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("degradationDirection", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("degradationDirection", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("degradationDirection", [value unsignedCharValue], 1U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheChangeIndicationAttribute_3() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the ChangeIndication attribute. Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("changeIndication", "enum8", "enum8")); - VerifyOrReturn(CheckConstraintMinValue("changeIndication", [value unsignedCharValue], 0U)); - VerifyOrReturn(CheckConstraintMaxValue("changeIndication", [value unsignedCharValue], 2U)); - - NextTest(); - }]; - - return CHIP_NO_ERROR; - } - - CHIP_ERROR TestThReadsFromTheDutTheInPlaceIndicatorAttribute_4() - { - - MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterWaterTankMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; - VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); - - [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"TH reads from the DUT the InPlaceIndicator attribute Error: %@", err); - - VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); - - VerifyOrReturn(CheckConstraintType("inPlaceIndicator", "boolean", "boolean")); - NextTest(); - }]; - - return CHIP_NO_ERROR; - } -}; - -class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { +class Test_TC_HEPAFREMON_1_1 : public TestCommandBridge { public: // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_ZEOFREMON_1_1() - : TestCommandBridge("Test_TC_ZEOFREMON_1_1") + Test_TC_HEPAFREMON_1_1() + : TestCommandBridge("Test_TC_HEPAFREMON_1_1") , mTestIndex(0) { AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); @@ -154032,7 +147232,7 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { } // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - ~Test_TC_ZEOFREMON_1_1() {} + ~Test_TC_HEPAFREMON_1_1() {} /////////// TestCommand Interface ///////// void NextTest() override @@ -154040,11 +147240,11 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { CHIP_ERROR err = CHIP_NO_ERROR; if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_ZEOFREMON_1_1\n"); + ChipLogProgress(chipTool, " **** Test Start: Test_TC_HEPAFREMON_1_1\n"); } if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_ZEOFREMON_1_1\n"); + ChipLogProgress(chipTool, " **** Test Complete: Test_TC_HEPAFREMON_1_1\n"); SetCommandExitStatus(CHIP_NO_ERROR); return; } @@ -154066,7 +147266,7 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { break; case 2: ChipLogProgress(chipTool, " ***** Test Step 2 : Read the global attribute: FeatureMap\n"); - if (ShouldSkip("!ZEOFREMON.S.F00 && !ZEOFREMON.S.F01")) { + if (ShouldSkip("!HEPAFREMON.S.F00 && !HEPAFREMON.S.F01")) { NextTest(); return; } @@ -154074,21 +147274,21 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { break; case 3: ChipLogProgress( - chipTool, " ***** Test Step 3 : Given ZEOFREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("ZEOFREMON.S.F00")) { + chipTool, " ***** Test Step 3 : Given HEPAFREMON.S.F00(Condition) ensure featuremap has the correct bit set\n"); + if (ShouldSkip("HEPAFREMON.S.F00")) { NextTest(); return; } - err = TestGivenZEOFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); + err = TestGivenHEPAFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3(); break; case 4: ChipLogProgress( - chipTool, " ***** Test Step 4 : Given ZEOFREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); - if (ShouldSkip("ZEOFREMON.S.F01")) { + chipTool, " ***** Test Step 4 : Given HEPAFREMON.S.F01(Warning) ensure featuremap has the correct bit set\n"); + if (ShouldSkip("HEPAFREMON.S.F01")) { NextTest(); return; } - err = TestGivenZEOFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); + err = TestGivenHEPAFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4(); break; case 5: ChipLogProgress(chipTool, " ***** Test Step 5 : Read the global attribute: AttributeList\n"); @@ -154096,21 +147296,21 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { break; case 6: ChipLogProgress( - chipTool, " ***** Test Step 6 : Read the feature dependent(ZEOFREMON.S.F00) attribute in AttributeList\n"); - if (ShouldSkip("ZEOFREMON.S.F00")) { + chipTool, " ***** Test Step 6 : Read the feature dependent(HEPAFREMON.S.F00) attribute in AttributeList\n"); + if (ShouldSkip("HEPAFREMON.S.F00")) { NextTest(); return; } - err = TestReadTheFeatureDependentZEOFREMONSF00AttributeInAttributeList_6(); + err = TestReadTheFeatureDependentHEPAFREMONSF00AttributeInAttributeList_6(); break; case 7: ChipLogProgress(chipTool, - " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (ZEOFREMON.S.A0002) in AttributeList\n"); - if (ShouldSkip("ZEOFREMON.S.A0002")) { + " ***** Test Step 7 : Read the optional attribute InPlaceIndicator (HEPAFREMON.S.A0002) in AttributeList\n"); + if (ShouldSkip("HEPAFREMON.S.A0002")) { NextTest(); return; } - err = TestReadTheOptionalAttributeInPlaceIndicatorZeofremonsa0002InAttributeList_7(); + err = TestReadTheOptionalAttributeInPlaceIndicatorHepafremonsa0002InAttributeList_7(); break; case 8: ChipLogProgress(chipTool, " ***** Test Step 8 : Read the global attribute: AcceptedCommandList\n"); @@ -154118,7 +147318,7 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { break; case 9: ChipLogProgress(chipTool, " ***** Test Step 9 : Read the optional command (ResetCondition) in AcceptedCommandList\n"); - if (ShouldSkip("ZEOFREMON.S.C00.Rsp")) { + if (ShouldSkip("HEPAFREMON.S.C00.Rsp")) { NextTest(); return; } @@ -154211,9 +147411,9 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeClusterRevisionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { @@ -154237,9 +147437,9 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { @@ -154259,17 +147459,17 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestGivenZEOFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() + CHIP_ERROR TestGivenHEPAFREMONSF00ConditionEnsureFeaturemapHasTheCorrectBitSet_3() { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given ZEOFREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); + NSLog(@"Given HEPAFREMON.S.F00(Condition) ensure featuremap has the correct bit set Error: %@", err); VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); @@ -154280,17 +147480,17 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestGivenZEOFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() + CHIP_ERROR TestGivenHEPAFREMONSF01WarningEnsureFeaturemapHasTheCorrectBitSet_4() { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeFeatureMapWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { - NSLog(@"Given ZEOFREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); + NSLog(@"Given HEPAFREMON.S.F01(Warning) ensure featuremap has the correct bit set Error: %@", err); VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); @@ -154305,9 +147505,9 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { @@ -154330,17 +147530,17 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestReadTheFeatureDependentZEOFREMONSF00AttributeInAttributeList_6() + CHIP_ERROR TestReadTheFeatureDependentHEPAFREMONSF00AttributeInAttributeList_6() { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the feature dependent(ZEOFREMON.S.F00) attribute in AttributeList Error: %@", err); + NSLog(@"Read the feature dependent(HEPAFREMON.S.F00) attribute in AttributeList Error: %@", err); VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); @@ -154354,17 +147554,17 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { return CHIP_NO_ERROR; } - CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorZeofremonsa0002InAttributeList_7() + CHIP_ERROR TestReadTheOptionalAttributeInPlaceIndicatorHepafremonsa0002InAttributeList_7() { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeAttributeListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { - NSLog(@"Read the optional attribute InPlaceIndicator (ZEOFREMON.S.A0002) in AttributeList Error: %@", err); + NSLog(@"Read the optional attribute InPlaceIndicator (HEPAFREMON.S.A0002) in AttributeList Error: %@", err); VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); @@ -154381,9 +147581,9 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { @@ -154402,9 +147602,9 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeAcceptedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { @@ -154425,9 +147625,9 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeGeneratedCommandListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { @@ -154451,9 +147651,9 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeEventListWithCompletion:^(NSArray * _Nullable value, NSError * _Nullable err) { @@ -154474,11 +147674,11 @@ class Test_TC_ZEOFREMON_1_1 : public TestCommandBridge { } }; -class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { +class Test_TC_HEPAFREMON_2_1 : public TestCommandBridge { public: // NOLINTBEGIN(clang-analyzer-nullability.NullPassedToNonnull): Test constructor nullability not enforced - Test_TC_ZEOFREMON_2_1() - : TestCommandBridge("Test_TC_ZEOFREMON_2_1") + Test_TC_HEPAFREMON_2_1() + : TestCommandBridge("Test_TC_HEPAFREMON_2_1") , mTestIndex(0) { AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); @@ -154488,7 +147688,7 @@ class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { } // NOLINTEND(clang-analyzer-nullability.NullPassedToNonnull) - ~Test_TC_ZEOFREMON_2_1() {} + ~Test_TC_HEPAFREMON_2_1() {} /////////// TestCommand Interface ///////// void NextTest() override @@ -154496,11 +147696,11 @@ class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { CHIP_ERROR err = CHIP_NO_ERROR; if (0 == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Start: Test_TC_ZEOFREMON_2_1\n"); + ChipLogProgress(chipTool, " **** Test Start: Test_TC_HEPAFREMON_2_1\n"); } if (mTestCount == mTestIndex) { - ChipLogProgress(chipTool, " **** Test Complete: Test_TC_ZEOFREMON_2_1\n"); + ChipLogProgress(chipTool, " **** Test Complete: Test_TC_HEPAFREMON_2_1\n"); SetCommandExitStatus(CHIP_NO_ERROR); return; } @@ -154518,7 +147718,7 @@ class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { break; case 1: ChipLogProgress(chipTool, " ***** Test Step 1 : TH reads from the DUT the Condition attribute.\n"); - if (ShouldSkip("ZEOFREMON.S.A0000")) { + if (ShouldSkip("HEPAFREMON.S.A0000")) { NextTest(); return; } @@ -154526,7 +147726,7 @@ class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { break; case 2: ChipLogProgress(chipTool, " ***** Test Step 2 : TH reads from the DUT the DegradationDirection attribute..\n"); - if (ShouldSkip("ZEOFREMON.S.A0001")) { + if (ShouldSkip("HEPAFREMON.S.A0001")) { NextTest(); return; } @@ -154534,7 +147734,7 @@ class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { break; case 3: ChipLogProgress(chipTool, " ***** Test Step 3 : TH reads from the DUT the ChangeIndication attribute.\n"); - if (ShouldSkip("ZEOFREMON.S.A0002")) { + if (ShouldSkip("HEPAFREMON.S.A0002")) { NextTest(); return; } @@ -154542,7 +147742,7 @@ class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { break; case 4: ChipLogProgress(chipTool, " ***** Test Step 4 : TH reads from the DUT the InPlaceIndicator attribute\n"); - if (ShouldSkip("ZEOFREMON.S.A0003")) { + if (ShouldSkip("HEPAFREMON.S.A0003")) { NextTest(); return; } @@ -154606,9 +147806,9 @@ class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeConditionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { @@ -154630,9 +147830,9 @@ class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeDegradationDirectionWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { @@ -154654,9 +147854,9 @@ class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeChangeIndicationWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { @@ -154678,9 +147878,9 @@ class Test_TC_ZEOFREMON_2_1 : public TestCommandBridge { { MTRBaseDevice * device = GetDevice("alpha"); - __auto_type * cluster = [[MTRBaseClusterZeoliteFilterMonitoring alloc] initWithDevice:device - endpointID:@(1) - queue:mCallbackQueue]; + __auto_type * cluster = [[MTRBaseClusterHEPAFilterMonitoring alloc] initWithDevice:device + endpointID:@(1) + queue:mCallbackQueue]; VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); [cluster readAttributeInPlaceIndicatorWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable err) { @@ -154917,28 +148117,8 @@ void registerCommandsTests(Commands & commands) make_unique(), make_unique(), make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), make_unique(), make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), - make_unique(), #endif // CONFIG_ENABLE_YAML_TESTS }; From 12d8fecea959532396b2b89069f9df43b3d994ac Mon Sep 17 00:00:00 2001 From: C Freeman Date: Fri, 9 Jun 2023 13:45:38 -0400 Subject: [PATCH 04/15] Fix spelling error carried over from spec (#27173) Fixes:#25974 --- src/app/tests/suites/certification/PICS.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/tests/suites/certification/PICS.yaml b/src/app/tests/suites/certification/PICS.yaml index ed767818f71afb..c361661a9a17cb 100644 --- a/src/app/tests/suites/certification/PICS.yaml +++ b/src/app/tests/suites/certification/PICS.yaml @@ -6915,7 +6915,7 @@ PICS: id: DGTHREAD.S.A0033 - label: - "Does the DUT(server) support the RxErrInvalidScrAddrCount attribute?" + "Does the DUT(server) support the RxErrInvalidSrcAddrCount attribute?" id: DGTHREAD.S.A0034 - label: "Does the DUT(server) support the RxErrSecCount attribute?" @@ -7255,7 +7255,7 @@ PICS: - label: "Does the DUT(client) have access privileges for the - RxErrInvalidScrAddrCount attribute implemented on the server?" + RxErrInvalidSrcAddrCount attribute implemented on the server?" id: DGTHREAD.C.A0034 - label: From 40fb7c246671e9d37ca8bb2cfbf37f81c1509334 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Fri, 9 Jun 2023 15:35:53 -0400 Subject: [PATCH 05/15] Update cloudbuild vscode version to be uniform ... somehow this line was not updated to latest (#27182) Co-authored-by: Andrei Litvin --- integrations/cloudbuild/smoke-test.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integrations/cloudbuild/smoke-test.yaml b/integrations/cloudbuild/smoke-test.yaml index 1134778bda2714..e3f18bcc42bef5 100644 --- a/integrations/cloudbuild/smoke-test.yaml +++ b/integrations/cloudbuild/smoke-test.yaml @@ -7,7 +7,7 @@ steps: git config --global --add safe.directory "*" git submodule update --init --recursive id: Submodules - - name: "connectedhomeip/chip-build-vscode:0.7.3" + - name: "connectedhomeip/chip-build-vscode:0.7.16" env: - PW_ENVIRONMENT_ROOT=/pwenv args: From 36aafc5d6ef42624b9cff2dddcf8b1181245c074 Mon Sep 17 00:00:00 2001 From: Matt Hazley Date: Mon, 12 Jun 2023 13:46:39 +0100 Subject: [PATCH 06/15] Added a CheckConstraint Min and Max function where the expected is a Nullable type (#27045) * Added a CheckConstraint Min and Max function where the expected is a Nullable type * Reversed the null check as it was wrong way around. Fixed new parameter to reference and const * Fixed return parameters Co-authored-by: Boris Zbarsky * Fixed return parameters Co-authored-by: Boris Zbarsky * Removed enable_if_t from new template functions --------- Co-authored-by: Boris Zbarsky --- .../tests/suites/include/ConstraintsChecker.h | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/app/tests/suites/include/ConstraintsChecker.h b/src/app/tests/suites/include/ConstraintsChecker.h index be446fd3f42c28..eb52c3b6b6bba5 100644 --- a/src/app/tests/suites/include/ConstraintsChecker.h +++ b/src/app/tests/suites/include/ConstraintsChecker.h @@ -299,6 +299,17 @@ class ConstraintsChecker return CheckConstraintMinValue(itemName, current.Value(), static_cast(expected)); } + template + bool CheckConstraintMinValue(const char * itemName, const chip::app::DataModel::Nullable & current, + const chip::app::DataModel::Nullable & expected) + { + if (expected.IsNull()) + { + return true; + } + return CheckConstraintMinValue(itemName, current, expected.Value()); + } + template bool CheckConstraintMinValue(const char * itemName, const T & current, const chip::Optional & expected) { @@ -375,6 +386,17 @@ class ConstraintsChecker return CheckConstraintMaxValue(itemName, current.Value(), static_cast(expected)); } + template + bool CheckConstraintMaxValue(const char * itemName, const chip::app::DataModel::Nullable & current, + const chip::app::DataModel::Nullable & expected) + { + if (expected.IsNull()) + { + return true; + } + return CheckConstraintMaxValue(itemName, current, expected.Value()); + } + template bool CheckConstraintMaxValue(const char * itemName, const T & current, const chip::Optional & expected) { From 0b14ea385efef2d93be29512f0d48a0f9304e8b0 Mon Sep 17 00:00:00 2001 From: Timothy Maes Date: Mon, 12 Jun 2023 17:04:04 +0200 Subject: [PATCH 07/15] [QPG] Update memory parsing configuration (#27199) --- scripts/tools/memory/platform/qpg.cfg | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/scripts/tools/memory/platform/qpg.cfg b/scripts/tools/memory/platform/qpg.cfg index 97aea63fdfa051..ec6a7d374c81f7 100644 --- a/scripts/tools/memory/platform/qpg.cfg +++ b/scripts/tools/memory/platform/qpg.cfg @@ -35,10 +35,21 @@ 'sections': { 'FLASH': [ '.text', - '.rom', + '.flashjumptable', + '.datajumptable', + '.m_flashjumptable', + '.loaded_user_license', '.native_user_license', + '.extended_user_license', '.isr_vector', '.ARM.exidx', + # Bootloader + '.bootloader', + '.bl_user_license', + '.upgrade_image_user_license', + # NVM / Factory areas + '.gpNVM', + '.factory_data', ], 'RAM': [ '.data', @@ -49,17 +60,17 @@ '.ret_hw', '.ret_sw', '.unused_area', - '.pkey', - '.pufr', '.lower_ram_retain', '.lower_ram_retain_gpmicro_accessible', '.higher_ram_noretain', - '.gpNVM', + '.rom_m_bss', + '.rom_m_data', + '.lower_ram_retain_gpmicro_accessible_mrom', + ], + 'OTA': [ + 'OTA', + 'JTOTA', ] } }, - 'collect': { - # Strip these prefixes from compilation unit paths. - 'prefix': ['/mnt/c/Projects', '/mnt/c'] - }, } From b894737dba48b75f0a30e4d6c0e7881572216ffa Mon Sep 17 00:00:00 2001 From: ihidchaos Date: Mon, 12 Jun 2023 23:05:23 +0800 Subject: [PATCH 08/15] Update syscalls_stubs.cpp (#27187) Fix the redundant assignment equals sign, which causes compilation to fail. --- examples/platform/silabs/syscalls_stubs.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/platform/silabs/syscalls_stubs.cpp b/examples/platform/silabs/syscalls_stubs.cpp index f6a845639c6e7c..685bd63f567bb5 100644 --- a/examples/platform/silabs/syscalls_stubs.cpp +++ b/examples/platform/silabs/syscalls_stubs.cpp @@ -174,7 +174,7 @@ int __attribute__((weak)) _read(int file, char * ptr, int len) { (void) file; #if SILABS_LOG_OUT_UART - return = uartConsoleRead(ptr, len); + return uartConsoleRead(ptr, len); #else (void) ptr; (void) len; From 452d3b4f5b7b16a25b5a8f1c3e0aba90802047a1 Mon Sep 17 00:00:00 2001 From: wyhong <30567533+wy-hh@users.noreply.github.com> Date: Mon, 12 Jun 2023 23:11:19 +0800 Subject: [PATCH 09/15] [Bouffalolab] Refact BL602 & BL702 platform code (#27186) * refact platform code * use common ConnectivityManagerImpl.cpp * fix compile error after merged * update readme * fix overflow issue * add common PlatformManagerImpl.cpp * fix restyle --- examples/lighting-app/bouffalolab/README.md | 2 +- .../lighting-app/bouffalolab/bl702/args.gni | 5 + .../bouffalolab/common/AppTask.cpp | 2 +- .../bouffalolab/common/plat/OTAConfig.cpp | 1 + .../bouffalolab/common/plat/OTAConfig.h | 1 - .../bouffalolab/common/plat/platform.cpp | 4 +- src/platform/BUILD.gn | 4 +- .../bouffalolab/BL602/BL602Config.cpp | 336 ------- src/platform/bouffalolab/BL602/BL602Config.h | 132 --- src/platform/bouffalolab/BL602/BUILD.gn | 65 +- .../bouffalolab/BL602/BlePlatformConfig.h | 36 - .../BL602/CHIPDevicePlatformConfig.h | 130 --- .../BL602/CHIPDevicePlatformEvent.h | 99 --- .../bouffalolab/BL602/CHIPMem-Platform.cpp | 164 ---- .../BL602/ConfigurationManagerImpl.cpp | 206 +---- .../BL602/ConfigurationManagerImpl.h | 109 --- .../BL602/ConnectivityManagerImpl.cpp | 36 +- .../BL602/DiagnosticDataProviderImpl.cpp | 122 +-- .../bouffalolab/BL602/InetPlatformConfig.h | 47 - .../BL602/KeyValueStoreManagerImpl.cpp | 198 ----- .../BL602/KeyValueStoreManagerImpl.h | 75 -- src/platform/bouffalolab/BL602/Logging.cpp | 69 -- .../BL602/NetworkCommissioningDriver.cpp | 3 +- .../bouffalolab/BL602/PlatformManagerImpl.cpp | 42 +- .../bouffalolab/BL602/SystemPlatformConfig.h | 49 - src/platform/bouffalolab/BL602/args.gni | 2 - .../bouffalolab/BL702/BLEManagerImpl.cpp | 834 ------------------ .../bouffalolab/BL702/BLEManagerImpl.h | 188 ---- src/platform/bouffalolab/BL702/BUILD.gn | 51 +- .../bouffalolab/BL702/CHIPPlatformConfig.h | 132 --- src/platform/bouffalolab/BL702/CHIPmemory.cpp | 142 --- .../BL702/ConnectivityManagerImpl.h | 138 --- .../BL702/DiagnosticDataProviderImpl.cpp | 237 +---- .../BL702/DiagnosticDataProviderImpl.h | 54 -- .../BL702/OTAImageProcessorImpl.cpp | 250 ------ .../bouffalolab/BL702/OTAImageProcessorImpl.h | 64 -- .../bouffalolab/BL702/PlatformManagerImpl.cpp | 28 +- .../bouffalolab/BL702/PlatformManagerImpl.h | 93 -- src/platform/bouffalolab/BL702/args.gni | 7 - .../bl702Config.cpp => common/BLConfig.cpp} | 111 +-- .../bl702Config.h => common/BLConfig.h} | 13 +- .../{BL602 => common}/BLEManagerImpl.cpp | 2 - .../{BL602 => common}/BLEManagerImpl.h | 0 .../{BL702 => common}/BlePlatformConfig.h | 0 .../CHIPDevicePlatformConfig.h | 39 +- .../CHIPDevicePlatformEvent.h | 9 +- .../{BL602 => common}/CHIPPlatformConfig.h | 35 +- .../ConfigurationManagerImpl.cpp | 121 +-- .../ConfigurationManagerImpl.h | 29 +- .../ConnectivityManagerImpl.cpp | 14 + .../ConnectivityManagerImpl.h | 36 +- .../common/DiagnosticDataProviderImpl.cpp | 217 +++++ .../DiagnosticDataProviderImpl.h | 25 +- .../{BL702 => common}/InetPlatformConfig.h | 2 +- .../KeyValueStoreManagerImpl.cpp | 8 +- .../KeyValueStoreManagerImpl.h | 0 .../bouffalolab/{BL702 => common}/Logging.cpp | 2 +- .../OTAImageProcessorImpl.cpp | 4 +- .../{BL602 => common}/OTAImageProcessorImpl.h | 3 +- .../common/PlatformManagerImpl.cpp | 54 ++ .../{BL602 => common}/PlatformManagerImpl.h | 10 +- .../{BL702 => common}/SystemPlatformConfig.h | 1 - .../ThreadStackManagerImpl.h | 0 src/platform/device.gni | 4 +- third_party/bouffalolab/repo | 2 +- 65 files changed, 571 insertions(+), 4327 deletions(-) delete mode 100644 src/platform/bouffalolab/BL602/BL602Config.cpp delete mode 100644 src/platform/bouffalolab/BL602/BL602Config.h delete mode 100644 src/platform/bouffalolab/BL602/BlePlatformConfig.h delete mode 100644 src/platform/bouffalolab/BL602/CHIPDevicePlatformConfig.h delete mode 100644 src/platform/bouffalolab/BL602/CHIPDevicePlatformEvent.h delete mode 100644 src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp delete mode 100644 src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h delete mode 100644 src/platform/bouffalolab/BL602/InetPlatformConfig.h delete mode 100644 src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp delete mode 100644 src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.h delete mode 100644 src/platform/bouffalolab/BL602/Logging.cpp delete mode 100644 src/platform/bouffalolab/BL602/SystemPlatformConfig.h delete mode 100644 src/platform/bouffalolab/BL702/BLEManagerImpl.cpp delete mode 100644 src/platform/bouffalolab/BL702/BLEManagerImpl.h delete mode 100644 src/platform/bouffalolab/BL702/CHIPPlatformConfig.h delete mode 100644 src/platform/bouffalolab/BL702/CHIPmemory.cpp delete mode 100644 src/platform/bouffalolab/BL702/ConnectivityManagerImpl.h delete mode 100644 src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.h delete mode 100644 src/platform/bouffalolab/BL702/OTAImageProcessorImpl.cpp delete mode 100644 src/platform/bouffalolab/BL702/OTAImageProcessorImpl.h delete mode 100644 src/platform/bouffalolab/BL702/PlatformManagerImpl.h rename src/platform/bouffalolab/{BL702/bl702Config.cpp => common/BLConfig.cpp} (58%) rename src/platform/bouffalolab/{BL702/bl702Config.h => common/BLConfig.h} (93%) rename src/platform/bouffalolab/{BL602 => common}/BLEManagerImpl.cpp (99%) rename src/platform/bouffalolab/{BL602 => common}/BLEManagerImpl.h (100%) rename src/platform/bouffalolab/{BL702 => common}/BlePlatformConfig.h (100%) rename src/platform/bouffalolab/{BL702 => common}/CHIPDevicePlatformConfig.h (58%) rename src/platform/bouffalolab/{BL702 => common}/CHIPDevicePlatformEvent.h (88%) rename src/platform/bouffalolab/{BL602 => common}/CHIPPlatformConfig.h (81%) rename src/platform/bouffalolab/{BL702 => common}/ConfigurationManagerImpl.cpp (61%) rename src/platform/bouffalolab/{BL702 => common}/ConfigurationManagerImpl.h (78%) rename src/platform/bouffalolab/{BL702 => common}/ConnectivityManagerImpl.cpp (83%) rename src/platform/bouffalolab/{BL602 => common}/ConnectivityManagerImpl.h (88%) create mode 100644 src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp rename src/platform/bouffalolab/{BL602 => common}/DiagnosticDataProviderImpl.h (85%) rename src/platform/bouffalolab/{BL702 => common}/InetPlatformConfig.h (96%) rename src/platform/bouffalolab/{BL702 => common}/KeyValueStoreManagerImpl.cpp (87%) rename src/platform/bouffalolab/{BL702 => common}/KeyValueStoreManagerImpl.h (100%) rename src/platform/bouffalolab/{BL702 => common}/Logging.cpp (97%) rename src/platform/bouffalolab/{BL602 => common}/OTAImageProcessorImpl.cpp (98%) rename src/platform/bouffalolab/{BL602 => common}/OTAImageProcessorImpl.h (97%) create mode 100644 src/platform/bouffalolab/common/PlatformManagerImpl.cpp rename src/platform/bouffalolab/{BL602 => common}/PlatformManagerImpl.h (95%) rename src/platform/bouffalolab/{BL702 => common}/SystemPlatformConfig.h (94%) rename src/platform/bouffalolab/{BL702 => common}/ThreadStackManagerImpl.h (100%) diff --git a/examples/lighting-app/bouffalolab/README.md b/examples/lighting-app/bouffalolab/README.md index db48724b5dd858..7e42d3bcc45b0a 100644 --- a/examples/lighting-app/bouffalolab/README.md +++ b/examples/lighting-app/bouffalolab/README.md @@ -305,7 +305,7 @@ ota-provider-app build and usage. - BLE commission BL602/BL702 lighting if not commissioned. - Start OTA software upgrade process ```shell - ./chip-tool otasoftwareupdaterequestor announce-ota-provider 1 0 0 0 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider 1 0 0 0 0 ``` where `` is node id of BL602/BL702 lighting app. - After OTA software upgrade gets done, BL602/BL702 will get reboot diff --git a/examples/lighting-app/bouffalolab/bl702/args.gni b/examples/lighting-app/bouffalolab/bl702/args.gni index c76c3d0f267d17..8087dc1470f236 100644 --- a/examples/lighting-app/bouffalolab/bl702/args.gni +++ b/examples/lighting-app/bouffalolab/bl702/args.gni @@ -30,3 +30,8 @@ lwip_platform = "bl702" chip_enable_ota_requestor = true chip_detail_logging = false + +pw_build_LINK_DEPS = [ + "$dir_pw_assert:impl", + "$dir_pw_log:impl", +] diff --git a/examples/lighting-app/bouffalolab/common/AppTask.cpp b/examples/lighting-app/bouffalolab/common/AppTask.cpp index 100e8792a59e42..3e7171dd75aa18 100644 --- a/examples/lighting-app/bouffalolab/common/AppTask.cpp +++ b/examples/lighting-app/bouffalolab/common/AppTask.cpp @@ -40,9 +40,9 @@ #endif #if CHIP_ENABLE_OPENTHREAD -#include #include #include +#include #include #endif diff --git a/examples/platform/bouffalolab/common/plat/OTAConfig.cpp b/examples/platform/bouffalolab/common/plat/OTAConfig.cpp index ed5c6286178ef7..b6ca3b621cd747 100644 --- a/examples/platform/bouffalolab/common/plat/OTAConfig.cpp +++ b/examples/platform/bouffalolab/common/plat/OTAConfig.cpp @@ -19,6 +19,7 @@ #include "OTAConfig.h" #include +#include // Global OTA objects chip::DefaultOTARequestor gRequestorCore; chip::DefaultOTARequestorStorage gRequestorStorage; diff --git a/examples/platform/bouffalolab/common/plat/OTAConfig.h b/examples/platform/bouffalolab/common/plat/OTAConfig.h index 906b7f533709cc..24d8fb5c11109f 100644 --- a/examples/platform/bouffalolab/common/plat/OTAConfig.h +++ b/examples/platform/bouffalolab/common/plat/OTAConfig.h @@ -22,7 +22,6 @@ #include #include #include -#include class OTAConfig { diff --git a/examples/platform/bouffalolab/common/plat/platform.cpp b/examples/platform/bouffalolab/common/plat/platform.cpp index 0c6f1912d3bb80..dc2f2a02fbfc1f 100644 --- a/examples/platform/bouffalolab/common/plat/platform.cpp +++ b/examples/platform/bouffalolab/common/plat/platform.cpp @@ -30,7 +30,7 @@ #include #include #endif -#include +#include #if HEAP_MONITORING #include @@ -38,9 +38,9 @@ #endif #if CHIP_ENABLE_OPENTHREAD -#include #include #include +#include #include #endif diff --git a/src/platform/BUILD.gn b/src/platform/BUILD.gn index 6473ed404beaf9..7f18adc631cb73 100644 --- a/src/platform/BUILD.gn +++ b/src/platform/BUILD.gn @@ -229,13 +229,13 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { } else if (chip_device_platform == "bl602") { defines += [ "CHIP_DEVICE_LAYER_TARGET_BL602=1", - "CHIP_DEVICE_LAYER_TARGET=bouffalolab/BL602", + "CHIP_DEVICE_LAYER_TARGET=bouffalolab/common", "CHIP_DEVICE_CONFIG_ENABLE_WIFI=${chip_enable_wifi}", ] } else if (chip_device_platform == "bl702") { defines += [ "CHIP_DEVICE_LAYER_TARGET_BL702=1", - "CHIP_DEVICE_LAYER_TARGET=bouffalolab/BL702", + "CHIP_DEVICE_LAYER_TARGET=bouffalolab/common", "CHIP_DEVICE_CONFIG_ENABLE_WIFI=${chip_enable_wifi}", ] } else if (chip_device_platform == "fake") { diff --git a/src/platform/bouffalolab/BL602/BL602Config.cpp b/src/platform/bouffalolab/BL602/BL602Config.cpp deleted file mode 100644 index 140b52d5fa0edd..00000000000000 --- a/src/platform/bouffalolab/BL602/BL602Config.cpp +++ /dev/null @@ -1,336 +0,0 @@ -/* - * - * Copyright (c) 2021-2022 Project CHIP Authors - * Copyright (c) 2019-2020 Google LLC. - * Copyright (c) 2019 Nest Labs, Inc. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Utilities for interacting with the the BL602 Easyflash module. - */ -/* this file behaves like a config.h, comes first */ -#include - -#include - -#include -#include -#include -#include -#include - -#include -#include - -// 3R: easyflash errno mapping to the CHIP errno - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -const BL602Config::Key BL602Config::kConfigKey_SerialNum = { "serial-num" }; -const BL602Config::Key BL602Config::kConfigKey_MfrDeviceId = { "device-id" }; -const BL602Config::Key BL602Config::kConfigKey_MfrDeviceCert = { "device-cert" }; -const BL602Config::Key BL602Config::kConfigKey_MfrDeviceICACerts = { "device-ca-certs" }; -const BL602Config::Key BL602Config::kConfigKey_MfrDevicePrivateKey = { "device-key" }; -const BL602Config::Key BL602Config::kConfigKey_HardwareVersion = { "hardware-ver" }; -const BL602Config::Key BL602Config::kConfigKey_ManufacturingDate = { "mfg-date" }; -const BL602Config::Key BL602Config::kConfigKey_SetupPinCode = { "pin-code" }; -const BL602Config::Key BL602Config::kConfigKey_SetupDiscriminator = { "discriminator" }; -const BL602Config::Key BL602Config::kConfigKey_Spake2pIterationCount = { "iteration-count" }; -const BL602Config::Key BL602Config::kConfigKey_Spake2pSalt = { "salt" }; -const BL602Config::Key BL602Config::kConfigKey_Spake2pVerifier = { "verifier" }; - -// Keys stored in the chip-config namespace -const BL602Config::Key BL602Config::kConfigKey_ServiceConfig = { "service-config" }; -const BL602Config::Key BL602Config::kConfigKey_PairedAccountId = { "account-id" }; -const BL602Config::Key BL602Config::kConfigKey_ServiceId = { "service-id" }; -const BL602Config::Key BL602Config::kConfigKey_LastUsedEpochKeyId = { "last-ek-id" }; -const BL602Config::Key BL602Config::kConfigKey_FailSafeArmed = { "fail-safe-armed" }; -const BL602Config::Key BL602Config::kConfigKey_WiFiStationSecType = { "sta-sec-type" }; -const BL602Config::Key BL602Config::kConfigKey_OperationalDeviceId = { "op-device-id" }; -const BL602Config::Key BL602Config::kConfigKey_OperationalDeviceCert = { "op-device-cert" }; -const BL602Config::Key BL602Config::kConfigKey_OperationalDeviceICACerts = { "op-device-ca-certs" }; -const BL602Config::Key BL602Config::kConfigKey_OperationalDevicePrivateKey = { "op-device-key" }; -const BL602Config::Key BL602Config::kConfigKey_RegulatoryLocation = { "regulatory-location" }; -const BL602Config::Key BL602Config::kConfigKey_CountryCode = { "country-code" }; -const BL602Config::Key BL602Config::kConfigKey_UniqueId = { "unique-id" }; - -const BL602Config::Key BL602Config::kCounterKey_RebootCount = { "reboot-count" }; -const BL602Config::Key BL602Config::kCounterKey_TotalOperationalHours = { "total-hours" }; - -CHIP_ERROR BL602Config::Init() -{ - return CHIP_NO_ERROR; -} - -CHIP_ERROR BL602Config::ReadConfigValue(Key key, bool & val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - size_t valLen = 0; - - ef_get_env_blob(key.name, &val, 1, &valLen); - if (0 == valLen) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR BL602Config::ReadConfigValue(Key key, uint32_t & val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - size_t valLen = 0; - - ef_get_env_blob(key.name, &val, sizeof(val), &valLen); - if (0 == valLen) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR BL602Config::ReadConfigValue(Key key, uint64_t & val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - size_t valLen = 0; - - ef_get_env_blob(key.name, &val, sizeof(val), &valLen); - if (0 == valLen) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR BL602Config::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - outLen = 0; - ef_get_env_blob(key.name, buf, bufSize, &outLen); - if (0 == outLen) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR BL602Config::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - ef_get_env_blob(key.name, buf, bufSize, &outLen); - if (0 == outLen) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValue(Key key, bool val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - EfErrCode ret = ef_set_env_blob(key.name, &val, sizeof(val)); - if (ret != EF_NO_ERR) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - SuccessOrExit(err); - - // ChipLogProgress(DeviceLayer, "Easyflash set: %s = %s", key.name, val ? "true" : "false"); -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValue(Key key, uint32_t val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - EfErrCode ret = ef_set_env_blob(key.name, &val, sizeof(val)); - if (ret != EF_NO_ERR) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - SuccessOrExit(err); - - // ChipLogProgress(DeviceLayer, "Easyflash set: %s = %" PRIu32 " (0x%" PRIX32 ")", key.name, val, val); - -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValue(Key key, uint64_t val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - EfErrCode ret = ef_set_env_blob(key.name, &val, sizeof(val)); - if (ret != EF_NO_ERR) - { - log_error("WriteConfigValue() failed. key: %s, ret: %d\r\n", StringOrNullMarker(key.name), ret); - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - SuccessOrExit(err); - - // ChipLogProgress(DeviceLayer, "Easyflash set: %s = %" PRIu64 " (0x%" PRIX64 ")", key.name, val, val); - -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValueStr(Key key, const char * str) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - if (str != NULL) - { - EfErrCode ret = ef_set_env(key.name, str); - if (ret != EF_NO_ERR) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - SuccessOrExit(err); - - // ChipLogProgress(DeviceLayer, "Easyflash set: %s = \"%s\"", key.name, str); - } - else - { - err = ClearConfigValue(key); - SuccessOrExit(err); - } - -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValueStr(Key key, const char * str, size_t strLen) -{ - CHIP_ERROR err; - chip::Platform::ScopedMemoryBuffer strCopy; - - if (str != NULL) - { - strCopy.Calloc(strLen + 1); - VerifyOrExit(strCopy, err = CHIP_ERROR_NO_MEMORY); - Platform::CopyString(strCopy.Get(), strLen + 1, str); - } - err = BL602Config::WriteConfigValueStr(key, strCopy.Get()); - -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - if (data != NULL) - { - EfErrCode ret = ef_set_env_blob(key.name, data, dataLen); - if (ret != EF_NO_ERR) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - SuccessOrExit(err); - - // ChipLogProgress(DeviceLayer, "Easyflash set: /%s = (blob length %" PRId32 ")", key.name, (unsigned long )dataLen); - } - else - { - err = ClearConfigValue(key); - SuccessOrExit(err); - } - -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteWifiInfo(const char * ssid, const char * passwd) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - -#if 0 - if (ssid != NULL && passwd != NULL) - { - EfErrCode ret = ef_set_env_blob(kBLConfigKey_wifissid, ssid, strlen(ssid)); - if (ret != EF_NO_ERR) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - ef_set_env_blob(kBLConfigKey_wifipassword, passwd, strlen(passwd)); - if (ret != EF_NO_ERR) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - SuccessOrExit(err); - - } - else - { - //err = ClearConfigValue(ssid); - //err = ClearConfigValue(passwd); - SuccessOrExit(err); - } - -exit: -#endif - - return err; -} - -CHIP_ERROR BL602Config::ClearConfigValue(Key key) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - EfErrCode ret = ef_del_env(key.name); - if (ret != EF_NO_ERR) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - SuccessOrExit(err); - - ChipLogProgress(DeviceLayer, "Easyflash erase: %s", StringOrNullMarker(key.name)); - -exit: - return err; -} - -bool BL602Config::ConfigValueExists(Key key) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - env_node_obj node; - bool result = ef_get_env_obj(key.name, &node); - if (!result) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err == CHIP_NO_ERROR; -} - -void BL602Config::RunConfigUnitTest() {} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/BL602Config.h b/src/platform/bouffalolab/BL602/BL602Config.h deleted file mode 100644 index 11be4c9ebe3402..00000000000000 --- a/src/platform/bouffalolab/BL602/BL602Config.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019-2020 Google LLC. - * Copyright (c) 2019 Nest Labs, Inc. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Utilities for interacting with the the BL602 Easyflash module. - */ - -#pragma once - -#include - -#include - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -/** - * Provides functions and definitions for accessing device configuration information on the BL602 platform. - * - * This class is designed to be mixed-in to concrete implementation classes as a means to - * provide access to configuration information to generic base classes. - */ -class BL602Config -{ -public: - static constexpr const char * kBLConfigKey_wifissid = ("bl-wifi-ssid"); - static constexpr const char * kBLConfigKey_wifipassword = ("bl-wifi-psk"); - struct Key; - - // Maximum length of an easyflash key name - static constexpr size_t kMaxConfigKeyNameLength = 15; - - // Easyflash namespaces used to store device configuration information. - static const char kConfigNamespace_ChipFactory[]; - static const char kConfigNamespace_ChipConfig[]; - static const char kConfigNamespace_ChipCounters[]; - - // Key definitions for well-known keys. - static const Key kConfigKey_SerialNum; - static const Key kConfigKey_MfrDeviceId; - static const Key kConfigKey_MfrDeviceCert; - static const Key kConfigKey_MfrDeviceICACerts; - static const Key kConfigKey_MfrDevicePrivateKey; - static const Key kConfigKey_HardwareVersion; - static const Key kConfigKey_ManufacturingDate; - static const Key kConfigKey_SetupPinCode; - static const Key kConfigKey_ServiceConfig; - static const Key kConfigKey_PairedAccountId; - static const Key kConfigKey_ServiceId; - static const Key kConfigKey_LastUsedEpochKeyId; - static const Key kConfigKey_FailSafeArmed; - static const Key kConfigKey_WiFiStationSecType; - static const Key kConfigKey_OperationalDeviceId; - static const Key kConfigKey_OperationalDeviceCert; - static const Key kConfigKey_OperationalDeviceICACerts; - static const Key kConfigKey_OperationalDevicePrivateKey; - static const Key kConfigKey_SetupDiscriminator; - static const Key kConfigKey_RegulatoryLocation; - static const Key kConfigKey_CountryCode; - static const Key kConfigKey_UniqueId; - static const Key kConfigKey_Spake2pIterationCount; - static const Key kConfigKey_Spake2pSalt; - static const Key kConfigKey_Spake2pVerifier; - - static const Key kCounterKey_RebootCount; - static const Key kCounterKey_TotalOperationalHours; - - static CHIP_ERROR Init(void); - - // Config value accessors. - static CHIP_ERROR ReadConfigValue(Key key, bool & val); - static CHIP_ERROR ReadConfigValue(Key key, uint32_t & val); - static CHIP_ERROR ReadConfigValue(Key key, uint64_t & val); - static CHIP_ERROR ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen); - static CHIP_ERROR ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen); - static CHIP_ERROR ReadConfigValueBin(const char * key, uint8_t * buf, size_t bufSize, size_t & outLen); - - static CHIP_ERROR WriteConfigValue(Key key, bool val); - static CHIP_ERROR WriteConfigValue(Key key, uint32_t val); - static CHIP_ERROR WriteConfigValue(Key key, uint64_t val); - static CHIP_ERROR WriteConfigValueStr(Key key, const char * str); - static CHIP_ERROR WriteConfigValueStr(Key key, const char * str, size_t strLen); - static CHIP_ERROR WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen); - static CHIP_ERROR WriteWifiInfo(const char * ssid, const char * passwd); - static CHIP_ERROR ReadWiFiInfo(const char * ssid, uint32_t ssid_size, const char * passwd, uint32_t passwd_size); - static bool isWiFiInfoSaved(void); - - static CHIP_ERROR ClearConfigValue(Key key); - static bool ConfigValueExists(Key key); - - // // NVS Namespace helper functions. - // static CHIP_ERROR EnsureNamespace(const char * ns); - // static CHIP_ERROR ClearNamespace(const char * ns); - - static void RunConfigUnitTest(void); -}; - -struct BL602Config::Key -{ - // const char * Namespace; - const char * name; - - bool operator==(const Key & other) const; -}; - -inline bool BL602Config::Key::operator==(const Key & other) const -{ - return strcmp(name, other.name) == 0; -} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/BUILD.gn b/src/platform/bouffalolab/BL602/BUILD.gn index 64846e02898547..0f414afb036db6 100644 --- a/src/platform/bouffalolab/BL602/BUILD.gn +++ b/src/platform/bouffalolab/BL602/BUILD.gn @@ -1,4 +1,5 @@ -# Copyright (c) 2021 Project CHIP Authors +# Copyright (c) 2022 Project CHIP Authors +# All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,7 +14,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("//build_overrides/pigweed.gni") import("${chip_root}/src/platform/device.gni") @@ -21,50 +21,45 @@ assert(chip_device_platform == "bl602") static_library("BL602") { sources = [ - "../../FreeRTOS/SystemTimeSupport.cpp", - "../../SingletonConfigurationManager.cpp", - "BL602Config.cpp", - "BL602Config.h", - "BLEManagerImpl.cpp", - "BLEManagerImpl.h", - "BlePlatformConfig.h", - "CHIPDevicePlatformConfig.h", - "CHIPDevicePlatformEvent.h", - "CHIPMem-Platform.cpp", - "CHIPPlatformConfig.h", "ConfigurationManagerImpl.cpp", - "ConfigurationManagerImpl.h", "ConnectivityManagerImpl.cpp", - "ConnectivityManagerImpl.h", "DiagnosticDataProviderImpl.cpp", - "DiagnosticDataProviderImpl.h", - "InetPlatformConfig.h", - "Logging.cpp", "NetworkCommissioningDriver.cpp", - "OTAImageProcessorImpl.cpp", "PlatformManagerImpl.cpp", - "PlatformManagerImpl.h", - "SystemPlatformConfig.h", "wifi_mgmr_portable.c", - "wifi_mgmr_portable.h", - ] - - deps = [ - "${chip_root}/src/lib/dnssd:platform_header", - "${chip_root}/src/setup_payload", - ] - - public_deps = [ "${chip_root}/src/platform:platform_base" ] - - sources += [ - "KeyValueStoreManagerImpl.cpp", - "KeyValueStoreManagerImpl.h", ] - sources += [ + common_sources = [ "${chip_root}/src/credentials/CHIPCert.h", "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", + "../../FreeRTOS/SystemTimeSupport.cpp", + "../../SingletonConfigurationManager.cpp", + "../common/BLConfig.cpp", + "../common/ConfigurationManagerImpl.cpp", + "../common/ConnectivityManagerImpl.cpp", + "../common/DiagnosticDataProviderImpl.cpp", "../common/FactoryDataProvider.cpp", "../common/FactoryDataProvider.h", + "../common/KeyValueStoreManagerImpl.cpp", + "../common/Logging.cpp", + "../common/PlatformManagerImpl.cpp", ] + + if (chip_enable_ota_requestor) { + sources += [ + "../common/OTAImageProcessorImpl.cpp", + "../common/OTAImageProcessorImpl.h", + ] + } + + if (chip_enable_ble) { + sources += [ + "../common/BLEManagerImpl.cpp", + "../common/BLEManagerImpl.h", + ] + } + sources += common_sources + + deps = [ "${chip_root}/src/lib/dnssd:platform_header" ] + public_deps = [ "${chip_root}/src/platform:platform_base" ] } diff --git a/src/platform/bouffalolab/BL602/BlePlatformConfig.h b/src/platform/bouffalolab/BL602/BlePlatformConfig.h deleted file mode 100644 index f445cabca58a59..00000000000000 --- a/src/platform/bouffalolab/BL602/BlePlatformConfig.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Platform-specific configuration overrides for the CHIP BLE - * Layer on the BL602 platform. - * - */ - -#pragma once - -// ==================== Platform Adaptations ==================== - -struct bt_conn; -#define BLE_CONNECTION_OBJECT bt_conn * -#define BLE_CONNECTION_UNINITIALIZED nullptr -#define BLE_MAX_RECEIVE_WINDOW_SIZE 5 - -// ========== Platform-specific Configuration Overrides ========= - -/* none so far */ diff --git a/src/platform/bouffalolab/BL602/CHIPDevicePlatformConfig.h b/src/platform/bouffalolab/BL602/CHIPDevicePlatformConfig.h deleted file mode 100644 index 7e6b56f57e3fed..00000000000000 --- a/src/platform/bouffalolab/BL602/CHIPDevicePlatformConfig.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 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. - */ - -/** - * @file - * Platform-specific configuration overrides for the Chip Device Layer - * on BL602 platforms using the BouffaloLab SDK. - */ - -#pragma once - -// ==================== Platform Adaptations ==================== - -#define CHIP_DEVICE_CONFIG_BL602_EASYFLASH_ERROR_MIN 22000000 -#define CHIP_DEVICE_CONFIG_BL602_BLE_ERROR_MIN 23000000 - -#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 0 -#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 - -#if CHIP_ENABLE_OPENTHREAD -#define CHIP_DEVICE_CONFIG_ENABLE_THREAD 1 -#define CHIP_DEVICE_CONFIG_ENABLE_MDNS 1 -#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 -#endif - -//#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 - -#define CHIP_DEVICE_CONFIG_PERSISTED_STORAGE_CRIT_EIDC_KEY 2 -#define CHIP_DEVICE_CONFIG_PERSISTED_STORAGE_PROD_EIDC_KEY 3 -#define CHIP_DEVICE_CONFIG_PERSISTED_STORAGE_INFO_EIDC_KEY 4 -#define CHIP_DEVICE_CONFIG_PERSISTED_STORAGE_DEBUG_EIDC_KEY 5 - -// ========== Platform-specific Configuration ========= - -// These are configuration options that are unique to the BL602 platform. -// These can be overridden by the application as needed. - -// -------------- BL602 EasyFlash Storage Configuration ------------- - -/** - * @def CHIP_DEVICE_CONFIG_EASYFLASH_MAX_NUM_OBJECTS - * - * @brief - * Configures the size of the easyflash cache and should be set >= the - * maximum number of Chip Config objects, e.g... - * Factory configs[5], System configs[23], Counter configs[32] + margin[4] = 64. - * - */ -#ifndef CHIP_DEVICE_CONFIG_EASYFLASH_MAX_NUM_OBJECTS -#define CHIP_DEVICE_CONFIG_EASYFLASH_MAX_NUM_OBJECTS 64 -#endif // CHIP_DEVICE_CONFIG_EASYFLASH_MAX_NUM_OBJECTS - -/** - * @def CHIP_DEVICE_CONFIG_EASYFLASH_MAX_OBJECT_SIZE - * - * @brief - * This determines the max size for any Chip easyflash object - * (e.g. for Config 'string' or 'binary' types). - */ -#ifndef CHIP_DEVICE_CONFIG_EASYFLASH_MAX_OBJECT_SIZE -#define CHIP_DEVICE_CONFIG_EASYFLASH_MAX_OBJECT_SIZE 1000 -#endif // CHIP_DEVICE_CONFIG_EASYFLASH_MAX_OBJECT_SIZE - -/** - * @def CHIP_DEVICE_CONFIG_EASYFLASH_NUM_FLASH_PAGES_FOR_STORAGE - * - * @brief - * This determines the Flash size used for easyflash data storage:- - * (assuming 2k Flash page size) => Total Flash size for easyflash: 8 * 2k = 16k - * The total size should allow sufficient margin for wear-levelling and - * repacking. - */ -#ifndef CHIP_DEVICE_CONFIG_EASYFLASH_NUM_FLASH_PAGES_FOR_STORAGE -#define CHIP_DEVICE_CONFIG_EASYFLASH_NUM_FLASH_PAGES_FOR_STORAGE 8 -#endif // CHIP_DEVICE_CONFIG_EASYFLASH_NUM_FLASH_PAGES_FOR_STORAGE - -// ========== Platform-specific Configuration Overrides ========= - -#ifndef CHIP_DEVICE_CONFIG_BLE_LL_TASK_PRIORITY -#define CHIP_DEVICE_CONFIG_BLE_LL_TASK_PRIORITY (configTIMER_TASK_PRIORITY - 1) -#endif // CHIP_DEVICE_CONFIG_BLE_LL_TASK_PRIORITY - -#ifndef CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY -#define CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY (CHIP_DEVICE_CONFIG_BLE_LL_TASK_PRIORITY - 1) -#endif // CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY - -#ifndef CHIP_DEVICE_CONFIG_BLE_APP_TASK_PRIORITY -#define CHIP_DEVICE_CONFIG_BLE_APP_TASK_PRIORITY (CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY - 1) -#endif // CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY - -#ifndef CHIP_DEVICE_CONFIG_BLE_APP_TASK_STACK_SIZE -#define CHIP_DEVICE_CONFIG_BLE_APP_TASK_STACK_SIZE 1536 -#endif // CHIP_DEVICE_CONFIG_BLE_APP_TASK_STACK_SIZE - -#ifndef CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE -#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE (8 * 1024) -#endif // CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE - -#ifndef CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE -#if defined(BL602MG21) -#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE (2 * 1024) -#else -#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE (3 * 1024) -#endif -#endif // CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE - -#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_TELEMETRY 0 -#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY 0 -#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY_FULL 0 - -#ifndef CHIP_DEVICE_CONFIG_BLE_APP_TASK_NAME -#define CHIP_DEVICE_CONFIG_BLE_APP_TASK_NAME "BLE_EVENT" -#endif // CHIP_DEVICE_CONFIG_BLE_APP_TASK_NAME - -#define CHIP_DEVICE_CONFIG_MAX_EVENT_QUEUE_SIZE 25 diff --git a/src/platform/bouffalolab/BL602/CHIPDevicePlatformEvent.h b/src/platform/bouffalolab/BL602/CHIPDevicePlatformEvent.h deleted file mode 100644 index 1342cc24ac2830..00000000000000 --- a/src/platform/bouffalolab/BL602/CHIPDevicePlatformEvent.h +++ /dev/null @@ -1,99 +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 - * Defines platform-specific event types and data for the chip - * Device Layer on the BL602 platform. - */ - -#pragma once - -#include - -#include -#include - -namespace chip { -namespace DeviceLayer { - -namespace DeviceEventType { - -/** - * Enumerates Zephyr platform-specific event types that are visible to the application. - */ -enum PublicPlatformSpecificEventTypes -{ - /* None currently defined */ -}; - -/** - * Enumerates Zephyr platform-specific event types that are internal to the chip Device Layer. - */ -enum InternalPlatformSpecificEventTypes -{ - kPlatformZephyrEvent = kRange_InternalPlatformSpecific, - kPlatformZephyrBleConnected, - kPlatformZephyrBleDisconnected, - kPlatformZephyrBleCCCWrite, - kPlatformZephyrBleC1WriteEvent, - kPlatformZephyrBleC2IndDoneEvent, - kPlatformZephyrBleOutOfBuffersEvent, -}; - -} // namespace DeviceEventType - -struct BleConnEventType -{ - bt_conn * BtConn; - uint8_t HciResult; -}; - -struct BleCCCWriteEventType -{ - bt_conn * BtConn; - uint16_t Value; -}; - -struct BleC1WriteEventType -{ - bt_conn * BtConn; - ::chip::System::PacketBuffer * Data; -}; - -struct BleC2IndDoneEventType -{ - bt_conn * BtConn; - uint8_t Result; -}; - -/** - * Represents platform-specific event information for BL602 platforms. - */ -struct ChipDevicePlatformEvent final -{ - union - { - BleConnEventType BleConnEvent; - BleCCCWriteEventType BleCCCWriteEvent; - BleC1WriteEventType BleC1WriteEvent; - BleC2IndDoneEventType BleC2IndDoneEvent; - }; -}; - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp b/src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp deleted file mode 100644 index 3b9b274941bfb8..00000000000000 --- a/src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 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. - */ - -/* - * - * Copyright (c) 2020-2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * This file implements heap memory allocation APIs for CHIP. These functions are platform - * specific and might be C Standard Library heap functions re-direction in most of cases. - * - */ - -//#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include - -extern "C" { -#include -}; - -#if CHIP_CONFIG_MEMORY_MGMT_PLATFORM - -extern "C" void memMonitoringTrackAlloc(void * ptr, size_t size); -extern "C" void memMonitoringTrackFree(void * ptr, size_t size); - -#ifndef trackAlloc -#define trackAlloc(pvAddress, uiSize) memMonitoringTrackAlloc(pvAddress, uiSize) -#endif -#ifndef trackFree -#define trackFree(pvAddress, uiSize) memMonitoringTrackFree(pvAddress, uiSize) -#endif - -namespace chip { -namespace Platform { - -#define VERIFY_INITIALIZED() VerifyInitialized(__func__) - -static std::atomic_int memoryInitialized{ 0 }; - -static void VerifyInitialized(const char * func) -{ - if (!memoryInitialized) - { - log_error("ABORT: chip::Platform::%s() called before chip::Platform::MemoryInit()\r\n", func); - abort(); - } -} - -CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize) -{ -#ifndef NDEBUG - if (memoryInitialized++ > 0) - { - log_error("ABORT: chip::Platform::MemoryInit() called twice.\r\n"); - abort(); - } -#endif - return CHIP_NO_ERROR; -} - -void MemoryAllocatorShutdown() -{ -#ifndef NDEBUG - if (--memoryInitialized < 0) - { - log_error("ABORT: chip::Platform::MemoryShutdown() called twice.\r\n"); - abort(); - } -#endif -} - -void * MemoryAlloc(size_t size) -{ - void * ptr; - VERIFY_INITIALIZED(); - ptr = pvPortMalloc(size); - trackAlloc(ptr, size); - return ptr; -} - -void * MemoryAlloc(size_t size, bool isLongTermAlloc) -{ - void * ptr; - VERIFY_INITIALIZED(); - ptr = pvPortMalloc(size); - trackAlloc(ptr, size); - return ptr; -} - -void * MemoryCalloc(size_t num, size_t size) -{ - void * ptr; - VERIFY_INITIALIZED(); - ptr = pvPortCalloc(num, size); - trackAlloc(ptr, size * num); - return ptr; -} - -void * MemoryRealloc(void * p, size_t size) -{ - VERIFY_INITIALIZED(); - return pvPortRealloc(p, size); -} - -void MemoryFree(void * p) -{ - VERIFY_INITIALIZED(); - trackFree(p, 0); - vPortFree(p); -} - -bool MemoryInternalCheckPointer(const void * p, size_t min_size) -{ - return (p != nullptr); -} - -} // namespace Platform -} // namespace chip - -extern "C" void memMonitoringTrackAlloc(void * ptr, size_t size) {} - -extern "C" void memMonitoringTrackFree(void * ptr, size_t size) {} - -#endif // CHIP_CONFIG_MEMORY_MGMT_PLATFORM diff --git a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp b/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp index 5c53153867fbe0..b112fe751a4358 100644 --- a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp @@ -1,7 +1,5 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Nest Labs, Inc. + * Copyright (c) 2022 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,213 +15,25 @@ * limitations under the License. */ -/** - * @file - * Provides the implementation of the Device Layer ConfigurationManager object - * for the BL602 platform. - */ -/* this file behaves like a config.h, comes first */ #include -#include -#include #include -#include + #include +#include +#include + +#include +#include + extern "C" { #include -#include -#include } namespace chip { namespace DeviceLayer { -using namespace ::chip::DeviceLayer::Internal; - -namespace { - -enum -{ - kChipProduct_Connect = 0x0016 -}; - -} // unnamed namespace - -/** Singleton instance of the ConfigurationManager implementation object for the BL602 platform. - */ -ConfigurationManagerImpl ConfigurationManagerImpl::sInstance; - -ConfigurationManagerImpl & ConfigurationManagerImpl::GetDefaultInstance() -{ - static ConfigurationManagerImpl sInstance; - return sInstance; -} - -CHIP_ERROR ConfigurationManagerImpl::Init() -{ - CHIP_ERROR err; - bool failSafeArmed; - uint32_t rebootCount; - - // Initialize the generic implementation base class. - err = Internal::GenericConfigurationManagerImpl::Init(); - SuccessOrExit(err); - - if (BL602Config::ConfigValueExists(BL602Config::kCounterKey_RebootCount)) - { - err = GetRebootCount(rebootCount); - SuccessOrExit(err); - } - else - { - rebootCount = 0; - } - - err = StoreRebootCount(rebootCount + 1); - SuccessOrExit(err); - - if (!BL602Config::ConfigValueExists(BL602Config::kCounterKey_TotalOperationalHours)) - { - err = StoreTotalOperationalHours(0); - SuccessOrExit(err); - } - - // If the fail-safe was armed when the device last shutdown, initiate a factory reset. - if (GetFailSafeArmed(failSafeArmed) == CHIP_NO_ERROR && failSafeArmed) - { - ChipLogProgress(DeviceLayer, "Detected fail-safe armed on reboot; initiating factory reset"); - InitiateFactoryReset(); - } - err = CHIP_NO_ERROR; - -exit: - return err; -} - -bool ConfigurationManagerImpl::CanFactoryReset() -{ - // TODO: query the application to determine if factory reset is allowed. - return true; -} - -void ConfigurationManagerImpl::InitiateFactoryReset() -{ - PlatformMgr().ScheduleWork(DoFactoryReset); -} - -CHIP_ERROR ConfigurationManagerImpl::GetRebootCount(uint32_t & rebootCount) -{ - return BL602Config::ReadConfigValue(BL602Config::kCounterKey_RebootCount, rebootCount); -} - -CHIP_ERROR ConfigurationManagerImpl::StoreRebootCount(uint32_t rebootCount) -{ - return BL602Config::WriteConfigValue(BL602Config::kCounterKey_RebootCount, rebootCount); -} - -CHIP_ERROR ConfigurationManagerImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) -{ - return ReadConfigValue(BL602Config::kCounterKey_TotalOperationalHours, totalOperationalHours); -} - -CHIP_ERROR ConfigurationManagerImpl::StoreTotalOperationalHours(uint32_t totalOperationalHours) -{ - return WriteConfigValue(BL602Config::kCounterKey_TotalOperationalHours, totalOperationalHours); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) -{ - BL602Config::Key configKey{ key }; - - CHIP_ERROR err = ReadConfigValue(configKey, value); - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - return err; -} - -CHIP_ERROR ConfigurationManagerImpl::WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) -{ - BL602Config::Key configKey{ key }; - return WriteConfigValue(configKey, value); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, bool & val) -{ - return BL602Config::ReadConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint32_t & val) -{ - return BL602Config::ReadConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint64_t & val) -{ - return BL602Config::ReadConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) -{ - return BL602Config::ReadConfigValueStr(key, buf, bufSize, outLen); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) -{ - return BL602Config::ReadConfigValueBin(key, buf, bufSize, outLen); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, bool val) -{ - return BL602Config::WriteConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint32_t val) -{ - return BL602Config::WriteConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint64_t val) -{ - return BL602Config::WriteConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str) -{ - return BL602Config::WriteConfigValueStr(key, str); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str, size_t strLen) -{ - return BL602Config::WriteConfigValueStr(key, str, strLen); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) -{ - return BL602Config::WriteConfigValueBin(key, data, dataLen); -} - -void ConfigurationManagerImpl::RunConfigUnitTest(void) -{ - BL602Config::RunConfigUnitTest(); -} - -void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) -{ - ChipLogProgress(DeviceLayer, "Performing factory reset"); - ef_env_set_default(); - ChipLogProgress(DeviceLayer, "System restarting"); - hal_reboot(); -} - -ConfigurationManager & ConfigurationMgrImpl() -{ - return ConfigurationManagerImpl::GetDefaultInstance(); -} - CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * buf) { bl_efuse_read_mac(buf); diff --git a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h b/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h deleted file mode 100644 index 0183da4e3a007f..00000000000000 --- a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Nest Labs, Inc. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Provides an implementation of the ConfigurationManager object - * for the BL602 platform. - */ - -#pragma once - -#include -#include -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include -#else -#include -#endif - -#include - -namespace chip { -namespace DeviceLayer { - -/** - * Concrete implementation of the ConfigurationManager singleton object for the BL602 platform. - */ -class ConfigurationManagerImpl final : public Internal::GenericConfigurationManagerImpl, -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - public Internal::GenericConnectivityManagerImpl_BLE -#else - public Internal::GenericConnectivityManagerImpl_NoBLE -#endif -{ -public: - static ConfigurationManagerImpl & GetDefaultInstance(); - // Allow the ConfigurationManager interface class to delegate method calls to - // the implementation methods provided by this class. - friend class ConfigurationManager; - -private: - // ===== Members that implement the ConfigurationManager public interface. - - CHIP_ERROR Init(void) override; - CHIP_ERROR GetPrimaryWiFiMACAddress(uint8_t * buf) override; - bool CanFactoryReset(void) override; - void InitiateFactoryReset(void) override; - CHIP_ERROR ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) override; - CHIP_ERROR WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) override; - - CHIP_ERROR GetRebootCount(uint32_t & rebootCount) override; - CHIP_ERROR StoreRebootCount(uint32_t rebootCount) override; - CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours) override; - CHIP_ERROR StoreTotalOperationalHours(uint32_t totalOperationalHours) override; -#if 0 - CHIP_ERROR GetBootReason(uint32_t & bootReasons) override; - CHIP_ERROR StoreBootReason(uint32_t bootReasons) override; -#endif - - // NOTE: Other public interface methods are implemented by GenericConfigurationManagerImpl<>. - - // ===== Members for internal use by the following friends. - - CHIP_ERROR ReadConfigValue(Key key, bool & val) override; - CHIP_ERROR ReadConfigValue(Key key, uint32_t & val) override; - CHIP_ERROR ReadConfigValue(Key key, uint64_t & val) override; - CHIP_ERROR ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) override; - CHIP_ERROR ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) override; - CHIP_ERROR WriteConfigValue(Key key, bool val) override; - CHIP_ERROR WriteConfigValue(Key key, uint32_t val) override; - CHIP_ERROR WriteConfigValue(Key key, uint64_t val) override; - CHIP_ERROR WriteConfigValueStr(Key key, const char * str) override; - CHIP_ERROR WriteConfigValueStr(Key key, const char * str, size_t strLen) override; - CHIP_ERROR WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) override; - void RunConfigUnitTest(void) override; - - static ConfigurationManagerImpl sInstance; - - // ===== Private members reserved for use by this class only. - - static void DoFactoryReset(intptr_t arg); -}; - -/** - * Returns the platform-specific implementation of the ConfigurationManager object. - * - * Applications can use this to gain access to features of the ConfigurationManager - * that are specific to the selected platform. - */ -ConfigurationManager & ConfigurationMgrImpl(); - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp index 56e3ebf522a36b..9f209d14ebf133 100644 --- a/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp @@ -1,7 +1,6 @@ /* - * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Nest Labs, Inc. + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* this file behaves like a config.h, comes first */ + #include #include @@ -68,7 +67,6 @@ using namespace ::chip::DeviceLayer::Internal; namespace chip { namespace DeviceLayer { -ConnectivityManagerImpl ConnectivityManagerImpl::sInstance; ConnectivityManager::WiFiStationState ConnectivityManagerImpl::mWiFiStationState = ConnectivityManager::kWiFiStationState_NotConnected; @@ -103,34 +101,6 @@ CHIP_ERROR ConnectivityManagerImpl::_SetWiFiStationMode(WiFiStationMode val) return err; } -CHIP_ERROR ConnectivityManagerImpl::_Init() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - // Initialize the generic base classes that require it. -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD - GenericConnectivityManagerImpl_Thread::_Init(); -#endif - - SuccessOrExit(err); - - err = SetWiFiStationMode(kWiFiStationMode_Enabled); - NetworkCommissioning::BLWiFiDriver::GetInstance().ReConnectWiFiNetwork(); - - SuccessOrExit(err); - -exit: - return err; -} - -void ConnectivityManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) -{ - // Forward the event to the generic base classes as needed. -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD - GenericConnectivityManagerImpl_Thread::_OnPlatformEvent(event); -#endif -} - bool ConnectivityManagerImpl::_IsWiFiStationEnabled(void) { return GetWiFiStationMode() == kWiFiStationMode_Enabled; diff --git a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp index 3597e599a4c587..b49fa9cbde9a5a 100644 --- a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp +++ b/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp @@ -1,6 +1,6 @@ /* - * - * Copyright (c) 2021-2022 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,133 +15,51 @@ * limitations under the License. */ -/** - * @file - * Provides an implementation of the DiagnosticDataProvider object - * for Bouffalolab BL602 platform. - */ - -#include - -#include -#include #include +#include +#include +#include #include extern "C" { +#include +#include + #include #include #include -#include -#include #include #include } -extern uint8_t _heap_size; - namespace chip { namespace DeviceLayer { -DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() -{ - static DiagnosticDataProviderImpl sInstance; - return sInstance; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) -{ - size_t freeHeapSize; - - freeHeapSize = xPortGetFreeHeapSize(); - currentHeapFree = static_cast(freeHeapSize); - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) -{ - currentHeapUsed = (uint32_t) &_heap_size - xPortGetFreeHeapSize(); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) -{ - currentHeapHighWatermark = (uint32_t) &_heap_size - xPortGetMinimumEverFreeHeapSize(); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetRebootCount(uint16_t & rebootCount) -{ - uint32_t count = 0; - - CHIP_ERROR err = ConfigurationMgr().GetRebootCount(count); - - if (err == CHIP_NO_ERROR) - { - VerifyOrReturnError(count <= UINT16_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); - rebootCount = static_cast(count); - } - - return err; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetUpTime(uint64_t & upTime) -{ - System::Clock::Timestamp currentTime = System::SystemClock().GetMonotonicTimestamp(); - System::Clock::Timestamp startTime = PlatformMgrImpl().GetStartTime(); - - if (currentTime >= startTime) - { - upTime = std::chrono::duration_cast(currentTime - startTime).count(); - return CHIP_NO_ERROR; - } - - return CHIP_ERROR_INVALID_TIME; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) -{ - uint64_t upTime = 0; - - if (GetUpTime(upTime) == CHIP_NO_ERROR) - { - uint32_t totalHours = 0; - if (ConfigurationMgr().GetTotalOperationalHours(totalHours) == CHIP_NO_ERROR) - { - VerifyOrReturnError(upTime / 3600 <= UINT32_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); - totalOperationalHours = totalHours + static_cast(upTime / 3600); - return CHIP_NO_ERROR; - } - } - - return CHIP_ERROR_INVALID_TIME; -} - CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason) { - BL_RST_REASON_E BL_RST_REASON = bl_sys_rstinfo_get(); - - bootReason = BootReasonType::kUnspecified; + BL_RST_REASON_E bootCause = bl_sys_rstinfo_get(); - if (BL_RST_REASON == BL_RST_POWER_OFF) + if (bootCause == BL_RST_POWER_OFF) { bootReason = BootReasonType::kPowerOnReboot; } - else if (BL_RST_REASON == BL_RST_HARDWARE_WATCHDOG) + else if (bootCause == BL_RST_HARDWARE_WATCHDOG) { bootReason = BootReasonType::kHardwareWatchdogReset; } - else if (BL_RST_REASON == BL_RST_SOFTWARE_WATCHDOG) + else if (bootCause == BL_RST_SOFTWARE_WATCHDOG) { bootReason = BootReasonType::kSoftwareWatchdogReset; } - else if (BL_RST_REASON == BL_RST_SOFTWARE) + else if (bootCause == BL_RST_SOFTWARE) { bootReason = BootReasonType::kSoftwareReset; } + else + { + bootReason = BootReasonType::kUnspecified; + } return CHIP_NO_ERROR; } @@ -214,11 +132,6 @@ void DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * net } } -DiagnosticDataProvider & GetDiagnosticDataProviderImpl() -{ - return DiagnosticDataProviderImpl::GetDefaultInstance(); -} - CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(MutableByteSpan & BssId) { return CopySpanToMutableSpan(ByteSpan(wifiMgmr.wifi_mgmr_stat_info.bssid), BssId); @@ -376,5 +289,4 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconRxCount(uint32_t & beaconRxC } } // namespace DeviceLayer -wifi_diagnosis_info_t * info; } // namespace chip diff --git a/src/platform/bouffalolab/BL602/InetPlatformConfig.h b/src/platform/bouffalolab/BL602/InetPlatformConfig.h deleted file mode 100644 index 0c17f57a4c798a..00000000000000 --- a/src/platform/bouffalolab/BL602/InetPlatformConfig.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Google LLC. - * - * 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 - * Platform-specific configuration overrides for the CHIP Inet - * Layer on BL602 platforms using the Bouffalolab SDK. - * - */ - -#pragma once - -#include - -// ==================== Platform Adaptations ==================== - -#define INET_CONFIG_ERROR_TYPE int32_t -#define INET_CONFIG_NO_ERROR 0 -#define INET_CONFIG_ERROR_MIN 1000000 -#define INET_CONFIG_ERROR_MAX 1000999 - -#define INET_CONFIG_ENABLE_IPV4 1 - -// ========== Platform-specific Configuration Overrides ========= - -#ifndef INET_CONFIG_NUM_TCP_ENDPOINTS -#define INET_CONFIG_NUM_TCP_ENDPOINTS 4 -#endif // INET_CONFIG_NUM_TCP_ENDPOINTS - -#ifndef INET_CONFIG_NUM_UDP_ENDPOINTS -#define INET_CONFIG_NUM_UDP_ENDPOINTS 6 -#endif // INET_CONFIG_NUM_UDP_ENDPOINTS diff --git a/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp b/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp deleted file mode 100644 index dc7aee8708d0f5..00000000000000 --- a/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Platform-specific key value storage implementation for BL602 - */ -/* this file behaves like a config.h, comes first */ -#include - -#include - -#include - -#include -#include - -namespace chip { -namespace DeviceLayer { -namespace PersistedStorage { - -using namespace ::chip::DeviceLayer::Internal; - -KeyValueStoreManagerImpl KeyValueStoreManagerImpl::sInstance; - -CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t value_size, size_t * read_bytes_size, - size_t offset_bytes) const -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - // todo: need get value at offset for return - size_t outlen = 0; - BL602Config::Key ckey = { key }; - - err = BL602Config::ReadConfigValueBin(ckey, (uint8_t *) value, value_size, outlen); - if (CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND == err) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - SuccessOrExit(err); - - if (read_bytes_size) - { - *read_bytes_size = outlen; - } - -exit: - return err; -} - -CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, size_t value_size) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - BL602Config::Key ckey = { key }; - - err = BL602Config::WriteConfigValueBin(ckey, (uint8_t *) value, value_size); - if (CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND == err) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - BL602Config::Key ckey = { key }; - - err = BL602Config::ClearConfigValue(ckey); - - if (CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND == err) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - return err; -} - -// #if defined(CHIP_KVS_AVAILABLE) && CHIP_KVS_AVAILABLE - -// CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t value_size, size_t * read_bytes_size, -// size_t offset_bytes) const -// { -// assert(CHIP_KVS_AVAILABLE); -// auto status_and_size = mKvs.Get(key, pw::span(reinterpret_cast(value), value_size), offset_bytes); -// if (read_bytes_size) -// { -// *read_bytes_size = status_and_size.size(); -// } -// switch (status_and_size.status().code()) -// { -// case pw::OkStatus().code(): -// return CHIP_NO_ERROR; -// case pw::Status::NotFound().code(): -// return CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; -// case pw::Status::DataLoss().code(): -// return CHIP_ERROR_INTEGRITY_CHECK_FAILED; -// case pw::Status::ResourceExhausted().code(): -// return CHIP_ERROR_BUFFER_TOO_SMALL; -// case pw::Status::FailedPrecondition().code(): -// return CHIP_ERROR_WELL_UNINITIALIZED; -// case pw::Status::InvalidArgument().code(): -// return CHIP_ERROR_INVALID_ARGUMENT; -// default: -// break; -// } -// return CHIP_ERROR_INTERNAL; // Unexpected KVS status. -// } - -// CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, size_t value_size) -// { -// assert(CHIP_KVS_AVAILABLE); -// auto status = mKvs.Put(key, pw::span(reinterpret_cast(value), value_size)); -// switch (status.code()) -// { -// case pw::OkStatus().code(): -// return CHIP_NO_ERROR; -// case pw::Status::DataLoss().code(): -// return CHIP_ERROR_INTEGRITY_CHECK_FAILED; -// case pw::Status::ResourceExhausted().code(): -// case pw::Status::AlreadyExists().code(): -// return CHIP_ERROR_PERSISTED_STORAGE_FAILED; -// case pw::Status::FailedPrecondition().code(): -// return CHIP_ERROR_WELL_UNINITIALIZED; -// case pw::Status::InvalidArgument().code(): -// return CHIP_ERROR_INVALID_ARGUMENT; -// default: -// break; -// } -// return CHIP_ERROR_INTERNAL; // Unexpected KVS status. -// } - -// CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) -// { -// printf("KeyValueStoreManagerImpl::_Delete, key = %s\r\n", key); -// assert(CHIP_KVS_AVAILABLE); -// printf("KeyValueStoreManagerImpl::_Delete, key = %s\r\n", key); - -// auto status = mKvs.Delete(key); -// switch (status.code()) -// { -// case pw::OkStatus().code(): -// return CHIP_NO_ERROR; -// case pw::Status::NotFound().code(): -// return CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; -// case pw::Status::DataLoss().code(): -// return CHIP_ERROR_INTEGRITY_CHECK_FAILED; -// case pw::Status::ResourceExhausted().code(): -// return CHIP_ERROR_PERSISTED_STORAGE_FAILED; -// case pw::Status::FailedPrecondition().code(): -// return CHIP_ERROR_WELL_UNINITIALIZED; -// case pw::Status::InvalidArgument().code(): -// return CHIP_ERROR_INVALID_ARGUMENT; -// default: -// break; -// } -// return CHIP_ERROR_INTERNAL; // Unexpected KVS status. -// } - -// CHIP_ERROR KeyValueStoreManagerImpl::ErasePartition() -// { -// assert(CHIP_KVS_AVAILABLE); -// auto status = mKvsPartition.Erase(); -// switch (status.code()) -// { -// case pw::OkStatus().code(): -// return CHIP_NO_ERROR; -// case pw::Status::DeadlineExceeded().code(): -// return CHIP_ERROR_TIMEOUT; -// case pw::Status::PermissionDenied().code(): -// return CHIP_ERROR_ACCESS_DENIED; -// default: -// break; -// } -// return CHIP_ERROR_INTERNAL; // Unexpected KVS status. -// } -// #endif // defined(CHIP_KVS_AVAILABLE) && CHIP_KVS_AVAILABLE - -} // namespace PersistedStorage -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.h b/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.h deleted file mode 100644 index c7d495b347db42..00000000000000 --- a/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Platform-specific key value storage implementation for BL602. - * - */ - -#pragma once -namespace chip { -namespace DeviceLayer { -namespace PersistedStorage { - -class KeyValueStoreManagerImpl final : public KeyValueStoreManager -{ - // Allow the KeyValueStoreManager interface class to delegate method calls to - // the implementation methods provided by this class. - friend class KeyValueStoreManager; - -public: - CHIP_ERROR _Get(const char * key, void * value, size_t value_size, size_t * read_bytes_size = nullptr, size_t offset = 0) const; - - CHIP_ERROR _Delete(const char * key); - - CHIP_ERROR _Put(const char * key, const void * value, size_t value_size); - -private: - // ===== Members for internal use by the following friends. - friend KeyValueStoreManager & KeyValueStoreMgr(); - friend KeyValueStoreManagerImpl & KeyValueStoreMgrImpl(); - - static KeyValueStoreManagerImpl sInstance; -}; - -/** - * Returns the public interface of the KeyValueStoreManager singleton object. - * - * Chip applications should use this to access features of the KeyValueStoreManager object - * that are common to all platforms. - */ -inline KeyValueStoreManager & KeyValueStoreMgr(void) -{ - return KeyValueStoreManagerImpl::sInstance; -} - -/** - * Returns the platform-specific implementation of the KeyValueStoreManager singleton object. - * - * Chip applications can use this to gain access to features of the KeyValueStoreManager - * that are specific to the ESP32 platform. - */ -inline KeyValueStoreManagerImpl & KeyValueStoreMgrImpl(void) -{ - return KeyValueStoreManagerImpl::sInstance; -} - -} // namespace PersistedStorage -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/Logging.cpp b/src/platform/bouffalolab/BL602/Logging.cpp deleted file mode 100644 index 33397bd520f409..00000000000000 --- a/src/platform/bouffalolab/BL602/Logging.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* See Project CHIP LICENSE file for licensing information. */ - -#include - -#include -#include - -#include -#include - -#ifdef PW_RPC_ENABLED -#include "PigweedLogger.h" -#endif - -namespace chip { -namespace Logging { -namespace Platform { - -void LogV(const char * module, uint8_t category, const char * msg, va_list v) -{ - char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; - -#ifndef PW_RPC_ENABLED - vsnprintf(formattedMsg, sizeof(formattedMsg), msg, v); - - switch (category) - { - case kLogCategory_Error: - log_error("[%s] %s\r\n", module, formattedMsg); - break; - case kLogCategory_Progress: - default: - log_info("[%s] %s\r\n", module, formattedMsg); - break; - case kLogCategory_Detail: - log_trace("[%s] %s\r\n", module, formattedMsg); - break; - } -#else - size_t prefixLen = 0; - - switch (category) - { - case kLogCategory_Error: - strcpy(formattedMsg, "[ERROR] "); - break; - case kLogCategory_Progress: - default: - strcpy(formattedMsg, "[INFO] "); - break; - case kLogCategory_Detail: - strcpy(formattedMsg, "[TRACE] "); - break; - } - - prefixLen = strlen(formattedMsg); - snprintf(formattedMsg + prefixLen, sizeof(formattedMsg) - prefixLen, "[%s] ", module); - prefixLen = strlen(formattedMsg); - vsnprintf(formattedMsg + prefixLen, sizeof(formattedMsg) - prefixLen, msg, v); - - PigweedLogger::putString(formattedMsg, strlen(formattedMsg)); - const char * newline = "\r\n"; - PigweedLogger::putString(newline, strlen(newline)); -#endif -} - -} // namespace Platform -} // namespace Logging -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp index f4ba42ff5adcc2..28f5a5f9a2892d 100644 --- a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp +++ b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp @@ -35,7 +35,7 @@ #define WIFI_STA_DISCONNECT_DELAY (pdMS_TO_TICKS(200)) using namespace ::chip; -//#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + namespace chip { namespace DeviceLayer { namespace NetworkCommissioning { @@ -425,4 +425,3 @@ bool BLWiFiDriver::WiFiNetworkIterator::Next(Network & item) } // namespace NetworkCommissioning } // namespace DeviceLayer } // namespace chip -//#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI diff --git a/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp index a8739d6adfbe9e..56761846061dc2 100644 --- a/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp @@ -1,7 +1,6 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Nest Labs, Inc. + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +15,12 @@ * limitations under the License. */ -/** - * @file - * Provides an implementation of the PlatformManager object - * for BL602 platforms using the Bouffalolab BL602 SDK. - */ -/* this file behaves like a config.h, comes first */ #include #include #include -#include #include +#include #include #include @@ -48,8 +41,6 @@ extern "C" { namespace chip { namespace DeviceLayer { -PlatformManagerImpl PlatformManagerImpl::sInstance; - static wifi_conf_t conf = { .country_code = "CN", }; @@ -237,7 +228,7 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) TaskHandle_t backup_eventLoopTask; // Initialize the configuration system. - err = Internal::BL602Config::Init(); + err = Internal::BLConfig::Init(); SuccessOrExit(err); // Initialize LwIP. @@ -269,30 +260,5 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) return err; } -void PlatformManagerImpl::_Shutdown() -{ - uint64_t upTime = 0; - - if (GetDiagnosticDataProvider().GetUpTime(upTime) == CHIP_NO_ERROR) - { - uint32_t totalOperationalHours = 0; - - if (ConfigurationMgr().GetTotalOperationalHours(totalOperationalHours) == CHIP_NO_ERROR) - { - ConfigurationMgr().StoreTotalOperationalHours(totalOperationalHours + static_cast(upTime / 3600)); - } - else - { - ChipLogError(DeviceLayer, "Failed to get total operational hours of the Node"); - } - } - else - { - ChipLogError(DeviceLayer, "Failed to get current uptime since the Node’s last reboot"); - } - - Internal::GenericPlatformManagerImpl_FreeRTOS::_Shutdown(); -} - } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL602/SystemPlatformConfig.h b/src/platform/bouffalolab/BL602/SystemPlatformConfig.h deleted file mode 100644 index cf6fbdc4be2240..00000000000000 --- a/src/platform/bouffalolab/BL602/SystemPlatformConfig.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Google LLC. - * - * 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 - * Platform-specific configuration overrides for the CHIP System - * Layer on Bouffalolab BL602 Platforms. - * - */ - -#pragma once - -#include - -namespace chip { -namespace DeviceLayer { -struct ChipDeviceEvent; -} // namespace DeviceLayer -} // namespace chip - -// ==================== Platform Adaptations ==================== -#define CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME 1 -#define CHIP_SYSTEM_CONFIG_LWIP_EVENT_TYPE int -#define CHIP_SYSTEM_CONFIG_EVENT_OBJECT_TYPE const struct ::chip::DeviceLayer::ChipDeviceEvent * - -#define CHIP_SYSTEM_CONFIG_ERROR_TYPE int32_t -#define CHIP_SYSTEM_CONFIG_NO_ERROR 0 -#define CHIP_SYSTEM_CONFIG_ERROR_MIN 7000000 -#define CHIP_SYSTEM_CONFIG_ERROR_MAX 7000999 -#define _CHIP_SYSTEM_CONFIG_ERROR(e) (CHIP_SYSTEM_CONFIG_ERROR_MIN + (e)) -#define CHIP_SYSTEM_LWIP_ERROR_MIN 3000000 -#define CHIP_SYSTEM_LWIP_ERROR_MAX 3000128 - -// ========== Platform-specific Configuration Overrides ========= diff --git a/src/platform/bouffalolab/BL602/args.gni b/src/platform/bouffalolab/BL602/args.gni index 0f32696fb1c914..9a4f156ce3ee8c 100644 --- a/src/platform/bouffalolab/BL602/args.gni +++ b/src/platform/bouffalolab/BL602/args.gni @@ -28,8 +28,6 @@ chip_inet_config_enable_ipv4 = true chip_enable_rotating_device_id = false -chip_config_memory_management = "platform" - chip_build_tests = false chip_inet_config_enable_dns_resolver = false chip_inet_config_enable_tun_endpoint = false diff --git a/src/platform/bouffalolab/BL702/BLEManagerImpl.cpp b/src/platform/bouffalolab/BL702/BLEManagerImpl.cpp deleted file mode 100644 index 2a90fdf646aaba..00000000000000 --- a/src/platform/bouffalolab/BL702/BLEManagerImpl.cpp +++ /dev/null @@ -1,834 +0,0 @@ -/* - * - * Copyright (c) 2020-2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define __ZEPHYR__ 1 -#include - -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - -#include "BLEManagerImpl.h" - -#include -#include -#include -#include -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -#include -#endif - -extern "C" { -#include -} - -#include -#include - -using namespace ::chip; -using namespace ::chip::Ble; -using namespace ::chip::System; - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -const bt_uuid_128 UUID128_CHIPoBLEChar_RX = - BT_UUID_INIT_128(0x11, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18); -const bt_uuid_128 UUID128_CHIPoBLEChar_TX = - BT_UUID_INIT_128(0x12, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18); -bt_uuid_16 UUID16_CHIPoBLEService = BT_UUID_INIT_16(0xFFF6); - -const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; - -const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -const bt_uuid_128 UUID128_CHIPoBLEChar_C3 = - BT_UUID_INIT_128(0x04, 0x8F, 0x21, 0x83, 0x8A, 0x74, 0x7D, 0xB8, 0xF2, 0x45, 0x72, 0x87, 0x38, 0x02, 0x63, 0x64); -#endif - -_bt_gatt_ccc CHIPoBLEChar_TX_CCC = BT_GATT_CCC_INITIALIZER(nullptr, BLEManagerImpl::HandleTXCCCWrite, nullptr); - -struct bt_gatt_attr sChipoBleAttributes[] = { - BT_GATT_PRIMARY_SERVICE(&UUID16_CHIPoBLEService.uuid), - BT_GATT_CHARACTERISTIC(&UUID128_CHIPoBLEChar_RX.uuid, BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, nullptr, BLEManagerImpl::HandleRXWrite, nullptr), - BT_GATT_CHARACTERISTIC(&UUID128_CHIPoBLEChar_TX.uuid, BT_GATT_CHRC_INDICATE, BT_GATT_PERM_NONE, nullptr, nullptr, nullptr), - BT_GATT_CCC_MANAGED(&CHIPoBLEChar_TX_CCC, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE), -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - BT_GATT_CHARACTERISTIC(&UUID128_CHIPoBLEChar_C3.uuid, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, BLEManagerImpl::HandleC3Read, - nullptr, nullptr), -#endif -}; - -struct bt_gatt_service sChipoBleService = { - .attrs = sChipoBleAttributes, - .attr_count = sizeof(sChipoBleAttributes) / sizeof(sChipoBleAttributes[0]), -}; - -static const int kCHIPoBLE_CCC_AttributeIndex = 3; - -CHIP_ERROR InitRandomStaticAddress() -{ - // When the BT privacy feature is disabled, generate a random static address once per boot. - // This must be done before bt_enable() has been called. - bt_addr_le_t addr; - - int error = bt_addr_le_create_static(&addr); - if (error) - { - ChipLogError(DeviceLayer, "Failed to create BLE address: %d", error); - return System::MapErrorZephyr(error); - } - - error = bt_id_create(&addr, nullptr); - - if (error < 0) - { - ChipLogError(DeviceLayer, "Failed to create BLE identity: %d", error); - return System::MapErrorZephyr(error); - } - - ChipLogProgress(DeviceLayer, "BLE address: %02X:%02X:%02X:%02X:%02X:%02X", addr.a.val[5], addr.a.val[4], addr.a.val[3], - addr.a.val[2], addr.a.val[1], addr.a.val[0]); - return CHIP_NO_ERROR; -} - -BLEManagerImpl BLEManagerImpl::sInstance; - -CHIP_ERROR BLEManagerImpl::_Init() -{ - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; - mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); - mFlags.Set(Flags::kFastAdvertisingEnabled, true); - mGAPConns = 0; - - memset(mSubscribedConns, 0, sizeof(mSubscribedConns)); - - ReturnErrorOnFailure(InitRandomStaticAddress()); - - ble_controller_init(configMAX_PRIORITIES - 1); - hci_driver_init(); - bt_enable(NULL); - - memset(&mConnCallbacks, 0, sizeof(mConnCallbacks)); - mConnCallbacks.connected = HandleConnect; - mConnCallbacks.disconnected = HandleDisconnect; - - bt_conn_cb_register(&mConnCallbacks); - - // Initialize the CHIP BleLayer. - ReturnErrorOnFailure(BleLayer::Init(this, this, &DeviceLayer::SystemLayer())); - - PlatformMgr().ScheduleWork(DriveBLEState, 0); - - return CHIP_NO_ERROR; -} - -void BLEManagerImpl::DriveBLEState(intptr_t arg) -{ - BLEMgrImpl().DriveBLEState(); -} - -void BLEManagerImpl::DriveBLEState() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - // Perform any initialization actions that must occur after the CHIP task is running. - if (!mFlags.Has(Flags::kAsyncInitCompleted)) - { - mFlags.Set(Flags::kAsyncInitCompleted); - } - - // If the application has enabled CHIPoBLE and BLE advertising... - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && - mFlags.Has(Flags::kAdvertisingEnabled) -#if CHIP_DEVICE_CONFIG_CHIPOBLE_SINGLE_CONNECTION - // and no connections are active... - && (NumConnections() == 0) -#endif - ) - { - // Start/re-start advertising if not already advertising, or if the - // advertising state needs to be refreshed. - if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kAdvertisingRefreshNeeded)) - { - mFlags.Clear(Flags::kAdvertisingRefreshNeeded); - err = StartAdvertising(); - SuccessOrExit(err); - } - } - else - { - if (mFlags.Has(Flags::kAdvertising)) - { - err = StopAdvertising(); - SuccessOrExit(err); - } - - // If no connections are active unregister also CHIPoBLE GATT service - if (NumConnections() == 0 && mFlags.Has(Flags::kChipoBleGattServiceRegister)) - { - // Unregister CHIPoBLE service to not allow discovering it when pairing is disabled. - if (bt_gatt_service_unregister(&sChipoBleService) != 0) - { - ChipLogError(DeviceLayer, "Failed to unregister CHIPoBLE GATT service"); - } - else - { - mFlags.Clear(Flags::kChipoBleGattServiceRegister); - } - } - } - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; - } -} - -struct BLEManagerImpl::ServiceData -{ - uint8_t uuid[2]; - ChipBLEDeviceIdentificationInfo deviceIdInfo; -} __attribute__((packed)); - -CHIP_ERROR BLEManagerImpl::StartAdvertising(void) -{ - int err = 0; - const bool isAdvertisingRerun = mFlags.Has(Flags::kAdvertising); - - // At first run always select fast advertising, on the next attempt slow down interval. - const uint32_t intervalMin = mFlags.Has(Flags::kFastAdvertisingEnabled) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN - : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MIN; - const uint32_t intervalMax = mFlags.Has(Flags::kFastAdvertisingEnabled) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX - : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX; - - bt_le_adv_param advParams; - advParams.id = BT_ID_DEFAULT; - advParams.options = BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME; - advParams.interval_min = intervalMin; - advParams.interval_max = intervalMax; - - // Define advertising and, if BLE device name is set, scan response data - ServiceData serviceData; - const uint8_t advFlags = BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR; - const bt_data advertisingData[] = { BT_DATA(BT_DATA_FLAGS, &advFlags, sizeof(advFlags)), - BT_DATA(BT_DATA_SVC_DATA16, &serviceData, sizeof(serviceData)) }; - - const char * deviceName = bt_get_name(); - const uint8_t deviceNameSize = static_cast(strlen(deviceName)); - const bt_data scanResponseData[] = { BT_DATA(BT_DATA_NAME_COMPLETE, deviceName, deviceNameSize) }; - const bt_data * scanResponseDataPtr = deviceNameSize > 0 ? scanResponseData : nullptr; - const size_t scanResponseDataLen = deviceNameSize > 0 ? sizeof(scanResponseData) / sizeof(scanResponseData[0]) : 0u; - - // Register dynamically CHIPoBLE GATT service - if (!mFlags.Has(Flags::kChipoBleGattServiceRegister)) - { - err = bt_gatt_service_register(&sChipoBleService); - - if (err != 0) - ChipLogError(DeviceLayer, "Failed to register CHIPoBLE GATT service"); - - VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - - mFlags.Set(Flags::kChipoBleGattServiceRegister); - } - - // Initialize service data - static_assert(sizeof(serviceData) == 10, "Size of BLE advertisement data changed! Was that intentional?"); - chip::Encoding::LittleEndian::Put16(serviceData.uuid, UUID16_CHIPoBLEService.val); - ReturnErrorOnFailure(ConfigurationMgr().GetBLEDeviceIdentificationInfo(serviceData.deviceIdInfo)); - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - ReturnErrorOnFailure(PrepareC3CharData()); -#endif - - if (!isAdvertisingRerun) - { -#if CONFIG_BT_PRIVACY - static_assert(CHIP_DEVICE_CONFIG_DISCOVERY_TIMEOUT_SECS <= CONFIG_BT_RPA_TIMEOUT, - "BLE advertising timeout is too long relative to RPA timeout"); - // Generate new private BLE address - bt_le_oob bleOobInfo; - err = bt_le_oob_get_local(advParams.id, &bleOobInfo); - VerifyOrReturnError(err == 0, MapErrorZephyr(err)); -#endif // CONFIG_BT_PRIVACY - } - - // Restart advertising - err = bt_le_adv_stop(); - VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - - err = bt_le_adv_start(&advParams, advertisingData, sizeof(advertisingData) / sizeof(advertisingData[0]), scanResponseDataPtr, - scanResponseDataLen); - VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - - // Transition to the Advertising state... - if (!mFlags.Has(Flags::kAdvertising)) - { - ChipLogProgress(DeviceLayer, "CHIPoBLE advertising started"); - - mFlags.Set(Flags::kAdvertising); - - // Post a CHIPoBLEAdvertisingChange(Started) event. - { - ChipDeviceEvent advChange; - advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; - advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Started; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&advChange)); - } - - if (mFlags.Has(Flags::kFastAdvertisingEnabled)) - { - // Start timer to change advertising interval. - DeviceLayer::SystemLayer().StartTimer( - System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME), - HandleBLEAdvertisementIntervalChange, this); - } - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::StopAdvertising(void) -{ - int err = bt_le_adv_stop(); - VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - - // Transition to the not Advertising state... - if (mFlags.Has(Flags::kAdvertising)) - { - mFlags.Clear(Flags::kAdvertising); - mFlags.Set(Flags::kFastAdvertisingEnabled, true); - - ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped"); - - // Post a CHIPoBLEAdvertisingChange(Stopped) event. - { - ChipDeviceEvent advChange; - advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; - advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Stopped; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&advChange)); - } - - // Cancel timer event changing CHIPoBLE advertisement interval - DeviceLayer::SystemLayer().CancelTimer(HandleBLEAdvertisementIntervalChange, this); - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) -{ - VerifyOrReturnError(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, - CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - - if (mFlags.Has(Flags::kAdvertisingEnabled) != val) - { - ChipLogDetail(DeviceLayer, "CHIPoBLE advertising set to %s", val ? "on" : "off"); - - mFlags.Set(Flags::kAdvertisingEnabled, val); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode) -{ - switch (mode) - { - case BLEAdvertisingMode::kFastAdvertising: - mFlags.Set(Flags::kFastAdvertisingEnabled, true); - break; - case BLEAdvertisingMode::kSlowAdvertising: - mFlags.Set(Flags::kFastAdvertisingEnabled, false); - break; - default: - return CHIP_ERROR_INVALID_ARGUMENT; - } - mFlags.Set(Flags::kAdvertisingRefreshNeeded); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) -{ - Platform::CopyString(buf, bufSize, bt_get_name()); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) -{ - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported) - { - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; - } - - ChipLogDetail(DeviceLayer, "Device name set to: %s", deviceName); - return MapErrorZephyr(bt_set_name(deviceName)); -} - -CHIP_ERROR BLEManagerImpl::HandleGAPConnect(const ChipDeviceEvent * event) -{ - const BleConnEventType * connEvent = &event->Platform.BleConnEvent; - - if (connEvent->HciResult == BT_HCI_ERR_SUCCESS) - { - ChipLogProgress(DeviceLayer, "BLE connection established (ConnId: 0x%02x)", bt_conn_index(connEvent->BtConn)); - mGAPConns++; - } - else - { - ChipLogError(DeviceLayer, "BLE connection failed (reason: 0x%02x)", connEvent->HciResult); - } - - ChipLogProgress(DeviceLayer, "Current number of connections: %u/%u", NumConnections(), CONFIG_BT_MAX_CONN); - - mFlags.Set(Flags::kAdvertisingRefreshNeeded); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - - bt_conn_unref(connEvent->BtConn); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::HandleGAPDisconnect(const ChipDeviceEvent * event) -{ - const BleConnEventType * connEvent = &event->Platform.BleConnEvent; - - ChipLogProgress(DeviceLayer, "BLE GAP connection terminated (reason 0x%02x)", connEvent->HciResult); - - mGAPConns--; - - // If indications were enabled for this connection, record that they are now disabled and - // notify the BLE Layer of a disconnect. - if (UnsetSubscribed(connEvent->BtConn)) - { - CHIP_ERROR disconReason; - switch (connEvent->HciResult) - { - case BT_HCI_ERR_REMOTE_USER_TERM_CONN: - // Do not treat proper connection termination as an error and exit. - VerifyOrExit(!ConfigurationMgr().IsFullyProvisioned(), ); - disconReason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; - break; - case BT_HCI_ERR_LOCALHOST_TERM_CONN: - disconReason = BLE_ERROR_APP_CLOSED_CONNECTION; - break; - default: - disconReason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT; - break; - } - HandleConnectionError(connEvent->BtConn, disconReason); - } - -exit: - // Unref bt_conn before scheduling DriveBLEState. - bt_conn_unref(connEvent->BtConn); - - ChipLogProgress(DeviceLayer, "Current number of connections: %u/%u", NumConnections(), CONFIG_BT_MAX_CONN); - - ChipDeviceEvent disconnectEvent; - disconnectEvent.Type = DeviceEventType::kCHIPoBLEConnectionClosed; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&disconnectEvent)); - - // Force a reconfiguration of advertising in case we switched to non-connectable mode when - // the BLE connection was established. - mFlags.Set(Flags::kAdvertisingRefreshNeeded); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::HandleTXCharCCCDWrite(const ChipDeviceEvent * event) -{ - const BleCCCWriteEventType * writeEvent = &event->Platform.BleCCCWriteEvent; - - ChipLogDetail(DeviceLayer, "ConnId: 0x%02x, New CCCD value: 0x%04x", bt_conn_index(writeEvent->BtConn), writeEvent->Value); - - // If the client has requested to enable indications and if it is not yet subscribed - if (writeEvent->Value == BT_GATT_CCC_INDICATE && SetSubscribed(writeEvent->BtConn)) - { - // Alert the BLE layer that CHIPoBLE "subscribe" has been received and increment the bt_conn reference counter. - HandleSubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); - - ChipLogProgress(DeviceLayer, "CHIPoBLE connection established (ConnId: 0x%02x, GATT MTU: %u)", - bt_conn_index(writeEvent->BtConn), GetMTU(writeEvent->BtConn)); - - // Post a CHIPoBLEConnectionEstablished event to the DeviceLayer and the application. - { - ChipDeviceEvent conEstEvent; - conEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&conEstEvent)); - } - } - else - { - if (UnsetSubscribed(writeEvent->BtConn)) - { - HandleUnsubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); - } - } - - bt_conn_unref(writeEvent->BtConn); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::HandleRXCharWrite(const ChipDeviceEvent * event) -{ - const BleC1WriteEventType * c1WriteEvent = &event->Platform.BleC1WriteEvent; - - ChipLogDetail(DeviceLayer, "Write request received for CHIPoBLE RX characteristic (ConnId 0x%02x)", - bt_conn_index(c1WriteEvent->BtConn)); - - HandleWriteReceived(c1WriteEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, - PacketBufferHandle::Adopt(c1WriteEvent->Data)); - bt_conn_unref(c1WriteEvent->BtConn); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::HandleTXCharComplete(const ChipDeviceEvent * event) -{ - const BleC2IndDoneEventType * c2IndDoneEvent = &event->Platform.BleC2IndDoneEvent; - - ChipLogDetail(DeviceLayer, "Indication for CHIPoBLE TX characteristic done (ConnId 0x%02x, result 0x%02x)", - bt_conn_index(c2IndDoneEvent->BtConn), c2IndDoneEvent->Result); - - // Signal the BLE Layer that the outstanding indication is complete. - HandleIndicationConfirmation(c2IndDoneEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); - bt_conn_unref(c2IndDoneEvent->BtConn); - - return CHIP_NO_ERROR; -} - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -CHIP_ERROR BLEManagerImpl::PrepareC3CharData() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - BitFlags additionalDataFields; - AdditionalDataPayloadGeneratorParams additionalDataPayloadParams; - -#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) - uint8_t rotatingDeviceIdUniqueId[ConfigurationManager::kRotatingDeviceIDUniqueIDLength] = {}; - MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId); - - err = DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan); - SuccessOrExit(err); - err = ConfigurationMgr().GetLifetimeCounter(additionalDataPayloadParams.rotatingDeviceIdLifetimeCounter); - SuccessOrExit(err); - additionalDataPayloadParams.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan; - additionalDataFields.Set(AdditionalDataFields::RotatingDeviceId); -#endif /* CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) */ - - err = AdditionalDataPayloadGenerator().generateAdditionalDataPayload(additionalDataPayloadParams, c3CharDataBufferHandle, - additionalDataFields); - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Failed to generate TLV encoded Additional Data (%s)", __func__); - } - - return err; -} -#endif - -void BLEManagerImpl::HandleBLEAdvertisementIntervalChange(System::Layer * layer, void * param) -{ - BLEMgr().SetAdvertisingMode(BLEAdvertisingMode::kSlowAdvertising); - ChipLogProgress(DeviceLayer, "CHIPoBLE advertising mode changed to slow"); -} - -void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - switch (event->Type) - { - case DeviceEventType::kPlatformZephyrBleConnected: - err = HandleGAPConnect(event); - break; - - case DeviceEventType::kPlatformZephyrBleDisconnected: - err = HandleGAPDisconnect(event); - break; - - case DeviceEventType::kPlatformZephyrBleCCCWrite: - err = HandleTXCharCCCDWrite(event); - break; - - case DeviceEventType::kPlatformZephyrBleC1WriteEvent: - err = HandleRXCharWrite(event); - break; - - case DeviceEventType::kPlatformZephyrBleC2IndDoneEvent: - err = HandleTXCharComplete(event); - break; - - default: - break; - } - - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %" CHIP_ERROR_FORMAT, err.Format()); - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; - PlatformMgr().ScheduleWork(DriveBLEState, 0); - } -} - -uint16_t BLEManagerImpl::_NumConnections(void) -{ - return mGAPConns; -} - -bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) -{ - ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (ConnId %02x)", bt_conn_index((bt_conn *) conId)); - return bt_conn_disconnect((bt_conn *) conId, BT_HCI_ERR_REMOTE_USER_TERM_CONN) == 0; -} - -uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const -{ - return bt_gatt_get_mtu((bt_conn *) conId); -} - -bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) -{ - ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); - return true; -} - -bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) -{ - ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); - return true; -} - -bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - int status = 0; - uint8_t index = bt_conn_index(conId); - bt_gatt_indicate_params * params = &mIndicateParams[index]; - - VerifyOrExit(IsSubscribed(conId) == true, err = CHIP_ERROR_INVALID_ARGUMENT); - - ChipLogDetail(DeviceLayer, "Sending indication for CHIPoBLE TX characteristic (ConnId %02x, len %u)", index, - pBuf->DataLength()); - - params->uuid = nullptr; - params->attr = &sChipoBleAttributes[kCHIPoBLE_CCC_AttributeIndex]; - params->func = HandleTXIndicated; - params->data = pBuf->Start(); - params->len = pBuf->DataLength(); - - status = bt_gatt_indicate(conId, params); - VerifyOrExit(status == 0, err = MapErrorZephyr(status)); - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %." CHIP_ERROR_FORMAT, err.Format()); - ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %d", status); - } - - return err == CHIP_NO_ERROR; -} - -bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf) -{ - ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); - return true; -} - -bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf) -{ - ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); - return true; -} - -bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, - const ChipBleUUID * svcId, const ChipBleUUID * charId) -{ - ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); - return true; -} - -void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) -{ - CloseConnection(conId); -} - -bool BLEManagerImpl::IsSubscribed(bt_conn * conn) -{ - return mSubscribedConns[bt_conn_index(conn)]; -} - -bool BLEManagerImpl::SetSubscribed(bt_conn * conn) -{ - uint8_t index = bt_conn_index(conn); - bool isSubscribed = mSubscribedConns[index]; - mSubscribedConns[index] = true; - - // If we were not subscribed previously, increment the reference counter of the connection. - if (!isSubscribed) - { - bt_conn_ref(conn); - } - - return !isSubscribed; -} - -bool BLEManagerImpl::UnsetSubscribed(bt_conn * conn) -{ - uint8_t index = bt_conn_index(conn); - bool isSubscribed = mSubscribedConns[index]; - mSubscribedConns[index] = false; - - // If we were subscribed previously, decrement the reference counter of the connection. - if (isSubscribed) - { - bt_conn_unref(conn); - } - - return isSubscribed; -} - -ssize_t BLEManagerImpl::HandleRXWrite(struct bt_conn * conId, const struct bt_gatt_attr * attr, const void * buf, uint16_t len, - uint16_t offset, uint8_t flags) -{ - ChipDeviceEvent event; - PacketBufferHandle packetBuf = PacketBufferHandle::NewWithData(buf, len); - - if (!packetBuf.IsNull()) - { - // Arrange to post a CHIPoBLERXWriteEvent event to the CHIP queue. - event.Type = DeviceEventType::kPlatformZephyrBleC1WriteEvent; - event.Platform.BleC1WriteEvent.BtConn = bt_conn_ref(conId); - event.Platform.BleC1WriteEvent.Data = std::move(packetBuf).UnsafeRelease(); - } - - // If we failed to allocate a buffer, post a kPlatformZephyrBleOutOfBuffersEvent event. - else - { - event.Type = DeviceEventType::kPlatformZephyrBleOutOfBuffersEvent; - } - - PlatformMgr().PostEventOrDie(&event); - - return len; -} - -bool BLEManagerImpl::HandleTXCCCWrite(struct bt_conn * conId, const struct bt_gatt_attr * attr, uint16_t value) -{ - ChipDeviceEvent event; - - if (value != BT_GATT_CCC_INDICATE && value != 0) - { - return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED); - } - - event.Type = DeviceEventType::kPlatformZephyrBleCCCWrite; - event.Platform.BleCCCWriteEvent.BtConn = bt_conn_ref(conId); - event.Platform.BleCCCWriteEvent.Value = value; - - PlatformMgr().PostEventOrDie(&event); - - return sizeof(value); -} - -void BLEManagerImpl::HandleTXIndicated(struct bt_conn * conId, IndicationAttrType, uint8_t err) -{ - ChipDeviceEvent event; - - event.Type = DeviceEventType::kPlatformZephyrBleC2IndDoneEvent; - event.Platform.BleC2IndDoneEvent.BtConn = bt_conn_ref(conId); - event.Platform.BleC2IndDoneEvent.Result = err; - - PlatformMgr().PostEventOrDie(&event); -} - -void BLEManagerImpl::HandleConnect(struct bt_conn * conId, uint8_t err) -{ - ChipDeviceEvent event; - - PlatformMgr().LockChipStack(); - - // Don't handle BLE connecting events when it is not related to CHIPoBLE - VerifyOrExit(sInstance.mFlags.Has(Flags::kChipoBleGattServiceRegister), ); - - event.Type = DeviceEventType::kPlatformZephyrBleConnected; - event.Platform.BleConnEvent.BtConn = bt_conn_ref(conId); - event.Platform.BleConnEvent.HciResult = err; - - PlatformMgr().PostEventOrDie(&event); - -exit: - PlatformMgr().UnlockChipStack(); -} - -void BLEManagerImpl::HandleDisconnect(struct bt_conn * conId, uint8_t reason) -{ - ChipDeviceEvent event; - - PlatformMgr().LockChipStack(); - - // Don't handle BLE disconnecting events when it is not related to CHIPoBLE - VerifyOrExit(sInstance.mFlags.Has(Flags::kChipoBleGattServiceRegister), ); - - event.Type = DeviceEventType::kPlatformZephyrBleDisconnected; - event.Platform.BleConnEvent.BtConn = bt_conn_ref(conId); - event.Platform.BleConnEvent.HciResult = reason; - - PlatformMgr().PostEventOrDie(&event); - -exit: - PlatformMgr().UnlockChipStack(); -} - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -ssize_t BLEManagerImpl::HandleC3Read(struct bt_conn * conId, const struct bt_gatt_attr * attr, void * buf, uint16_t len, - uint16_t offset) -{ - ChipLogDetail(DeviceLayer, "Read request received for CHIPoBLE C3 (ConnId 0x%02x)", bt_conn_index(conId)); - - if (sInstance.c3CharDataBufferHandle.IsNull()) - { - return 0; - } - - return bt_gatt_attr_read(conId, attr, buf, len, offset, sInstance.c3CharDataBufferHandle->Start(), - sInstance.c3CharDataBufferHandle->DataLength()); -} -#endif - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/bouffalolab/BL702/BLEManagerImpl.h b/src/platform/bouffalolab/BL702/BLEManagerImpl.h deleted file mode 100644 index 0f9ff7666a1c1e..00000000000000 --- a/src/platform/bouffalolab/BL702/BLEManagerImpl.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - -#include -#include -#include - -#include - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -using namespace chip::Ble; - -/** - * Concrete implementation of the BLEManager singleton object for the BL702 platform. - */ -class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePlatformDelegate, private BleApplicationDelegate -{ - // Allow the BLEManager interface class to delegate method calls to - // the implementation methods provided by this class. - friend BLEManager; - -private: - // ===== Members that implement the BLEManager internal interface. - using IndicationAttrType = - std::conditional_t::value, - bt_gatt_indicate_params *, const bt_gatt_attr *>; - CHIP_ERROR _Init(void); - void _Shutdown() {} - bool _IsAdvertisingEnabled(void); - CHIP_ERROR _SetAdvertisingEnabled(bool val); - bool _IsAdvertising(void); - CHIP_ERROR _SetAdvertisingMode(BLEAdvertisingMode mode); - CHIP_ERROR _GetDeviceName(char * buf, size_t bufSize); - CHIP_ERROR _SetDeviceName(const char * deviceName); - uint16_t _NumConnections(void); - void _OnPlatformEvent(const ChipDeviceEvent * event); - BleLayer * _GetBleLayer(void); - - // ===== Members that implement virtual methods on BlePlatformDelegate. - - bool SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId); - bool UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId); - bool CloseConnection(BLE_CONNECTION_OBJECT conId); - uint16_t GetMTU(BLE_CONNECTION_OBJECT conId) const; - bool SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf); - bool SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf); - bool SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf); - bool SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const ChipBleUUID * svcId, - const ChipBleUUID * charId); - - // ===== Members that implement virtual methods on BleApplicationDelegate. - - void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId); - - // ===== Private members reserved for use by this class only. - - enum class Flags : uint8_t - { - kAsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ - kAdvertisingEnabled = 0x0002, /**< The application has enabled CHIPoBLE advertising. */ - kFastAdvertisingEnabled = 0x0004, /**< The application has enabled fast advertising. */ - kAdvertising = 0x0008, /**< The system is currently CHIPoBLE advertising. */ - kAdvertisingRefreshNeeded = - 0x0010, /**< The advertising state/configuration has changed, but the SoftDevice has yet to be updated. */ - kChipoBleGattServiceRegister = 0x0020, /**< The system has currently CHIPoBLE GATT service registered. */ - }; - - struct ServiceData; - - BitFlags mFlags; - uint16_t mGAPConns; - CHIPoBLEServiceMode mServiceMode; - bool mSubscribedConns[CONFIG_BT_MAX_CONN]; - bt_gatt_indicate_params mIndicateParams[CONFIG_BT_MAX_CONN]; - bt_conn_cb mConnCallbacks; -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - PacketBufferHandle c3CharDataBufferHandle; -#endif - - void DriveBLEState(void); - CHIP_ERROR ConfigureAdvertising(void); - CHIP_ERROR StartAdvertising(void); - CHIP_ERROR StopAdvertising(void); - CHIP_ERROR HandleGAPConnect(const ChipDeviceEvent * event); - CHIP_ERROR HandleGAPDisconnect(const ChipDeviceEvent * event); - CHIP_ERROR HandleRXCharWrite(const ChipDeviceEvent * event); - CHIP_ERROR HandleTXCharCCCDWrite(const ChipDeviceEvent * event); - CHIP_ERROR HandleTXCharComplete(const ChipDeviceEvent * event); -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - CHIP_ERROR PrepareC3CharData(); -#endif - bool IsSubscribed(bt_conn * conn); - bool SetSubscribed(bt_conn * conn); - bool UnsetSubscribed(bt_conn * conn); - uint32_t GetAdvertisingInterval(); - - static void DriveBLEState(intptr_t arg); - - // Below callbacks run from the system workqueue context and have a limited stack capacity. - static void HandleTXIndicated(bt_conn * conn, IndicationAttrType attr, uint8_t err); - static void HandleConnect(bt_conn * conn, uint8_t err); - static void HandleDisconnect(bt_conn * conn, uint8_t reason); - static void HandleBLEAdvertisementIntervalChange(System::Layer * layer, void * param); - - // ===== Members for internal use by the following friends. - - friend BLEManager & BLEMgr(void); - friend BLEManagerImpl & BLEMgrImpl(void); - - static BLEManagerImpl sInstance; - -public: - // Below callbacks are public in order to be visible from the global scope. - static ssize_t HandleRXWrite(bt_conn * conn, const bt_gatt_attr * attr, const void * buf, uint16_t len, uint16_t offset, - uint8_t flags); - static bool HandleTXCCCWrite(bt_conn * conn, const bt_gatt_attr * attr, uint16_t value); - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - static ssize_t HandleC3Read(struct bt_conn * conn, const struct bt_gatt_attr * attr, void * buf, uint16_t len, uint16_t offset); -#endif -}; - -/** - * Returns a reference to the public interface of the BLEManager singleton object. - * - * Internal components should use this to access features of the BLEManager object - * that are common to all platforms. - */ -inline BLEManager & BLEMgr(void) -{ - return BLEManagerImpl::sInstance; -} - -/** - * Returns the platform-specific implementation of the BLEManager singleton object. - * - * Internal components can use this to gain access to features of the BLEManager - * that are specific to the BL702 platform. - */ -inline BLEManagerImpl & BLEMgrImpl(void) -{ - return BLEManagerImpl::sInstance; -} - -inline BleLayer * BLEManagerImpl::_GetBleLayer() -{ - return this; -} - -inline bool BLEManagerImpl::_IsAdvertisingEnabled(void) -{ - return mFlags.Has(Flags::kAdvertisingEnabled); -} - -inline bool BLEManagerImpl::_IsAdvertising(void) -{ - return mFlags.Has(Flags::kAdvertising); -} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/bouffalolab/BL702/BUILD.gn b/src/platform/bouffalolab/BL702/BUILD.gn index ae941605978012..dd0279175bfd50 100644 --- a/src/platform/bouffalolab/BL702/BUILD.gn +++ b/src/platform/bouffalolab/BL702/BUILD.gn @@ -25,60 +25,53 @@ if (chip_enable_openthread) { static_library("BL702") { sources = [ - "../../FreeRTOS/SystemTimeSupport.cpp", - "../../SingletonConfigurationManager.cpp", - "CHIPDevicePlatformConfig.h", - "CHIPDevicePlatformEvent.h", - "CHIPmemory.cpp", - "ConfigurationManagerImpl.cpp", - "ConfigurationManagerImpl.h", - "ConnectivityManagerImpl.cpp", - "ConnectivityManagerImpl.h", "DiagnosticDataProviderImpl.cpp", - "DiagnosticDataProviderImpl.h", - "InetPlatformConfig.h", - "KeyValueStoreManagerImpl.cpp", - "KeyValueStoreManagerImpl.h", - "Logging.cpp", "PlatformManagerImpl.cpp", - "PlatformManagerImpl.h", - "SystemPlatformConfig.h", - "bl702Config.cpp", - "bl702Config.h", ] - deps = [] + common_sources = [ + "../../FreeRTOS/SystemTimeSupport.cpp", + "../../SingletonConfigurationManager.cpp", + "../common/BLConfig.cpp", + "../common/ConfigurationManagerImpl.cpp", + "../common/ConnectivityManagerImpl.cpp", + "../common/DiagnosticDataProviderImpl.cpp", + "../common/KeyValueStoreManagerImpl.cpp", + "../common/Logging.cpp", + "../common/PlatformManagerImpl.cpp", + + # "${chip_root}/src/credentials/CHIPCert.h", + # "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", - public_deps = [ - "${chip_root}/src/crypto", - "${chip_root}/src/platform:platform_base", + # "../common/FactoryDataProvider.cpp", + # "../common/FactoryDataProvider.h", ] if (chip_enable_ota_requestor) { sources += [ - "OTAImageProcessorImpl.cpp", - "OTAImageProcessorImpl.h", + "../common/OTAImageProcessorImpl.cpp", + "../common/OTAImageProcessorImpl.h", ] } if (chip_enable_ble) { sources += [ - "BLEManagerImpl.cpp", - "BLEManagerImpl.h", + "../common/BLEManagerImpl.cpp", + "../common/BLEManagerImpl.h", ] } + sources += common_sources if (chip_enable_openthread) { # needed for MTD/FTD import("//build_overrides/bouffalolab_iot_sdk.gni") import("${bouffalolab_iot_sdk_build_root}/bl702/bl_iot_sdk.gni") - public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl702:bl_iot_sdk" ] + deps = [ "${bouffalolab_iot_sdk_build_root}/bl702:bl_iot_sdk" ] sources += [ "../../OpenThread/OpenThreadUtils.cpp", "ThreadStackManagerImpl.cpp", - "ThreadStackManagerImpl.h", ] if (chip_mdns == "platform") { @@ -90,4 +83,6 @@ static_library("BL702") { deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] } } + + public_deps = [ "${chip_root}/src/platform:platform_base" ] } diff --git a/src/platform/bouffalolab/BL702/CHIPPlatformConfig.h b/src/platform/bouffalolab/BL702/CHIPPlatformConfig.h deleted file mode 100644 index b5815d686157b8..00000000000000 --- a/src/platform/bouffalolab/BL702/CHIPPlatformConfig.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -// ==================== General Platform Adaptations ==================== - -#define ChipDie() assert() - -#define CHIP_CONFIG_PERSISTED_STORAGE_KEY_TYPE uint16_t -#define CHIP_CONFIG_PERSISTED_STORAGE_ENC_MSG_CNTR_ID 1 -#define CHIP_CONFIG_PERSISTED_STORAGE_MAX_KEY_LENGTH 2 - -#define CHIP_CONFIG_LIFETIIME_PERSISTED_COUNTER_KEY 0x01 -#define CHIP_CONFIG_PERSISTED_STORAGE_KEY_GLOBAL_MESSAGE_COUNTER 0x2 - -// ==================== Security Adaptations ==================== - -// This platform uses mbedtls, but these defines don't seem to be used in source -#define CHIP_CONFIG_USE_OPENSSL_ECC 0 -#define CHIP_CONFIG_USE_MICRO_ECC 1 - -#define CHIP_CONFIG_HASH_IMPLEMENTATION_OPENSSL 0 -#define CHIP_CONFIG_HASH_IMPLEMENTATION_MINCRYPT 0 -#define CHIP_CONFIG_HASH_IMPLEMENTATION_MBEDTLS 1 -#define CHIP_CONFIG_HASH_IMPLEMENTATION_PLATFORM 0 - -//#define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(bl_sha_ctx_t) -#define CHIP_CONFIG_SHA256_CONTEXT_SIZE ((1 + 5 + 18 + 16 + 16) * sizeof(unsigned int)) - -#define CHIP_CONFIG_AES_IMPLEMENTATION_OPENSSL 0 -#define CHIP_CONFIG_AES_IMPLEMENTATION_AESNI 0 -#define CHIP_CONFIG_AES_IMPLEMENTATION_MBEDTLS 1 -#define CHIP_CONFIG_AES_IMPLEMENTATION_PLATFORM 0 - -#define CHIP_CONFIG_RNG_IMPLEMENTATION_OPENSSL 0 -#define CHIP_CONFIG_RNG_IMPLEMENTATION_CHIPDRBG 1 -#define CHIP_CONFIG_RNG_IMPLEMENTATION_PLATFORM 0 - -#define CHIP_CONFIG_ENABLE_PASE_INITIATOR 0 -#define CHIP_CONFIG_ENABLE_PASE_RESPONDER 1 -#define CHIP_CONFIG_ENABLE_CASE_INITIATOR 1 - -#define CHIP_CONFIG_SUPPORT_PASE_CONFIG0 0 -#define CHIP_CONFIG_SUPPORT_PASE_CONFIG1 0 -#define CHIP_CONFIG_SUPPORT_PASE_CONFIG2 0 -#define CHIP_CONFIG_SUPPORT_PASE_CONFIG3 0 -#define CHIP_CONFIG_SUPPORT_PASE_CONFIG4 1 - -#define CHIP_CONFIG_ENABLE_KEY_EXPORT_INITIATOR 0 - -#define CHIP_CONFIG_ENABLE_PROVISIONING_BUNDLE_SUPPORT 0 - -// ==================== General Configuration Overrides ==================== - -#ifndef CHIP_CONFIG_MAX_PEER_NODES -#define CHIP_CONFIG_MAX_PEER_NODES 16 -#endif // CHIP_CONFIG_MAX_PEER_NODES - -#ifndef CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS -#define CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS 8 -#endif // CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS - -#ifndef CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS -#define CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS 8 -#endif // CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS - -#ifndef CHIP_CONFIG_MAX_ACTIVE_CHANNELS -#define CHIP_CONFIG_MAX_ACTIVE_CHANNELS 8 -#endif // CHIP_CONFIG_MAX_ACTIVE_CHANNELS - -#ifndef CHIP_CONFIG_MAX_CHANNEL_HANDLES -#define CHIP_CONFIG_MAX_CHANNEL_HANDLES 16 -#endif // CHIP_CONFIG_MAX_CHANNEL_HANDLES - -#ifndef CHIP_CONFIG_RMP_TIMER_DEFAULT_PERIOD_SHIFT -#define CHIP_CONFIG_RMP_TIMER_DEFAULT_PERIOD_SHIFT 6 -#endif // CHIP_CONFIG_RMP_TIMER_DEFAULT_PERIOD_SHIFT - -#ifndef CHIP_LOG_FILTERING -#define CHIP_LOG_FILTERING 0 -#endif // CHIP_LOG_FILTERING - -#ifndef CHIP_CONFIG_MAX_INTERFACES -#define CHIP_CONFIG_MAX_INTERFACES 4 -#endif // CHIP_CONFIG_MAX_INTERFACES - -#ifndef CHIP_CONFIG_MAX_LOCAL_ADDR_UDP_ENDPOINTS -#define CHIP_CONFIG_MAX_LOCAL_ADDR_UDP_ENDPOINTS 4 -#endif // CHIP_CONFIG_MAX_LOCAL_ADDR_UDP_ENDPOINTS - -#ifndef CHIP_CONFIG_MAX_FABRICS -#define CHIP_CONFIG_MAX_FABRICS 5 -#endif - -// ==================== Security Configuration Overrides ==================== - -#ifndef CHIP_CONFIG_MAX_APPLICATION_GROUPS -#define CHIP_CONFIG_MAX_APPLICATION_GROUPS 4 -#endif // CHIP_CONFIG_MAX_APPLICATION_GROUPS - -#ifndef CHIP_CONFIG_DEBUG_CERT_VALIDATION -#define CHIP_CONFIG_DEBUG_CERT_VALIDATION 0 -#endif // CHIP_CONFIG_DEBUG_CERT_VALIDATION - -#ifndef CHIP_CONFIG_ENABLE_CASE_RESPONDER -#define CHIP_CONFIG_ENABLE_CASE_RESPONDER 1 -#endif // CHIP_CONFIG_ENABLE_CASE_RESPONDER - -#ifndef CHIP_CONFIG_FREERTOS_USE_STATIC_TASK -#define CHIP_CONFIG_FREERTOS_USE_STATIC_TASK 1 -#endif - -#ifndef CHIP_CONFIG_FREERTOS_USE_STATIC_QUEUE -#define CHIP_CONFIG_FREERTOS_USE_STATIC_QUEUE 1 -#endif diff --git a/src/platform/bouffalolab/BL702/CHIPmemory.cpp b/src/platform/bouffalolab/BL702/CHIPmemory.cpp deleted file mode 100644 index 5438016ad53d0f..00000000000000 --- a/src/platform/bouffalolab/BL702/CHIPmemory.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include - -#ifndef NDEBUG -#include -#include -#endif - -#if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC -#include -#include -#endif // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC - -#if CHIP_CONFIG_MEMORY_MGMT_PLATFORM - -#include "FreeRTOS.h" -#include "task.h" - -namespace chip { -namespace Platform { - -#ifdef NDEBUG - -#define VERIFY_INITIALIZED() -#define VERIFY_POINTER(p) - -#else - -#define VERIFY_INITIALIZED() VerifyInitialized(__func__) - -static std::atomic_int memoryInitialized{ 0 }; - -static void VerifyInitialized(const char * func) -{ - if (!memoryInitialized) - { - fprintf(stderr, "ABORT: chip::Platform::%s() called before chip::Platform::MemoryInit()\n", func); - abort(); - } -} - -#define VERIFY_POINTER(p) \ - do \ - if (((p) != nullptr) && (MemoryDebugCheckPointer((p)) == false)) \ - { \ - fprintf(stderr, "ABORT: chip::Platform::%s() found corruption on %p\n", __func__, (p)); \ - abort(); \ - } \ - while (0) - -#endif - -CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize) -{ -#ifndef NDEBUG - if (memoryInitialized++ > 0) - { - fprintf(stderr, "ABORT: chip::Platform::MemoryInit() called twice.\n"); - abort(); - } -#endif - - return CHIP_NO_ERROR; -} - -void MemoryAllocatorShutdown() -{ -#ifndef NDEBUG - if (--memoryInitialized < 0) - { - fprintf(stderr, "ABORT: chip::Platform::MemoryShutdown() called twice.\n"); - abort(); - } -#endif -#if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC - dmalloc_shutdown(); -#endif // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC -} - -void * MemoryAlloc(size_t size) -{ - VERIFY_INITIALIZED(); - - return malloc(size); -} - -void * MemoryCalloc(size_t num, size_t size) -{ - VERIFY_INITIALIZED(); - - return pvPortCallocPsram(num, size); -} - -void * MemoryRealloc(void * p, size_t size) -{ - VERIFY_INITIALIZED(); - VERIFY_POINTER(p); - - return realloc(p, size); -} - -void MemoryFree(void * p) -{ - VERIFY_INITIALIZED(); - VERIFY_POINTER(p); - - free(p); -} - -bool MemoryInternalCheckPointer(const void * p, size_t min_size) -{ -#if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC - return CanCastTo(min_size) && (p != nullptr) && - (dmalloc_verify_pnt(__FILE__, __LINE__, __func__, p, 1, static_cast(min_size)) == MALLOC_VERIFY_NOERROR); -#else // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC - return (p != nullptr); -#endif // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC -} - -} // namespace Platform -} // namespace chip - -#endif // CHIP_CONFIG_MEMORY_MGMT_MALLOC diff --git a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.h b/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.h deleted file mode 100644 index 06774161b8c3f2..00000000000000 --- a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include -#if INET_CONFIG_ENABLE_TCP_ENDPOINT -#include -#endif -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include -#else -#include -#endif -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include -#else -#include -#endif -#include - -namespace chip { -namespace DeviceLayer { - -/** - * Concrete implementation of the ConnectivityManager singleton object for the CC13X2_26X2 platforms. - */ -class ConnectivityManagerImpl final : public ConnectivityManager, - public Internal::GenericConnectivityManagerImpl, - public Internal::GenericConnectivityManagerImpl_UDP, -#if INET_CONFIG_ENABLE_TCP_ENDPOINT - public Internal::GenericConnectivityManagerImpl_TCP, -#endif -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - public Internal::GenericConnectivityManagerImpl_BLE, -#else - public Internal::GenericConnectivityManagerImpl_NoBLE, -#endif -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD - public Internal::GenericConnectivityManagerImpl_Thread, -#else - public Internal::GenericConnectivityManagerImpl_NoThread, -#endif - public Internal::GenericConnectivityManagerImpl_NoWiFi -{ - // Allow the ConnectivityManager interface class to delegate method calls to - // the implementation methods provided by this class. - friend class ConnectivityManager; - -#if CHIP_DEVICE_CONFIG_ENABLE_WIFI -public: - static WiFiStationState mWiFiStationState; - static void GetWiFiMacAddress(uint8_t *); -#endif - -private: - // ===== Members that implement the ConnectivityManager abstract interface. - -#if CHIP_DEVICE_CONFIG_ENABLE_WIFI - bool _IsWiFiStationConnected(void); - bool _IsWiFiStationEnabled(void); - ConnectivityManager::WiFiStationMode _GetWiFiStationMode(void); - - friend void DriveState(int arg); - void NetworkChanged(void); - bool _IsWiFiStationProvisioned(void); - void _ClearWiFiStationProvision(void); -#endif - - CHIP_ERROR _Init(void); - void _OnPlatformEvent(const ChipDeviceEvent * event); - - // ===== Members for internal use by the following friends. - - friend ConnectivityManager & ConnectivityMgr(void); - friend ConnectivityManagerImpl & ConnectivityMgrImpl(void); - - static ConnectivityManagerImpl sInstance; -}; - -/** - * Returns the public interface of the ConnectivityManager singleton object. - * - * chip applications should use this to access features of the ConnectivityManager object - * that are common to all platforms. - */ -inline ConnectivityManager & ConnectivityMgr(void) -{ - return ConnectivityManagerImpl::sInstance; -} - -/** - * Returns the platform-specific implementation of the ConnectivityManager singleton object. - * - * chip applications can use this to gain access to features of the ConnectivityManager - * that are specific to the BL702 platform - */ -inline ConnectivityManagerImpl & ConnectivityMgrImpl(void) -{ - return ConnectivityManagerImpl::sInstance; -} - -#if CHIP_DEVICE_CONFIG_ENABLE_WIFI -inline bool ConnectivityManagerImpl::_IsWiFiStationConnected(void) -{ - return mWiFiStationState == kWiFiStationState_Connected; -} - -inline bool ConnectivityManagerImpl::_IsWiFiStationEnabled(void) -{ - return true; -} - -inline ConnectivityManager::WiFiStationMode ConnectivityManagerImpl::_GetWiFiStationMode(void) -{ - return kWiFiStationMode_Enabled; -} - -#endif - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp index acdf61e27caa26..62fe129c0a9685 100644 --- a/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp +++ b/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp @@ -15,229 +15,40 @@ * limitations under the License. */ -#include -#include - #include -#include - -#include - -#include - -using namespace ::chip::app::Clusters::GeneralDiagnostics; +#include +#include +extern "C" { +#include +} namespace chip { namespace DeviceLayer { -extern "C" size_t get_heap_size(void); -extern "C" size_t get_heap3_size(void); - -DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() -{ - static DiagnosticDataProviderImpl sInstance; - return sInstance; -} - -/* - * The following Heap stats are compiled values done by the FreeRTOS Heap5 implementation. - * It keeps track of the number of calls to allocate and free memory as well as the - * number of free bytes remaining, but says nothing about fragmentation. - */ -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) -{ - /** for BL706 with PSRAM, just get SRAM heap size which is more critical for firmware execution **/ - -#ifdef CFG_USE_PSRAM - size_t freeHeapSize = xPortGetFreeHeapSize() + xPortGetFreeHeapSizePsram(); -#else - size_t freeHeapSize = xPortGetFreeHeapSize(); -#endif - currentHeapFree = static_cast(freeHeapSize); - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) -{ - // Calculate the Heap used based on Total heap - Free heap - -#ifdef CFG_USE_PSRAM - int64_t heapUsed = (get_heap_size() + get_heap3_size() - xPortGetFreeHeapSize() - xPortGetFreeHeapSizePsram()); -#else - size_t freeHeapSize = xPortGetFreeHeapSize(); -#endif - - // Something went wrong, this should not happen - VerifyOrReturnError(heapUsed >= 0, CHIP_ERROR_INVALID_INTEGER_VALUE); - currentHeapUsed = static_cast(heapUsed); - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) -{ - // FreeRTOS records the lowest amount of available heap during runtime - // currentHeapHighWatermark wants the highest heap usage point so we calculate it here - -#ifdef CFG_USE_PSRAM - int64_t HighestHeapUsageRecorded = - (get_heap_size() + get_heap3_size() - xPortGetMinimumEverFreeHeapSize() - xPortGetMinimumEverFreeHeapSizePsram()); -#else - size_t freeHeapSize = xPortGetFreeHeapSize(); - int64_t HighestHeapUsageRecorded = (get_heap_size() - xPortGetMinimumEverFreeHeapSize()); -#endif - - // Something went wrong, this should not happen - VerifyOrReturnError(HighestHeapUsageRecorded >= 0, CHIP_ERROR_INVALID_INTEGER_VALUE); - currentHeapHighWatermark = static_cast(HighestHeapUsageRecorded); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetThreadMetrics(ThreadMetrics ** threadMetricsOut) +CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason) { - /* Obtain all available task information */ - TaskStatus_t * taskStatusArray; - ThreadMetrics * head = nullptr; - uint32_t arraySize, x, dummy; - - arraySize = uxTaskGetNumberOfTasks(); + BL_RST_REASON_E bootCause = bl_sys_rstinfo_get(); - taskStatusArray = static_cast(chip::Platform::MemoryCalloc(arraySize, sizeof(TaskStatus_t))); - - if (taskStatusArray != NULL) + if (BL_RST_POR == bootCause) { - /* Generate raw status information about each task. */ - arraySize = uxTaskGetSystemState(taskStatusArray, arraySize, &dummy); - /* For each populated position in the taskStatusArray array, - format the raw data as human readable ASCII data. */ - - for (x = 0; x < arraySize; x++) - { - ThreadMetrics * thread = new ThreadMetrics(); - if (thread) - { - Platform::CopyString(thread->NameBuf, taskStatusArray[x].pcTaskName); - thread->name.Emplace(CharSpan::fromCharString(thread->NameBuf)); - thread->id = taskStatusArray[x].xTaskNumber; - thread->stackFreeMinimum.Emplace(taskStatusArray[x].usStackHighWaterMark); - - /* Unsupported metrics */ - // thread->stackSize - // thread->stackFreeCurrent - - thread->Next = head; - head = thread; - } - } - - *threadMetricsOut = head; - /* The array is no longer needed, free the memory it consumes. */ - chip::Platform::MemoryFree(taskStatusArray); + bootReason = BootReasonType::kPowerOnReboot; } - - return CHIP_NO_ERROR; -} - -void DiagnosticDataProviderImpl::ReleaseThreadMetrics(ThreadMetrics * threadMetrics) -{ - while (threadMetrics) + else if (BL_RST_BOR == bootCause) { - ThreadMetrics * del = threadMetrics; - threadMetrics = threadMetrics->Next; - delete del; + bootReason = BootReasonType::kBrownOutReset; } -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetRebootCount(uint16_t & rebootCount) -{ - uint32_t count = 0; - CHIP_ERROR err = ConfigurationMgr().GetRebootCount(count); - - if (err == CHIP_NO_ERROR) - { - VerifyOrReturnError(count <= UINT16_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); - rebootCount = static_cast(count); - } - - return err; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason) -{ - uint32_t reason = 0; - CHIP_ERROR err = ConfigurationMgr().GetBootReason(reason); - - if (err == CHIP_NO_ERROR) + else if (BL_RST_WDT == bootCause) { - VerifyOrReturnError(reason <= UINT8_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); - bootReason = static_cast(reason); + bootReason = BootReasonType::kHardwareWatchdogReset; } - - return err; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetUpTime(uint64_t & upTime) -{ - System::Clock::Timestamp currentTime = System::SystemClock().GetMonotonicTimestamp(); - System::Clock::Timestamp startTime = PlatformMgrImpl().GetStartTime(); - - if (currentTime >= startTime) + else if (BL_RST_SOFTWARE == bootCause) { - upTime = std::chrono::duration_cast(currentTime - startTime).count(); - return CHIP_NO_ERROR; + bootReason = BootReasonType::kSoftwareReset; } - - return CHIP_ERROR_INVALID_TIME; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) -{ - uint64_t upTime = 0; - - if (GetUpTime(upTime) == CHIP_NO_ERROR) + else { - uint32_t totalHours = 0; - if (ConfigurationMgr().GetTotalOperationalHours(totalHours) == CHIP_NO_ERROR) - { - VerifyOrReturnError(upTime / 3600 <= UINT32_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); - totalOperationalHours = totalHours + static_cast(upTime / 3600); - return CHIP_NO_ERROR; - } + bootReason = BootReasonType::kUnspecified; } - - return CHIP_ERROR_INVALID_TIME; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetActiveHardwareFaults(GeneralFaults & hardwareFaults) -{ -#if CHIP_CONFIG_TEST - ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kRadio))); - ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kSensor))); - ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kPowerSource))); - ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kUserInterfaceFault))); -#endif - - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetActiveRadioFaults(GeneralFaults & radioFaults) -{ -#if CHIP_CONFIG_TEST - ReturnErrorOnFailure(radioFaults.add(EMBER_ZCL_RADIO_FAULT_ENUM_THREAD_FAULT)); - ReturnErrorOnFailure(radioFaults.add(EMBER_ZCL_RADIO_FAULT_ENUM_BLE_FAULT)); -#endif - - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetActiveNetworkFaults(GeneralFaults & networkFaults) -{ -#if CHIP_CONFIG_TEST - ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kHardwareFailure))); - ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kNetworkJammed))); - ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kConnectionFailed))); -#endif - return CHIP_NO_ERROR; } @@ -245,23 +56,18 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** { NetworkInterface * ifp = new NetworkInterface(); -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD - const char * threadNetworkName = otThreadGetNetworkName(ThreadStackMgrImpl().OTInstance()); ifp->name = Span(threadNetworkName, strlen(threadNetworkName)); ifp->isOperational = true; ifp->offPremiseServicesReachableIPv4.SetNull(); ifp->offPremiseServicesReachableIPv6.SetNull(); - ifp->type = InterfaceTypeEnum::EMBER_ZCL_INTERFACE_TYPE_ENUM_THREAD; + ifp->type = EMBER_ZCL_INTERFACE_TYPE_ENUM_THREAD; uint8_t macBuffer[ConfigurationManager::kPrimaryMACAddressLength]; ConfigurationMgr().GetPrimary802154MACAddress(macBuffer); ifp->hardwareAddress = ByteSpan(macBuffer, ConfigurationManager::kPrimaryMACAddressLength); -#else - /* TODO */ -#endif - *netifpp = ifp; + return CHIP_NO_ERROR; } @@ -275,10 +81,5 @@ void DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * net } } -DiagnosticDataProvider & GetDiagnosticDataProviderImpl() -{ - return DiagnosticDataProviderImpl::GetDefaultInstance(); -} - } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.h b/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.h deleted file mode 100644 index 6411b8e4cbd501..00000000000000 --- a/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -#include - -namespace chip { -namespace DeviceLayer { - -/** - * Concrete implementation of the PlatformManager singleton object for Linux platforms. - */ -class DiagnosticDataProviderImpl : public DiagnosticDataProvider -{ -public: - static DiagnosticDataProviderImpl & GetDefaultInstance(); - - // ===== Methods that implement the PlatformManager abstract interface. - - CHIP_ERROR GetCurrentHeapFree(uint64_t & currentHeapFree) override; - CHIP_ERROR GetCurrentHeapUsed(uint64_t & currentHeapUsed) override; - CHIP_ERROR GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) override; - CHIP_ERROR GetThreadMetrics(ThreadMetrics ** threadMetricsOut) override; - void ReleaseThreadMetrics(ThreadMetrics * threadMetrics) override; - CHIP_ERROR GetRebootCount(uint16_t & rebootCount) override; - CHIP_ERROR GetBootReason(BootReasonType & bootReason) override; - CHIP_ERROR GetUpTime(uint64_t & upTime) override; - CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours) override; - CHIP_ERROR GetActiveHardwareFaults(GeneralFaults & hardwareFaults) override; - CHIP_ERROR GetActiveRadioFaults(GeneralFaults & radioFaults) override; - CHIP_ERROR GetActiveNetworkFaults(GeneralFaults & networkFaults) override; - CHIP_ERROR GetNetworkInterfaces(NetworkInterface ** netifpp) override; - void ReleaseNetworkInterfaces(NetworkInterface * netifp) override; -}; - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.cpp b/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.cpp deleted file mode 100644 index 1e49c74e4f9eb0..00000000000000 --- a/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.cpp +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "OTAImageProcessorImpl.h" -extern "C" { -#include -#include -} - -using namespace chip::System; - -namespace chip { - -CHIP_ERROR OTAImageProcessorImpl::PrepareDownload() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandlePrepareDownload, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::Finalize() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandleFinalize, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::Apply() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandleApply, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::Abort() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandleAbort, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block) -{ - if ((nullptr == block.data()) || block.empty()) - { - return CHIP_ERROR_INVALID_ARGUMENT; - } - - // Store block data for HandleProcessBlock to access - CHIP_ERROR err = SetBlock(block); - if (err != CHIP_NO_ERROR) - { - ChipLogError(SoftwareUpdate, "Cannot set block data: %" CHIP_ERROR_FORMAT, err.Format()); - } - - DeviceLayer::PlatformMgr().ScheduleWork(HandleProcessBlock, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context) -{ - auto * imageProcessor = reinterpret_cast(context); - - if (imageProcessor == nullptr) - { - ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); - return; - } - else if (imageProcessor->mDownloader == nullptr) - { - ChipLogError(SoftwareUpdate, "mDownloader is null"); - return; - } - - imageProcessor->mParams.downloadedBytes = 0; - imageProcessor->mParams.totalFileBytes = 0; - imageProcessor->mHeaderParser.Init(); - - imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR); -} - -void OTAImageProcessorImpl::HandleFinalize(intptr_t context) -{ - auto * imageProcessor = reinterpret_cast(context); - - if (imageProcessor == nullptr) - { - return; - } - - if (hosal_ota_check() < 0) - { - imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); - ChipLogProgress(SoftwareUpdate, "OTA image verification error"); - } - else - { - ChipLogProgress(SoftwareUpdate, "OTA image downloaded"); - } - - imageProcessor->ReleaseBlock(); -} - -void OTAImageProcessorImpl::HandleApply(intptr_t context) -{ - auto * imageProcessor = reinterpret_cast(context); - - if (imageProcessor == nullptr) - { - return; - } - - hosal_ota_apply(0); - DeviceLayer::SystemLayer().StartTimer( - System::Clock::Seconds32(OTA_AUTO_REBOOT_DELAY), - [](Layer *, void *) { - ChipLogProgress(SoftwareUpdate, "Rebooting..."); - hal_reboot(); - }, - nullptr); -} - -void OTAImageProcessorImpl::HandleAbort(intptr_t context) -{ - auto * imageProcessor = reinterpret_cast(context); - if (imageProcessor == nullptr) - { - return; - } - - hosal_ota_abort(); - - imageProcessor->ReleaseBlock(); -} - -void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) -{ - OTAImageHeader header; - CHIP_ERROR error; - auto * imageProcessor = reinterpret_cast(context); - - if (imageProcessor == nullptr) - { - ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); - return; - } - else if (imageProcessor->mDownloader == nullptr) - { - ChipLogError(SoftwareUpdate, "mDownloader is null"); - return; - } - - ByteSpan block = imageProcessor->mBlock; - if (imageProcessor->mHeaderParser.IsInitialized()) - { - - error = imageProcessor->mHeaderParser.AccumulateAndDecode(block, header); - if (CHIP_ERROR_BUFFER_TOO_SMALL == error) - { - return; - } - else if (CHIP_NO_ERROR != error) - { - ChipLogError(SoftwareUpdate, "Matter image header parser error %s", chip::ErrorStr(error)); - imageProcessor->mDownloader->EndDownload(CHIP_ERROR_INVALID_FILE_IDENTIFIER); - imageProcessor->mHeaderParser.Clear(); - return; - } - - ChipLogProgress(SoftwareUpdate, "Image Header software version: %ld payload size: %lu", header.mSoftwareVersion, - (long unsigned int) header.mPayloadSize); - imageProcessor->mParams.totalFileBytes = header.mPayloadSize; - imageProcessor->mHeaderParser.Clear(); - - if (hosal_ota_start(header.mPayloadSize) < 0) - { - imageProcessor->mDownloader->EndDownload(CHIP_ERROR_OPEN_FAILED); - return; - } - } - - if (imageProcessor->mParams.totalFileBytes) - { - if (hosal_ota_update(imageProcessor->mParams.totalFileBytes, imageProcessor->mParams.downloadedBytes, - (uint8_t *) block.data(), block.size()) < 0) - { - imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); - return; - } - imageProcessor->mParams.downloadedBytes += block.size(); - } - - imageProcessor->mDownloader->FetchNextData(); -} - -// Store block data for HandleProcessBlock to access -CHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block) -{ - if ((block.data() == nullptr) || block.empty()) - { - return CHIP_NO_ERROR; - } - - // Allocate memory for block data if we don't have enough already - if (mBlock.size() < block.size()) - { - ReleaseBlock(); - - mBlock = MutableByteSpan(static_cast(chip::Platform::MemoryAlloc(block.size())), block.size()); - if (mBlock.data() == nullptr) - { - return CHIP_ERROR_NO_MEMORY; - } - } - - // Store the actual block data - CHIP_ERROR err = CopySpanToMutableSpan(block, mBlock); - if (err != CHIP_NO_ERROR) - { - ChipLogError(SoftwareUpdate, "Cannot copy block data: %" CHIP_ERROR_FORMAT, err.Format()); - return err; - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::ReleaseBlock() -{ - if (mBlock.data() != nullptr) - { - chip::Platform::MemoryFree(mBlock.data()); - } - - mBlock = MutableByteSpan(); - return CHIP_NO_ERROR; -} - -} // namespace chip diff --git a/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.h b/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.h deleted file mode 100644 index 4bae9152f8f48c..00000000000000 --- a/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include -#include - -namespace chip { - -class OTAImageProcessorImpl : public OTAImageProcessorInterface -{ -public: - //////////// OTAImageProcessorInterface Implementation /////////////// - CHIP_ERROR PrepareDownload() override; - CHIP_ERROR Finalize() override; - CHIP_ERROR Apply() override; - CHIP_ERROR Abort() override; - CHIP_ERROR ProcessBlock(ByteSpan & block) override; - bool IsFirstImageRun() override { return false; } - CHIP_ERROR ConfirmCurrentImage() override { return CHIP_NO_ERROR; } - - void SetOTADownloader(OTADownloader * downloader) { mDownloader = downloader; } - -private: - //////////// Actual handlers for the OTAImageProcessorInterface /////////////// - static void HandlePrepareDownload(intptr_t context); - static void HandleFinalize(intptr_t context); - static void HandleApply(intptr_t context); - static void HandleAbort(intptr_t context); - static void HandleProcessBlock(intptr_t context); - - /** - * Called to allocate memory for mBlock if necessary and set it to block - */ - CHIP_ERROR SetBlock(ByteSpan & block); - - /** - * Called to release allocated memory for mBlock - */ - CHIP_ERROR ReleaseBlock(); - - MutableByteSpan mBlock; - OTADownloader * mDownloader; - OTAImageHeaderParser mHeaderParser; -}; - -} // namespace chip diff --git a/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp index 3f7e1399fe722b..b195abce5fb3b9 100644 --- a/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp @@ -15,13 +15,12 @@ * limitations under the License. */ -/* this file behaves like a config.h, comes first */ #include #include #include #include -#include +#include #include #include @@ -57,7 +56,7 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) otRadio_opt_t opt; // Initialize the configuration system. - err = Internal::BL702Config::Init(); + err = Internal::BLConfig::Init(); SuccessOrExit(err); opt.byte = 0; @@ -88,6 +87,29 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) exit: return err; } +void PlatformManagerImpl::_Shutdown() +{ + uint64_t upTime = 0; + if (GetDiagnosticDataProvider().GetUpTime(upTime) == CHIP_NO_ERROR) + { + uint32_t totalOperationalHours = 0; + + if (ConfigurationMgr().GetTotalOperationalHours(totalOperationalHours) == CHIP_NO_ERROR) + { + ConfigurationMgr().StoreTotalOperationalHours(totalOperationalHours + static_cast(upTime / 3600)); + } + else + { + ChipLogError(DeviceLayer, "Failed to get total operational hours of the Node"); + } + } + else + { + ChipLogError(DeviceLayer, "Failed to get current uptime since the Node’s last reboot"); + } + + Internal::GenericPlatformManagerImpl_FreeRTOS::_Shutdown(); +} } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/PlatformManagerImpl.h b/src/platform/bouffalolab/BL702/PlatformManagerImpl.h deleted file mode 100644 index 9dd8e14c87d293..00000000000000 --- a/src/platform/bouffalolab/BL702/PlatformManagerImpl.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -namespace chip { -namespace DeviceLayer { - -class PlatformManagerImpl final : public PlatformManager, public Internal::GenericPlatformManagerImpl_FreeRTOS -{ - // Allow the PlatformManager interface class to delegate method calls to - // the implementation methods provided by this class. - friend PlatformManager; - - // Allow the generic implementation base class to call helper methods on - // this class. -#ifndef DOXYGEN_SHOULD_SKIP_THIS - friend Internal::GenericPlatformManagerImpl_FreeRTOS; -#endif - -protected: - void _RunEventLoop(void); - -public: - // ===== Platform-specific members that may be accessed directly by the application. - System::Clock::Timestamp GetStartTime() { return mStartTime; } - -private: - // ===== Methods that implement the PlatformManager abstract interface. - - CHIP_ERROR _InitChipStack(void); - - // ===== Members for internal use by the following friends. - friend PlatformManager & PlatformMgr(void); - friend PlatformManagerImpl & PlatformMgrImpl(void); - friend class Internal::BLEManagerImpl; - - static PlatformManagerImpl sInstance; - System::Clock::Timestamp mStartTime = System::Clock::kZero; - - using Internal::GenericPlatformManagerImpl_FreeRTOS::PostEventFromISR; - - // ===== Methods that implement the PlatformManager Implementation dedicated. - CHIP_ERROR PlatformInit(void); -}; - -/** - * Returns the public interface of the PlatformManager singleton object. - * - * chip applications should use this to access features of the PlatformManager - * object that are common to all platforms. - */ -inline PlatformManager & PlatformMgr(void) -{ - return PlatformManagerImpl::sInstance; -} - -/** - * Returns the platform-specific implementation of the PlatformManager - * singleton object. - * - * chip applications can use this to gain access to features of the - * PlatformManager that are specific to the Baffalolab BL702 SoC. - */ -inline PlatformManagerImpl & PlatformMgrImpl(void) -{ - return PlatformManagerImpl::sInstance; -} - -inline void PlatformManagerImpl::_RunEventLoop(void) -{ - PlatformInit(); - Internal::GenericPlatformManagerImpl_FreeRTOS::_RunEventLoop(); -} - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL702/args.gni b/src/platform/bouffalolab/BL702/args.gni index eca543ed30dc06..47a03c6f7bd268 100644 --- a/src/platform/bouffalolab/BL702/args.gni +++ b/src/platform/bouffalolab/BL702/args.gni @@ -29,8 +29,6 @@ chip_inet_config_enable_tcp_endpoint = false chip_build_tests = false -chip_config_memory_management = "platform" - openthread_external_mbedtls = mbedtls_target openthread_project_core_config_file = "bl702-openthread-core-bl-config.h" openthread_core_config_platform_check_file = @@ -39,8 +37,3 @@ openthread_project_include_dirs = [ "${chip_root}/src/platform/bouffalolab/BL702" ] openthread_external_platform = "${bouffalolab_iot_sdk_build_root}/bl702:bl_iot_sdk" - -pw_build_LINK_DEPS = [ - "$dir_pw_assert:impl", - "$dir_pw_log:impl", -] diff --git a/src/platform/bouffalolab/BL702/bl702Config.cpp b/src/platform/bouffalolab/common/BLConfig.cpp similarity index 58% rename from src/platform/bouffalolab/BL702/bl702Config.cpp rename to src/platform/bouffalolab/common/BLConfig.cpp index a036a9277afe66..b8144dd1c23025 100644 --- a/src/platform/bouffalolab/BL702/bl702Config.cpp +++ b/src/platform/bouffalolab/common/BLConfig.cpp @@ -17,7 +17,7 @@ #include -#include +#include #include #include @@ -31,13 +31,12 @@ namespace chip { namespace DeviceLayer { namespace Internal { -// // Prefix used for Easyflash keys that contain Chip group encryption keys. -CHIP_ERROR BL702Config::Init() +CHIP_ERROR BLConfig::Init() { return CHIP_NO_ERROR; } -CHIP_ERROR BL702Config::ReadConfigValue(const char * key, uint8_t * val, size_t size, size_t & readsize) +CHIP_ERROR BLConfig::ReadConfigValue(const char * key, uint8_t * val, size_t size, size_t & readsize) { env_node_obj node; @@ -71,25 +70,25 @@ CHIP_ERROR BL702Config::ReadConfigValue(const char * key, uint8_t * val, size_t return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } -CHIP_ERROR BL702Config::ReadConfigValue(const char * key, bool & val) +CHIP_ERROR BLConfig::ReadConfigValue(const char * key, bool & val) { size_t readlen = 0; return ReadConfigValue(key, (uint8_t *) &val, 1, readlen); } -CHIP_ERROR BL702Config::ReadConfigValue(const char * key, uint32_t & val) +CHIP_ERROR BLConfig::ReadConfigValue(const char * key, uint32_t & val) { size_t readlen = 0; return ReadConfigValue(key, (uint8_t *) &val, sizeof(val), readlen); } -CHIP_ERROR BL702Config::ReadConfigValue(const char * key, uint64_t & val) +CHIP_ERROR BLConfig::ReadConfigValue(const char * key, uint64_t & val) { size_t readlen = 0; return ReadConfigValue(key, (uint8_t *) &val, sizeof(val), readlen); } -CHIP_ERROR BL702Config::ReadConfigValueStr(const char * key, char * buf, size_t bufSize, size_t & outLen) +CHIP_ERROR BLConfig::ReadConfigValueStr(const char * key, char * buf, size_t bufSize, size_t & outLen) { size_t readlen = 0; if (CHIP_NO_ERROR == ReadConfigValue(key, (uint8_t *) buf, bufSize, readlen)) @@ -106,7 +105,7 @@ CHIP_ERROR BL702Config::ReadConfigValueStr(const char * key, char * buf, size_t return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } -CHIP_ERROR BL702Config::ReadConfigValueBin(const char * key, uint8_t * buf, size_t bufSize, size_t & outLen) +CHIP_ERROR BLConfig::ReadConfigValueBin(const char * key, uint8_t * buf, size_t bufSize, size_t & outLen) { size_t readlen = 0; if (CHIP_NO_ERROR == ReadConfigValue(key, (uint8_t *) buf, bufSize, readlen)) @@ -118,7 +117,7 @@ CHIP_ERROR BL702Config::ReadConfigValueBin(const char * key, uint8_t * buf, size return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } -CHIP_ERROR BL702Config::WriteConfigValue(const char * key, uint8_t * val, size_t size) +CHIP_ERROR BLConfig::WriteConfigValue(const char * key, uint8_t * val, size_t size) { EfErrCode ret = EF_NO_ERR; @@ -141,42 +140,42 @@ CHIP_ERROR BL702Config::WriteConfigValue(const char * key, uint8_t * val, size_t } } -CHIP_ERROR BL702Config::WriteConfigValue(const char * key, bool val) +CHIP_ERROR BLConfig::WriteConfigValue(const char * key, bool val) { return WriteConfigValue(key, (uint8_t *) &val, sizeof(val)); } -CHIP_ERROR BL702Config::WriteConfigValue(const char * key, uint32_t val) +CHIP_ERROR BLConfig::WriteConfigValue(const char * key, uint32_t val) { return WriteConfigValue(key, (uint8_t *) &val, sizeof(val)); } -CHIP_ERROR BL702Config::WriteConfigValue(const char * key, uint64_t val) +CHIP_ERROR BLConfig::WriteConfigValue(const char * key, uint64_t val) { return WriteConfigValue(key, (uint8_t *) &val, sizeof(val)); } -CHIP_ERROR BL702Config::WriteConfigValueStr(const char * key, const char * str) +CHIP_ERROR BLConfig::WriteConfigValueStr(const char * key, const char * str) { return WriteConfigValue(key, (uint8_t *) str, strlen(str) + 1); } -CHIP_ERROR BL702Config::WriteConfigValueStr(const char * key, const char * str, size_t strLen) +CHIP_ERROR BLConfig::WriteConfigValueStr(const char * key, const char * str, size_t strLen) { return WriteConfigValue(key, (uint8_t *) str, strLen); } -CHIP_ERROR BL702Config::WriteConfigValueBin(const char * key, const uint8_t * data, size_t dataLen) +CHIP_ERROR BLConfig::WriteConfigValueBin(const char * key, const uint8_t * data, size_t dataLen) { return WriteConfigValue(key, (uint8_t *) data, dataLen); } -CHIP_ERROR BL702Config::ClearConfigValue(const char * key) +CHIP_ERROR BLConfig::ClearConfigValue(const char * key) { return EF_NO_ERR == ef_del_env(key) ? CHIP_NO_ERROR : CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } -CHIP_ERROR BL702Config::FactoryResetConfig(void) +CHIP_ERROR BLConfig::FactoryResetConfig(void) { // Only reset config section information @@ -185,16 +184,16 @@ CHIP_ERROR BL702Config::FactoryResetConfig(void) return CHIP_NO_ERROR; } -void BL702Config::RunConfigUnitTest() {} +void BLConfig::RunConfigUnitTest() {} -bool BL702Config::ConfigValueExists(const char * key) +bool BLConfig::ConfigValueExists(const char * key) { env_node_obj node; return ef_get_env_obj(key, &node); } -CHIP_ERROR BL702Config::ReadKVS(const char * key, void * value, size_t value_size, size_t * read_bytes_size, size_t offset_bytes) +CHIP_ERROR BLConfig::ReadKVS(const char * key, void * value, size_t value_size, size_t * read_bytes_size, size_t offset_bytes) { size_t read_len = 0, datalen; env_node_obj node; @@ -247,7 +246,7 @@ CHIP_ERROR BL702Config::ReadKVS(const char * key, void * value, size_t value_siz return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } -CHIP_ERROR BL702Config::WriteKVS(const char * key, const void * value, size_t value_size) +CHIP_ERROR BLConfig::WriteKVS(const char * key, const void * value, size_t value_size) { EfErrCode ret = EF_NO_ERR; @@ -270,7 +269,7 @@ CHIP_ERROR BL702Config::WriteKVS(const char * key, const void * value, size_t va } } -CHIP_ERROR BL702Config::ClearKVS(const char * key) +CHIP_ERROR BLConfig::ClearKVS(const char * key) { ef_port_env_lock(); @@ -281,72 +280,6 @@ CHIP_ERROR BL702Config::ClearKVS(const char * key) return CHIP_NO_ERROR; } -CHIP_ERROR BL702Config::WriteWiFiInfo(const char * ssid, const char * passwd) -{ - char *pssid = (char *) ssid, *ppass = (char *) passwd; - - ef_port_env_lock(); - - if (EF_NO_ERR == ef_set_env_blob(kBLConfigKey_wifissid, pssid, strlen(pssid)) && - EF_NO_ERR == ef_set_env_blob(kBLConfigKey_wifipassword, ppass, strlen(ppass))) - { - - ef_port_env_unlock(); - - return CHIP_NO_ERROR; - } - - ef_port_env_unlock(); - - return CHIP_ERROR_PERSISTED_STORAGE_FAILED; -} - -CHIP_ERROR BL702Config::ReadWiFiInfo(const char * ssid, uint32_t ssid_size, const char * passwd, uint32_t passwd_size) -{ - size_t saved_value_len = 0; - char *pssid = (char *) ssid, *ppass = (char *) passwd; - - memset((void *) ssid, 0, ssid_size); - memset((void *) passwd, 0, passwd_size); - - ef_port_env_lock(); - - ef_get_env_blob(kBLConfigKey_wifissid, (void *) pssid, ssid_size, &saved_value_len); - if (saved_value_len != 0) - { - saved_value_len = 0; - ef_get_env_blob(kBLConfigKey_wifipassword, (void *) ppass, passwd_size, &saved_value_len); - } - - ef_port_env_unlock(); - - return saved_value_len ? CHIP_NO_ERROR : CHIP_ERROR_PERSISTED_STORAGE_FAILED; -} - -CHIP_ERROR BL702Config::ClearWiFiInfo(void) -{ - ef_port_env_lock(); - if (EF_NO_ERR == ef_del_env(kBLConfigKey_wifissid) && EF_NO_ERR == ef_del_env(kBLConfigKey_wifipassword)) - { - ef_port_env_unlock(); - - return CHIP_NO_ERROR; - } - ef_port_env_unlock(); - - return CHIP_ERROR_PERSISTED_STORAGE_FAILED; -} - -bool BL702Config::isWiFiInfoSaved() -{ - env_node_obj node; - - char tssid[64], tpasswd[64]; - ReadWiFiInfo(tssid, sizeof(tssid), tpasswd, sizeof(tpasswd)); - - return ef_get_env_obj(kBLConfigKey_wifissid, &node) && ef_get_env_obj(kBLConfigKey_wifipassword, &node); -} - } // namespace Internal } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/bl702Config.h b/src/platform/bouffalolab/common/BLConfig.h similarity index 93% rename from src/platform/bouffalolab/BL702/bl702Config.h rename to src/platform/bouffalolab/common/BLConfig.h index af40b430964a3c..3b533a08f5e142 100644 --- a/src/platform/bouffalolab/BL702/bl702Config.h +++ b/src/platform/bouffalolab/common/BLConfig.h @@ -25,14 +25,13 @@ namespace chip { namespace DeviceLayer { namespace Internal { -#define KCONFIG_SECT_PSV "PSV" /** - * Provides functions and definitions for accessing device configuration information on the BL702 platform. + * Provides functions and definitions for accessing device configuration information on the Bouffalo Lab platform. * * This class is designed to be mixed-in to concrete implementation classes as a means to * provide access to configuration information to generic base classes. */ -class BL702Config +class BLConfig { public: using Key = const char *; @@ -107,14 +106,6 @@ class BL702Config static CHIP_ERROR ReadKVS(const char * key, void * value, size_t value_size, size_t * read_bytes_size, size_t offset_bytes); static CHIP_ERROR WriteKVS(const char * key, const void * value, size_t value_size); static CHIP_ERROR ClearKVS(const char * key); - -#ifdef CFG_USE_PSRAM - static bool isPsramRegion(void * paddr); -#endif - static CHIP_ERROR WriteWiFiInfo(const char * ssid, const char * password); - static CHIP_ERROR ReadWiFiInfo(const char * ssid, uint32_t ssid_size, const char * passwd, uint32_t passwd_size); - static bool isWiFiInfoSaved(); - static CHIP_ERROR ClearWiFiInfo(void); }; } // namespace Internal diff --git a/src/platform/bouffalolab/BL602/BLEManagerImpl.cpp b/src/platform/bouffalolab/common/BLEManagerImpl.cpp similarity index 99% rename from src/platform/bouffalolab/BL602/BLEManagerImpl.cpp rename to src/platform/bouffalolab/common/BLEManagerImpl.cpp index 20d5bc9006d81d..ff26daf1167bd8 100644 --- a/src/platform/bouffalolab/BL602/BLEManagerImpl.cpp +++ b/src/platform/bouffalolab/common/BLEManagerImpl.cpp @@ -696,8 +696,6 @@ bool BLEManagerImpl::SetSubscribed(bt_conn * conn) bool isSubscribed = mSubscribedConns[index]; mSubscribedConns[index] = true; - ChipLogError(DeviceLayer, "BLEManagerImpl::SetSubscribed %u", index); - // If we were not subscribed previously, increment the reference counter of the connection. if (!isSubscribed) { diff --git a/src/platform/bouffalolab/BL602/BLEManagerImpl.h b/src/platform/bouffalolab/common/BLEManagerImpl.h similarity index 100% rename from src/platform/bouffalolab/BL602/BLEManagerImpl.h rename to src/platform/bouffalolab/common/BLEManagerImpl.h diff --git a/src/platform/bouffalolab/BL702/BlePlatformConfig.h b/src/platform/bouffalolab/common/BlePlatformConfig.h similarity index 100% rename from src/platform/bouffalolab/BL702/BlePlatformConfig.h rename to src/platform/bouffalolab/common/BlePlatformConfig.h diff --git a/src/platform/bouffalolab/BL702/CHIPDevicePlatformConfig.h b/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h similarity index 58% rename from src/platform/bouffalolab/BL702/CHIPDevicePlatformConfig.h rename to src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h index d71c8ff00ec895..698c9419620374 100644 --- a/src/platform/bouffalolab/BL702/CHIPDevicePlatformConfig.h +++ b/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h @@ -17,38 +17,29 @@ #pragma once -// ==================== Platform Adaptations ==================== - +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 1 +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 +#else #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 0 #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 - -// ========== Platform-specific Configuration ========= - -#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_TELEMETRY 0 -#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY 0 -#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY_FULL 0 -#define CHIP_DEVICE_CONFIG_ENABLE_TUNNEL_TELEMETRY 0 - -// ========== CHIP Platform Configuration ========= -#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE (4 * 1024) -#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE (6 * 1024) -#define CHIP_DEVICE_CONFIG_MAX_EVENT_QUEUE_SIZE 15 +#endif #if CHIP_ENABLE_OPENTHREAD #define CHIP_DEVICE_CONFIG_ENABLE_THREAD 1 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_DNS_CLIENT 1 -#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 +#else +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_DNS_CLIENT 0 #endif -// Per 5.2.5.2. Commencement Section of CHIP spec, BLE advertisement is -// disabled for Locks and Barrier Access Devices. -#define CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART 0 -#define CHIP_DEVICE_CONFIG_ENABLE_PAIRING_AUTOSTART 1 +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 -#ifndef CHIP_DEVICE_CONFIG_ENABLE_DNSSD -#define CHIP_DEVICE_CONFIG_ENABLE_DNSSD 1 -#endif -#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DISCOVERY 1 +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_TELEMETRY 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY_FULL 0 -#define CHIP_DEVICE_CONFIG_PERSISTED_STORAGE_GLOBAL_EIDC_KEY 2 +#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE (8 * 1024) +#define CHIP_DEVICE_CONFIG_MAX_EVENT_QUEUE_SIZE 25 diff --git a/src/platform/bouffalolab/BL702/CHIPDevicePlatformEvent.h b/src/platform/bouffalolab/common/CHIPDevicePlatformEvent.h similarity index 88% rename from src/platform/bouffalolab/BL702/CHIPDevicePlatformEvent.h rename to src/platform/bouffalolab/common/CHIPDevicePlatformEvent.h index d14d1f7b9bb2ac..8746bebf82bfe8 100644 --- a/src/platform/bouffalolab/BL702/CHIPDevicePlatformEvent.h +++ b/src/platform/bouffalolab/common/CHIPDevicePlatformEvent.h @@ -17,9 +17,10 @@ #pragma once +#include + #include #include -#include namespace chip { namespace DeviceLayer { @@ -27,7 +28,7 @@ namespace DeviceLayer { namespace DeviceEventType { /** - * Enumerates BL702 platform-specific event types that are visible to the application. + * Enumerates Bouffalo Lab platforms event types that are visible to the application. */ enum PublicPlatformSpecificEventTypes { @@ -35,7 +36,7 @@ enum PublicPlatformSpecificEventTypes }; /** - * Enumerates BL702 platform-specific event types that are internal to the chip Device Layer. + * Enumerates Bouffalo Lab platforms event types that are internal to the chip Device Layer. */ enum InternalPlatformSpecificEventTypes { @@ -75,7 +76,7 @@ struct BleC2IndDoneEventType }; /** - * Represents platform-specific event information for the BL702 platform. + * Represents platform-specific event information for Bouffalo Lab platforms. */ struct ChipDevicePlatformEvent final { diff --git a/src/platform/bouffalolab/BL602/CHIPPlatformConfig.h b/src/platform/bouffalolab/common/CHIPPlatformConfig.h similarity index 81% rename from src/platform/bouffalolab/BL602/CHIPPlatformConfig.h rename to src/platform/bouffalolab/common/CHIPPlatformConfig.h index 44d3114c1fcc75..c3e39f3d2d22d9 100644 --- a/src/platform/bouffalolab/BL602/CHIPPlatformConfig.h +++ b/src/platform/bouffalolab/common/CHIPPlatformConfig.h @@ -1,7 +1,6 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Google LLC. + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,28 +15,11 @@ * limitations under the License. */ -/** - * @file - * Platform-specific configuration overrides for CHIP on - * Bouffalolab BL602 platforms. - */ - #pragma once #include // ==================== General Platform Adaptations ==================== - -#define CHIP_CONFIG_ERROR_TYPE int32_t -#define CHIP_CONFIG_NO_ERROR 0 -#define CHIP_CONFIG_ERROR_MIN 4000000 -#define CHIP_CONFIG_ERROR_MAX 4000999 - -#define ASN1_CONFIG_ERROR_TYPE int32_t -#define ASN1_CONFIG_NO_ERROR 0 -#define ASN1_CONFIG_ERROR_MIN 5000000 -#define ASN1_CONFIG_ERROR_MAX 5000999 - #define ChipDie() abort() #define CHIP_CONFIG_PERSISTED_STORAGE_KEY_TYPE const char * @@ -47,14 +29,8 @@ #define CHIP_CONFIG_LIFETIIME_PERSISTED_COUNTER_KEY 0x01 // ==================== Security Adaptations ==================== - -#define CHIP_CONFIG_USE_OPENSSL_ECC 0 -#define CHIP_CONFIG_USE_MICRO_ECC 0 - -#define CHIP_CONFIG_HASH_IMPLEMENTATION_OPENSSL 0 -#define CHIP_CONFIG_HASH_IMPLEMENTATION_MINCRYPT 1 -#define CHIP_CONFIG_HASH_IMPLEMENTATION_MBEDTLS 0 -#define CHIP_CONFIG_HASH_IMPLEMENTATION_PLATFORM 0 +//#define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(bl_sha_ctx_t) +#define CHIP_CONFIG_SHA256_CONTEXT_SIZE ((1 + 5 + 18 + 16 + 16) * sizeof(unsigned int)) #define CHIP_CONFIG_AES_IMPLEMENTATION_OPENSSL 0 #define CHIP_CONFIG_AES_IMPLEMENTATION_AESNI 0 @@ -65,9 +41,6 @@ #define CHIP_CONFIG_RNG_IMPLEMENTATION_CHIPDRBG 1 #define CHIP_CONFIG_RNG_IMPLEMENTATION_PLATFORM 0 -//#define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(bl_sha_ctx_t) -#define CHIP_CONFIG_SHA256_CONTEXT_SIZE ((1 + 5 + 18 + 16 + 16) * sizeof(unsigned int)) - #define CHIP_CONFIG_ENABLE_PASE_INITIATOR 0 #define CHIP_CONFIG_ENABLE_PASE_RESPONDER 1 #define CHIP_CONFIG_ENABLE_CASE_INITIATOR 1 diff --git a/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.cpp b/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp similarity index 61% rename from src/platform/bouffalolab/BL702/ConfigurationManagerImpl.cpp rename to src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp index 00878976150d26..4618e7f72f7274 100644 --- a/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.cpp +++ b/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp @@ -35,9 +35,6 @@ namespace chip { namespace DeviceLayer { using namespace ::chip::DeviceLayer::Internal; - -/** Singleton instance of the ConfigurationManager implementation object. - */ ConfigurationManagerImpl & ConfigurationManagerImpl::GetDefaultInstance() { static ConfigurationManagerImpl sInstance; @@ -50,42 +47,25 @@ CHIP_ERROR ConfigurationManagerImpl::Init() bool failSafeArmed; uint32_t rebootCount = 0; - err = Internal::GenericConfigurationManagerImpl::Init(); + err = Internal::GenericConfigurationManagerImpl::Init(); + SuccessOrExit(err); - BL_RST_REASON_E bootCause = bl_sys_rstinfo_get(); - mBootReason = to_underlying(BootReasonType::kUnspecified); - if (BL_RST_POR == bootCause) - { - mBootReason = to_underlying(BootReasonType::kPowerOnReboot); - } - else if (BL_RST_BOR == bootCause) - { - mBootReason = to_underlying(BootReasonType::kBrownOutReset); - } - else if (BL_RST_WDT == bootCause) + if (BLConfig::ConfigValueExists(BLConfig::kCounterKey_RebootCount)) { - mBootReason = to_underlying(BootReasonType::kHardwareWatchdogReset); + err = GetRebootCount(rebootCount); + SuccessOrExit(err); } - // else if (BL_RST_HBN == bootCause) { - // mBootReason = BootReasonType::SoftwareReset; - // } - else if (BL_RST_SOFTWARE == bootCause) + else { - mBootReason = to_underlying(BootReasonType::kSoftwareReset); + rebootCount = 0; } + err = StoreRebootCount(rebootCount + 1); + SuccessOrExit(err); - if (BL_RST_HBN != bootCause) + if (!BLConfig::ConfigValueExists(BLConfig::kCounterKey_TotalOperationalHours)) { - if (CHIP_NO_ERROR == ReadConfigValue(BL702Config::kCounterKey_RebootCount, rebootCount)) - { - rebootCount += 1; - } - WriteConfigValue(BL702Config::kCounterKey_RebootCount, rebootCount + 1); - } - - if (!BL702Config::ConfigValueExists(BL702Config::kCounterKey_TotalOperationalHours)) - { - ReturnErrorOnFailure(StoreTotalOperationalHours(0)); + err = StoreTotalOperationalHours(0); + SuccessOrExit(err); } // If the fail-safe was armed when the device last shutdown, initiate a factory reset. @@ -96,6 +76,7 @@ CHIP_ERROR ConfigurationManagerImpl::Init() } err = CHIP_NO_ERROR; +exit: return err; } @@ -110,113 +91,102 @@ void ConfigurationManagerImpl::InitiateFactoryReset() PlatformMgr().ScheduleWork(DoFactoryReset); } -CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) -{ - char keyname[sizeof(KCONFIG_SECT_PSV) + 10]; - - sprintf(keyname, "%s_%x", KCONFIG_SECT_PSV, key); - - CHIP_ERROR err = ReadConfigValue(keyname, value); - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - return err; -} - -CHIP_ERROR ConfigurationManagerImpl::WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) -{ - char keyname[sizeof(KCONFIG_SECT_PSV) + 10]; - - sprintf(keyname, "%s_%d", KCONFIG_SECT_PSV, key); - - return WriteConfigValue(keyname, value); -} - CHIP_ERROR ConfigurationManagerImpl::GetRebootCount(uint32_t & rebootCount) { - return ReadConfigValue(BL702Config::kCounterKey_RebootCount, rebootCount); + return BLConfig::ReadConfigValue(BLConfig::kCounterKey_RebootCount, rebootCount); } CHIP_ERROR ConfigurationManagerImpl::StoreRebootCount(uint32_t rebootCount) { - return WriteConfigValue(BL702Config::kCounterKey_RebootCount, rebootCount); + return BLConfig::WriteConfigValue(BLConfig::kCounterKey_RebootCount, rebootCount); } CHIP_ERROR ConfigurationManagerImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) { - return ReadConfigValue(BL702Config::kCounterKey_TotalOperationalHours, totalOperationalHours); + return ReadConfigValue(BLConfig::kCounterKey_TotalOperationalHours, totalOperationalHours); } CHIP_ERROR ConfigurationManagerImpl::StoreTotalOperationalHours(uint32_t totalOperationalHours) { - return WriteConfigValue(BL702Config::kCounterKey_TotalOperationalHours, totalOperationalHours); + return WriteConfigValue(BLConfig::kCounterKey_TotalOperationalHours, totalOperationalHours); } -CHIP_ERROR ConfigurationManagerImpl::GetBootReason(uint32_t & bootReason) +CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) { - bootReason = mBootReason; - return CHIP_NO_ERROR; + BLConfig::Key configKey{ key }; + + CHIP_ERROR err = ReadConfigValue(configKey, value); + if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) + { + err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; + } + return err; +} + +CHIP_ERROR ConfigurationManagerImpl::WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) +{ + BLConfig::Key configKey{ key }; + return WriteConfigValue(configKey, value); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, bool & val) { - return BL702Config::ReadConfigValue(key, val); + return BLConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint32_t & val) { - return BL702Config::ReadConfigValue(key, val); + return BLConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint64_t & val) { - return BL702Config::ReadConfigValue(key, val); + return BLConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { - return BL702Config::ReadConfigValueStr(key, buf, bufSize, outLen); + return BLConfig::ReadConfigValueStr(key, buf, bufSize, outLen); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) { - return BL702Config::ReadConfigValueBin(key, buf, bufSize, outLen); + return BLConfig::ReadConfigValueBin(key, buf, bufSize, outLen); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, bool val) { - return BL702Config::WriteConfigValue(key, val); + return BLConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint32_t val) { - return BL702Config::WriteConfigValue(key, val); + return BLConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint64_t val) { - return BL702Config::WriteConfigValue(key, val); + return BLConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str) { - return BL702Config::WriteConfigValueStr(key, str); + return BLConfig::WriteConfigValueStr(key, str); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str, size_t strLen) { - return BL702Config::WriteConfigValueStr(key, str, strLen); + return BLConfig::WriteConfigValueStr(key, str, strLen); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) { - return BL702Config::WriteConfigValueBin(key, data, dataLen); + return BLConfig::WriteConfigValueBin(key, data, dataLen); } void ConfigurationManagerImpl::RunConfigUnitTest(void) { - BL702Config::RunConfigUnitTest(); + BLConfig::RunConfigUnitTest(); } void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) @@ -225,7 +195,7 @@ void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) ChipLogProgress(DeviceLayer, "Performing factory reset"); - err = BL702Config::FactoryResetConfig(); + err = BLConfig::FactoryResetConfig(); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "FactoryResetConfig() failed: %s", ErrorStr(err)); @@ -240,6 +210,5 @@ ConfigurationManager & ConfigurationMgrImpl() { return ConfigurationManagerImpl::GetDefaultInstance(); } - } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.h b/src/platform/bouffalolab/common/ConfigurationManagerImpl.h similarity index 78% rename from src/platform/bouffalolab/BL702/ConfigurationManagerImpl.h rename to src/platform/bouffalolab/common/ConfigurationManagerImpl.h index db7668bf0f5eab..1d69d582185e75 100644 --- a/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.h +++ b/src/platform/bouffalolab/common/ConfigurationManagerImpl.h @@ -17,7 +17,8 @@ #pragma once -#include +#include + #include namespace chip { @@ -26,32 +27,26 @@ namespace DeviceLayer { /** * Concrete implementation of the ConfigurationManager singleton object for the bl702 platform. */ -class ConfigurationManagerImpl : public Internal::GenericConfigurationManagerImpl +class ConfigurationManagerImpl : public Internal::GenericConfigurationManagerImpl { public: - // This returns an instance of this class. static ConfigurationManagerImpl & GetDefaultInstance(); CHIP_ERROR GetRebootCount(uint32_t & rebootCount); CHIP_ERROR StoreRebootCount(uint32_t rebootCount); CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours); CHIP_ERROR StoreTotalOperationalHours(uint32_t totalOperationalHours); - CHIP_ERROR GetBootReason(uint32_t & bootReason); private: - uint32_t mBootReason; - - // ===== Members that implement the ConfigurationManager public interface. + // ===== Members that implement the ConfigurationManager private interface. CHIP_ERROR Init(void) override; + bool CanFactoryReset(void) override; void InitiateFactoryReset(void) override; CHIP_ERROR ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) override; CHIP_ERROR WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) override; - // NOTE: Other public interface methods are implemented by GenericConfigurationManagerImpl<>. - - // ===== Members that implement the GenericConfigurationManagerImpl protected interface. CHIP_ERROR ReadConfigValue(Key key, bool & val) override; CHIP_ERROR ReadConfigValue(Key key, uint32_t & val) override; CHIP_ERROR ReadConfigValue(Key key, uint64_t & val) override; @@ -65,22 +60,12 @@ class ConfigurationManagerImpl : public Internal::GenericConfigurationManagerImp CHIP_ERROR WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) override; void RunConfigUnitTest(void) override; - // ===== Private members reserved for use by this class only. - - static void DoFactoryReset(intptr_t arg); - #if CHIP_DEVICE_CONFIG_ENABLE_WIFI CHIP_ERROR GetPrimaryWiFiMACAddress(uint8_t * buf) override; #endif -}; -#if CHIP_DEVICE_CONFIG_ENABLE_WIFI -inline CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * buf) -{ - ConnectivityManagerImpl::GetWiFiMacAddress(buf); - return CHIP_NO_ERROR; -} -#endif + static void DoFactoryReset(intptr_t arg); +}; } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp similarity index 83% rename from src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp rename to src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp index cf1585a44a0e53..f1a47e5a68de06 100644 --- a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp +++ b/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp @@ -28,6 +28,13 @@ #include #endif +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include +#ifdef BL602 +#include +#endif +#endif + #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include #endif @@ -54,6 +61,13 @@ CHIP_ERROR ConnectivityManagerImpl::_Init() GenericConnectivityManagerImpl_Thread::_Init(); #endif +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + CHIP_ERROR err = SetWiFiStationMode(kWiFiStationMode_Enabled); + NetworkCommissioning::BLWiFiDriver::GetInstance().ReConnectWiFiNetwork(); + + ReturnErrorOnFailure(err); +#endif + return CHIP_NO_ERROR; } diff --git a/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.h b/src/platform/bouffalolab/common/ConnectivityManagerImpl.h similarity index 88% rename from src/platform/bouffalolab/BL602/ConnectivityManagerImpl.h rename to src/platform/bouffalolab/common/ConnectivityManagerImpl.h index 3efacc02c75043..8c06c585fb806f 100644 --- a/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.h +++ b/src/platform/bouffalolab/common/ConnectivityManagerImpl.h @@ -1,7 +1,6 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Nest Labs, Inc. + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +23,11 @@ #if INET_CONFIG_ENABLE_TCP_ENDPOINT #include #endif +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI #include +#else +#include +#endif #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include #else @@ -36,23 +39,20 @@ #include #endif -namespace Inet { -class IPAddress; -} // namespace Inet - namespace chip { namespace DeviceLayer { -/** - * Concrete implementation of the ConnectivityManager singleton object for Bouffalolab BL602 platforms. - */ class ConnectivityManagerImpl final : public ConnectivityManager, public Internal::GenericConnectivityManagerImpl, public Internal::GenericConnectivityManagerImpl_UDP, #if INET_CONFIG_ENABLE_TCP_ENDPOINT public Internal::GenericConnectivityManagerImpl_TCP, #endif +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI public Internal::GenericConnectivityManagerImpl_WiFi, +#else + public Internal::GenericConnectivityManagerImpl_NoWiFi, +#endif #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE public Internal::GenericConnectivityManagerImpl_BLE, #else @@ -68,6 +68,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, // the implementation methods provided by this class. friend class ConnectivityManager; +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI public: static WiFiStationState mWiFiStationState; @@ -76,19 +77,22 @@ class ConnectivityManagerImpl final : public ConnectivityManager, void OnStationConnected(void); void ChangeWiFiStationState(WiFiStationState newState); void OnIPv6AddressAvailable(); +#endif private: // ===== Members that implement the ConnectivityManager abstract interface. - +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI bool _IsWiFiStationEnabled(void); - bool _IsWiFiStationProvisioned(void); + // bool _IsWiFiStationProvisioned(void); CHIP_ERROR _SetWiFiStationMode(WiFiStationMode val); + void GetWifiState(void); + WiFiStationState GetWiFiStationState(void); +#endif + void DriveStationState(void); static void DriveStationState(::chip::System::Layer * aLayer, void * aAppState); CHIP_ERROR _Init(void); void _OnPlatformEvent(const ChipDeviceEvent * event); - void GetWifiState(void); - WiFiStationState GetWiFiStationState(void); // ===== Members for internal use by the following friends. @@ -98,6 +102,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, static ConnectivityManagerImpl sInstance; }; +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI inline ConnectivityManager::WiFiStationState ConnectivityManagerImpl::GetWiFiStationState(void) { return mWiFiStationState; @@ -107,6 +112,7 @@ inline bool ConnectivityManagerImpl::_IsWiFiStationConnected(void) { return mWiFiStationState == kWiFiStationState_Connected; } +#endif /** * Returns the public interface of the ConnectivityManager singleton object. @@ -123,7 +129,7 @@ inline ConnectivityManager & ConnectivityMgr(void) * Returns the platform-specific implementation of the ConnectivityManager singleton object. * * Chip applications can use this to gain access to features of the ConnectivityManager - * that are specific to the ESP32 platform. + * that are specific to the Bouffalo Lab platform. */ inline ConnectivityManagerImpl & ConnectivityMgrImpl(void) { diff --git a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp new file mode 100644 index 00000000000000..6e11e6f91d261e --- /dev/null +++ b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include +#include + +#include + +namespace chip { +namespace DeviceLayer { + +extern "C" size_t get_heap_size(void); +#ifdef CFG_USE_PSRAM +extern "C" size_t get_heap3_size(void); +#endif + +DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() +{ + static DiagnosticDataProviderImpl sInstance; + return sInstance; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) +{ +#ifdef CFG_USE_PSRAM + size_t freeHeapSize = xPortGetFreeHeapSize() + xPortGetFreeHeapSizePsram(); +#else + size_t freeHeapSize = xPortGetFreeHeapSize(); +#endif + + currentHeapFree = static_cast(freeHeapSize); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) +{ +#ifdef CFG_USE_PSRAM + currentHeapUsed = (get_heap_size() + get_heap3_size() - xPortGetFreeHeapSize() - xPortGetFreeHeapSizePsram()); +#else + currentHeapUsed = (get_heap_size() - xPortGetFreeHeapSize()); +#endif + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) +{ +#ifdef CFG_USE_PSRAM + currentHeapHighWatermark = + get_heap_size() + get_heap3_size() - xPortGetMinimumEverFreeHeapSize() - xPortGetMinimumEverFreeHeapSizePsram(); +#else + currentHeapHighWatermark = get_heap_size() - xPortGetMinimumEverFreeHeapSize(); +#endif + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetThreadMetrics(ThreadMetrics ** threadMetricsOut) +{ + /* Obtain all available task information */ + TaskStatus_t * taskStatusArray; + ThreadMetrics * head = nullptr; + uint32_t arraySize, x, dummy; + + arraySize = uxTaskGetNumberOfTasks(); + + taskStatusArray = static_cast(chip::Platform::MemoryCalloc(arraySize, sizeof(TaskStatus_t))); + + if (taskStatusArray != NULL) + { + /* Generate raw status information about each task. */ + arraySize = uxTaskGetSystemState(taskStatusArray, arraySize, &dummy); + /* For each populated position in the taskStatusArray array, + format the raw data as human readable ASCII data. */ + + for (x = 0; x < arraySize; x++) + { + ThreadMetrics * thread = new ThreadMetrics(); + if (thread) + { + Platform::CopyString(thread->NameBuf, taskStatusArray[x].pcTaskName); + thread->name.Emplace(CharSpan::fromCharString(thread->NameBuf)); + thread->id = taskStatusArray[x].xTaskNumber; + thread->stackFreeMinimum.Emplace(taskStatusArray[x].usStackHighWaterMark); + + /* Unsupported metrics */ + // thread->stackSize + // thread->stackFreeCurrent + + thread->Next = head; + head = thread; + } + } + + *threadMetricsOut = head; + /* The array is no longer needed, free the memory it consumes. */ + chip::Platform::MemoryFree(taskStatusArray); + } + + return CHIP_NO_ERROR; +} + +void DiagnosticDataProviderImpl::ReleaseThreadMetrics(ThreadMetrics * threadMetrics) +{ + while (threadMetrics) + { + ThreadMetrics * del = threadMetrics; + threadMetrics = threadMetrics->Next; + delete del; + } +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetRebootCount(uint16_t & rebootCount) +{ + uint32_t count = 0; + + CHIP_ERROR err = ConfigurationMgr().GetRebootCount(count); + + if (err == CHIP_NO_ERROR) + { + VerifyOrReturnError(count <= UINT16_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); + rebootCount = static_cast(count); + } + + return err; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetUpTime(uint64_t & upTime) +{ + System::Clock::Timestamp currentTime = System::SystemClock().GetMonotonicTimestamp(); + System::Clock::Timestamp startTime = PlatformMgrImpl().GetStartTime(); + + if (currentTime >= startTime) + { + upTime = std::chrono::duration_cast(currentTime - startTime).count(); + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_INVALID_TIME; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) +{ + uint64_t upTime = 0; + + if (GetUpTime(upTime) == CHIP_NO_ERROR) + { + uint32_t totalHours = 0; + if (ConfigurationMgr().GetTotalOperationalHours(totalHours) == CHIP_NO_ERROR) + { + VerifyOrReturnError(upTime / 3600 <= UINT32_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); + totalOperationalHours = totalHours + static_cast(upTime / 3600); + return CHIP_NO_ERROR; + } + } + + return CHIP_ERROR_INVALID_TIME; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetActiveHardwareFaults(GeneralFaults & hardwareFaults) +{ +#if CHIP_CONFIG_TEST + ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kRadio))); + ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kSensor))); + ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kPowerSource))); + ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kUserInterfaceFault))); +#endif + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetActiveRadioFaults(GeneralFaults & radioFaults) +{ +#if CHIP_CONFIG_TEST + ReturnErrorOnFailure(radioFaults.add(EMBER_ZCL_RADIO_FAULT_ENUM_THREAD_FAULT)); + ReturnErrorOnFailure(radioFaults.add(EMBER_ZCL_RADIO_FAULT_ENUM_BLE_FAULT)); +#endif + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetActiveNetworkFaults(GeneralFaults & networkFaults) +{ +#if CHIP_CONFIG_TEST + ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kHardwareFailure))); + ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kNetworkJammed))); + ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kConnectionFailed))); +#endif + + return CHIP_NO_ERROR; +} + +DiagnosticDataProvider & GetDiagnosticDataProviderImpl() +{ + return DiagnosticDataProviderImpl::GetDefaultInstance(); +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.h b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h similarity index 85% rename from src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.h rename to src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h index f8a1688d1c3870..8001afb0544cb3 100644 --- a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.h +++ b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,11 +14,6 @@ * limitations under the License. */ -/** - * @file - * Provides an implementation of the DiagnosticDataProvider object. - */ - #pragma once #include @@ -42,14 +36,18 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider CHIP_ERROR GetCurrentHeapFree(uint64_t & currentHeapFree) override; CHIP_ERROR GetCurrentHeapUsed(uint64_t & currentHeapUsed) override; CHIP_ERROR GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) override; - + CHIP_ERROR GetThreadMetrics(ThreadMetrics ** threadMetricsOut) override; + void ReleaseThreadMetrics(ThreadMetrics * threadMetrics) override; CHIP_ERROR GetRebootCount(uint16_t & rebootCount) override; + CHIP_ERROR GetBootReason(BootReasonType & bootReason) override; CHIP_ERROR GetUpTime(uint64_t & upTime) override; CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours) override; - CHIP_ERROR GetBootReason(BootReasonType & bootReason) override; - + CHIP_ERROR GetActiveHardwareFaults(GeneralFaults & hardwareFaults) override; + CHIP_ERROR GetActiveRadioFaults(GeneralFaults & radioFaults) override; + CHIP_ERROR GetActiveNetworkFaults(GeneralFaults & networkFaults) override; CHIP_ERROR GetNetworkInterfaces(NetworkInterface ** netifpp) override; void ReleaseNetworkInterfaces(NetworkInterface * netifp) override; +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI CHIP_ERROR GetWiFiBssId(MutableByteSpan & BssId) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) override; @@ -64,15 +62,8 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider CHIP_ERROR GetWiFiCurrentMaxRate(uint64_t & currentMaxRate) override; CHIP_ERROR GetWiFiOverrunCount(uint64_t & overrunCount) override; CHIP_ERROR ResetWiFiNetworkDiagnosticsCounts() override; +#endif }; -/** - * Returns the platform-specific implementation of the DiagnosticDataProvider singleton object. - * - * Applications can use this to gain access to features of the DiagnosticDataProvider - * that are specific to the selected platform. - */ -DiagnosticDataProvider & GetDiagnosticDataProviderImpl(); - } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/InetPlatformConfig.h b/src/platform/bouffalolab/common/InetPlatformConfig.h similarity index 96% rename from src/platform/bouffalolab/BL702/InetPlatformConfig.h rename to src/platform/bouffalolab/common/InetPlatformConfig.h index 088999420a6aae..d4552c22c81d5a 100644 --- a/src/platform/bouffalolab/BL702/InetPlatformConfig.h +++ b/src/platform/bouffalolab/common/InetPlatformConfig.h @@ -30,5 +30,5 @@ #endif // INET_CONFIG_NUM_TCP_ENDPOINTS #ifndef INET_CONFIG_NUM_UDP_ENDPOINTS -#define INET_CONFIG_NUM_UDP_ENDPOINTS 4 +#define INET_CONFIG_NUM_UDP_ENDPOINTS 6 #endif // INET_CONFIG_NUM_UDP_ENDPOINTS diff --git a/src/platform/bouffalolab/BL702/KeyValueStoreManagerImpl.cpp b/src/platform/bouffalolab/common/KeyValueStoreManagerImpl.cpp similarity index 87% rename from src/platform/bouffalolab/BL702/KeyValueStoreManagerImpl.cpp rename to src/platform/bouffalolab/common/KeyValueStoreManagerImpl.cpp index 929cfbace3668a..94dfb678c11b09 100644 --- a/src/platform/bouffalolab/BL702/KeyValueStoreManagerImpl.cpp +++ b/src/platform/bouffalolab/common/KeyValueStoreManagerImpl.cpp @@ -22,7 +22,7 @@ #include -#include +#include namespace chip { namespace DeviceLayer { @@ -37,7 +37,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t { VerifyOrReturnError(key, CHIP_ERROR_INVALID_ARGUMENT); - CHIP_ERROR err = BL702Config::ReadKVS(key, value, value_size, read_bytes_size, offset_bytes); + CHIP_ERROR err = BLConfig::ReadKVS(key, value, value_size, read_bytes_size, offset_bytes); if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; @@ -49,12 +49,12 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, { VerifyOrReturnError(key, CHIP_ERROR_INVALID_ARGUMENT); - return BL702Config::WriteKVS(key, value, value_size); + return BLConfig::WriteKVS(key, value, value_size); } CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) { - return BL702Config::ClearKVS((char *) key); + return BLConfig::ClearKVS((char *) key); } } // namespace PersistedStorage diff --git a/src/platform/bouffalolab/BL702/KeyValueStoreManagerImpl.h b/src/platform/bouffalolab/common/KeyValueStoreManagerImpl.h similarity index 100% rename from src/platform/bouffalolab/BL702/KeyValueStoreManagerImpl.h rename to src/platform/bouffalolab/common/KeyValueStoreManagerImpl.h diff --git a/src/platform/bouffalolab/BL702/Logging.cpp b/src/platform/bouffalolab/common/Logging.cpp similarity index 97% rename from src/platform/bouffalolab/BL702/Logging.cpp rename to src/platform/bouffalolab/common/Logging.cpp index 5bb986d63cb27d..e008fcd022b331 100644 --- a/src/platform/bouffalolab/BL702/Logging.cpp +++ b/src/platform/bouffalolab/common/Logging.cpp @@ -33,7 +33,7 @@ namespace chip { namespace Logging { namespace Platform { -char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; +static char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; void LogV(const char * module, uint8_t category, const char * msg, va_list v) { #ifndef PW_RPC_ENABLED diff --git a/src/platform/bouffalolab/BL602/OTAImageProcessorImpl.cpp b/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp similarity index 98% rename from src/platform/bouffalolab/BL602/OTAImageProcessorImpl.cpp rename to src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp index 97af465ef1fef3..6e38bf0b5a77cd 100644 --- a/src/platform/bouffalolab/BL602/OTAImageProcessorImpl.cpp +++ b/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp @@ -1,6 +1,5 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,7 +25,6 @@ extern "C" { } using namespace chip::System; -using namespace ::chip::DeviceLayer::Internal; namespace chip { diff --git a/src/platform/bouffalolab/BL602/OTAImageProcessorImpl.h b/src/platform/bouffalolab/common/OTAImageProcessorImpl.h similarity index 97% rename from src/platform/bouffalolab/BL602/OTAImageProcessorImpl.h rename to src/platform/bouffalolab/common/OTAImageProcessorImpl.h index c2cd9fa5607d9f..3e68f3c59d329a 100644 --- a/src/platform/bouffalolab/BL602/OTAImageProcessorImpl.h +++ b/src/platform/bouffalolab/common/OTAImageProcessorImpl.h @@ -1,6 +1,5 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/src/platform/bouffalolab/common/PlatformManagerImpl.cpp b/src/platform/bouffalolab/common/PlatformManagerImpl.cpp new file mode 100644 index 00000000000000..f31ae77999db64 --- /dev/null +++ b/src/platform/bouffalolab/common/PlatformManagerImpl.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include + +namespace chip { +namespace DeviceLayer { + +PlatformManagerImpl PlatformManagerImpl::sInstance; + +void PlatformManagerImpl::_Shutdown() +{ + uint64_t upTime = 0; + + if (GetDiagnosticDataProvider().GetUpTime(upTime) == CHIP_NO_ERROR) + { + uint32_t totalOperationalHours = 0; + + if (ConfigurationMgr().GetTotalOperationalHours(totalOperationalHours) == CHIP_NO_ERROR) + { + ConfigurationMgr().StoreTotalOperationalHours(totalOperationalHours + static_cast(upTime / 3600)); + } + else + { + ChipLogError(DeviceLayer, "Failed to get total operational hours of the Node"); + } + } + else + { + ChipLogError(DeviceLayer, "Failed to get current uptime since the Node’s last reboot"); + } + + Internal::GenericPlatformManagerImpl_FreeRTOS::_Shutdown(); +} +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL602/PlatformManagerImpl.h b/src/platform/bouffalolab/common/PlatformManagerImpl.h similarity index 95% rename from src/platform/bouffalolab/BL602/PlatformManagerImpl.h rename to src/platform/bouffalolab/common/PlatformManagerImpl.h index 4e6641b6e1e66f..448bc0636971f1 100644 --- a/src/platform/bouffalolab/BL602/PlatformManagerImpl.h +++ b/src/platform/bouffalolab/common/PlatformManagerImpl.h @@ -16,15 +16,11 @@ * limitations under the License. */ -/** - * @file - * Provides an implementation of the PlatformManager object - * for BL602 platforms using the Bouffalolab SDK. - */ - #pragma once +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI #include +#endif #include namespace chip { @@ -62,7 +58,9 @@ class PlatformManagerImpl final : public PlatformManager, public Internal::Gener friend PlatformManager & PlatformMgr(void); friend PlatformManagerImpl & PlatformMgrImpl(void); friend class Internal::BLEManagerImpl; +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI friend void OnWiFiPlatformEvent(input_event_t * event, void * private_data); +#endif System::Clock::Timestamp mStartTime = System::Clock::kZero; diff --git a/src/platform/bouffalolab/BL702/SystemPlatformConfig.h b/src/platform/bouffalolab/common/SystemPlatformConfig.h similarity index 94% rename from src/platform/bouffalolab/BL702/SystemPlatformConfig.h rename to src/platform/bouffalolab/common/SystemPlatformConfig.h index 4912f404626de3..2fb7579c677dd5 100644 --- a/src/platform/bouffalolab/BL702/SystemPlatformConfig.h +++ b/src/platform/bouffalolab/common/SystemPlatformConfig.h @@ -26,6 +26,5 @@ struct ChipDeviceEvent; } // namespace chip // ==================== Platform Adaptations ==================== -#define CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_EVENT_FUNCTIONS 1 #define CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME 1 #define CHIP_SYSTEM_CONFIG_EVENT_OBJECT_TYPE const struct ::chip::DeviceLayer::ChipDeviceEvent * diff --git a/src/platform/bouffalolab/BL702/ThreadStackManagerImpl.h b/src/platform/bouffalolab/common/ThreadStackManagerImpl.h similarity index 100% rename from src/platform/bouffalolab/BL702/ThreadStackManagerImpl.h rename to src/platform/bouffalolab/common/ThreadStackManagerImpl.h diff --git a/src/platform/device.gni b/src/platform/device.gni index 6eb09ace0d32ec..43bf65ab03b72f 100644 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -152,9 +152,9 @@ if (chip_device_platform == "cc13x2_26x2") { } else if (chip_device_platform == "ameba") { _chip_device_layer = "Ameba" } else if (chip_device_platform == "bl602") { - _chip_device_layer = "bouffalolab/BL602" + _chip_device_layer = "bouffalolab/common" } else if (chip_device_platform == "bl702") { - _chip_device_layer = "bouffalolab/BL702" + _chip_device_layer = "bouffalolab/common" } else if (chip_device_platform == "cyw30739") { _chip_device_layer = "Infineon/CYW30739" } else if (chip_device_platform == "webos") { diff --git a/third_party/bouffalolab/repo b/third_party/bouffalolab/repo index 7ca85fd77663ab..125a1237081749 160000 --- a/third_party/bouffalolab/repo +++ b/third_party/bouffalolab/repo @@ -1 +1 @@ -Subproject commit 7ca85fd77663ab6e13ce8481593474ea38ad4bb2 +Subproject commit 125a1237081749d5cc3ab5c1dc2017465960bba4 From 5c84a75d8b6ebd89b72d19b487314e2079655014 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 12 Jun 2023 15:28:51 -0400 Subject: [PATCH 10/15] Bump third_party/pigweed/repo from `7c87569` to `d8e4b80` (#27195) Bumps [third_party/pigweed/repo](https://github.com/google/pigweed) from `7c87569` to `d8e4b80`. - [Commits](https://github.com/google/pigweed/compare/7c875693d478ac0da2f358a1542a4fc1cad1b60d...d8e4b80c79540b12d367e4581250d133c8415596) --- updated-dependencies: - dependency-name: third_party/pigweed/repo dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- third_party/pigweed/repo | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/pigweed/repo b/third_party/pigweed/repo index 7c875693d478ac..d8e4b80c79540b 160000 --- a/third_party/pigweed/repo +++ b/third_party/pigweed/repo @@ -1 +1 @@ -Subproject commit 7c875693d478ac0da2f358a1542a4fc1cad1b60d +Subproject commit d8e4b80c79540b12d367e4581250d133c8415596 From d6fbc625dbb5a7c887cc2af1ff1788e4db1d076c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 12 Jun 2023 16:21:41 -0400 Subject: [PATCH 11/15] Bump third_party/openthread/repo from `b200c96` to `9b99fbf` (#27196) Bumps [third_party/openthread/repo](https://github.com/openthread/openthread) from `b200c96` to `9b99fbf`. - [Release notes](https://github.com/openthread/openthread/releases) - [Commits](https://github.com/openthread/openthread/compare/b200c968e7da615663a78532c6b4dd856ee9049a...9b99fbfd092380b0b8760bcb4863ea7c5f46e476) --- updated-dependencies: - dependency-name: third_party/openthread/repo dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- third_party/openthread/repo | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/openthread/repo b/third_party/openthread/repo index b200c968e7da61..9b99fbfd092380 160000 --- a/third_party/openthread/repo +++ b/third_party/openthread/repo @@ -1 +1 @@ -Subproject commit b200c968e7da615663a78532c6b4dd856ee9049a +Subproject commit 9b99fbfd092380b0b8760bcb4863ea7c5f46e476 From 212142b130a52789b68c063e68a5bf01d8591ce2 Mon Sep 17 00:00:00 2001 From: Wang Qixiang <43193572+wqx6@users.noreply.github.com> Date: Tue, 13 Jun 2023 09:48:59 +0800 Subject: [PATCH 12/15] ESP32: Move the openthread platform config file to examples (#27162) --- examples/all-clusters-app/esp32/main/main.cpp | 9 +++++++++ .../esp32/main/main.cpp | 9 +++++++++ examples/lighting-app/esp32/main/main.cpp | 12 ++++++++++++ .../platform/esp32/common}/OpenthreadConfig.h | 0 src/platform/ESP32/BUILD.gn | 1 - src/platform/ESP32/OpenthreadLauncher.c | 19 ++++++++++--------- src/platform/ESP32/OpenthreadLauncher.h | 4 ++++ 7 files changed, 44 insertions(+), 10 deletions(-) rename {src/platform/ESP32 => examples/platform/esp32/common}/OpenthreadConfig.h (100%) diff --git a/examples/all-clusters-app/esp32/main/main.cpp b/examples/all-clusters-app/esp32/main/main.cpp index 6d9c4e2c488af4..4f4450c882767c 100644 --- a/examples/all-clusters-app/esp32/main/main.cpp +++ b/examples/all-clusters-app/esp32/main/main.cpp @@ -51,6 +51,8 @@ #endif #if CONFIG_OPENTHREAD_ENABLED +#include +#include #include #endif @@ -192,6 +194,13 @@ extern "C" void app_main() ESP_LOGE(TAG, "GetAppTask().StartAppTask() failed : %" CHIP_ERROR_FORMAT, error.Format()); } #if CHIP_DEVICE_CONFIG_ENABLE_THREAD + esp_openthread_platform_config_t config = { + .radio_config = ESP_OPENTHREAD_DEFAULT_RADIO_CONFIG(), + .host_config = ESP_OPENTHREAD_DEFAULT_HOST_CONFIG(), + .port_config = ESP_OPENTHREAD_DEFAULT_PORT_CONFIG(), + }; + set_openthread_platform_config(&config); + if (DeviceLayer::ThreadStackMgr().InitThreadStack() != CHIP_NO_ERROR) { ESP_LOGE(TAG, "Failed to initialize Thread stack"); diff --git a/examples/all-clusters-minimal-app/esp32/main/main.cpp b/examples/all-clusters-minimal-app/esp32/main/main.cpp index 989c221f6de5f9..f62a30a71d7a96 100644 --- a/examples/all-clusters-minimal-app/esp32/main/main.cpp +++ b/examples/all-clusters-minimal-app/esp32/main/main.cpp @@ -52,6 +52,8 @@ #endif #if CONFIG_OPENTHREAD_ENABLED +#include +#include #include #endif @@ -186,6 +188,13 @@ extern "C" void app_main() } #if CHIP_DEVICE_CONFIG_ENABLE_THREAD + esp_openthread_platform_config_t config = { + .radio_config = ESP_OPENTHREAD_DEFAULT_RADIO_CONFIG(), + .host_config = ESP_OPENTHREAD_DEFAULT_HOST_CONFIG(), + .port_config = ESP_OPENTHREAD_DEFAULT_PORT_CONFIG(), + }; + set_openthread_platform_config(&config); + if (DeviceLayer::ThreadStackMgr().InitThreadStack() != CHIP_NO_ERROR) { ESP_LOGE(TAG, "Failed to initialize Thread stack"); diff --git a/examples/lighting-app/esp32/main/main.cpp b/examples/lighting-app/esp32/main/main.cpp index 283140c0ca6f40..a33d783a98439c 100644 --- a/examples/lighting-app/esp32/main/main.cpp +++ b/examples/lighting-app/esp32/main/main.cpp @@ -46,6 +46,11 @@ #include "Rpc.h" #endif +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +#include +#include +#endif + #include "DeviceWithDisplay.h" #if CONFIG_ENABLE_ESP32_DEVICE_INFO_PROVIDER @@ -158,6 +163,13 @@ extern "C" void app_main() SetDeviceAttestationCredentialsProvider(get_dac_provider()); #if CHIP_DEVICE_CONFIG_ENABLE_THREAD + esp_openthread_platform_config_t config = { + .radio_config = ESP_OPENTHREAD_DEFAULT_RADIO_CONFIG(), + .host_config = ESP_OPENTHREAD_DEFAULT_HOST_CONFIG(), + .port_config = ESP_OPENTHREAD_DEFAULT_PORT_CONFIG(), + }; + set_openthread_platform_config(&config); + if (ThreadStackMgr().InitThreadStack() != CHIP_NO_ERROR) { ESP_LOGE(TAG, "Failed to initialize Thread stack"); diff --git a/src/platform/ESP32/OpenthreadConfig.h b/examples/platform/esp32/common/OpenthreadConfig.h similarity index 100% rename from src/platform/ESP32/OpenthreadConfig.h rename to examples/platform/esp32/common/OpenthreadConfig.h diff --git a/src/platform/ESP32/BUILD.gn b/src/platform/ESP32/BUILD.gn index 6532efbec4fda3..1d27940db829fa 100644 --- a/src/platform/ESP32/BUILD.gn +++ b/src/platform/ESP32/BUILD.gn @@ -153,7 +153,6 @@ static_library("ESP32") { "../OpenThread/GenericNetworkCommissioningThreadDriver.cpp", "../OpenThread/GenericNetworkCommissioningThreadDriver.h", "../OpenThread/OpenThreadUtils.cpp", - "OpenthreadConfig.h", "OpenthreadLauncher.c", "OpenthreadLauncher.h", "ThreadStackManagerImpl.cpp", diff --git a/src/platform/ESP32/OpenthreadLauncher.c b/src/platform/ESP32/OpenthreadLauncher.c index 5c5bf6c9beea9b..7183767016bb89 100644 --- a/src/platform/ESP32/OpenthreadLauncher.c +++ b/src/platform/ESP32/OpenthreadLauncher.c @@ -15,7 +15,6 @@ * limitations under the License. */ -#include "OpenthreadConfig.h" #include "driver/uart.h" #include "esp_event.h" #include "esp_netif.h" @@ -31,7 +30,8 @@ #include "openthread/logging.h" #include "openthread/tasklet.h" -static esp_netif_t * openthread_netif = NULL; +static esp_netif_t * openthread_netif = NULL; +static esp_openthread_platform_config_t * s_platform_config = NULL; static esp_netif_t * init_openthread_netif(const esp_openthread_platform_config_t * config) { @@ -55,6 +55,11 @@ static void ot_task_worker(void * context) vTaskDelete(NULL); } +void set_openthread_platform_config(esp_openthread_platform_config_t * config) +{ + s_platform_config = config; +} + esp_err_t openthread_init_stack(void) { // Used eventfds: @@ -67,15 +72,11 @@ esp_err_t openthread_init_stack(void) ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_vfs_eventfd_register(&eventfd_config)); - esp_openthread_platform_config_t config = { - .radio_config = ESP_OPENTHREAD_DEFAULT_RADIO_CONFIG(), - .host_config = ESP_OPENTHREAD_DEFAULT_HOST_CONFIG(), - .port_config = ESP_OPENTHREAD_DEFAULT_PORT_CONFIG(), - }; + assert(s_platform_config); // Initialize the OpenThread stack - ESP_ERROR_CHECK(esp_openthread_init(&config)); + ESP_ERROR_CHECK(esp_openthread_init(s_platform_config)); // Initialize the esp_netif bindings - openthread_netif = init_openthread_netif(&config); + openthread_netif = init_openthread_netif(s_platform_config); return ESP_OK; } diff --git a/src/platform/ESP32/OpenthreadLauncher.h b/src/platform/ESP32/OpenthreadLauncher.h index c562bfa34220ec..6817a4dc5afb80 100644 --- a/src/platform/ESP32/OpenthreadLauncher.h +++ b/src/platform/ESP32/OpenthreadLauncher.h @@ -17,10 +17,14 @@ #pragma once +#include +#include + #ifdef __cplusplus extern "C" { #endif +void set_openthread_platform_config(esp_openthread_platform_config_t * config); esp_err_t openthread_init_stack(void); esp_err_t openthread_launch_task(void); From 6b99adbc3e82095f79822ba497bdb5a5fcd12842 Mon Sep 17 00:00:00 2001 From: weicheng Date: Tue, 13 Jun 2023 11:38:01 +0800 Subject: [PATCH 13/15] [ASR] add more examples (#26622) --- .github/workflows/examples-asr.yaml | 9 +- docs/guides/asr_getting_started_guide.md | 23 +- examples/all-clusters-app/asr/.gn | 29 + examples/all-clusters-app/asr/BUILD.gn | 135 +++++ examples/all-clusters-app/asr/README.md | 62 +++ examples/all-clusters-app/asr/args.gni | 27 + examples/all-clusters-app/asr/build_overrides | 1 + examples/all-clusters-app/asr/cfg.gni | 23 + .../all-clusters-app/asr/include/AppConfig.h | 60 +++ .../all-clusters-app/asr/include/AppEvent.h | 51 ++ .../all-clusters-app/asr/include/AppTask.h | 64 +++ .../asr/include/ButtonHandler.h | 53 ++ .../asr/include/CHIPProjectConfig.h | 92 ++++ .../asr/include/DeviceCallbacks.h | 47 ++ examples/all-clusters-app/asr/src/AppTask.cpp | 274 ++++++++++ .../asr/src/ButtonHandler.cpp | 117 ++++ .../asr/src/DeviceCallbacks.cpp | 276 ++++++++++ examples/all-clusters-app/asr/src/main.cpp | 86 +++ .../asr/third_party/connectedhomeip | 1 + examples/all-clusters-minimal-app/asr/.gn | 29 + .../all-clusters-minimal-app/asr/BUILD.gn | 134 +++++ .../all-clusters-minimal-app/asr/README.md | 54 ++ .../all-clusters-minimal-app/asr/args.gni | 27 + .../asr/build_overrides | 1 + examples/all-clusters-minimal-app/asr/cfg.gni | 23 + .../asr/include/AppConfig.h | 54 ++ .../asr/include/AppEvent.h | 51 ++ .../asr/include/AppTask.h | 65 +++ .../asr/include/CHIPProjectConfig.h | 92 ++++ .../asr/include/DeviceCallbacks.h | 44 ++ .../asr/src/AppTask.cpp | 230 ++++++++ .../asr/src/DeviceCallbacks.cpp | 180 +++++++ .../all-clusters-minimal-app/asr/src/main.cpp | 85 +++ .../asr/third_party/connectedhomeip | 1 + examples/bridge-app/asr/.gn | 29 + examples/bridge-app/asr/BUILD.gn | 134 +++++ examples/bridge-app/asr/README.md | 67 +++ examples/bridge-app/asr/args.gni | 27 + examples/bridge-app/asr/build_overrides | 1 + examples/bridge-app/asr/cfg.gni | 23 + examples/bridge-app/asr/include/AppConfig.h | 42 ++ examples/bridge-app/asr/include/AppTask.h | 44 ++ .../asr/include/CHIPProjectConfig.h | 118 ++++ .../bridge-app/asr/include/DeviceCallbacks.h | 42 ++ examples/bridge-app/asr/src/AppTask.cpp | 102 ++++ .../bridge-app/asr/src/DeviceCallbacks.cpp | 133 +++++ .../asr/src/bridged-actions-stub.cpp | 100 ++++ examples/bridge-app/asr/src/main.cpp | 76 +++ .../bridge-app/asr/subdevice/SubDevice.cpp | 154 ++++++ examples/bridge-app/asr/subdevice/SubDevice.h | 70 +++ .../asr/subdevice/SubDeviceManager.cpp | 269 +++++++++ .../asr/subdevice/SubDeviceManager.h | 77 +++ .../asr/subdevice/subdevice_test.cpp | 159 ++++++ .../asr/third_party/connectedhomeip | 1 + examples/light-switch-app/asr/.gn | 29 + examples/light-switch-app/asr/BUILD.gn | 136 +++++ examples/light-switch-app/asr/README.md | 52 ++ examples/light-switch-app/asr/args.gni | 27 + examples/light-switch-app/asr/build_overrides | 1 + examples/light-switch-app/asr/cfg.gni | 23 + .../light-switch-app/asr/include/AppConfig.h | 74 +++ .../light-switch-app/asr/include/AppEvent.h | 64 +++ .../light-switch-app/asr/include/AppTask.h | 88 +++ .../asr/include/BindingHandler.h | 62 +++ .../asr/include/ButtonHandler.h | 38 ++ .../asr/include/CHIPProjectConfig.h | 111 ++++ .../asr/include/DeviceCallbacks.h | 42 ++ .../light-switch-app/asr/include/LEDManager.h | 48 ++ .../asr/include/LightSwitch.h | 53 ++ examples/light-switch-app/asr/src/AppTask.cpp | 509 ++++++++++++++++++ .../asr/src/BindingHandler.cpp | 316 +++++++++++ .../asr/src/ButtonHandler.cpp | 122 +++++ .../asr/src/DeviceCallbacks.cpp | 147 +++++ .../light-switch-app/asr/src/LEDManager.cpp | 96 ++++ .../light-switch-app/asr/src/LightSwitch.cpp | 113 ++++ examples/light-switch-app/asr/src/main.cpp | 77 +++ .../asr/third_party/connectedhomeip | 1 + examples/lock-app/asr/.gn | 29 + examples/lock-app/asr/BUILD.gn | 131 +++++ examples/lock-app/asr/README.md | 56 ++ examples/lock-app/asr/args.gni | 27 + examples/lock-app/asr/build_overrides | 1 + examples/lock-app/asr/cfg.gni | 23 + examples/lock-app/asr/include/AppConfig.h | 83 +++ examples/lock-app/asr/include/AppEvent.h | 57 ++ examples/lock-app/asr/include/AppTask.h | 95 ++++ .../lock-app/asr/include/BoltLockManager.h | 84 +++ examples/lock-app/asr/include/ButtonHandler.h | 51 ++ .../lock-app/asr/include/CHIPProjectConfig.h | 112 ++++ .../lock-app/asr/include/DeviceCallbacks.h | 42 ++ examples/lock-app/asr/include/LEDManager.h | 47 ++ examples/lock-app/asr/src/AppTask.cpp | 497 +++++++++++++++++ examples/lock-app/asr/src/BoltLockManager.cpp | 225 ++++++++ examples/lock-app/asr/src/ButtonHandler.cpp | 100 ++++ examples/lock-app/asr/src/DeviceCallbacks.cpp | 162 ++++++ examples/lock-app/asr/src/LEDManager.cpp | 96 ++++ examples/lock-app/asr/src/main.cpp | 84 +++ .../lock-app/asr/third_party/connectedhomeip | 1 + examples/ota-requestor-app/asr/.gn | 29 + examples/ota-requestor-app/asr/BUILD.gn | 129 +++++ examples/ota-requestor-app/asr/README.md | 61 +++ examples/ota-requestor-app/asr/args.gni | 27 + .../ota-requestor-app/asr/build_overrides | 1 + examples/ota-requestor-app/asr/cfg.gni | 25 + .../ota-requestor-app/asr/include/AppConfig.h | 43 ++ .../ota-requestor-app/asr/include/AppTask.h | 44 ++ .../asr/include/CHIPProjectConfig.h | 109 ++++ .../asr/include/DeviceCallbacks.h | 42 ++ .../ota-requestor-app/asr/src/AppTask.cpp | 103 ++++ .../asr/src/DeviceCallbacks.cpp | 148 +++++ examples/ota-requestor-app/asr/src/main.cpp | 78 +++ .../asr/third_party/connectedhomeip | 1 + examples/temperature-measurement-app/asr/.gn | 29 + .../temperature-measurement-app/asr/BUILD.gn | 129 +++++ .../temperature-measurement-app/asr/README.md | 40 ++ .../temperature-measurement-app/asr/args.gni | 27 + .../asr/build_overrides | 1 + .../temperature-measurement-app/asr/cfg.gni | 23 + .../asr/include/AppConfig.h | 79 +++ .../asr/include/AppEvent.h | 57 ++ .../asr/include/AppTask.h | 65 +++ .../asr/include/CHIPProjectConfig.h | 109 ++++ .../asr/include/DeviceCallbacks.h | 42 ++ .../asr/src/AppTask.cpp | 104 ++++ .../asr/src/DeviceCallbacks.cpp | 143 +++++ .../asr/src/main.cpp | 84 +++ .../asr/third_party/connectedhomeip | 1 + examples/thermostat/asr/.gn | 29 + examples/thermostat/asr/BUILD.gn | 132 +++++ examples/thermostat/asr/README.md | 52 ++ examples/thermostat/asr/args.gni | 27 + examples/thermostat/asr/build_overrides | 1 + examples/thermostat/asr/cfg.gni | 23 + examples/thermostat/asr/include/AppConfig.h | 81 +++ examples/thermostat/asr/include/AppEvent.h | 71 +++ examples/thermostat/asr/include/AppTask.h | 73 +++ .../thermostat/asr/include/BindingHandler.h | 54 ++ .../thermostat/asr/include/CHIPClusters.h | 80 +++ .../asr/include/CHIPProjectConfig.h | 109 ++++ .../thermostat/asr/include/DeviceCallbacks.h | 42 ++ .../thermostat/asr/include/SensorManager.h | 46 ++ .../asr/include/TemperatureManager.h | 65 +++ examples/thermostat/asr/src/AppTask.cpp | 176 ++++++ .../thermostat/asr/src/DeviceCallbacks.cpp | 130 +++++ examples/thermostat/asr/src/SensorManager.cpp | 88 +++ .../thermostat/asr/src/TemperatureManager.cpp | 135 +++++ examples/thermostat/asr/src/main.cpp | 79 +++ .../asr/third_party/connectedhomeip | 1 + scripts/build/build/targets.py | 8 + scripts/build/builders/asr.py | 44 +- .../build/testdata/all_targets_linux_x64.txt | 2 +- 151 files changed, 11712 insertions(+), 9 deletions(-) create mode 100755 examples/all-clusters-app/asr/.gn create mode 100755 examples/all-clusters-app/asr/BUILD.gn create mode 100755 examples/all-clusters-app/asr/README.md create mode 100755 examples/all-clusters-app/asr/args.gni create mode 120000 examples/all-clusters-app/asr/build_overrides create mode 100755 examples/all-clusters-app/asr/cfg.gni create mode 100644 examples/all-clusters-app/asr/include/AppConfig.h create mode 100755 examples/all-clusters-app/asr/include/AppEvent.h create mode 100644 examples/all-clusters-app/asr/include/AppTask.h create mode 100644 examples/all-clusters-app/asr/include/ButtonHandler.h create mode 100755 examples/all-clusters-app/asr/include/CHIPProjectConfig.h create mode 100644 examples/all-clusters-app/asr/include/DeviceCallbacks.h create mode 100644 examples/all-clusters-app/asr/src/AppTask.cpp create mode 100644 examples/all-clusters-app/asr/src/ButtonHandler.cpp create mode 100644 examples/all-clusters-app/asr/src/DeviceCallbacks.cpp create mode 100644 examples/all-clusters-app/asr/src/main.cpp create mode 120000 examples/all-clusters-app/asr/third_party/connectedhomeip create mode 100755 examples/all-clusters-minimal-app/asr/.gn create mode 100755 examples/all-clusters-minimal-app/asr/BUILD.gn create mode 100755 examples/all-clusters-minimal-app/asr/README.md create mode 100755 examples/all-clusters-minimal-app/asr/args.gni create mode 120000 examples/all-clusters-minimal-app/asr/build_overrides create mode 100755 examples/all-clusters-minimal-app/asr/cfg.gni create mode 100644 examples/all-clusters-minimal-app/asr/include/AppConfig.h create mode 100755 examples/all-clusters-minimal-app/asr/include/AppEvent.h create mode 100755 examples/all-clusters-minimal-app/asr/include/AppTask.h create mode 100755 examples/all-clusters-minimal-app/asr/include/CHIPProjectConfig.h create mode 100755 examples/all-clusters-minimal-app/asr/include/DeviceCallbacks.h create mode 100644 examples/all-clusters-minimal-app/asr/src/AppTask.cpp create mode 100644 examples/all-clusters-minimal-app/asr/src/DeviceCallbacks.cpp create mode 100644 examples/all-clusters-minimal-app/asr/src/main.cpp create mode 120000 examples/all-clusters-minimal-app/asr/third_party/connectedhomeip create mode 100755 examples/bridge-app/asr/.gn create mode 100755 examples/bridge-app/asr/BUILD.gn create mode 100755 examples/bridge-app/asr/README.md create mode 100755 examples/bridge-app/asr/args.gni create mode 120000 examples/bridge-app/asr/build_overrides create mode 100755 examples/bridge-app/asr/cfg.gni create mode 100644 examples/bridge-app/asr/include/AppConfig.h create mode 100644 examples/bridge-app/asr/include/AppTask.h create mode 100755 examples/bridge-app/asr/include/CHIPProjectConfig.h create mode 100644 examples/bridge-app/asr/include/DeviceCallbacks.h create mode 100644 examples/bridge-app/asr/src/AppTask.cpp create mode 100644 examples/bridge-app/asr/src/DeviceCallbacks.cpp create mode 100755 examples/bridge-app/asr/src/bridged-actions-stub.cpp create mode 100644 examples/bridge-app/asr/src/main.cpp create mode 100644 examples/bridge-app/asr/subdevice/SubDevice.cpp create mode 100755 examples/bridge-app/asr/subdevice/SubDevice.h create mode 100644 examples/bridge-app/asr/subdevice/SubDeviceManager.cpp create mode 100644 examples/bridge-app/asr/subdevice/SubDeviceManager.h create mode 100644 examples/bridge-app/asr/subdevice/subdevice_test.cpp create mode 120000 examples/bridge-app/asr/third_party/connectedhomeip create mode 100755 examples/light-switch-app/asr/.gn create mode 100755 examples/light-switch-app/asr/BUILD.gn create mode 100755 examples/light-switch-app/asr/README.md create mode 100755 examples/light-switch-app/asr/args.gni create mode 120000 examples/light-switch-app/asr/build_overrides create mode 100755 examples/light-switch-app/asr/cfg.gni create mode 100644 examples/light-switch-app/asr/include/AppConfig.h create mode 100755 examples/light-switch-app/asr/include/AppEvent.h create mode 100755 examples/light-switch-app/asr/include/AppTask.h create mode 100755 examples/light-switch-app/asr/include/BindingHandler.h create mode 100644 examples/light-switch-app/asr/include/ButtonHandler.h create mode 100755 examples/light-switch-app/asr/include/CHIPProjectConfig.h create mode 100755 examples/light-switch-app/asr/include/DeviceCallbacks.h create mode 100644 examples/light-switch-app/asr/include/LEDManager.h create mode 100644 examples/light-switch-app/asr/include/LightSwitch.h create mode 100644 examples/light-switch-app/asr/src/AppTask.cpp create mode 100644 examples/light-switch-app/asr/src/BindingHandler.cpp create mode 100644 examples/light-switch-app/asr/src/ButtonHandler.cpp create mode 100644 examples/light-switch-app/asr/src/DeviceCallbacks.cpp create mode 100644 examples/light-switch-app/asr/src/LEDManager.cpp create mode 100644 examples/light-switch-app/asr/src/LightSwitch.cpp create mode 100644 examples/light-switch-app/asr/src/main.cpp create mode 120000 examples/light-switch-app/asr/third_party/connectedhomeip create mode 100755 examples/lock-app/asr/.gn create mode 100755 examples/lock-app/asr/BUILD.gn create mode 100755 examples/lock-app/asr/README.md create mode 100755 examples/lock-app/asr/args.gni create mode 120000 examples/lock-app/asr/build_overrides create mode 100755 examples/lock-app/asr/cfg.gni create mode 100644 examples/lock-app/asr/include/AppConfig.h create mode 100755 examples/lock-app/asr/include/AppEvent.h create mode 100755 examples/lock-app/asr/include/AppTask.h create mode 100755 examples/lock-app/asr/include/BoltLockManager.h create mode 100755 examples/lock-app/asr/include/ButtonHandler.h create mode 100755 examples/lock-app/asr/include/CHIPProjectConfig.h create mode 100755 examples/lock-app/asr/include/DeviceCallbacks.h create mode 100644 examples/lock-app/asr/include/LEDManager.h create mode 100644 examples/lock-app/asr/src/AppTask.cpp create mode 100755 examples/lock-app/asr/src/BoltLockManager.cpp create mode 100644 examples/lock-app/asr/src/ButtonHandler.cpp create mode 100644 examples/lock-app/asr/src/DeviceCallbacks.cpp create mode 100644 examples/lock-app/asr/src/LEDManager.cpp create mode 100755 examples/lock-app/asr/src/main.cpp create mode 120000 examples/lock-app/asr/third_party/connectedhomeip create mode 100755 examples/ota-requestor-app/asr/.gn create mode 100755 examples/ota-requestor-app/asr/BUILD.gn create mode 100755 examples/ota-requestor-app/asr/README.md create mode 100755 examples/ota-requestor-app/asr/args.gni create mode 120000 examples/ota-requestor-app/asr/build_overrides create mode 100755 examples/ota-requestor-app/asr/cfg.gni create mode 100644 examples/ota-requestor-app/asr/include/AppConfig.h create mode 100644 examples/ota-requestor-app/asr/include/AppTask.h create mode 100755 examples/ota-requestor-app/asr/include/CHIPProjectConfig.h create mode 100644 examples/ota-requestor-app/asr/include/DeviceCallbacks.h create mode 100644 examples/ota-requestor-app/asr/src/AppTask.cpp create mode 100644 examples/ota-requestor-app/asr/src/DeviceCallbacks.cpp create mode 100644 examples/ota-requestor-app/asr/src/main.cpp create mode 120000 examples/ota-requestor-app/asr/third_party/connectedhomeip create mode 100755 examples/temperature-measurement-app/asr/.gn create mode 100755 examples/temperature-measurement-app/asr/BUILD.gn create mode 100755 examples/temperature-measurement-app/asr/README.md create mode 100755 examples/temperature-measurement-app/asr/args.gni create mode 120000 examples/temperature-measurement-app/asr/build_overrides create mode 100755 examples/temperature-measurement-app/asr/cfg.gni create mode 100644 examples/temperature-measurement-app/asr/include/AppConfig.h create mode 100755 examples/temperature-measurement-app/asr/include/AppEvent.h create mode 100755 examples/temperature-measurement-app/asr/include/AppTask.h create mode 100755 examples/temperature-measurement-app/asr/include/CHIPProjectConfig.h create mode 100644 examples/temperature-measurement-app/asr/include/DeviceCallbacks.h create mode 100644 examples/temperature-measurement-app/asr/src/AppTask.cpp create mode 100644 examples/temperature-measurement-app/asr/src/DeviceCallbacks.cpp create mode 100755 examples/temperature-measurement-app/asr/src/main.cpp create mode 120000 examples/temperature-measurement-app/asr/third_party/connectedhomeip create mode 100755 examples/thermostat/asr/.gn create mode 100755 examples/thermostat/asr/BUILD.gn create mode 100755 examples/thermostat/asr/README.md create mode 100755 examples/thermostat/asr/args.gni create mode 120000 examples/thermostat/asr/build_overrides create mode 100755 examples/thermostat/asr/cfg.gni create mode 100644 examples/thermostat/asr/include/AppConfig.h create mode 100755 examples/thermostat/asr/include/AppEvent.h create mode 100644 examples/thermostat/asr/include/AppTask.h create mode 100644 examples/thermostat/asr/include/BindingHandler.h create mode 100644 examples/thermostat/asr/include/CHIPClusters.h create mode 100755 examples/thermostat/asr/include/CHIPProjectConfig.h create mode 100644 examples/thermostat/asr/include/DeviceCallbacks.h create mode 100644 examples/thermostat/asr/include/SensorManager.h create mode 100755 examples/thermostat/asr/include/TemperatureManager.h create mode 100644 examples/thermostat/asr/src/AppTask.cpp create mode 100644 examples/thermostat/asr/src/DeviceCallbacks.cpp create mode 100644 examples/thermostat/asr/src/SensorManager.cpp create mode 100644 examples/thermostat/asr/src/TemperatureManager.cpp create mode 100644 examples/thermostat/asr/src/main.cpp create mode 120000 examples/thermostat/asr/third_party/connectedhomeip diff --git a/.github/workflows/examples-asr.yaml b/.github/workflows/examples-asr.yaml index 7a5722cf2918c7..a8fd72fc3bfe28 100644 --- a/.github/workflows/examples-asr.yaml +++ b/.github/workflows/examples-asr.yaml @@ -64,7 +64,14 @@ jobs: run: | ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ + --target asr-asr582x-all-clusters \ + --target asr-asr582x-all-clusters-minimal \ --target asr-asr582x-lighting \ - --target asr-asr582x-lighting-ota \ + --target asr-asr582x-light-switch \ + --target asr-asr582x-lock \ + --target asr-asr582x-ota-requestor \ + --target asr-asr582x-bridge \ + --target asr-asr582x-temperature-measurement \ + --target asr-asr582x-thermostat \ build \ " \ No newline at end of file diff --git a/docs/guides/asr_getting_started_guide.md b/docs/guides/asr_getting_started_guide.md index fa86dfda279328..6d6b15230faf4d 100644 --- a/docs/guides/asr_getting_started_guide.md +++ b/docs/guides/asr_getting_started_guide.md @@ -14,6 +14,7 @@ platform that uses ASR FreeRTOS SDK. - [IP mode](#ip-mode) - [Shell](#shell) - [OTA](#ota) + - [Factory](#factory) --- @@ -72,7 +73,8 @@ to speed up development. You can find them in the samples with `/asr` subfolder. `--target` when build the examples. - After building the application, `DOGO` tool is used to flash it to the - board. + board, please refer to the + [DOGO Tool User Guide](https://asriot.readthedocs.io/en/latest/ASR550X/Download-Tool/ASR_IoT_DOGO_Tool_User_Guide.html). ## Commissioning @@ -128,7 +130,18 @@ There are two commissioning modes supported by ASR platform: ## OTA -To build the example with the Matter OTA Requestor functionality, exactly the -same steps as above but add argument `-ota` when using the `build_examples.py` -script. For example: -`./scripts/build/build_examples.py --target asr-$ASR_BOARD-lighting-ota build` +1. To build the example with the Matter OTA Requestor functionality, exactly the + same steps as above but add argument `-ota` when using the + `build_examples.py` script. For example: + `./scripts/build/build_examples.py --target asr-$ASR_BOARD-lighting-ota build` +2. For more usage details, please refer to the + [OTA example](../../examples/ota-requestor-app/asr/README.md) + +## Factory + +1. To build the example with the ASR Factory Data Provider, exactly the same + steps as above but add argument `-factory` when using the `build_examples.py` + script. For example: + `./scripts/build/build_examples.py --target asr-$ASR_BOARD-lighting-factory build` +2. For more usage details, please refer to the + [Factory Tool User Guide](https://github.com/asriot/Tools/blob/main/factory_tool/README.md) diff --git a/examples/all-clusters-app/asr/.gn b/examples/all-clusters-app/asr/.gn new file mode 100755 index 00000000000000..8d75f1eafcdb89 --- /dev/null +++ b/examples/all-clusters-app/asr/.gn @@ -0,0 +1,29 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/all-clusters-app/asr/BUILD.gn b/examples/all-clusters-app/asr/BUILD.gn new file mode 100755 index 00000000000000..d639d658589519 --- /dev/null +++ b/examples/all-clusters-app/asr/BUILD.gn @@ -0,0 +1,135 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/asr.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("${asr_sdk_build_root}/asr_sdk.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/src/lib/lib.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/asr/asr_executable.gni") + +import("cfg.gni") + +assert(current_os == "freertos") + +asr_project_dir = "${chip_root}/examples/all-clusters-app/asr" +examples_plat_dir = "${chip_root}/examples/platform/asr" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + +asr_sdk_sources("all_clusters_app_sdk_sources") { + include_dirs = [ + "${chip_root}/src/platform/ASR", + "${asr_project_dir}/include", + "${examples_plat_dir}", + ] + + defines = [ + "ASR_LOG_ENABLED=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + ] + + if (chip_enable_factory_data) { + defines += [ + "CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER=1", + "CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER=1", + ] + } + + if (chip_lwip_ip6_hook) { + defines += [ + "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", + "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", + ] + } + + sources = [ "${asr_project_dir}/include/CHIPProjectConfig.h" ] + + public_configs = [ "${asr_sdk_build_root}:asr_sdk_config" ] +} + +asr_executable("clusters_app") { + include_dirs = [] + defines = [] + output_name = "chip-asr-clusters-example.out" + + sources = [ + "${chip_root}/examples/all-clusters-app/all-clusters-common/src/bridged-actions-stub.cpp", + "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", + "${examples_plat_dir}/CHIPDeviceManager.cpp", + "${examples_plat_dir}/LEDWidget.cpp", + "${examples_plat_dir}/init_Matter.cpp", + "${examples_plat_dir}/init_asrPlatform.cpp", + "${examples_plat_dir}/shell/matter_shell.cpp", + "src/AppTask.cpp", + "src/ButtonHandler.cpp", + "src/DeviceCallbacks.cpp", + "src/main.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${examples_plat_dir}/init_OTARequestor.cpp" ] + } + + deps = [ + ":all_clusters_app_sdk_sources", + "${chip_root}/examples/all-clusters-app/all-clusters-common", + "${chip_root}/examples/common/QRCode", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs += [ + "include", + "${examples_plat_dir}", + "${asr_project_dir}/include", + "${chip_root}/examples/all-clusters-app/all-clusters-common/include", + "${chip_root}/src", + "${chip_root}/src/lib", + "${chip_root}/src/lib/support", + "${chip_root}/src/app/util", + ] + + defines = [ "ASR_NETWORK_LAYER_BLE=${chip_config_network_layer_ble}" ] + + if (chip_build_libshell) { + defines += [ "CONFIG_ENABLE_CHIP_SHELL=1" ] + sources += [ "${examples_plat_dir}/shell/launch_shell.cpp" ] + include_dirs += [ "${examples_plat_dir}/shell" ] + } + + if (chip_print_memory_usage) { + ldflags += [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } + + output_dir = root_out_dir +} + +group("asr") { + deps = [ ":clusters_app" ] +} + +group("default") { + deps = [ ":asr" ] +} diff --git a/examples/all-clusters-app/asr/README.md b/examples/all-clusters-app/asr/README.md new file mode 100755 index 00000000000000..287da141fc0e24 --- /dev/null +++ b/examples/all-clusters-app/asr/README.md @@ -0,0 +1,62 @@ +# Matter ASR All Clusters Example + +A prototype application that demonstrates device commissioning and cluster +control on ASR platform. + +--- + +- [Matter ASR All Clusters Example](#matter-asr-all-clusters-example) + - [Supported Chips](#supported-chips) + - [Building and Commissioning](#building-and-commissioning) + - [Cluster Control](#cluster-control) + - [Light switch press button and light status LED](#light-switch-press-button-and-light-status-led) + +--- + +## Supported Chips + +The Matter demo application is supported on: + +- ASR582X +- ASR595X + +## Building and Commissioning + +Please refer +[Building and Commissioning](../../../docs/guides/asr_getting_started_guide.md#building-the-example-application) +guides to get started + +``` +./scripts/build/build_examples.py --target asr-$ASR_BOARD-all-clusters build +``` + +## Cluster Control + +After successful commissioning, use `chip-tool` to control the board + +For example, read sensor measured value: + +``` +./chip-tool temperaturemeasurement read measured-value 1 +./chip-tool relativehumiditymeasurement read measured-value 1 +./chip-tool pressuremeasurement read measured-value 1 +``` + +Or,control the OnOff Cluster attribute: + +``` +./chip-tool onoff read on-off 1 +./chip-tool onoff on 1 +./chip-tool onoff off 1 +./chip-tool onoff toggle 1 +``` + +## Light switch press button and light status LED + +This demo uses button to test changing the light states and LED to show the +state of these changes. + +| Name | Pin | +| :----: | :---: | +| LED | PAD6 | +| BUTTON | PAD12 | diff --git a/examples/all-clusters-app/asr/args.gni b/examples/all-clusters-app/asr/args.gni new file mode 100755 index 00000000000000..66a2de849083d4 --- /dev/null +++ b/examples/all-clusters-app/asr/args.gni @@ -0,0 +1,27 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("//cfg.gni") +import("${chip_root}/src/platform/ASR/args.gni") + +asr_target_project = + get_label_info(":all_clusters_app_sdk_sources", "label_no_toolchain") + +declare_args() { + # Disable lock tracking, since our FreeRTOS configuration does not set + # INCLUDE_xSemaphoreGetMutexHolder + chip_stack_lock_tracking = "none" +} diff --git a/examples/all-clusters-app/asr/build_overrides b/examples/all-clusters-app/asr/build_overrides new file mode 120000 index 00000000000000..194ee0b812dc3d --- /dev/null +++ b/examples/all-clusters-app/asr/build_overrides @@ -0,0 +1 @@ +../../build_overrides/ \ No newline at end of file diff --git a/examples/all-clusters-app/asr/cfg.gni b/examples/all-clusters-app/asr/cfg.gni new file mode 100755 index 00000000000000..15fe50e79efb6d --- /dev/null +++ b/examples/all-clusters-app/asr/cfg.gni @@ -0,0 +1,23 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + chip_enable_factory_data = false + + chip_lwip_ip6_hook = false + + setupPinCode = 20202021 + + setupDiscriminator = 3840 +} diff --git a/examples/all-clusters-app/asr/include/AppConfig.h b/examples/all-clusters-app/asr/include/AppConfig.h new file mode 100644 index 00000000000000..40abc79020f59e --- /dev/null +++ b/examples/all-clusters-app/asr/include/AppConfig.h @@ -0,0 +1,60 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// ---- Lighting Example App Config ---- + +#define APP_TASK_NAME "APP" + +#define APP_EVENT_QUEUE_SIZE 10 +#define APP_TASK_STACK_SIZE (1024 * 4) +#define APP_WAIT_LOOP 1000 + +#define MATTER_DEVICE_NAME "ASR-Clusters" + +#define GPIO_TASK_NAME "gpio" +#define GPIO_TASK_STACK_SIZE 1024 + +#define APP_BUTTON_PRESSED 0 +#define APP_BUTTON_RELEASED 1 + +#define SWITCH1_BUTTON GPIO12_INDEX +#define SWITCH2_BUTTON GPIO13_INDEX + +#define LIGHT1_LED PWM_OUTPUT_CH4 +#define LIGHT2_LED PWM_OUTPUT_CH6 + +// Time it takes in ms for the simulated actuator to move from one +// state to another. +#define ACTUATOR_MOVEMENT_PERIOS_MS 2000 + +// ASR Logging +#ifdef __cplusplus +extern "C" { +#endif + +void appError(int err); +void ASR_LOG(const char * aFormat, ...); + +#ifdef __cplusplus +} + +#include +void appError(CHIP_ERROR error); +#endif diff --git a/examples/all-clusters-app/asr/include/AppEvent.h b/examples/all-clusters-app/asr/include/AppEvent.h new file mode 100755 index 00000000000000..2c59845f3bb577 --- /dev/null +++ b/examples/all-clusters-app/asr/include/AppEvent.h @@ -0,0 +1,51 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 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. + */ + +#pragma once +#include + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +struct AppEvent +{ + enum AppEventTypes + { + kEventType_Button = 0, + kEventType_Timer, + kEventType_Light, + kEventType_Install, + }; + + uint16_t Type; + + union + { + struct + { + uint8_t ButtonIdx; + uint8_t Action; + } ButtonEvent; + struct + { + void * Context; + } TimerEvent; + }; + + EventHandler Handler; +}; diff --git a/examples/all-clusters-app/asr/include/AppTask.h b/examples/all-clusters-app/asr/include/AppTask.h new file mode 100644 index 00000000000000..184e309af5eeba --- /dev/null +++ b/examples/all-clusters-app/asr/include/AppTask.h @@ -0,0 +1,64 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "AppEvent.h" +#include +#include +#include +#include +#include + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) + +class AppTask +{ + +public: + CHIP_ERROR StartAppTask(); + static void AppTaskMain(void * pvParameter); + static void AppEventHandler(AppEvent * aEvent); + void PostButtonEvent(uint8_t btnIdx, uint8_t btnAction); + void PostEvent(const AppEvent * event); + /** + * Use internally for registration of the ChipDeviceEvents + */ + static void CommonDeviceEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + +private: + friend AppTask & GetAppTask(void); + + CHIP_ERROR Init(); + + static AppTask sAppTask; + static void AppTimerCallback(void * params); + void DispatchEvent(AppEvent * event); + static void OnOffUpdateClusterState(void); +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/all-clusters-app/asr/include/ButtonHandler.h b/examples/all-clusters-app/asr/include/ButtonHandler.h new file mode 100644 index 00000000000000..621459d464c322 --- /dev/null +++ b/examples/all-clusters-app/asr/include/ButtonHandler.h @@ -0,0 +1,53 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "AppEvent.h" +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include +#ifdef CFG_PLF_RV32 +#include "asr_gpio.h" +#else +#include "duet_gpio.h" +#endif + +class ButtonHandler +{ +public: + static void Init(void); + + struct KeyInformation + { + uint8_t keyDown; + uint8_t keyImPulse; + uint8_t keyReleasePulse; + }; + + static KeyInformation keyInfo; + + static ButtonHandler & GetInstance() + { + static ButtonHandler sButtonHandler; + return sButtonHandler; + } + +private: + static void GpioInit(void); +}; diff --git a/examples/all-clusters-app/asr/include/CHIPProjectConfig.h b/examples/all-clusters-app/asr/include/CHIPProjectConfig.h new file mode 100755 index 00000000000000..6a81ee6517aedb --- /dev/null +++ b/examples/all-clusters-app/asr/include/CHIPProjectConfig.h @@ -0,0 +1,92 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 +#define CHIP_CONFIG_REQUIRE_AUTH 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a version of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 1 +#endif + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) diff --git a/examples/all-clusters-app/asr/include/DeviceCallbacks.h b/examples/all-clusters-app/asr/include/DeviceCallbacks.h new file mode 100644 index 00000000000000..d30939cd28b424 --- /dev/null +++ b/examples/all-clusters-app/asr/include/DeviceCallbacks.h @@ -0,0 +1,47 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.h + * + * Implementations for the DeviceManager callbacks for this application + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include +#include +#include + +class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks +{ +public: + void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg) override; + void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value) override; + +private: + void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); + void OnOnOffPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); + void OnLevelPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint16_t size, + uint8_t * value); + void OnColorPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); + void OnIdentifyPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); +}; diff --git a/examples/all-clusters-app/asr/src/AppTask.cpp b/examples/all-clusters-app/asr/src/AppTask.cpp new file mode 100644 index 00000000000000..d55ef713dde3f2 --- /dev/null +++ b/examples/all-clusters-app/asr/src/AppTask.cpp @@ -0,0 +1,274 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * Copyright 2021, Cypress Semiconductor Corporation (an Infineon company) + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" +#include "AppConfig.h" +#include "AppEvent.h" +#include "ButtonHandler.h" +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include "LEDWidget.h" +#include "init_Matter.h" +#include "qrcodegen.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; + +LEDWidget sStatusLED; +LEDWidget sLightLED; + +namespace { +lega_thread_t sAppTaskHandle; +lega_queue_t sAppEventQueue; +lega_timer_t sAppTimer; + +constexpr EndpointId kNetworkCommissioningEndpointMain = 0; +constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; + +app::Clusters::NetworkCommissioning::Instance + sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, + &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); +} // namespace + +AppTask AppTask::sAppTask; + +void NetWorkCommissioningInstInit() +{ + sWiFiNetworkCommissioningInstance.Init(); + + // We only have network commissioning on endpoint 0. + emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); +} + +static DeviceCallbacks EchoCallbacks; + +CHIP_ERROR AppTask::StartAppTask() +{ + CHIP_ERROR err = CHIP_NO_ERROR; + OSStatus status; + + status = lega_rtos_init_queue(&sAppEventQueue, "EventQueue", sizeof(AppEvent), APP_EVENT_QUEUE_SIZE); + + VerifyOrExit(status == kNoErr, err = CHIP_ERROR_NO_MEMORY); + + status = lega_rtos_init_timer(&sAppTimer, 3000, (timer_handler_t) AppTimerCallback, (void *) this); + + VerifyOrExit(status == kNoErr, err = CHIP_ERROR_NO_MEMORY); + + status = lega_rtos_create_thread(&sAppTaskHandle, 2, APP_TASK_NAME, (lega_thread_function_t) AppTaskMain, APP_TASK_STACK_SIZE, + (lega_thread_arg_t) this); + + VerifyOrExit(status == kNoErr, err = APP_ERROR_CREATE_TASK_FAILED); + +exit: + return err; +} + +CHIP_ERROR AppTask::Init() +{ + ASR_LOG("App Task started"); + + if (MatterInitializer::Init_Matter_Stack(MATTER_DEVICE_NAME) != CHIP_NO_ERROR) + return CHIP_ERROR_INTERNAL; + + CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); + + if (deviceMgr.Init(&EchoCallbacks) != CHIP_NO_ERROR) + return CHIP_ERROR_INTERNAL; + + if (MatterInitializer::Init_Matter_Server() != CHIP_NO_ERROR) + return CHIP_ERROR_INTERNAL; + + NetWorkCommissioningInstInit(); + + ASR_LOG("Current Software Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + ConfigurationMgr().LogDeviceConfig(); + + // Print setup info + PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); + + return CHIP_NO_ERROR; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + AppEvent event; + CHIP_ERROR err = sAppTask.Init(); + + ButtonHandler::Init(); + + sLightLED.Init(LIGHT1_LED); // embedded board light + sStatusLED.Init(LIGHT2_LED); + + lega_rtos_start_timer(&sAppTimer); + + if (err != CHIP_NO_ERROR) + { + ASR_LOG("AppTask.Init() failed"); + appError(err); + } + + while (true) + { + /* Check the event queue. */ + if (lega_rtos_is_queue_empty(&sAppEventQueue)) + { + lega_rtos_delay_milliseconds(1); + continue; + } + + /* Pop one event from the event queue. */ + lega_rtos_pop_from_queue(&sAppEventQueue, &event, LEGA_WAIT_FOREVER); + + sAppTask.DispatchEvent(&event); + } +} + +void AppTask::AppEventHandler(AppEvent * aEvent) +{ + static char lightState; + int16_t temperature = 2550; + int16_t humidity = 5000; + int16_t pressure = 1234; + + switch (aEvent->Type) + { + case AppEvent::kEventType_Timer: { + chip::app::Clusters::TemperatureMeasurement::Attributes::MeasuredValue::Set( + /* endpoint ID */ 1, /* temperature in 0.01*C */ int16_t(temperature)); + + chip::app::Clusters::RelativeHumidityMeasurement::Attributes::MeasuredValue::Set( + /* endpoint ID */ 1, /* humidity in 0.01% */ int16_t(humidity)); + + chip::app::Clusters::PressureMeasurement::Attributes::MeasuredValue::Set( + /* endpoint ID */ 1, /* pressure in 0.01 */ int16_t(pressure)); + + break; + } + + case AppEvent::kEventType_Button: { + lightState = !lightState; + /* ON/OFF Light Led based on Button interrupt */ + if (lightState) + { + sLightLED.Set(1); + sLightLED.SetBrightness(100); + } + else + { + sLightLED.Set(0); + } + + /* Update OnOff Cluster state */ + sAppTask.OnOffUpdateClusterState(); + break; + } + + default: + break; + } +} + +void AppTask::AppTimerCallback(void * params) +{ + AppEvent timer_event = {}; + timer_event.Type = AppEvent::kEventType_Timer; + timer_event.TimerEvent.Context = nullptr; + + timer_event.Handler = AppEventHandler; + sAppTask.PostEvent(&timer_event); +} + +void AppTask::PostButtonEvent(uint8_t btnIdx, uint8_t btnAction) +{ + ASR_LOG("%s %s\n", btnIdx == SWITCH1_BUTTON ? "btn1" : "btn2", btnAction == APP_BUTTON_PRESSED ? "Pressed" : "Released"); + + if (btnIdx != SWITCH1_BUTTON && btnIdx != SWITCH2_BUTTON) + { + return; + } + + AppEvent button_event = {}; + button_event.Type = AppEvent::kEventType_Button; + button_event.ButtonEvent.ButtonIdx = btnIdx; + button_event.ButtonEvent.Action = btnAction; + + if (btnAction == APP_BUTTON_RELEASED) + { + button_event.Handler = AppEventHandler; + sAppTask.PostEvent(&button_event); + } +} + +void AppTask::PostEvent(const AppEvent * aEvent) +{ + OSStatus status = lega_rtos_push_to_queue(&sAppEventQueue, const_cast(aEvent), LEGA_NO_WAIT); + if (kNoErr != status) + { + ASR_LOG("Post event failed."); + } +} + +void AppTask::DispatchEvent(AppEvent * aEvent) +{ + if (aEvent->Handler) + { + aEvent->Handler(aEvent); + } + else + { + ASR_LOG("Event received with no handler. Dropping event."); + } +} + +void AppTask::OnOffUpdateClusterState(void) +{ + uint8_t onoff = sLightLED.Get(); + + // write the new on/off value + EmberAfStatus status = app::Clusters::OnOff::Attributes::OnOff::Set(1, onoff); + + if (status != EMBER_ZCL_STATUS_SUCCESS) + { + ASR_LOG("ERR: updating on/off %x", status); + } +} + +bool lowPowerClusterSleep() +{ + return true; +} diff --git a/examples/all-clusters-app/asr/src/ButtonHandler.cpp b/examples/all-clusters-app/asr/src/ButtonHandler.cpp new file mode 100644 index 00000000000000..1faa7f7f56fbe1 --- /dev/null +++ b/examples/all-clusters-app/asr/src/ButtonHandler.cpp @@ -0,0 +1,117 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ButtonHandler.h" +#include "AppConfig.h" +#include "AppTask.h" +#include + +#ifdef CFG_PLF_RV32 +#define duet_gpio_dev_t asr_gpio_dev_t +#define duet_gpio_init asr_gpio_init +#define duet_gpio_input_get asr_gpio_input_get +#define DUET_INPUT_PULL_UP ASR_INPUT_PULL_UP +#endif + +TaskHandle_t sGpioTaskHandle; +ButtonHandler::KeyInformation ButtonHandler::keyInfo = { 0 }; + +static void GpioTaskMain(void * pvParameter); + +void ButtonHandler::Init(void) +{ + GpioInit(); + + xTaskCreate(GpioTaskMain, GPIO_TASK_NAME, GPIO_TASK_STACK_SIZE, 0, 2, &sGpioTaskHandle); +} + +// port pin +duet_gpio_dev_t switch1_btn; +duet_gpio_dev_t switch2_btn; + +void ButtonHandler::GpioInit(void) +{ + // light switch1 button + switch1_btn.port = SWITCH1_BUTTON; + switch1_btn.config = DUET_INPUT_PULL_UP; + switch1_btn.priv = NULL; + duet_gpio_init(&switch1_btn); + + switch2_btn.port = SWITCH2_BUTTON; + switch2_btn.config = DUET_INPUT_PULL_UP; + switch2_btn.priv = NULL; + duet_gpio_init(&switch2_btn); +} + +void GpioTaskMain(void * pvParameter) +{ + ASR_LOG("GPIO Task started"); + uint32_t btnValue; + uint8_t currentKeys = 0; + + for (;;) + { + vTaskDelay(50 / portTICK_PERIOD_MS); + + duet_gpio_input_get(&switch1_btn, &btnValue); + + if (!btnValue) + { + currentKeys |= 0x01; + } + else + { + currentKeys &= ~0x01; + } + + duet_gpio_input_get(&switch2_btn, &btnValue); + + if (!btnValue) + { + currentKeys |= 0x02; + } + else + { + currentKeys &= ~0x02; + } + + ButtonHandler::keyInfo.keyImPulse = (ButtonHandler::keyInfo.keyDown ^ currentKeys) & ~ButtonHandler::keyInfo.keyDown; + ButtonHandler::keyInfo.keyReleasePulse = (ButtonHandler::keyInfo.keyDown ^ currentKeys) & ButtonHandler::keyInfo.keyDown; + ButtonHandler::keyInfo.keyDown = currentKeys; + + if (ButtonHandler::keyInfo.keyImPulse & 0x01) + { + GetAppTask().PostButtonEvent(SWITCH1_BUTTON, APP_BUTTON_PRESSED); + } + + if (ButtonHandler::keyInfo.keyImPulse & 0x02) + { + GetAppTask().PostButtonEvent(SWITCH2_BUTTON, APP_BUTTON_PRESSED); + } + + if (ButtonHandler::keyInfo.keyReleasePulse & 0x01) + { + GetAppTask().PostButtonEvent(SWITCH1_BUTTON, APP_BUTTON_RELEASED); + } + + if (ButtonHandler::keyInfo.keyReleasePulse & 0x02) + { + GetAppTask().PostButtonEvent(SWITCH2_BUTTON, APP_BUTTON_RELEASED); + } + } +} diff --git a/examples/all-clusters-app/asr/src/DeviceCallbacks.cpp b/examples/all-clusters-app/asr/src/DeviceCallbacks.cpp new file mode 100644 index 00000000000000..7b284250787382 --- /dev/null +++ b/examples/all-clusters-app/asr/src/DeviceCallbacks.cpp @@ -0,0 +1,276 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.cpp + * + * Implements all the callbacks to the application from the CHIP Stack + * + **/ +#include "DeviceCallbacks.h" + +#include "CHIPDeviceManager.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "LEDWidget.h" +#include "init_OTARequestor.h" +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT +#include "route_hook/asr_route_hook.h" +#endif + +static const char * TAG = "app-devicecallbacks"; + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::System; +using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceManager; +using namespace ::chip::Logging; + +extern LEDWidget sLightLED; +extern LEDWidget sStatusLED; + +uint32_t identifyTimerCount; +constexpr uint32_t kIdentifyTimerDelayMS = 250; + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +constexpr uint32_t kInitOTARequestorDelaySec = 3; + +void InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +{ + OTAInitializer::Instance().InitOTARequestor(); +} +#endif +void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + switch (event->Type) + { + case DeviceEventType::kInternetConnectivityChange: + OnInternetConnectivityChange(event); + break; + + case DeviceEventType::kInterfaceIpAddressChanged: + if ((event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned) || + (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned)) + { + // MDNS server restart on any ip assignment: if link local ipv6 is configured, that + // will not trigger a 'internet connectivity change' as there is no internet + // connectivity. MDNS still wants to refresh its listening interfaces to include the + // newly selected address. + chip::app::DnssdServer::Instance().StartServer(); + + if (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned) + { +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT + ChipLogProgress(NotSpecified, "Initializing route hook..."); + asr_route_hook_init(); +#endif + } + } + break; + } +} + +void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t type, + uint16_t size, uint8_t * value) +{ + switch (clusterId) + { + case app::Clusters::OnOff::Id: + OnOnOffPostAttributeChangeCallback(endpointId, attributeId, value); + break; + + case app::Clusters::Identify::Id: + OnIdentifyPostAttributeChangeCallback(endpointId, attributeId, value); + break; + + default: + break; + } +} + +void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + static bool isOTAInitialized = false; +#endif + if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv4 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); + } + else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv4 connectivity..."); + } + if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv6 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Init OTA requestor only when we have gotten IPv6 address + if (!isOTAInitialized) + { + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec), + InitOTARequestorHandler, nullptr); + isOTAInitialized = true; + } +#endif + } + else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv6 connectivity..."); + } +} + +void DeviceCallbacks::OnOnOffPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) +{ + VerifyOrExit(attributeId == chip::app::Clusters::OnOff::Attributes::OnOff::Id, + ChipLogError(DeviceLayer, TAG, "Unhandled Attribute ID: '0x%04x", attributeId)); + VerifyOrExit(endpointId == 1 || endpointId == 2, + ChipLogError(DeviceLayer, TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId)); + + switch (attributeId) + { + case chip::app::Clusters::OnOff::Attributes::OnOff::Id: { + ChipLogProgress(Zcl, "ON/OFF level: %u ", *value); + // At this point we can assume that value points to a bool value. + sLightLED.Set(*value); + } + break; + + case chip::app::Clusters::OnOff::Attributes::OnTime::Id: + case chip::app::Clusters::OnOff::Attributes::OffWaitTime::Id: + case chip::app::Clusters::OnOff::Attributes::StartUpOnOff::Id: + case chip::app::Clusters::OnOff::Attributes::GlobalSceneControl::Id: { + ChipLogProgress(Zcl, "Unprocessed attribute ID: %" PRIx32, attributeId); + } + break; + + default: + ChipLogProgress(Zcl, "Unknown attribute ID: %" PRIx32, attributeId); + return; + } // switch (attributeId) +exit: + return; +} + +void DeviceCallbacks::OnLevelPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint16_t size, + uint8_t * value) +{ + switch (attributeId) + { + case chip::app::Clusters::LevelControl::Attributes::CurrentLevel::Id: { + if (size == 1) + { + uint8_t tmp = *value; + ChipLogProgress(Zcl, "New level: %u ", tmp); + sLightLED.SetBrightness(tmp); + } + else + { + ChipLogError(Zcl, "wrong length for level: %d\n", size); + } + } + break; + + case chip::app::Clusters::LevelControl::Attributes::MinLevel::Id: + case chip::app::Clusters::LevelControl::Attributes::MaxLevel::Id: + case chip::app::Clusters::LevelControl::Attributes::CurrentFrequency::Id: + case chip::app::Clusters::LevelControl::Attributes::MinFrequency::Id: + case chip::app::Clusters::LevelControl::Attributes::MaxFrequency::Id: + case chip::app::Clusters::LevelControl::Attributes::Options::Id: + case chip::app::Clusters::LevelControl::Attributes::OnOffTransitionTime::Id: + case chip::app::Clusters::LevelControl::Attributes::OnLevel::Id: + case chip::app::Clusters::LevelControl::Attributes::OnTransitionTime::Id: + case chip::app::Clusters::LevelControl::Attributes::OffTransitionTime::Id: + case chip::app::Clusters::LevelControl::Attributes::DefaultMoveRate::Id: + case chip::app::Clusters::LevelControl::Attributes::StartUpCurrentLevel::Id: { + ChipLogProgress(Zcl, "Unprocessed attribute ID: %" PRIx32, attributeId); + } + break; + + default: + ChipLogProgress(Zcl, "Unknown attribute ID: %" PRIx32, attributeId); + return; + + } // switch (attributeId) +} + +void DeviceCallbacks::OnColorPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) +{ + using namespace app::Clusters::ColorControl::Attributes; + + uint8_t hue, saturation; + + if ((attributeId != CurrentHue::Id) && (attributeId != CurrentSaturation::Id)) + { + ChipLogProgress(Zcl, "Unknown attribute ID: %" PRIx32, attributeId); + return; + } + + if (attributeId == CurrentHue::Id) + { + hue = *value; + CurrentSaturation::Get(endpointId, &saturation); + } + if (attributeId == CurrentSaturation::Id) + { + saturation = *value; + CurrentHue::Get(endpointId, &hue); + } + + ChipLogProgress(Zcl, "New hue: %d, New saturation: %d ", hue, saturation); +} + +void IdentifyTimerHandler(Layer * systemLayer, void * appState) +{ + if (identifyTimerCount) + { + systemLayer->StartTimer(Clock::Milliseconds32(kIdentifyTimerDelayMS), IdentifyTimerHandler, appState); + identifyTimerCount--; + } +} + +void DeviceCallbacks::OnIdentifyPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) +{ + VerifyOrExit(attributeId == chip::app::Clusters::Identify::Attributes::IdentifyTime::Id, + ChipLogError(DeviceLayer, "[%s] Unhandled Attribute ID: '0x%04lx", TAG, attributeId)); + VerifyOrExit(endpointId == 1, ChipLogError(DeviceLayer, "[%s] Unexpected EndPoint ID: `0x%02x'", TAG, endpointId)); + + // timerCount represents the number of callback executions before we stop the timer. + // value is expressed in seconds and the timer is fired every 250ms, so just multiply value by 4. + // Also, we want timerCount to be odd number, so the ligth state ends in the same state it starts. + identifyTimerCount = (*value) * 4; + + DeviceLayer::SystemLayer().CancelTimer(IdentifyTimerHandler, this); + DeviceLayer::SystemLayer().StartTimer(Clock::Milliseconds32(kIdentifyTimerDelayMS), IdentifyTimerHandler, this); +exit: + return; +} diff --git a/examples/all-clusters-app/asr/src/main.cpp b/examples/all-clusters-app/asr/src/main.cpp new file mode 100644 index 00000000000000..98048869353676 --- /dev/null +++ b/examples/all-clusters-app/asr/src/main.cpp @@ -0,0 +1,86 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * Copyright 2021, Cypress Semiconductor Corporation (an Infineon company) + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include +#include + +#include +#include + +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include +#include +#include +#include + +#include + +#include "AppConfig.h" +#include "init_asrPlatform.h" +#include + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; +// ================================================================================ +// App Error +//================================================================================= +void appError(int err) +{ + ASR_LOG("!!!!!!!!!!!! App Critical Error: %d !!!!!!!!!!!", err); + lega_rtos_declare_critical(); + lega_rtos_enter_critical(); + while (1) + ; +} + +void appError(CHIP_ERROR error) +{ + appError(static_cast(error.AsInteger())); +} +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + init_asrPlatform(); + + CHIP_ERROR ret = GetAppTask().StartAppTask(); + if (ret != CHIP_NO_ERROR) + { + ASR_LOG("GetAppTask().Init() failed"); + appError(ret); + } + /* Start the FreeRTOS scheduler */ + vTaskStartScheduler(); + + chip::Platform::MemoryShutdown(); + PlatformMgr().StopEventLoopTask(); + PlatformMgr().Shutdown(); + + // Should never get here. + ASR_LOG("vTaskStartScheduler() failed"); + appError(ret); +} diff --git a/examples/all-clusters-app/asr/third_party/connectedhomeip b/examples/all-clusters-app/asr/third_party/connectedhomeip new file mode 120000 index 00000000000000..11a54ed360106c --- /dev/null +++ b/examples/all-clusters-app/asr/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../ \ No newline at end of file diff --git a/examples/all-clusters-minimal-app/asr/.gn b/examples/all-clusters-minimal-app/asr/.gn new file mode 100755 index 00000000000000..8d75f1eafcdb89 --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/.gn @@ -0,0 +1,29 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/all-clusters-minimal-app/asr/BUILD.gn b/examples/all-clusters-minimal-app/asr/BUILD.gn new file mode 100755 index 00000000000000..752062a9b96ebf --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/BUILD.gn @@ -0,0 +1,134 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/asr.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("${asr_sdk_build_root}/asr_sdk.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/src/lib/lib.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/asr/asr_executable.gni") + +import("cfg.gni") + +assert(current_os == "freertos") + +asr_project_dir = "${chip_root}/examples/all-clusters-minimal-app/asr" +examples_plat_dir = "${chip_root}/examples/platform/asr" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + +asr_sdk_sources("all_clusters_app_sdk_sources") { + include_dirs = [ + "${chip_root}/src/platform/ASR", + "${asr_project_dir}/include", + "${examples_plat_dir}", + ] + + defines = [ + "ASR_LOG_ENABLED=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + ] + + if (chip_enable_factory_data) { + defines += [ + "CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER=1", + "CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER=1", + ] + } + + if (chip_lwip_ip6_hook) { + defines += [ + "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", + "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", + ] + } + + sources = [ "${asr_project_dir}/include/CHIPProjectConfig.h" ] + + public_configs = [ "${asr_sdk_build_root}:asr_sdk_config" ] +} + +asr_executable("clusters_minimal_app") { + include_dirs = [] + defines = [] + output_name = "chip-asr-clusters-minimal-example.out" + + sources = [ + "${chip_root}/examples/all-clusters-app/all-clusters-common/src/bridged-actions-stub.cpp", + "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", + "${examples_plat_dir}/CHIPDeviceManager.cpp", + "${examples_plat_dir}/LEDWidget.cpp", + "${examples_plat_dir}/init_Matter.cpp", + "${examples_plat_dir}/init_asrPlatform.cpp", + "${examples_plat_dir}/shell/matter_shell.cpp", + "src/AppTask.cpp", + "src/DeviceCallbacks.cpp", + "src/main.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${examples_plat_dir}/init_OTARequestor.cpp" ] + } + + deps = [ + ":all_clusters_app_sdk_sources", + "${chip_root}/examples/all-clusters-minimal-app/all-clusters-common", + "${chip_root}/examples/common/QRCode", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs += [ + "include", + "${examples_plat_dir}", + "${asr_project_dir}/include", + "${chip_root}/examples/all-clusters-app/all-clusters-common/include", + "${chip_root}/src", + "${chip_root}/src/lib", + "${chip_root}/src/lib/support", + "${chip_root}/src/app/util", + ] + + defines = [ "ASR_NETWORK_LAYER_BLE=${chip_config_network_layer_ble}" ] + + if (chip_build_libshell) { + defines += [ "CONFIG_ENABLE_CHIP_SHELL=1" ] + sources += [ "${examples_plat_dir}/shell/launch_shell.cpp" ] + include_dirs += [ "${examples_plat_dir}/shell" ] + } + + if (chip_print_memory_usage) { + ldflags += [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } + + output_dir = root_out_dir +} + +group("asr") { + deps = [ ":clusters_minimal_app" ] +} + +group("default") { + deps = [ ":asr" ] +} diff --git a/examples/all-clusters-minimal-app/asr/README.md b/examples/all-clusters-minimal-app/asr/README.md new file mode 100755 index 00000000000000..8926066fccece9 --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/README.md @@ -0,0 +1,54 @@ +# Matter ASR All Clusters Example + +A prototype application that demonstrates device commissioning and cluster +control on ASR platform. + +--- + +- [Matter ASR All Clusters Example](#matter-asr-all-clusters-example) + - [Supported Chips](#supported-chips) + - [Building and Commissioning](#building-and-commissioning) + - [Cluster Control](#cluster-control) + - [Light switch press button and light status LED](#light-switch-press-button-and-light-status-led) + +--- + +## Supported Chips + +The Matter demo application is supported on: + +- ASR582X +- ASR595X + +## Building and Commissioning + +Please refer +[Building and Commissioning](../../../docs/guides/asr_getting_started_guide.md#building-the-example-application) +guides to get started + +``` +./scripts/build/build_examples.py --target asr-$ASR_BOARD-all-clusters-minimal build +``` + +## Cluster Control + +After successful commissioning, use `chip-tool` to control the board + +For example,control the OnOff Cluster attribute: + +``` +./chip-tool onoff read on-off 1 +./chip-tool onoff on 1 +./chip-tool onoff off 1 +./chip-tool onoff toggle 1 +``` + +## Light switch press button and light status LED + +This demo uses button to test changing the light states and LED to show the +state of these changes. + +| Name | Pin | +| :----: | :---: | +| LED | PAD6 | +| BUTTON | PAD12 | diff --git a/examples/all-clusters-minimal-app/asr/args.gni b/examples/all-clusters-minimal-app/asr/args.gni new file mode 100755 index 00000000000000..66a2de849083d4 --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/args.gni @@ -0,0 +1,27 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("//cfg.gni") +import("${chip_root}/src/platform/ASR/args.gni") + +asr_target_project = + get_label_info(":all_clusters_app_sdk_sources", "label_no_toolchain") + +declare_args() { + # Disable lock tracking, since our FreeRTOS configuration does not set + # INCLUDE_xSemaphoreGetMutexHolder + chip_stack_lock_tracking = "none" +} diff --git a/examples/all-clusters-minimal-app/asr/build_overrides b/examples/all-clusters-minimal-app/asr/build_overrides new file mode 120000 index 00000000000000..194ee0b812dc3d --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/build_overrides @@ -0,0 +1 @@ +../../build_overrides/ \ No newline at end of file diff --git a/examples/all-clusters-minimal-app/asr/cfg.gni b/examples/all-clusters-minimal-app/asr/cfg.gni new file mode 100755 index 00000000000000..15fe50e79efb6d --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/cfg.gni @@ -0,0 +1,23 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + chip_enable_factory_data = false + + chip_lwip_ip6_hook = false + + setupPinCode = 20202021 + + setupDiscriminator = 3840 +} diff --git a/examples/all-clusters-minimal-app/asr/include/AppConfig.h b/examples/all-clusters-minimal-app/asr/include/AppConfig.h new file mode 100644 index 00000000000000..6a633267878a8d --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/include/AppConfig.h @@ -0,0 +1,54 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// ---- Lighting Example App Config ---- + +#define APP_TASK_NAME "APP" + +#define APP_EVENT_QUEUE_SIZE 10 +#define APP_TASK_STACK_SIZE (1024 * 4) +#define APP_WAIT_LOOP 1000 + +#define MATTER_DEVICE_NAME "ASR-Clusters-m" + +#define APP_LIGHT_BUTTON_IDX 0 +#define APP_BUTTON_DEBOUNCE_PERIOD_MS 50 + +#define APP_BUTTON_PRESSED 0 +#define APP_BUTTON_RELEASED 1 + +// Time it takes in ms for the simulated actuator to move from one +// state to another. +#define ACTUATOR_MOVEMENT_PERIOS_MS 2000 + +// ASR Logging +#ifdef __cplusplus +extern "C" { +#endif + +void appError(int err); +void ASR_LOG(const char * aFormat, ...); + +#ifdef __cplusplus +} + +#include +void appError(CHIP_ERROR error); +#endif diff --git a/examples/all-clusters-minimal-app/asr/include/AppEvent.h b/examples/all-clusters-minimal-app/asr/include/AppEvent.h new file mode 100755 index 00000000000000..2c59845f3bb577 --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/include/AppEvent.h @@ -0,0 +1,51 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 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. + */ + +#pragma once +#include + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +struct AppEvent +{ + enum AppEventTypes + { + kEventType_Button = 0, + kEventType_Timer, + kEventType_Light, + kEventType_Install, + }; + + uint16_t Type; + + union + { + struct + { + uint8_t ButtonIdx; + uint8_t Action; + } ButtonEvent; + struct + { + void * Context; + } TimerEvent; + }; + + EventHandler Handler; +}; diff --git a/examples/all-clusters-minimal-app/asr/include/AppTask.h b/examples/all-clusters-minimal-app/asr/include/AppTask.h new file mode 100755 index 00000000000000..97d1bfe538fb64 --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/include/AppTask.h @@ -0,0 +1,65 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "AppEvent.h" +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include +#include + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) + +class AppTask +{ + +public: + CHIP_ERROR StartAppTask(); + static void AppTaskMain(void * pvParameter); + static void LightActionEventHandler(AppEvent * aEvent); + void ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction); + void PostEvent(const AppEvent * event); + /** + * Use internally for registration of the ChipDeviceEvents + */ + static void CommonDeviceEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + +private: + friend AppTask & GetAppTask(void); + + CHIP_ERROR Init(); + + static AppTask sAppTask; + void DispatchEvent(AppEvent * event); + static void OnOffUpdateClusterState(void); +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/all-clusters-minimal-app/asr/include/CHIPProjectConfig.h b/examples/all-clusters-minimal-app/asr/include/CHIPProjectConfig.h new file mode 100755 index 00000000000000..6a81ee6517aedb --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/include/CHIPProjectConfig.h @@ -0,0 +1,92 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 +#define CHIP_CONFIG_REQUIRE_AUTH 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a version of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 1 +#endif + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) diff --git a/examples/all-clusters-minimal-app/asr/include/DeviceCallbacks.h b/examples/all-clusters-minimal-app/asr/include/DeviceCallbacks.h new file mode 100755 index 00000000000000..18ebb25ed75f36 --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/include/DeviceCallbacks.h @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.h + * + * Implementations for the DeviceManager callbacks for this application + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include +#include +#include + +class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks +{ +public: + void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg) override; + void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value) override; + +private: + void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); + void OnOnOffPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); + void OnIdentifyPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); +}; diff --git a/examples/all-clusters-minimal-app/asr/src/AppTask.cpp b/examples/all-clusters-minimal-app/asr/src/AppTask.cpp new file mode 100644 index 00000000000000..6b97d430953867 --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/src/AppTask.cpp @@ -0,0 +1,230 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * Copyright 2021, Cypress Semiconductor Corporation (an Infineon company) + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" +#include "AppConfig.h" +#include "AppEvent.h" +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include "LEDWidget.h" +#include "qrcodegen.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "init_Matter.h" +#include "lega_rtos_api.h" + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; + +LEDWidget sStatusLED; +LEDWidget sLightLED; +LEDWidget sClusterLED; + +namespace { +TaskHandle_t sAppTaskHandle; +QueueHandle_t sAppEventQueue; +constexpr EndpointId kNetworkCommissioningEndpointMain = 0; +constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; + +app::Clusters::NetworkCommissioning::Instance + sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, + &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); +} // namespace + +AppTask AppTask::sAppTask; + +void NetWorkCommissioningInstInit() +{ + sWiFiNetworkCommissioningInstance.Init(); + + // We only have network commissioning on endpoint 0. + emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); +} + +static DeviceCallbacks EchoCallbacks; + +CHIP_ERROR AppTask::StartAppTask() +{ + sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); + if (sAppEventQueue == NULL) + { + ASR_LOG("Failed to allocate app event queue"); + appError(APP_ERROR_EVENT_QUEUE_FAILED); + } + // Start App task. + xTaskCreate(AppTaskMain, APP_TASK_NAME, APP_TASK_STACK_SIZE, 0, 2, &sAppTaskHandle); + return (sAppTaskHandle == nullptr) ? APP_ERROR_CREATE_TASK_FAILED : CHIP_NO_ERROR; +} + +CHIP_ERROR AppTask::Init() +{ + ASR_LOG("App Task started"); + + if (MatterInitializer::Init_Matter_Stack(MATTER_DEVICE_NAME) != CHIP_NO_ERROR) + return CHIP_ERROR_INTERNAL; + + CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); + + if (deviceMgr.Init(&EchoCallbacks) != CHIP_NO_ERROR) + return CHIP_ERROR_INTERNAL; + + if (MatterInitializer::Init_Matter_Server() != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + NetWorkCommissioningInstInit(); + + ASR_LOG("Current Software Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + ConfigurationMgr().LogDeviceConfig(); + + // Print setup info + PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); + + return CHIP_NO_ERROR; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + AppEvent event; + CHIP_ERROR err = sAppTask.Init(); + + if (err != CHIP_NO_ERROR) + { + ASR_LOG("AppTask.Init() failed"); + appError(err); + } + + while (true) + { + BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10)); + while (eventReceived == pdTRUE) + { + sAppTask.DispatchEvent(&event); + eventReceived = xQueueReceive(sAppEventQueue, &event, 0); + } + } +} + +void AppTask::LightActionEventHandler(AppEvent * aEvent) +{ + /* ON/OFF Light Led based on Button interrupt */ + sLightLED.Invert(); + + /* Update OnOff Cluster state */ + sAppTask.OnOffUpdateClusterState(); +} + +void AppTask::ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction) +{ + if (btnIdx != APP_LIGHT_BUTTON_IDX) + { + return; + } + + AppEvent button_event = {}; + button_event.Type = AppEvent::kEventType_Button; + button_event.ButtonEvent.ButtonIdx = btnIdx; + button_event.ButtonEvent.Action = btnAction; + + if ((btnIdx == APP_LIGHT_BUTTON_IDX) && (btnAction == APP_BUTTON_RELEASED)) + { + button_event.Handler = LightActionEventHandler; + sAppTask.PostEvent(&button_event); + } +} + +void AppTask::PostEvent(const AppEvent * aEvent) +{ + if (sAppEventQueue != NULL) + { + BaseType_t status; + if (lega_rtos_is_in_interrupt_context()) + { + BaseType_t higherPrioTaskWoken = pdFALSE; + status = xQueueSendFromISR(sAppEventQueue, aEvent, &higherPrioTaskWoken); + +#ifdef portYIELD_FROM_ISR + portYIELD_FROM_ISR(higherPrioTaskWoken); +#elif portEND_SWITCHING_ISR // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + portEND_SWITCHING_ISR(higherPrioTaskWoken); +#else // portYIELD_FROM_ISR or portEND_SWITCHING_ISR +#error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR" +#endif // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + } + else + { + status = xQueueSend(sAppEventQueue, aEvent, 1); + } + + if (!status) + ASR_LOG("Failed to post event to app task event queue"); + } + else + { + ASR_LOG("Event Queue is NULL should never happen"); + } +} + +void AppTask::DispatchEvent(AppEvent * aEvent) +{ + if (aEvent->Handler) + { + aEvent->Handler(aEvent); + } + else + { + ASR_LOG("Event received with no handler. Dropping event."); + } +} + +void AppTask::OnOffUpdateClusterState(void) +{ + uint8_t onoff = sLightLED.Get(); + + // write the new on/off value + EmberAfStatus status = app::Clusters::OnOff::Attributes::OnOff::Set(2, onoff); + + if (status != EMBER_ZCL_STATUS_SUCCESS) + { + ASR_LOG("ERR: updating on/off %x", status); + } +} + +bool lowPowerClusterSleep() +{ + return true; +} diff --git a/examples/all-clusters-minimal-app/asr/src/DeviceCallbacks.cpp b/examples/all-clusters-minimal-app/asr/src/DeviceCallbacks.cpp new file mode 100644 index 00000000000000..104b3f52a46364 --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/src/DeviceCallbacks.cpp @@ -0,0 +1,180 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.cpp + * + * Implements all the callbacks to the application from the CHIP Stack + * + **/ +#include "DeviceCallbacks.h" + +#include "CHIPDeviceManager.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "LEDWidget.h" +#include "init_OTARequestor.h" +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT +#include "route_hook/asr_route_hook.h" +#endif + +static const char * TAG = "app-devicecallbacks"; + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::System; +using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceManager; +using namespace ::chip::Logging; + +uint32_t identifyTimerCount; +constexpr uint32_t kIdentifyTimerDelayMS = 250; +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +constexpr uint32_t kInitOTARequestorDelaySec = 3; + +void InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +{ + OTAInitializer::Instance().InitOTARequestor(); +} +#endif +void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + switch (event->Type) + { + case DeviceEventType::kInternetConnectivityChange: + OnInternetConnectivityChange(event); + break; + + case DeviceEventType::kInterfaceIpAddressChanged: + if ((event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned) || + (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned)) + { + // MDNS server restart on any ip assignment: if link local ipv6 is configured, that + // will not trigger a 'internet connectivity change' as there is no internet + // connectivity. MDNS still wants to refresh its listening interfaces to include the + // newly selected address. + chip::app::DnssdServer::Instance().StartServer(); + + if (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned) + { +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT + ChipLogProgress(NotSpecified, "Initializing route hook..."); + asr_route_hook_init(); +#endif + } + } + break; + } +} + +void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t type, + uint16_t size, uint8_t * value) +{ + switch (clusterId) + { + case app::Clusters::OnOff::Id: + OnOnOffPostAttributeChangeCallback(endpointId, attributeId, value); + break; + + case app::Clusters::Identify::Id: + OnIdentifyPostAttributeChangeCallback(endpointId, attributeId, value); + break; + + default: + break; + } +} + +void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + static bool isOTAInitialized = false; +#endif + if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv4 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); + } + else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv4 connectivity..."); + } + if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv6 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Init OTA requestor only when we have gotten IPv6 address + if (!isOTAInitialized) + { + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec), + InitOTARequestorHandler, nullptr); + isOTAInitialized = true; + } +#endif + } + else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv6 connectivity..."); + } +} + +void DeviceCallbacks::OnOnOffPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) +{ + VerifyOrExit(attributeId == chip::app::Clusters::OnOff::Attributes::OnOff::Id, + ChipLogError(DeviceLayer, TAG, "Unhandled Attribute ID: '0x%04x", attributeId)); + VerifyOrExit(endpointId == 1 || endpointId == 2, + ChipLogError(DeviceLayer, TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId)); + + // At this point we can assume that value points to a bool value. + // statusLED1.Set(*value); + +exit: + return; +} + +void IdentifyTimerHandler(Layer * systemLayer, void * appState, CHIP_ERROR error) +{ + if (identifyTimerCount) + { + identifyTimerCount--; + } +} + +void DeviceCallbacks::OnIdentifyPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) +{ + VerifyOrExit(attributeId == chip::app::Clusters::Identify::Attributes::IdentifyTime::Id, + ChipLogError(DeviceLayer, "[%s] Unhandled Attribute ID: '0x%04lx", TAG, attributeId)); + VerifyOrExit(endpointId == 1, ChipLogError(DeviceLayer, "[%s] Unexpected EndPoint ID: `0x%02x'", TAG, endpointId)); + + // timerCount represents the number of callback executions before we stop the timer. + // value is expressed in seconds and the timer is fired every 250ms, so just multiply value by 4. + // Also, we want timerCount to be odd number, so the ligth state ends in the same state it starts. + identifyTimerCount = (*value) * 4; +exit: + return; +} diff --git a/examples/all-clusters-minimal-app/asr/src/main.cpp b/examples/all-clusters-minimal-app/asr/src/main.cpp new file mode 100644 index 00000000000000..7ef86db3591b1f --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/src/main.cpp @@ -0,0 +1,85 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * Copyright 2021, Cypress Semiconductor Corporation (an Infineon company) + * 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 "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include +#include +#include +#include + +#include + +#include "AppConfig.h" +#include "init_asrPlatform.h" +#include + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; +// ================================================================================ +// App Error +//================================================================================= +void appError(int err) +{ + ASR_LOG("!!!!!!!!!!!! App Critical Error: %d !!!!!!!!!!!", err); + lega_rtos_declare_critical(); + lega_rtos_enter_critical(); + while (1) + ; +} + +void appError(CHIP_ERROR error) +{ + appError(static_cast(error.AsInteger())); +} +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + init_asrPlatform(); + + CHIP_ERROR ret = GetAppTask().StartAppTask(); + if (ret != CHIP_NO_ERROR) + { + ASR_LOG("GetAppTask().Init() failed"); + appError(ret); + } + /* Start the FreeRTOS scheduler */ + vTaskStartScheduler(); + + chip::Platform::MemoryShutdown(); + PlatformMgr().StopEventLoopTask(); + PlatformMgr().Shutdown(); + + // Should never get here. + ASR_LOG("vTaskStartScheduler() failed"); + appError(ret); +} diff --git a/examples/all-clusters-minimal-app/asr/third_party/connectedhomeip b/examples/all-clusters-minimal-app/asr/third_party/connectedhomeip new file mode 120000 index 00000000000000..11a54ed360106c --- /dev/null +++ b/examples/all-clusters-minimal-app/asr/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../ \ No newline at end of file diff --git a/examples/bridge-app/asr/.gn b/examples/bridge-app/asr/.gn new file mode 100755 index 00000000000000..8d75f1eafcdb89 --- /dev/null +++ b/examples/bridge-app/asr/.gn @@ -0,0 +1,29 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/bridge-app/asr/BUILD.gn b/examples/bridge-app/asr/BUILD.gn new file mode 100755 index 00000000000000..a8db71bd3de7d3 --- /dev/null +++ b/examples/bridge-app/asr/BUILD.gn @@ -0,0 +1,134 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/asr.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("${asr_sdk_build_root}/asr_sdk.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/src/lib/lib.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/asr/asr_executable.gni") + +import("cfg.gni") + +assert(current_os == "freertos") + +asr_project_dir = "${chip_root}/examples/bridge-app/asr" +examples_plat_dir = "${chip_root}/examples/platform/asr" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + +asr_sdk_sources("bridge_app_sdk_sources") { + include_dirs = [ + "${chip_root}/src/platform/ASR", + "${asr_project_dir}/include", + "${examples_plat_dir}", + ] + + defines = [ + "ASR_LOG_ENABLED=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + "ENABLE_ASR_BRIDGE_SUBDEVICE_TEST=1", + ] + + if (chip_enable_factory_data) { + defines += [ + "CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER=1", + "CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER=1", + ] + } + + if (chip_lwip_ip6_hook) { + defines += [ + "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", + "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", + ] + } + + sources = [ "${asr_project_dir}/include/CHIPProjectConfig.h" ] + + public_configs = [ "${asr_sdk_build_root}:asr_sdk_config" ] +} + +asr_executable("bridge_app") { + include_dirs = [] + defines = [] + output_name = "chip-asr-bridge-example.out" + + sources = [ + "${examples_plat_dir}/CHIPDeviceManager.cpp", + "${examples_plat_dir}/LEDWidget.cpp", + "${examples_plat_dir}/init_Matter.cpp", + "${examples_plat_dir}/init_asrPlatform.cpp", + "${examples_plat_dir}/shell/matter_shell.cpp", + "src/AppTask.cpp", + "src/DeviceCallbacks.cpp", + "src/bridged-actions-stub.cpp", + "src/main.cpp", + "subdevice/SubDevice.cpp", + "subdevice/SubDeviceManager.cpp", + "subdevice/subdevice_test.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${examples_plat_dir}/init_OTARequestor.cpp" ] + } + + deps = [ + ":bridge_app_sdk_sources", + "${chip_root}/examples/bridge-app/bridge-common", + "${chip_root}/examples/common/QRCode", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs += [ + "include", + "subdevice", + "${examples_plat_dir}", + "${asr_project_dir}/include", + "${chip_root}/src/lib", + ] + + defines = [ "ASR_NETWORK_LAYER_BLE=${chip_config_network_layer_ble}" ] + + if (chip_build_libshell) { + defines += [ "CONFIG_ENABLE_CHIP_SHELL=1" ] + sources += [ "${examples_plat_dir}/shell/launch_shell.cpp" ] + include_dirs += [ "${examples_plat_dir}/shell" ] + } + + if (chip_print_memory_usage) { + ldflags += [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } + + output_dir = root_out_dir +} + +group("asr") { + deps = [ ":bridge_app" ] +} + +group("default") { + deps = [ ":asr" ] +} diff --git a/examples/bridge-app/asr/README.md b/examples/bridge-app/asr/README.md new file mode 100755 index 00000000000000..7f4e11a4b2bbe1 --- /dev/null +++ b/examples/bridge-app/asr/README.md @@ -0,0 +1,67 @@ +# Matter ASR Bridge Example + +This example demonstrates the Matter Bridge application on ASR platform. + +--- + +- [Matter ASR Bridge Example](#matter-asr-bridge-example) + - [Supported Chips](#supported-chips) + - [Introduction](#introduction) + - [Building and Commissioning](#building-and-commissioning) + - [Testing the example](#testing-the-example) + +--- + +## Supported Chips + +The Matter demo application is supported on: + +- ASR582X +- ASR595X + +## Introduction + +A prototype application that demonstrates dynamic endpoint with device +commissioning and cluster control. It adds the non-chip device as endpoints on a +bridge(Matter device). In this example four light devices supporting on-off +cluster have been added as endpoints + +1. Light1 at endpoint 3 +2. Light2 at endpoint 4 +3. Light3 at endpoint 5 +4. Light4 at endpoint 6 + +## Building and Commissioning + +Please refer +[Building and Commissioning](../../../docs/guides/asr_getting_started_guide.md#building-the-example-application) +guides to get started + +``` +./scripts/build/build_examples.py --target asr-$ASR_BOARD-bridge build +``` + +## Testing the example + +- An additional light-switch device is required to complete this example. +- Commission bridge device with node-id `1` +- Commission light-switch device with node-id `2` +- After bridge device and light-switch device successful commissioning, use + the GUI tool `DOGO` to input AT command `subdevice sync` for the bridge + device, and then use chip-tool to write ACL to the bridge device. + ``` + ./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null },{"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": [2], "targets": null }]' 1 0 + ``` +- After successful commissioning, use the `chip-tool` for binding + light-switch's endpoint 1 with bridge device's endpoint 3 respectively. + ``` + ./chip-tool binding write binding '[{"fabricIndex": 1, "node":1, "endpoint":3, "cluster":6}]' 2 1 + ``` +- Light switch button + + This demo uses button to test changing the `Light1`, and the bridge device + will output log information: + + | Name | Pin | + | :----: | :--: | + | BUTTON | PAD6 | diff --git a/examples/bridge-app/asr/args.gni b/examples/bridge-app/asr/args.gni new file mode 100755 index 00000000000000..705cc2b6022c81 --- /dev/null +++ b/examples/bridge-app/asr/args.gni @@ -0,0 +1,27 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("//cfg.gni") +import("${chip_root}/src/platform/ASR/args.gni") + +asr_target_project = + get_label_info(":bridge_app_sdk_sources", "label_no_toolchain") + +declare_args() { + # Disable lock tracking, since our FreeRTOS configuration does not set + # INCLUDE_xSemaphoreGetMutexHolder + chip_stack_lock_tracking = "none" +} diff --git a/examples/bridge-app/asr/build_overrides b/examples/bridge-app/asr/build_overrides new file mode 120000 index 00000000000000..194ee0b812dc3d --- /dev/null +++ b/examples/bridge-app/asr/build_overrides @@ -0,0 +1 @@ +../../build_overrides/ \ No newline at end of file diff --git a/examples/bridge-app/asr/cfg.gni b/examples/bridge-app/asr/cfg.gni new file mode 100755 index 00000000000000..15fe50e79efb6d --- /dev/null +++ b/examples/bridge-app/asr/cfg.gni @@ -0,0 +1,23 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + chip_enable_factory_data = false + + chip_lwip_ip6_hook = false + + setupPinCode = 20202021 + + setupDiscriminator = 3840 +} diff --git a/examples/bridge-app/asr/include/AppConfig.h b/examples/bridge-app/asr/include/AppConfig.h new file mode 100644 index 00000000000000..1250881f65bf60 --- /dev/null +++ b/examples/bridge-app/asr/include/AppConfig.h @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// ---- Lighting Example App Config ---- + +#define APP_TASK_NAME "APP" +#define MATTER_DEVICE_NAME "ASR-Bridge" +#define APP_TASK_STACK_SIZE (1024 * 4) + +#define LIGHT_LED PWM_OUTPUT_CH4 + +// ASR Logging +#ifdef __cplusplus +extern "C" { +#endif + +void appError(int err); +void ASR_LOG(const char * aFormat, ...); + +#ifdef __cplusplus +} + +#include +void appError(CHIP_ERROR error); +#endif diff --git a/examples/bridge-app/asr/include/AppTask.h b/examples/bridge-app/asr/include/AppTask.h new file mode 100644 index 00000000000000..6cdf9e29daed8e --- /dev/null +++ b/examples/bridge-app/asr/include/AppTask.h @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include + +class AppTask +{ + +public: + CHIP_ERROR StartAppTask(); + static void AppTaskMain(void * pvParameter); + +private: + friend AppTask & GetAppTask(void); + + static AppTask sAppTask; +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/bridge-app/asr/include/CHIPProjectConfig.h b/examples/bridge-app/asr/include/CHIPProjectConfig.h new file mode 100755 index 00000000000000..6b159a670b5ed7 --- /dev/null +++ b/examples/bridge-app/asr/include/CHIPProjectConfig.h @@ -0,0 +1,118 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +/** + * CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY + * + * Enables the use of a hard-coded default Chip device id and credentials if no device id + * is found in Chip NV storage. + * + * This option is for testing only and should be disabled in production releases. + */ +#define CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY 34 + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// define Device type based on the application +#define CHIP_DEVICE_CONFIG_DEVICE_TYPE 257 // 0x0101 Dimmable Bulb + +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 1 +#endif + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS + * + * Enable recording UTC timestamps. + */ +#define CHIP_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS 1 + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) + +/** + * CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT + * + * A size, max count of the sub device for bridge app. + */ +#define CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT (16) diff --git a/examples/bridge-app/asr/include/DeviceCallbacks.h b/examples/bridge-app/asr/include/DeviceCallbacks.h new file mode 100644 index 00000000000000..2b5cfe386f8f05 --- /dev/null +++ b/examples/bridge-app/asr/include/DeviceCallbacks.h @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.h + * + * Implementations for the DeviceManager callbacks for this application + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include +#include +#include + +class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks +{ +public: + virtual void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value) override; + +private: + void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); +}; diff --git a/examples/bridge-app/asr/src/AppTask.cpp b/examples/bridge-app/asr/src/AppTask.cpp new file mode 100644 index 00000000000000..be6763819ac986 --- /dev/null +++ b/examples/bridge-app/asr/src/AppTask.cpp @@ -0,0 +1,102 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" +#include "AppConfig.h" +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include "SubDeviceManager.h" +#include "init_Matter.h" +#include "qrcodegen.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +TaskHandle_t sAppTaskHandle; +} // namespace + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; + +AppTask AppTask::sAppTask; + +namespace { +constexpr EndpointId kNetworkCommissioningEndpointMain = 0; +constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; + +app::Clusters::NetworkCommissioning::Instance + sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, + &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); +} // namespace + +void NetWorkCommissioningInstInit() +{ + sWiFiNetworkCommissioningInstance.Init(); + + // We only have network commissioning on endpoint 0. + emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); +} + +static DeviceCallbacks EchoCallbacks; + +CHIP_ERROR AppTask::StartAppTask() +{ + // Start App task. + xTaskCreate(AppTaskMain, APP_TASK_NAME, APP_TASK_STACK_SIZE, 0, 2, &sAppTaskHandle); + return (sAppTaskHandle == nullptr) ? CHIP_APPLICATION_ERROR(0x02) : CHIP_NO_ERROR; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + ASR_LOG("App Task started"); + + if (MatterInitializer::Init_Matter_Stack(MATTER_DEVICE_NAME) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); + + if (deviceMgr.Init(&EchoCallbacks) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + if (MatterInitializer::Init_Matter_Server() != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + NetWorkCommissioningInstInit(); + + ASR_LOG("Current Firmware Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + ConfigurationMgr().LogDeviceConfig(); + + // Print setup info + PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); + + /* Init Device Endpoint */ + Init_Bridge_Endpoint(); + + /* Delete task */ + vTaskDelete(NULL); +} diff --git a/examples/bridge-app/asr/src/DeviceCallbacks.cpp b/examples/bridge-app/asr/src/DeviceCallbacks.cpp new file mode 100644 index 00000000000000..f16b4c956c8022 --- /dev/null +++ b/examples/bridge-app/asr/src/DeviceCallbacks.cpp @@ -0,0 +1,133 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.cpp + * + * Implements all the callbacks to the application from the CHIP Stack + * + **/ +#include "DeviceCallbacks.h" +#include "AppConfig.h" +#include "CHIPDeviceManager.h" +#include "init_OTARequestor.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT +#include "route_hook/asr_route_hook.h" +#endif + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::System; +using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceManager; +using namespace ::chip::Logging; +using namespace ::chip::app::Clusters; + +uint32_t identifyTimerCount; +constexpr uint32_t kIdentifyTimerDelayMS = 250; +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +constexpr uint32_t kInitOTARequestorDelaySec = 3; + +void InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +{ + OTAInitializer::Instance().InitOTARequestor(); +} +#endif +void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + switch (event->Type) + { + case DeviceEventType::kInternetConnectivityChange: + OnInternetConnectivityChange(event); + break; + + case DeviceEventType::kInterfaceIpAddressChanged: + if ((event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned) || + (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned)) + { + // MDNS server restart on any ip assignment: if link local ipv6 is configured, that + // will not trigger a 'internet connectivity change' as there is no internet + // connectivity. MDNS still wants to refresh its listening interfaces to include the + // newly selected address. + chip::app::DnssdServer::Instance().StartServer(); + + if (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned) + { +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT + ChipLogProgress(NotSpecified, "Initializing route hook..."); + asr_route_hook_init(); +#endif + } + } + break; + } +} + +void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + static bool isOTAInitialized = false; +#endif + if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established) + { + ASR_LOG("IPv4 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); + } + else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost) + { + ASR_LOG("Lost IPv4 connectivity..."); + } + if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established) + { + ASR_LOG("IPv6 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Init OTA requestor only when we have gotten IPv6 address + if (!isOTAInitialized) + { + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec), + InitOTARequestorHandler, nullptr); + isOTAInitialized = true; + } +#endif + } + else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost) + { + ASR_LOG("Lost IPv6 connectivity..."); + } +} + +void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t type, + uint16_t size, uint8_t * value) +{ + ASR_LOG("PostAttributeChangeCallback - Cluster ID: '0x%" PRIx32 "', EndPoint ID: '0x%x', Attribute ID: '0x%" PRIx32 "'", + clusterId, endpointId, attributeId); +} diff --git a/examples/bridge-app/asr/src/bridged-actions-stub.cpp b/examples/bridge-app/asr/src/bridged-actions-stub.cpp new file mode 100755 index 00000000000000..91539e63f8f38e --- /dev/null +++ b/examples/bridge-app/asr/src/bridged-actions-stub.cpp @@ -0,0 +1,100 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include + +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; +using namespace chip::app::Clusters::Actions::Attributes; + +namespace { + +class ActionsAttrAccess : public AttributeAccessInterface +{ +public: + // Register for the Actions cluster on all endpoints. + ActionsAttrAccess() : AttributeAccessInterface(Optional::Missing(), Actions::Id) {} + + CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override; + +private: + static constexpr uint16_t ClusterRevision = 1; + + CHIP_ERROR ReadActionListAttribute(EndpointId endpoint, AttributeValueEncoder & aEncoder); + CHIP_ERROR ReadEndpointListAttribute(EndpointId endpoint, AttributeValueEncoder & aEncoder); + CHIP_ERROR ReadSetupUrlAttribute(EndpointId endpoint, AttributeValueEncoder & aEncoder); + CHIP_ERROR ReadClusterRevision(EndpointId endpoint, AttributeValueEncoder & aEncoder); +}; + +constexpr uint16_t ActionsAttrAccess::ClusterRevision; + +CHIP_ERROR ActionsAttrAccess::ReadActionListAttribute(EndpointId endpoint, AttributeValueEncoder & aEncoder) +{ + // Just return an empty list + return aEncoder.EncodeEmptyList(); +} + +CHIP_ERROR ActionsAttrAccess::ReadEndpointListAttribute(EndpointId endpoint, AttributeValueEncoder & aEncoder) +{ + // Just return an empty list + return aEncoder.EncodeEmptyList(); +} + +CHIP_ERROR ActionsAttrAccess::ReadSetupUrlAttribute(EndpointId endpoint, AttributeValueEncoder & aEncoder) +{ + const char SetupUrl[] = "https://example.com"; + return aEncoder.Encode(chip::Span(SetupUrl, strlen(SetupUrl))); +} + +CHIP_ERROR ActionsAttrAccess::ReadClusterRevision(EndpointId endpoint, AttributeValueEncoder & aEncoder) +{ + return aEncoder.Encode(ClusterRevision); +} + +ActionsAttrAccess gAttrAccess; + +CHIP_ERROR ActionsAttrAccess::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) +{ + VerifyOrDie(aPath.mClusterId == Actions::Id); + + switch (aPath.mAttributeId) + { + case ActionList::Id: + return ReadActionListAttribute(aPath.mEndpointId, aEncoder); + case EndpointLists::Id: + return ReadEndpointListAttribute(aPath.mEndpointId, aEncoder); + case SetupURL::Id: + return ReadSetupUrlAttribute(aPath.mEndpointId, aEncoder); + case ClusterRevision::Id: + return ReadClusterRevision(aPath.mEndpointId, aEncoder); + default: + break; + } + return CHIP_NO_ERROR; +} +} // anonymous namespace + +void MatterActionsPluginServerInitCallback(void) +{ + registerAttributeAccessOverride(&gAttrAccess); +} diff --git a/examples/bridge-app/asr/src/main.cpp b/examples/bridge-app/asr/src/main.cpp new file mode 100644 index 00000000000000..228eeff6f1ee68 --- /dev/null +++ b/examples/bridge-app/asr/src/main.cpp @@ -0,0 +1,76 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppConfig.h" +#include "init_asrPlatform.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; +// ================================================================================ +// App Error +//================================================================================= +void appError(int err) +{ + ASR_LOG("!!!!!!!!!!!! App Critical Error: %d !!!!!!!!!!!", err); + lega_rtos_declare_critical(); + lega_rtos_enter_critical(); + while (1) + ; +} + +void appError(CHIP_ERROR error) +{ + appError(static_cast(error.AsInteger())); +} +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + init_asrPlatform(); + + CHIP_ERROR ret = GetAppTask().StartAppTask(); + if (ret != CHIP_NO_ERROR) + { + ASR_LOG("GetAppTask().Init() failed"); + appError(ret); + } + /* Start the FreeRTOS scheduler */ + vTaskStartScheduler(); + + chip::Platform::MemoryShutdown(); + PlatformMgr().StopEventLoopTask(); + PlatformMgr().Shutdown(); + + // Should never get here. + ASR_LOG("vTaskStartScheduler() failed"); + appError(ret); +} diff --git a/examples/bridge-app/asr/subdevice/SubDevice.cpp b/examples/bridge-app/asr/subdevice/SubDevice.cpp new file mode 100644 index 00000000000000..c0b60cc3d90f81 --- /dev/null +++ b/examples/bridge-app/asr/subdevice/SubDevice.cpp @@ -0,0 +1,154 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "SubDevice.h" +#ifdef __cplusplus +extern "C" { +#endif +#include +#if CONFIG_ENABLE_ASR_APP_MESH +#include "app.h" +#include "sonata_gap_api.h" +#include "sonata_gatt_api.h" +#endif +#ifdef __cplusplus +} +#endif + +#include +#include +#include + +using namespace ::chip::Platform; + +SubDevice::SubDevice(const char * szSubDeviceName, const char * szLocation) +{ + CopyString(mName, sizeof(mName), szSubDeviceName); + CopyString(mLocation, sizeof(mLocation), szLocation); + mState = kState_Off; + mReachable = false; + mEndpointId = 0; + mChanged_CB = nullptr; +} + +bool SubDevice::IsOn() const +{ + return mState == kState_On; +} + +bool SubDevice::IsReachable() const +{ + return mReachable; +} + +void SubDevice::SetOnOff(bool aOn) +{ + bool changed; + + if (aOn) + { + changed = (mState != kState_On); + mState = kState_On; + ChipLogProgress(DeviceLayer, "SubDevice[%s]: ON", mName); +#if CONFIG_ENABLE_ASR_APP_MESH + if (strcmp(mName, "Light 1") == 0) + { + app_mesh_control_fan(1); + } + else + { + app_mesh_control_light(1); + } +#endif + } + else + { + changed = (mState != kState_Off); + mState = kState_Off; + ChipLogProgress(DeviceLayer, "SubDevice[%s]: OFF", mName); +#if CONFIG_ENABLE_ASR_APP_MESH + if (strcmp(mName, "Light 1") == 0) + { + app_mesh_control_fan(0); + } + else + { + app_mesh_control_light(0); + } +#endif + } + + if (changed && mChanged_CB) + { + mChanged_CB(this, kChanged_State); + } +} + +void SubDevice::SetReachable(bool aReachable) +{ + bool changed = (mReachable != aReachable); + + mReachable = aReachable; + + if (aReachable) + { + ChipLogProgress(DeviceLayer, "SubDevice[%s]: ONLINE", mName); + } + else + { + ChipLogProgress(DeviceLayer, "SubDevice[%s]: OFFLINE", mName); + } + + if (changed && mChanged_CB) + { + mChanged_CB(this, kChanged_Reachable); + } +} + +void SubDevice::SetName(const char * szName) +{ + bool changed = (strncmp(mName, szName, sizeof(mName)) != 0); + + ChipLogProgress(DeviceLayer, "SubDevice[%s]: New Name=\"%s\"", mName, szName); + + CopyString(mName, sizeof(mName), szName); + + if (changed && mChanged_CB) + { + mChanged_CB(this, kChanged_Name); + } +} + +void SubDevice::SetLocation(const char * szLocation) +{ + bool changed = (strncmp(mLocation, szLocation, sizeof(mLocation)) != 0); + + CopyString(mLocation, sizeof(mLocation), szLocation); + + ChipLogProgress(DeviceLayer, "SubDevice[%s]: Location=\"%s\"", mName, mLocation); + + if (changed && mChanged_CB) + { + mChanged_CB(this, kChanged_Location); + } +} + +void SubDevice::SetChangeCallback(SubDeviceCallback_fn aChanged_CB) +{ + mChanged_CB = aChanged_CB; +} diff --git a/examples/bridge-app/asr/subdevice/SubDevice.h b/examples/bridge-app/asr/subdevice/SubDevice.h new file mode 100755 index 00000000000000..d583b07b18c191 --- /dev/null +++ b/examples/bridge-app/asr/subdevice/SubDevice.h @@ -0,0 +1,70 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// These are the bridged devices +#include +#include +#include +#include + +class SubDevice +{ +public: + static const int kSubDeviceNameSize = 32; + static const int kSubDeviceLocationSize = 32; + + enum State_t + { + kState_On = 0, + kState_Off, + } State; + + enum Changed_t + { + kChanged_Reachable = 0x01, + kChanged_State = 0x02, + kChanged_Location = 0x04, + kChanged_Name = 0x08, + } Changed; + + SubDevice(const char * szSubDeviceName, const char * szLocation); + + bool IsOn() const; + bool IsReachable() const; + void SetOnOff(bool aOn); + void SetReachable(bool aReachable); + void SetName(const char * szSubDeviceName); + void SetLocation(const char * szLocation); + inline void SetEndpointId(chip::EndpointId id) { mEndpointId = id; }; + inline chip::EndpointId GetEndpointId() { return mEndpointId; }; + inline char * GetName() { return mName; }; + inline char * GetLocation() { return mLocation; }; + + using SubDeviceCallback_fn = std::function; + void SetChangeCallback(SubDeviceCallback_fn aChanged_CB); + +private: + State_t mState; + bool mReachable; + char mName[kSubDeviceNameSize]; + char mLocation[kSubDeviceLocationSize]; + chip::EndpointId mEndpointId; + SubDeviceCallback_fn mChanged_CB; +}; diff --git a/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp b/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp new file mode 100644 index 00000000000000..6e15406c9ff4fa --- /dev/null +++ b/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp @@ -0,0 +1,269 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "SubDeviceManager.h" +#include "SubDevice.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; +using namespace ::chip::Platform; +using namespace ::chip::app::Clusters; + +static EndpointId gCurrentEndpointId; +static EndpointId gFirstDynamicEndpointId; + +static SubDevice * gSubDevices[CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT]; // number of dynamic endpoints count + +int AddDeviceEndpoint(SubDevice * dev, EmberAfEndpointType * ep, const Span & deviceTypeList, + const Span & dataVersionStorage, chip::EndpointId parentEndpointId) +{ + uint8_t index = 0; + while (index < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT) + { + if (NULL == gSubDevices[index]) + { + gSubDevices[index] = dev; + EmberAfStatus ret; + while (1) + { + dev->SetEndpointId(gCurrentEndpointId); + ret = + emberAfSetDynamicEndpoint(index, gCurrentEndpointId, ep, dataVersionStorage, deviceTypeList, parentEndpointId); + if (ret == EMBER_ZCL_STATUS_SUCCESS) + { + ChipLogProgress(DeviceLayer, "Added device %s to dynamic endpoint %d (index=%d)", dev->GetName(), + gCurrentEndpointId, index); + return index; + } + else if (ret != EMBER_ZCL_STATUS_DUPLICATE_EXISTS) + { + return -1; + } + // Handle wrap condition + if (++gCurrentEndpointId < gFirstDynamicEndpointId) + { + gCurrentEndpointId = gFirstDynamicEndpointId; + } + } + } + index++; + } + ChipLogProgress(DeviceLayer, "Failed to add dynamic endpoint: No endpoints available!"); + return -1; +} + +CHIP_ERROR RemoveDeviceEndpoint(SubDevice * dev) +{ + for (uint8_t index = 0; index < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; index++) + { + if (gSubDevices[index] == dev) + { + EndpointId ep = emberAfClearDynamicEndpoint(index); + gSubDevices[index] = NULL; + ChipLogProgress(DeviceLayer, "Removed device %s from dynamic endpoint %d (index=%d)", dev->GetName(), ep, index); + // Silence complaints about unused ep when progress logging + // disabled. + UNUSED_VAR(ep); + return CHIP_NO_ERROR; + } + } + return CHIP_ERROR_INTERNAL; +} + +EmberAfStatus HandleReadBridgedDeviceBasicAttribute(SubDevice * dev, chip::AttributeId attributeId, uint8_t * buffer, + uint16_t maxReadLength) +{ + using namespace BridgedDeviceBasicInformation::Attributes; + ChipLogProgress(DeviceLayer, "HandleReadBridgedDeviceBasicAttribute: attrId=%" PRIu32 ", maxReadLength=%u", attributeId, + maxReadLength); + + if ((attributeId == Reachable::Id) && (maxReadLength == 1)) + { + *buffer = dev->IsReachable() ? 1 : 0; + } + else if ((attributeId == NodeLabel::Id) && (maxReadLength == 32)) + { + MutableByteSpan zclNameSpan(buffer, maxReadLength); + MakeZclCharString(zclNameSpan, dev->GetName()); + } + else if ((attributeId == ClusterRevision::Id) && (maxReadLength == 2)) + { + *buffer = (uint16_t) ZCL_BRIDGED_DEVICE_BASIC_CLUSTER_REVISION; + } + else + { + return EMBER_ZCL_STATUS_FAILURE; + } + + return EMBER_ZCL_STATUS_SUCCESS; +} + +EmberAfStatus HandleReadOnOffAttribute(SubDevice * dev, chip::AttributeId attributeId, uint8_t * buffer, uint16_t maxReadLength) +{ + ChipLogProgress(DeviceLayer, "HandleReadOnOffAttribute: attrId=%" PRIu32 ", maxReadLength=%u", attributeId, maxReadLength); + + if ((attributeId == OnOff::Attributes::OnOff::Id) && (maxReadLength == 1)) + { + *buffer = dev->IsOn() ? 1 : 0; + } + else if ((attributeId == OnOff::Attributes::ClusterRevision::Id) && (maxReadLength == 2)) + { + *buffer = (uint16_t) ZCL_ON_OFF_CLUSTER_REVISION; + } + else + { + return EMBER_ZCL_STATUS_FAILURE; + } + + return EMBER_ZCL_STATUS_SUCCESS; +} + +EmberAfStatus HandleWriteOnOffAttribute(SubDevice * dev, chip::AttributeId attributeId, uint8_t * buffer) +{ + ChipLogProgress(DeviceLayer, "HandleWriteOnOffAttribute: attrId=%" PRIu32, attributeId); + + ReturnErrorCodeIf((attributeId != OnOff::Attributes::OnOff::Id) || (!dev->IsReachable()), EMBER_ZCL_STATUS_FAILURE); + dev->SetOnOff(*buffer == 1); + return EMBER_ZCL_STATUS_SUCCESS; +} + +EmberAfStatus emberAfExternalAttributeReadCallback(EndpointId endpoint, ClusterId clusterId, + const EmberAfAttributeMetadata * attributeMetadata, uint8_t * buffer, + uint16_t maxReadLength) +{ + uint16_t endpointIndex = emberAfGetDynamicIndexFromEndpoint(endpoint); + + if ((endpointIndex < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT) && (gSubDevices[endpointIndex] != NULL)) + { + SubDevice * dev = gSubDevices[endpointIndex]; + + // if (clusterId == BridgedDeviceBasic::Id) + if (clusterId == BridgedDeviceBasicInformation::Id) + { + return HandleReadBridgedDeviceBasicAttribute(dev, attributeMetadata->attributeId, buffer, maxReadLength); + } + else if (clusterId == OnOff::Id) + { + return HandleReadOnOffAttribute(dev, attributeMetadata->attributeId, buffer, maxReadLength); + } + } + + return EMBER_ZCL_STATUS_FAILURE; +} + +EmberAfStatus emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, + const EmberAfAttributeMetadata * attributeMetadata, uint8_t * buffer) +{ + uint16_t endpointIndex = emberAfGetDynamicIndexFromEndpoint(endpoint); + + if (endpointIndex < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT) + { + SubDevice * dev = gSubDevices[endpointIndex]; + + if ((dev->IsReachable()) && (clusterId == OnOff::Id)) + { + return HandleWriteOnOffAttribute(dev, attributeMetadata->attributeId, buffer); + } + } + + return EMBER_ZCL_STATUS_FAILURE; +} + +namespace { +void CallReportingCallback(intptr_t closure) +{ + auto path = reinterpret_cast(closure); + MatterReportingAttributeChangeCallback(*path); + Platform::Delete(path); +} + +void ScheduleReportingCallback(SubDevice * dev, ClusterId cluster, AttributeId attribute) +{ + auto * path = Platform::New(dev->GetEndpointId(), cluster, attribute); + DeviceLayer::PlatformMgr().ScheduleWork(CallReportingCallback, reinterpret_cast(path)); +} +} // anonymous namespace + +void HandleDeviceStatusChanged(SubDevice * dev, SubDevice::Changed_t itemChangedMask) +{ + if (itemChangedMask & SubDevice::kChanged_Reachable) + { + // ScheduleReportingCallback(dev, BridgedDeviceBasic::Id, BridgedDeviceBasic::Attributes::Reachable::Id); + ScheduleReportingCallback(dev, BridgedDeviceBasicInformation::Id, BridgedDeviceBasicInformation::Attributes::Reachable::Id); + } + + if (itemChangedMask & SubDevice::kChanged_State) + { + ScheduleReportingCallback(dev, OnOff::Id, OnOff::Attributes::OnOff::Id); + } + + if (itemChangedMask & SubDevice::kChanged_Name) + { + // ScheduleReportingCallback(dev, BridgedDeviceBasic::Id, BridgedDeviceBasic::Attributes::NodeLabel::Id); + ScheduleReportingCallback(dev, BridgedDeviceBasicInformation::Id, BridgedDeviceBasicInformation::Attributes::NodeLabel::Id); + } +} + +const EmberAfDeviceType gRootDeviceTypes[] = { { DEVICE_TYPE_ROOT_NODE, DEVICE_VERSION_DEFAULT } }; +const EmberAfDeviceType gAggregateNodeDeviceTypes[] = { { DEVICE_TYPE_BRIDGE, DEVICE_VERSION_DEFAULT } }; + +bool emberAfActionsClusterInstantActionCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, + const Actions::Commands::InstantAction::DecodableType & commandData) +{ + // No actions are implemented, just return status NotFound. + commandObj->AddStatus(commandPath, Protocols::InteractionModel::Status::NotFound); + return true; +} + +void Init_Bridge_Endpoint() +{ + // bridge will have own database named gSubDevices. + // Clear database + memset(gSubDevices, 0, sizeof(gSubDevices)); + + // Set starting endpoint id where dynamic endpoints will be assigned, which + // will be the next consecutive endpoint id after the last fixed endpoint. + gFirstDynamicEndpointId = static_cast( + static_cast(emberAfEndpointFromIndex(static_cast(emberAfFixedEndpointCount() - 1))) + 1); + gCurrentEndpointId = gFirstDynamicEndpointId; + + // Disable last fixed endpoint, which is used as a placeholder for all of the + // supported clusters so that ZAP will generated the requisite code. + emberAfEndpointEnableDisable(emberAfEndpointFromIndex(static_cast(emberAfFixedEndpointCount() - 1)), false); + + // A bridge has root node device type on EP0 and aggregate node device type (bridge) at EP1 + emberAfSetDeviceTypeList(0, Span(gRootDeviceTypes)); + emberAfSetDeviceTypeList(1, Span(gAggregateNodeDeviceTypes)); +} diff --git a/examples/bridge-app/asr/subdevice/SubDeviceManager.h b/examples/bridge-app/asr/subdevice/SubDeviceManager.h new file mode 100644 index 00000000000000..6885f3492a6cc7 --- /dev/null +++ b/examples/bridge-app/asr/subdevice/SubDeviceManager.h @@ -0,0 +1,77 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "SubDevice.h" +#include "SubDeviceManager.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; + +#ifdef __cplusplus +extern "C" { +#endif + +// (taken from chip-devices.xml) +#define DEVICE_TYPE_BRIDGED_NODE 0x0013 +// (taken from lo-devices.xml) +#define DEVICE_TYPE_LO_ON_OFF_LIGHT 0x0100 + +// (taken from chip-devices.xml) +#define DEVICE_TYPE_ROOT_NODE 0x0016 +// (taken from chip-devices.xml) +#define DEVICE_TYPE_BRIDGE 0x000e + +// Device Version for dynamic endpoints: +#define DEVICE_VERSION_DEFAULT 1 + +/* REVISION definitions: + */ + +#define ZCL_DESCRIPTOR_CLUSTER_REVISION (1u) +#define ZCL_BRIDGED_DEVICE_BASIC_CLUSTER_REVISION (1u) +#define ZCL_FIXED_LABEL_CLUSTER_REVISION (1u) +#define ZCL_ON_OFF_CLUSTER_REVISION (4u) + +int AddDeviceEndpoint(SubDevice * dev, EmberAfEndpointType * ep, const Span & deviceTypeList, + const Span & dataVersionStorage, chip::EndpointId parentEndpointId); +CHIP_ERROR RemoveDeviceEndpoint(SubDevice * dev); +EmberAfStatus HandleReadBridgedDeviceBasicAttribute(SubDevice * dev, chip::AttributeId attributeId, uint8_t * buffer, + uint16_t maxReadLength); +void HandleDeviceStatusChanged(SubDevice * dev, SubDevice::Changed_t itemChangedMask); +void Init_Bridge_Endpoint(); +#ifdef __cplusplus +} +#endif diff --git a/examples/bridge-app/asr/subdevice/subdevice_test.cpp b/examples/bridge-app/asr/subdevice/subdevice_test.cpp new file mode 100644 index 00000000000000..f4998294043925 --- /dev/null +++ b/examples/bridge-app/asr/subdevice/subdevice_test.cpp @@ -0,0 +1,159 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "SubDevice.h" +#include "SubDeviceManager.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; +using namespace ::chip::Platform; +using namespace ::chip::app::Clusters; + +#if ENABLE_ASR_BRIDGE_SUBDEVICE_TEST + +static const int kNodeLabelSize = 32; +// Current ZCL implementation of Struct uses a max-size array of 254 bytes +static const int kDescriptorAttributeArraySize = 254; + +// 4 Bridged devices +static SubDevice gLight1("Light 1", "Office"); +static SubDevice gLight2("Light 2", "Office"); +static SubDevice gLight3("Light 3", "Kitchen"); +static SubDevice gLight4("Light 4", "Den"); + +/* BRIDGED DEVICE ENDPOINT: contains the following clusters: + - On/Off + - Descriptor + - Bridged Device Basic +*/ + +// Declare On/Off cluster attributes +DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(onOffAttrs) +DECLARE_DYNAMIC_ATTRIBUTE(OnOff::Attributes::OnOff::Id, BOOLEAN, 1, 0), /* on/off */ + DECLARE_DYNAMIC_ATTRIBUTE_LIST_END(); + +// Declare Descriptor cluster attributes +DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(descriptorAttrs) +DECLARE_DYNAMIC_ATTRIBUTE(Descriptor::Attributes::DeviceTypeList::Id, ARRAY, kDescriptorAttributeArraySize, 0), /* device list */ + DECLARE_DYNAMIC_ATTRIBUTE(Descriptor::Attributes::ServerList::Id, ARRAY, kDescriptorAttributeArraySize, 0), /* server list */ + DECLARE_DYNAMIC_ATTRIBUTE(Descriptor::Attributes::ClientList::Id, ARRAY, kDescriptorAttributeArraySize, 0), /* client list */ + DECLARE_DYNAMIC_ATTRIBUTE(Descriptor::Attributes::PartsList::Id, ARRAY, kDescriptorAttributeArraySize, 0), /* parts list */ + DECLARE_DYNAMIC_ATTRIBUTE_LIST_END(); + +// Declare Bridged Device Basic information cluster attributes +DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(bridgedDeviceBasicAttrs) +DECLARE_DYNAMIC_ATTRIBUTE(BridgedDeviceBasicInformation::Attributes::NodeLabel::Id, CHAR_STRING, kNodeLabelSize, 0), /* NodeLabel */ + DECLARE_DYNAMIC_ATTRIBUTE(BridgedDeviceBasicInformation::Attributes::Reachable::Id, BOOLEAN, 1, 0), /* Reachable */ + DECLARE_DYNAMIC_ATTRIBUTE_LIST_END(); + +// Declare Cluster List for Bridged Light endpoint +// TODO: It's not clear whether it would be better to get the command lists from +// the ZAP config on our last fixed endpoint instead. +constexpr CommandId onOffIncomingCommands[] = { + app::Clusters::OnOff::Commands::Off::Id, + app::Clusters::OnOff::Commands::On::Id, + app::Clusters::OnOff::Commands::Toggle::Id, + app::Clusters::OnOff::Commands::OffWithEffect::Id, + app::Clusters::OnOff::Commands::OnWithRecallGlobalScene::Id, + app::Clusters::OnOff::Commands::OnWithTimedOff::Id, + kInvalidCommandId, +}; + +DECLARE_DYNAMIC_CLUSTER_LIST_BEGIN(bridgedLightClusters) +DECLARE_DYNAMIC_CLUSTER(OnOff::Id, onOffAttrs, onOffIncomingCommands, nullptr), + DECLARE_DYNAMIC_CLUSTER(Descriptor::Id, descriptorAttrs, nullptr, nullptr), + // DECLARE_DYNAMIC_CLUSTER(BridgedDeviceBasic::Id, bridgedDeviceBasicAttrs, nullptr, nullptr) + DECLARE_DYNAMIC_CLUSTER(BridgedDeviceBasicInformation::Id, bridgedDeviceBasicAttrs, nullptr, + nullptr) DECLARE_DYNAMIC_CLUSTER_LIST_END; + +// Declare Bridged Light endpoint +DECLARE_DYNAMIC_ENDPOINT(bridgedLightEndpoint, bridgedLightClusters); + +DataVersion gLight1DataVersions[ArraySize(bridgedLightClusters)]; +DataVersion gLight2DataVersions[ArraySize(bridgedLightClusters)]; +DataVersion gLight3DataVersions[ArraySize(bridgedLightClusters)]; +DataVersion gLight4DataVersions[ArraySize(bridgedLightClusters)]; + +const EmberAfDeviceType gRootDeviceTypes[] = { { DEVICE_TYPE_ROOT_NODE, DEVICE_VERSION_DEFAULT } }; +const EmberAfDeviceType gAggregateNodeDeviceTypes[] = { { DEVICE_TYPE_BRIDGE, DEVICE_VERSION_DEFAULT } }; + +const EmberAfDeviceType gBridgedOnOffDeviceTypes[] = { { DEVICE_TYPE_LO_ON_OFF_LIGHT, DEVICE_VERSION_DEFAULT }, + { DEVICE_TYPE_BRIDGED_NODE, DEVICE_VERSION_DEFAULT } }; + +extern "C" void Sync_SubDevice_test(void); +extern "C" void Add_SubDevice_test(void); +extern "C" void Remove_SubDevice_test(void); + +void Sync_SubDevice_test() +{ + gLight1.SetReachable(true); + gLight2.SetReachable(true); + gLight3.SetReachable(true); + gLight4.SetReachable(true); + + // Whenever bridged device changes its state + gLight1.SetChangeCallback(&HandleDeviceStatusChanged); + gLight2.SetChangeCallback(&HandleDeviceStatusChanged); + gLight3.SetChangeCallback(&HandleDeviceStatusChanged); + gLight4.SetChangeCallback(&HandleDeviceStatusChanged); + + // Add lights 1..4 --> will be mapped to ZCL endpoints 3..6 + AddDeviceEndpoint(&gLight1, &bridgedLightEndpoint, Span(gBridgedOnOffDeviceTypes), + Span(gLight1DataVersions), 1); + AddDeviceEndpoint(&gLight2, &bridgedLightEndpoint, Span(gBridgedOnOffDeviceTypes), + Span(gLight2DataVersions), 1); + AddDeviceEndpoint(&gLight3, &bridgedLightEndpoint, Span(gBridgedOnOffDeviceTypes), + Span(gLight3DataVersions), 1); + AddDeviceEndpoint(&gLight4, &bridgedLightEndpoint, Span(gBridgedOnOffDeviceTypes), + Span(gLight4DataVersions), 1); +} + +void Add_SubDevice_test() +{ + gLight2.SetReachable(true); + gLight2.SetChangeCallback(&HandleDeviceStatusChanged); + // Re-add Light 2 -- > will be mapped to ZCL endpoint 7 + AddDeviceEndpoint(&gLight2, &bridgedLightEndpoint, Span(gBridgedOnOffDeviceTypes), + Span(gLight2DataVersions), 1); +} + +void Remove_SubDevice_test() +{ + gLight2.SetChangeCallback(NULL); + gLight2.SetReachable(false); + // Remove Light 2 -- Others Lights remain + RemoveDeviceEndpoint(&gLight2); +} +#endif // ENABLE_ASR_BRIDGE_SUBDEVICE_TEST diff --git a/examples/bridge-app/asr/third_party/connectedhomeip b/examples/bridge-app/asr/third_party/connectedhomeip new file mode 120000 index 00000000000000..11a54ed360106c --- /dev/null +++ b/examples/bridge-app/asr/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../ \ No newline at end of file diff --git a/examples/light-switch-app/asr/.gn b/examples/light-switch-app/asr/.gn new file mode 100755 index 00000000000000..8d75f1eafcdb89 --- /dev/null +++ b/examples/light-switch-app/asr/.gn @@ -0,0 +1,29 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/light-switch-app/asr/BUILD.gn b/examples/light-switch-app/asr/BUILD.gn new file mode 100755 index 00000000000000..68f0db7fbe4ef7 --- /dev/null +++ b/examples/light-switch-app/asr/BUILD.gn @@ -0,0 +1,136 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/asr.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("${asr_sdk_build_root}/asr_sdk.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/src/lib/lib.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/asr/asr_executable.gni") + +import("//cfg.gni") + +assert(current_os == "freertos") + +asr_project_dir = "${chip_root}/examples/light-switch-app/asr" +examples_plat_dir = "${chip_root}/examples/platform/asr" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + +asr_sdk_sources("light_switch_app_sdk_sources") { + include_dirs = [ + "${chip_root}/src/platform/ASR", + "${asr_project_dir}/include", + "${examples_plat_dir}", + ] + + defines = [ + "ASR_LOG_ENABLED=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + ] + + if (chip_enable_factory_data) { + defines += [ + "CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER=1", + "CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER=1", + ] + } + + if (chip_lwip_ip6_hook) { + defines += [ + "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", + "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", + ] + } + + sources = [ "${asr_project_dir}/include/CHIPProjectConfig.h" ] + + public_configs = [ "${asr_sdk_build_root}:asr_sdk_config" ] +} + +asr_executable("light_switch_app") { + include_dirs = [] + defines = [] + output_name = "chip-asr-light-switch-example.out" + + public_deps = [ + ":light_switch_app_sdk_sources", + "${chip_root}/examples/common/QRCode", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs += [ + "include", + "${examples_plat_dir}", + "${asr_project_dir}/include", + "${chip_root}/src/lib", + ] + + sources = [ + "${examples_plat_dir}/CHIPDeviceManager.cpp", + "${examples_plat_dir}/LEDWidget.cpp", + "${examples_plat_dir}/init_Matter.cpp", + "${examples_plat_dir}/init_asrPlatform.cpp", + "${examples_plat_dir}/shell/matter_shell.cpp", + "src/AppTask.cpp", + "src/BindingHandler.cpp", + "src/ButtonHandler.cpp", + "src/DeviceCallbacks.cpp", + "src/LEDManager.cpp", + "src/LightSwitch.cpp", + "src/main.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${examples_plat_dir}/init_OTARequestor.cpp" ] + } + + defines = [ "ASR_NETWORK_LAYER_BLE=${chip_config_network_layer_ble}" ] + + if (chip_build_libshell) { + defines += [ "CONFIG_ENABLE_CHIP_SHELL=1" ] + sources += [ "${examples_plat_dir}/shell/launch_shell.cpp" ] + include_dirs += [ "${examples_plat_dir}/shell" ] + } + + defines += [ "GENERIC_SWITCH_ENDPOINT=1" ] + + public_deps += + [ "${chip_root}/examples/light-switch-app/light-switch-common" ] + + output_dir = root_out_dir + + if (chip_print_memory_usage) { + ldflags = [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } +} + +group("asr") { + deps = [ ":light_switch_app" ] +} + +group("default") { + deps = [ ":asr" ] +} diff --git a/examples/light-switch-app/asr/README.md b/examples/light-switch-app/asr/README.md new file mode 100755 index 00000000000000..c7eba7e2ea116e --- /dev/null +++ b/examples/light-switch-app/asr/README.md @@ -0,0 +1,52 @@ +# Matter ASR Light Switch Example + +This example demonstrates the Matter Light Switch application on ASR platform. + +--- + +- [Matter ASR Light Switch Example](#matter-asr-light-switch-example) + - [Supported Chips](#supported-chips) + - [Building and Commissioning](#building-and-commissioning) + - [Testing the example](#testing-the-example) + +--- + +## Supported Chips + +The Matter demo application is supported on: + +- ASR582X +- ASR595X + +## Building and Commissioning + +Please refer +[Building and Commissioning](../../../docs/guides/asr_getting_started_guide.md#building-the-example-application) +guides to get started + +``` +./scripts/build/build_examples.py --target asr-$ASR_BOARD-light-switch build +``` + +## Testing the example + +- An additional lighting device is required to complete this example. +- Commission lighting device with node-id `1` +- Commission light-switch device with node-id `2` +- After successful commissioning, use the `chip-tool` to write the ACL in + Lighting device to allow access from light-switch device and chip-tool. + ``` + ./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null },{"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": [2], "targets": null }]' 1 0 + ``` +- After successful commissioning, use the `chip-tool` for binding in + light-switch. + ``` + ./chip-tool binding write binding '[{"fabricIndex": 1, "node":1, "endpoint":1, "cluster":6}]' 2 1 + ``` +- Light switch button + + This demo uses button to test changing the state of lighting: + + | Name | Pin | + | :----: | :--: | + | BUTTON | PAD6 | diff --git a/examples/light-switch-app/asr/args.gni b/examples/light-switch-app/asr/args.gni new file mode 100755 index 00000000000000..d46ba8ec90759f --- /dev/null +++ b/examples/light-switch-app/asr/args.gni @@ -0,0 +1,27 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("//cfg.gni") +import("${chip_root}/src/platform/ASR/args.gni") + +asr_target_project = + get_label_info(":light_switch_app_sdk_sources", "label_no_toolchain") + +declare_args() { + # Disable lock tracking, since our FreeRTOS configuration does not set + # INCLUDE_xSemaphoreGetMutexHolder + chip_stack_lock_tracking = "none" +} diff --git a/examples/light-switch-app/asr/build_overrides b/examples/light-switch-app/asr/build_overrides new file mode 120000 index 00000000000000..194ee0b812dc3d --- /dev/null +++ b/examples/light-switch-app/asr/build_overrides @@ -0,0 +1 @@ +../../build_overrides/ \ No newline at end of file diff --git a/examples/light-switch-app/asr/cfg.gni b/examples/light-switch-app/asr/cfg.gni new file mode 100755 index 00000000000000..15fe50e79efb6d --- /dev/null +++ b/examples/light-switch-app/asr/cfg.gni @@ -0,0 +1,23 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + chip_enable_factory_data = false + + chip_lwip_ip6_hook = false + + setupPinCode = 20202021 + + setupDiscriminator = 3840 +} diff --git a/examples/light-switch-app/asr/include/AppConfig.h b/examples/light-switch-app/asr/include/AppConfig.h new file mode 100644 index 00000000000000..88fefe79fd45cc --- /dev/null +++ b/examples/light-switch-app/asr/include/AppConfig.h @@ -0,0 +1,74 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#ifdef CFG_PLF_RV32 +#include "asr_gpio.h" +#include "asr_pinmux.h" +#define duet_gpio_dev_t asr_gpio_dev_t +#else +#include "duet_gpio.h" +#include "duet_pinmux.h" +#endif + +#define TASK_NAME "APP" +#define MATTER_DEVICE_NAME "ASR-Switch" +#define APP_TASK_STACK_SIZE (4096) +#define APP_EVENT_QUEUE_SIZE 10 + +#define GPIO_TASK_NAME "gpio" +#define GPIO_TASK_STACK_SIZE 1024 + +#define BUTTON_DEBOUNCE_PERIOD_MS 50 + +#define BUTTON_PRESSED 0 +#define BUTTON_RELEASED 1 + +#define SWITCH1_BUTTON GPIO6_INDEX +#define SWITCH2_BUTTON GPIO7_INDEX +#define GENERIC_SWITCH_BUTTON GPIO7_INDEX +#define SYSTEM_STATE_LED GPIO12_INDEX +#define SWITCH_LED GPIO13_INDEX + +// Time it takes in ms for the simulated actuator to move from one +// state to another. +#define ACTUATOR_MOVEMENT_PERIOS_MS 2000 + +// ---- Lock Example SWU Config ---- +#define SWU_INTERVAl_WINDOW_MIN_MS (23 * 60 * 60 * 1000) // 23 hours +#define SWU_INTERVAl_WINDOW_MAX_MS (24 * 60 * 60 * 1000) // 24 hours + +// ---- Thread Polling Config ---- +#define THREAD_ACTIVE_POLLING_INTERVAL_MS 100 +#define THREAD_INACTIVE_POLLING_INTERVAL_MS 1000 + +// ASR Logging +#ifdef __cplusplus +extern "C" { +#endif + +void appError(int err); +void ASR_LOG(const char * aFormat, ...); + +#ifdef __cplusplus +} + +#include +void appError(CHIP_ERROR error); +#endif diff --git a/examples/light-switch-app/asr/include/AppEvent.h b/examples/light-switch-app/asr/include/AppEvent.h new file mode 100755 index 00000000000000..49ded0945896f9 --- /dev/null +++ b/examples/light-switch-app/asr/include/AppEvent.h @@ -0,0 +1,64 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +struct AppEvent +{ + constexpr static uint8_t kButtonPushEvent = 1; + constexpr static uint8_t kButtonReleaseEvent = 0; + + enum AppEventTypes + { + kEventType_StartBLEAdvertising, + kEventType_Button, + kEventType_Timer, + kEventType_UpdateLedState, + kEventType_IdentifyStart, + kEventType_IdentifyStop, + kEventType_Light, + kEventType_Install, + }; + + uint16_t Type; + + union + { + struct + { + uint8_t PinNo; + uint8_t Action; + } ButtonEvent; + struct + { + uint8_t TimerType; + void * Context; + } TimerEvent; + struct + { + uint8_t Action; + int32_t Actor; + } LightEvent; + }; + + EventHandler Handler; +}; diff --git a/examples/light-switch-app/asr/include/AppTask.h b/examples/light-switch-app/asr/include/AppTask.h new file mode 100755 index 00000000000000..c103fd6f60944e --- /dev/null +++ b/examples/light-switch-app/asr/include/AppTask.h @@ -0,0 +1,88 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "AppEvent.h" + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include +#include + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) + +class AppTask +{ + +public: + CHIP_ERROR StartAppTask(); + void PostEvent(const AppEvent * event); + static void AppTaskMain(void * pvParameter); + static void UpdateClusterState(void); + static void ButtonEventHandler(uint8_t, uint8_t); + static void UpdateStatusLED(); + +private: + enum class Timer : uint8_t + { + Function, + DimmerTrigger, + Dimmer + }; + enum class TimerFunction : uint8_t + { + NoneSelected = 0, + SoftwareUpdate, + FactoryReset + }; + TimerFunction mFunction = TimerFunction::NoneSelected; + + enum class Button : uint8_t + { + Function, + Dimmer, + }; + + friend AppTask & GetAppTask(void); + static AppTask sAppTask; + + CHIP_ERROR Init(); + + void DispatchEvent(AppEvent * event); + + static void ButtonPushHandler(AppEvent *); + static void ButtonReleaseHandler(AppEvent *); + static void StartBLEAdvertisingHandler(AppEvent *); + + static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent *, intptr_t); +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/light-switch-app/asr/include/BindingHandler.h b/examples/light-switch-app/asr/include/BindingHandler.h new file mode 100755 index 00000000000000..28509842b7ed84 --- /dev/null +++ b/examples/light-switch-app/asr/include/BindingHandler.h @@ -0,0 +1,62 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "app-common/zap-generated/ids/Clusters.h" +#include "app-common/zap-generated/ids/Commands.h" +#include "lib/core/CHIPError.h" +#include +#include +#include +#include + +class BindingHandler +{ +public: + struct BindingData + { + chip::EndpointId EndpointId; + chip::CommandId CommandId; + chip::ClusterId ClusterId; + uint8_t Value; + bool IsGroup{ false }; + }; + + void Init(); + void PrintBindingTable(); + bool IsGroupBound(); + + static void SwitchWorkerHandler(intptr_t); + static void OnInvokeCommandFailure(BindingData & aBindingData, CHIP_ERROR aError); + + static BindingHandler & GetInstance() + { + static BindingHandler sBindingHandler; + return sBindingHandler; + } + +private: + static void OnOffProcessCommand(chip::CommandId, const EmberBindingTableEntry &, chip::OperationalDeviceProxy *, void *); + static void LevelControlProcessCommand(chip::CommandId, const EmberBindingTableEntry &, chip::OperationalDeviceProxy *, void *); + static void LightSwitchChangedHandler(const EmberBindingTableEntry &, chip::OperationalDeviceProxy *, void *); + static void LightSwitchContextReleaseHandler(void * context); + static void InitInternal(intptr_t); + + bool mCaseSessionRecovered = false; +}; diff --git a/examples/light-switch-app/asr/include/ButtonHandler.h b/examples/light-switch-app/asr/include/ButtonHandler.h new file mode 100644 index 00000000000000..8e853ba46b1da1 --- /dev/null +++ b/examples/light-switch-app/asr/include/ButtonHandler.h @@ -0,0 +1,38 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "AppEvent.h" +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include +#ifdef CFG_PLF_RV32 +#include "asr_gpio.h" +#else +#include "duet_gpio.h" +#endif + +class ButtonHandler +{ +public: + static void Init(void); + +private: + static void GpioInit(void); +}; diff --git a/examples/light-switch-app/asr/include/CHIPProjectConfig.h b/examples/light-switch-app/asr/include/CHIPProjectConfig.h new file mode 100755 index 00000000000000..df81858b4f3bc0 --- /dev/null +++ b/examples/light-switch-app/asr/include/CHIPProjectConfig.h @@ -0,0 +1,111 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 1 +#endif + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS + * + * Enable recording UTC timestamps. + */ +#define CHIP_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS 1 + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) + +/** + * @def CHIP_CONFIG_MRP_DEFAULT_ACTIVE_RETRY_INTERVAL + * + * @brief + * Active retransmit interval, or time to wait before retransmission after + * subsequent failures in milliseconds. + * + * This is the default value, that might be adjusted by end device depending on its + * needs (e.g. sleeping period) using Service Discovery TXT record CRA key. + * + */ +#define CHIP_CONFIG_MRP_DEFAULT_ACTIVE_RETRY_INTERVAL (2000_ms32) diff --git a/examples/light-switch-app/asr/include/DeviceCallbacks.h b/examples/light-switch-app/asr/include/DeviceCallbacks.h new file mode 100755 index 00000000000000..204263cdaed4b2 --- /dev/null +++ b/examples/light-switch-app/asr/include/DeviceCallbacks.h @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.h + * + * Implementations for the DeviceManager callbacks for this application + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include +#include +#include + +class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks +{ +public: + void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg) override; + void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value) override; + +private: + void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); +}; diff --git a/examples/light-switch-app/asr/include/LEDManager.h b/examples/light-switch-app/asr/include/LEDManager.h new file mode 100644 index 00000000000000..a8c29a24a61e07 --- /dev/null +++ b/examples/light-switch-app/asr/include/LEDManager.h @@ -0,0 +1,48 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include "AppConfig.h" +#include + +#ifndef LED_Manager_H +#define LED_Manager_H + +class LEDManager +{ +public: + static void InitGpio(void); + void Init(uint8_t ledNum); + void Set(bool state); + void Invert(void); + void Blink(uint32_t changeRateMS); + void Blink(uint32_t onTimeMS, uint32_t offTimeMS); + void Animate(); + +private: + uint64_t mLastChangeTimeMS; + uint32_t mBlinkOnTimeMS; + uint32_t mBlinkOffTimeMS; + uint8_t mGPIONum; + bool mState; + duet_gpio_dev_t gpio; + + void DoSet(bool state); +}; + +#endif // LED_Manager_H diff --git a/examples/light-switch-app/asr/include/LightSwitch.h b/examples/light-switch-app/asr/include/LightSwitch.h new file mode 100644 index 00000000000000..746d46286cb225 --- /dev/null +++ b/examples/light-switch-app/asr/include/LightSwitch.h @@ -0,0 +1,53 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +class LightSwitch +{ +public: + enum class Action : uint8_t + { + Toggle, /// Switch state on lighting-app device + On, /// Turn on light on lighting-app device + Off /// Turn off light on lighting-app device + }; + + void Init(chip::EndpointId aLightSwitchEndpoint); + void InitGeneric(chip::EndpointId aGenericSwitchEndpoint); + void InitiateActionSwitch(Action); + void SwitchChangeBrightness(uint16_t sBrightness); + void GenericSwitchInitialPress(); + void GenericSwitchReleasePress(); + chip::EndpointId GetLightSwitchEndpointId() { return mLightSwitchEndpoint; } + + static LightSwitch & GetInstance() + { + static LightSwitch sLightSwitch; + return sLightSwitch; + } + +private: + constexpr static auto kMaximumBrightness = 254; + + chip::EndpointId mLightSwitchEndpoint; + chip::EndpointId mGenericSwitchEndpointId; +}; diff --git a/examples/light-switch-app/asr/src/AppTask.cpp b/examples/light-switch-app/asr/src/AppTask.cpp new file mode 100644 index 00000000000000..8836459a7564f2 --- /dev/null +++ b/examples/light-switch-app/asr/src/AppTask.cpp @@ -0,0 +1,509 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" +#include "AppConfig.h" +#include "AppEvent.h" +#include "BindingHandler.h" +#include "ButtonHandler.h" +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include "LEDManager.h" +#include "LightSwitch.h" +#include "init_Matter.h" +#include "lega_rtos_api.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::app; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; + +LightSwitch kLightSwitch1; + +namespace { +TaskHandle_t sAppTaskHandle; +QueueHandle_t sAppEventQueue; + +LEDManager sStatusLED; +LEDManager sSwitchLED; + +constexpr EndpointId kLightSwitch1_EndpointId = 1; +#if DUAL_LIGHTSWITCH_ENDPOINT +LightSwitch kLightSwitch2; +constexpr EndpointId kLightSwitch2_EndpointId = 2; +#endif +#if GENERIC_SWITCH_ENDPOINT +LightSwitch GenericSwitch; +constexpr EndpointId kGenericSwitchEndpointId = 2; +#endif + +constexpr size_t kAppEventQueueSize = 10; + +constexpr EndpointId kNetworkCommissioningEndpointMain = 0; +constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; + +app::Clusters::NetworkCommissioning::Instance + sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, + &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); + +void NetWorkCommissioningInstInit() +{ + sWiFiNetworkCommissioningInstance.Init(); + + // We only have network commissioning on endpoint 0. + emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); +} + +Clusters::Identify::EffectIdentifierEnum sIdentifyEffect = Clusters::Identify::EffectIdentifierEnum::kStopEffect; + +namespace { +void OnTriggerIdentifyEffectCompleted(chip::System::Layer * systemLayer, void * appState) +{ + sIdentifyEffect = Clusters::Identify::EffectIdentifierEnum::kStopEffect; +} +} // namespace + +void OnTriggerIdentifyEffect(Identify * identify) +{ + sIdentifyEffect = identify->mCurrentEffectIdentifier; + + if (identify->mCurrentEffectIdentifier == Clusters::Identify::EffectIdentifierEnum::kChannelChange) + { + ChipLogProgress(Zcl, "IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE - Not supported, use effect varriant %d", + to_underlying(identify->mEffectVariant)); + sIdentifyEffect = static_cast(identify->mEffectVariant); + } + + switch (sIdentifyEffect) + { + case Clusters::Identify::EffectIdentifierEnum::kBlink: + case Clusters::Identify::EffectIdentifierEnum::kBreathe: + case Clusters::Identify::EffectIdentifierEnum::kOkay: + (void) chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds16(5), OnTriggerIdentifyEffectCompleted, + identify); + break; + case Clusters::Identify::EffectIdentifierEnum::kFinishEffect: + (void) chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerIdentifyEffectCompleted, identify); + (void) chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds16(1), OnTriggerIdentifyEffectCompleted, + identify); + break; + case Clusters::Identify::EffectIdentifierEnum::kStopEffect: + (void) chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerIdentifyEffectCompleted, identify); + sIdentifyEffect = Clusters::Identify::EffectIdentifierEnum::kStopEffect; + break; + default: + ChipLogProgress(Zcl, "No identifier effect"); + } +} + +Identify gIdentify = { + chip::EndpointId{ 1 }, + [](Identify *) { ChipLogProgress(Zcl, "onIdentifyStart"); }, + [](Identify *) { ChipLogProgress(Zcl, "onIdentifyStop"); }, + Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator, + OnTriggerIdentifyEffect, +}; +} // namespace + +AppTask AppTask::sAppTask; +static DeviceCallbacks EchoCallbacks; + +CHIP_ERROR AppTask::StartAppTask() +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); + if (sAppEventQueue == NULL) + { + ASR_LOG("Failed to allocate app event queue"); + appError(APP_ERROR_EVENT_QUEUE_FAILED); + } + + // Start App task. + xTaskCreate(AppTaskMain, TASK_NAME, APP_TASK_STACK_SIZE, 0, 2, &sAppTaskHandle); + err = (sAppTaskHandle == nullptr) ? APP_ERROR_CREATE_TASK_FAILED : CHIP_NO_ERROR; + + return err; +} + +CHIP_ERROR AppTask::Init() +{ + ASR_LOG("App Task started"); + + if (MatterInitializer::Init_Matter_Stack(MATTER_DEVICE_NAME) != CHIP_NO_ERROR) + return CHIP_ERROR_INTERNAL; + + CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); + + if (deviceMgr.Init(&EchoCallbacks) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + if (MatterInitializer::Init_Matter_Server() != CHIP_NO_ERROR) + return CHIP_ERROR_INTERNAL; + + NetWorkCommissioningInstInit(); + + kLightSwitch1.Init(kLightSwitch1_EndpointId); +#if DUAL_LIGHTSWITCH_ENDPOINT + kLightSwitch2.Init(kLightSwitch2_EndpointId); +#endif +#if GENERIC_SWITCH_ENDPOINT + GenericSwitch.InitGeneric(kGenericSwitchEndpointId); +#endif + // Initialize LEDs + LEDManager::InitGpio(); + + sStatusLED.Init(SYSTEM_STATE_LED); + sStatusLED.Set(false); + + sSwitchLED.Init(SWITCH_LED); + sSwitchLED.Set(false); + UpdateStatusLED(); + + // Initialise WSTK buttons PB0 and PB1 (including debounce). + ButtonHandler::Init(); + + UpdateClusterState(); + + ASR_LOG("Current Software Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + ConfigurationMgr().LogDeviceConfig(); + + // Print setup info + PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); + + return CHIP_NO_ERROR; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + AppEvent event; + + CHIP_ERROR err = sAppTask.Init(); + if (err != CHIP_NO_ERROR) + { + ASR_LOG("AppTask.Init() failed"); + appError(err); + } + + while (true) + { + BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10)); + while (eventReceived == pdTRUE) + { + sAppTask.DispatchEvent(&event); + eventReceived = xQueueReceive(sAppEventQueue, &event, 0); + } + + sStatusLED.Animate(); + sSwitchLED.Animate(); + } +} + +void AppTask::PostEvent(const AppEvent * aEvent) +{ + if (sAppEventQueue != NULL) + { + BaseType_t status; + if (lega_rtos_is_in_interrupt_context()) + { + BaseType_t higherPrioTaskWoken = pdFALSE; + status = xQueueSendFromISR(sAppEventQueue, aEvent, &higherPrioTaskWoken); + +#ifdef portYIELD_FROM_ISR + portYIELD_FROM_ISR(higherPrioTaskWoken); +#elif portEND_SWITCHING_ISR // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + portEND_SWITCHING_ISR(higherPrioTaskWoken); +#else // portYIELD_FROM_ISR or portEND_SWITCHING_ISR +#error "Must have portYIELD_FROM_ISR or portEND_SWITCHING_ISR" +#endif // portYIELD_FROM_ISR or portEND_SWITCHING_ISR + } + else + { + status = xQueueSend(sAppEventQueue, aEvent, 1); + } + + if (!status) + ASR_LOG("Failed to post event to app task event queue"); + } + else + { + ASR_LOG("Event Queue is NULL should never happen"); + } +} + +void AppTask::DispatchEvent(AppEvent * aEvent) +{ + if (aEvent->Handler) + { + aEvent->Handler(aEvent); + } + else + { + ASR_LOG("Event received with no handler. Dropping event."); + } +} + +void AppTask::UpdateClusterState(void) {} + +#define SWITCH_Toggle + +//#define SWITCH_DELAY_ONOFF + +#if DUAL_LIGHTSWITCH_ENDPOINT +#undef SWITCH_Toggle +#undef SWITCH_DELAY_ONOFF +#endif + +#ifdef SWITCH_DELAY_ONOFF +#define SWITCH_TIMER "switch_delay_timer" +#define SWITCH_DELAY_TIME 5 * 1000 +static TimerHandle_t Switch_TimerHandle; +void Switch_Delay_CallBack(TimerHandle_t xTimer) +{ + ASR_LOG("Switch1 OFF!"); + kLightSwitch1.InitiateActionSwitch(LightSwitch::Action::Off); +} +#endif + +void AppTask::ButtonPushHandler(AppEvent * aEvent) +{ + if (aEvent->Type == AppEvent::kEventType_Button) + { + switch (aEvent->ButtonEvent.PinNo) + { + case SWITCH1_BUTTON: +#ifdef SWITCH_Toggle + // ASR_LOG("Switch1 Button Pushed."); +#endif +#if DUAL_LIGHTSWITCH_ENDPOINT + ASR_LOG("Switch1 ON!"); + kLightSwitch1.InitiateActionSwitch(LightSwitch::Action::On); +#endif +#ifdef SWITCH_DELAY_ONOFF + { + ASR_LOG("Switch1 ON ,delay %d ms!", SWITCH_DELAY_TIME); + kLightSwitch1.InitiateActionSwitch(LightSwitch::Action::On); + + if (Switch_TimerHandle == NULL) + { + Switch_TimerHandle = + xTimerCreate(SWITCH_TIMER, pdMS_TO_TICKS(SWITCH_DELAY_TIME), pdFALSE, NULL, Switch_Delay_CallBack); + if (Switch_TimerHandle == NULL) + { + ASR_LOG("Failed to create a timer"); + } + } + if (xTimerIsTimerActive(Switch_TimerHandle)) + { + ASR_LOG("switch timer already started!"); + if (xTimerStop(Switch_TimerHandle, 0) == pdFAIL) + { + ASR_LOG("switch timer stop() failed"); + } + } + if (xTimerChangePeriod(Switch_TimerHandle, pdMS_TO_TICKS(SWITCH_DELAY_TIME), 100) != pdPASS) + { + ASR_LOG("switch timer start() failed"); + } + } +#endif + break; +#if DUAL_LIGHTSWITCH_ENDPOINT + case SWITCH2_BUTTON: + ASR_LOG("Switch2 ON!"); + kLightSwitch2.InitiateActionSwitch(LightSwitch::Action::On); + break; +#endif +#if GENERIC_SWITCH_ENDPOINT + case GENERIC_SWITCH_BUTTON: + ASR_LOG("GenericSwitch: InitialPress"); + GenericSwitch.GenericSwitchInitialPress(); + break; +#endif + default: + break; + } + } +} + +void AppTask::ButtonReleaseHandler(AppEvent * aEvent) +{ + + if (aEvent->Type == AppEvent::kEventType_Button) + { + switch (aEvent->ButtonEvent.PinNo) + { + case SWITCH1_BUTTON: +#ifdef SWITCH_Toggle + sSwitchLED.Set(false); + ASR_LOG("Switch1 Toggle!"); + kLightSwitch1.InitiateActionSwitch(LightSwitch::Action::Toggle); +#endif +#if DUAL_LIGHTSWITCH_ENDPOINT + ASR_LOG("Switch1 OFF!"); + kLightSwitch1.InitiateActionSwitch(LightSwitch::Action::Off); +#endif + break; +#if DUAL_LIGHTSWITCH_ENDPOINT + case SWITCH2_BUTTON: + ASR_LOG("Switch2 OFF!"); + kLightSwitch2.InitiateActionSwitch(LightSwitch::Action::Off); + break; +#endif +#if GENERIC_SWITCH_ENDPOINT + case GENERIC_SWITCH_BUTTON: + ASR_LOG("GenericSwitch: ShortRelease"); + GenericSwitch.GenericSwitchReleasePress(); + break; +#endif + default: + break; + } + } +} + +void AppTask::StartBLEAdvertisingHandler(AppEvent * aEvent) +{ + /// Don't allow on starting Matter service BLE advertising after Thread provisioning. + if (Server::GetInstance().GetFabricTable().FabricCount() != 0) + { + ASR_LOG("Matter service BLE advertising not started - device is already commissioned"); + return; + } + + if (ConnectivityMgr().IsBLEAdvertisingEnabled()) + { + ASR_LOG("BLE advertising is already enabled"); + return; + } + + ASR_LOG("Enabling BLE advertising..."); + if (Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() != CHIP_NO_ERROR) + { + ASR_LOG("OpenBasicCommissioningWindow() failed"); + } +} + +void AppTask::UpdateStatusLED() +{ + bool sHaveBLEConnections = (ConnectivityMgr().NumBLEConnections() != 0); + bool sIsWiFiBLEAdvertising = ConnectivityMgr().IsBLEAdvertisingEnabled(); + bool sIsWiFiProvisioned = ConnectivityMgr().IsWiFiStationProvisioned(); + bool sIsWiFiEnabled = ConnectivityMgr().IsWiFiStationEnabled(); + // Status LED indicates: + // - blinking 1 s - advertising, ready to commission + // - blinking 200 ms - commissioning in progress + // - constant lightning means commissioned with Thread network + if (sIsWiFiBLEAdvertising && !sHaveBLEConnections) + { + sStatusLED.Blink(50, 950); + } + else if (sIsWiFiProvisioned && sIsWiFiEnabled) + { + sStatusLED.Set(true); + } + else if (sHaveBLEConnections) + { + sStatusLED.Blink(30, 170); + } + else + { + sStatusLED.Blink(500); + } +} + +void AppTask::ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction) +{ + + AppEvent buttonEvent; + buttonEvent.Type = AppEvent::kEventType_Button; + + if (btnIdx == SWITCH1_BUTTON) + { + if (btnAction == BUTTON_PRESSED) + { + buttonEvent.ButtonEvent.PinNo = SWITCH1_BUTTON; + buttonEvent.ButtonEvent.Action = AppEvent::kButtonPushEvent; + buttonEvent.Handler = ButtonPushHandler; + sAppTask.PostEvent(&buttonEvent); + } + else if (btnAction == BUTTON_RELEASED) + { + buttonEvent.ButtonEvent.PinNo = SWITCH1_BUTTON; + buttonEvent.ButtonEvent.Action = AppEvent::kButtonReleaseEvent; + buttonEvent.Handler = ButtonReleaseHandler; + sAppTask.PostEvent(&buttonEvent); + } + } +#if DUAL_LIGHTSWITCH_ENDPOINT + else if (btnIdx == SWITCH2_BUTTON) + { + if (btnAction == BUTTON_PRESSED) + { + buttonEvent.ButtonEvent.PinNo = SWITCH2_BUTTON; + buttonEvent.ButtonEvent.Action = AppEvent::kButtonPushEvent; + buttonEvent.Handler = ButtonPushHandler; + sAppTask.PostEvent(&buttonEvent); + } + else if (btnAction == BUTTON_RELEASED) + { + buttonEvent.ButtonEvent.PinNo = SWITCH2_BUTTON; + buttonEvent.ButtonEvent.Action = AppEvent::kButtonReleaseEvent; + buttonEvent.Handler = ButtonReleaseHandler; + sAppTask.PostEvent(&buttonEvent); + } + } +#endif +#if GENERIC_SWITCH_ENDPOINT + else if (btnIdx == GENERIC_SWITCH_BUTTON) + { + if (btnAction == BUTTON_PRESSED) + { + buttonEvent.ButtonEvent.PinNo = GENERIC_SWITCH_BUTTON; + buttonEvent.ButtonEvent.Action = AppEvent::kButtonPushEvent; + buttonEvent.Handler = ButtonPushHandler; + sAppTask.PostEvent(&buttonEvent); + } + else if (btnAction == BUTTON_RELEASED) + { + buttonEvent.ButtonEvent.PinNo = GENERIC_SWITCH_BUTTON; + buttonEvent.ButtonEvent.Action = AppEvent::kButtonReleaseEvent; + buttonEvent.Handler = ButtonReleaseHandler; + sAppTask.PostEvent(&buttonEvent); + } + } +#endif +} diff --git a/examples/light-switch-app/asr/src/BindingHandler.cpp b/examples/light-switch-app/asr/src/BindingHandler.cpp new file mode 100644 index 00000000000000..bb2d1d754fc70f --- /dev/null +++ b/examples/light-switch-app/asr/src/BindingHandler.cpp @@ -0,0 +1,316 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "BindingHandler.h" +#include "AppConfig.h" +#include "app/CommandSender.h" +#include "app/clusters/bindings/BindingManager.h" +#include "app/server/Server.h" +#include "controller/InvokeInteraction.h" +#include "platform/CHIPDeviceLayer.h" +#include +#include + +using namespace chip; +using namespace chip::app; + +void BindingHandler::Init() +{ + // The initialization of binding manager will try establishing connection with unicast peers + // so it requires the Server instance to be correctly initialized. Post the init function to + // the event queue so that everything is ready when initialization is conducted. + chip::DeviceLayer::PlatformMgr().ScheduleWork(InitInternal); +} + +void BindingHandler::OnInvokeCommandFailure(BindingData & aBindingData, CHIP_ERROR aError) +{ + CHIP_ERROR error; + + if (aError == CHIP_ERROR_TIMEOUT && !BindingHandler::GetInstance().mCaseSessionRecovered) + { + ASR_LOG("Response timeout for invoked command, trying to recover CASE session."); + + // Set flag to not try recover session multiple times. + BindingHandler::GetInstance().mCaseSessionRecovered = true; + + // Allocate new object to make sure its life time will be appropriate. + BindingHandler::BindingData * data = Platform::New(); + *data = aBindingData; + + // Establish new CASE session and retrasmit command that was not applied. + error = BindingManager::GetInstance().NotifyBoundClusterChanged(aBindingData.EndpointId, aBindingData.ClusterId, + static_cast(data)); + + if (CHIP_NO_ERROR != error) + { + ASR_LOG("NotifyBoundClusterChanged failed due to: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + } + else + { + ASR_LOG("Binding command was not applied! Reason: %" CHIP_ERROR_FORMAT, aError.Format()); + } +} + +void BindingHandler::OnOffProcessCommand(CommandId aCommandId, const EmberBindingTableEntry & aBinding, + OperationalDeviceProxy * aDevice, void * aContext) +{ + CHIP_ERROR ret = CHIP_NO_ERROR; + BindingData * data = reinterpret_cast(aContext); + + auto onSuccess = [](const ConcreteCommandPath & commandPath, const StatusIB & status, const auto & dataResponse) { + ASR_LOG("Binding command applied successfully!"); + + // If session was recovered and communication works, reset flag to the initial state. + if (BindingHandler::GetInstance().mCaseSessionRecovered) + BindingHandler::GetInstance().mCaseSessionRecovered = false; + }; + + auto onFailure = [dataRef = *data](CHIP_ERROR aError) mutable { BindingHandler::OnInvokeCommandFailure(dataRef, aError); }; + + if (aDevice) + { + // We are validating connection is ready once here instead of multiple times in each case statement below. + VerifyOrDie(aDevice->ConnectionReady()); + } + + switch (aCommandId) + { + case Clusters::OnOff::Commands::Toggle::Id: + Clusters::OnOff::Commands::Toggle::Type toggleCommand; + if (aDevice) + { + ret = Controller::InvokeCommandRequest(aDevice->GetExchangeManager(), aDevice->GetSecureSession().Value(), + aBinding.remote, toggleCommand, onSuccess, onFailure); + } + else + { + + Messaging::ExchangeManager & exchangeMgr = Server::GetInstance().GetExchangeManager(); + ret = Controller::InvokeGroupCommandRequest(&exchangeMgr, aBinding.fabricIndex, aBinding.groupId, toggleCommand); + } + break; + + case Clusters::OnOff::Commands::On::Id: + Clusters::OnOff::Commands::On::Type onCommand; + if (aDevice) + { + ret = Controller::InvokeCommandRequest(aDevice->GetExchangeManager(), aDevice->GetSecureSession().Value(), + aBinding.remote, onCommand, onSuccess, onFailure); + } + else + { + Messaging::ExchangeManager & exchangeMgr = Server::GetInstance().GetExchangeManager(); + ret = Controller::InvokeGroupCommandRequest(&exchangeMgr, aBinding.fabricIndex, aBinding.groupId, onCommand); + } + break; + + case Clusters::OnOff::Commands::Off::Id: + Clusters::OnOff::Commands::Off::Type offCommand; + if (aDevice) + { + ret = Controller::InvokeCommandRequest(aDevice->GetExchangeManager(), aDevice->GetSecureSession().Value(), + aBinding.remote, offCommand, onSuccess, onFailure); + } + else + { + Messaging::ExchangeManager & exchangeMgr = Server::GetInstance().GetExchangeManager(); + ret = Controller::InvokeGroupCommandRequest(&exchangeMgr, aBinding.fabricIndex, aBinding.groupId, offCommand); + } + break; + default: + ASR_LOG("Invalid binding command data - commandId is not supported"); + break; + } + if (CHIP_NO_ERROR != ret) + { + ASR_LOG("Invoke OnOff Command Request ERROR: %s", ErrorStr(ret)); + } +} + +void BindingHandler::LevelControlProcessCommand(CommandId aCommandId, const EmberBindingTableEntry & aBinding, + OperationalDeviceProxy * aDevice, void * aContext) +{ + CHIP_ERROR ret = CHIP_NO_ERROR; + BindingData * data = reinterpret_cast(aContext); + + auto onSuccess = [](const ConcreteCommandPath & commandPath, const StatusIB & status, const auto & dataResponse) { + ASR_LOG("Binding command applied successfully!"); + + // If session was recovered and communication works, reset flag to the initial state. + if (BindingHandler::GetInstance().mCaseSessionRecovered) + BindingHandler::GetInstance().mCaseSessionRecovered = false; + }; + + auto onFailure = [dataRef = *data](CHIP_ERROR aError) mutable { BindingHandler::OnInvokeCommandFailure(dataRef, aError); }; + + if (aDevice) + { + // We are validating connection is ready once here instead of multiple times in each case statement below. + VerifyOrDie(aDevice->ConnectionReady()); + } + + switch (aCommandId) + { + case Clusters::LevelControl::Commands::MoveToLevel::Id: { + Clusters::LevelControl::Commands::MoveToLevel::Type moveToLevelCommand; + moveToLevelCommand.level = data->Value; + if (aDevice) + { + ret = Controller::InvokeCommandRequest(aDevice->GetExchangeManager(), aDevice->GetSecureSession().Value(), + aBinding.remote, moveToLevelCommand, onSuccess, onFailure); + } + else + { + Messaging::ExchangeManager & exchangeMgr = Server::GetInstance().GetExchangeManager(); + ret = Controller::InvokeGroupCommandRequest(&exchangeMgr, aBinding.fabricIndex, aBinding.groupId, moveToLevelCommand); + } + } + break; + default: + ASR_LOG("Invalid binding command data - CommandId is not supported"); + break; + } + if (CHIP_NO_ERROR != ret) + { + ASR_LOG("Invoke Group Command Request ERROR: %s", ErrorStr(ret)); + } +} + +void BindingHandler::LightSwitchChangedHandler(const EmberBindingTableEntry & aBinding, OperationalDeviceProxy * deviceProxy, + void * context) +{ + VerifyOrReturn(context != nullptr, ChipLogError(NotSpecified, "OnDeviceConnectedFn: context is null")); + BindingData * data = static_cast(context); + + if (aBinding.type == EMBER_MULTICAST_BINDING && data->IsGroup) + { + switch (data->ClusterId) + { + case Clusters::OnOff::Id: + OnOffProcessCommand(data->CommandId, aBinding, nullptr, context); + break; + case Clusters::LevelControl::Id: + LevelControlProcessCommand(data->CommandId, aBinding, nullptr, context); + break; + default: + ChipLogError(NotSpecified, "Invalid binding group command data"); + break; + } + } + else if (aBinding.type == EMBER_UNICAST_BINDING && !data->IsGroup) + { + switch (data->ClusterId) + { + case Clusters::OnOff::Id: + OnOffProcessCommand(data->CommandId, aBinding, deviceProxy, context); + break; + case Clusters::LevelControl::Id: + LevelControlProcessCommand(data->CommandId, aBinding, deviceProxy, context); + break; + default: + ChipLogError(NotSpecified, "Invalid binding unicast command data"); + break; + } + } +} + +void BindingHandler::LightSwitchContextReleaseHandler(void * context) +{ + VerifyOrReturn(context != nullptr, ChipLogError(NotSpecified, "LightSwitchContextReleaseHandler: context is null")); + + Platform::Delete(static_cast(context)); +} + +void BindingHandler::InitInternal(intptr_t arg) +{ + ASR_LOG("Initialize binding Handler"); + auto & server = chip::Server::GetInstance(); + chip::BindingManager::GetInstance().Init( + { &server.GetFabricTable(), server.GetCASESessionManager(), &server.GetPersistentStorage() }); + chip::BindingManager::GetInstance().RegisterBoundDeviceChangedHandler(LightSwitchChangedHandler); + chip::BindingManager::GetInstance().RegisterBoundDeviceContextReleaseHandler(LightSwitchContextReleaseHandler); + BindingHandler::GetInstance().PrintBindingTable(); +} + +bool BindingHandler::IsGroupBound() +{ + BindingTable & bindingTable = BindingTable::GetInstance(); + + for (auto & entry : bindingTable) + { + if (EMBER_MULTICAST_BINDING == entry.type) + { + return true; + } + } + return false; +} + +void BindingHandler::PrintBindingTable() +{ + BindingTable & bindingTable = BindingTable::GetInstance(); + + ASR_LOG("Binding Table size: [%d]:", bindingTable.Size()); + uint8_t i = 0; + for (auto & entry : bindingTable) + { + switch (entry.type) + { + case EMBER_UNICAST_BINDING: + ASR_LOG("[%d] UNICAST:", i++); + ASR_LOG("\t\t+ Fabric: %d\n \ + \t+ LocalEndpoint %d \n \ + \t+ ClusterId %d \n \ + \t+ RemoteEndpointId %d \n \ + \t+ NodeId %d", + (int) entry.fabricIndex, (int) entry.local, (int) entry.clusterId.Value(), (int) entry.remote, + (int) entry.nodeId); + break; + case EMBER_MULTICAST_BINDING: + ASR_LOG("[%d] GROUP:", i++); + ASR_LOG("\t\t+ Fabric: %d\n \ + \t+ LocalEndpoint %d \n \ + \t+ RemoteEndpointId %d \n \ + \t+ GroupId %d", + (int) entry.fabricIndex, (int) entry.local, (int) entry.remote, (int) entry.groupId); + break; + case EMBER_UNUSED_BINDING: + ASR_LOG("[%d] UNUSED", i++); + break; + // case EMBER_MANY_TO_ONE_BINDING: + // ASR_LOG("[%d] MANY TO ONE", i++); + // break; + default: + break; + } + } +} + +/******************************************************** + * Switch functions + *********************************************************/ + +void BindingHandler::SwitchWorkerHandler(intptr_t context) +{ + VerifyOrReturn(context != 0, ChipLogError(NotSpecified, "SwitchWorkerFunction - Invalid work data")); + + BindingData * data = reinterpret_cast(context); + BindingManager::GetInstance().NotifyBoundClusterChanged(data->EndpointId, data->ClusterId, static_cast(data)); +} diff --git a/examples/light-switch-app/asr/src/ButtonHandler.cpp b/examples/light-switch-app/asr/src/ButtonHandler.cpp new file mode 100644 index 00000000000000..c0d521bc9d8858 --- /dev/null +++ b/examples/light-switch-app/asr/src/ButtonHandler.cpp @@ -0,0 +1,122 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ButtonHandler.h" +#include "AppConfig.h" +#include "AppTask.h" +#include + +#ifdef CFG_PLF_RV32 +#define duet_gpio_init asr_gpio_init +#define duet_gpio_input_get asr_gpio_input_get +#define DUET_INPUT_PULL_UP ASR_INPUT_PULL_UP +#endif + +TaskHandle_t sGpioTaskHandle; +static void GpioTaskMain(void * pvParameter); + +void ButtonHandler::Init(void) +{ + GpioInit(); + + xTaskCreate(GpioTaskMain, GPIO_TASK_NAME, GPIO_TASK_STACK_SIZE, 0, 2, &sGpioTaskHandle); +} + +// port pin +duet_gpio_dev_t switch1_btn; +duet_gpio_dev_t switch2_btn; + +void ButtonHandler::GpioInit(void) +{ + // light switch1 button + switch1_btn.port = SWITCH1_BUTTON; + switch1_btn.config = DUET_INPUT_PULL_UP; + switch1_btn.priv = NULL; + duet_gpio_init(&switch1_btn); +#if DUAL_LIGHTSWITCH_ENDPOINT + // light switch2 button + switch2_btn.port = SWITCH2_BUTTON; +#endif +#if GENERIC_SWITCH_ENDPOINT + // generic switch2 button + switch2_btn.port = GENERIC_SWITCH_BUTTON; +#endif + switch2_btn.config = DUET_INPUT_PULL_UP; + switch2_btn.priv = NULL; + duet_gpio_init(&switch2_btn); +} + +static uint32_t btn1Value = 1; +static uint8_t btn1_trigger = 0; +static uint32_t btn2Value = 1; +static uint8_t btn2_trigger = 0; +void GpioTaskMain(void * pvParameter) +{ + ASR_LOG("GPIO Task started"); + uint32_t btnValue; + uint8_t buttonevent = 0; + while (true) + { + vTaskDelay(50 / portTICK_PERIOD_MS); + // switch button 1 + duet_gpio_input_get(&switch1_btn, &btnValue); + if (btnValue != btn1Value) + { + if (btn1_trigger) + { + btn1Value = btnValue; + buttonevent = (uint8_t) btnValue; + GetAppTask().ButtonEventHandler(SWITCH1_BUTTON, (buttonevent) ? BUTTON_RELEASED : BUTTON_PRESSED); + btn1_trigger = 0; + } + else + { + btn1_trigger = 1; + } + } + else + { + btn1_trigger = 0; + } + // switch button 2 + duet_gpio_input_get(&switch2_btn, &btnValue); + if (btnValue != btn2Value) + { + if (btn2_trigger) + { + btn2Value = btnValue; + buttonevent = (uint8_t) btnValue; +#if DUAL_LIGHTSWITCH_ENDPOINT + GetAppTask().ButtonEventHandler(SWITCH2_BUTTON, (buttonevent) ? BUTTON_RELEASED : BUTTON_PRESSED); +#endif +#if GENERIC_SWITCH_ENDPOINT + GetAppTask().ButtonEventHandler(GENERIC_SWITCH_BUTTON, (buttonevent) ? BUTTON_RELEASED : BUTTON_PRESSED); +#endif + btn2_trigger = 0; + } + else + { + btn2_trigger = 1; + } + } + else + { + btn2_trigger = 0; + } + } +} diff --git a/examples/light-switch-app/asr/src/DeviceCallbacks.cpp b/examples/light-switch-app/asr/src/DeviceCallbacks.cpp new file mode 100644 index 00000000000000..e967094e0fbccd --- /dev/null +++ b/examples/light-switch-app/asr/src/DeviceCallbacks.cpp @@ -0,0 +1,147 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.cpp + * + * Implements all the callbacks to the application from the CHIP Stack + * + **/ +#include "DeviceCallbacks.h" +#include "AppTask.h" +#include "CHIPDeviceManager.h" +#include "LEDWidget.h" +#include "init_OTARequestor.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT +#include "route_hook/asr_route_hook.h" +#endif + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::System; +using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceManager; +using namespace ::chip::Logging; +using namespace ::chip::app::Clusters; + +uint32_t identifyTimerCount; + +constexpr uint32_t kIdentifyTimerDelayMS = 250; +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +constexpr uint32_t kInitOTARequestorDelaySec = 3; + +void InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +{ + OTAInitializer::Instance().InitOTARequestor(); +} +#endif +void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + switch (event->Type) + { + case DeviceEventType::kInternetConnectivityChange: + OnInternetConnectivityChange(event); + GetAppTask().UpdateStatusLED(); + break; + case DeviceEventType::kCHIPoBLEAdvertisingChange: + GetAppTask().UpdateStatusLED(); + break; + case DeviceEventType::kInterfaceIpAddressChanged: + if ((event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned) || + (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned)) + { + // MDNS server restart on any ip assignment: if link local ipv6 is configured, that + // will not trigger a 'internet connectivity change' as there is no internet + // connectivity. MDNS still wants to refresh its listening interfaces to include the + // newly selected address. + chip::app::DnssdServer::Instance().StartServer(); + + if (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned) + { +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT + ChipLogProgress(NotSpecified, "Initializing route hook..."); + asr_route_hook_init(); +#endif + } + } + break; + } +} + +void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t type, + uint16_t size, uint8_t * value) +{ + ChipLogProgress(Zcl, "Cluster callback: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + + if (clusterId == OnOffSwitchConfiguration::Id) + { + ChipLogProgress(Zcl, "OnOff Switch Configuration attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", + ChipLogValueMEI(attributeId), type, *value, size); + // WIP Apply attribute change to Light + } + else if (clusterId == Identify::Id) + { + ChipLogProgress(Zcl, "Identify attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", + ChipLogValueMEI(attributeId), type, *value, size); + } +} + +void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + static bool isOTAInitialized = false; +#endif + if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv4 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); + } + else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv4 connectivity..."); + } + if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv6 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Init OTA requestor only when we have gotten IPv6 address + if (!isOTAInitialized) + { + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec), + InitOTARequestorHandler, nullptr); + isOTAInitialized = true; + } +#endif + } + else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv6 connectivity..."); + } +} diff --git a/examples/light-switch-app/asr/src/LEDManager.cpp b/examples/light-switch-app/asr/src/LEDManager.cpp new file mode 100644 index 00000000000000..518f5c05186abf --- /dev/null +++ b/examples/light-switch-app/asr/src/LEDManager.cpp @@ -0,0 +1,96 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "LEDManager.h" +#include "AppTask.h" +#include + +#ifdef CFG_PLF_RV32 +#define duet_gpio_init asr_gpio_init +#define duet_gpio_output_low asr_gpio_output_low +#define duet_gpio_output_high asr_gpio_output_high +#define DUET_OUTPUT_PUSH_PULL ASR_OUTPUT_PUSH_PULL +#endif + +void LEDManager::InitGpio(void) {} + +void LEDManager::Init(uint8_t gpioNum) +{ + mLastChangeTimeMS = 0; + mBlinkOnTimeMS = 0; + mBlinkOffTimeMS = 0; + mGPIONum = gpioNum; + + gpio.port = mGPIONum; + gpio.config = DUET_OUTPUT_PUSH_PULL; + duet_gpio_init(&gpio); +} + +void LEDManager::Invert(void) +{ + Set(!mState); +} + +void LEDManager::Set(bool state) +{ + mBlinkOnTimeMS = 0; + mBlinkOffTimeMS = 0; + DoSet(state); +} + +void LEDManager::Blink(uint32_t changeRateMS) +{ + Blink(changeRateMS, changeRateMS); +} + +void LEDManager::Blink(uint32_t onTimeMS, uint32_t offTimeMS) +{ + mBlinkOnTimeMS = onTimeMS; + mBlinkOffTimeMS = offTimeMS; + Animate(); +} + +void LEDManager::Animate() +{ + if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0) + { + uint64_t nowMS = chip::System::SystemClock().GetMonotonicMilliseconds64().count(); + uint64_t stateDurMS = ((mState) ? mBlinkOnTimeMS : mBlinkOffTimeMS); + uint64_t nextChangeTimeMS = mLastChangeTimeMS + stateDurMS; + + if (nextChangeTimeMS < nowMS) + { + DoSet(!mState); + mLastChangeTimeMS = nowMS; + } + } +} + +void LEDManager::DoSet(bool state) +{ + mState = state; + + if (state) + { + duet_gpio_output_low(&gpio); + } + else + { + duet_gpio_output_high(&gpio); + } +} diff --git a/examples/light-switch-app/asr/src/LightSwitch.cpp b/examples/light-switch-app/asr/src/LightSwitch.cpp new file mode 100644 index 00000000000000..4365131e3110e5 --- /dev/null +++ b/examples/light-switch-app/asr/src/LightSwitch.cpp @@ -0,0 +1,113 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "LightSwitch.h" +#include "AppEvent.h" +#include "BindingHandler.h" +#include +#include +#include +#include +#include + +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; + +void LightSwitch::Init(chip::EndpointId aLightDimmerSwitchEndpoint) +{ + BindingHandler::GetInstance().Init(); + mLightSwitchEndpoint = aLightDimmerSwitchEndpoint; +} + +void LightSwitch::InitiateActionSwitch(Action mAction) +{ + BindingHandler::BindingData * data = Platform::New(); + if (data) + { + data->EndpointId = mLightSwitchEndpoint; + data->ClusterId = Clusters::OnOff::Id; + switch (mAction) + { + case Action::Toggle: + data->CommandId = Clusters::OnOff::Commands::Toggle::Id; + break; + case Action::On: + data->CommandId = Clusters::OnOff::Commands::On::Id; + break; + case Action::Off: + data->CommandId = Clusters::OnOff::Commands::Off::Id; + break; + default: + Platform::Delete(data); + return; + } + data->IsGroup = BindingHandler::GetInstance().IsGroupBound(); + DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::SwitchWorkerHandler, reinterpret_cast(data)); + } +} + +void LightSwitch::SwitchChangeBrightness(uint16_t sBrightness) +{ + BindingHandler::BindingData * data = Platform::New(); + if (data) + { + data->EndpointId = mLightSwitchEndpoint; + data->CommandId = Clusters::LevelControl::Commands::MoveToLevel::Id; + data->ClusterId = Clusters::LevelControl::Id; + // set brightness of light. + if (sBrightness > kMaximumBrightness) + { + sBrightness = kMaximumBrightness; + } + data->Value = (uint8_t) sBrightness; + data->IsGroup = BindingHandler::GetInstance().IsGroupBound(); + DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::SwitchWorkerHandler, reinterpret_cast(data)); + } +} + +void LightSwitch::InitGeneric(chip::EndpointId aGenericSwitchEndpoint) +{ + BindingHandler::GetInstance().Init(); + mGenericSwitchEndpointId = aGenericSwitchEndpoint; +} + +void LightSwitch::GenericSwitchInitialPress() +{ + DeviceLayer::SystemLayer().ScheduleLambda([this] { + // Press moves Position from 0 (idle) to 1 (press) + uint8_t newPosition = 1; + + Clusters::Switch::Attributes::CurrentPosition::Set(mGenericSwitchEndpointId, newPosition); + // InitialPress event takes newPosition as event data + Clusters::SwitchServer::Instance().OnInitialPress(mGenericSwitchEndpointId, newPosition); + }); +} + +void LightSwitch::GenericSwitchReleasePress() +{ + DeviceLayer::SystemLayer().ScheduleLambda([this] { + // Release moves Position from 1 (press) to 0 (idle) + uint8_t previousPosition = 1; + uint8_t newPosition = 0; + + Clusters::Switch::Attributes::CurrentPosition::Set(mGenericSwitchEndpointId, newPosition); + // ShortRelease event takes previousPosition as event data + Clusters::SwitchServer::Instance().OnShortRelease(mGenericSwitchEndpointId, previousPosition); + }); +} diff --git a/examples/light-switch-app/asr/src/main.cpp b/examples/light-switch-app/asr/src/main.cpp new file mode 100644 index 00000000000000..f83f06573ff7d5 --- /dev/null +++ b/examples/light-switch-app/asr/src/main.cpp @@ -0,0 +1,77 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppConfig.h" +#include "init_asrPlatform.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; +// ================================================================================ +// App Error +//================================================================================= +void appError(int err) +{ + ASR_LOG("!!!!!!!!!!!! App Critical Error: %d !!!!!!!!!!!", err); + lega_rtos_declare_critical(); + lega_rtos_enter_critical(); + while (1) + ; +} + +void appError(CHIP_ERROR error) +{ + appError(static_cast(error.AsInteger())); +} +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + init_asrPlatform(); + + CHIP_ERROR ret = GetAppTask().StartAppTask(); + if (ret != CHIP_NO_ERROR) + { + ASR_LOG("GetAppTask().Init() failed"); + appError(ret); + } + /* Start the FreeRTOS scheduler */ + vTaskStartScheduler(); + + chip::Platform::MemoryShutdown(); + PlatformMgr().StopEventLoopTask(); + PlatformMgr().Shutdown(); + + // Should never get here. + ASR_LOG("vTaskStartScheduler() failed"); + appError(ret); +} diff --git a/examples/light-switch-app/asr/third_party/connectedhomeip b/examples/light-switch-app/asr/third_party/connectedhomeip new file mode 120000 index 00000000000000..11a54ed360106c --- /dev/null +++ b/examples/light-switch-app/asr/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../ \ No newline at end of file diff --git a/examples/lock-app/asr/.gn b/examples/lock-app/asr/.gn new file mode 100755 index 00000000000000..8d75f1eafcdb89 --- /dev/null +++ b/examples/lock-app/asr/.gn @@ -0,0 +1,29 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/lock-app/asr/BUILD.gn b/examples/lock-app/asr/BUILD.gn new file mode 100755 index 00000000000000..8e6b86822418d8 --- /dev/null +++ b/examples/lock-app/asr/BUILD.gn @@ -0,0 +1,131 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/asr.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("${asr_sdk_build_root}/asr_sdk.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/src/lib/lib.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/asr/asr_executable.gni") + +import("cfg.gni") + +assert(current_os == "freertos") + +asr_project_dir = "${chip_root}/examples/lock-app/asr" +examples_plat_dir = "${chip_root}/examples/platform/asr" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + +asr_sdk_sources("lock_app_sdk_sources") { + include_dirs = [ + "${chip_root}/src/platform/ASR", + "${asr_project_dir}/include", + "${examples_plat_dir}", + ] + + defines = [ + "ASR_LOG_ENABLED=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + ] + + if (chip_enable_factory_data) { + defines += [ + "CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER=1", + "CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER=1", + ] + } + + if (chip_lwip_ip6_hook) { + defines += [ + "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", + "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", + ] + } + + sources = [ "${asr_project_dir}/include/CHIPProjectConfig.h" ] + + public_configs = [ "${asr_sdk_build_root}:asr_sdk_config" ] +} + +asr_executable("lock_app") { + include_dirs = [] + defines = [] + output_name = "chip-asr-lock-example.out" + + public_deps = [ + ":lock_app_sdk_sources", + "${chip_root}/examples/common/QRCode", + "${chip_root}/examples/lock-app/lock-common", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs += [ + "include", + "${examples_plat_dir}", + "${asr_project_dir}/include", + "${chip_root}/src/lib", + ] + + sources = [ + "${examples_plat_dir}/CHIPDeviceManager.cpp", + "${examples_plat_dir}/LEDWidget.cpp", + "${examples_plat_dir}/init_Matter.cpp", + "${examples_plat_dir}/init_asrPlatform.cpp", + "${examples_plat_dir}/shell/matter_shell.cpp", + "src/AppTask.cpp", + "src/BoltLockManager.cpp", + "src/ButtonHandler.cpp", + "src/DeviceCallbacks.cpp", + "src/LEDManager.cpp", + "src/main.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${examples_plat_dir}/init_OTARequestor.cpp" ] + } + + defines = [ "ASR_NETWORK_LAYER_BLE=${chip_config_network_layer_ble}" ] + + if (chip_build_libshell) { + defines += [ "CONFIG_ENABLE_CHIP_SHELL=1" ] + sources += [ "${examples_plat_dir}/shell/launch_shell.cpp" ] + include_dirs += [ "${examples_plat_dir}/shell" ] + } + + output_dir = root_out_dir + + if (chip_print_memory_usage) { + ldflags = [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } +} + +group("asr") { + deps = [ ":lock_app" ] +} + +group("default") { + deps = [ ":asr" ] +} diff --git a/examples/lock-app/asr/README.md b/examples/lock-app/asr/README.md new file mode 100755 index 00000000000000..00c7bc0f8a37eb --- /dev/null +++ b/examples/lock-app/asr/README.md @@ -0,0 +1,56 @@ +# Matter ASR Lock Example + +The ASR Lock Example demonstrates how to remotely control a door lock device +with one basic bolt. It uses buttons to test changing the lock and device states +and LEDs to show the state of these changes. You can use this example as a +reference for creating your own application. + +--- + +- [Matter ASR Lock Example](#matter-asr-lock-example) + - [Supported Chips](#supported-chips) + - [Building and Commissioning](#building-and-commissioning) + - [Cluster Control](#cluster-control) + - [Lock press button and lock status led](#lock-press-button-and-lock-status-led) + +--- + +## Supported Chips + +The Matter demo application is supported on: + +- ASR582X +- ASR595X + +## Building and Commissioning + +Please refer +[Building and Commissioning](../../../docs/guides/asr_getting_started_guide.md#building-the-example-application) +guides to get started + +``` +./scripts/build/build_examples.py --target asr-$ASR_BOARD-lock build +``` + +## Cluster Control + +After successful commissioning, use `chip-tool` to control the board + +- OnOff Cluster + +``` +./chip-tool onoff read on-off 1 +./chip-tool onoff on 1 +./chip-tool onoff off 1 +./chip-tool onoff toggle 1 +``` + +## Lock press button and lock status led + +This demo uses button to test changing the lock and device states and LED to +show the state of these changes. + +| Name | Pin | +| :---------: | :---: | +| LOCK-STATE | PAD13 | +| LOCK-BUTTON | PAD6 | diff --git a/examples/lock-app/asr/args.gni b/examples/lock-app/asr/args.gni new file mode 100755 index 00000000000000..9c9e2aa953656d --- /dev/null +++ b/examples/lock-app/asr/args.gni @@ -0,0 +1,27 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("//cfg.gni") +import("${chip_root}/src/platform/ASR/args.gni") + +asr_target_project = + get_label_info(":lock_app_sdk_sources", "label_no_toolchain") + +declare_args() { + # Disable lock tracking, since our FreeRTOS configuration does not set + # INCLUDE_xSemaphoreGetMutexHolder + chip_stack_lock_tracking = "none" +} diff --git a/examples/lock-app/asr/build_overrides b/examples/lock-app/asr/build_overrides new file mode 120000 index 00000000000000..194ee0b812dc3d --- /dev/null +++ b/examples/lock-app/asr/build_overrides @@ -0,0 +1 @@ +../../build_overrides/ \ No newline at end of file diff --git a/examples/lock-app/asr/cfg.gni b/examples/lock-app/asr/cfg.gni new file mode 100755 index 00000000000000..15fe50e79efb6d --- /dev/null +++ b/examples/lock-app/asr/cfg.gni @@ -0,0 +1,23 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + chip_enable_factory_data = false + + chip_lwip_ip6_hook = false + + setupPinCode = 20202021 + + setupDiscriminator = 3840 +} diff --git a/examples/lock-app/asr/include/AppConfig.h b/examples/lock-app/asr/include/AppConfig.h new file mode 100644 index 00000000000000..60320f47c9f3c7 --- /dev/null +++ b/examples/lock-app/asr/include/AppConfig.h @@ -0,0 +1,83 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#ifdef CFG_PLF_RV32 +#include "asr_gpio.h" +#include "asr_pinmux.h" +#define duet_gpio_dev_t asr_gpio_dev_t +#else +#include "duet_gpio.h" +#include "duet_pinmux.h" +#endif + +// ---- Lock Example App Config ---- + +#define APP_TASK_NAME "APP" + +#define APP_TASK_STACK_SIZE (1024 * 4) +#define APP_TASK_PRIORITY 2 +#define APP_EVENT_QUEUE_SIZE 10 + +#define MATTER_DEVICE_NAME "ASR-LOCK" + +#define APP_LOCK_BUTTON_IDX 0 +#define APP_FUNCTION_BUTTON_IDX 1 + +#define APP_LOCK_BUTTON GPIO6_INDEX +#define APP_FUNCTION_BUTTON GPIO7_INDEX + +#define APP_BUTTON_DEBOUNCE_PERIOD_MS 50 + +#define APP_BUTTON_PRESSED 0 +#define APP_BUTTON_RELEASED 1 + +#define SYSTEM_STATE_LED GPIO12_INDEX +#define LOCK_STATE_LED GPIO13_INDEX + +#define FACTORY_RESET_TRIGGER_TIMEOUT 3000 +#define FACTORY_RESET_CANCEL_WINDOW_TIMEOUT 3000 + +// Time it takes in ms for the simulated actuator to move from one +// state to another. +#define ACTUATOR_MOVEMENT_PERIOS_MS 2000 + +// ---- Lock Example SWU Config ---- +#define SWU_INTERVAl_WINDOW_MIN_MS (23 * 60 * 60 * 1000) // 23 hours +#define SWU_INTERVAl_WINDOW_MAX_MS (24 * 60 * 60 * 1000) // 24 hours + +// ---- Thread Polling Config ---- +#define THREAD_ACTIVE_POLLING_INTERVAL_MS 100 +#define THREAD_INACTIVE_POLLING_INTERVAL_MS 1000 + +// ASR Logging +#ifdef __cplusplus +extern "C" { +#endif + +void appError(int err); +void ASR_LOG(const char * aFormat, ...); + +#ifdef __cplusplus +} + +#include +void appError(CHIP_ERROR error); +#endif diff --git a/examples/lock-app/asr/include/AppEvent.h b/examples/lock-app/asr/include/AppEvent.h new file mode 100755 index 00000000000000..7b954c05230f1d --- /dev/null +++ b/examples/lock-app/asr/include/AppEvent.h @@ -0,0 +1,57 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2018 Nest Labs, Inc. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +struct AppEvent +{ + enum AppEventTypes + { + kEventType_Button = 0, + kEventType_Timer, + kEventType_Lock, + kEventType_Install, + }; + + uint16_t Type; + + union + { + struct + { + uint8_t ButtonIdx; + uint8_t Action; + } ButtonEvent; + struct + { + void * Context; + } TimerEvent; + struct + { + uint8_t Action; + int32_t Actor; + } LockEvent; + }; + + EventHandler Handler; +}; diff --git a/examples/lock-app/asr/include/AppTask.h b/examples/lock-app/asr/include/AppTask.h new file mode 100755 index 00000000000000..854d70efdb9744 --- /dev/null +++ b/examples/lock-app/asr/include/AppTask.h @@ -0,0 +1,95 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "AppEvent.h" +#include "BoltLockManager.h" + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include +#include + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) + +class AppTask +{ + +public: + CHIP_ERROR StartAppTask(); + static void AppTaskMain(void * pvParameter); + + void PostLockActionRequest(int32_t actor, BoltLockManager::Action action); + void PostEvent(const AppEvent * event); + + void ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction); + void UpdateClusterState(void); + +private: + friend AppTask & GetAppTask(void); + + CHIP_ERROR Init(); + + static void ActionInitiated(BoltLockManager::Action action, int32_t actor); + static void ActionCompleted(BoltLockManager::Action action); + + void CancelTimer(void); + + void DispatchEvent(AppEvent * event); + + static void FunctionTimerEventHandler(AppEvent * event); + static void FunctionHandler(AppEvent * event); + static void LockActionEventHandler(AppEvent * event); + static void TimerEventHandler(TimerHandle_t timer); + + static void UpdateCluster(intptr_t context); + + void StartTimer(uint32_t aTimeoutMs); + + enum class Function + { + kNoneSelected = 0, + kSoftwareUpdate = 0, + kStartBleAdv = 1, + kFactoryReset = 2, + + kInvalid + }; + + Function mFunction = Function::kNoneSelected; + bool mFunctionTimerActive = false; + bool mSyncClusterToButtonAction = false; + + static AppTask sAppTask; +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/lock-app/asr/include/BoltLockManager.h b/examples/lock-app/asr/include/BoltLockManager.h new file mode 100755 index 00000000000000..4c0093b3efd592 --- /dev/null +++ b/examples/lock-app/asr/include/BoltLockManager.h @@ -0,0 +1,84 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include "AppEvent.h" + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support + +#include + +class BoltLockManager +{ +public: + enum class Action + { + kLock = 0, + kUnlock, + KInvalid + }; + + enum class State + { + kLockingInitiated = 0, + kLockingCompleted, + kUnlockingInitiated, + kUnlockingCompleted, + }; + + CHIP_ERROR Init(); + bool IsUnlocked(); + void EnableAutoRelock(bool aOn); + void SetAutoLockDuration(uint32_t aDurationInSecs); + bool IsActionInProgress(); + bool InitiateAction(int32_t aActor, Action aAction); + + typedef void (*Callback_fn_initiated)(Action, int32_t aActor); + typedef void (*Callback_fn_completed)(Action); + void SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB); + +private: + friend BoltLockManager & BoltLockMgr(void); + State mState = State::kUnlockingCompleted; + + Callback_fn_initiated mActionInitiated_CB; + Callback_fn_completed mActionCompleted_CB; + + bool mAutoRelock = false; + uint32_t mAutoLockDuration = 0; + bool mAutoLockTimerArmed = false; + + void CancelTimer(void); + void StartTimer(uint32_t aTimeoutMs); + + static void TimerEventHandler(TimerHandle_t xTimer); + static void AutoReLockTimerEventHandler(AppEvent * aEvent); + static void ActuatorMovementTimerEventHandler(AppEvent * aEvent); + + static BoltLockManager sLock; +}; + +inline BoltLockManager & BoltLockMgr(void) +{ + return BoltLockManager::sLock; +} diff --git a/examples/lock-app/asr/include/ButtonHandler.h b/examples/lock-app/asr/include/ButtonHandler.h new file mode 100755 index 00000000000000..978cad1937b8d9 --- /dev/null +++ b/examples/lock-app/asr/include/ButtonHandler.h @@ -0,0 +1,51 @@ +/* + * + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer suppo +#ifdef CFG_PLF_RV32 +#include "asr_gpio.h" +#define duet_gpio_dev_t asr_gpio_dev_t +#define DUET_INPUT_PULL_UP ASR_INPUT_PULL_UP +#define duet_gpio_init asr_gpio_init +#define duet_gpio_output_low asr_gpio_output_low +#define duet_gpio_output_high asr_gpio_output_high +#define duet_gpio_input_get asr_gpio_input_get +#define duet_gpio_enable_irq asr_gpio_enable_irq +#define DUET_IRQ_TRIGGER_FALLING_EDGE ASR_IRQ_TRIGGER_FALLING_EDGE +#else +#include "duet_gpio.h" +#endif + +#define GPIO_INTERRUPT_PRIORITY (5) + +class ButtonHandler +{ +public: + static void Init(void); + +private: + static void GpioInit(void); + static void lockbuttonIsr(void * handler_arg); + static void functionbuttonIsr(void * handler_arg); + static void TimerCallback(TimerHandle_t xTimer); +}; diff --git a/examples/lock-app/asr/include/CHIPProjectConfig.h b/examples/lock-app/asr/include/CHIPProjectConfig.h new file mode 100755 index 00000000000000..fbaf9ea3c7c9be --- /dev/null +++ b/examples/lock-app/asr/include/CHIPProjectConfig.h @@ -0,0 +1,112 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +/** + * CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY + * + * Enables the use of a hard-coded default Chip device id and credentials if no device id + * is found in Chip NV storage. + * + * This option is for testing only and should be disabled in production releases. + */ +#define CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY 34 + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// define Device type based on the application +#define CHIP_DEVICE_CONFIG_DEVICE_TYPE 10 // 0x00A Door lock + +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 1 +#endif + +/** + * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + * + * Enable support for Chip-over-BLE (CHIPoBLE). + */ +// #define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) diff --git a/examples/lock-app/asr/include/DeviceCallbacks.h b/examples/lock-app/asr/include/DeviceCallbacks.h new file mode 100755 index 00000000000000..11fb7177fe8466 --- /dev/null +++ b/examples/lock-app/asr/include/DeviceCallbacks.h @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.h + * + * Implementations for the DeviceManager callbacks for this application + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include +#include +#include + +class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks +{ +public: + void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg) override; + void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value) override; + +private: + void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); +}; diff --git a/examples/lock-app/asr/include/LEDManager.h b/examples/lock-app/asr/include/LEDManager.h new file mode 100644 index 00000000000000..b64d1e88e8c17c --- /dev/null +++ b/examples/lock-app/asr/include/LEDManager.h @@ -0,0 +1,47 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include "AppConfig.h" +#include + +#ifndef LED_Manager_H +#define LED_Manager_H + +class LEDManager +{ +public: + void InitGpio(void); + void Init(uint8_t ledNum); + void Set(bool state); + void Invert(void); + void Blink(uint32_t changeRateMS); + void Blink(uint32_t onTimeMS, uint32_t offTimeMS); + void Animate(); + +private: + uint64_t mLastChangeTimeMS; + uint32_t mBlinkOnTimeMS; + uint32_t mBlinkOffTimeMS; + uint8_t mGPIONum; + bool mState; + duet_gpio_dev_t gpio; + + void DoSet(bool state); +}; + +#endif // LED_Manager_H diff --git a/examples/lock-app/asr/src/AppTask.cpp b/examples/lock-app/asr/src/AppTask.cpp new file mode 100644 index 00000000000000..d46069955dc6ab --- /dev/null +++ b/examples/lock-app/asr/src/AppTask.cpp @@ -0,0 +1,497 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" +#include "AppConfig.h" +#include "AppEvent.h" +#include "ButtonHandler.h" +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include "LEDManager.h" +#include "qrcodegen.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "init_Matter.h" +#include +#include +#include +#include +#include + +namespace { + +TimerHandle_t sFunctionTimer; // FreeRTOS app sw timer. + +TaskHandle_t sAppTaskHandle; +QueueHandle_t sAppEventQueue; + +LEDManager sStatusLED; +LEDManager sLockLED; + +bool sIsWiFiStationEnabled = false; +bool sIsWiFiStationConnected = false; +bool sHaveBLEConnections = false; +} // namespace + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; + +AppTask AppTask::sAppTask; + +namespace { +constexpr EndpointId kNetworkCommissioningEndpointMain = 0; +constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; + +app::Clusters::NetworkCommissioning::Instance + sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, + &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); +} // namespace + +void NetWorkCommissioningInstInit() +{ + sWiFiNetworkCommissioningInstance.Init(); + + // We only have network commissioning on endpoint 0. + emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); +} + +static DeviceCallbacks EchoCallbacks; + +CHIP_ERROR AppTask::StartAppTask() +{ + sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); + if (sAppEventQueue == NULL) + { + ASR_LOG("Failed to allocate app event queue"); + appError(APP_ERROR_EVENT_QUEUE_FAILED); + } + + // Start App task. + xTaskCreate(AppTaskMain, APP_TASK_NAME, APP_TASK_STACK_SIZE, 0, 2, &sAppTaskHandle); + return (sAppTaskHandle == nullptr) ? APP_ERROR_CREATE_TASK_FAILED : CHIP_NO_ERROR; +} + +CHIP_ERROR AppTask::Init() +{ + ASR_LOG("App Task started"); + + CHIP_ERROR err = CHIP_NO_ERROR; + + if (MatterInitializer::Init_Matter_Stack(MATTER_DEVICE_NAME) != CHIP_NO_ERROR) + return CHIP_ERROR_INTERNAL; + + CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); + + if (deviceMgr.Init(&EchoCallbacks) != CHIP_NO_ERROR) + return CHIP_ERROR_INTERNAL; + + if (MatterInitializer::Init_Matter_Server() != CHIP_NO_ERROR) + return CHIP_ERROR_INTERNAL; + + // Initialise WSTK buttons PB0 and PB1 (including debounce). + ButtonHandler::Init(); + + // Create FreeRTOS sw timer for Function Selection. + sFunctionTimer = xTimerCreate("FnTmr", // Just a text name, not used by the RTOS kernel + 1, // == default timer period (mS) + false, // no timer reload (==one-shot) + (void *) this, // init timer id = app task obj context + TimerEventHandler // timer callback handler + ); + if (sFunctionTimer == NULL) + { + ASR_LOG("funct timer create failed"); + appError(APP_ERROR_CREATE_TIMER_FAILED); + } + + NetWorkCommissioningInstInit(); + + ASR_LOG("Current Software Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + err = BoltLockMgr().Init(); + if (err != CHIP_NO_ERROR) + { + ASR_LOG("BoltLockMgr().Init() failed"); + appError(err); + } + + BoltLockMgr().SetCallbacks(ActionInitiated, ActionCompleted); + + // Initialize LEDs + sStatusLED.Init(SYSTEM_STATE_LED); + sStatusLED.Set(0); + + sLockLED.Init(LOCK_STATE_LED); + sLockLED.Set(!BoltLockMgr().IsUnlocked()); + + ConfigurationMgr().LogDeviceConfig(); + + // Print setup info + PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); + + return err; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + AppEvent event; + + CHIP_ERROR err = sAppTask.Init(); + if (err != CHIP_NO_ERROR) + { + ASR_LOG("AppTask.Init() failed"); + appError(err); + } + + while (true) + { + BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10)); + if (eventReceived == pdTRUE) + { + sAppTask.DispatchEvent(&event); + } + + // Update the status LED if factory reset has not been initiated. + // + // If system has "full connectivity", keep the LED On constantly. + // + // If thread and service provisioned, but not attached to the thread network + // yet OR no connectivity to the service OR subscriptions are not fully + // established THEN blink the LED Off for a short period of time. + // + // If the system has ble connection(s) uptill the stage above, THEN blink + // the LEDs at an even rate of 100ms. + // + // Otherwise, blink the LED ON for a very short time. + if (sAppTask.mFunction != Function::kFactoryReset) + { + if (sIsWiFiStationEnabled && !sIsWiFiStationConnected) + { + sStatusLED.Blink(950, 50); + } + else if (sHaveBLEConnections) + { + sStatusLED.Blink(100, 100); + } + else + { + sStatusLED.Blink(50, 950); + } + } + sStatusLED.Animate(); + sLockLED.Animate(); + } +} + +void AppTask::LockActionEventHandler(AppEvent * event) +{ + bool initiated = false; + BoltLockManager::Action action = BoltLockManager::Action::KInvalid; + int32_t actor = 0; + CHIP_ERROR err = CHIP_NO_ERROR; + + if (event->Type == AppEvent::kEventType_Lock) + { + action = static_cast(event->LockEvent.Action); + actor = event->LockEvent.Actor; + } + else if (event->Type == AppEvent::kEventType_Button) + { + if (BoltLockMgr().IsUnlocked()) + { + action = BoltLockManager::Action::kLock; + } + else + { + action = BoltLockManager::Action::kUnlock; + } + actor = AppEvent::kEventType_Button; + } + else + { + err = APP_ERROR_UNHANDLED_EVENT; + } + + if (err == CHIP_NO_ERROR) + { + initiated = BoltLockMgr().InitiateAction(actor, action); + + if (!initiated) + { + ASR_LOG("Action is already in progress or active."); + } + } +} + +void AppTask::ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction) +{ + if (btnIdx != APP_LOCK_BUTTON_IDX && btnIdx != APP_FUNCTION_BUTTON_IDX) + { + return; + } + + AppEvent button_event = {}; + button_event.Type = AppEvent::kEventType_Button; + button_event.ButtonEvent.ButtonIdx = btnIdx; + button_event.ButtonEvent.Action = btnAction; + + if (btnIdx == APP_LOCK_BUTTON_IDX) + { + button_event.Handler = LockActionEventHandler; + sAppTask.PostEvent(&button_event); + } + else if (btnIdx == APP_FUNCTION_BUTTON_IDX) + { + button_event.Handler = FunctionHandler; + sAppTask.PostEvent(&button_event); + } +} + +void AppTask::TimerEventHandler(TimerHandle_t timer) +{ + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.TimerEvent.Context = (void *) timer; + event.Handler = FunctionTimerEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::FunctionTimerEventHandler(AppEvent * event) +{ + if (event->Type != AppEvent::kEventType_Timer) + { + return; + } + + // If we reached here, the button was held past FACTORY_RESET_TRIGGER_TIMEOUT, + // initiate factory reset + if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == Function::kStartBleAdv) + { + ASR_LOG("Factory Reset Triggered. Release button within %ums to cancel.", FACTORY_RESET_CANCEL_WINDOW_TIMEOUT); + + // Start timer for FACTORY_RESET_CANCEL_WINDOW_TIMEOUT to allow user to + // cancel, if required. + sAppTask.StartTimer(FACTORY_RESET_CANCEL_WINDOW_TIMEOUT); + + sAppTask.mFunction = Function::kFactoryReset; + + // Turn off all LEDs before starting blink to make sure blink is + // co-ordinated. + sStatusLED.Set(false); + sLockLED.Set(false); + + sStatusLED.Blink(500); + sLockLED.Blink(500); + } + else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == Function::kFactoryReset) + { + // Actually trigger Factory Reset + sAppTask.mFunction = Function::kNoneSelected; + chip::Server::GetInstance().ScheduleFactoryReset(); + } +} + +void AppTask::FunctionHandler(AppEvent * event) +{ + if (event->ButtonEvent.ButtonIdx != APP_FUNCTION_BUTTON_IDX) + { + return; + } + // To trigger software update: press the APP_FUNCTION_BUTTON button briefly (< + // FACTORY_RESET_TRIGGER_TIMEOUT) To initiate factory reset: press the + // APP_FUNCTION_BUTTON for FACTORY_RESET_TRIGGER_TIMEOUT + + // FACTORY_RESET_CANCEL_WINDOW_TIMEOUT All LEDs start blinking after + // FACTORY_RESET_TRIGGER_TIMEOUT to signal factory reset has been initiated. + // To cancel factory reset: release the APP_FUNCTION_BUTTON once all LEDs + // start blinking within the FACTORY_RESET_CANCEL_WINDOW_TIMEOUT + if (event->ButtonEvent.Action == APP_BUTTON_RELEASED) + { + if (!sAppTask.mFunctionTimerActive && sAppTask.mFunction == Function::kNoneSelected) + { + sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT); + sAppTask.mFunction = Function::kStartBleAdv; + } + } + else + { + // If the button was released before factory reset got initiated, start Thread Network + if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == Function::kStartBleAdv) + { + sAppTask.CancelTimer(); + sAppTask.mFunction = Function::kNoneSelected; + } + else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == Function::kFactoryReset) + { + // Set lock status LED back to show state of lock. + sLockLED.Set(!BoltLockMgr().IsUnlocked()); + + sAppTask.CancelTimer(); + + // Change the function to none selected since factory reset has been + // canceled. + sAppTask.mFunction = Function::kNoneSelected; + + ASR_LOG("Factory Reset has been Canceled"); + } + } +} + +void AppTask::CancelTimer() +{ + if (xTimerStop(sFunctionTimer, 0) == pdFAIL) + { + ASR_LOG("app timer stop() failed"); + appError(APP_ERROR_STOP_TIMER_FAILED); + } + + mFunctionTimerActive = false; +} + +void AppTask::StartTimer(uint32_t aTimeoutInMs) +{ + if (xTimerIsTimerActive(sFunctionTimer)) + { + ASR_LOG("app timer already started!"); + CancelTimer(); + } + + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(sFunctionTimer, aTimeoutInMs / portTICK_PERIOD_MS, 100) != pdPASS) + { + ASR_LOG("app timer start() failed"); + appError(APP_ERROR_START_TIMER_FAILED); + } + + mFunctionTimerActive = true; +} + +void AppTask::ActionInitiated(BoltLockManager::Action action, int32_t actor) +{ + // If the action has been initiated by the lock, update the bolt lock trait + // and start flashing the LEDs rapidly to indicate action initiation. + if (action == BoltLockManager::Action::kLock) + { + ASR_LOG("Lock Action has been initiated"); + } + else if (action == BoltLockManager::Action::kUnlock) + { + ASR_LOG("Unlock Action has been initiated"); + } + + if (actor == AppEvent::kEventType_Button) + { + sAppTask.mSyncClusterToButtonAction = true; + } + + sLockLED.Blink(50, 50); +} + +void AppTask::ActionCompleted(BoltLockManager::Action action) +{ + // if the action has been completed by the lock, update the bolt lock trait. + // Turn on the lock LED if in a LOCKED state OR + // Turn off the lock LED if in an UNLOCKED state. + if (action == BoltLockManager::Action::kLock) + { + ASR_LOG("Lock Action has been completed"); + + sLockLED.Set(true); + } + else if (action == BoltLockManager::Action::kUnlock) + { + ASR_LOG("Unlock Action has been completed"); + + sLockLED.Set(false); + } + + if (sAppTask.mSyncClusterToButtonAction) + { + sAppTask.UpdateClusterState(); + sAppTask.mSyncClusterToButtonAction = false; + } +} + +void AppTask::PostLockActionRequest(int32_t actor, BoltLockManager::Action action) +{ + AppEvent event; + event.Type = AppEvent::kEventType_Lock; + event.LockEvent.Actor = actor; + event.LockEvent.Action = static_cast(action); + event.Handler = LockActionEventHandler; + PostEvent(&event); +} + +void AppTask::PostEvent(const AppEvent * event) +{ + if (sAppEventQueue != NULL) + { + if (!xQueueSend(sAppEventQueue, event, 1)) + { + ASR_LOG("Failed to post event to app task event queue"); + } + } +} + +void AppTask::DispatchEvent(AppEvent * event) +{ + if (event->Handler) + { + event->Handler(event); + } + else + { + ASR_LOG("Event received with no handler. Dropping event."); + } +} + +void AppTask::UpdateCluster(intptr_t context) +{ + uint8_t unlocked = BoltLockMgr().IsUnlocked(); + + DlLockState newState = unlocked ? DlLockState::kUnlocked : DlLockState::kLocked; + + OperationSourceEnum source = OperationSourceEnum::kUnspecified; + // write the new lock value + EmberAfStatus status = + DoorLockServer::Instance().SetLockState(1, newState, source) ? EMBER_ZCL_STATUS_SUCCESS : EMBER_ZCL_STATUS_FAILURE; + if (status != EMBER_ZCL_STATUS_SUCCESS) + { + ASR_LOG("ERR: updating lock state %x", status); + } +} + +void AppTask::UpdateClusterState(void) +{ + chip::DeviceLayer::PlatformMgr().ScheduleWork(UpdateCluster, reinterpret_cast(nullptr)); +} diff --git a/examples/lock-app/asr/src/BoltLockManager.cpp b/examples/lock-app/asr/src/BoltLockManager.cpp new file mode 100755 index 00000000000000..c52f55dec78377 --- /dev/null +++ b/examples/lock-app/asr/src/BoltLockManager.cpp @@ -0,0 +1,225 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "BoltLockManager.h" + +#include "AppConfig.h" +#include "AppTask.h" +#include + +BoltLockManager BoltLockManager::sLock; + +TimerHandle_t sLockTimer; + +CHIP_ERROR BoltLockManager::Init() +{ + // Create FreeRTOS sw timer for lock timer. + sLockTimer = xTimerCreate("lockTmr", // Just a text name, not used by the RTOS kernel + 1, // == default timer period (mS) + false, // no timer reload (==one-shot) + (void *) this, // init timer id = lock obj context + TimerEventHandler // timer callback handler + ); + + if (sLockTimer == NULL) + { + ASR_LOG("sLockTimer timer create failed"); + appError(APP_ERROR_CREATE_TIMER_FAILED); + } + + mState = State::kUnlockingCompleted; + mAutoLockTimerArmed = false; + mAutoRelock = false; + mAutoLockDuration = 0; + + return CHIP_NO_ERROR; +} + +void BoltLockManager::SetCallbacks(Callback_fn_initiated aActionInitiated_CB, Callback_fn_completed aActionCompleted_CB) +{ + mActionInitiated_CB = aActionInitiated_CB; + mActionCompleted_CB = aActionCompleted_CB; +} + +bool BoltLockManager::IsActionInProgress() +{ + return (mState == State::kLockingInitiated || mState == State::kUnlockingInitiated); +} + +bool BoltLockManager::IsUnlocked() +{ + return (mState == State::kUnlockingCompleted); +} + +void BoltLockManager::EnableAutoRelock(bool aOn) +{ + mAutoRelock = aOn; +} + +void BoltLockManager::SetAutoLockDuration(uint32_t aDurationInSecs) +{ + mAutoLockDuration = aDurationInSecs; +} + +bool BoltLockManager::InitiateAction(int32_t aActor, Action aAction) +{ + bool action_initiated = false; + State new_state; + + // Initiate Lock/Unlock Action only when the previous one is complete. + if (mState == State::kLockingCompleted && aAction == Action::kUnlock) + { + action_initiated = true; + + new_state = State::kUnlockingInitiated; + } + else if (mState == State::kUnlockingCompleted && aAction == Action::kLock) + { + action_initiated = true; + + new_state = State::kLockingInitiated; + } + + if (action_initiated) + { + if (mAutoLockTimerArmed && new_state == State::kLockingInitiated) + { + // If auto lock timer has been armed and someone initiates locking, + // cancel the timer and continue as normal. + mAutoLockTimerArmed = false; + + CancelTimer(); + } + + StartTimer(ACTUATOR_MOVEMENT_PERIOS_MS); + + // Since the timer started successfully, update the state and trigger callback + mState = new_state; + + if (mActionInitiated_CB) + { + mActionInitiated_CB(aAction, aActor); + } + } + + return action_initiated; +} + +void BoltLockManager::StartTimer(uint32_t aTimeoutMs) +{ + if (xTimerIsTimerActive(sLockTimer)) + { + ASR_LOG("app timer already started!"); + CancelTimer(); + } + + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(sLockTimer, (aTimeoutMs / portTICK_PERIOD_MS), 100) != pdPASS) + { + ASR_LOG("sLockTimer timer start() failed"); + appError(APP_ERROR_START_TIMER_FAILED); + } +} + +void BoltLockManager::CancelTimer(void) +{ + if (xTimerStop(sLockTimer, 0) == pdFAIL) + { + ASR_LOG("Lock timer timer stop() failed"); + appError(APP_ERROR_STOP_TIMER_FAILED); + } +} + +void BoltLockManager::TimerEventHandler(TimerHandle_t xTimer) +{ + // Get lock obj context from timer id. + BoltLockManager * lock = static_cast(pvTimerGetTimerID(xTimer)); + + // The timer event handler will be called in the context of the timer task + // once sLockTimer expires. Post an event to apptask queue with the actual handler + // so that the event can be handled in the context of the apptask. + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.TimerEvent.Context = lock; + if (lock->mAutoLockTimerArmed) + { + event.Handler = AutoReLockTimerEventHandler; + } + else + { + event.Handler = ActuatorMovementTimerEventHandler; + } + GetAppTask().PostEvent(&event); +} + +void BoltLockManager::AutoReLockTimerEventHandler(AppEvent * aEvent) +{ + BoltLockManager * lock = static_cast(aEvent->TimerEvent.Context); + int32_t actor = 0; + + // Make sure auto lock timer is still armed. + if (!lock->mAutoLockTimerArmed) + { + return; + } + + lock->mAutoLockTimerArmed = false; + + ASR_LOG("Auto Re-Lock has been triggered!"); + + lock->InitiateAction(actor, Action::kLock); +} + +void BoltLockManager::ActuatorMovementTimerEventHandler(AppEvent * aEvent) +{ + Action actionCompleted = Action::KInvalid; + + BoltLockManager * lock = static_cast(aEvent->TimerEvent.Context); + + if (lock->mState == State::kLockingInitiated) + { + lock->mState = State::kLockingCompleted; + actionCompleted = Action::kLock; + } + else if (lock->mState == State::kUnlockingInitiated) + { + lock->mState = State::kUnlockingCompleted; + actionCompleted = Action::kUnlock; + } + + if (actionCompleted != Action::KInvalid) + { + if (lock->mActionCompleted_CB) + { + lock->mActionCompleted_CB(actionCompleted); + } + + if (lock->mAutoRelock && actionCompleted == Action::kUnlock) + { + // Start the timer for auto relock + lock->StartTimer(lock->mAutoLockDuration * 1000); + + lock->mAutoLockTimerArmed = true; + + ASR_LOG("Auto Re-lock enabled. Will be triggered in %lu seconds", lock->mAutoLockDuration); + } + } +} diff --git a/examples/lock-app/asr/src/ButtonHandler.cpp b/examples/lock-app/asr/src/ButtonHandler.cpp new file mode 100644 index 00000000000000..b74f1befd4652d --- /dev/null +++ b/examples/lock-app/asr/src/ButtonHandler.cpp @@ -0,0 +1,100 @@ +/* + * + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ButtonHandler.h" +#include "AppConfig.h" +#include "AppTask.h" + +namespace { +constexpr int kButtonCount = 2; + +TimerHandle_t buttonTimers[kButtonCount]; // FreeRTOS timers used for debouncing +// buttons. Array to hold handles to +// the created timers. + +} // namespace + +void ButtonHandler::Init(void) +{ + GpioInit(); + // Create FreeRTOS sw timers for debouncing buttons. + for (uint8_t i = 0; i < kButtonCount; i++) + { + buttonTimers[i] = xTimerCreate("BtnTmr", // Just a text name, not used by the RTOS kernel + APP_BUTTON_DEBOUNCE_PERIOD_MS, // timer period + false, // no timer reload (==one-shot) + (void *) (int) i, // init timer id = button index + TimerCallback // timer callback handler (all buttons use + // the same timer cn function) + ); + } +} + +// port pin +duet_gpio_dev_t lock_btn; +duet_gpio_dev_t func_btn; + +void ButtonHandler::GpioInit(void) +{ + // lock button + lock_btn.port = APP_LOCK_BUTTON; + lock_btn.config = DUET_INPUT_PULL_UP; + lock_btn.priv = NULL; + duet_gpio_init(&lock_btn); + duet_gpio_enable_irq(&lock_btn, DUET_IRQ_TRIGGER_FALLING_EDGE, lockbuttonIsr, NULL); + + // function button + func_btn.port = APP_FUNCTION_BUTTON; + func_btn.config = DUET_INPUT_PULL_UP; + func_btn.priv = NULL; + duet_gpio_init(&func_btn); + duet_gpio_enable_irq(&func_btn, DUET_IRQ_TRIGGER_FALLING_EDGE, functionbuttonIsr, NULL); +} + +void ButtonHandler::lockbuttonIsr(void * handler_arg) +{ + portBASE_TYPE taskWoken = pdFALSE; + xTimerStartFromISR(buttonTimers[APP_LOCK_BUTTON_IDX], &taskWoken); +} + +void ButtonHandler::functionbuttonIsr(void * handler_arg) +{ + portBASE_TYPE taskWoken = pdFALSE; + xTimerStartFromISR(buttonTimers[APP_FUNCTION_BUTTON_IDX], &taskWoken); +} + +void ButtonHandler::TimerCallback(TimerHandle_t xTimer) +{ + // Get the button index of the expired timer and call button event helper. + uint32_t timerId; + uint8_t buttonevent = 0; + uint32_t btnValue; + + timerId = (uint32_t) pvTimerGetTimerID(xTimer); + if (timerId == APP_LOCK_BUTTON_IDX) + { + duet_gpio_input_get(&lock_btn, &btnValue); + buttonevent = (uint8_t) btnValue; + } + else + { + duet_gpio_input_get(&func_btn, &btnValue); + buttonevent = (uint8_t) btnValue; + } + GetAppTask().ButtonEventHandler(timerId, (buttonevent) ? APP_BUTTON_PRESSED : APP_BUTTON_RELEASED); +} diff --git a/examples/lock-app/asr/src/DeviceCallbacks.cpp b/examples/lock-app/asr/src/DeviceCallbacks.cpp new file mode 100644 index 00000000000000..8782f038f29677 --- /dev/null +++ b/examples/lock-app/asr/src/DeviceCallbacks.cpp @@ -0,0 +1,162 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.cpp + * + * Implements all the callbacks to the application from the CHIP Stack + * + **/ +#include "DeviceCallbacks.h" + +#include "AppTask.h" +#include "BoltLockManager.h" +#include "CHIPDeviceManager.h" +#include "LEDWidget.h" +#include "init_OTARequestor.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT +#include "route_hook/asr_route_hook.h" +#endif + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::System; +using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceManager; +using namespace ::chip::Logging; +using namespace ::chip::app::Clusters; + +uint32_t identifyTimerCount; +constexpr uint32_t kIdentifyTimerDelayMS = 250; +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +constexpr uint32_t kInitOTARequestorDelaySec = 3; + +void InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +{ + OTAInitializer::Instance().InitOTARequestor(); +} +#endif +void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + switch (event->Type) + { + case DeviceEventType::kInternetConnectivityChange: + OnInternetConnectivityChange(event); + break; + + case DeviceEventType::kInterfaceIpAddressChanged: + if ((event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned) || + (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned)) + { + // MDNS server restart on any ip assignment: if link local ipv6 is configured, that + // will not trigger a 'internet connectivity change' as there is no internet + // connectivity. MDNS still wants to refresh its listening interfaces to include the + // newly selected address. + chip::app::DnssdServer::Instance().StartServer(); + + if (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned) + { +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT + ChipLogProgress(NotSpecified, "Initializing route hook..."); + asr_route_hook_init(); +#endif + } + } + break; + } +} + +void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t type, + uint16_t size, uint8_t * value) +{ + ChipLogProgress(DeviceLayer, + "MatterPostAttributeChangeCallback - Cluster ID: " ChipLogFormatMEI + ", EndPoint ID: '0x%02x', Attribute ID: " ChipLogFormatMEI, + ChipLogValueMEI(clusterId), endpointId, ChipLogValueMEI(attributeId)); + + if (clusterId == OnOff::Id && attributeId == OnOff::Attributes::OnOff::Id) + { + BoltLockMgr().InitiateAction(AppEvent::kEventType_Lock, + *value ? BoltLockManager::Action::kLock : BoltLockManager::Action::kUnlock); + } +} + +void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + static bool isOTAInitialized = false; +#endif + if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv4 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); + } + else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv4 connectivity..."); + } + if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv6 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Init OTA requestor only when we have gotten IPv6 address + if (!isOTAInitialized) + { + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec), + InitOTARequestorHandler, nullptr); + isOTAInitialized = true; + } +#endif + } + else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv6 connectivity..."); + } +} + +/** @brief OnOff Cluster Init + * + * This function is called when a specific cluster is initialized. It gives the + * application an opportunity to take care of cluster initialization procedures. + * It is called exactly once for each endpoint where cluster is present. + * + * @param endpoint Ver.: always + * + * TODO Issue #3841 + * emberAfOnOffClusterInitCallback happens before the stack initialize the cluster + * attributes to the default value. + * The logic here expects something similar to the deprecated Plugins callback + * emberAfPluginOnOffClusterServerPostInitCallback. + * + */ +void emberAfOnOffClusterInitCallback(EndpointId endpoint) +{ + GetAppTask().UpdateClusterState(); +} diff --git a/examples/lock-app/asr/src/LEDManager.cpp b/examples/lock-app/asr/src/LEDManager.cpp new file mode 100644 index 00000000000000..c5e140f98487b6 --- /dev/null +++ b/examples/lock-app/asr/src/LEDManager.cpp @@ -0,0 +1,96 @@ +/* + * + * Copyright (c) 2018 Nest Labs, Inc. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "LEDManager.h" +#include "AppTask.h" +#include + +#ifdef CFG_PLF_RV32 +#define duet_gpio_init asr_gpio_init +#define duet_gpio_output_low asr_gpio_output_low +#define duet_gpio_output_high asr_gpio_output_high +#define DUET_OUTPUT_PUSH_PULL ASR_OUTPUT_PUSH_PULL +#endif + +void LEDManager::InitGpio(void) {} + +void LEDManager::Init(uint8_t gpioNum) +{ + mLastChangeTimeMS = 0; + mBlinkOnTimeMS = 0; + mBlinkOffTimeMS = 0; + mGPIONum = gpioNum; + + gpio.port = mGPIONum; + gpio.config = DUET_OUTPUT_PUSH_PULL; + duet_gpio_init(&gpio); +} + +void LEDManager::Invert(void) +{ + Set(!mState); +} + +void LEDManager::Set(bool state) +{ + mBlinkOnTimeMS = 0; + mBlinkOffTimeMS = 0; + DoSet(state); +} + +void LEDManager::Blink(uint32_t changeRateMS) +{ + Blink(changeRateMS, changeRateMS); +} + +void LEDManager::Blink(uint32_t onTimeMS, uint32_t offTimeMS) +{ + mBlinkOnTimeMS = onTimeMS; + mBlinkOffTimeMS = offTimeMS; + Animate(); +} + +void LEDManager::Animate() +{ + if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0) + { + uint64_t nowMS = chip::System::SystemClock().GetMonotonicMilliseconds64().count(); + uint64_t stateDurMS = ((mState) ? mBlinkOnTimeMS : mBlinkOffTimeMS); + uint64_t nextChangeTimeMS = mLastChangeTimeMS + stateDurMS; + + if (nextChangeTimeMS < nowMS) + { + DoSet(!mState); + mLastChangeTimeMS = nowMS; + } + } +} + +void LEDManager::DoSet(bool state) +{ + mState = state; + + if (state) + { + duet_gpio_output_low(&gpio); + } + else + { + duet_gpio_output_high(&gpio); + } +} diff --git a/examples/lock-app/asr/src/main.cpp b/examples/lock-app/asr/src/main.cpp new file mode 100755 index 00000000000000..8dc468f24cb738 --- /dev/null +++ b/examples/lock-app/asr/src/main.cpp @@ -0,0 +1,84 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include + +#include "AppConfig.h" +#include "init_asrPlatform.h" +#include + +#include "ASRUtils.h" + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; +// ================================================================================ +// App Error +//================================================================================= +void appError(int err) +{ + ASR_LOG("!!!!!!!!!!!! App Critical Error: %d !!!!!!!!!!!", err); + lega_rtos_declare_critical(); + lega_rtos_enter_critical(); + while (1) + ; +} + +void appError(CHIP_ERROR error) +{ + appError(static_cast(error.AsInteger())); +} +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + init_asrPlatform(); + + CHIP_ERROR ret = GetAppTask().StartAppTask(); + if (ret != CHIP_NO_ERROR) + { + ASR_LOG("GetAppTask().Init() failed"); + appError(ret); + } + /* Start the FreeRTOS scheduler */ + vTaskStartScheduler(); + + chip::Platform::MemoryShutdown(); + PlatformMgr().StopEventLoopTask(); + PlatformMgr().Shutdown(); + + // Should never get here. + ASR_LOG("vTaskStartScheduler() failed"); + appError(ret); +} diff --git a/examples/lock-app/asr/third_party/connectedhomeip b/examples/lock-app/asr/third_party/connectedhomeip new file mode 120000 index 00000000000000..11a54ed360106c --- /dev/null +++ b/examples/lock-app/asr/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../ \ No newline at end of file diff --git a/examples/ota-requestor-app/asr/.gn b/examples/ota-requestor-app/asr/.gn new file mode 100755 index 00000000000000..8d75f1eafcdb89 --- /dev/null +++ b/examples/ota-requestor-app/asr/.gn @@ -0,0 +1,29 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/ota-requestor-app/asr/BUILD.gn b/examples/ota-requestor-app/asr/BUILD.gn new file mode 100755 index 00000000000000..93b0b4a0673bec --- /dev/null +++ b/examples/ota-requestor-app/asr/BUILD.gn @@ -0,0 +1,129 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/asr.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("${asr_sdk_build_root}/asr_sdk.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/src/lib/lib.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/asr/asr_executable.gni") + +import("cfg.gni") + +assert(current_os == "freertos") + +asr_project_dir = "${chip_root}/examples/ota-requestor-app/asr" +examples_plat_dir = "${chip_root}/examples/platform/asr" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + +asr_sdk_sources("ota_requestor_app_sdk_sources") { + include_dirs = [ + "${chip_root}/src/platform/ASR", + "${asr_project_dir}/include", + "${examples_plat_dir}", + ] + + defines = [ + "ASR_LOG_ENABLED=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + ] + + if (chip_enable_factory_data) { + defines += [ + "CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER=1", + "CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER=1", + ] + } + + if (chip_lwip_ip6_hook) { + defines += [ + "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", + "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", + ] + } + + sources = [ "${asr_project_dir}/include/CHIPProjectConfig.h" ] + + public_configs = [ "${asr_sdk_build_root}:asr_sdk_config" ] +} + +asr_executable("ota_requestor_app") { + include_dirs = [] + defines = [] + output_name = "chip-asr-ota-requestor-example.out" + + sources = [ + "${examples_plat_dir}/CHIPDeviceManager.cpp", + "${examples_plat_dir}/LEDWidget.cpp", + "${examples_plat_dir}/init_Matter.cpp", + "${examples_plat_dir}/init_asrPlatform.cpp", + "${examples_plat_dir}/shell/matter_shell.cpp", + "src/AppTask.cpp", + "src/DeviceCallbacks.cpp", + "src/main.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${examples_plat_dir}/init_OTARequestor.cpp" ] + } + + deps = [ + ":ota_requestor_app_sdk_sources", + "${chip_root}/examples/common/QRCode", + "${chip_root}/examples/ota-requestor-app/ota-requestor-common", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs += [ + "include", + "${examples_plat_dir}", + "${asr_project_dir}/include", + "${chip_root}/src/lib", + "${chip_root}/examples/ota-requestor-app/ota-requestor-common/include", + ] + + defines = [ "ASR_NETWORK_LAYER_BLE=${chip_config_network_layer_ble}" ] + + if (chip_build_libshell) { + defines += [ "CONFIG_ENABLE_CHIP_SHELL=1" ] + sources += [ "${examples_plat_dir}/shell/launch_shell.cpp" ] + include_dirs += [ "${examples_plat_dir}/shell" ] + } + + if (chip_print_memory_usage) { + ldflags += [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } + + output_dir = root_out_dir +} + +group("asr") { + deps = [ ":ota_requestor_app" ] +} + +group("default") { + deps = [ ":asr" ] +} diff --git a/examples/ota-requestor-app/asr/README.md b/examples/ota-requestor-app/asr/README.md new file mode 100755 index 00000000000000..d0dcc9f7146554 --- /dev/null +++ b/examples/ota-requestor-app/asr/README.md @@ -0,0 +1,61 @@ +# Matter ASR OTA Requestor Example + +This example demonstrates the Matter OTA Requestor application on ASR platform. + +--- + +- [Matter ASR OTA Requestor Example](#matter-asr-ota-requestor-example) + - [Supported Chips](#supported-chips) + - [Building and Commissioning](#building-and-commissioning) + - [Testing the example](#testing-the-example) + +--- + +## Supported Chips + +The Matter demo application is supported on: + +- ASR582X +- ASR595X + +## Building and Commissioning + +Please refer +[Building and Commissioning](../../../docs/guides/asr_getting_started_guide.md#building-the-example-application) +guides to get started + +``` +./scripts/build/build_examples.py --target asr-$ASR_BOARD-ota-requestor build +``` + +## Testing the example + +- Make OTA image: Taking lighting-app as an example, light project must + compiled before this operation: + + ``` + third_party/asr/asr582x/asr_sdk/tools/otaImage/image_gen_header out/asr-asr582x-lighting/chip-asr-lighting-example.bin flash_remapping + ``` + + After that, `chip-asr-lighting-example.ota.bin` will generated in the + directory `./out/asr-asr582x-lighting/`. + +- Run the Linux OTA Provider with OTA image. + ``` + ./chip-ota-provider-app -f chip-asr-lighting-example.ota.bin + ``` +- OTA Provider commissioning in another Linux terminal. + ``` + ./chip-tool pairing onnetwork 1 20202021 + ``` +- After OTA Provider commissioning is successful, use `chip-tool` to write ACL + for OAT Provider. + ``` + ./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null },{"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": null, "targets": null }]' 0 + ``` +- Commission ota requestor device with node-id `OTA REQUESTOR APP NODE ID` +- After OTA Requestor commissioning is successful, use `chip-tool` to inform + OTA Provider to send OTA image to OTA Requestor. + ``` + ./chip-tool otasoftwareupdaterequestor announce-ota-provider 1 0 0 0 0 + ``` diff --git a/examples/ota-requestor-app/asr/args.gni b/examples/ota-requestor-app/asr/args.gni new file mode 100755 index 00000000000000..1f1b199cc87b61 --- /dev/null +++ b/examples/ota-requestor-app/asr/args.gni @@ -0,0 +1,27 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("//cfg.gni") +import("${chip_root}/src/platform/ASR/args.gni") + +asr_target_project = + get_label_info(":ota_requestor_app_sdk_sources", "label_no_toolchain") + +declare_args() { + # Disable lock tracking, since our FreeRTOS configuration does not set + # INCLUDE_xSemaphoreGetMutexHolder + chip_stack_lock_tracking = "none" +} diff --git a/examples/ota-requestor-app/asr/build_overrides b/examples/ota-requestor-app/asr/build_overrides new file mode 120000 index 00000000000000..194ee0b812dc3d --- /dev/null +++ b/examples/ota-requestor-app/asr/build_overrides @@ -0,0 +1 @@ +../../build_overrides/ \ No newline at end of file diff --git a/examples/ota-requestor-app/asr/cfg.gni b/examples/ota-requestor-app/asr/cfg.gni new file mode 100755 index 00000000000000..f2d7bfbc1b80fb --- /dev/null +++ b/examples/ota-requestor-app/asr/cfg.gni @@ -0,0 +1,25 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + chip_enable_factory_data = false + + chip_lwip_ip6_hook = false + + setupPinCode = 20202021 + + setupDiscriminator = 3840 +} + +chip_enable_ota_requestor = true diff --git a/examples/ota-requestor-app/asr/include/AppConfig.h b/examples/ota-requestor-app/asr/include/AppConfig.h new file mode 100644 index 00000000000000..826ebfd44f3793 --- /dev/null +++ b/examples/ota-requestor-app/asr/include/AppConfig.h @@ -0,0 +1,43 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// ---- Lighting Example App Config ---- + +#define MATTER_DEVICE_NAME "ASR-OTA-REQ" +#define APP_TASK_NAME "APP" +#define APP_TASK_STACK_SIZE (1024 * 4) + +#define LIGHT_LED PWM_OUTPUT_CH3 + +// ASR Logging +#ifdef __cplusplus +extern "C" { +#endif + +void appError(int err); +void ASR_LOG(const char * aFormat, ...); + +#ifdef __cplusplus +} + +#include +void appError(CHIP_ERROR error); +#endif diff --git a/examples/ota-requestor-app/asr/include/AppTask.h b/examples/ota-requestor-app/asr/include/AppTask.h new file mode 100644 index 00000000000000..fd7f4d9f058f1d --- /dev/null +++ b/examples/ota-requestor-app/asr/include/AppTask.h @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include +#include +#include + +class AppTask +{ + +public: + CHIP_ERROR StartAppTask(); + static void AppTaskMain(void * pvParameter); + +private: + friend AppTask & GetAppTask(void); + + static AppTask sAppTask; +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/ota-requestor-app/asr/include/CHIPProjectConfig.h b/examples/ota-requestor-app/asr/include/CHIPProjectConfig.h new file mode 100755 index 00000000000000..9f21f281471076 --- /dev/null +++ b/examples/ota-requestor-app/asr/include/CHIPProjectConfig.h @@ -0,0 +1,109 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +/** + * CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY + * + * Enables the use of a hard-coded default Chip device id and credentials if no device id + * is found in Chip NV storage. + * + * This option is for testing only and should be disabled in production releases. + */ +#define CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY 34 + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 1 +#endif + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS + * + * Enable recording UTC timestamps. + */ +#define CHIP_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS 1 + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) diff --git a/examples/ota-requestor-app/asr/include/DeviceCallbacks.h b/examples/ota-requestor-app/asr/include/DeviceCallbacks.h new file mode 100644 index 00000000000000..2b5cfe386f8f05 --- /dev/null +++ b/examples/ota-requestor-app/asr/include/DeviceCallbacks.h @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.h + * + * Implementations for the DeviceManager callbacks for this application + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include +#include +#include + +class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks +{ +public: + virtual void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value) override; + +private: + void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); +}; diff --git a/examples/ota-requestor-app/asr/src/AppTask.cpp b/examples/ota-requestor-app/asr/src/AppTask.cpp new file mode 100644 index 00000000000000..3eb7cd14b69aec --- /dev/null +++ b/examples/ota-requestor-app/asr/src/AppTask.cpp @@ -0,0 +1,103 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" +#include "AppConfig.h" +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include "LEDWidget.h" +#include "init_Matter.h" +#include "qrcodegen.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +TaskHandle_t sAppTaskHandle; +} // namespace + +LEDWidget lightLED; + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; + +AppTask AppTask::sAppTask; + +namespace { +constexpr EndpointId kNetworkCommissioningEndpointMain = 0; +constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; + +app::Clusters::NetworkCommissioning::Instance + sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, + &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); +} // namespace + +void NetWorkCommissioningInstInit() +{ + sWiFiNetworkCommissioningInstance.Init(); + + // We only have network commissioning on endpoint 0. + emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); +} + +static DeviceCallbacks EchoCallbacks; + +CHIP_ERROR AppTask::StartAppTask() +{ + // Start App task. + xTaskCreate(AppTaskMain, APP_TASK_NAME, APP_TASK_STACK_SIZE, 0, 2, &sAppTaskHandle); + return (sAppTaskHandle == nullptr) ? CHIP_APPLICATION_ERROR(0x02) : CHIP_NO_ERROR; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + ASR_LOG("App Task started"); + + if (MatterInitializer::Init_Matter_Stack(MATTER_DEVICE_NAME) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); + + if (deviceMgr.Init(&EchoCallbacks) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + if (MatterInitializer::Init_Matter_Server() != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + NetWorkCommissioningInstInit(); + + ASR_LOG("Current Firmware Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + ConfigurationMgr().LogDeviceConfig(); + + // Print setup info + PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); + + lightLED.Init(LIGHT_LED); + /* Delete task */ + vTaskDelete(NULL); +} diff --git a/examples/ota-requestor-app/asr/src/DeviceCallbacks.cpp b/examples/ota-requestor-app/asr/src/DeviceCallbacks.cpp new file mode 100644 index 00000000000000..a1fa28e413f647 --- /dev/null +++ b/examples/ota-requestor-app/asr/src/DeviceCallbacks.cpp @@ -0,0 +1,148 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.cpp + * + * Implements all the callbacks to the application from the CHIP Stack + * + **/ +#include "DeviceCallbacks.h" +#include "AppConfig.h" +#include "CHIPDeviceManager.h" +#include "init_OTARequestor.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT +#include "route_hook/asr_route_hook.h" +#endif + +using namespace ::chip; +using namespace ::chip::app::Clusters; +using namespace ::chip::Inet; +using namespace ::chip::System; +using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceManager; +using namespace ::chip::Logging; + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +constexpr uint32_t kInitOTARequestorDelaySec = 3; + +void InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +{ + OTAInitializer::Instance().InitOTARequestor(); +} +#endif +void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + switch (event->Type) + { + case DeviceEventType::kInternetConnectivityChange: + OnInternetConnectivityChange(event); + break; + + case DeviceEventType::kInterfaceIpAddressChanged: + if ((event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned) || + (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned)) + { + // MDNS server restart on any ip assignment: if link local ipv6 is configured, that + // will not trigger a 'internet connectivity change' as there is no internet + // connectivity. MDNS still wants to refresh its listening interfaces to include the + // newly selected address. + chip::app::DnssdServer::Instance().StartServer(); + + if (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned) + { +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT + ChipLogProgress(NotSpecified, "Initializing route hook..."); + asr_route_hook_init(); +#endif + } + } + break; + } +} + +void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + static bool isOTAInitialized = false; +#endif + if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established) + { + ASR_LOG("IPv4 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Init OTA requestor only when we have gotten IPv6 address. + // Now, init it when we have gotten IPv4 address just for verification. + // It depends on your application! + if (!isOTAInitialized) + { + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec), + InitOTARequestorHandler, nullptr); + isOTAInitialized = true; + } +#endif + } + else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost) + { + ASR_LOG("Lost IPv4 connectivity..."); + } + if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established) + { + ASR_LOG("IPv6 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Init OTA requestor only when we have gotten IPv6 address + if (!isOTAInitialized) + { + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec), + InitOTARequestorHandler, nullptr); + isOTAInitialized = true; + } +#endif + } + else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost) + { + ASR_LOG("Lost IPv6 connectivity..."); + } +} + +void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t type, + uint16_t size, uint8_t * value) +{ + switch (clusterId) + { + case Identify::Id: + ChipLogProgress(Zcl, "Identify attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u", + ChipLogValueMEI(attributeId), type, *value, size); + break; + default: + ChipLogProgress(Zcl, "Unknown cluster ID: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + break; + } +} diff --git a/examples/ota-requestor-app/asr/src/main.cpp b/examples/ota-requestor-app/asr/src/main.cpp new file mode 100644 index 00000000000000..1dc5a4e0e69a00 --- /dev/null +++ b/examples/ota-requestor-app/asr/src/main.cpp @@ -0,0 +1,78 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppConfig.h" +#include "init_asrPlatform.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; +// ================================================================================ +// App Error +//================================================================================= +void appError(int err) +{ + ASR_LOG("!!!!!!!!!!!! App Critical Error: %d !!!!!!!!!!!", err); + lega_rtos_declare_critical(); + lega_rtos_enter_critical(); + while (1) + ; +} + +void appError(CHIP_ERROR error) +{ + appError(static_cast(error.AsInteger())); +} + +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + init_asrPlatform(); + + CHIP_ERROR ret = GetAppTask().StartAppTask(); + if (ret != CHIP_NO_ERROR) + { + ASR_LOG("GetAppTask().Init() failed"); + appError(ret); + } + /* Start the FreeRTOS scheduler */ + vTaskStartScheduler(); + + chip::Platform::MemoryShutdown(); + PlatformMgr().StopEventLoopTask(); + PlatformMgr().Shutdown(); + + // Should never get here. + ASR_LOG("vTaskStartScheduler() failed"); + appError(ret); +} diff --git a/examples/ota-requestor-app/asr/third_party/connectedhomeip b/examples/ota-requestor-app/asr/third_party/connectedhomeip new file mode 120000 index 00000000000000..11a54ed360106c --- /dev/null +++ b/examples/ota-requestor-app/asr/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../ \ No newline at end of file diff --git a/examples/temperature-measurement-app/asr/.gn b/examples/temperature-measurement-app/asr/.gn new file mode 100755 index 00000000000000..8d75f1eafcdb89 --- /dev/null +++ b/examples/temperature-measurement-app/asr/.gn @@ -0,0 +1,29 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/temperature-measurement-app/asr/BUILD.gn b/examples/temperature-measurement-app/asr/BUILD.gn new file mode 100755 index 00000000000000..6a8e4f76990449 --- /dev/null +++ b/examples/temperature-measurement-app/asr/BUILD.gn @@ -0,0 +1,129 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/asr.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("${asr_sdk_build_root}/asr_sdk.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/src/lib/lib.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/asr/asr_executable.gni") + +import("//cfg.gni") + +assert(current_os == "freertos") + +asr_project_dir = "${chip_root}/examples/temperature-measurement-app/asr" +examples_plat_dir = "${chip_root}/examples/platform/asr" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + +asr_sdk_sources("temperature_measurement_app_sdk_sources") { + include_dirs = [ + "${chip_root}/src/platform/ASR", + "${asr_project_dir}/include", + "${examples_plat_dir}", + ] + + defines = [ + "ASR_LOG_ENABLED=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + "ASR_ENABLE_LED1_DISPLAY=0", + ] + + if (chip_enable_factory_data) { + defines += [ + "CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER=1", + "CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER=1", + ] + } + + if (chip_lwip_ip6_hook) { + defines += [ + "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", + "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", + ] + } + + sources = [ "${asr_project_dir}/include/CHIPProjectConfig.h" ] + + public_configs = [ "${asr_sdk_build_root}:asr_sdk_config" ] +} + +asr_executable("temperature_measurement_app") { + include_dirs = [] + defines = [] + output_name = "chip-asr-temperature-measurment-example.out" + + public_deps = [ + ":temperature_measurement_app_sdk_sources", + "${chip_root}/examples/common/QRCode", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/examples/temperature-measurement-app/temperature-measurement-common", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs += [ + "include", + "${examples_plat_dir}", + "${asr_project_dir}/include", + "${chip_root}/src/lib", + ] + + sources = [ + "${examples_plat_dir}/CHIPDeviceManager.cpp", + "${examples_plat_dir}/LEDWidget.cpp", + "${examples_plat_dir}/init_Matter.cpp", + "${examples_plat_dir}/init_asrPlatform.cpp", + "${examples_plat_dir}/shell/matter_shell.cpp", + "src/AppTask.cpp", + "src/DeviceCallbacks.cpp", + "src/main.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${examples_plat_dir}/init_OTARequestor.cpp" ] + } + + defines = [ "ASR_NETWORK_LAYER_BLE=${chip_config_network_layer_ble}" ] + + if (chip_build_libshell) { + defines += [ "CONFIG_ENABLE_CHIP_SHELL=1" ] + sources += [ "${examples_plat_dir}/shell/launch_shell.cpp" ] + include_dirs += [ "${examples_plat_dir}/shell" ] + } + + output_dir = root_out_dir + + if (chip_print_memory_usage) { + ldflags = [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } +} + +group("asr") { + deps = [ ":temperature_measurement_app" ] +} + +group("default") { + deps = [ ":asr" ] +} diff --git a/examples/temperature-measurement-app/asr/README.md b/examples/temperature-measurement-app/asr/README.md new file mode 100755 index 00000000000000..4151259686e80a --- /dev/null +++ b/examples/temperature-measurement-app/asr/README.md @@ -0,0 +1,40 @@ +# Matter ASR Temperature Measurement Example + +The ASR Temperature Measurement Example demonstrates getting simulated data from +temperature sensor. + +--- + +- [Matter ASR Temperature Measurement Example](#matter-asr-temperature-measurement-example) + - [Supported Chips](#supported-chips) + - [Building and Commissioning](#building-and-commissioning) + - [Cluster Control](#cluster-control) + +--- + +## Supported Chips + +The Matter demo application is supported on: + +- ASR582X +- ASR595X + +## Building and Commissioning + +Please refer +[Building and Commissioning](../../../docs/guides/asr_getting_started_guide.md#building-the-example-application) +guides to get started + +``` +./scripts/build/build_examples.py --target asr-$ASR_BOARD-temperature-measurement build +``` + +## Cluster Control + +After successful commissioning, use `chip-tool` to control the board + +For example,read temperature sensor measured value: + +``` +./chip-tool temperaturemeasurement read measured-value 1 +``` diff --git a/examples/temperature-measurement-app/asr/args.gni b/examples/temperature-measurement-app/asr/args.gni new file mode 100755 index 00000000000000..2156d7904ec9f6 --- /dev/null +++ b/examples/temperature-measurement-app/asr/args.gni @@ -0,0 +1,27 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("//cfg.gni") +import("${chip_root}/src/platform/ASR/args.gni") + +asr_target_project = get_label_info(":temperature_measurement_app_sdk_sources", + "label_no_toolchain") + +declare_args() { + # Disable lock tracking, since our FreeRTOS configuration does not set + # INCLUDE_xSemaphoreGetMutexHolder + chip_stack_lock_tracking = "none" +} diff --git a/examples/temperature-measurement-app/asr/build_overrides b/examples/temperature-measurement-app/asr/build_overrides new file mode 120000 index 00000000000000..e578e73312ebd1 --- /dev/null +++ b/examples/temperature-measurement-app/asr/build_overrides @@ -0,0 +1 @@ +../../build_overrides \ No newline at end of file diff --git a/examples/temperature-measurement-app/asr/cfg.gni b/examples/temperature-measurement-app/asr/cfg.gni new file mode 100755 index 00000000000000..15fe50e79efb6d --- /dev/null +++ b/examples/temperature-measurement-app/asr/cfg.gni @@ -0,0 +1,23 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + chip_enable_factory_data = false + + chip_lwip_ip6_hook = false + + setupPinCode = 20202021 + + setupDiscriminator = 3840 +} diff --git a/examples/temperature-measurement-app/asr/include/AppConfig.h b/examples/temperature-measurement-app/asr/include/AppConfig.h new file mode 100644 index 00000000000000..4955ee049d07ad --- /dev/null +++ b/examples/temperature-measurement-app/asr/include/AppConfig.h @@ -0,0 +1,79 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#ifdef CFG_PLF_RV32 +#include "asr_gpio.h" +#include "asr_pinmux.h" +#define duet_gpio_dev_t asr_gpio_dev_t +#else +#include "duet_gpio.h" +#include "duet_pinmux.h" +#endif +// ---- Lock Example App Config ---- + +#define APP_TASK_NAME "APP" + +#define APP_TASK_STACK_SIZE (1024 * 4) + +#define MATTER_DEVICE_NAME "ASR-Temperature" + +#define APP_LOCK_BUTTON_IDX 0 +#define APP_FUNCTION_BUTTON_IDX 1 + +#define APP_LOCK_BUTTON GPIO10_INDEX +#define APP_FUNCTION_BUTTON GPIO11_INDEX + +#define APP_BUTTON_DEBOUNCE_PERIOD_MS 50 + +#define APP_BUTTON_PRESSED 0 +#define APP_BUTTON_RELEASED 1 + +#define SYSTEM_STATE_LED GPIO12_INDEX +#define LOCK_STATE_LED GPIO13_INDEX + +// Time it takes in ms for the simulated actuator to move from one +// state to another. +#define ACTUATOR_MOVEMENT_PERIOS_MS 2000 + +// ---- Lock Example SWU Config ---- +#define SWU_INTERVAl_WINDOW_MIN_MS (23 * 60 * 60 * 1000) // 23 hours +#define SWU_INTERVAl_WINDOW_MAX_MS (24 * 60 * 60 * 1000) // 24 hours + +// ---- Thread Polling Config ---- +#define THREAD_ACTIVE_POLLING_INTERVAL_MS 100 +#define THREAD_INACTIVE_POLLING_INTERVAL_MS 1000 + +// ASR Logging +#ifdef __cplusplus +extern "C" { +#endif + +void appError(int err); +void ASR_LOG(const char * aFormat, ...); + +#ifdef __cplusplus +} + +#define CONFIG_RENDEZVOUS_MODE 6 + +#include +void appError(CHIP_ERROR error); +#endif diff --git a/examples/temperature-measurement-app/asr/include/AppEvent.h b/examples/temperature-measurement-app/asr/include/AppEvent.h new file mode 100755 index 00000000000000..7b954c05230f1d --- /dev/null +++ b/examples/temperature-measurement-app/asr/include/AppEvent.h @@ -0,0 +1,57 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2018 Nest Labs, Inc. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +struct AppEvent +{ + enum AppEventTypes + { + kEventType_Button = 0, + kEventType_Timer, + kEventType_Lock, + kEventType_Install, + }; + + uint16_t Type; + + union + { + struct + { + uint8_t ButtonIdx; + uint8_t Action; + } ButtonEvent; + struct + { + void * Context; + } TimerEvent; + struct + { + uint8_t Action; + int32_t Actor; + } LockEvent; + }; + + EventHandler Handler; +}; diff --git a/examples/temperature-measurement-app/asr/include/AppTask.h b/examples/temperature-measurement-app/asr/include/AppTask.h new file mode 100755 index 00000000000000..97d1bfe538fb64 --- /dev/null +++ b/examples/temperature-measurement-app/asr/include/AppTask.h @@ -0,0 +1,65 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "AppEvent.h" +#include "FreeRTOS.h" +#include "timers.h" // provides FreeRTOS timer support +#include +#include + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) + +class AppTask +{ + +public: + CHIP_ERROR StartAppTask(); + static void AppTaskMain(void * pvParameter); + static void LightActionEventHandler(AppEvent * aEvent); + void ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction); + void PostEvent(const AppEvent * event); + /** + * Use internally for registration of the ChipDeviceEvents + */ + static void CommonDeviceEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + +private: + friend AppTask & GetAppTask(void); + + CHIP_ERROR Init(); + + static AppTask sAppTask; + void DispatchEvent(AppEvent * event); + static void OnOffUpdateClusterState(void); +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/temperature-measurement-app/asr/include/CHIPProjectConfig.h b/examples/temperature-measurement-app/asr/include/CHIPProjectConfig.h new file mode 100755 index 00000000000000..00af1a3364eb3e --- /dev/null +++ b/examples/temperature-measurement-app/asr/include/CHIPProjectConfig.h @@ -0,0 +1,109 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +/** + * CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY + * + * Enables the use of a hard-coded default Chip device id and credentials if no device id + * is found in Chip NV storage. + * + * This option is for testing only and should be disabled in production releases. + */ +#define CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY 37 + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 1 +#endif + +/** + * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + * + * Enable support for Chip-over-BLE (CHIPoBLE). + */ +// #define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) diff --git a/examples/temperature-measurement-app/asr/include/DeviceCallbacks.h b/examples/temperature-measurement-app/asr/include/DeviceCallbacks.h new file mode 100644 index 00000000000000..dccb1bef2c0f7d --- /dev/null +++ b/examples/temperature-measurement-app/asr/include/DeviceCallbacks.h @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.h + * + * Implementations for the DeviceManager callbacks for this application + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include +#include +#include + +class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks +{ +public: + virtual void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value); + +private: + void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); +}; diff --git a/examples/temperature-measurement-app/asr/src/AppTask.cpp b/examples/temperature-measurement-app/asr/src/AppTask.cpp new file mode 100644 index 00000000000000..bdb37a20e6c7fd --- /dev/null +++ b/examples/temperature-measurement-app/asr/src/AppTask.cpp @@ -0,0 +1,104 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" +#include "AppConfig.h" +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include "LEDWidget.h" +#include "qrcodegen.h" +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "init_Matter.h" + +namespace { +TaskHandle_t sAppTaskHandle; +} // namespace + +LEDWidget lightLED; + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; + +AppTask AppTask::sAppTask; + +namespace { +constexpr EndpointId kNetworkCommissioningEndpointMain = 0; +constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; + +app::Clusters::NetworkCommissioning::Instance + sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, + &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); +} // namespace + +void NetWorkCommissioningInstInit() +{ + sWiFiNetworkCommissioningInstance.Init(); + + // We only have network commissioning on endpoint 0. + emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); +} + +static DeviceCallbacks EchoCallbacks; + +CHIP_ERROR AppTask::StartAppTask() +{ + // Start App task. + xTaskCreate(AppTaskMain, APP_TASK_NAME, APP_TASK_STACK_SIZE, 0, 2, &sAppTaskHandle); + return (sAppTaskHandle == nullptr) ? CHIP_APPLICATION_ERROR(0x02) : CHIP_NO_ERROR; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + ASR_LOG("App Task started"); + + if (MatterInitializer::Init_Matter_Stack(MATTER_DEVICE_NAME) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); + + if (deviceMgr.Init(&EchoCallbacks) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + if (MatterInitializer::Init_Matter_Server() != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + NetWorkCommissioningInstInit(); + + ASR_LOG("Current Firmware Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + ConfigurationMgr().LogDeviceConfig(); + + // Print setup info + PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); + + /* Delete task */ + vTaskDelete(NULL); +} diff --git a/examples/temperature-measurement-app/asr/src/DeviceCallbacks.cpp b/examples/temperature-measurement-app/asr/src/DeviceCallbacks.cpp new file mode 100644 index 00000000000000..0ecafc10a5eb6c --- /dev/null +++ b/examples/temperature-measurement-app/asr/src/DeviceCallbacks.cpp @@ -0,0 +1,143 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.cpp + * + * Implements all the callbacks to the application from the CHIP Stack + * + **/ +#include "DeviceCallbacks.h" +#include "AppConfig.h" + +#include +#include + +#include "init_OTARequestor.h" +#include +#include +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT +#include "route_hook/asr_route_hook.h" +#endif + +constexpr uint32_t kReportDelaySec = 3; + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::System; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +constexpr uint32_t kInitOTARequestorDelaySec = 3; + +void InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +{ + OTAInitializer::Instance().InitOTARequestor(); +} +#endif +void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + switch (event->Type) + { + case DeviceEventType::kInternetConnectivityChange: + OnInternetConnectivityChange(event); + break; + + case DeviceEventType::kInterfaceIpAddressChanged: + if ((event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned) || + (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned)) + { + // MDNS server restart on any ip assignment: if link local ipv6 is configured, that + // will not trigger a 'internet connectivity change' as there is no internet + // connectivity. MDNS still wants to refresh its listening interfaces to include the + // newly selected address. + chip::app::DnssdServer::Instance().StartServer(); + + if (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned) + { +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT + ChipLogProgress(NotSpecified, "Initializing route hook..."); + asr_route_hook_init(); +#endif + } + } + break; + } +} + +void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t type, + uint16_t size, uint8_t * value) +{ + ChipLogProgress(DeviceLayer, + "PostAttributeChangeCallback - Cluster ID: " ChipLogFormatMEI + ", EndPoint ID: '0x%02x', Attribute ID: " ChipLogFormatMEI, + ChipLogValueMEI(clusterId), endpointId, ChipLogValueMEI(attributeId)); +} + +void TempMeas(System::Layer * systemLayer, void * appState) +{ + + int16_t temperature = 2550; + int16_t humidity = 5000; + + ASR_LOG("Sensor T:%d H:%d", temperature, humidity); + + chip::app::Clusters::TemperatureMeasurement::Attributes::MeasuredValue::Set( + /* endpoint ID */ 1, /* temperature in 0.01*C */ int16_t(temperature)); + + // chip::app::Clusters::RelativeHumidityMeasurement::Attributes::MeasuredValue::Set( + // /* endpoint ID */ 1, /* humidity in 0.01*C */ int16_t(humidity)); + + systemLayer->StartTimer(Clock::Seconds32(kReportDelaySec), TempMeas, nullptr); +} + +void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + static bool isOTAInitialized = false; +#endif + if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv4 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kReportDelaySec), TempMeas, nullptr); + } + else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv4 connectivity..."); + } + if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv6 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Init OTA requestor only when we have gotten IPv6 address + if (!isOTAInitialized) + { + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec), + InitOTARequestorHandler, nullptr); + isOTAInitialized = true; + } +#endif + } + else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv6 connectivity..."); + } +} diff --git a/examples/temperature-measurement-app/asr/src/main.cpp b/examples/temperature-measurement-app/asr/src/main.cpp new file mode 100755 index 00000000000000..8dc468f24cb738 --- /dev/null +++ b/examples/temperature-measurement-app/asr/src/main.cpp @@ -0,0 +1,84 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include + +#include "AppConfig.h" +#include "init_asrPlatform.h" +#include + +#include "ASRUtils.h" + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; +// ================================================================================ +// App Error +//================================================================================= +void appError(int err) +{ + ASR_LOG("!!!!!!!!!!!! App Critical Error: %d !!!!!!!!!!!", err); + lega_rtos_declare_critical(); + lega_rtos_enter_critical(); + while (1) + ; +} + +void appError(CHIP_ERROR error) +{ + appError(static_cast(error.AsInteger())); +} +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + init_asrPlatform(); + + CHIP_ERROR ret = GetAppTask().StartAppTask(); + if (ret != CHIP_NO_ERROR) + { + ASR_LOG("GetAppTask().Init() failed"); + appError(ret); + } + /* Start the FreeRTOS scheduler */ + vTaskStartScheduler(); + + chip::Platform::MemoryShutdown(); + PlatformMgr().StopEventLoopTask(); + PlatformMgr().Shutdown(); + + // Should never get here. + ASR_LOG("vTaskStartScheduler() failed"); + appError(ret); +} diff --git a/examples/temperature-measurement-app/asr/third_party/connectedhomeip b/examples/temperature-measurement-app/asr/third_party/connectedhomeip new file mode 120000 index 00000000000000..11a54ed360106c --- /dev/null +++ b/examples/temperature-measurement-app/asr/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../ \ No newline at end of file diff --git a/examples/thermostat/asr/.gn b/examples/thermostat/asr/.gn new file mode 100755 index 00000000000000..8d75f1eafcdb89 --- /dev/null +++ b/examples/thermostat/asr/.gn @@ -0,0 +1,29 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/thermostat/asr/BUILD.gn b/examples/thermostat/asr/BUILD.gn new file mode 100755 index 00000000000000..cc972b5b162163 --- /dev/null +++ b/examples/thermostat/asr/BUILD.gn @@ -0,0 +1,132 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/asr.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("${asr_sdk_build_root}/asr_sdk.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/src/lib/lib.gni") +import("${chip_root}/src/platform/device.gni") +import("${chip_root}/third_party/asr/asr_executable.gni") + +import("//cfg.gni") + +assert(current_os == "freertos") + +asr_project_dir = "${chip_root}/examples/thermostat/asr" +examples_plat_dir = "${chip_root}/examples/platform/asr" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = false +} + +asr_sdk_sources("thermostat_sdk_sources") { + include_dirs = [ + "${chip_root}/src/platform/ASR", + "${asr_project_dir}/include", + "${examples_plat_dir}", + ] + + defines = [ + "ASR_LOG_ENABLED=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + "ASR_ENABLE_LED1_DISPLAY=0", + "ASR_ENABLE_LED2_DISPLAY=0", + ] + + if (chip_enable_factory_data) { + defines += [ + "CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER=1", + "CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER=1", + ] + } + + if (chip_lwip_ip6_hook) { + defines += [ + "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", + "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", + ] + } + + sources = [ "${asr_project_dir}/include/CHIPProjectConfig.h" ] + + public_configs = [ "${asr_sdk_build_root}:asr_sdk_config" ] +} + +asr_executable("thermostat") { + include_dirs = [] + defines = [] + output_name = "chip-asr-thermostat-example.out" + + public_deps = [ + ":thermostat_sdk_sources", + "${chip_root}/examples/common/QRCode", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/examples/thermostat/thermostat-common", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs += [ + "include", + "${examples_plat_dir}", + "${asr_project_dir}/include", + "${chip_root}/src/lib", + ] + + sources = [ + "${examples_plat_dir}/CHIPDeviceManager.cpp", + "${examples_plat_dir}/LEDWidget.cpp", + "${examples_plat_dir}/init_Matter.cpp", + "${examples_plat_dir}/init_asrPlatform.cpp", + "${examples_plat_dir}/shell/matter_shell.cpp", + "src/AppTask.cpp", + "src/DeviceCallbacks.cpp", + "src/SensorManager.cpp", + "src/TemperatureManager.cpp", + "src/main.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "${examples_plat_dir}/init_OTARequestor.cpp" ] + } + + defines = [ "ASR_NETWORK_LAYER_BLE=${chip_config_network_layer_ble}" ] + + if (chip_build_libshell) { + defines += [ "CONFIG_ENABLE_CHIP_SHELL=1" ] + sources += [ "${examples_plat_dir}/shell/launch_shell.cpp" ] + include_dirs += [ "${examples_plat_dir}/shell" ] + } + + output_dir = root_out_dir + + if (chip_print_memory_usage) { + ldflags = [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } +} + +group("asr") { + deps = [ ":thermostat" ] +} + +group("default") { + deps = [ ":asr" ] +} diff --git a/examples/thermostat/asr/README.md b/examples/thermostat/asr/README.md new file mode 100755 index 00000000000000..f582c1b97e045e --- /dev/null +++ b/examples/thermostat/asr/README.md @@ -0,0 +1,52 @@ +# Matter ASR Thermostat Example + +The ASR Thermostat Example demonstrates controlling a thermostat and getting +temperature from local sensor. + +--- + +- [Matter ASR Thermostat Example](#matter-asr-thermostat-example) + - [Supported Chips](#supported-chips) + - [Building and Commissioning](#building-and-commissioning) + - [Cluster Control](#cluster-control) + +--- + +## Supported Chips + +The Matter demo application is supported on: + +- ASR582X +- ASR595X + +## Building and Commissioning + +Please refer +[Building and Commissioning](../../../docs/guides/asr_getting_started_guide.md#building-the-example-application) +guides to get started + +``` +./scripts/build/build_examples.py --target asr-$ASR_BOARD-thermostat build +``` + +## Cluster Control + +After successful commissioning, use `chip-tool` to control the board + +For example,read local-temperature value: + +``` +./chip-tool thermostat read local-temperature 1 +``` + +increases the temperature by sending a SetpointRaiseLower command: + +``` +./chip-tool thermostat setpoint-raise-lower 0 10 1 +``` + +decreases the temperature by sending a SetpointRaiseLower command: + +``` +./chip-tool thermostat setpoint-raise-lower 0 -10 1 +``` diff --git a/examples/thermostat/asr/args.gni b/examples/thermostat/asr/args.gni new file mode 100755 index 00000000000000..89f03298f4490a --- /dev/null +++ b/examples/thermostat/asr/args.gni @@ -0,0 +1,27 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("//cfg.gni") +import("${chip_root}/src/platform/ASR/args.gni") + +asr_target_project = + get_label_info(":thermostat_sdk_sources", "label_no_toolchain") + +declare_args() { + # Disable lock tracking, since our FreeRTOS configuration does not set + # INCLUDE_xSemaphoreGetMutexHolder + chip_stack_lock_tracking = "none" +} diff --git a/examples/thermostat/asr/build_overrides b/examples/thermostat/asr/build_overrides new file mode 120000 index 00000000000000..e578e73312ebd1 --- /dev/null +++ b/examples/thermostat/asr/build_overrides @@ -0,0 +1 @@ +../../build_overrides \ No newline at end of file diff --git a/examples/thermostat/asr/cfg.gni b/examples/thermostat/asr/cfg.gni new file mode 100755 index 00000000000000..15fe50e79efb6d --- /dev/null +++ b/examples/thermostat/asr/cfg.gni @@ -0,0 +1,23 @@ +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + chip_enable_factory_data = false + + chip_lwip_ip6_hook = false + + setupPinCode = 20202021 + + setupDiscriminator = 3840 +} diff --git a/examples/thermostat/asr/include/AppConfig.h b/examples/thermostat/asr/include/AppConfig.h new file mode 100644 index 00000000000000..86c67695c016bc --- /dev/null +++ b/examples/thermostat/asr/include/AppConfig.h @@ -0,0 +1,81 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#ifdef CFG_PLF_RV32 +#include "asr_gpio.h" +#include "asr_pinmux.h" +#define duet_gpio_dev_t asr_gpio_dev_t +#else +#include "duet_gpio.h" +#include "duet_pinmux.h" +#endif + +// ---- Lock Example App Config ---- + +#define APP_TASK_NAME "APP" + +#define APP_EVENT_QUEUE_SIZE 10 +#define APP_TASK_STACK_SIZE (1024 * 4) + +#define MATTER_DEVICE_NAME "ASR-Thermostat" + +#define APP_LOCK_BUTTON_IDX 0 +#define APP_FUNCTION_BUTTON_IDX 1 + +#define APP_LOCK_BUTTON GPIO10_INDEX +#define APP_FUNCTION_BUTTON GPIO11_INDEX + +#define APP_BUTTON_DEBOUNCE_PERIOD_MS 50 + +#define APP_BUTTON_PRESSED 0 +#define APP_BUTTON_RELEASED 1 + +#define SYSTEM_STATE_LED GPIO12_INDEX +#define LOCK_STATE_LED GPIO13_INDEX + +// Time it takes in ms for the simulated actuator to move from one +// state to another. +#define ACTUATOR_MOVEMENT_PERIOS_MS 2000 + +// ---- Lock Example SWU Config ---- +#define SWU_INTERVAl_WINDOW_MIN_MS (23 * 60 * 60 * 1000) // 23 hours +#define SWU_INTERVAl_WINDOW_MAX_MS (24 * 60 * 60 * 1000) // 24 hours + +// ---- Thread Polling Config ---- +#define THREAD_ACTIVE_POLLING_INTERVAL_MS 100 +#define THREAD_INACTIVE_POLLING_INTERVAL_MS 1000 + +// ASR Logging +#ifdef __cplusplus +extern "C" { +#endif + +void appError(int err); +void ASR_LOG(const char * aFormat, ...); + +#ifdef __cplusplus +} + +#define CONFIG_RENDEZVOUS_MODE 6 + +#include +void appError(CHIP_ERROR error); +#endif diff --git a/examples/thermostat/asr/include/AppEvent.h b/examples/thermostat/asr/include/AppEvent.h new file mode 100755 index 00000000000000..36a2593cd3263c --- /dev/null +++ b/examples/thermostat/asr/include/AppEvent.h @@ -0,0 +1,71 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2018 Nest Labs, Inc. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +struct AppEvent +{ + enum AppEventTypes + { + kEventType_Button = 0, + kEventType_Timer, + kEventType_UpdateLedState, + kEventType_IdentifyStart, + kEventType_IdentifyStop, + kEventType_Lighting, + kEventType_Thermostat, + kEventType_Install, + kEventType_Contact, + kEventType_Start, + }; + + uint16_t Type; + + union + { + struct + { + uint8_t Action; + } ButtonEvent; + struct + { + void * Context; + } TimerEvent; + struct + { + uint8_t Action; + int32_t Actor; + } LightingEvent; + struct + { + uint8_t Action; + } ContactEvent; + struct + { + uint8_t Action; + int32_t Actor; + } StartEvent; + }; + + EventHandler Handler; +}; diff --git a/examples/thermostat/asr/include/AppTask.h b/examples/thermostat/asr/include/AppTask.h new file mode 100644 index 00000000000000..90a8ac65adff46 --- /dev/null +++ b/examples/thermostat/asr/include/AppTask.h @@ -0,0 +1,73 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "AppEvent.h" +#include "FreeRTOS.h" +#include "SensorManager.h" +#include "TemperatureManager.h" +#include "timers.h" // provides FreeRTOS timer support +#include +#include + +#include +#include +#include + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) + +class AppTask +{ + +public: + CHIP_ERROR StartAppTask(); + static void AppTaskMain(void * pvParameter); + static void LightActionEventHandler(AppEvent * aEvent); + void ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction); + void PostEvent(const AppEvent * event); + /** + * Use internally for registration of the ChipDeviceEvents + */ + static void CommonDeviceEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + void UpdateClusterState(void); + void UpdateThermoStatUI(void); + +private: + friend AppTask & GetAppTask(void); + + CHIP_ERROR Init(); + + static AppTask sAppTask; + void DispatchEvent(AppEvent * event); + static void OnOffUpdateClusterState(void); +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} diff --git a/examples/thermostat/asr/include/BindingHandler.h b/examples/thermostat/asr/include/BindingHandler.h new file mode 100644 index 00000000000000..50874b67c04421 --- /dev/null +++ b/examples/thermostat/asr/include/BindingHandler.h @@ -0,0 +1,54 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include "app-common/zap-generated/ids/Attributes.h" +#include "app-common/zap-generated/ids/Clusters.h" +#include "app-common/zap-generated/ids/Commands.h" +#include "lib/core/CHIPError.h" +#include +#include +#include +#include + +class BindingHandler +{ +public: + static void Init(); + static void ThermostatNotifyFunction(intptr_t); + static void PrintBindingTable(); + static bool IsGroupBound(); + + struct BindingData + { + chip::EndpointId EndpointId; + chip::CommandId CommandId; + chip::ClusterId ClusterId; + chip::AttributeId AttributeId; + uint8_t Value; + bool IsGroup{ false }; + }; + + static void SubscribeHumidityAttribute(chip::AttributeId attributeId, chip::DeviceProxy * peer_device, void * context); + +private: + static void ReadTemperatureAttribute(chip::AttributeId, const EmberBindingTableEntry &, chip::DeviceProxy *, void *); + static void ReadHumidityAttribute(chip::AttributeId, const EmberBindingTableEntry &, chip::DeviceProxy *, void *); + static void ThermostatChangedHandler(const EmberBindingTableEntry &, chip::OperationalDeviceProxy *, void *); + static void ThermostatContextReleaseHandler(void *); + static void InitInternal(intptr_t); +}; diff --git a/examples/thermostat/asr/include/CHIPClusters.h b/examples/thermostat/asr/include/CHIPClusters.h new file mode 100644 index 00000000000000..e3b7157126b8c8 --- /dev/null +++ b/examples/thermostat/asr/include/CHIPClusters.h @@ -0,0 +1,80 @@ +/* + * + * 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. + */ + +// Prevent multiple inclusion +#pragma once + +#include +#include + +#include +#include +#include + +namespace chip { +namespace Controller { + +class DLL_EXPORT IdentifyCluster : public ClusterBase +{ +public: + IdentifyCluster(Messaging::ExchangeManager & exchangeManager, const SessionHandle & session, EndpointId endpoint) : + ClusterBase(exchangeManager, session, endpoint) + {} + ~IdentifyCluster() {} +}; + +class DLL_EXPORT DescriptorCluster : public ClusterBase +{ +public: + DescriptorCluster(Messaging::ExchangeManager & exchangeManager, const SessionHandle & session, EndpointId endpoint) : + ClusterBase(exchangeManager, session, endpoint) + {} + ~DescriptorCluster() {} +}; + +class DLL_EXPORT OtaSoftwareUpdateProviderCluster : public ClusterBase +{ +public: + OtaSoftwareUpdateProviderCluster(Messaging::ExchangeManager & exchangeManager, const SessionHandle & session, + EndpointId endpoint) : + ClusterBase(exchangeManager, session, endpoint) + {} + ~OtaSoftwareUpdateProviderCluster() {} +}; + +class DLL_EXPORT TemperatureMeasurementCluster : public ClusterBase +{ +public: + TemperatureMeasurementCluster(Messaging::ExchangeManager & exchangeManager, const SessionHandle & session, + EndpointId endpoint) : + ClusterBase(exchangeManager, session, endpoint) + {} + ~TemperatureMeasurementCluster() {} +}; + +class DLL_EXPORT RelativeHumidityMeasurementCluster : public ClusterBase +{ +public: + RelativeHumidityMeasurementCluster(Messaging::ExchangeManager & exchangeManager, const SessionHandle & session, + EndpointId endpoint) : + ClusterBase(exchangeManager, session, endpoint) + {} + ~RelativeHumidityMeasurementCluster() {} +}; + +} // namespace Controller +} // namespace chip diff --git a/examples/thermostat/asr/include/CHIPProjectConfig.h b/examples/thermostat/asr/include/CHIPProjectConfig.h new file mode 100755 index 00000000000000..00af1a3364eb3e --- /dev/null +++ b/examples/thermostat/asr/include/CHIPProjectConfig.h @@ -0,0 +1,109 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +/** + * CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY + * + * Enables the use of a hard-coded default Chip device id and credentials if no device id + * is found in Chip NV storage. + * + * This option is for testing only and should be disabled in production releases. + */ +#define CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY 37 + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "1.0" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 1 +#endif + +/** + * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + * + * Enable support for Chip-over-BLE (CHIPoBLE). + */ +// #define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) diff --git a/examples/thermostat/asr/include/DeviceCallbacks.h b/examples/thermostat/asr/include/DeviceCallbacks.h new file mode 100644 index 00000000000000..dccb1bef2c0f7d --- /dev/null +++ b/examples/thermostat/asr/include/DeviceCallbacks.h @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.h + * + * Implementations for the DeviceManager callbacks for this application + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include +#include +#include + +class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks +{ +public: + virtual void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t type, uint16_t size, uint8_t * value); + +private: + void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); +}; diff --git a/examples/thermostat/asr/include/SensorManager.h b/examples/thermostat/asr/include/SensorManager.h new file mode 100644 index 00000000000000..76095c30259e78 --- /dev/null +++ b/examples/thermostat/asr/include/SensorManager.h @@ -0,0 +1,46 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "AppEvent.h" +#include "lega_at_api.h" +#include +#include +#include +#include + +class SensorManager +{ +public: + CHIP_ERROR Init(); + +private: + friend SensorManager & SensorMgr(); + + // Reads new generated sensor value, stores it, and updates local temperature attribute + static void TimerEventHandler(lega_timer_t * timer); + static void SensorTimerEventHandler(AppEvent * aEvent); + + static SensorManager sSensorManager; +}; + +inline SensorManager & SensorMgr() +{ + return SensorManager::sSensorManager; +} diff --git a/examples/thermostat/asr/include/TemperatureManager.h b/examples/thermostat/asr/include/TemperatureManager.h new file mode 100755 index 00000000000000..e19a4fcf248057 --- /dev/null +++ b/examples/thermostat/asr/include/TemperatureManager.h @@ -0,0 +1,65 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include + +#include + +using namespace chip; + +// AppCluster Spec Table 85. +enum ThermMode +{ + OFF = 0, + AUTO, + NOT_USED, + COOL, + HEAT, +}; + +class TemperatureManager +{ +public: + CHIP_ERROR Init(); + void AttributeChangeHandler(EndpointId endpointId, AttributeId attributeId, uint8_t * value, uint16_t size); + uint8_t GetMode(); + int8_t GetCurrentTemp(); + int8_t GetHeatingSetPoint(); + int8_t GetCoolingSetPoint(); + +private: + friend TemperatureManager & TempMgr(); + + int8_t mCurrentTempCelsius; + int8_t mCoolingCelsiusSetPoint; + int8_t mHeatingCelsiusSetPoint; + uint8_t mThermMode; + + int8_t ConvertToPrintableTemp(int16_t temperature); + static TemperatureManager sTempMgr; +}; + +inline TemperatureManager & TempMgr() +{ + return TemperatureManager::sTempMgr; +} diff --git a/examples/thermostat/asr/src/AppTask.cpp b/examples/thermostat/asr/src/AppTask.cpp new file mode 100644 index 00000000000000..544c3c42108be2 --- /dev/null +++ b/examples/thermostat/asr/src/AppTask.cpp @@ -0,0 +1,176 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" +#include "AppConfig.h" +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include "LEDWidget.h" +#include "init_Matter.h" +#include "qrcodegen.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; +using namespace ::chip::System; + +namespace { +TaskHandle_t sAppTaskHandle; +QueueHandle_t sAppEventQueue; + +constexpr EndpointId kThermostatEndpointId = 1; +} // namespace + +namespace { +constexpr EndpointId kNetworkCommissioningEndpointMain = 0; +constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; + +app::Clusters::NetworkCommissioning::Instance + sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, + &(NetworkCommissioning::ASRWiFiDriver::GetInstance())); +} // namespace + +void NetWorkCommissioningInstInit() +{ + sWiFiNetworkCommissioningInstance.Init(); + + // We only have network commissioning on endpoint 0. + emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); +} + +AppTask AppTask::sAppTask; +static DeviceCallbacks EchoCallbacks; +LEDWidget lightLED; + +CHIP_ERROR AppTask::StartAppTask() +{ + sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); + if (sAppEventQueue == NULL) + { + ASR_LOG("Failed to allocate app event queue"); + appError(APP_ERROR_EVENT_QUEUE_FAILED); + } + // Start App task. + xTaskCreate(AppTaskMain, APP_TASK_NAME, APP_TASK_STACK_SIZE, 0, 2, &sAppTaskHandle); + return (sAppTaskHandle == nullptr) ? CHIP_APPLICATION_ERROR(0x02) : CHIP_NO_ERROR; +} + +CHIP_ERROR AppTask::Init() +{ + if (MatterInitializer::Init_Matter_Stack(MATTER_DEVICE_NAME) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); + + if (deviceMgr.Init(&EchoCallbacks) != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + if (MatterInitializer::Init_Matter_Server() != CHIP_NO_ERROR) + appError(CHIP_ERROR_INTERNAL); + + NetWorkCommissioningInstInit(); + + ASR_LOG("Current Firmware Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + ConfigurationMgr().LogDeviceConfig(); + + // Print setup info + PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); + + CHIP_ERROR err; + err = SensorMgr().Init(); + if (err != CHIP_NO_ERROR) + { + ASR_LOG("SensorMgr Init fail"); + appError(err); + } + err = TempMgr().Init(); + if (err != CHIP_NO_ERROR) + { + ASR_LOG("TempMgr Init fail"); + appError(err); + } + + return CHIP_NO_ERROR; +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + + AppEvent event; + CHIP_ERROR err = sAppTask.Init(); + if (err != CHIP_NO_ERROR) + { + ASR_LOG("AppTask.Init() failed"); + appError(err); + } + + while (true) + { + BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10)); + if (eventReceived == pdTRUE) + { + sAppTask.DispatchEvent(&event); + } + } + + /* Delete task */ + vTaskDelete(NULL); +} + +void AppTask::UpdateThermoStatUI(void) +{ + ASR_LOG("Thermostat Status - M:%d T:%d'C H:%d'C C:%d'C", TempMgr().GetMode(), TempMgr().GetCurrentTemp(), + TempMgr().GetHeatingSetPoint(), TempMgr().GetCoolingSetPoint()); +} + +void AppTask::UpdateClusterState() {} + +void AppTask::PostEvent(const AppEvent * event) +{ + if (sAppEventQueue != NULL) + { + if (!xQueueSend(sAppEventQueue, event, 1)) + { + ASR_LOG("Failed to post event to app task event queue"); + } + } +} + +void AppTask::DispatchEvent(AppEvent * event) +{ + if (event->Handler) + { + event->Handler(event); + } + else + { + ASR_LOG("Event received with no handler. Dropping event."); + } +} diff --git a/examples/thermostat/asr/src/DeviceCallbacks.cpp b/examples/thermostat/asr/src/DeviceCallbacks.cpp new file mode 100644 index 00000000000000..62f991c7086da9 --- /dev/null +++ b/examples/thermostat/asr/src/DeviceCallbacks.cpp @@ -0,0 +1,130 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.cpp + * + * Implements all the callbacks to the application from the CHIP Stack + * + **/ +#include "DeviceCallbacks.h" +#include "AppConfig.h" +#include "TemperatureManager.h" +#include +#include + +#include "init_OTARequestor.h" +#include +#include +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT +#include "route_hook/asr_route_hook.h" +#endif + +constexpr uint32_t kReportDelaySec = 3; + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::System; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +constexpr uint32_t kInitOTARequestorDelaySec = 3; + +void InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +{ + OTAInitializer::Instance().InitOTARequestor(); +} +#endif +void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + switch (event->Type) + { + case DeviceEventType::kInternetConnectivityChange: + OnInternetConnectivityChange(event); + break; + + case DeviceEventType::kInterfaceIpAddressChanged: + if ((event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned) || + (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned)) + { + // MDNS server restart on any ip assignment: if link local ipv6 is configured, that + // will not trigger a 'internet connectivity change' as there is no internet + // connectivity. MDNS still wants to refresh its listening interfaces to include the + // newly selected address. + chip::app::DnssdServer::Instance().StartServer(); + + if (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned) + { +#if defined CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT || defined CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT + ChipLogProgress(NotSpecified, "Initializing route hook..."); + asr_route_hook_init(); +#endif + } + } + break; + } +} + +void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t type, + uint16_t size, uint8_t * value) +{ + ChipLogProgress(DeviceLayer, + "PostAttributeChangeCallback - Cluster ID: " ChipLogFormatMEI + ", EndPoint ID: '0x%02x', Attribute ID: " ChipLogFormatMEI, + ChipLogValueMEI(clusterId), endpointId, ChipLogValueMEI(attributeId)); + + if (clusterId == chip::app::Clusters::Thermostat::Id) + { + TempMgr().AttributeChangeHandler(endpointId, attributeId, value, size); + } +} + +void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + static bool isOTAInitialized = false; +#endif + if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv4 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); + } + else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv4 connectivity..."); + } + if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established) + { + ChipLogProgress(DeviceLayer, "IPv6 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + // Init OTA requestor only when we have gotten IPv6 address + if (!isOTAInitialized) + { + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(kInitOTARequestorDelaySec), + InitOTARequestorHandler, nullptr); + isOTAInitialized = true; + } +#endif + } + else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost) + { + ChipLogProgress(DeviceLayer, "Lost IPv6 connectivity..."); + } +} diff --git a/examples/thermostat/asr/src/SensorManager.cpp b/examples/thermostat/asr/src/SensorManager.cpp new file mode 100644 index 00000000000000..8d2d405e02c768 --- /dev/null +++ b/examples/thermostat/asr/src/SensorManager.cpp @@ -0,0 +1,88 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "SensorManager.h" +#include "AppConfig.h" +#include "AppTask.h" +#include "lega_rtos_api.h" + +using namespace chip; +using namespace ::chip::DeviceLayer; + +constexpr EndpointId kThermostatEndpoint = 1; +constexpr uint16_t kSensorTimerPeriodMs = 30000; // 30s timer period +constexpr uint16_t kMinTemperatureDelta = 50; // 0.5 degree Celsius + +lega_timer_t sSensorTimer; + +SensorManager SensorManager::sSensorManager; + +constexpr uint16_t kSimulatedReadingFrequency = (60000 / kSensorTimerPeriodMs); // Change Simulated number at each minutes +static int16_t mSimulatedTemp[] = { 2300, 2400, 2800, 2550, 2200, 2125, 2100, 2600, 1800, 2700 }; + +CHIP_ERROR SensorManager::Init() +{ + // Initialize temp sensor timer + lega_rtos_init_timer(&sSensorTimer, kSensorTimerPeriodMs, (timer_handler_t) &TimerEventHandler, this); + lega_rtos_start_timer(&sSensorTimer); + + return CHIP_NO_ERROR; +} + +void SensorManager::TimerEventHandler(lega_timer_t * timer) +{ + AppEvent event; + event.Type = AppEvent::kEventType_Thermostat; + event.TimerEvent.Context = timer->arg; + event.Handler = SensorTimerEventHandler; + GetAppTask().PostEvent(&event); +} + +void SensorManager::SensorTimerEventHandler(AppEvent * aEvent) +{ + int16_t temperature = 0; + static int16_t lastTemperature = 0; + + static uint8_t nbOfRepetition = 0; + static uint8_t simulatedIndex = 0; + if (simulatedIndex >= sizeof(mSimulatedTemp)) + { + simulatedIndex = 0; + } + temperature = mSimulatedTemp[simulatedIndex]; + + nbOfRepetition++; + if (nbOfRepetition >= kSimulatedReadingFrequency) + { + simulatedIndex++; + nbOfRepetition = 0; + } + + ASR_LOG("Sensor Temp is : %d", temperature); + + if ((temperature >= (lastTemperature + kMinTemperatureDelta)) || temperature <= (lastTemperature - kMinTemperatureDelta)) + { + lastTemperature = temperature; + PlatformMgr().LockChipStack(); + app::Clusters::Thermostat::Attributes::LocalTemperature::Set(kThermostatEndpoint, temperature); + PlatformMgr().UnlockChipStack(); + } + + // Start next timer to handle temp sensor. + lega_rtos_start_timer(&sSensorTimer); +} diff --git a/examples/thermostat/asr/src/TemperatureManager.cpp b/examples/thermostat/asr/src/TemperatureManager.cpp new file mode 100644 index 00000000000000..219f428e85e781 --- /dev/null +++ b/examples/thermostat/asr/src/TemperatureManager.cpp @@ -0,0 +1,135 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "TemperatureManager.h" +#include "AppConfig.h" +#include "AppTask.h" + +using namespace chip; +using namespace ::chip::DeviceLayer; + +constexpr EndpointId kThermostatEndpoint = 1; + +namespace ThermAttr = chip::app::Clusters::Thermostat::Attributes; + +TemperatureManager TemperatureManager::sTempMgr; + +CHIP_ERROR TemperatureManager::Init() +{ + app::DataModel::Nullable temp; + int16_t heatingSetpoint, coolingSetpoint; + uint8_t systemMode; + + PlatformMgr().LockChipStack(); + ThermAttr::LocalTemperature::Get(kThermostatEndpoint, temp); + ThermAttr::OccupiedCoolingSetpoint::Get(kThermostatEndpoint, &coolingSetpoint); + ThermAttr::OccupiedHeatingSetpoint::Get(kThermostatEndpoint, &heatingSetpoint); + ThermAttr::SystemMode::Get(kThermostatEndpoint, &systemMode); + PlatformMgr().UnlockChipStack(); + + mCurrentTempCelsius = ConvertToPrintableTemp(temp.Value()); + mHeatingCelsiusSetPoint = ConvertToPrintableTemp(coolingSetpoint); + mCoolingCelsiusSetPoint = ConvertToPrintableTemp(heatingSetpoint); + mThermMode = systemMode; + + GetAppTask().UpdateThermoStatUI(); + + return CHIP_NO_ERROR; +} + +int8_t TemperatureManager::ConvertToPrintableTemp(int16_t temperature) +{ + constexpr uint8_t kRoundUpValue = 50; + + // Round up the temperature as we won't print decimals on LCD + // Is it a negative temperature + if (temperature < 0) + { + temperature -= kRoundUpValue; + } + else + { + temperature += kRoundUpValue; + } + + return static_cast(temperature / 100); +} + +void TemperatureManager::AttributeChangeHandler(EndpointId endpointId, AttributeId attributeId, uint8_t * value, uint16_t size) +{ + switch (attributeId) + { + case ThermAttr::LocalTemperature::Id: { + int8_t Temp = ConvertToPrintableTemp(*((int16_t *) value)); + ASR_LOG("Local temp %d", Temp); + mCurrentTempCelsius = Temp; + } + break; + + case ThermAttr::OccupiedCoolingSetpoint::Id: { + int8_t coolingTemp = ConvertToPrintableTemp(*((int16_t *) value)); + ASR_LOG("CoolingSetpoint %d", coolingTemp); + mCoolingCelsiusSetPoint = coolingTemp; + } + break; + + case ThermAttr::OccupiedHeatingSetpoint::Id: { + int8_t heatingTemp = ConvertToPrintableTemp(*((int16_t *) value)); + ASR_LOG("HeatingSetpoint %d", heatingTemp); + mHeatingCelsiusSetPoint = heatingTemp; + } + break; + + case ThermAttr::SystemMode::Id: { + ASR_LOG("SystemMode %d", static_cast(*value)); + uint8_t mode = static_cast(*value); + if (mThermMode != mode) + { + mThermMode = mode; + } + } + break; + + default: { + ASR_LOG("Unhandled thermostat attribute %x", attributeId); + return; + } + break; + } + + GetAppTask().UpdateThermoStatUI(); +} + +uint8_t TemperatureManager::GetMode() +{ + return mThermMode; +} + +int8_t TemperatureManager::GetCurrentTemp() +{ + return mCurrentTempCelsius; +} +int8_t TemperatureManager::GetHeatingSetPoint() +{ + return mHeatingCelsiusSetPoint; +} + +int8_t TemperatureManager::GetCoolingSetPoint() +{ + return mCoolingCelsiusSetPoint; +} diff --git a/examples/thermostat/asr/src/main.cpp b/examples/thermostat/asr/src/main.cpp new file mode 100644 index 00000000000000..eb58449e1caab3 --- /dev/null +++ b/examples/thermostat/asr/src/main.cpp @@ -0,0 +1,79 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "AppConfig.h" +#include "AppTask.h" +#include "init_asrPlatform.h" + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; +// ================================================================================ +// App Error +//================================================================================= +void appError(int err) +{ + ASR_LOG("!!!!!!!!!!!! App Critical Error: %d !!!!!!!!!!!", err); + lega_rtos_declare_critical(); + lega_rtos_enter_critical(); + while (1) + ; +} + +void appError(CHIP_ERROR error) +{ + appError(static_cast(error.AsInteger())); +} +// ================================================================================ +// Main Code +// ================================================================================ +int main(void) +{ + init_asrPlatform(); + + CHIP_ERROR ret = GetAppTask().StartAppTask(); + if (ret != CHIP_NO_ERROR) + { + ASR_LOG("GetAppTask().Init() failed"); + appError(ret); + } + /* Start the FreeRTOS scheduler */ + vTaskStartScheduler(); + + chip::Platform::MemoryShutdown(); + PlatformMgr().StopEventLoopTask(); + PlatformMgr().Shutdown(); + + // Should never get here. + ASR_LOG("vTaskStartScheduler() failed"); + appError(ret); +} diff --git a/examples/thermostat/asr/third_party/connectedhomeip b/examples/thermostat/asr/third_party/connectedhomeip new file mode 120000 index 00000000000000..11a54ed360106c --- /dev/null +++ b/examples/thermostat/asr/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../ \ No newline at end of file diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index f573feec814940..279191e45d1bf9 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -418,7 +418,15 @@ def BuildASRTarget(): # apps target.AppendFixedTargets([ + TargetPart('all-clusters', app=ASRApp.ALL_CLUSTERS), + TargetPart('all-clusters-minimal', app=ASRApp.ALL_CLUSTERS_MINIMAL), TargetPart('lighting', app=ASRApp.LIGHT), + TargetPart('light-switch', app=ASRApp.LIGHT_SWITCH), + TargetPart('lock', app=ASRApp.LOCK), + TargetPart('bridge', app=ASRApp.BRIDGE), + TargetPart('temperature-measurement', app=ASRApp.TEMPERATURE_MEASUREMENT), + TargetPart('thermostat', app=ASRApp.THERMOSTAT), + TargetPart('ota-requestor', app=ASRApp.OTA_REQUESTOR), ]) # modifiers diff --git a/scripts/build/builders/asr.py b/scripts/build/builders/asr.py index c329f70e29ddc7..23c9e4294c138a 100644 --- a/scripts/build/builders/asr.py +++ b/scripts/build/builders/asr.py @@ -19,17 +19,57 @@ class ASRApp(Enum): + ALL_CLUSTERS = auto() + ALL_CLUSTERS_MINIMAL = auto() LIGHT = auto() + LIGHT_SWITCH = auto() + LOCK = auto() + BRIDGE = auto() + TEMPERATURE_MEASUREMENT = auto() + THERMOSTAT = auto() + OTA_REQUESTOR = auto() def ExampleName(self): - if self == ASRApp.LIGHT: + if self == ASRApp.ALL_CLUSTERS: + return 'all-clusters-app' + elif self == ASRApp.ALL_CLUSTERS_MINIMAL: + return 'all-clusters-minimal-app' + elif self == ASRApp.LIGHT: return 'lighting-app' + elif self == ASRApp.LIGHT_SWITCH: + return 'light-switch-app' + elif self == ASRApp.LOCK: + return 'lock-app' + elif self == ASRApp.BRIDGE: + return 'bridge-app' + elif self == ASRApp.TEMPERATURE_MEASUREMENT: + return 'temperature-measurement-app' + elif self == ASRApp.THERMOSTAT: + return 'thermostat' + elif self == ASRApp.OTA_REQUESTOR: + return 'ota-requestor-app' else: raise Exception('Unknown app type: %r' % self) def AppNamePrefix(self): - if self == ASRApp.LIGHT: + if self == ASRApp.ALL_CLUSTERS: + return 'chip-asr-all-clusters-app' + elif self == ASRApp.ALL_CLUSTERS_MINIMAL: + return 'chip-asr-all-clusters-minimal-app' + elif self == ASRApp.LIGHT: return 'chip-asr-lighting-app' + elif self == ASRApp.LIGHT_SWITCH: + return 'chip-asr-light-switch-app' + elif self == ASRApp.LOCK: + return 'chip-asr-lock-example' + elif self == ASRApp.BRIDGE: + return 'chip-asr-bridge-example' + elif self == ASRApp.TEMPERATURE_MEASUREMENT: + return 'chip-asr-temperature-measurement-example' + elif self == ASRApp.THERMOSTAT: + return 'chip-asr-thermostat-example' + elif self == ASRApp.OTA_REQUESTOR: + return 'chip-asr-ota-requestor-example' else: raise Exception('Unknown app type: %r' % self) diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index e4f8a8968253f8..1b8c95d4c51c7d 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -1,5 +1,5 @@ ameba-amebad-{all-clusters,all-clusters-minimal,light,light-switch,pigweed} -asr-{asr582x,asr595x}-lighting[-ota][-shell][-no_logging][-factory][-rotating_id] +asr-{asr582x,asr595x}-{all-clusters,all-clusters-minimal,lighting,light-switch,lock,bridge,temperature-measurement,thermostat,ota-requestor}[-ota][-shell][-no_logging][-factory][-rotating_id] android-{arm,arm64,x86,x64,androidstudio-arm,androidstudio-arm64,androidstudio-x86,androidstudio-x64}-{chip-tool,chip-test,tv-server,tv-casting-app,java-matter-controller}[-no-debug] bouffalolab-{bl602-iot-matter-v1,bl602-iot-dvk-3s,bl602-night-light,xt-zb6-devkit,bl706-iot-dvk,bl706-night-light}-light[-shell][-115200][-rpc][-cdc] cc32xx-lock From 7ab05664502038468466807238e5e56e29a2840b Mon Sep 17 00:00:00 2001 From: Marcin Kajor Date: Fri, 9 Jun 2023 13:53:43 +0200 Subject: [PATCH 14/15] Adapt docs to the changed chip-tool command naming. Recently the otasoftwareupdaterequestor attributes' and commands' names have been slightly modified in chip-tool but it looks like the correlated documentation has not been synced. Also fixed spell checker errors. Signed-off-by: Marcin Kajor --- .github/.wordlist.txt | 1 + docs/guides/esp32/ota.md | 8 ++++---- docs/guides/infineon_psoc6_software_update.md | 2 +- docs/guides/nrfconnect_examples_software_update.md | 4 ++-- docs/guides/silabs_efr32_software_update.md | 2 +- examples/all-clusters-app/telink/Readme.md | 2 +- examples/all-clusters-minimal-app/telink/Readme.md | 2 +- examples/bridge-app/telink/README.md | 2 +- examples/contact-sensor-app/nxp/k32w/k32w0/README.md | 2 +- examples/contact-sensor-app/telink/README.md | 2 +- examples/light-switch-app/telink/README.md | 2 +- examples/lighting-app/nxp/k32w/k32w0/README.md | 2 +- examples/lighting-app/telink/README.md | 2 +- examples/lock-app/telink/README.md | 2 +- examples/ota-requestor-app/ameba/README.md | 4 ++-- examples/ota-requestor-app/esp32/README.md | 2 +- examples/ota-requestor-app/infineon/cyw30739/README.md | 2 +- examples/ota-requestor-app/linux/README.md | 10 +++++----- examples/ota-requestor-app/telink/Readme.md | 2 +- examples/pump-app/telink/README.md | 2 +- examples/pump-controller-app/telink/README.md | 2 +- examples/temperature-measurement-app/telink/README.md | 2 +- examples/thermostat/telink/Readme.md | 2 +- examples/window-app/telink/README.md | 2 +- 24 files changed, 33 insertions(+), 32 deletions(-) diff --git a/.github/.wordlist.txt b/.github/.wordlist.txt index 6e43cf46167d78..4375a4e77f3204 100644 --- a/.github/.wordlist.txt +++ b/.github/.wordlist.txt @@ -979,6 +979,7 @@ otaissues OTAProvider OTAProviderIpAddress OTAProviderNodeId +otaproviders OTAProviderSerialPort OTARequesterImpl OTARequestorDriver diff --git a/docs/guides/esp32/ota.md b/docs/guides/esp32/ota.md index fb243735fc9696..7c9c388b422cb9 100644 --- a/docs/guides/esp32/ota.md +++ b/docs/guides/esp32/ota.md @@ -35,15 +35,15 @@ control list. ### Using Console -After commissioning is successful, read the default-ota-providers list of +After commissioning is successful, read the default-otaproviders list of requestor using the command below. ``` ./out/debug/chip-tool otasoftwareupdaterequestor read default-otaproviders 0 ``` -If the list does not have your provider, write into default-ota-providers list -of requestor using the command below. +If the list does not have your provider, write into default-otaproviders list of +requestor using the command below. ``` ./out/debug/chip-tool otasoftwareupdaterequestor write default-otaproviders '[{"fabricIndex": 1, "providerNodeID": , "endpoint": 0}, {"fabricIndex": 1, "providerNodeID": , "endpoint": 0}]' 0 @@ -65,7 +65,7 @@ After commissioning is successful, announce OTA provider's presence using chip-tool. On receiving this command OTA requestor will query for OTA image. ``` -./out/debug/chip-tool otasoftwareupdaterequestor announce-ota-provider 0 0 0 0 +./out/debug/chip-tool otasoftwareupdaterequestor announce-otaprovider 0 0 0 0 ``` ## Encrypted OTA diff --git a/docs/guides/infineon_psoc6_software_update.md b/docs/guides/infineon_psoc6_software_update.md index 713b0b1409b254..4367142b79e4d8 100644 --- a/docs/guides/infineon_psoc6_software_update.md +++ b/docs/guides/infineon_psoc6_software_update.md @@ -69,7 +69,7 @@ Infineon PSoC6 example applications by passing the * Once the commissioning process completes enter: ``` - ./out/chip-tool otasoftwareupdaterequestor announce-ota-provider 1 0 0 0 2 0 + ./out/chip-tool otasoftwareupdaterequestor announce-otaprovider 1 0 0 0 2 0 ``` * The application device will connect to the Provider and start the image diff --git a/docs/guides/nrfconnect_examples_software_update.md b/docs/guides/nrfconnect_examples_software_update.md index 608c29f444fd70..ebaf08f46a587f 100644 --- a/docs/guides/nrfconnect_examples_software_update.md +++ b/docs/guides/nrfconnect_examples_software_update.md @@ -81,7 +81,7 @@ To test the DFU over Matter, you need to complete the following steps: Requestor Endpoint ID, respectively): ``` - ./out/chiptool/chip-tool otasoftwareupdaterequestor write default-ota-providers '[{"fabricIndex": 1, "providerNodeID": 1, "endpoint": 0}]' 2 0 + ./out/chiptool/chip-tool otasoftwareupdaterequestor write default-otaproviders '[{"fabricIndex": 1, "providerNodeID": 1, "endpoint": 0}]' 2 0 ``` 9. Configure the OTA Provider with the access control list (ACL) that grants @@ -109,7 +109,7 @@ To test the DFU over Matter, you need to complete the following steps: Requestor Endpoint ID, respectively): ``` - ./out/chiptool/chip-tool otasoftwareupdaterequestor announce-ota-provider 1 0 0 0 2 0 + ./out/chiptool/chip-tool otasoftwareupdaterequestor announce-otaprovider 1 0 0 0 2 0 ``` Once the device is made aware of the OTA Provider node, it automatically diff --git a/docs/guides/silabs_efr32_software_update.md b/docs/guides/silabs_efr32_software_update.md index adc95607914000..3d8649cf91511b 100644 --- a/docs/guides/silabs_efr32_software_update.md +++ b/docs/guides/silabs_efr32_software_update.md @@ -61,7 +61,7 @@ where operationalDataset is obtained from the OpenThread Border Router. - Once the commissioning process completes enter: - ./out/chip-tool otasoftwareupdaterequestor announce-ota-provider 1 0 0 0 2 0 + ./out/chip-tool otasoftwareupdaterequestor announce-otaprovider 1 0 0 0 2 0 - The application device will connect to the Provider and start the image download. Once the image is downloaded the device will reboot into the diff --git a/examples/all-clusters-app/telink/Readme.md b/examples/all-clusters-app/telink/Readme.md index ececcdb4a1fd0b..aaea384d83b4c5 100644 --- a/examples/all-clusters-app/telink/Readme.md +++ b/examples/all-clusters-app/telink/Readme.md @@ -163,7 +163,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/all-clusters-minimal-app/telink/Readme.md b/examples/all-clusters-minimal-app/telink/Readme.md index f2fc7f4d0518ee..1051c077a3ed11 100644 --- a/examples/all-clusters-minimal-app/telink/Readme.md +++ b/examples/all-clusters-minimal-app/telink/Readme.md @@ -146,7 +146,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/bridge-app/telink/README.md b/examples/bridge-app/telink/README.md index bec1790828de37..34ce68e54edb3d 100644 --- a/examples/bridge-app/telink/README.md +++ b/examples/bridge-app/telink/README.md @@ -308,7 +308,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/contact-sensor-app/nxp/k32w/k32w0/README.md b/examples/contact-sensor-app/nxp/k32w/k32w0/README.md index bfbf287e113d6c..af98333cb8b99f 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w0/README.md +++ b/examples/contact-sensor-app/nxp/k32w/k32w0/README.md @@ -642,7 +642,7 @@ user@computer1:~/connectedhomeip$ : ./out/chip-tool-app/chip-tool pairing ble-th Start the OTA process: ``` -user@computer1:~/connectedhomeip$ : ./out/chip-tool-app/chip-tool otasoftwareupdaterequestor announce-ota-provider 1 0 0 0 2 0 +user@computer1:~/connectedhomeip$ : ./out/chip-tool-app/chip-tool otasoftwareupdaterequestor announce-otaprovider 1 0 0 0 2 0 ``` ### Known issues ota diff --git a/examples/contact-sensor-app/telink/README.md b/examples/contact-sensor-app/telink/README.md index d8d60e627d8875..68475be1d69c9b 100755 --- a/examples/contact-sensor-app/telink/README.md +++ b/examples/contact-sensor-app/telink/README.md @@ -165,7 +165,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/light-switch-app/telink/README.md b/examples/light-switch-app/telink/README.md index bca98378dd8e6f..76f62c6db681ee 100755 --- a/examples/light-switch-app/telink/README.md +++ b/examples/light-switch-app/telink/README.md @@ -286,7 +286,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/lighting-app/nxp/k32w/k32w0/README.md b/examples/lighting-app/nxp/k32w/k32w0/README.md index 5019e8a4f612f6..674960ee0d560c 100644 --- a/examples/lighting-app/nxp/k32w/k32w0/README.md +++ b/examples/lighting-app/nxp/k32w/k32w0/README.md @@ -655,7 +655,7 @@ user@computer1:~/connectedhomeip$ : ./out/chip-tool-app/chip-tool pairing ble-th Start the OTA process: ``` -user@computer1:~/connectedhomeip$ : ./out/chip-tool-app/chip-tool otasoftwareupdaterequestor announce-ota-provider 1 0 0 0 2 0 +user@computer1:~/connectedhomeip$ : ./out/chip-tool-app/chip-tool otasoftwareupdaterequestor announce-otaprovider 1 0 0 0 2 0 ``` ## Known issues ota diff --git a/examples/lighting-app/telink/README.md b/examples/lighting-app/telink/README.md index e9c4c5a104780c..ddb536496e77bc 100644 --- a/examples/lighting-app/telink/README.md +++ b/examples/lighting-app/telink/README.md @@ -251,7 +251,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/lock-app/telink/README.md b/examples/lock-app/telink/README.md index 8905d996d7f666..d6eefac21b5fdd 100755 --- a/examples/lock-app/telink/README.md +++ b/examples/lock-app/telink/README.md @@ -168,7 +168,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/ota-requestor-app/ameba/README.md b/examples/ota-requestor-app/ameba/README.md index 73be70beeef4f2..029cbed876b7ba 100644 --- a/examples/ota-requestor-app/ameba/README.md +++ b/examples/ota-requestor-app/ameba/README.md @@ -53,7 +53,7 @@ A prototype application that demonstrates OTA Requestor capabilities. 4. Write the Default OTA providers into Ameba - $ ./chip-tool otasoftwareupdaterequestor write default-ota-providers '[{"fabricIndex": 1, "providerNodeID": 2, "endpoint": 0}]' 1 0 + $ ./chip-tool otasoftwareupdaterequestor write default-otaproviders '[{"fabricIndex": 1, "providerNodeID": 2, "endpoint": 0}]' 1 0 5. Configure the ACL of the ota-provider-app to allow access for Ameba @@ -61,7 +61,7 @@ A prototype application that demonstrates OTA Requestor capabilities. 6. Use the chip-tool to announce the ota-provider-app to start the OTA process - $ ./chip-tool otasoftwareupdaterequestor announce-ota-provider 1 0 0 0 2 0 + $ ./chip-tool otasoftwareupdaterequestor announce-otaprovider 1 0 0 0 2 0 7. The OTA process should include downloading the image, verification of image header, erasing upgraded flash partition, writing to flash and checksum diff --git a/examples/ota-requestor-app/esp32/README.md b/examples/ota-requestor-app/esp32/README.md index 734985783df06c..1951b4535b13ca 100644 --- a/examples/ota-requestor-app/esp32/README.md +++ b/examples/ota-requestor-app/esp32/README.md @@ -28,7 +28,7 @@ After commissioning is successful, announce OTA provider's presence using chip-tool. On receiving this command OTA requestor will query for OTA image. ``` -./out/debug/chip-tool otasoftwareupdaterequestor announce-ota-provider 0 0 0 0 +./out/debug/chip-tool otasoftwareupdaterequestor announce-otaprovider 0 0 0 0 ``` Once the transfer is complete, OTA requestor sends ApplyUpdateRequest command to diff --git a/examples/ota-requestor-app/infineon/cyw30739/README.md b/examples/ota-requestor-app/infineon/cyw30739/README.md index 0a55e93bf60a1d..629418c395d552 100644 --- a/examples/ota-requestor-app/infineon/cyw30739/README.md +++ b/examples/ota-requestor-app/infineon/cyw30739/README.md @@ -135,5 +135,5 @@ Put the CYW30739 in to the recovery mode before running the flash script. chip-tool pairing onnetwork-vendor 4321 20202021 9050 # Announce the OTA provider to the requestor - chip-tool otasoftwareupdaterequestor announce-ota-provider 4321 9 0 0 1234 0 + chip-tool otasoftwareupdaterequestor announce-otaprovider 4321 9 0 0 1234 0 ``` diff --git a/examples/ota-requestor-app/linux/README.md b/examples/ota-requestor-app/linux/README.md index 9cb47171aae555..d347ffaf0e52a6 100644 --- a/examples/ota-requestor-app/linux/README.md +++ b/examples/ota-requestor-app/linux/README.md @@ -306,7 +306,7 @@ out/chip-tool pairing onnetwork-long 0x1234567890 20202021 18 **Write to the DefaultOTAProviders attribute** ``` -out/chip-tool otasoftwareupdaterequestor write default-ota-providers '[{"providerNodeID": 3735928559, "endpoint": 0}]' 0x1234567890 0 +out/chip-tool otasoftwareupdaterequestor write default-otaproviders '[{"providerNodeID": 3735928559, "endpoint": 0}]' 0x1234567890 0 ``` Every 60 seconds from when the OTA Requestor application has launched, the OTA @@ -400,15 +400,15 @@ out/chip-tool pairing onnetwork-long 0xB0B 20202021 18 --commissioner-name beta **Write/Read DefaultOTAProviders on the first fabric (alpha)** ``` -out/chip-tool otasoftwareupdaterequestor write default-ota-providers '[{"providerNodeID": 12648430, "endpoint": 0}]' 0xDEB 0 -out/chip-tool otasoftwareupdaterequestor read default-ota-providers 0xDEB 0 +out/chip-tool otasoftwareupdaterequestor write default-otaproviders '[{"providerNodeID": 12648430, "endpoint": 0}]' 0xDEB 0 +out/chip-tool otasoftwareupdaterequestor read default-otaproviders 0xDEB 0 ``` **Write/Read DefaultOTAProviders on second fabric (beta)** ``` -out/chip-tool otasoftwareupdaterequestor write default-ota-providers '[{"providerNodeID": 45242, "endpoint": 0}]' 0xB0B 0 --commissioner-name beta -out/chip-tool otasoftwareupdaterequestor read default-ota-providers 0xB0B 0 --commissioner-name beta +out/chip-tool otasoftwareupdaterequestor write default-otaproviders '[{"providerNodeID": 45242, "endpoint": 0}]' 0xB0B 0 --commissioner-name beta +out/chip-tool otasoftwareupdaterequestor read default-otaproviders 0xB0B 0 --commissioner-name beta ``` **Write ACL for the first OTA Provider application** diff --git a/examples/ota-requestor-app/telink/Readme.md b/examples/ota-requestor-app/telink/Readme.md index 00ed51bbb4182d..b1f2947a4e3a1b 100755 --- a/examples/ota-requestor-app/telink/Readme.md +++ b/examples/ota-requestor-app/telink/Readme.md @@ -154,7 +154,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/pump-app/telink/README.md b/examples/pump-app/telink/README.md index b1e923856b2588..19bdcc291e5fb6 100755 --- a/examples/pump-app/telink/README.md +++ b/examples/pump-app/telink/README.md @@ -169,7 +169,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/pump-controller-app/telink/README.md b/examples/pump-controller-app/telink/README.md index 1f3cd0130f248a..253b676e7392fa 100755 --- a/examples/pump-controller-app/telink/README.md +++ b/examples/pump-controller-app/telink/README.md @@ -170,7 +170,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/temperature-measurement-app/telink/README.md b/examples/temperature-measurement-app/telink/README.md index 68c79aabd1b2f4..4b33ad843c7e84 100644 --- a/examples/temperature-measurement-app/telink/README.md +++ b/examples/temperature-measurement-app/telink/README.md @@ -150,7 +150,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/thermostat/telink/Readme.md b/examples/thermostat/telink/Readme.md index c8c306bda9d73b..9b097c02ad9611 100755 --- a/examples/thermostat/telink/Readme.md +++ b/examples/thermostat/telink/Readme.md @@ -161,7 +161,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: diff --git a/examples/window-app/telink/README.md b/examples/window-app/telink/README.md index a19defc822f1a4..d8e02132cd6bec 100644 --- a/examples/window-app/telink/README.md +++ b/examples/window-app/telink/README.md @@ -232,7 +232,7 @@ Usage of OTA: - Use the chip-tool to announce the ota-provider-app to start the OTA process ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 ``` here: From 650439dd4d9475227c5775da1b5d78cac0e96bed Mon Sep 17 00:00:00 2001 From: Marcin Kajor Date: Tue, 13 Jun 2023 15:34:58 +0200 Subject: [PATCH 15/15] Update the nrfconnect Factory Data docs with extended rd_uid info. Also aligned the related json schema with the docs. Signed-off-by: Marcin Kajor --- .../nrfconnect_factory_data_configuration.md | 44 +++++++++---------- .../nrfconnect/nrfconnect_factory_data.schema | 4 +- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/docs/guides/nrfconnect_factory_data_configuration.md b/docs/guides/nrfconnect_factory_data_configuration.md index 59eb99b50ad101..2abb6e58e17f96 100644 --- a/docs/guides/nrfconnect_factory_data_configuration.md +++ b/docs/guides/nrfconnect_factory_data_configuration.md @@ -89,28 +89,28 @@ about The following table lists the parameters of a factory data set: -| Key name | Full name | Length | Format | Conformance | Description | -| :------------------: | :----------------------------------: | :------------------: | :----------: | :---------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | -| `version` | factory data version | 2 B | uint16 | mandatory | A version of the current factory data set. It cannot be changed by a user and it must be coherent with current version of the Factory Data Provider on device side. | -| `sn` | serial number | <1, 32> B | ASCII string | mandatory | A serial number parameter defines an unique number of manufactured device. The maximum length of the serial number is 32 characters. | -| `vendor_id` | vendor ID | 2 B | uint16 | mandatory | A CSA-assigned ID for the organization responsible for producing the device. | -| `product_id` | product ID | 2 B | uint16 | mandatory | A unique ID assigned by the device vendor to identify the product. It defaults to a CSA-assigned ID that designates a non-production or test product. | -| `vendor_name` | vendor name | <1, 32> B | ASCII string | mandatory | A human-readable vendor name that provides a simple string containing identification of device's vendor for the application and Matter stack purposes. | -| `product_name` | product name | <1, 32> B | ASCII string | mandatory | A human-readable product name that provides a simple string containing identification of the product for the application and the Matter stack purposes. | -| `date` | manufacturing date | <8, 10> B | ISO 8601 | mandatory | A manufacturing date specifies the date that the device was manufactured. The date format used is ISO 8601, for example `YYYY-MM-DD`. | -| `hw_ver` | hardware version | 2 B | uint16 | mandatory | A hardware version number that specifies the version number of the hardware of the device. The value meaning and the versioning scheme is defined by the vendor. | -| `hw_ver_str` | hardware version string | <1, 64> B | uint16 | mandatory | A hardware version string parameter that specifies the version of the hardware of the device as a more user-friendly value than that presented by the hardware version integer value. The value meaning and the versioning scheme is defined by the vendor. | -| `rd_uid` | rotating device ID unique ID | <16, 32> B | byte string | mandatory | The unique ID for rotating device ID, which consists of a randomly-generated 128-bit (or longer) octet string. This parameter should be protected against reading or writing over-the-air after initial introduction into the device, and stay fixed during the lifetime of the device. | -| `dac_cert` | (DAC) Device Attestation Certificate | <1, 602> B | byte string | mandatory | The Device Attestation Certificate (DAC) and the corresponding private key are unique to each Matter device. The DAC is used for the Device Attestation process and to perform commissioning into a fabric. The DAC is a DER-encoded X.509v3-compliant certificate, as defined in RFC 5280. | -| `dac_key` | DAC private key | 68 B | byte string | mandatory | The private key associated with the Device Attestation Certificate (DAC). This key should be encrypted and maximum security should be guaranteed while generating and providing it to factory data. | -| `pai_cert` | Product Attestation Intermediate | <1, 602> B | byte string | mandatory | An intermediate certificate is an X.509 certificate, which has been signed by the root certificate. The last intermediate certificate in a chain is used to sign the leaf (the Matter device) certificate. The PAI is a DER-encoded X.509v3-compliant certificate as defined in RFC 5280. | | -| `spake2_it` | SPAKE2+ iteration counter | 4 B | uint32 | mandatory | A SPAKE2+ iteration counter is the amount of PBKDF2 (a key derivation function) interactions in a cryptographic process used during SPAKE2+ Verifier generation. | -| `spake2_salt` | SPAKE2+ salt | <32, 64> B | byte string | mandatory | The SPAKE2+ salt is a random piece of data, at least 32 byte long. It is used as an additional input to a one-way function that performs the cryptographic operations. A new salt should be randomly generated for each password. | -| `spake2_verifier` | SPAKE2+ verifier | 97 B | byte string | mandatory | The SPAKE2+ verifier generated using SPAKE2+ salt, iteration counter, and passcode. | -| `discriminator` | Discriminator | 2 B | uint16 | mandatory | A 12-bit value matching the field of the same name in the setup code. The discriminator is used during the discovery process. | -| `passcode` | SPAKE passcode | 4 B | uint32 | optional | A pairing passcode is a 27-bit unsigned integer which serves as a proof of possession during the commissioning. Its value must be restricted to the values from `0x0000001` to `0x5F5E0FE` (`00000001` to `99999998` in decimal), excluding the following invalid passcode values: `00000000`, `11111111`, `22222222`, `33333333`, `44444444`, `55555555`, `66666666`, `77777777`, `88888888`, `99999999`, `12345678`, `87654321`. | -| `product_appearance` | Product visible appearance | 2 B | CBOR map | optional | The appearance field is a structure that describes the visible appearance of the product. This field is provided in a CBOR map and consists of two attributes: `finish` (1 B), `primary_color` (1 B). See the [Appearance field description](#appearance-field-description) to learn how to set all attributes. | -| `user` | User data | variable, max 1024 B | CBOR map | optional | The user data is provided in the JSON format. This parameter is optional and depends on the device manufacturer's purpose. It is provided as a CBOR map type from persistent storage and should be parsed in the user application. This data is not used by the Matter stack. To learn how to work with user data, see the [How to set user data](#how-to-set-user-data) section. | +| Key name | Full name | Length | Format | Conformance | Description | +| :------------------: | :----------------------------------: | :------------------: | :----------: | :---------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| `version` | factory data version | 2 B | uint16 | mandatory | A version of the current factory data set. It cannot be changed by a user and it must be coherent with current version of the Factory Data Provider on device side. | +| `sn` | serial number | <1, 32> B | ASCII string | mandatory | A serial number parameter defines an unique number of manufactured device. The maximum length of the serial number is 32 characters. | +| `vendor_id` | vendor ID | 2 B | uint16 | mandatory | A CSA-assigned ID for the organization responsible for producing the device. | +| `product_id` | product ID | 2 B | uint16 | mandatory | A unique ID assigned by the device vendor to identify the product. It defaults to a CSA-assigned ID that designates a non-production or test product. | +| `vendor_name` | vendor name | <1, 32> B | ASCII string | mandatory | A human-readable vendor name that provides a simple string containing identification of device's vendor for the application and Matter stack purposes. | +| `product_name` | product name | <1, 32> B | ASCII string | mandatory | A human-readable product name that provides a simple string containing identification of the product for the application and the Matter stack purposes. | +| `date` | manufacturing date | 10 B | ISO 8601 | mandatory | A manufacturing date specifies the date that the device was manufactured. The date format used is ISO 8601, for example `YYYY-MM-DD`. | +| `hw_ver` | hardware version | 2 B | uint16 | mandatory | A hardware version number that specifies the version number of the hardware of the device. The value meaning and the versioning scheme is defined by the vendor. | +| `hw_ver_str` | hardware version string | <1, 64> B | uint16 | mandatory | A hardware version string parameter that specifies the version of the hardware of the device as a more user-friendly value than that presented by the hardware version integer value. The value meaning and the versioning scheme is defined by the vendor. | +| `rd_uid` | rotating device ID unique ID | <16, 32> B | byte string | mandatory | The unique ID for rotating device ID, which consists of a randomly-generated 128-bit (or longer) octet string. This parameter should be protected against reading or writing over-the-air after initial introduction into the device, and stay fixed during the lifetime of the device. When building an application with the Factory Data support, the `CONFIG_CHIP_FACTORY_DATA_ROTATING_DEVICE_UID_MAX_LEN` must be set with the length of the actual `rd_uid` stored in the Factory Data partition. | +| `dac_cert` | (DAC) Device Attestation Certificate | <1, 602> B | byte string | mandatory | The Device Attestation Certificate (DAC) and the corresponding private key are unique to each Matter device. The DAC is used for the Device Attestation process and to perform commissioning into a fabric. The DAC is a DER-encoded X.509v3-compliant certificate, as defined in RFC 5280. | +| `dac_key` | DAC private key | 68 B | byte string | mandatory | The private key associated with the Device Attestation Certificate (DAC). This key should be encrypted and maximum security should be guaranteed while generating and providing it to factory data. | +| `pai_cert` | Product Attestation Intermediate | <1, 602> B | byte string | mandatory | An intermediate certificate is an X.509 certificate, which has been signed by the root certificate. The last intermediate certificate in a chain is used to sign the leaf (the Matter device) certificate. The PAI is a DER-encoded X.509v3-compliant certificate as defined in RFC 5280. | +| `spake2_it` | SPAKE2+ iteration counter | 4 B | uint32 | mandatory | A SPAKE2+ iteration counter is the amount of PBKDF2 (a key derivation function) interactions in a cryptographic process used during SPAKE2+ Verifier generation. | +| `spake2_salt` | SPAKE2+ salt | <32, 64> B | byte string | mandatory | The SPAKE2+ salt is a random piece of data, at least 32 byte long. It is used as an additional input to a one-way function that performs the cryptographic operations. A new salt should be randomly generated for each password. | +| `spake2_verifier` | SPAKE2+ verifier | 97 B | byte string | mandatory | The SPAKE2+ verifier generated using SPAKE2+ salt, iteration counter, and passcode. | +| `discriminator` | Discriminator | 2 B | uint16 | mandatory | A 12-bit value matching the field of the same name in the setup code. The discriminator is used during the discovery process. | +| `passcode` | SPAKE passcode | 4 B | uint32 | optional | A pairing passcode is a 27-bit unsigned integer which serves as a proof of possession during the commissioning. Its value must be restricted to the values from `0x0000001` to `0x5F5E0FE` (`00000001` to `99999998` in decimal), excluding the following invalid passcode values: `00000000`, `11111111`, `22222222`, `33333333`, `44444444`, `55555555`, `66666666`, `77777777`, `88888888`, `99999999`, `12345678`, `87654321`. | +| `product_appearance` | Product visible appearance | 2 B | CBOR map | optional | The appearance field is a structure that describes the visible appearance of the product. This field is provided in a CBOR map and consists of two attributes: `finish` (1 B), `primary_color` (1 B). See the [Appearance field description](#appearance-field-description) to learn how to set all attributes. | +| `user` | User data | variable, max 1024 B | CBOR map | optional | The user data is provided in the JSON format. This parameter is optional and depends on the device manufacturer's purpose. It is provided as a CBOR map type from persistent storage and should be parsed in the user application. This data is not used by the Matter stack. To learn how to work with user data, see the [How to set user data](#how-to-set-user-data) section. | ### Factory data format diff --git a/scripts/tools/nrfconnect/nrfconnect_factory_data.schema b/scripts/tools/nrfconnect/nrfconnect_factory_data.schema index 0c61d3330826c3..8c2d249bb7bdc0 100644 --- a/scripts/tools/nrfconnect/nrfconnect_factory_data.schema +++ b/scripts/tools/nrfconnect/nrfconnect_factory_data.schema @@ -26,7 +26,7 @@ "description": "Current version of the factory data set", "type": "integer", "minimum": 0, - "maximum": 255 + "maximum": 65535 }, "sn": { "description": "Serial number of device", @@ -82,7 +82,7 @@ "description": "Hardware version - integer", "type": "integer", "minimum": 0, - "maximum": 65536 + "maximum": 65535 }, "hw_ver_str": { "description": "A string representation of hardware version",