diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index aa85ea11d42d0a..aa89d097aae4ca 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -86,3 +86,6 @@ RUN sed -i '/^TIZEN_SDK_DATA_PATH/d' $TIZEN_SDK_ROOT/sdk.info \ && : # last line ENV TIZEN_ROOTFS /tizen_rootfs + +# Fast Model GDB plugins path for debugging support +ENV FAST_MODEL_PLUGINS_PATH /opt/FastModelsPortfolio_11.16/plugins/Linux64_GCC-9.3 diff --git a/.github/workflows/darwin-tests.yaml b/.github/workflows/darwin-tests.yaml index 832011847dd5c4..3ec097cb22b0b0 100644 --- a/.github/workflows/darwin-tests.yaml +++ b/.github/workflows/darwin-tests.yaml @@ -94,7 +94,7 @@ jobs: --target darwin-x64-ota-provider-${BUILD_VARIANT} \ --target darwin-x64-ota-requestor-${BUILD_VARIANT} \ --target darwin-x64-tv-app-${BUILD_VARIANT} \ - --target darwin-x64-bridge-app-${BUILD_VARIANT} \ + --target darwin-x64-bridge-${BUILD_VARIANT} \ build \ --copy-artifacts-to objdir-clone \ " @@ -113,7 +113,7 @@ jobs: --ota-provider-app ./out/darwin-x64-ota-provider-${BUILD_VARIANT}/chip-ota-provider-app \ --ota-requestor-app ./out/darwin-x64-ota-requestor-${BUILD_VARIANT}/chip-ota-requestor-app \ --tv-app ./out/darwin-x64-tv-app-${BUILD_VARIANT}/chip-tv-app \ - --bridge-app ./out/darwin-x64-tv-app-${BUILD_VARIANT}/chip-bridge-app \ + --bridge-app ./out/darwin-x64-bridge-${BUILD_VARIANT}/chip-bridge-app \ " - name: Uploading core files uses: actions/upload-artifact@v2 diff --git a/.github/workflows/docker_img.yaml b/.github/workflows/docker_img.yaml index 73c45ee303a756..98619b886d9303 100644 --- a/.github/workflows/docker_img.yaml +++ b/.github/workflows/docker_img.yaml @@ -54,6 +54,7 @@ jobs: - "-telink" - "-ti" - "-tizen" + - "-openiotsdk" # NOTE: vscode image consumes ~52 GB disk space but GitHub-hosted runners provide ~10 GB free disk space(https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources) #- "-vscode" - "-zap" diff --git a/.github/workflows/examples-bl602.yaml b/.github/workflows/examples-bl602.yaml deleted file mode 100644 index 56166d9e667756..00000000000000 --- a/.github/workflows/examples-bl602.yaml +++ /dev/null @@ -1,79 +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. - -name: Build example - BL602 - -on: - push: - pull_request: - -concurrency: - group: ${{ github.ref }}-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.number) || (github.event_name == 'workflow_dispatch' && github.run_number) || github.sha }} - cancel-in-progress: true - -jobs: - bl602: - name: BL602 - timeout-minutes: 90 - - runs-on: ubuntu-latest - if: github.actor != 'restyled-io[bot]' - - container: - image: connectedhomeip/chip-build:latest - volumes: - - "/tmp/bloat_reports:/tmp/bloat_reports" - steps: - - uses: Wandalen/wretry.action@v1.0.15 - name: Checkout - with: - action: actions/checkout@v3 - with: | - token: ${{ github.token }} - attempt_limit: 3 - attempt_delay: 2000 - - name: Checkout submodules - run: scripts/checkout_submodules.py --shallow --platform bl602 - - - name: Set up environment for size reports - if: ${{ !env.ACT }} - env: - GH_CONTEXT: ${{ toJson(github) }} - run: scripts/tools/memory/gh_sizes_environment.py "${GH_CONTEXT}" - - - name: Build example BL602 Lighting App - timeout-minutes: 30 - run: | - ./scripts/run_in_build_env.sh \ - "./scripts/build/build_examples.py --target bl602-light build" - - - name: Get Lighting size stats - run: | - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py bl602 bl602 lighting-app \ - out/bl602-light/chip-bl602-lighting-example.out /tmp/bloat_reports/ - - - name: Build example BL602 Lighting App with RPCs - timeout-minutes: 30 - run: | - scripts/examples/gn_bl602_example.sh lighting-app ./out/bl602-light-rpc 'import("//with_pw_rpc.gni")' - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py bl602 bl602+rpc lighting-app \ - out/bl602-light-rpc/chip-bl602-lighting-example.out /tmp/bloat_reports/ - - - name: Uploading Size Reports - uses: actions/upload-artifact@v2 - if: ${{ !env.ACT }} - with: - name: Size,BL602-Examples,${{ env.GH_EVENT_PR }},${{ env.GH_EVENT_HASH }},${{ env.GH_EVENT_PARENT }},${{ github.event_name }} - path: | - /tmp/bloat_reports/ diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index 3b53d17b35d726..e34c54882624fc 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -name: Build example - Bouffalolab BL702 +name: Build example - BouffaloLab on: push: @@ -23,6 +23,62 @@ concurrency: cancel-in-progress: true jobs: + bl602: + name: BL602 + timeout-minutes: 90 + + runs-on: ubuntu-latest + if: github.actor != 'restyled-io[bot]' + + container: + image: connectedhomeip/chip-build:latest + volumes: + - "/tmp/bloat_reports:/tmp/bloat_reports" + steps: + - uses: Wandalen/wretry.action@v1.0.15 + name: Checkout + with: + action: actions/checkout@v3 + with: | + token: ${{ github.token }} + attempt_limit: 3 + attempt_delay: 2000 + - name: Checkout submodules + run: scripts/checkout_submodules.py --shallow --platform bl602 + + - name: Set up environment for size reports + if: ${{ !env.ACT }} + env: + GH_CONTEXT: ${{ toJson(github) }} + run: scripts/tools/memory/gh_sizes_environment.py "${GH_CONTEXT}" + + - name: Build example BL602 Lighting App + timeout-minutes: 30 + run: | + ./scripts/run_in_build_env.sh \ + "./scripts/build/build_examples.py --target bouffalolab-bl602-iot-matter-v1-light build" + + - name: Get Lighting size stats + run: | + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py bl602 bl602 lighting-app \ + out/bouffalolab-bl602-iot-matter-v1-light/chip-bl602-lighting-example.out /tmp/bloat_reports/ + + - name: Build example BL602 Lighting App with RPCs + timeout-minutes: 30 + run: | + ./scripts/run_in_build_env.sh \ + "./scripts/build/build_examples.py --target bouffalolab-bl602-iot-matter-v1-light-115200-rpc build" + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py bl602 bl602+rpc lighting-app \ + out/bouffalolab-bl602-iot-matter-v1-light-115200-rpc/chip-bl602-lighting-example.out /tmp/bloat_reports/ + + - name: Uploading Size Reports + uses: actions/upload-artifact@v2 + if: ${{ !env.ACT }} + with: + name: Size,BL602-Examples,${{ env.GH_EVENT_PR }},${{ env.GH_EVENT_HASH }},${{ env.GH_EVENT_PARENT }},${{ github.event_name }} + path: | + /tmp/bloat_reports/ + bl702: name: BL702 timeout-minutes: 90 @@ -52,21 +108,22 @@ jobs: GH_CONTEXT: ${{ toJson(github) }} run: scripts/tools/memory/gh_sizes_environment.py "${GH_CONTEXT}" + - name: Build example BL702 Lighting App timeout-minutes: 30 run: | ./scripts/run_in_build_env.sh \ - "./scripts/build/build_examples.py --target bouffalolab-bl706-iot-dvk-light build" + "./scripts/build/build_examples.py --target bouffalolab-xt-zb6-devkit-light build" .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py bl702 bl702 lighting-app \ - out/bouffalolab-bl706-iot-dvk-light/chip-bl702-lighting-example.out /tmp/bloat_reports/ + out/bouffalolab-xt-zb6-devkit-light/chip-bl702-lighting-example.out /tmp/bloat_reports/ - name: Build example BL702 Lighting App with RPCs timeout-minutes: 30 run: | ./scripts/run_in_build_env.sh \ - "./scripts/build/build_examples.py --target bouffalolab-bl706-iot-dvk-light-rpc build" + "./scripts/build/build_examples.py --target bouffalolab-xt-zb6-devkit-light-115200-rpc build" .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py bl702 bl702+rpc lighting-app \ - out/bouffalolab-bl706-iot-dvk-light-rpc/chip-bl702-lighting-example.out /tmp/bloat_reports/ + out/bouffalolab-xt-zb6-devkit-light-115200-rpc/chip-bl702-lighting-example.out /tmp/bloat_reports/ - name: Uploading Size Reports uses: actions/upload-artifact@v2 diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index b135a227b50159..f58cc0c69ecce7 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -189,7 +189,7 @@ jobs: --target linux-x64-ota-provider-${BUILD_VARIANT} \ --target linux-x64-ota-requestor-${BUILD_VARIANT} \ --target linux-x64-tv-app-${BUILD_VARIANT} \ - --target linux-x64-bridge-app-${BUILD_VARIANT} \ + --target linux-x64-bridge-${BUILD_VARIANT} \ build \ --copy-artifacts-to objdir-clone \ " @@ -207,7 +207,7 @@ jobs: --ota-provider-app ./out/linux-x64-ota-provider-${BUILD_VARIANT}/chip-ota-provider-app \ --ota-requestor-app ./out/linux-x64-ota-requestor-${BUILD_VARIANT}/chip-ota-requestor-app \ --tv-app ./out/linux-x64-tv-app-${BUILD_VARIANT}/chip-tv-app \ - --bridge-app ./out/linux-x64-tv-app-${BUILD_VARIANT}/chip-bridge-app \ + --bridge-app ./out/linux-x64-bridge-${BUILD_VARIANT}/chip-bridge-app \ " - name: Uploading core files uses: actions/upload-artifact@v2 @@ -293,7 +293,7 @@ jobs: --target darwin-x64-ota-provider-${BUILD_VARIANT} \ --target darwin-x64-ota-requestor-${BUILD_VARIANT} \ --target darwin-x64-tv-app-${BUILD_VARIANT} \ - --target darwin-x64-bridge-app-${BUILD_VARIANT} \ + --target darwin-x64-bridge-${BUILD_VARIANT} \ build \ --copy-artifacts-to objdir-clone \ " @@ -312,7 +312,7 @@ jobs: --ota-provider-app ./out/darwin-x64-ota-provider-${BUILD_VARIANT}/chip-ota-provider-app \ --ota-requestor-app ./out/darwin-x64-ota-requestor-${BUILD_VARIANT}/chip-ota-requestor-app \ --tv-app ./out/darwin-x64-tv-app-${BUILD_VARIANT}/chip-tv-app \ - --bridge-app ./out/darwin-x64-tv-app-${BUILD_VARIANT}/chip-bridge-app \ + --bridge-app ./out/darwin-x64-bridge-${BUILD_VARIANT}/chip-bridge-app \ " - name: Uploading core files uses: actions/upload-artifact@v2 diff --git a/.gitmodules b/.gitmodules index 5a60849e011130..5b8d0b466a3b40 100644 --- a/.gitmodules +++ b/.gitmodules @@ -288,3 +288,13 @@ url = https://github.com/matter-mtk/genio-matter-lwip.git branch = main platforms = genio +[submodule "open-iot-sdk"] + path = third_party/open-iot-sdk/sdk + url = https://git.gitlab.arm.com/iot/open-iot-sdk/sdk.git + branch = main + platforms = openiotsdk +[submodule "open-iot-sdk-storage"] + path = third_party/open-iot-sdk/storage + url = https://git.gitlab.arm.com/iot/open-iot-sdk/storage.git + branch = main + platforms = openiotsdk diff --git a/examples/chip-tool/commands/common/CHIPCommand.cpp b/examples/chip-tool/commands/common/CHIPCommand.cpp index 5c56a75c81da52..c5edba6c3dd19f 100644 --- a/examples/chip-tool/commands/common/CHIPCommand.cpp +++ b/examples/chip-tool/commands/common/CHIPCommand.cpp @@ -89,7 +89,7 @@ CHIP_ERROR CHIPCommand::MaybeSetUpStack() StartTracing(); -#if CHIP_DEVICE_LAYER_TARGET_LINUX && CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#if (CHIP_DEVICE_LAYER_TARGET_LINUX || CHIP_DEVICE_LAYER_TARGET_TIZEN) && CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE // By default, Linux device is configured as a BLE peripheral while the controller needs a BLE central. ReturnLogErrorOnFailure(chip::DeviceLayer::Internal::BLEMgrImpl().ConfigureBle(mBleAdapterId.ValueOr(0), true)); #endif diff --git a/examples/lighting-app/bouffalolab/bl602/BUILD.gn b/examples/lighting-app/bouffalolab/bl602/BUILD.gn index a00a5a47503269..f6a9513561d049 100644 --- a/examples/lighting-app/bouffalolab/bl602/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl602/BUILD.gn @@ -43,13 +43,10 @@ declare_args() { # OTA periodic query timeout in seconds ota_periodic_query_timeout = 86400 -} -show_qr_code = false + board = "BL602-IoT-Matter-V1" -# BL-HWC-G1 (No LCD) -if (bl602_board == "BL-HWC-G1" || bl602_board == "IOT_DVK_3S") { - show_qr_code = false + baudrate = 2000000 } bl602_sdk("sdk") { @@ -68,6 +65,7 @@ bl602_sdk("sdk") { "CONFIG_PSM_EASYFLASH_SIZE=16384", "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", "OTA_PERIODIC_QUERY_TIMEOUT=${ota_periodic_query_timeout}", + "CHIP_UART_BAUDRATE=${baudrate}", ] if (chip_enable_pw_rpc) { @@ -107,16 +105,10 @@ bl602_executable("lighting_app") { include_dirs = [ "include" ] - if (bl602_board == "IOT_DVK_3S") { - defines = [ "BOARD_ID=0" ] - } else { + if ("BL602-IoT-Matter-V1" == board || "BL602-IOT-DVK-3S" == board) { defines = [ "BOARD_ID=1" ] - } - - if (show_qr_code) { - sources += [ "${examples_plat_dir}/display/lcd.c" ] - - defines += [ "DISPLAY_ENABLED" ] + } else { + defines = [ "BOARD_ID=0" ] } if (chip_enable_pw_rpc) { diff --git a/examples/lighting-app/bouffalolab/bl602/README.md b/examples/lighting-app/bouffalolab/bl602/README.md index 1c66c73ecc5c83..cbf2b90d62c90c 100644 --- a/examples/lighting-app/bouffalolab/bl602/README.md +++ b/examples/lighting-app/bouffalolab/bl602/README.md @@ -1,10 +1,14 @@ # BL602 This example functions as a wifi light bulb device type, with on/off -capabilities. The steps were verified on BL602-IoT-Matter-V1 board. +capabilities. The steps were verified on following boards: + +- BL602-IoT-Matter-V1, [here](https://www.amazon.com/dp/B0B9ZVGXD8) to + purchase. +- BL602-NIGHT-LIGHT + +## BL602-IoT-Matter-V1 board -BL602-IoT-Matter-V1 board and -[purchase link](https://www.amazon.com/dp/B0B9ZVGXD8): ## Initial setup @@ -12,7 +16,7 @@ BL602-IoT-Matter-V1 board and The steps in this document were validated on Ubuntu 18.04 and 20.04. - Install dependencies as specified in the connectedhomeip repository: - [Building Matter](https://github.com/project-chip/connectedhomeip/blob/interop_testing_te9/docs/guides/BUILDING.md). + [Building Matter](https://github.com/project-chip/connectedhomeip/blob/master/docs/guides/BUILDING.md). - Install other dependencies: ``` @@ -31,20 +35,42 @@ The steps in this document were validated on Ubuntu 18.04 and 20.04. source ./scripts/activate.sh ``` -## Build the image and flash the board + > Note, Bouffalolab flash tool, `bflb-iot-tool`, imports under this + > environment. If not, please try `scripts/bootstrap.sh` for matter + > environment update. + +## Build CHIP BL602 Lighting App example - Build the [lighting-app](https://github.com/project-chip/connectedhomeip/tree/master/examples/lighting-app/bouffalolab/bl602) ``` - ./scripts/build/build_examples.py --target bl602-light build + ./scripts/build/build_examples.py --target bouffalolab-bl602-iot-matter-v1-light build + ./scripts/build/build_examples.py --target bouffalolab-bl602-night-light-light build ``` -- Build the lighting-app with Pigweed RPC: +- Build target name with `-115200` appended for UART baudrate 115200 command + enabled as following commands. + ```shell + ./scripts/build/build_examples.py --target bouffalolab-bl602-iot-matter-v1-light-115200 build ``` - ./scripts/examples/gn_bl602_example.sh lighting-app ./out/bl602-light 'import("//with_pw_rpc.gni")' - ``` + + > UART baudrate is 2000000 by default. + +- Build target name with `-rpc` appended for rpc enabled as following + commands. + `shell ./scripts/build/build_examples.py --target bouffalolab-xt-zb6-devkit-light-rpc build` + > For multiple build options, such as UART baudrate 115200 + rpc, please try + > build command as + > `./scripts/build/build_examples.py --target bouffalolab-xt-zb6-devkit-light-rpc-115200 build` + +## Download image + +After building gets done, a python `chip-bl602-lighting-example.flash.py` will +generated under build output folder. Such as +chip-bl602-lighting-example.flash.py for lighting-app example. Please check +`help` option of script for more detail. - Connect the board to your flashing station (MacOS, Ubuntu, Windows). @@ -54,25 +80,14 @@ The steps in this document were validated on Ubuntu 18.04 and 20.04. - Press the RESET button and release it. - Release the BOOT button. -- The device should present itself as a USB serial device on your computer. - You may look it up in /dev/ttyACM0 +- Enter build out folder, download image as following execution under build + output folder: + ```shell + ./chip-bl602-lighting-example.flash.py --port /dev/tty.usbserial-3 ``` - ls -la /dev/tty* - ``` - - If the device is at /dev/ttyACM0, flash the board using the following - commands: - - ``` - cd third_party/bouffalolab/repo/tools/flash_tool - ./bflb_iot_tool-ubuntu --chipname=BL602 --baudrate=115200 --port=/dev/ttyACM0 --pt=chips/bl602/partition/partition_cfg_4M.toml --dts=chips/bl602/device_tree/bl_factory_params_IoTKitA_40M.dts --firmware=../../../../../out/bl602-light/chip-bl602-lighting-example.bin - ``` - - ``` - If you want to erase previous network information in flash, you can add --erase parameters to the bflb_iot_tool-ubuntu18 command. For Windows and MacOS, replace bflb_iot_tool-ubuntu18 with bflb_iot_tool.exe and bflb_iot_tool-macos, respectively. - ``` + > Note, where `/dev/tty.usbserial-3` is UART port of device. ## Validate the example @@ -80,7 +95,7 @@ The steps in this document were validated on Ubuntu 18.04 and 20.04. `/dev/ttyACM0`: ``` -picocom -b 115200 /dev/ttyACM0 +picocom -b 2000000 /dev/ttyACM0 ``` 2.To reset the board, press the RESET button, and you will see the log in the diff --git a/examples/lighting-app/bouffalolab/bl602/include/CHIPProjectConfig.h b/examples/lighting-app/bouffalolab/bl602/include/CHIPProjectConfig.h index d36ef3e7326b4d..db99b4c1a72ef7 100644 --- a/examples/lighting-app/bouffalolab/bl602/include/CHIPProjectConfig.h +++ b/examples/lighting-app/bouffalolab/bl602/include/CHIPProjectConfig.h @@ -68,7 +68,7 @@ * TODO: 3R */ //#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID 0xF001 -#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID 0x8001 +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID 0x8005 /** * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION diff --git a/examples/lighting-app/bouffalolab/bl702/BUILD.gn b/examples/lighting-app/bouffalolab/bl702/BUILD.gn index 1101a90630c0d4..8243bb9924a97f 100644 --- a/examples/lighting-app/bouffalolab/bl702/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702/BUILD.gn @@ -43,7 +43,7 @@ declare_args() { # Monitor & log memory usage at runtime. enable_heap_monitoring = false - board = "BL706-IoT-DVK" + board = "XT-ZB6-DevKit" module_type = "BL706C-22" enable_psram = true baudrate = 2000000 @@ -95,13 +95,16 @@ bl702_executable("lighting_app") { defines += [ "CFG_USE_PSRAM=1" ] } - if ("BL706-NIGHT-LIGHT" == board) { - defines += [ "APP_BOARD_LED_STATUS=0" ] + if ("BL706C-22" == module_type) { + defines += [ "BOARD_BTN_BOOT_PIN" ] + } + + if ("XT-ZB6-DevKit" == board) { + defines += [ "XT_ZB6_DevKit" ] + } else if ("BL706-NIGHT-LIGHT" == board) { defines += [ "BL706_NIGHT_LIGHT" ] - defines += [ "APP_BOARD_BTN=0" ] } else if ("BL702-IoT-DVK" == board || "BL706-IoT-DVK" == board) { - defines += [ "APP_BOARD_LED_STATUS=1" ] - defines += [ "APP_BOARD_BTN=1" ] + defines += [ "BL706_IOT_DVK" ] } sources = [ diff --git a/examples/lighting-app/bouffalolab/bl702/README.md b/examples/lighting-app/bouffalolab/bl702/README.md index f02b1b84758f86..09f709643268bc 100644 --- a/examples/lighting-app/bouffalolab/bl702/README.md +++ b/examples/lighting-app/bouffalolab/bl702/README.md @@ -7,12 +7,11 @@ This example is powered by BL706 and functions as a Thread light bulb device type, with on/off, level and color capabilities. The steps were verified with following boards: - - BL706-IoT-DVK - - BL706-NIGHT-LIGHT +- `XT-ZB6-DevKit` +- `BL706-IoT-DVK` +- `BL706-NIGHT-LIGHT` -## Build - -### Prerequisite +## Prerequisite - Clone connectedhomeip github repo and update all submodule; - Install all tools (likely already present for CHIP developers). @@ -24,143 +23,106 @@ following boards: ```shell source scripts/bootstrap.sh ``` - > Note, `scripts/bootstrap.sh` only installs `bflb-iot-tool` under - > connectedhomeip build context. + > Note, `bflb-iot-tool` is only installed under connectedhomeip build + > context by matter environment setup `scripts/bootstrap.sh`. - Others, please execute the following script before any build commands - executed; and `bflb-iot-tool` will import under this environment. + executed; and `bflb-iot-tool` imports under this environment. ```shell source scripts/activate.sh ``` ## Build CHIP BL702 Lighting App example -- Build with script `gn_bouffalolab_example.sh` under root folder of - connectedhomeip repo +- Build for `XT-ZB6-DevKit` and BL706-NIGHT-LIGHT as following commands. - - Command format: + ```shell + ./scripts/build/build_examples.py --target bouffalolab-xt-zb6-devkit-light build + ./scripts/build/build_examples.py --target bouffalolab-bl706-night-light-light build + ``` - ```shell - ./scripts/examples/gn_bouffalolab_example.sh [] - ``` +- Build target name with `-115200` appended for UART baudrate 115200 command + enabled as following commands. - - Build lighting-app for board BL706-IoT-DVK. + ```shell + ./scripts/build/build_examples.py --target bouffalolab-xt-zb6-devkit-light-rpc build + ``` - ```shell - ./scripts/examples/gn_bouffalolab_example.sh lighting-app out/debug BL706-IoT-DVK - ``` + > UART baudrate is 2000000 by default. - - Build lighting-app for board BL706-NIGHT-LIGHT +- Build target name with `-shell` appended for UART shell command enabled as + following commands. - ```shell - ./scripts/examples/gn_bouffalolab_example.sh lighting-app out/debug BL706-NIGHT-LIGHT - ``` + ```shell + ./scripts/build/build_examples.py --target bouffalolab-xt-zb6-devkit-light-shell build + ``` - - With UART shell command enabled: +- Build target name with `-rpc` appended for rpc enabled as following + commands. + `shell ./scripts/build/build_examples.py --target bouffalolab-xt-zb6-devkit-light-rpc build` + > For multiple build options, such as UART baudrate 115200 + rpc, please try + > build command as + > `./scripts/build/build_examples.py --target bouffalolab-xt-zb6-devkit-light-rpc-115200 build` - ```shell - ./scripts/examples/gn_bouffalolab_example.sh lighting-app out/debug BL706-IoT-DVK chip_build_libshell=true - ``` +## Download image - - With pigweed RPC enabled: - ```shell - ./scripts/examples/gn_bouffalolab_example.sh lighting-app out/debug BL706-IoT-DVK 'import("//with_pw_rpc.gni")' - ``` - > Note, UART shell command and pigweed RPC can not build together. +- Using script `chip-bl702-lighting-example.flash.py`. -- Build with `build_examples.py` + After building gets done, a python `chip-bl702-lighting-example.flash.py` + will generated under build output folder. Such as + chip-bl702-lighting-example.flash.py for lighting-app example. Please check + `--help` option of script for more detail. - - Build for BL706-IoT-DVK and BL706-NIGHT-LIGHT as following commands. + - Hold BOOT pin and reset chip, let it be in download mode. + - Enter build out folder, download image as following execution under + build output folder: ```shell - ./scripts/build/build_examples.py --target bouffalolab-BL706-IoT-DVK-BL706C-22-light build - ./scripts/build/build_examples.py --target bouffalolab-BL706-NIGHT-LIGHT-light build + ./chip-bl702-lighting-example.flash.py --port /dev/tty.usbserial-3 ``` - - Build with pigweed RPC enabled as following commands. + > Note, where `/dev/tty.usbserial-3` is UART port of device. + + - Build Bouffalolab OTA image as following execution under build output + folder: ```shell - ./scripts/build/build_examples.py --target bouffalolab-BL706-IoT-DVK-BL706C-22-light-rpc build + ./chip-bl702-lighting-example.flash.py --build ``` - -- Build options - - - Build options list There are some build options for function and debug - purpose as below. - - `chip_build_libshell`, whether to enable shell command line. It is - set to false by default. - - `baudrate`, UART baudrate for log output or shell command line. - - `enable_psram`, whether to enable `PSRAM`. It is set to true by - default. - - How to use Before using these build options, please check whether they - are available to configure in BUILD.gn file under example application - folder. - - build with `build_examples.py` Modify value of build options in - BUILD.gn file under example application folder. - - build with gn_bouffalolab_example.sh Input build options, such as - ``` - ./scripts/examples/gn_bouffalolab_example.sh lighting-app out/debug BL706-IoT-DVK chip_build_libshell=true - ``` - -- Download image - - - Using script `chip-bl702-lighting-example.flash.py`. - - After building gets done, a python - `chip-bl702-lighting-example.flash.py` will generated under build output - folder. Such as chip-bl702-lighting-example.flash.py for lighting-app - example. Please check `help` option of script for more detail. - - - Hold BOOT pin and reset chip, let it be in download mode. - - Download image as following execution under build output folder: - - ```shell - ./chip-bl702-lighting-example.flash.py --port /dev/tty.usbserial-3 - ``` - - > Note, where `/dev/tty.usbserial-3` is UART port of device. - - - Build Bouffalolab OTA image as following execution under build - output folder: - ```shell - ./chip-bl702-lighting-example.flash.py --build - ``` - After script executed, a folder `ota_images` and image - `FW_OTA.bin.xz.hash` will generated. `FW_OTA.bin.xz.hash` is - compressed with hash verification with - `chip-bl702-lighting-example.bin`. - - > Note, `chip-bl702-lighting-example.flash.py` uses Python module - > `bflb-iot-tool` to flash device. Please make sure current terminal is - > under matter build environment, otherwise, Python module - > `bflb-iot-tool` should be installed with default Python. - - - Using `Bouffalo Lab` flash tool`BLDevCube` - - Hold BOOT pin and reset chip, let it be in download mode. - - Select `DTS` file - `/examples/platform/bouffalolab/bl702/flash_config/bl_factory_params_IoTKitA_32M.dts`; - - Select Partition Table - `/examples/platform/bouffalolab/bl702/flash_config/partition_cfg_2M.toml`; - - Select Firmware Bin chip-bl702-lighting-example.bin; - - Select Chip Erase if need; - - Choose Target COM port. - - Then click Create & Download. - > Where `connectedhomeip_repo_path` is the root path of repo - > connectedhomeip. - -- Firmware Behavior - - - IOT Dev board Status LED: TX0
Lighting LED: RX1
Factory Reset: - Short `IO11` to `GND` over 3 seconds
- - - Night Light Unprovisioned state: light shows yellow. Provisioned state: - light show white. Factory Reset: Power cycle 3 times before light is on; - at 3rd time, light shows green and does factory reset after 3 seconds - later. And factory reset can be cancelled during 3 seconds wait time. - -- UART baudrate for log and shell command - - By default, UART baudrate is 2000000 - - To change UART baudrate, please run script `gn_bouffalolab_example.sh` - with `baudrate=[uart baudrate]` followed, such as - `./scripts/examples/gn_bouffalolab_example.sh lighting-app out/debug BL706-NIGHT-LIGHT module_type="BL702" baudrate=115200` + After script executed, a folder `ota_images` and an image + `FW_OTA.bin.xz.hash` will be generated. `FW_OTA.bin.xz.hash` is + compressed with hash verification for `chip-bl702-lighting-example.bin`. + + > Note, `chip-bl702-lighting-example.flash.py` uses Python module + > `bflb-iot-tool` to flash device. Please make sure current terminal is + > under matter build environment; otherwise, Python module `bflb-iot-tool` + > should be installed under default Python environment using command + > `pip install bflb-iot-tool`. + +- Using `Bouffalo Lab` flash tool`BLDevCube` + - Hold BOOT pin and reset chip, let it be in download mode. + - Select `DTS` file; + - Select Partition Table + `/examples/platform/bouffalolab/bl702/flash_config/partition_cfg_2M.toml`; + - Select Firmware Bin chip-bl702-lighting-example.bin; + - Select Chip Erase if need; + - Choose Target COM port. + - Then click Create & Download. + > Where `connectedhomeip_repo_path` is the root path of repo + > connectedhomeip. + +## Firmware Behavior + +- `XT-ZB6-DevKit` board + + - Lighting LED, controlled by on/off command, level command and identify + command. + - Factory Reset: Press down boot pin over 4 seconds, and release boot pin + +- `Night Light` board + - Unprovisioned state: light shows yellow. + - Provisioned state: light show white. + - Factory Reset: Power cycle 3 times before light is on; at 3rd time, + light shows green and does factory reset after 3 seconds later. And + factory reset can be cancelled during 3 seconds wait time. ## Test with chip-tool @@ -204,7 +166,7 @@ which `` is how many seconds to execute identify command. - Under connectedhomeip repo path ```shell - $ ./src/app/ota_image_tool.py create -v 0xFFF1 -p 0x8005 -vn 1 -vs "1.0" -da sha256 lighting-app.ota + $ ./src/app/ota_image_tool.py create -v 0xFFF1 -p 0x8005 -vn 10 -vs "1.0" -da sha256 lighting-app.ota ``` diff --git a/examples/lighting-app/bouffalolab/bl702/include/AppTask.h b/examples/lighting-app/bouffalolab/bl702/include/AppTask.h index b56f746f04763e..b9be603d96e7b6 100644 --- a/examples/lighting-app/bouffalolab/bl702/include/AppTask.h +++ b/examples/lighting-app/bouffalolab/bl702/include/AppTask.h @@ -48,18 +48,20 @@ class AppTask { APP_EVENT_NONE = 0x00000000, - APP_EVENT_STARTED = 0x00000001, APP_EVENT_BTN_FACTORY_RESET_CANCEL = 0x00000002, APP_EVENT_BTN_FACTORY_RESET_IND = 0x00000004, - APP_EVENT_BTN_FACTORY_RESET_PW_PRC = 0x00000008, + APP_EVENT_BTN_FACTORY_RESET_PRESS = 0x00000008, - APP_EVENT_INIT_ALL_MASK = APP_EVENT_STARTED | APP_EVENT_BTN_FACTORY_RESET_CANCEL | APP_EVENT_BTN_FACTORY_RESET_IND, - APP_EVENT_TIMER = 0x00000010, + APP_EVENT_BTN_ALL_MASK = + APP_EVENT_BTN_FACTORY_RESET_CANCEL | APP_EVENT_BTN_FACTORY_RESET_IND | APP_EVENT_BTN_FACTORY_RESET_PRESS, + APP_EVENT_TIMER = 0x00000010, + APP_EVENT_BTN_SHORT = 0x00000020, - APP_EVENT_SYS_BLE_ADV = 0x00000100, - APP_EVENT_SYS_BLE_CONN = 0x00000200, - APP_EVENT_SYS_PROVISIONED = 0x00000400, - APP_EVENT_FACTORY_RESET = 0x00001000, + APP_EVENT_SYS_BLE_ADV = 0x00000100, + APP_EVENT_SYS_BLE_CONN = 0x00000200, + APP_EVENT_SYS_PROVISIONED = 0x00000400, + APP_EVENT_SYS_LIGHT_TOGGLE = 0x00000800, + APP_EVENT_FACTORY_RESET = 0x00001000, APP_EVENT_SYS_ALL_MASK = APP_EVENT_SYS_BLE_ADV | APP_EVENT_SYS_BLE_CONN | APP_EVENT_SYS_PROVISIONED | APP_EVENT_FACTORY_RESET, @@ -67,18 +69,16 @@ class AppTask APP_EVENT_LIGHTING_ONOFF = 0x00010000, APP_EVENT_LIGHTING_LEVEL = 0x00020000, APP_EVENT_LIGHTING_COLOR = 0x00040000, - APP_EVENT_LIGHTING_CHECK = 0x00080000, APP_EVENT_LIGHTING_GO_THROUGH = 0x00100000, - APP_EVENT_LIGHTING_MASK = - APP_EVENT_LIGHTING_ONOFF | APP_EVENT_LIGHTING_LEVEL | APP_EVENT_LIGHTING_COLOR | APP_EVENT_LIGHTING_CHECK, + APP_EVENT_LIGHTING_MASK = APP_EVENT_LIGHTING_ONOFF | APP_EVENT_LIGHTING_LEVEL | APP_EVENT_LIGHTING_COLOR, APP_EVENT_IDENTIFY_START = 0x01000000, APP_EVENT_IDENTIFY_IDENTIFY = 0x02000000, APP_EVENT_IDENTIFY_STOP = 0x04000000, APP_EVENT_IDENTIFY_MASK = APP_EVENT_IDENTIFY_START | APP_EVENT_IDENTIFY_IDENTIFY | APP_EVENT_IDENTIFY_STOP, - APP_EVENT_ALL_MASK = - APP_EVENT_LIGHTING_MASK | APP_EVENT_INIT_ALL_MASK | APP_EVENT_SYS_ALL_MASK | APP_EVENT_TIMER | APP_EVENT_IDENTIFY_MASK, + APP_EVENT_ALL_MASK = APP_EVENT_LIGHTING_MASK | APP_EVENT_BTN_ALL_MASK | APP_EVENT_SYS_ALL_MASK | APP_EVENT_TIMER | + APP_EVENT_BTN_SHORT | APP_EVENT_IDENTIFY_MASK, }; void SetEndpointId(EndpointId endpointId) @@ -112,15 +112,12 @@ class AppTask static void LightingUpdate(app_event_t event = APP_EVENT_NONE); -#if APP_BOARD_LED_STATUS || APP_BOARD_BTN static bool StartTimer(void); static void CancelTimer(void); - static void TimerEventHandler(void); - static void TimerDutyCycle(app_event_t event); + static void TimerEventHandler(app_event_t event); static void TimerCallback(TimerHandle_t xTimer); -#endif -#if APP_BOARD_BTN +#ifdef LED_BTN_RESET static void ButtonInit(void); static bool ButtonPressed(void); static void ButtonEventHandler(void * arg); @@ -136,9 +133,9 @@ class AppTask TaskHandle_t sAppTaskHandle; QueueHandle_t sAppEventQueue; TimerHandle_t sTimer; - uint32_t mBlinkOnTimeMS; - uint32_t mBlinkOffTimeMS; - uint64_t buttonPressedTimeout; + uint32_t mTimerIntvl; + uint64_t mButtonPressedTime; + bool mIsFactoryResetIndicat; static StackType_t appStack[APP_TASK_STACK_SIZE / sizeof(StackType_t)]; static StaticTask_t appTaskStruct; diff --git a/examples/lighting-app/bouffalolab/bl702/include/board.h b/examples/lighting-app/bouffalolab/bl702/include/board.h index e0e47c6a194f4f..2185ce86448d65 100644 --- a/examples/lighting-app/bouffalolab/bl702/include/board.h +++ b/examples/lighting-app/bouffalolab/bl702/include/board.h @@ -57,22 +57,31 @@ #define LED_G_PIN_PORT 1 #define LED_G_PIN 16 -#define LED1_PIN LED_B_PIN_PORT - #define MAX_PWM_CHANNEL 3 -#else +#elif defined(XT_ZB6_DevKit) + +#define LED_B_PIN_PORT 3 +#define LED_B_PIN 18 -#define LED1_PIN 22 +#define LED_R_PIN_PORT 4 +#define LED_R_PIN 19 -#define LED_B_PIN_PORT 1 -#define LED_B_PIN 31 +#define LED_G_PIN_PORT 0 +#define LED_G_PIN 20 + +#define MAX_PWM_CHANNEL 1 + +#else + +#define LED_B_PIN_PORT 2 +#define LED_B_PIN 22 #define MAX_PWM_CHANNEL 1 #endif -#if APP_BOARD_BTN -#define LED_BTN_RESET 11 +#if defined(BOARD_BTN_BOOT_PIN) +#define LED_BTN_RESET 31 #endif #define SPI_WIFI_MISO_PIN 4 diff --git a/examples/lighting-app/bouffalolab/bl702/src/AppTask.cpp b/examples/lighting-app/bouffalolab/bl702/src/AppTask.cpp index 641562bd520cf5..bc8944a10f14e1 100644 --- a/examples/lighting-app/bouffalolab/bl702/src/AppTask.cpp +++ b/examples/lighting-app/bouffalolab/bl702/src/AppTask.cpp @@ -17,7 +17,6 @@ * limitations under the License. */ -#include "AppTask.h" #include "AppConfig.h" #include "LEDWidget.h" #include @@ -49,7 +48,6 @@ #endif #if CHIP_ENABLE_OPENTHREAD -#include #include #include #include @@ -77,8 +75,12 @@ extern "C" { #include } -#define FACTORY_RESET_TRIGGER_TIMEOUT 3000 -#define FACTORY_RESET_CANCEL_WINDOW_TIMEOUT 3000 +#include "AppTask.h" + +#define APP_BUTTON_PRESS_JITTER 50 +#define APP_BUTTON_PRESS_SHORT 1000 +#define APP_BUTTON_PRESS_LONG 4000 + #define APP_TASK_PRIORITY 2 #define EXT_DISCOVERY_TIMEOUT_SECS 20 #define APP_LIGHT_ENDPOINT_ID 1 @@ -86,10 +88,6 @@ extern "C" { #define APP_REBOOT_RESET_COUNT_KEY "app_reset_cnt" namespace { -#if APP_BOARD_LED_STATUS -LEDWidget sStatusLED; -#endif - #ifdef BL706_NIGHT_LIGHT ColorLEDWidget sLightLED; #else @@ -100,11 +98,7 @@ Identify sIdentify = { APP_LIGHT_ENDPOINT_ID, AppTask::IdentifyStartHandler, AppTask::IdentifyStopHandler, -#if APP_BOARD_LED_STATUS - EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, -#else EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LIGHT, -#endif }; } // namespace @@ -148,9 +142,7 @@ void PlatformManagerImpl::PlatformInit(void) chip::DeviceLayer::ConnectivityMgr().SetBLEDeviceName("BL702_LIGHT"); - ot_alarmInit(); - ot_radioInit(); -#if CONFIG_ENABLE_CHIP_SHELL +#if CHIP_ENABLE_OPENTHREAD && CONFIG_ENABLE_CHIP_SHELL cmd_otcli_init(); #endif ChipLogProgress(NotSpecified, "Initializing OpenThread stack"); @@ -214,9 +206,7 @@ void PlatformManagerImpl::PlatformInit(void) chip::rpc::Init(); #endif -#if APP_BOARD_LED_STATUS || APP_BOARD_BTN GetAppTask().PostEvent(AppTask::APP_EVENT_TIMER); -#endif vTaskResume(GetAppTask().sAppTaskHandle); } @@ -272,16 +262,11 @@ void AppTask::PostEvent(app_event_t event) void AppTask::AppTaskMain(void * pvParameter) { app_event_t appEvent; - static uint32_t taskDelay = portMAX_DELAY; - bool isStateReady = false; - -#if APP_BOARD_LED_STATUS - sStatusLED.Init(); -#endif + bool isStateReady = false; sLightLED.Init(); -#if APP_BOARD_BTN +#ifdef LED_BTN_RESET ButtonInit(); #else uint32_t resetCnt = 0; @@ -290,13 +275,14 @@ void AppTask::AppTaskMain(void * pvParameter) ef_get_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt), &saved_value_len); if (resetCnt >= APP_REBOOT_RESET_COUNT) { - GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); + GetAppTask().PostEvent(APP_EVENT_BTN_FACTORY_RESET_IND); } else { resetCnt++; ef_set_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt)); } + GetAppTask().mButtonPressedTime = chip::System::SystemClock().GetMonotonicMilliseconds64().count(); #endif ChipLogProgress(NotSpecified, "Starting Platform Manager Event Loop"); @@ -308,49 +294,49 @@ void AppTask::AppTaskMain(void * pvParameter) } vTaskSuspend(NULL); -#if APP_BOARD_LED_STATUS || APP_BOARD_BTN GetAppTask().sTimer = xTimerCreate("lightTmr", pdMS_TO_TICKS(1000), false, NULL, AppTask::TimerCallback); if (GetAppTask().sTimer == NULL) { ChipLogError(NotSpecified, "Failed to create timer task"); appError(APP_ERROR_EVENT_QUEUE_FAILED); } -#endif ChipLogProgress(NotSpecified, "App Task started, with heap %d left\r\n", xPortGetFreeHeapSize()); + StartTimer(); + while (true) { appEvent = APP_EVENT_NONE; - BaseType_t eventReceived = xTaskNotifyWait(0, APP_EVENT_ALL_MASK, (uint32_t *) &appEvent, taskDelay); + BaseType_t eventReceived = xTaskNotifyWait(0, APP_EVENT_ALL_MASK, (uint32_t *) &appEvent, portMAX_DELAY); if (eventReceived) { -#if APP_BOARD_LED_STATUS || APP_BOARD_BTN - TimerDutyCycle(appEvent); -#endif - PlatformMgr().LockChipStack(); if (APP_EVENT_SYS_BLE_ADV & appEvent) { LightingSetStatus(APP_EVENT_SYS_BLE_ADV); + LightingUpdate(APP_EVENT_LIGHTING_GO_THROUGH); + isStateReady = false; } if (APP_EVENT_SYS_PROVISIONED & appEvent) { LightingSetStatus(APP_EVENT_SYS_PROVISIONED); + LightingUpdate(APP_EVENT_LIGHTING_GO_THROUGH); + isStateReady = true; } + if (APP_EVENT_BTN_SHORT & appEvent) + { + LightingSetStatus(APP_EVENT_SYS_LIGHT_TOGGLE); + LightingUpdate(APP_EVENT_LIGHTING_GO_THROUGH); + } + if ((APP_EVENT_LIGHTING_MASK & appEvent) && isStateReady) { -#if APP_BOARD_LED_STATUS || APP_BOARD_BTN - if (APP_EVENT_LIGHTING_CHECK & appEvent) - { - TimerDutyCycle(APP_EVENT_SYS_PROVISIONED); - } -#endif LightingUpdate((app_event_t)(APP_EVENT_LIGHTING_MASK & appEvent)); } @@ -361,27 +347,12 @@ void AppTask::AppTaskMain(void * pvParameter) if (APP_EVENT_FACTORY_RESET & appEvent) { -#if !APP_BOARD_LED_STATUS - LightingSetStatus(APP_EVENT_FACTORY_RESET); - LightingUpdate(APP_EVENT_LIGHTING_GO_THROUGH); - vTaskDelay(FACTORY_RESET_TRIGGER_TIMEOUT); -#endif DeviceLayer::ConfigurationMgr().InitiateFactoryReset(); } - if (APP_EVENT_BTN_FACTORY_RESET_PW_PRC & appEvent) - { - vTaskDelay(FACTORY_RESET_TRIGGER_TIMEOUT); - DeviceLayer::ConfigurationMgr().InitiateFactoryReset(); - } + TimerEventHandler(appEvent); PlatformMgr().UnlockChipStack(); -#if APP_BOARD_LED_STATUS || APP_BOARD_BTN - if (APP_EVENT_TIMER & appEvent) - { - TimerEventHandler(); - } -#endif } } } @@ -421,27 +392,10 @@ void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t arg) void AppTask::LightingUpdate(app_event_t event) { - static uint32_t updateOpCnt = 0; uint8_t v, onoff, hue, sat; EmberAfAttributeType dataType; EndpointId endpoint = GetAppTask().GetEndpointId(); - if (APP_EVENT_LIGHTING_CHECK & event) - { - if (updateOpCnt++ < 2) - { - GetAppTask().PostEvent(APP_EVENT_LIGHTING_CHECK); - return; - } - updateOpCnt = 0; - } - else if (APP_EVENT_LIGHTING_MASK & event) - { - updateOpCnt = 0; - GetAppTask().PostEvent(APP_EVENT_LIGHTING_CHECK); - return; - } - do { if (EMBER_ZCL_STATUS_SUCCESS != @@ -501,42 +455,17 @@ void AppTask::LightingSetOnoff(uint8_t bonoff) void AppTask::LightingSetStatus(app_event_t status) { - uint8_t level, hue, sat; + uint8_t onoff = 1, level, hue, sat; EndpointId endpoint = GetAppTask().GetEndpointId(); static bool isProvisioned = false; -#if !APP_BOARD_BTN - uint32_t resetCnt = 0; - size_t saved_value_len = 0; - - if ((APP_EVENT_SYS_BLE_ADV | APP_EVENT_SYS_PROVISIONED) & status) + if (APP_EVENT_SYS_LIGHT_TOGGLE == status) { - - if (0 == GetAppTask().buttonPressedTimeout) - { - - GetAppTask().buttonPressedTimeout = chip::System::SystemClock().GetMonotonicMilliseconds64().count(); - ef_get_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt), &saved_value_len); - if (resetCnt >= APP_REBOOT_RESET_COUNT) - { - GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); - } - else - { - resetCnt = 0; - ef_set_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt)); - } - } + emberAfReadAttribute(endpoint, ZCL_ON_OFF_CLUSTER_ID, ZCL_ON_OFF_ATTRIBUTE_ID, (uint8_t *) &onoff, + ZCL_BOOLEAN_ATTRIBUTE_TYPE); + onoff = 1 - onoff; } - else if (APP_EVENT_FACTORY_RESET & status) - { - /** reset resetCnt to zero before factory reset, just in case to cancel factory reset */ - resetCnt = 0; - ef_set_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt)); - } -#endif - - if (APP_EVENT_SYS_BLE_ADV == status) + else if (APP_EVENT_SYS_BLE_ADV == status) { hue = 35; emberAfWriteAttribute(endpoint, ZCL_COLOR_CONTROL_CLUSTER_ID, ZCL_COLOR_CONTROL_CURRENT_HUE_ATTRIBUTE_ID, (uint8_t *) &hue, @@ -544,6 +473,10 @@ void AppTask::LightingSetStatus(app_event_t status) sat = 254; emberAfWriteAttribute(endpoint, ZCL_COLOR_CONTROL_CLUSTER_ID, ZCL_COLOR_CONTROL_CURRENT_SATURATION_ATTRIBUTE_ID, (uint8_t *) &sat, ZCL_INT8U_ATTRIBUTE_TYPE); + level = 254; + emberAfWriteAttribute(endpoint, ZCL_LEVEL_CONTROL_CLUSTER_ID, ZCL_CURRENT_LEVEL_ATTRIBUTE_ID, (uint8_t *) &level, + ZCL_INT8U_ATTRIBUTE_TYPE); + isProvisioned = false; } else if (APP_EVENT_SYS_PROVISIONED == status) @@ -556,55 +489,27 @@ void AppTask::LightingSetStatus(app_event_t status) sat = 0; emberAfWriteAttribute(endpoint, ZCL_COLOR_CONTROL_CLUSTER_ID, ZCL_COLOR_CONTROL_CURRENT_SATURATION_ATTRIBUTE_ID, (uint8_t *) &sat, ZCL_INT8U_ATTRIBUTE_TYPE); - } - else if (APP_EVENT_FACTORY_RESET == status) - { - hue = 84; - emberAfWriteAttribute(endpoint, ZCL_COLOR_CONTROL_CLUSTER_ID, ZCL_COLOR_CONTROL_CURRENT_HUE_ATTRIBUTE_ID, (uint8_t *) &hue, + level = 254; + emberAfWriteAttribute(endpoint, ZCL_LEVEL_CONTROL_CLUSTER_ID, ZCL_CURRENT_LEVEL_ATTRIBUTE_ID, (uint8_t *) &level, ZCL_INT8U_ATTRIBUTE_TYPE); - sat = 254; - emberAfWriteAttribute(endpoint, ZCL_COLOR_CONTROL_CLUSTER_ID, ZCL_COLOR_CONTROL_CURRENT_SATURATION_ATTRIBUTE_ID, - (uint8_t *) &sat, ZCL_INT8U_ATTRIBUTE_TYPE); } - level = 254; - emberAfWriteAttribute(endpoint, ZCL_LEVEL_CONTROL_CLUSTER_ID, ZCL_CURRENT_LEVEL_ATTRIBUTE_ID, (uint8_t *) &level, - ZCL_INT8U_ATTRIBUTE_TYPE); - - level = 1; - emberAfWriteAttribute(endpoint, ZCL_ON_OFF_CLUSTER_ID, ZCL_ON_OFF_ATTRIBUTE_ID, (uint8_t *) &level, ZCL_BOOLEAN_ATTRIBUTE_TYPE); + emberAfWriteAttribute(endpoint, ZCL_ON_OFF_CLUSTER_ID, ZCL_ON_OFF_ATTRIBUTE_ID, (uint8_t *) &onoff, ZCL_BOOLEAN_ATTRIBUTE_TYPE); } -#if APP_BOARD_LED_STATUS || APP_BOARD_BTN bool AppTask::StartTimer(void) { - uint32_t aTimeoutMs = GetAppTask().mBlinkOnTimeMS; - -#if APP_BOARD_LED_STATUS - if (GetAppTask().mBlinkOffTimeMS) - { - aTimeoutMs = sStatusLED.GetOnoff() ? GetAppTask().mBlinkOnTimeMS : GetAppTask().mBlinkOffTimeMS; - sStatusLED.Toggle(); - } - else - { - if (!sStatusLED.GetOnoff()) - { - sStatusLED.SetOnoff(1); - } - } -#endif - if (xTimerIsTimerActive(GetAppTask().sTimer)) { CancelTimer(); } - if (aTimeoutMs == 0) + + if (GetAppTask().mTimerIntvl == 0) { - aTimeoutMs = 1000; + GetAppTask().mTimerIntvl = 1000; } - if (xTimerChangePeriod(GetAppTask().sTimer, pdMS_TO_TICKS(aTimeoutMs), pdMS_TO_TICKS(100)) != pdPASS) + if (xTimerChangePeriod(GetAppTask().sTimer, pdMS_TO_TICKS(GetAppTask().mTimerIntvl), pdMS_TO_TICKS(100)) != pdPASS) { ChipLogProgress(NotSpecified, "Failed to access timer with 100 ms delay."); } @@ -622,61 +527,104 @@ void AppTask::TimerCallback(TimerHandle_t xTimer) GetAppTask().PostEvent(APP_EVENT_TIMER); } -void AppTask::TimerEventHandler(void) +void AppTask::TimerEventHandler(app_event_t event) { -#if APP_BOARD_BTN - if (GetAppTask().buttonPressedTimeout) + if (event & APP_EVENT_BTN_FACTORY_RESET_PRESS) { - /** device is being in factory reset confirm state*/ - if (ButtonPressed()) - { - if (GetAppTask().buttonPressedTimeout < chip::System::SystemClock().GetMonotonicMilliseconds64().count()) - { - GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); - } - } - else + GetAppTask().mTimerIntvl = APP_BUTTON_PRESS_JITTER; + StartTimer(); + } + else if (event & APP_EVENT_BTN_FACTORY_RESET_IND) + { + if (GetAppTask().mButtonPressedTime) { - /** factory reset cancelled */ - GetAppTask().buttonPressedTimeout = 0; - GetAppTask().PostEvent(APP_EVENT_BTN_FACTORY_RESET_CANCEL); + GetAppTask().mIsFactoryResetIndicat = true; +#ifdef BL706_NIGHT_LIGHT + sLightLED.SetColor(254, 0, 210); +#ifndef LED_BTN_RESET + uint32_t resetCnt = 0; + GetAppTask().mButtonPressedTime = 0; + ef_set_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt)); + + vTaskDelay(APP_BUTTON_PRESS_LONG); + GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); +#endif +#else + sLightLED.Toggle(); + GetAppTask().mTimerIntvl = 100; + StartTimer(); +#endif } } -#endif - StartTimer(); -} - -void AppTask::TimerDutyCycle(app_event_t event) -{ - static uint32_t backup_blinkOnTimeMS, backup_blinkOffTimeMS; - - if (event & APP_EVENT_SYS_PROVISIONED) + if (event & APP_EVENT_BTN_FACTORY_RESET_CANCEL) { - GetAppTask().mBlinkOnTimeMS = 1000, GetAppTask().mBlinkOffTimeMS = 0; - } - else if (event & APP_EVENT_SYS_BLE_CONN) - { - GetAppTask().mBlinkOnTimeMS = 100, GetAppTask().mBlinkOffTimeMS = 100; - } - else if (event & APP_EVENT_SYS_BLE_ADV) - { - GetAppTask().mBlinkOnTimeMS = 100, GetAppTask().mBlinkOffTimeMS = 900; - } - else if (event & APP_EVENT_BTN_FACTORY_RESET_IND) - { - if (500 != backup_blinkOffTimeMS || 500 != backup_blinkOnTimeMS) + GetAppTask().mTimerIntvl = 1000; + StartTimer(); + if (GetAppTask().mIsFactoryResetIndicat) { - backup_blinkOnTimeMS = GetAppTask().mBlinkOnTimeMS, backup_blinkOffTimeMS = GetAppTask().mBlinkOffTimeMS; + LightingUpdate(APP_EVENT_LIGHTING_GO_THROUGH); } - GetAppTask().mBlinkOnTimeMS = 500, GetAppTask().mBlinkOffTimeMS = 500; + GetAppTask().mIsFactoryResetIndicat = false; + GetAppTask().mButtonPressedTime = 0; } - else if (event & APP_EVENT_BTN_FACTORY_RESET_CANCEL) + + if (APP_EVENT_TIMER & event) { - GetAppTask().mBlinkOnTimeMS = backup_blinkOnTimeMS, GetAppTask().mBlinkOffTimeMS = backup_blinkOffTimeMS; + + if (GetAppTask().mButtonPressedTime) + { + if (GetAppTask().mIsFactoryResetIndicat) + { + if (chip::System::SystemClock().GetMonotonicMilliseconds64().count() - GetAppTask().mButtonPressedTime >= + APP_BUTTON_PRESS_LONG) + { + /** factory reset indicat done. */ + sLightLED.SetOnoff(false); + GetAppTask().mTimerIntvl = 1000; + } + else + { +#ifndef BL706_NIGHT_LIGHT + sLightLED.Toggle(); +#endif + } + } + else + { + +#ifdef BL706_NIGHT_LIGHT + if (GetAppTask().mButtonPressedTime && + chip::System::SystemClock().GetMonotonicMilliseconds64().count() - GetAppTask().mButtonPressedTime > + APP_BUTTON_PRESS_LONG) + { + uint32_t resetCnt = 0; + GetAppTask().mButtonPressedTime = 0; + ef_set_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt)); + } +#else +#ifdef LED_BTN_RESET + if (ButtonPressed()) + { + if (!GetAppTask().mIsFactoryResetIndicat && + chip::System::SystemClock().GetMonotonicMilliseconds64().count() - GetAppTask().mButtonPressedTime >= + APP_BUTTON_PRESS_SHORT) + { + GetAppTask().PostEvent(APP_EVENT_BTN_FACTORY_RESET_IND); + } + } + else + { + GetAppTask().PostEvent(APP_EVENT_BTN_FACTORY_RESET_CANCEL); + } +#endif +#endif + } + } + + StartTimer(); } } -#endif void AppTask::IdentifyStartHandler(Identify *) { @@ -714,36 +662,61 @@ void AppTask::IdentifyHandleOp(app_event_t event) void AppTask::ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction) { - GetAppTask().PostEvent(APP_EVENT_BTN_FACTORY_RESET_PW_PRC); - GetAppTask().buttonPressedTimeout = - chip::System::SystemClock().GetMonotonicMilliseconds64().count() + FACTORY_RESET_TRIGGER_TIMEOUT - 100; + GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); } -#if APP_BOARD_BTN -hosal_gpio_dev_t gpio_key = { .port = LED_BTN_RESET, .config = INPUT_PULL_UP, .priv = NULL }; +#ifdef LED_BTN_RESET +hosal_gpio_dev_t gpio_key = { .port = LED_BTN_RESET, .config = INPUT_HIGH_IMPEDANCE, .priv = NULL }; void AppTask::ButtonInit(void) { - GetAppTask().buttonPressedTimeout = 0; + GetAppTask().mButtonPressedTime = 0; + GetAppTask().mIsFactoryResetIndicat = false; hosal_gpio_init(&gpio_key); - hosal_gpio_irq_set(&gpio_key, HOSAL_IRQ_TRIG_NEG_PULSE, GetAppTask().ButtonEventHandler, NULL); + hosal_gpio_irq_set(&gpio_key, HOSAL_IRQ_TRIG_POS_PULSE, GetAppTask().ButtonEventHandler, NULL); } bool AppTask::ButtonPressed(void) { uint8_t val = 1; hosal_gpio_input_get(&gpio_key, &val); - return val == 0; + return val == 1; } void AppTask::ButtonEventHandler(void * arg) { + uint32_t presstime; if (ButtonPressed()) { - GetAppTask().PostEvent(APP_EVENT_BTN_FACTORY_RESET_IND); - GetAppTask().buttonPressedTimeout = - chip::System::SystemClock().GetMonotonicMilliseconds64().count() + FACTORY_RESET_TRIGGER_TIMEOUT - 100; + hosal_gpio_irq_set(&gpio_key, HOSAL_IRQ_TRIG_NEG_LEVEL, GetAppTask().ButtonEventHandler, NULL); + + GetAppTask().mButtonPressedTime = chip::System::SystemClock().GetMonotonicMilliseconds64().count(); + GetAppTask().PostEvent(APP_EVENT_BTN_FACTORY_RESET_PRESS); + } + else + { + hosal_gpio_irq_set(&gpio_key, HOSAL_IRQ_TRIG_POS_PULSE, GetAppTask().ButtonEventHandler, NULL); + + if (GetAppTask().mButtonPressedTime) + { + + presstime = chip::System::SystemClock().GetMonotonicMilliseconds64().count() - GetAppTask().mButtonPressedTime; + if (presstime >= APP_BUTTON_PRESS_LONG) + { + GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); + } + else if (presstime <= APP_BUTTON_PRESS_SHORT && presstime >= APP_BUTTON_PRESS_JITTER) + { + GetAppTask().PostEvent(APP_EVENT_BTN_SHORT); + } + else + { + GetAppTask().PostEvent(APP_EVENT_BTN_FACTORY_RESET_CANCEL); + } + } + + GetAppTask().mButtonPressedTime = 0; } } #endif diff --git a/examples/lighting-app/infineon/psoc6/src/AppTask.cpp b/examples/lighting-app/infineon/psoc6/src/AppTask.cpp index 64bd0c189fb377..89605fc8a9c6e6 100644 --- a/examples/lighting-app/infineon/psoc6/src/AppTask.cpp +++ b/examples/lighting-app/infineon/psoc6/src/AppTask.cpp @@ -305,18 +305,18 @@ void AppTask::AppTaskMain(void * pvParameter) void AppTask::LightActionEventHandler(AppEvent * event) { - bool initiated = false; LightingManager::Action_t action; - int32_t actor = 0; - CHIP_ERROR err = CHIP_NO_ERROR; + int32_t actor; - if (event->Type == AppEvent::kEventType_Light) + switch (event->Type) { + case AppEvent::kEventType_Light: { action = static_cast(event->LightEvent.Action); actor = event->LightEvent.Actor; + break; } - else if (event->Type == AppEvent::kEventType_Button) - { + + case AppEvent::kEventType_Button: { if (LightMgr().IsLightOn()) { action = LightingManager::OFF_ACTION; @@ -325,21 +325,18 @@ void AppTask::LightActionEventHandler(AppEvent * event) { action = LightingManager::ON_ACTION; } + actor = AppEvent::kEventType_Button; + break; } - else - { - err = APP_ERROR_UNHANDLED_EVENT; + + default: + return; } - if (err == CHIP_NO_ERROR) + if (!LightMgr().InitiateAction(actor, action)) { - initiated = LightMgr().InitiateAction(actor, action); - - if (!initiated) - { - P6_LOG("Action is already in progress or active."); - } + P6_LOG("Action is already in progress or active."); } } diff --git a/examples/lock-app/efr32/BUILD.gn b/examples/lock-app/efr32/BUILD.gn index fac904a047fee5..996cb0f086a67d 100644 --- a/examples/lock-app/efr32/BUILD.gn +++ b/examples/lock-app/efr32/BUILD.gn @@ -187,6 +187,10 @@ efr32_executable("lock_app") { sources += [ "${examples_plat_dir}/uart.cpp" ] } + if (chip_build_libshell) { + sources += [ "src/EventHandlerLibShell.cpp" ] + } + deps = [ ":sdk", "${chip_root}/examples/lock-app/lock-common", diff --git a/examples/lock-app/efr32/include/AppTask.h b/examples/lock-app/efr32/include/AppTask.h index a28837e776b85a..0c7723475772be 100644 --- a/examples/lock-app/efr32/include/AppTask.h +++ b/examples/lock-app/efr32/include/AppTask.h @@ -49,6 +49,9 @@ #define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) #define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) #define APP_ERROR_ALLOCATION_FAILED CHIP_APPLICATION_ERROR(0x07) +#if defined(ENABLE_CHIP_SHELL) +#define APP_ERROR_TOO_MANY_SHELL_ARGUMENTS CHIP_APPLICATION_ERROR(0x08) +#endif // ENABLE_CHIP_SHELL /********************************************************** * AppTask Declaration diff --git a/examples/lock-app/efr32/include/EventHandlerLibShell.h b/examples/lock-app/efr32/include/EventHandlerLibShell.h new file mode 100644 index 00000000000000..3ad9f11cbf2fdc --- /dev/null +++ b/examples/lock-app/efr32/include/EventHandlerLibShell.h @@ -0,0 +1,40 @@ +/* + * + * 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 + +class EventData +{ +public: + chip::EventId eventId; +}; + +class AlarmEventData : public EventData +{ +public: + DlAlarmCode alarmCode; +}; + +class DoorStateEventData : public EventData +{ +public: + DlDoorState doorState; +}; + +CHIP_ERROR RegisterLockEvents(); +void EventWorkerFunction(intptr_t context); diff --git a/examples/lock-app/efr32/src/AppTask.cpp b/examples/lock-app/efr32/src/AppTask.cpp index f624eb50073234..ae683cc92f86b5 100644 --- a/examples/lock-app/efr32/src/AppTask.cpp +++ b/examples/lock-app/efr32/src/AppTask.cpp @@ -20,6 +20,9 @@ #include "AppTask.h" #include "AppConfig.h" #include "AppEvent.h" +#if defined(ENABLE_CHIP_SHELL) +#include "EventHandlerLibShell.h" +#endif // ENABLE_CHIP_SHELL #ifdef ENABLE_WSTK_LEDS #include "LEDWidget.h" @@ -161,6 +164,15 @@ CHIP_ERROR AppTask::Init() appError(err); } +#if defined(ENABLE_CHIP_SHELL) + err = RegisterLockEvents(); + if (err != CHIP_NO_ERROR) + { + EFR32_LOG("RegisterLockEvents() failed"); + appError(err); + } +#endif // ENABLE_CHIP_SHELL + // Initial lock state chip::app::DataModel::Nullable state; chip::EndpointId endpointId{ 1 }; diff --git a/examples/lock-app/efr32/src/EventHandlerLibShell.cpp b/examples/lock-app/efr32/src/EventHandlerLibShell.cpp new file mode 100644 index 00000000000000..02979f56238a23 --- /dev/null +++ b/examples/lock-app/efr32/src/EventHandlerLibShell.cpp @@ -0,0 +1,211 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "EventHandlerLibShell.h" +#include "AppTask.h" +#include "lib/shell/Engine.h" +#include "lib/shell/commands/Help.h" + +#include "app/server/Server.h" +#include "platform/CHIPDeviceLayer.h" +#include + +constexpr uint8_t lockEndpoint = 1; + +using namespace chip; +using namespace chip::app; +using namespace Clusters::DoorLock; +using Shell::Engine; +using Shell::shell_command_t; +using Shell::streamer_get; +using Shell::streamer_printf; + +Engine sShellDoorlockSubCommands; +Engine sShellDoorlockEventSubCommands; +Engine sShellDoorlockEventAlarmSubCommands; +Engine sShellDoorlockEventDoorStateSubCommands; + +/******************************************************** + * Doorlock shell functions + *********************************************************/ + +CHIP_ERROR DoorlockHelpHandler(int argc, char ** argv) +{ + sShellDoorlockSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DoorlockCommandHandler(int argc, char ** argv) +{ + if (argc == 0) + { + return DoorlockHelpHandler(argc, argv); + } + + return sShellDoorlockSubCommands.ExecCommand(argc, argv); +} + +/******************************************************** + * Event shell functions + *********************************************************/ + +CHIP_ERROR EventHelpHandler(int argc, char ** argv) +{ + sShellDoorlockEventSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +CHIP_ERROR EventDoorlockCommandHandler(int argc, char ** argv) +{ + if (argc == 0) + { + return EventHelpHandler(argc, argv); + } + + return sShellDoorlockEventSubCommands.ExecCommand(argc, argv); +} + +/******************************************************** + * Alarm shell functions + *********************************************************/ + +CHIP_ERROR AlarmHelpHandler(int argc, char ** argv) +{ + sShellDoorlockEventAlarmSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +CHIP_ERROR AlarmEventHandler(int argc, char ** argv) +{ + + if (argc == 0) + { + return AlarmHelpHandler(argc, argv); + } + if (argc >= 2) + { + ChipLogError(Zcl, "Too many arguments provided to function %s, line %d", __func__, __LINE__); + return APP_ERROR_TOO_MANY_SHELL_ARGUMENTS; + } + + AlarmEventData * data = Platform::New(); + data->eventId = Events::DoorLockAlarm::Id; + data->alarmCode = static_cast(atoi(argv[0])); + + DeviceLayer::PlatformMgr().ScheduleWork(EventWorkerFunction, reinterpret_cast(data)); + + return CHIP_NO_ERROR; +} + +/******************************************************** + * Door state shell functions + *********************************************************/ + +CHIP_ERROR DoorStateHelpHandler(int argc, char ** argv) +{ + sShellDoorlockEventDoorStateSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DoorStateEventHandler(int argc, char ** argv) +{ + + if (argc == 0) + { + return DoorStateHelpHandler(argc, argv); + } + if (argc >= 2) + { + ChipLogError(Zcl, "Too many arguments provided to function %s, line %d", __func__, __LINE__); + return APP_ERROR_TOO_MANY_SHELL_ARGUMENTS; + } + + DoorStateEventData * data = Platform::New(); + data->eventId = Events::DoorStateChange::Id; + data->doorState = static_cast(atoi(argv[0])); + + DeviceLayer::PlatformMgr().ScheduleWork(EventWorkerFunction, reinterpret_cast(data)); + + return CHIP_NO_ERROR; +} + +/** + * @brief configures lock matter shell + * + */ + +CHIP_ERROR RegisterLockEvents() +{ + static const shell_command_t sDoorlockSubCommands[] = { { &DoorlockHelpHandler, "help", "Usage: doorlock " }, + { &EventDoorlockCommandHandler, "event", + " Usage: doorlock event " } }; + + static const shell_command_t sDoorlockEventSubCommands[] = { + { &EventHelpHandler, "help", "Usage : doorlock event " }, + { &AlarmEventHandler, "lock-alarm", "Sends lock alarm event to lock app" }, + { &DoorStateEventHandler, "door-state-change", "Sends door state change event to lock app" } + }; + + static const shell_command_t sDoorlockEventAlarmSubCommands[] = { { &AlarmHelpHandler, "help", + "Usage : doorlock event lock-alarm AlarmCode" } }; + + static const shell_command_t sDoorlockEventDoorStateSubCommands[] = { + { &DoorStateHelpHandler, "help", "Usage : doorlock event door-state-change DoorState" } + }; + + static const shell_command_t sDoorLockCommand = { &DoorlockCommandHandler, "doorlock", + "doorlock commands. Usage: doorlock " }; + + sShellDoorlockEventAlarmSubCommands.RegisterCommands(sDoorlockEventAlarmSubCommands, ArraySize(sDoorlockEventAlarmSubCommands)); + + sShellDoorlockEventDoorStateSubCommands.RegisterCommands(sDoorlockEventDoorStateSubCommands, + ArraySize(sDoorlockEventDoorStateSubCommands)); + + sShellDoorlockEventSubCommands.RegisterCommands(sDoorlockEventSubCommands, ArraySize(sDoorlockEventSubCommands)); + sShellDoorlockSubCommands.RegisterCommands(sDoorlockSubCommands, ArraySize(sDoorlockSubCommands)); + + Engine::Root().RegisterCommands(&sDoorLockCommand, 1); + + return CHIP_NO_ERROR; +} + +void EventWorkerFunction(intptr_t context) +{ + VerifyOrReturn(context != 0, ChipLogError(NotSpecified, "EventWorkerFunction - Invalid work data")); + + EventData * data = reinterpret_cast(context); + + switch (data->eventId) + { + case Events::DoorLockAlarm::Id: { + AlarmEventData * alarmData = reinterpret_cast(context); + DoorLockServer::Instance().SendLockAlarmEvent(lockEndpoint, alarmData->alarmCode); + break; + } + + case Events::DoorStateChange::Id: { + DoorStateEventData * doorStateData = reinterpret_cast(context); + DoorLockServer::Instance().SetDoorState(lockEndpoint, doorStateData->doorState); + break; + } + + default: { + ChipLogError(Zcl, "Invalid Event Id %s, line %d", __func__, __LINE__); + break; + } + } +} diff --git a/examples/lock-app/infineon/psoc6/src/AppTask.cpp b/examples/lock-app/infineon/psoc6/src/AppTask.cpp index ad532c6707f72e..d9d46398ee8afa 100644 --- a/examples/lock-app/infineon/psoc6/src/AppTask.cpp +++ b/examples/lock-app/infineon/psoc6/src/AppTask.cpp @@ -388,18 +388,18 @@ void AppTask::AppTaskMain(void * pvParameter) void AppTask::LockActionEventHandler(AppEvent * event) { - bool initiated = false; LockManager::Action_t action; int32_t actor; - CHIP_ERROR err = CHIP_NO_ERROR; - if (event->Type == AppEvent::kEventType_Lock) + switch (event->Type) { + case AppEvent::kEventType_Lock: { action = static_cast(event->LockEvent.Action); actor = event->LockEvent.Actor; + break; } - else if (event->Type == AppEvent::kEventType_Button) - { + + case AppEvent::kEventType_Button: { if (LockMgr().NextState() == true) { action = LockManager::LOCK_ACTION; @@ -408,21 +408,18 @@ void AppTask::LockActionEventHandler(AppEvent * event) { action = LockManager::UNLOCK_ACTION; } + actor = AppEvent::kEventType_Button; + break; } - else - { - err = APP_ERROR_UNHANDLED_EVENT; + + default: + return; } - if (err == CHIP_NO_ERROR) + if (!LockMgr().InitiateAction(actor, action)) { - initiated = LockMgr().InitiateAction(actor, action); - - if (!initiated) - { - P6_LOG("Action is already in progress or active."); - } + P6_LOG("Action is already in progress or active."); } } diff --git a/examples/platform/bouffalolab/bl602/flash_config/partition_cfg_2M.toml b/examples/platform/bouffalolab/bl602/flash_config/partition_cfg_2M.toml new file mode 100644 index 00000000000000..4705a3891e0a25 --- /dev/null +++ b/examples/platform/bouffalolab/bl602/flash_config/partition_cfg_2M.toml @@ -0,0 +1,94 @@ +[pt_table] +#partition table is 4K in size +address0 = 0xE000 +address1 = 0xF000 + +[[pt_entry]] +type = 0 +name = "FW" +device = 0 +address0 = 0x10000 +size0 = 0x15C000 +address1 = 0x16C000 +size1 = 0x4000 +# compressed image must set len,normal image can left it to 0 +len = 0 + +[[pt_entry]] +type = 2 +name = "mfg" +device = 0 +address0 = 0x16C000 +size0 = 0x4000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + +[[pt_entry]] +type = 3 +name = "media" +device = 0 +address0 = 0x1A2000 +size0 = 0x47000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + +[[pt_entry]] +type = 4 +name = "PSM" +device = 0 +address0 = 0x1E9000 +size0 = 0x8000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + +[[pt_entry]] +type = 5 +name = "KEY" +device = 0 +address0 = 0x1F1000 +size0 = 0x2000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + +[[pt_entry]] +type = 6 +name = "DATA" +device = 0 +address0 = 0x1F3000 +size0 = 0x5000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + + +[[pt_entry]] +type = 7 +name = "factory" +device = 0 +address0 = 0x1F8000 +size0 = 0x7000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + +#if user want to put RF calibration data on flash, uncomment following pt entry +#[[pt_entry]] +#type = 8 +#name = "rf_para" +#device = 0 +#address0 = 0x1FF000 +#size0 = 0x1000 +#address1 = 0 +#size1 = 0 +## compressed image must set len,normal image can left it to 0 +#len = 0 diff --git a/examples/platform/bouffalolab/bl602/flash_config/partition_cfg_4M.toml b/examples/platform/bouffalolab/bl602/flash_config/partition_cfg_4M.toml new file mode 100644 index 00000000000000..c7812b9cb70fa9 --- /dev/null +++ b/examples/platform/bouffalolab/bl602/flash_config/partition_cfg_4M.toml @@ -0,0 +1,94 @@ +[pt_table] +#partition table is 4K in size +address0 = 0xE000 +address1 = 0xF000 + +[[pt_entry]] +type = 0 +name = "FW" +device = 0 +address0 = 0x10000 +size0 = 0x160000 +address1 = 0x170000 +size1 = 0x100000 +# compressed image must set len,normal image can left it to 0 +len = 0 + +[[pt_entry]] +type = 2 +name = "mfg" +device = 0 +address0 = 0x270000 +size0 = 0x2F000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + +[[pt_entry]] +type = 3 +name = "media" +device = 0 +address0 = 0x272000 +size0 = 0x1000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + +[[pt_entry]] +type = 4 +name = "PSM" +device = 0 +address0 = 0x273000 +size0 = 0x33000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + +[[pt_entry]] +type = 5 +name = "KEY" +device = 0 +address0 = 0x2A6000 +size0 = 0x2000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + +[[pt_entry]] +type = 6 +name = "DATA" +device = 0 +address0 = 0x2A8000 +size0 = 0x5000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + + +[[pt_entry]] +type = 7 +name = "factory" +device = 0 +address0 = 0x2AD000 +size0 = 0x7000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 + +#if user want to put RF calibration data on flash, uncomment following pt entry +#[[pt_entry]] +#type = 8 +#name = "rf_para" +#device = 0 +#address0 = 0x1FF000 +#size0 = 0x1000 +#address1 = 0 +#size1 = 0 +## compressed image must set len,normal image can left it to 0 +#len = 0 diff --git a/examples/platform/bouffalolab/bl702/LEDWidget.cpp b/examples/platform/bouffalolab/bl702/LEDWidget.cpp index ed7f7735034425..6eddbceaee0778 100644 --- a/examples/platform/bouffalolab/bl702/LEDWidget.cpp +++ b/examples/platform/bouffalolab/bl702/LEDWidget.cpp @@ -1,7 +1,6 @@ /* * * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -28,12 +27,14 @@ void LEDWidget::Init() { +#ifdef LED1_PIN mPin = LED1_PIN; hosal_gpio_dev_t gpio_led = { .config = OUTPUT_OPEN_DRAIN_NO_PULL, .priv = NULL }; gpio_led.port = mPin; hosal_gpio_init(&gpio_led); +#endif SetOnoff(false); } @@ -44,6 +45,7 @@ void LEDWidget::Toggle(void) void LEDWidget::SetOnoff(bool state) { +#ifdef LED1_PIN hosal_gpio_dev_t gpio_led = { .port = mPin, .config = OUTPUT_OPEN_DRAIN_NO_PULL, .priv = NULL }; mOnoff = state; @@ -56,6 +58,7 @@ void LEDWidget::SetOnoff(bool state) { hosal_gpio_output_set(&gpio_led, 0); } +#endif } bool LEDWidget::GetOnoff(void) @@ -67,8 +70,10 @@ void DimmableLEDWidget::Init() { mOnoff = light_v = 0; +#ifdef MAX_PWM_CHANNEL demo_hosal_pwm_init(); demo_hosal_pwm_start(); +#endif } void DimmableLEDWidget::Toggle(void) @@ -79,6 +84,7 @@ void DimmableLEDWidget::Toggle(void) void DimmableLEDWidget::SetOnoff(bool state) { mOnoff = state; +#ifdef MAX_PWM_CHANNEL if (mOnoff) { if (light_v) @@ -94,11 +100,14 @@ void DimmableLEDWidget::SetOnoff(bool state) { set_level(0); } +#endif } void DimmableLEDWidget::SetLevel(uint8_t level) { +#ifdef MAX_PWM_CHANNEL set_level(level); +#endif light_v = level; mOnoff = light_v > 0; } @@ -106,9 +115,10 @@ void DimmableLEDWidget::SetLevel(uint8_t level) void ColorLEDWidget::Init() { mOnoff = light_v = light_s = light_h = 0; - +#ifdef MAX_PWM_CHANNEL demo_hosal_pwm_init(); demo_hosal_pwm_start(); +#endif } void ColorLEDWidget::Toggle(void) @@ -118,6 +128,7 @@ void ColorLEDWidget::Toggle(void) void ColorLEDWidget::SetOnoff(bool state) { +#ifdef MAX_PWM_CHANNEL mOnoff = state; if (mOnoff) { @@ -134,6 +145,7 @@ void ColorLEDWidget::SetOnoff(bool state) { set_color(0, light_h, light_s); } +#endif } void ColorLEDWidget::SetLevel(uint8_t level) @@ -143,7 +155,9 @@ void ColorLEDWidget::SetLevel(uint8_t level) void ColorLEDWidget::SetColor(uint8_t level, uint8_t hue, uint8_t sat) { +#ifdef MAX_PWM_CHANNEL set_color(level, hue, sat); +#endif light_v = level; light_h = hue; light_s = sat; diff --git a/examples/platform/bouffalolab/bl702/LEDWidget.h b/examples/platform/bouffalolab/bl702/LEDWidget.h index e332f33fc0847c..935a1750620066 100644 --- a/examples/platform/bouffalolab/bl702/LEDWidget.h +++ b/examples/platform/bouffalolab/bl702/LEDWidget.h @@ -1,7 +1,6 @@ /* * * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/examples/platform/bouffalolab/bl702/demo_pwm.c b/examples/platform/bouffalolab/bl702/demo_pwm.c index 321b12089615f0..5f0104ffc7bc67 100644 --- a/examples/platform/bouffalolab/bl702/demo_pwm.c +++ b/examples/platform/bouffalolab/bl702/demo_pwm.c @@ -94,25 +94,21 @@ void set_level(uint8_t currLevel) para.duty_cycle = currLevel * PWM_DUTY_CYCLE / 254; para.freq = PWM_FREQ; - printf("[set_level] currLevel:0x%02x\r\n", currLevel); demo_hosal_pwm_change_param(¶); } void set_color_red(uint8_t currLevel) { - printf("set_color_red\r\n"); set_color(currLevel, 0, 254); } void set_color_green(uint8_t currLevel) { - printf("set_color_green\r\n"); set_color(currLevel, 84, 254); } void set_color_yellow(uint8_t currLevel) { - printf("set_color_yellow\r\n"); set_color(currLevel, 42, 254); } @@ -183,10 +179,6 @@ void set_color(uint8_t currLevel, uint8_t currHue, uint8_t currSat) para[2].duty_cycle = green * PWM_DUTY_CYCLE / 254; para[2].freq = PWM_FREQ; - printf("[set_color] currLevel:0x%02x, currHue:0x%02x, currSat:0x%02x, hue:0x%04x, sat:0x%02x, red:0x%lx, green:0x%lx, " - "blue:0x%lx \r\n", - currLevel, currHue, currSat, hue, sat, red, green, blue); - demo_hosal_pwm_change_param(para); #else set_level(currLevel); diff --git a/examples/platform/bouffalolab/bl702/flash_config/bl_factory_params_IoTKitA_32M.dts b/examples/platform/bouffalolab/bl702/flash_config/bl_factory_params_IoTKitA_32M.dts deleted file mode 100755 index 71afea9235a174..00000000000000 --- a/examples/platform/bouffalolab/bl702/flash_config/bl_factory_params_IoTKitA_32M.dts +++ /dev/null @@ -1,116 +0,0 @@ -/dts-v1/; -// version: 17 -// last_comp_version: 16 -// boot_cpuid_phys: 0x0 - -/ { - model = "bl bl702 AVB board"; - compatible = "bl,bl702-sample", "bl,bl702-common"; - #address-cells = <0x1>; - #size-cells = <0x1>; - gpio { - #address-cells = <1>; - #size-cells = <1>; - max_num = <40>; - gpio0 { - status = "okay"; - pin = <22>; - feature = "led"; - active = "Hi"; //Hi or Lo - mode = "onoff"; //blink or hearbeat or onoff - time = <100>; //duration for this mode - }; - gpio1 { - status = "disable"; - pin = <6>; - feature = "led"; - active = "Hi"; //Hi or Lo - mode = "blink"; //blink or hearbeat or onoff - time = <100>; //duration for this mode - }; - gpio2 { - status = "disable"; - pin = <5>; - feature = "button"; - active = "Hi"; - mode = "multipress"; - button { - debounce = <10>; - short_press_ms { - start = <30>; - end = <4000>; - kevent = <2>; - }; - long_press_ms { - start = <4001>; - end = <10000>; - kevent = <3>; - }; - longlong_press_ms { - start = <10001>; - kevent = <4>; - }; - trig_level = "Lo"; - }; - hbn_use = "disable"; - }; - }; - uart { - #address-cells = <1>; - #size-cells = <1>; - uart@4000A000 { - status = "okay"; - id = <0>; - compatible = "bl702_uart"; - path = "/dev/ttyS0"; - baudrate = <2000000>; - pin { - rx = <15>; - tx = <14>; - }; - feature { - tx = "okay"; - rx = "okay"; - cts = "disable"; - rts = "disable"; - }; - }; - uart@4000A100 { - status = "disable"; - id = <1>; - compatible = "bl702_uart"; - path = "/dev/ttyS1"; - baudrate = <115200>; - pin { - rx = <3>; - tx = <4>; - }; - feature { - tx = "okay"; - rx = "okay"; - cts = "disable"; - rts = "disable"; - }; - }; - }; - wireless { - #address-cells = <1>; - #size-cells = <1>; - mac { - mode = "MBF"; // 'M': manufacture; 'B': efuse; 'F': flash - mac_addr = [C8 43 57 82 73 40 88 88]; - }; - brd_rf { - xtal_mode = "MF"; - xtal = <36 36 0 60 60>; - pwr = <14>; - pwr_mode = "bf";//B: only use power offset in EFUSE; b: use power offset in EFUSE with incremental mode; F: only use power offset in Flash; f: use power offset in Flash with incremental mode - //pwr_offset = <10 10>;//due to the limit of current DTC, negative value is used. So we work around by adding all the poweroffset with 10. so 8 represents -2; 10 represents 0; 13 represents 3 - pwr_offset_zigbee = <10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10>; - pwr_offset_ble = <10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10>; - }; - rf_temp { - en_tcal = <0>; - }; - }; -}; diff --git a/examples/platform/bouffalolab/bl702/flash_config/partition_cfg_2M.toml b/examples/platform/bouffalolab/bl702/flash_config/partition_cfg_2M.toml index ec51ddbc63d4f1..f6a22deaf30a27 100644 --- a/examples/platform/bouffalolab/bl702/flash_config/partition_cfg_2M.toml +++ b/examples/platform/bouffalolab/bl702/flash_config/partition_cfg_2M.toml @@ -8,8 +8,8 @@ type = 0 name = "FW" device = 0 address0 = 0x3000 -size0 = 0x127000 -address1 = 0x12A000 +size0 = 0x12b000 +address1 = 0x12e000 size1 = 0xC9000 # compressed image must set len,normal image can left it to 0 len = 0 @@ -33,8 +33,8 @@ age = 0 type = 2 name = "PSM" device = 0 -address0 = 0x1F3000 -size0 = 0x8000 +address0 = 0x1F7000 +size0 = 0x4000 address1 = 0 size1 = 0 # compressed image must set len,normal image can left it to 0 diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CommissionerDiscoveryFragment.java b/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CommissionerDiscoveryFragment.java index dc491e58b59170..ddc613658d1366 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CommissionerDiscoveryFragment.java +++ b/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CommissionerDiscoveryFragment.java @@ -133,7 +133,9 @@ public String getCommissionerButtonText(DiscoveredNodeData commissioner) { ? (aux.isEmpty() ? "" : " from ") + "Vendor ID: " + commissioner.getVendorId() : ""; aux = aux.isEmpty() ? aux : "\n[" + aux + "]"; - return main + aux; + + String preCommissioned = commissioner.isPreCommissioned() ? " (Pre-commissioned)" : ""; + return main + aux + preCommissioned; } /** Interface for notifying the host. */ diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CommissioningFragment.java b/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CommissioningFragment.java deleted file mode 100644 index ca01c26219cbf1..00000000000000 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/CommissioningFragment.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.chip.casting.app; - -import android.os.Bundle; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; -import com.chip.casting.ContentApp; -import com.chip.casting.DiscoveredNodeData; -import com.chip.casting.FailureCallback; -import com.chip.casting.MatterCallbackHandler; -import com.chip.casting.MatterError; -import com.chip.casting.SuccessCallback; -import com.chip.casting.TvCastingApp; -import com.chip.casting.VideoPlayer; -import com.chip.casting.util.GlobalCastingConstants; - -/** A {@link Fragment} to get the TV Casting App commissioned. */ -public class CommissioningFragment extends Fragment { - private static final String TAG = CommissioningFragment.class.getSimpleName(); - - private final TvCastingApp tvCastingApp; - private final DiscoveredNodeData selectedCommissioner; - - private boolean openCommissioningWindowSuccess; - private boolean sendUdcSuccess; - - public CommissioningFragment(TvCastingApp tvCastingApp, DiscoveredNodeData selectedCommissioner) { - this.tvCastingApp = tvCastingApp; - this.selectedCommissioner = selectedCommissioner; - } - - /** - * Use this factory method to create a new instance of this fragment using the provided - * parameters. - * - * @return A new instance of fragment CommissioningFragment. - */ - public static CommissioningFragment newInstance( - TvCastingApp tvCastingApp, DiscoveredNodeData selectedCommissioner) { - return new CommissioningFragment(tvCastingApp, selectedCommissioner); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - - @Override - public View onCreateView( - LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - Callback callback = (CommissioningFragment.Callback) this.getActivity(); - this.openCommissioningWindowSuccess = - tvCastingApp.openBasicCommissioningWindow( - GlobalCastingConstants.CommissioningWindowDurationSecs, - new MatterCallbackHandler() { - @Override - public void handle(MatterError error) { - Log.d(TAG, "handle() called on CommissioningComplete event with " + error); - } - }, - new SuccessCallback() { - @Override - public void handle(VideoPlayer videoPlayer) { - Log.d(TAG, "handle() called on OnConnectionSuccess with " + videoPlayer); - callback.handleCommissioningComplete(); - } - }, - new FailureCallback() { - @Override - public void handle(MatterError matterError) { - Log.d(TAG, "handle() called on OnConnectionFailure with " + matterError); - } - }, - new SuccessCallback() { - @Override - public void handle(ContentApp contentApp) { - Log.d(TAG, "handle() called on OnNewOrUpdatedEndpoint with " + contentApp); - } - }); - if (this.openCommissioningWindowSuccess) { - if (selectedCommissioner != null && selectedCommissioner.getNumIPs() > 0) { - String ipAddress = selectedCommissioner.getIpAddresses().get(0).getHostAddress(); - Log.d( - TAG, - "CommissioningFragment calling tvCastingApp.sendUserDirectedCommissioningRequest with IP: " - + ipAddress - + " port: " - + selectedCommissioner.getPort()); - - this.sendUdcSuccess = tvCastingApp.sendCommissioningRequest(selectedCommissioner); - } - } - - return inflater.inflate(R.layout.fragment_commissioning, container, false); - } - - @Override - public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - String commissioningWindowStatus = "Failed to open commissioning window"; - if (this.openCommissioningWindowSuccess) { - commissioningWindowStatus = "Commissioning window has been opened. Commission manually."; - if (this.sendUdcSuccess) { - commissioningWindowStatus = - "Commissioning window has been opened. Commissioning requested from " - + selectedCommissioner.getDeviceName(); - } - TextView onboardingPayloadView = getView().findViewById(R.id.onboardingPayload); - onboardingPayloadView.setText( - "Onboarding PIN: " - + GlobalCastingConstants.SetupPasscode - + "\nDiscriminator: " - + GlobalCastingConstants.Discriminator); - } - - TextView commissioningWindowStatusView = getView().findViewById(R.id.commissioningWindowStatus); - commissioningWindowStatusView.setText(commissioningWindowStatus); - } - - /** Interface for notifying the host. */ - public interface Callback { - /** Notifies listener to trigger transition on completion of commissioning */ - void handleCommissioningComplete(); - } -} diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ConnectionFragment.java b/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ConnectionFragment.java new file mode 100644 index 00000000000000..c48b28974ef22e --- /dev/null +++ b/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/ConnectionFragment.java @@ -0,0 +1,155 @@ +package com.chip.casting.app; + +import android.os.Bundle; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; +import com.chip.casting.ContentApp; +import com.chip.casting.DiscoveredNodeData; +import com.chip.casting.FailureCallback; +import com.chip.casting.MatterCallbackHandler; +import com.chip.casting.MatterError; +import com.chip.casting.SuccessCallback; +import com.chip.casting.TvCastingApp; +import com.chip.casting.VideoPlayer; +import com.chip.casting.util.GlobalCastingConstants; + +/** A {@link Fragment} to get the TV Casting App commissioned / connected. */ +public class ConnectionFragment extends Fragment { + private static final String TAG = ConnectionFragment.class.getSimpleName(); + + private final TvCastingApp tvCastingApp; + private final DiscoveredNodeData selectedCommissioner; + + private boolean verifyOrEstablishConnectionSuccess; + private boolean openCommissioningWindowSuccess; + private boolean sendUdcSuccess; + + public ConnectionFragment(TvCastingApp tvCastingApp, DiscoveredNodeData selectedCommissioner) { + this.tvCastingApp = tvCastingApp; + this.selectedCommissioner = selectedCommissioner; + } + + /** + * Use this factory method to create a new instance of this fragment using the provided + * parameters. + * + * @return A new instance of fragment CommissioningFragment. + */ + public static ConnectionFragment newInstance( + TvCastingApp tvCastingApp, DiscoveredNodeData selectedCommissioner) { + return new ConnectionFragment(tvCastingApp, selectedCommissioner); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + Callback callback = (ConnectionFragment.Callback) this.getActivity(); + + SuccessCallback onConnectionSuccess = + new SuccessCallback() { + @Override + public void handle(VideoPlayer videoPlayer) { + Log.d(TAG, "handle() called on OnConnectionSuccess with " + videoPlayer); + callback.handleCommissioningComplete(); + } + }; + + FailureCallback onConnectionFailure = + new FailureCallback() { + @Override + public void handle(MatterError matterError) { + Log.d(TAG, "handle() called on OnConnectionFailure with " + matterError); + } + }; + + SuccessCallback onNewOrUpdatedEndpoints = + new SuccessCallback() { + @Override + public void handle(ContentApp contentApp) { + Log.d(TAG, "handle() called on OnNewOrUpdatedEndpoint with " + contentApp); + } + }; + + if (selectedCommissioner != null && selectedCommissioner.isPreCommissioned()) { + VideoPlayer videoPlayer = selectedCommissioner.toConnectableVideoPlayer(); + Log.d(TAG, "Calling verifyOrEstablishConnectionSuccess with VideoPlayer: " + videoPlayer); + this.verifyOrEstablishConnectionSuccess = + tvCastingApp.verifyOrEstablishConnection( + videoPlayer, onConnectionSuccess, onConnectionFailure, onNewOrUpdatedEndpoints); + } else { + Log.d(TAG, "Running commissioning"); + this.openCommissioningWindowSuccess = + tvCastingApp.openBasicCommissioningWindow( + GlobalCastingConstants.CommissioningWindowDurationSecs, + new MatterCallbackHandler() { + @Override + public void handle(MatterError error) { + Log.d(TAG, "handle() called on CommissioningComplete event with " + error); + } + }, + onConnectionSuccess, + onConnectionFailure, + onNewOrUpdatedEndpoints); + + if (this.openCommissioningWindowSuccess) { + if (selectedCommissioner != null && selectedCommissioner.getNumIPs() > 0) { + String ipAddress = selectedCommissioner.getIpAddresses().get(0).getHostAddress(); + Log.d( + TAG, + "ConnectionFragment calling tvCastingApp.sendUserDirectedCommissioningRequest with IP: " + + ipAddress + + " port: " + + selectedCommissioner.getPort()); + + this.sendUdcSuccess = tvCastingApp.sendCommissioningRequest(selectedCommissioner); + } + } + } + + return inflater.inflate(R.layout.fragment_connection, container, false); + } + + @Override + public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + String commissioningWindowStatus = ""; + if (selectedCommissioner != null && selectedCommissioner.isPreCommissioned()) { + commissioningWindowStatus = "Establishing connection with selected Video Player"; + } else { + commissioningWindowStatus = "Failed to open commissioning window"; + if (this.openCommissioningWindowSuccess) { + commissioningWindowStatus = "Commissioning window has been opened. Commission manually."; + if (this.sendUdcSuccess) { + commissioningWindowStatus = + "Commissioning window has been opened. Commissioning requested from " + + selectedCommissioner.getDeviceName(); + } + TextView onboardingPayloadView = getView().findViewById(R.id.onboardingPayload); + onboardingPayloadView.setText( + "Onboarding PIN: " + + GlobalCastingConstants.SetupPasscode + + "\nDiscriminator: " + + GlobalCastingConstants.Discriminator); + } + } + + TextView commissioningWindowStatusView = getView().findViewById(R.id.commissioningWindowStatus); + commissioningWindowStatusView.setText(commissioningWindowStatus); + } + + /** Interface for notifying the host. */ + public interface Callback { + /** Notifies listener to trigger transition on completion of commissioning */ + void handleCommissioningComplete(); + } +} diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/MainActivity.java b/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/MainActivity.java index 88b85610b475f6..d2a4327685b832 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/MainActivity.java +++ b/examples/tv-casting-app/android/App/app/src/main/java/com/chip/casting/app/MainActivity.java @@ -15,14 +15,16 @@ import chip.platform.NsdManagerServiceResolver; import chip.platform.PreferencesConfigurationManager; import chip.platform.PreferencesKeyValueStoreManager; +import com.chip.casting.AppParameters; import com.chip.casting.DACProviderStub; import com.chip.casting.DiscoveredNodeData; import com.chip.casting.TvCastingApp; import com.chip.casting.util.GlobalCastingConstants; +import java.util.Random; public class MainActivity extends AppCompatActivity implements CommissionerDiscoveryFragment.Callback, - CommissioningFragment.Callback, + ConnectionFragment.Callback, SelectClusterFragment.Callback { private static final String TAG = MainActivity.class.getSimpleName(); @@ -46,7 +48,7 @@ protected void onCreate(Bundle savedInstanceState) { @Override public void handleCommissioningButtonClicked(DiscoveredNodeData commissioner) { - showFragment(CommissioningFragment.newInstance(tvCastingApp, commissioner)); + showFragment(ConnectionFragment.newInstance(tvCastingApp, commissioner)); } @Override @@ -90,7 +92,12 @@ private void initJni() { chipAppServer = new ChipAppServer(); chipAppServer.startApp(); - tvCastingApp.init(); + AppParameters appParameters = new AppParameters(); + byte[] rotatingDeviceIdUniqueId = + new byte[AppParameters.MIN_ROTATING_DEVICE_ID_UNIQUE_ID_LENGTH]; + new Random().nextBytes(rotatingDeviceIdUniqueId); + appParameters.setRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueId); + tvCastingApp.init(appParameters); } private void showFragment(Fragment fragment, boolean showOnBack) { diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/AppParameters.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/AppParameters.java new file mode 100644 index 00000000000000..ffca2ac246dd40 --- /dev/null +++ b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/AppParameters.java @@ -0,0 +1,32 @@ +/* + * 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. + * + */ +package com.chip.casting; + +public class AppParameters { + public static final int MIN_ROTATING_DEVICE_ID_UNIQUE_ID_LENGTH = 16; + + private byte[] rotatingDeviceIdUniqueId; + + public void setRotatingDeviceIdUniqueId(byte[] rotatingDeviceIdUniqueId) { + this.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueId; + } + + public byte[] getRotatingDeviceIdUniqueId() { + return rotatingDeviceIdUniqueId; + } +} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/DiscoveredNodeData.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/DiscoveredNodeData.java index 982fbd84800671..b8a051036edd54 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/DiscoveredNodeData.java +++ b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/DiscoveredNodeData.java @@ -47,6 +47,8 @@ public class DiscoveredNodeData { private int numIPs; private List ipAddresses; + private VideoPlayer connectableVideoPlayer; + public DiscoveredNodeData(NsdServiceInfo serviceInfo) { Map attributes = serviceInfo.getAttributes(); this.deviceName = new String(attributes.get(KEY_DEVICE_NAME), StandardCharsets.UTF_8); @@ -69,6 +71,18 @@ public DiscoveredNodeData(NsdServiceInfo serviceInfo) { this.numIPs = 1; } + void setConnectableVideoPlayer(VideoPlayer videoPlayer) { + this.connectableVideoPlayer = videoPlayer; + } + + public boolean isPreCommissioned() { + return connectableVideoPlayer != null; + } + + public VideoPlayer toConnectableVideoPlayer() { + return connectableVideoPlayer; + } + public String getHostName() { return hostName; } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdDiscoveryListener.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdDiscoveryListener.java index cbc2ccadbad571..5a0f48550634f0 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdDiscoveryListener.java +++ b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdDiscoveryListener.java @@ -28,6 +28,7 @@ public class NsdDiscoveryListener implements NsdManager.DiscoveryListener { private final NsdManager nsdManager; private final String targetServiceType; private final List deviceTypeFilter; + private final List preCommissionedVideoPlayers; private final SuccessCallback successCallback; private final FailureCallback failureCallback; @@ -35,11 +36,13 @@ public NsdDiscoveryListener( NsdManager nsdManager, String targetServiceType, List deviceTypeFilter, + List preCommissionedVideoPlayers, SuccessCallback successCallback, FailureCallback failureCallback) { this.nsdManager = nsdManager; this.targetServiceType = targetServiceType; this.deviceTypeFilter = deviceTypeFilter; + this.preCommissionedVideoPlayers = preCommissionedVideoPlayers; this.successCallback = successCallback; this.failureCallback = failureCallback; } @@ -55,7 +58,12 @@ public void onServiceFound(NsdServiceInfo service) { if (service.getServiceType().equals(targetServiceType)) { nsdManager.resolveService( service, - new NsdResolveListener(nsdManager, deviceTypeFilter, successCallback, failureCallback)); + new NsdResolveListener( + nsdManager, + deviceTypeFilter, + preCommissionedVideoPlayers, + successCallback, + failureCallback)); } else { Log.d(TAG, "Ignoring discovered service: " + service.toString()); } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdResolveListener.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdResolveListener.java index 6275ad2b491a29..55de0226489427 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdResolveListener.java +++ b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/NsdResolveListener.java @@ -28,16 +28,24 @@ public class NsdResolveListener implements NsdManager.ResolveListener { private final NsdManager nsdManager; private final List deviceTypeFilter; + private final List preCommissionedVideoPlayers; private final SuccessCallback successCallback; private final FailureCallback failureCallback; public NsdResolveListener( NsdManager nsdManager, List deviceTypeFilter, + List preCommissionedVideoPlayers, SuccessCallback successCallback, FailureCallback failureCallback) { this.nsdManager = nsdManager; this.deviceTypeFilter = deviceTypeFilter; + this.preCommissionedVideoPlayers = preCommissionedVideoPlayers; + if (preCommissionedVideoPlayers != null) { + for (VideoPlayer videoPlayer : preCommissionedVideoPlayers) { + Log.d(TAG, "Precommissioned video player: " + videoPlayer); + } + } this.successCallback = successCallback; this.failureCallback = failureCallback; } @@ -48,6 +56,7 @@ public void onServiceResolved(NsdServiceInfo serviceInfo) { Log.d(TAG, "DiscoveredNodeData resolved: " + discoveredNodeData); if (isPassingDeviceTypeFilter(discoveredNodeData)) { + addCommissioningInfo(discoveredNodeData); successCallback.handle(discoveredNodeData); } else { Log.d( @@ -62,9 +71,9 @@ public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) { switch (errorCode) { case NsdManager.FAILURE_ALREADY_ACTIVE: Log.e(TAG, "NsdResolveListener FAILURE_ALREADY_ACTIVE - Service: " + serviceInfo); - nsdManager.resolveService( - serviceInfo, - new NsdResolveListener(nsdManager, deviceTypeFilter, successCallback, failureCallback)); + failureCallback.handle( + new MatterError( + 3, "NsdResolveListener FAILURE_ALREADY_ACTIVE - Service: " + serviceInfo)); break; case NsdManager.FAILURE_INTERNAL_ERROR: Log.e(TAG, "NsdResolveListener FAILURE_INTERNAL_ERROR - Service: " + serviceInfo); @@ -85,4 +94,23 @@ private boolean isPassingDeviceTypeFilter(DiscoveredNodeData discoveredNodeData) || deviceTypeFilter.isEmpty() || deviceTypeFilter.contains(discoveredNodeData.getDeviceType()); } + + private void addCommissioningInfo(DiscoveredNodeData discoveredNodeData) { + if (preCommissionedVideoPlayers != null) { + for (VideoPlayer videoPlayer : preCommissionedVideoPlayers) { + if (videoPlayer.isSameAs(discoveredNodeData)) { + Log.d( + TAG, + "Matching Video Player with the following information found for DiscoveredNodeData" + + videoPlayer); + discoveredNodeData.setConnectableVideoPlayer(videoPlayer); + return; + } + } + } + Log.d( + TAG, + "No matching VideoPlayers found from the cache for new DiscoveredNodeData: " + + discoveredNodeData); + } } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TvCastingApp.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TvCastingApp.java index 364b3a1502be0b..20235ae21b38e2 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TvCastingApp.java +++ b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/TvCastingApp.java @@ -32,7 +32,7 @@ public class TvCastingApp { private final String TARGET_SERVICE_TYPE = "_matterd._udp."; private final List DEVICE_TYPE_FILTER = Arrays.asList(35L); // Video player = 35; - public native void init(); + public native boolean init(AppParameters appParameters); public native void setDACProvider(DACProvider provider); @@ -47,11 +47,14 @@ public void discoverVideoPlayerCommissioners( multicastLock.setReferenceCounted(true); multicastLock.acquire(); + List preCommissionedVideoPlayers = readCachedVideoPlayers(); + NsdDiscoveryListener nsdDiscoveryListener = new NsdDiscoveryListener( nsdManager, TARGET_SERVICE_TYPE, DEVICE_TYPE_FILTER, + preCommissionedVideoPlayers, discoverySuccessCallback, discoveryFailureCallback); @@ -63,6 +66,7 @@ public void discoverVideoPlayerCommissioners( new Runnable() { @Override public void run() { + Log.d(TAG, "TvCastingApp stopping Video Player commissioner discovery"); nsdManager.stopServiceDiscovery(nsdDiscoveryListener); multicastLock.release(); } @@ -275,7 +279,7 @@ public native boolean keypadInput_sendKey( /** * APPLICATION BASIC * - *

TODO: Add APIs to subscribe to Application, Status and AllowedVendorList + *

TODO: Add APIs to subscribe to & read Application, Status and AllowedVendorList */ public native boolean applicationBasic_subscribeToVendorName( ContentApp contentApp, @@ -287,7 +291,7 @@ public native boolean applicationBasic_subscribeToVendorName( public native boolean applicationBasic_subscribeToVendorID( ContentApp contentApp, - SuccessCallback readSuccessHandler, + SuccessCallback readSuccessHandler, FailureCallback readFailureHandler, int minInterval, int maxInterval, @@ -303,7 +307,7 @@ public native boolean applicationBasic_subscribeToApplicationName( public native boolean applicationBasic_subscribeToProductID( ContentApp contentApp, - SuccessCallback readSuccessHandler, + SuccessCallback readSuccessHandler, FailureCallback readFailureHandler, int minInterval, int maxInterval, @@ -317,6 +321,31 @@ public native boolean applicationBasic_subscribeToApplicationVersion( int maxInterval, SubscriptionEstablishedCallback subscriptionEstablishedHandler); + public native boolean applicationBasic_readVendorName( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler); + + public native boolean applicationBasic_readVendorID( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler); + + public native boolean applicationBasic_readApplicationName( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler); + + public native boolean applicationBasic_readProductID( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandler); + + public native boolean applicationBasic_readApplicationVersion( + ContentApp contentApp, + SuccessCallback readSuccessHandler, + FailureCallback readFailureHandlerr); + static { System.loadLibrary("TvCastingApp"); } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/VideoPlayer.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/VideoPlayer.java index 85c487850cd08d..9ba557c910b704 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/VideoPlayer.java +++ b/examples/tv-casting-app/android/App/app/src/main/jni/com/chip/casting/VideoPlayer.java @@ -17,10 +17,15 @@ */ package com.chip.casting; +import java.net.InetAddress; +import java.util.HashSet; import java.util.List; import java.util.Objects; +import java.util.Set; public class VideoPlayer { + private static final String TAG = VideoPlayer.class.getSimpleName(); + private long nodeId; private byte fabricIndex; private String deviceName; @@ -30,6 +35,9 @@ public class VideoPlayer { private List contentApps; private boolean isConnected = false; + private int numIPs; + private List ipAddresses; + private boolean isInitialized = false; public VideoPlayer( @@ -40,6 +48,8 @@ public VideoPlayer( int productId, int deviceType, List contentApps, + int numIPs, + List ipAddresses, boolean isConnected) { this.nodeId = nodeId; this.fabricIndex = fabricIndex; @@ -49,9 +59,43 @@ public VideoPlayer( this.deviceType = deviceType; this.contentApps = contentApps; this.isConnected = isConnected; + this.numIPs = numIPs; + this.ipAddresses = ipAddresses; this.isInitialized = true; } + public boolean isSameAs(DiscoveredNodeData discoveredNodeData) { + // return false because 'this' VideoPlayer is not null + if (discoveredNodeData == null) { + return false; + } + + // return false because deviceNames are different + if (Objects.equals(deviceName, discoveredNodeData.getDeviceName()) == false) { + return false; + } + + // return false because not even a single IP Address matches + if (ipAddresses != null) { + boolean matchFound = false; + Set discoveredNodeDataIpAddressSet = + new HashSet(discoveredNodeData.getIpAddresses()); + for (InetAddress videoPlayerIpAddress : ipAddresses) { + if (discoveredNodeDataIpAddressSet.contains(videoPlayerIpAddress)) { + matchFound = true; + break; + } + } + + if (!matchFound) { + return false; + } + } + + // otherwise, return true + return true; + } + public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; @@ -78,8 +122,18 @@ public java.lang.String toString() { + vendorId + ", productId=" + productId + + ", deviceType=" + + deviceType + + ", contentApps=" + + contentApps + ", isConnected=" + isConnected + + ", numIPs=" + + numIPs + + ", ipAddresses=" + + ipAddresses + + ", isInitialized=" + + isInitialized + '}'; } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.cpp index db59f4a08d1276..8112c6b2acfb90 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.cpp @@ -22,6 +22,27 @@ #include #include +CHIP_ERROR convertJAppParametersToCppAppParams(jobject appParameters, AppParams & outAppParams) +{ + ChipLogProgress(AppServer, "convertJContentAppToTargetEndpointInfo called"); + JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturnError(appParameters != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + + jclass jAppParametersClass; + ReturnErrorOnFailure( + chip::JniReferences::GetInstance().GetClassRef(env, "com/chip/casting/AppParameters", jAppParametersClass)); + + jfieldID jRotatingDeviceIdUniqueIdField = env->GetFieldID(jAppParametersClass, "rotatingDeviceIdUniqueId", "[B"); + jobject jRotatingDeviceIdUniqueId = env->GetObjectField(appParameters, jRotatingDeviceIdUniqueIdField); + if (jRotatingDeviceIdUniqueId != nullptr) + { + chip::JniByteArray jniRotatingDeviceIdUniqueIdByteArray(env, static_cast(jRotatingDeviceIdUniqueId)); + outAppParams.SetRotatingDeviceIdUniqueId(MakeOptional(jniRotatingDeviceIdUniqueIdByteArray.byteSpan())); + } + + return CHIP_NO_ERROR; +} + CHIP_ERROR convertJContentAppToTargetEndpointInfo(jobject contentApp, TargetEndpointInfo & outTargetEndpointInfo) { ChipLogProgress(AppServer, "convertJContentAppToTargetEndpointInfo called"); @@ -99,14 +120,14 @@ CHIP_ERROR convertJVideoPlayerToTargetVideoPlayerInfo(jobject videoPlayer, Targe jfieldID jFabricIndexField = env->GetFieldID(jVideoPlayerClass, "fabricIndex", "B"); chip::FabricIndex fabricIndex = static_cast(env->GetByteField(videoPlayer, jFabricIndexField)); - jfieldID jVendorIdField = env->GetFieldID(jVideoPlayerClass, "vendorId", "S"); - uint16_t vendorId = static_cast(env->GetShortField(videoPlayer, jVendorIdField)); + jfieldID jVendorIdField = env->GetFieldID(jVideoPlayerClass, "vendorId", "I"); + uint16_t vendorId = static_cast(env->GetIntField(videoPlayer, jVendorIdField)); - jfieldID jProductIdField = env->GetFieldID(jVideoPlayerClass, "productId", "S"); - uint16_t productId = static_cast(env->GetShortField(videoPlayer, jProductIdField)); + jfieldID jProductIdField = env->GetFieldID(jVideoPlayerClass, "productId", "I"); + uint16_t productId = static_cast(env->GetIntField(videoPlayer, jProductIdField)); - jfieldID jDeviceType = env->GetFieldID(jVideoPlayerClass, "deviceType", "S"); - uint16_t deviceType = static_cast(env->GetShortField(videoPlayer, jDeviceType)); + jfieldID jDeviceType = env->GetFieldID(jVideoPlayerClass, "deviceType", "I"); + uint16_t deviceType = static_cast(env->GetIntField(videoPlayer, jDeviceType)); jfieldID getDeviceNameField = env->GetFieldID(jVideoPlayerClass, "deviceName", "Ljava/lang/String;"); jstring jDeviceName = static_cast(env->GetObjectField(videoPlayer, getDeviceNameField)); @@ -152,7 +173,7 @@ CHIP_ERROR convertTargetVideoPlayerInfoToJVideoPlayer(TargetVideoPlayerInfo * ta ReturnErrorOnFailure( chip::JniReferences::GetInstance().GetClassRef(env, "com/chip/casting/VideoPlayer", jVideoPlayerClass)); jmethodID jVideoPlayerConstructor = - env->GetMethodID(jVideoPlayerClass, "", "(JBLjava/lang/String;IIILjava/util/List;Z)V"); + env->GetMethodID(jVideoPlayerClass, "", "(JBLjava/lang/String;IIILjava/util/List;ILjava/util/List;Z)V"); jobject jContentAppList = nullptr; TargetEndpointInfo * endpoints = targetVideoPlayerInfo->GetEndpoints(); @@ -166,11 +187,37 @@ CHIP_ERROR convertTargetVideoPlayerInfoToJVideoPlayer(TargetVideoPlayerInfo * ta chip::JniReferences::GetInstance().AddToList(jContentAppList, contentApp); } } - jstring deviceName = env->NewStringUTF(targetVideoPlayerInfo->GetDeviceName()); - outVideoPlayer = env->NewObject(jVideoPlayerClass, jVideoPlayerConstructor, targetVideoPlayerInfo->GetNodeId(), + + jstring deviceName = + targetVideoPlayerInfo->GetDeviceName() == nullptr ? nullptr : env->NewStringUTF(targetVideoPlayerInfo->GetDeviceName()); + + jobject jIPAddressList = nullptr; + const chip::Inet::IPAddress * ipAddresses = targetVideoPlayerInfo->GetIpAddresses(); + if (ipAddresses != nullptr) + { + chip::JniReferences::GetInstance().CreateArrayList(jIPAddressList); + for (size_t i = 0; i < targetVideoPlayerInfo->GetNumIPs() && i < chip::Dnssd::CommonResolutionData::kMaxIPAddresses; + i++) + { + char addrCString[chip::Inet::IPAddress::kMaxStringLength]; + ipAddresses[i].ToString(addrCString, chip::Inet::IPAddress::kMaxStringLength); + jstring jIPAddressStr = env->NewStringUTF(addrCString); + + jclass jIPAddressClass; + ReturnErrorOnFailure(chip::JniReferences::GetInstance().GetClassRef(env, "java/net/InetAddress", jIPAddressClass)); + jmethodID jGetByNameMid = + env->GetStaticMethodID(jIPAddressClass, "getByName", "(Ljava/lang/String;)Ljava/net/InetAddress;"); + jobject jIPAddress = env->CallStaticObjectMethod(jIPAddressClass, jGetByNameMid, jIPAddressStr); + + chip::JniReferences::GetInstance().AddToList(jIPAddressList, jIPAddress); + } + } + + outVideoPlayer = env->NewObject(jVideoPlayerClass, jVideoPlayerConstructor, targetVideoPlayerInfo->GetNodeId(), targetVideoPlayerInfo->GetFabricIndex(), deviceName, targetVideoPlayerInfo->GetVendorId(), targetVideoPlayerInfo->GetProductId(), targetVideoPlayerInfo->GetDeviceType(), - jContentAppList, targetVideoPlayerInfo->GetOperationalDeviceProxy() != nullptr); + jContentAppList, targetVideoPlayerInfo->GetNumIPs(), jIPAddressList, + targetVideoPlayerInfo->GetOperationalDeviceProxy() != nullptr); } return CHIP_NO_ERROR; } diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.h index 192ffa2b65961d..a2c59596d9e9e5 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.h +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/ConversionUtils.h @@ -16,11 +16,14 @@ */ #pragma once +#include "AppParams.h" #include "TargetEndpointInfo.h" #include "TargetVideoPlayerInfo.h" #include +CHIP_ERROR convertJAppParametersToCppAppParams(jobject appParameters, AppParams & outAppParams); + CHIP_ERROR convertJContentAppToTargetEndpointInfo(jobject contentApp, TargetEndpointInfo & outTargetEndpointInfo); CHIP_ERROR convertTargetEndpointInfoToJContentApp(TargetEndpointInfo * targetEndpointInfo, jobject & outContentApp); diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp index 60a10ea2696f5e..862334ae1ee4cb 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.cpp @@ -178,7 +178,7 @@ jobject OnConnectionSuccessHandlerJNI::ConvertToJObject(TargetVideoPlayerInfo * { ChipLogError(AppServer, "OnConnectionSuccessHandlerJNI::ConvertToJObject failed with %" CHIP_ERROR_FORMAT, err.Format()); } - return nullptr; + return videoPlayer; } jobject OnNewOrUpdatedEndpointHandlerJNI::ConvertToJObject(TargetEndpointInfo * targetEndpointInfo) @@ -383,7 +383,7 @@ jobject VendorIDSuccessHandlerJNI::ConvertToJObject( chip::app::Clusters::ApplicationBasic::Attributes::VendorID::TypeInfo::DecodableArgType responseData) { ChipLogProgress(AppServer, "VendorIDSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToShortJObject(responseData); + return ConvertToIntegerJObject(responseData); } jobject ApplicationNameSuccessHandlerJNI::ConvertToJObject( @@ -397,7 +397,7 @@ jobject ProductIDSuccessHandlerJNI::ConvertToJObject( chip::app::Clusters::ApplicationBasic::Attributes::ProductID::TypeInfo::DecodableArgType responseData) { ChipLogProgress(AppServer, "ProductIDSuccessHandlerJNI::ConvertToJObject called"); - return ConvertToShortJObject(responseData); + return ConvertToIntegerJObject(responseData); } jobject ApplicationVersionSuccessHandlerJNI::ConvertToJObject( diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h index d78988699b88f9..3261aa60874ad2 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/MatterCallbackHandler-JNI.h @@ -235,7 +235,7 @@ class VendorIDSuccessHandlerJNI : public SuccessHandlerJNI { public: - VendorIDSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Short;)V") {} + VendorIDSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Integer;)V") {} jobject ConvertToJObject(chip::app::Clusters::ApplicationBasic::Attributes::VendorID::TypeInfo::DecodableArgType responseData); }; @@ -252,7 +252,7 @@ class ProductIDSuccessHandlerJNI : public SuccessHandlerJNI { public: - ProductIDSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Short;)V") {} + ProductIDSuccessHandlerJNI() : SuccessHandlerJNI("(Ljava/lang/Integer;)V") {} jobject ConvertToJObject(chip::app::Clusters::ApplicationBasic::Attributes::ProductID::TypeInfo::DecodableArgType responseData); }; diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.cpp index 928f489e2b84a7..33d7c753bf9042 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.cpp @@ -52,6 +52,36 @@ void JNI_OnUnload(JavaVM * jvm, void * reserved) return AndroidAppServerJNI_OnUnload(jvm, reserved); } +JNI_METHOD(jboolean, init)(JNIEnv *, jobject, jobject jAppParameters) +{ + chip::DeviceLayer::StackLock lock; + ChipLogProgress(AppServer, "JNI_METHOD init called"); + + CHIP_ERROR err = CHIP_NO_ERROR; + if (jAppParameters == nullptr) + { + err = CastingServer::GetInstance()->Init(); + } + else + { + AppParams appParams; + err = convertJAppParametersToCppAppParams(jAppParameters, appParams); + VerifyOrExit(err == CHIP_NO_ERROR, + ChipLogError(AppServer, "Conversion of AppParameters from jobject to Cpp type failed: %" CHIP_ERROR_FORMAT, + err.Format())); + err = CastingServer::GetInstance()->Init(&appParams); + } + VerifyOrExit(err == CHIP_NO_ERROR, + ChipLogError(AppServer, "Call to CastingServer::GetInstance()->Init() failed: %" CHIP_ERROR_FORMAT, err.Format())); +exit: + if (err != CHIP_NO_ERROR) + { + return false; + } + + return true; +} + JNI_METHOD(void, setDACProvider)(JNIEnv *, jobject, jobject provider) { if (!chip::Credentials::IsDeviceAttestationCredentialsProviderSet()) @@ -202,6 +232,7 @@ JNI_METHOD(jobject, getActiveTargetVideoPlayers)(JNIEnv * env, jobject) JNI_METHOD(jboolean, sendUserDirectedCommissioningRequest)(JNIEnv * env, jobject, jstring addressJStr, jint port) { + chip::DeviceLayer::StackLock lock; ChipLogProgress(AppServer, "JNI_METHOD sendUserDirectedCommissioningRequest called with port %d", port); Inet::IPAddress addressInet; JniUtfString addressJniString(env, addressJStr); @@ -225,6 +256,7 @@ JNI_METHOD(jboolean, sendUserDirectedCommissioningRequest)(JNIEnv * env, jobject JNI_METHOD(jboolean, sendCommissioningRequest)(JNIEnv * env, jobject, jobject jDiscoveredNodeData) { + chip::DeviceLayer::StackLock lock; ChipLogProgress(AppServer, "JNI_METHOD sendCommissioningRequest called"); chip::Dnssd::DiscoveredNodeData commissioner; @@ -245,12 +277,6 @@ JNI_METHOD(jboolean, sendCommissioningRequest)(JNIEnv * env, jobject, jobject jD return true; } -JNI_METHOD(void, init)(JNIEnv *, jobject) -{ - ChipLogProgress(AppServer, "JNI_METHOD init called"); - CastingServer::GetInstance()->Init(); -} - JNI_METHOD(jboolean, contentLauncherLaunchURL) (JNIEnv * env, jobject, jobject contentApp, jstring contentUrl, jstring contentDisplayStr, jobject jResponseHandler) { @@ -411,9 +437,7 @@ JNI_METHOD(jboolean, contentLauncher_1subscribeToSupportedStreamingProtocols) err = TvCastingAppJNIMgr().getSupportedStreamingProtocolsSuccessHandler().SetUp(env, jReadSuccessHandler); VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); - err = TvCastingAppJNIMgr() - .getSubscriptionReadFailureHandler(ContentLauncher_SupportedStreamingProtocols) - .SetUp(env, jReadFailureHandler); + err = TvCastingAppJNIMgr().getReadFailureHandler(ContentLauncher_SupportedStreamingProtocols).SetUp(env, jReadFailureHandler); VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SubscriptionReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); @@ -430,7 +454,7 @@ JNI_METHOD(jboolean, contentLauncher_1subscribeToSupportedStreamingProtocols) TvCastingAppJNIMgr().getSupportedStreamingProtocolsSuccessHandler().Handle(responseData); }, [](void * context, CHIP_ERROR err) { - TvCastingAppJNIMgr().getSubscriptionReadFailureHandler(ContentLauncher_SupportedStreamingProtocols).Handle(err); + TvCastingAppJNIMgr().getReadFailureHandler(ContentLauncher_SupportedStreamingProtocols).Handle(err); }, static_cast(minInterval), static_cast(maxInterval), [](void * context) { @@ -1742,3 +1766,209 @@ JNI_METHOD(jboolean, applicationBasic_1subscribeToApplicationVersion) return true; } + +JNI_METHOD(jboolean, applicationBasic_1readVendorName) +(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler) +{ + chip::DeviceLayer::StackLock lock; + + ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1readVendorName called"); + + TargetEndpointInfo endpoint; + CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); + VerifyOrExit(err == CHIP_NO_ERROR, + ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, + err.Format())); + + err = TvCastingAppJNIMgr().getReadVendorNameSuccessHandler().SetUp(env, jReadSuccessHandler); + VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); + + err = TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_VendorName).SetUp(env, jReadFailureHandler); + VerifyOrExit(CHIP_NO_ERROR == err, + ChipLogError(AppServer, "ReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); + + err = CastingServer::GetInstance()->ApplicationBasic_ReadVendorName( + &endpoint, nullptr, + [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::VendorName::TypeInfo::DecodableArgType responseData) { + TvCastingAppJNIMgr().getVendorNameSuccessHandler().Handle(responseData); + }, + [](void * context, CHIP_ERROR err) { + TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_VendorName).Handle(err); + }); + + VerifyOrExit( + CHIP_NO_ERROR == err, + ChipLogError(AppServer, "CastingServer.applicationBasic_1readVendorName failed %" CHIP_ERROR_FORMAT, err.Format())); + +exit: + if (err != CHIP_NO_ERROR) + { + return false; + } + + return true; +} + +JNI_METHOD(jboolean, applicationBasic_1readVendorID) +(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler) +{ + chip::DeviceLayer::StackLock lock; + + ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1readVendorID called"); + + TargetEndpointInfo endpoint; + CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); + VerifyOrExit(err == CHIP_NO_ERROR, + ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, + err.Format())); + + err = TvCastingAppJNIMgr().getVendorIDSuccessHandler().SetUp(env, jReadSuccessHandler); + VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); + + err = TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_VendorID).SetUp(env, jReadFailureHandler); + VerifyOrExit(CHIP_NO_ERROR == err, + ChipLogError(AppServer, "ReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); + + err = CastingServer::GetInstance()->ApplicationBasic_ReadVendorID( + &endpoint, nullptr, + [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::VendorID::TypeInfo::DecodableArgType responseData) { + TvCastingAppJNIMgr().getVendorIDSuccessHandler().Handle(responseData); + }, + [](void * context, CHIP_ERROR err) { TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_VendorID).Handle(err); }); + + VerifyOrExit(CHIP_NO_ERROR == err, + ChipLogError(AppServer, "CastingServer.applicationBasic_ReadVendorID failed %" CHIP_ERROR_FORMAT, err.Format())); + +exit: + if (err != CHIP_NO_ERROR) + { + return false; + } + + return true; +} + +JNI_METHOD(jboolean, applicationBasic_1readApplicationName) +(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler) +{ + chip::DeviceLayer::StackLock lock; + + ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1readApplicationName called"); + + TargetEndpointInfo endpoint; + CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); + VerifyOrExit(err == CHIP_NO_ERROR, + ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, + err.Format())); + + err = TvCastingAppJNIMgr().getApplicationNameSuccessHandler().SetUp(env, jReadSuccessHandler); + VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); + + err = TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ApplicationName).SetUp(env, jReadFailureHandler); + VerifyOrExit(CHIP_NO_ERROR == err, + ChipLogError(AppServer, "ReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); + + err = CastingServer::GetInstance()->ApplicationBasic_ReadApplicationName( + &endpoint, nullptr, + [](void * context, + chip::app::Clusters::ApplicationBasic::Attributes::ApplicationName::TypeInfo::DecodableArgType responseData) { + TvCastingAppJNIMgr().getApplicationNameSuccessHandler().Handle(responseData); + }, + [](void * context, CHIP_ERROR err) { + TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ApplicationName).Handle(err); + }); + + VerifyOrExit( + CHIP_NO_ERROR == err, + ChipLogError(AppServer, "CastingServer.applicationBasic_ReadApplicationName failed %" CHIP_ERROR_FORMAT, err.Format())); + +exit: + if (err != CHIP_NO_ERROR) + { + return false; + } + + return true; +} + +JNI_METHOD(jboolean, applicationBasic_1readProductID) +(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler) +{ + chip::DeviceLayer::StackLock lock; + + ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1readProductID called"); + + TargetEndpointInfo endpoint; + CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); + VerifyOrExit(err == CHIP_NO_ERROR, + ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, + err.Format())); + + err = TvCastingAppJNIMgr().getProductIDSuccessHandler().SetUp(env, jReadSuccessHandler); + VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); + + err = TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ProductID).SetUp(env, jReadFailureHandler); + VerifyOrExit(CHIP_NO_ERROR == err, + ChipLogError(AppServer, "ReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); + + err = CastingServer::GetInstance()->ApplicationBasic_ReadProductID( + &endpoint, nullptr, + [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::ProductID::TypeInfo::DecodableArgType responseData) { + TvCastingAppJNIMgr().getProductIDSuccessHandler().Handle(responseData); + }, + [](void * context, CHIP_ERROR err) { TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ProductID).Handle(err); }); + + VerifyOrExit(CHIP_NO_ERROR == err, + ChipLogError(AppServer, "CastingServer.applicationBasic_ReadProductID failed %" CHIP_ERROR_FORMAT, err.Format())); + +exit: + if (err != CHIP_NO_ERROR) + { + return false; + } + + return true; +} + +JNI_METHOD(jboolean, applicationBasic_1readApplicationVersion) +(JNIEnv * env, jobject, jobject contentApp, jobject jReadSuccessHandler, jobject jReadFailureHandler) +{ + chip::DeviceLayer::StackLock lock; + + ChipLogProgress(AppServer, "JNI_METHOD applicationBasic_1readApplicationVersion called"); + + TargetEndpointInfo endpoint; + CHIP_ERROR err = convertJContentAppToTargetEndpointInfo(contentApp, endpoint); + VerifyOrExit(err == CHIP_NO_ERROR, + ChipLogError(AppServer, "Conversion from jobject contentApp to TargetEndpointInfo * failed: %" CHIP_ERROR_FORMAT, + err.Format())); + + err = TvCastingAppJNIMgr().getApplicationVersionSuccessHandler().SetUp(env, jReadSuccessHandler); + VerifyOrExit(CHIP_NO_ERROR == err, ChipLogError(AppServer, "SuccessHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); + + err = TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ApplicationVersion).SetUp(env, jReadFailureHandler); + VerifyOrExit(CHIP_NO_ERROR == err, + ChipLogError(AppServer, "ReadFailureHandler.SetUp failed %" CHIP_ERROR_FORMAT, err.Format())); + + err = CastingServer::GetInstance()->ApplicationBasic_ReadApplicationVersion( + &endpoint, nullptr, + [](void * context, + chip::app::Clusters::ApplicationBasic::Attributes::ApplicationVersion::TypeInfo::DecodableArgType responseData) { + TvCastingAppJNIMgr().getApplicationVersionSuccessHandler().Handle(responseData); + }, + [](void * context, CHIP_ERROR err) { + TvCastingAppJNIMgr().getReadFailureHandler(ApplicationBasic_ApplicationVersion).Handle(err); + }); + + VerifyOrExit( + CHIP_NO_ERROR == err, + ChipLogError(AppServer, "CastingServer.applicationBasic_ReadApplicationVersion failed %" CHIP_ERROR_FORMAT, err.Format())); + +exit: + if (err != CHIP_NO_ERROR) + { + return false; + } + + return true; +} diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.h b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.h index 71bd0bddb466be..7d2b384b3718ae 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.h +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/TvCastingApp-JNI.h @@ -45,6 +45,8 @@ class TvCastingAppJNI return mMediaCommandResponseHandler[name]; } + FailureHandlerJNI & getReadFailureHandler(enum MediaAttributeName name) { return mReadFailureHandler[name]; } + FailureHandlerJNI & getSubscriptionReadFailureHandler(enum MediaAttributeName name) { return mSubscriptionReadFailureHandler[name]; @@ -80,6 +82,15 @@ class TvCastingAppJNI ProductIDSuccessHandlerJNI & getProductIDSuccessHandler() { return mProductIDSuccessHandlerJNI; } ApplicationVersionSuccessHandlerJNI & getApplicationVersionSuccessHandler() { return mApplicationVersionSuccessHandlerJNI; } + VendorNameSuccessHandlerJNI & getReadVendorNameSuccessHandler() { return mReadVendorNameSuccessHandlerJNI; } + VendorIDSuccessHandlerJNI & getReadVendorIDSuccessHandler() { return mReadVendorIDSuccessHandlerJNI; } + ApplicationNameSuccessHandlerJNI & getReadApplicationNameSuccessHandler() { return mReadApplicationNameSuccessHandlerJNI; } + ProductIDSuccessHandlerJNI & getReadProductIDSuccessHandler() { return mReadProductIDSuccessHandlerJNI; } + ApplicationVersionSuccessHandlerJNI & getReadApplicationVersionSuccessHandler() + { + return mReadApplicationVersionSuccessHandlerJNI; + } + private: friend TvCastingAppJNI & TvCastingAppJNIMgr(); @@ -97,6 +108,7 @@ class TvCastingAppJNI MatterCallbackHandlerJNI mMediaCommandResponseHandler[MEDIA_COMMAND_COUNT]; FailureHandlerJNI mSubscriptionReadFailureHandler[MEDIA_ATTRIBUTE_COUNT]; SubscriptionEstablishedHandlerJNI mSubscriptionEstablishedHandler[MEDIA_ATTRIBUTE_COUNT]; + FailureHandlerJNI mReadFailureHandler[MEDIA_ATTRIBUTE_COUNT]; CurrentStateSuccessHandlerJNI mCurrentStateSuccessHandlerJNI; DurationSuccessHandlerJNI mDurationSuccessHandlerJNI; @@ -119,6 +131,12 @@ class TvCastingAppJNI ApplicationNameSuccessHandlerJNI mApplicationNameSuccessHandlerJNI; ProductIDSuccessHandlerJNI mProductIDSuccessHandlerJNI; ApplicationVersionSuccessHandlerJNI mApplicationVersionSuccessHandlerJNI; + + VendorNameSuccessHandlerJNI mReadVendorNameSuccessHandlerJNI; + VendorIDSuccessHandlerJNI mReadVendorIDSuccessHandlerJNI; + ApplicationNameSuccessHandlerJNI mReadApplicationNameSuccessHandlerJNI; + ProductIDSuccessHandlerJNI mReadProductIDSuccessHandlerJNI; + ApplicationVersionSuccessHandlerJNI mReadApplicationVersionSuccessHandlerJNI; }; inline class TvCastingAppJNI & TvCastingAppJNIMgr() diff --git a/examples/tv-casting-app/android/App/app/src/main/res/layout/fragment_commissioning.xml b/examples/tv-casting-app/android/App/app/src/main/res/layout/fragment_connection.xml similarity index 94% rename from examples/tv-casting-app/android/App/app/src/main/res/layout/fragment_commissioning.xml rename to examples/tv-casting-app/android/App/app/src/main/res/layout/fragment_connection.xml index c75708136c4090..f0381f3e5ae773 100644 --- a/examples/tv-casting-app/android/App/app/src/main/res/layout/fragment_commissioning.xml +++ b/examples/tv-casting-app/android/App/app/src/main/res/layout/fragment_connection.xml @@ -3,7 +3,7 @@ xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" - tools:context=".CommissioningFragment" + tools:context=".ConnectionFragment" android:padding="10sp"> + +#ifndef AppParameters_h +#define AppParameters_h + +@interface AppParameters : NSObject + +@property NSData * rotatingDeviceIdUniqueId; + +- (AppParameters *)initWithRotatingDeviceIdUniqueId:(NSData *)rotatingDeviceIdUniqueId; + +@end + +#endif /* AppParameters_h */ diff --git a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/AppParameters.m b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/AppParameters.m new file mode 100644 index 00000000000000..287d4ab40fd57c --- /dev/null +++ b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/AppParameters.m @@ -0,0 +1,33 @@ +/** + * + * 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. + */ + +#import + +#import "AppParameters.h" + +@implementation AppParameters + +- (AppParameters *)initWithRotatingDeviceIdUniqueId:(NSData *)rotatingDeviceIdUniqueId +{ + self = [super init]; + if (self) { + _rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueId; + } + return self; +} + +@end diff --git a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/CastingServerBridge.h b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/CastingServerBridge.h index f828ae5f01c70f..b91f930f5327a7 100644 --- a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/CastingServerBridge.h +++ b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/CastingServerBridge.h @@ -15,6 +15,7 @@ * limitations under the License. */ +#import "AppParameters.h" #import "ContentApp.h" #import "ContentLauncherTypes.h" #import "DiscoveredNodeData.h" @@ -32,6 +33,10 @@ + (CastingServerBridge * _Nullable)getSharedInstance; +- (void)initApp:(AppParameters * _Nullable)appParameters + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + initAppStatusHandler:(nullable void (^)(bool))initAppStatusHandler; + /*! @brief Browse for on-network commissioner TVs @@ -1003,6 +1008,100 @@ successCallback:(void (^_Nonnull)(NSString * _Nonnull))successCallback failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback subscriptionEstablishedCallback:(void (^_Nonnull)())subscriptionEstablishedCallback; -@end +/*! + @brief Read ApplicationBasic:VendorName + + @param contentApp Content app endpoint to target + + @param clientQueue Queue to invoke callbacks on + + @param requestSentHandler Handler to call on sending the request + + @param successCallback Callback for when a read report is successfully received + + @param failureCallback Callback for when there is a failure in receiving a read report + */ +- (void)applicationBasic_readVendorName:(ContentApp * _Nonnull)contentApp + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + requestSentHandler:(void (^_Nonnull)(MatterError * _Nonnull))requestSentHandler + successCallback:(void (^_Nonnull)(NSString * _Nonnull))successCallback + failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback; + +/*! + @brief Read ApplicationBasic:VendorID + + @param contentApp Content app endpoint to target + + @param clientQueue Queue to invoke callbacks on + + @param requestSentHandler Handler to call on sending the request + + @param successCallback Callback for when a read report is successfully received + + @param failureCallback Callback for when there is a failure in receiving a read report + */ +- (void)applicationBasic_readVendorID:(ContentApp * _Nonnull)contentApp + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + requestSentHandler:(void (^_Nonnull)(MatterError * _Nonnull))requestSentHandler + successCallback:(void (^_Nonnull)(NSNumber * _Nonnull))successCallback + failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback; + +/*! + @brief Read ApplicationBasic:ApplicationName + + @param contentApp Content app endpoint to target + + @param clientQueue Queue to invoke callbacks on + + @param requestSentHandler Handler to call on sending the request + + @param successCallback Callback for when a read report is successfully received + + @param failureCallback Callback for when there is a failure in receiving a read report + */ +- (void)applicationBasic_readApplicationName:(ContentApp * _Nonnull)contentApp + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + requestSentHandler:(void (^_Nonnull)(MatterError * _Nonnull))requestSentHandler + successCallback:(void (^_Nonnull)(NSString * _Nonnull))successCallback + failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback; + +/*! + @brief Read ApplicationBasic:ProductID + + @param contentApp Content app endpoint to target + + @param clientQueue Queue to invoke callbacks on + + @param requestSentHandler Handler to call on sending the request + + @param successCallback Callback for when a read report is successfully received + + @param failureCallback Callback for when there is a failure in receiving a read report + */ +- (void)applicationBasic_readProductID:(ContentApp * _Nonnull)contentApp + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + requestSentHandler:(void (^_Nonnull)(MatterError * _Nonnull))requestSentHandler + successCallback:(void (^_Nonnull)(uint16_t))successCallback + failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback; + +/*! + @brief Read ApplicationBasic:ApplicationVersion + + @param contentApp Content app endpoint to target + + @param clientQueue Queue to invoke callbacks on + + @param requestSentHandler Handler to call on sending the request + + @param successCallback Callback for when a read report is successfully received + + @param failureCallback Callback for when there is a failure in receiving a read report + */ +- (void)applicationBasic_readApplicationVersion:(ContentApp * _Nonnull)contentApp + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + requestSentHandler:(void (^_Nonnull)(MatterError * _Nonnull))requestSentHandler + successCallback:(void (^_Nonnull)(NSString * _Nonnull))successCallback + failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback; +@end #endif /* CastingServerBridge_h */ diff --git a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/CastingServerBridge.mm b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/CastingServerBridge.mm index dd89e32cbd42fe..c4ffd87f2a09d8 100644 --- a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/CastingServerBridge.mm +++ b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/CastingServerBridge.mm @@ -54,6 +54,10 @@ @interface CastingServerBridge () @property NSMutableDictionary * subscriptionReadFailureCallbacks; +@property NSMutableDictionary * readSuccessCallbacks; + +@property NSMutableDictionary * readFailureCallbacks; + @end @implementation CastingServerBridge @@ -122,12 +126,35 @@ - (instancetype)init _subscriptionReadFailureCallbacks = [NSMutableDictionary dictionary]; chip::DeviceLayer::PlatformMgrImpl().StartEventLoopTask(); - - CastingServer::GetInstance()->Init(); } return self; } +- (void)initApp:(AppParameters * _Nullable)appParameters + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + initAppStatusHandler:(nullable void (^)(bool))initAppStatusHandler +{ + ChipLogProgress(AppServer, "CastingServerBridge().initApp() called"); + + dispatch_async(_chipWorkQueue, ^{ + bool initAppStatus = true; + + AppParams appParams; + + CHIP_ERROR err = CastingServer::GetInstance()->Init(); + if (err != CHIP_NO_ERROR) { + ChipLogError(AppServer, "CastingServerBridge().initApp() failed: %" CHIP_ERROR_FORMAT, err.Format()); + initAppStatus = false; + } + + dispatch_async(clientQueue, ^{ + initAppStatusHandler(initAppStatus); + }); + }); + + CastingServer::GetInstance()->Init(); +} + - (void)discoverCommissioners:(dispatch_queue_t _Nonnull)clientQueue discoveryRequestSentHandler:(nullable void (^)(bool))discoveryRequestSentHandler { @@ -153,11 +180,17 @@ - (void)getDiscoveredCommissioner:(int)index ChipLogProgress(AppServer, "CastingServerBridge().getDiscoveredCommissioner() called"); dispatch_async(_chipWorkQueue, ^{ + chip::Optional associatedConnectableVideoPlayer; DiscoveredNodeData * commissioner = nil; const chip::Dnssd::DiscoveredNodeData * cppDiscoveredNodeData - = CastingServer::GetInstance()->GetDiscoveredCommissioner(index); + = CastingServer::GetInstance()->GetDiscoveredCommissioner(index, associatedConnectableVideoPlayer); if (cppDiscoveredNodeData != nullptr) { commissioner = [ConversionUtils convertToObjCDiscoveredNodeDataFrom:cppDiscoveredNodeData]; + if (associatedConnectableVideoPlayer.HasValue()) { + VideoPlayer * connectableVideoPlayer = + [ConversionUtils convertToObjCVideoPlayerFrom:associatedConnectableVideoPlayer.Value()]; + [commissioner setConnectableVideoPlayer:connectableVideoPlayer]; + } } dispatch_async(clientQueue, ^{ @@ -1725,4 +1758,185 @@ - (void)applicationBasic_subscribeApplicationVersion:(ContentApp * _Nonnull)cont }); } +- (void)applicationBasic_readVendorName:(ContentApp * _Nonnull)contentApp + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + requestSentHandler:(void (^_Nonnull)(MatterError * _Nonnull))requestSentHandler + successCallback:(void (^_Nonnull)(NSString * _Nonnull))successCallback + failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback +{ + ChipLogProgress(AppServer, "CastingServerBridge().applicationBasic_readVendorName() called on Content App with endpoint ID %d", + contentApp.endpointId); + + [_readSuccessCallbacks setObject:successCallback forKey:@"applicationBasic_readVendorName"]; + [_readFailureCallbacks setObject:failureCallback forKey:@"applicationBasic_readVendorName"]; + + dispatch_async(_chipWorkQueue, ^{ + TargetEndpointInfo endpoint; + [ConversionUtils convertToCppTargetEndpointInfoFrom:contentApp outTargetEndpointInfo:endpoint]; + + CHIP_ERROR err = CastingServer::GetInstance()->ApplicationBasic_ReadVendorName( + &endpoint, nullptr, + [](void * context, + chip::app::Clusters::ApplicationBasic::Attributes::VendorName::TypeInfo::DecodableArgType vendorName) { + void (^callback)(NSString * _Nonnull) = [[CastingServerBridge getSharedInstance].subscriptionReadSuccessCallbacks + objectForKey:@"applicationBasic_readVendorName"]; + callback([NSString stringWithUTF8String:vendorName.data()]); + }, + [](void * context, CHIP_ERROR err) { + void (^callback)(MatterError *) = [[CastingServerBridge getSharedInstance].subscriptionReadFailureCallbacks + objectForKey:@"applicationBasic_readVendorName"]; + callback([[MatterError alloc] initWithCode:err.AsInteger() message:[NSString stringWithUTF8String:err.AsString()]]); + }); + dispatch_async(clientQueue, ^{ + requestSentHandler([[MatterError alloc] initWithCode:err.AsInteger() + message:[NSString stringWithUTF8String:err.AsString()]]); + }); + }); +} + +- (void)applicationBasic_readVendorID:(ContentApp * _Nonnull)contentApp + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + requestSentHandler:(void (^_Nonnull)(MatterError * _Nonnull))requestSentHandler + successCallback:(void (^_Nonnull)(NSNumber * _Nonnull))successCallback + failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback +{ + ChipLogProgress(AppServer, "CastingServerBridge().applicationBasic_readVendorID() called on Content App with endpoint ID %d", + contentApp.endpointId); + + [_readSuccessCallbacks setObject:successCallback forKey:@"applicationBasic_readVendorID"]; + [_readFailureCallbacks setObject:failureCallback forKey:@"applicationBasic_readVendorID"]; + + dispatch_async(_chipWorkQueue, ^{ + TargetEndpointInfo endpoint; + [ConversionUtils convertToCppTargetEndpointInfoFrom:contentApp outTargetEndpointInfo:endpoint]; + + CHIP_ERROR err = CastingServer::GetInstance()->ApplicationBasic_ReadVendorID( + &endpoint, nullptr, + [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::VendorID::TypeInfo::DecodableArgType vendorID) { + void (^callback)(NSNumber * _Nonnull) = [[CastingServerBridge getSharedInstance].subscriptionReadSuccessCallbacks + objectForKey:@"applicationBasic_readVendorID"]; + callback(@(vendorID)); + }, + [](void * context, CHIP_ERROR err) { + void (^callback)(MatterError *) = [[CastingServerBridge getSharedInstance].subscriptionReadFailureCallbacks + objectForKey:@"applicationBasic_readVendorID"]; + callback([[MatterError alloc] initWithCode:err.AsInteger() message:[NSString stringWithUTF8String:err.AsString()]]); + }); + dispatch_async(clientQueue, ^{ + requestSentHandler([[MatterError alloc] initWithCode:err.AsInteger() + message:[NSString stringWithUTF8String:err.AsString()]]); + }); + }); +} + +- (void)applicationBasic_readApplicationName:(ContentApp * _Nonnull)contentApp + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + requestSentHandler:(void (^_Nonnull)(MatterError * _Nonnull))requestSentHandler + successCallback:(void (^_Nonnull)(NSString * _Nonnull))successCallback + failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback +{ + ChipLogProgress(AppServer, + "CastingServerBridge().applicationBasic_readApplicationName() called on Content App with endpoint ID %d", + contentApp.endpointId); + + [_readSuccessCallbacks setObject:successCallback forKey:@"applicationBasic_readApplicationName"]; + [_readFailureCallbacks setObject:failureCallback forKey:@"applicationBasic_readApplicationName"]; + + dispatch_async(_chipWorkQueue, ^{ + TargetEndpointInfo endpoint; + [ConversionUtils convertToCppTargetEndpointInfoFrom:contentApp outTargetEndpointInfo:endpoint]; + + CHIP_ERROR err = CastingServer::GetInstance()->ApplicationBasic_ReadApplicationName( + &endpoint, nullptr, + [](void * context, + chip::app::Clusters::ApplicationBasic::Attributes::ApplicationName::TypeInfo::DecodableArgType applicationName) { + void (^callback)(NSString * _Nonnull) = [[CastingServerBridge getSharedInstance].subscriptionReadSuccessCallbacks + objectForKey:@"applicationBasic_readApplicationName"]; + callback([NSString stringWithUTF8String:applicationName.data()]); + }, + [](void * context, CHIP_ERROR err) { + void (^callback)(MatterError *) = [[CastingServerBridge getSharedInstance].subscriptionReadFailureCallbacks + objectForKey:@"applicationBasic_readApplicationName"]; + callback([[MatterError alloc] initWithCode:err.AsInteger() message:[NSString stringWithUTF8String:err.AsString()]]); + }); + dispatch_async(clientQueue, ^{ + requestSentHandler([[MatterError alloc] initWithCode:err.AsInteger() + message:[NSString stringWithUTF8String:err.AsString()]]); + }); + }); +} + +- (void)applicationBasic_readProductID:(ContentApp * _Nonnull)contentApp + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + requestSentHandler:(void (^_Nonnull)(MatterError * _Nonnull))requestSentHandler + successCallback:(void (^_Nonnull)(uint16_t))successCallback + failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback +{ + ChipLogProgress(AppServer, "CastingServerBridge().applicationBasic_readProductID() called on Content App with endpoint ID %d", + contentApp.endpointId); + + [_readSuccessCallbacks setObject:successCallback forKey:@"applicationBasic_readProductID"]; + [_readFailureCallbacks setObject:failureCallback forKey:@"applicationBasic_readProductID"]; + + dispatch_async(_chipWorkQueue, ^{ + TargetEndpointInfo endpoint; + [ConversionUtils convertToCppTargetEndpointInfoFrom:contentApp outTargetEndpointInfo:endpoint]; + + CHIP_ERROR err = CastingServer::GetInstance()->ApplicationBasic_ReadProductID( + &endpoint, nullptr, + [](void * context, chip::app::Clusters::ApplicationBasic::Attributes::ProductID::TypeInfo::DecodableArgType productID) { + void (^callback)(uint16_t) = [[CastingServerBridge getSharedInstance].subscriptionReadSuccessCallbacks + objectForKey:@"applicationBasic_readProductID"]; + callback(productID); + }, + [](void * context, CHIP_ERROR err) { + void (^callback)(MatterError *) = [[CastingServerBridge getSharedInstance].subscriptionReadFailureCallbacks + objectForKey:@"applicationBasic_readProductID"]; + callback([[MatterError alloc] initWithCode:err.AsInteger() message:[NSString stringWithUTF8String:err.AsString()]]); + }); + dispatch_async(clientQueue, ^{ + requestSentHandler([[MatterError alloc] initWithCode:err.AsInteger() + message:[NSString stringWithUTF8String:err.AsString()]]); + }); + }); +} + +- (void)applicationBasic_readApplicationVersion:(ContentApp * _Nonnull)contentApp + clientQueue:(dispatch_queue_t _Nonnull)clientQueue + requestSentHandler:(void (^_Nonnull)(MatterError * _Nonnull))requestSentHandler + successCallback:(void (^_Nonnull)(NSString * _Nonnull))successCallback + failureCallback:(void (^_Nonnull)(MatterError * _Nonnull))failureCallback +{ + ChipLogProgress(AppServer, + "CastingServerBridge().applicationBasic_readApplicationVersion() called on Content App with endpoint ID %d", + contentApp.endpointId); + + [_readSuccessCallbacks setObject:successCallback forKey:@"applicationBasic_readApplicationVersion"]; + [_readFailureCallbacks setObject:failureCallback forKey:@"applicationBasic_readApplicationVersion"]; + + dispatch_async(_chipWorkQueue, ^{ + TargetEndpointInfo endpoint; + [ConversionUtils convertToCppTargetEndpointInfoFrom:contentApp outTargetEndpointInfo:endpoint]; + + CHIP_ERROR err = CastingServer::GetInstance()->ApplicationBasic_ReadApplicationVersion( + &endpoint, nullptr, + [](void * context, + chip::app::Clusters::ApplicationBasic::Attributes::ApplicationVersion::TypeInfo::DecodableArgType + applicationVersion) { + void (^callback)(NSString * _Nonnull) = [[CastingServerBridge getSharedInstance].subscriptionReadSuccessCallbacks + objectForKey:@"applicationBasic_readApplicationVersion"]; + callback([NSString stringWithUTF8String:applicationVersion.data()]); + }, + [](void * context, CHIP_ERROR err) { + void (^callback)(MatterError *) = [[CastingServerBridge getSharedInstance].subscriptionReadFailureCallbacks + objectForKey:@"applicationBasic_readApplicationVersion"]; + callback([[MatterError alloc] initWithCode:err.AsInteger() message:[NSString stringWithUTF8String:err.AsString()]]); + }); + dispatch_async(clientQueue, ^{ + requestSentHandler([[MatterError alloc] initWithCode:err.AsInteger() + message:[NSString stringWithUTF8String:err.AsString()]]); + }); + }); +} + @end diff --git a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/ConversionUtils.hpp b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/ConversionUtils.hpp index df6a0360816ce8..bf92cf09a0069b 100644 --- a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/ConversionUtils.hpp +++ b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/ConversionUtils.hpp @@ -17,10 +17,12 @@ #import +#import "AppParameters.h" #import "ContentApp.h" #import "DiscoveredNodeData.h" #import "VideoPlayer.h" +#import #import #import #include @@ -32,6 +34,8 @@ /** * @brief Objective C to C++ converters */ ++ (CHIP_ERROR)convertToCppAppParamsInfoFrom:(AppParameters * _Nonnull)objCAppParameters outAppParams:(AppParams &)outAppParams; + + (CHIP_ERROR)convertToCppTargetEndpointInfoFrom:(ContentApp * _Nonnull)objCContentApp outTargetEndpointInfo:(TargetEndpointInfo &)outTargetEndpointInfo; diff --git a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/ConversionUtils.mm b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/ConversionUtils.mm index ca626201fdf236..f71cab0bf0e1c6 100644 --- a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/ConversionUtils.mm +++ b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/ConversionUtils.mm @@ -20,6 +20,19 @@ @implementation ConversionUtils ++ (CHIP_ERROR)convertToCppAppParamsInfoFrom:(AppParameters * _Nonnull)objCAppParameters outAppParams:(AppParams &)outAppParams +{ + VerifyOrReturnError(objCAppParameters != nil, CHIP_ERROR_INVALID_ARGUMENT); + + if (objCAppParameters.rotatingDeviceIdUniqueId != nil) { + chip::ByteSpan rotatingDeviceIdUniqueId + = chip::ByteSpan(static_cast(objCAppParameters.rotatingDeviceIdUniqueId.bytes), + objCAppParameters.rotatingDeviceIdUniqueId.length); + outAppParams.SetRotatingDeviceIdUniqueId(MakeOptional(rotatingDeviceIdUniqueId)); + } + return CHIP_NO_ERROR; +} + + (CHIP_ERROR)convertToCppTargetEndpointInfoFrom:(ContentApp * _Nonnull)objCContentApp outTargetEndpointInfo:(TargetEndpointInfo &)outTargetEndpointInfo { diff --git a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/DiscoveredNodeData.h b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/DiscoveredNodeData.h index 24240cc4a4acda..f4cf95f4be7e6a 100644 --- a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/DiscoveredNodeData.h +++ b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/DiscoveredNodeData.h @@ -17,6 +17,8 @@ #import +#import "VideoPlayer.h" + #ifndef DiscoveredNodeData_h #define DiscoveredNodeData_h @@ -54,6 +56,12 @@ - (DiscoveredNodeData *)initWithDeviceName:(NSString *)deviceName vendorId:(uint16_t)vendorId productId:(uint16_t)productId; +- (bool)isPreCommissioned; + +- (VideoPlayer *)getConnectableVideoPlayer; + +- (void)setConnectableVideoPlayer:(VideoPlayer *)videoPlayer; + @end #endif /* DiscoveredNodeData_h */ diff --git a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/DiscoveredNodeData.mm b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/DiscoveredNodeData.mm index 541352b3d31bf9..f8c85e52269dbb 100644 --- a/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/DiscoveredNodeData.mm +++ b/examples/tv-casting-app/darwin/MatterTvCastingBridge/MatterTvCastingBridge/DiscoveredNodeData.mm @@ -20,6 +20,12 @@ #import "DiscoveredNodeData.h" #include +@interface DiscoveredNodeData () + +@property (nonatomic) VideoPlayer * connectableVideoPlayer; + +@end + @implementation DiscoveredNodeData - (DiscoveredNodeData *)initWithDeviceName:(NSString *)deviceName vendorId:(uint16_t)vendorId productId:(uint16_t)productId @@ -35,7 +41,12 @@ - (DiscoveredNodeData *)initWithDeviceName:(NSString *)deviceName vendorId:(uint - (NSString *)description { - return [NSString stringWithFormat:@"%@ with Product ID: %d and Vendor ID: %d", _deviceName, _productId, _vendorId]; + if ([self isPreCommissioned]) { + return [NSString + stringWithFormat:@"%@ with Product ID: %d and Vendor ID: %d [Pre-Commissioned]", _deviceName, _productId, _vendorId]; + } else { + return [NSString stringWithFormat:@"%@ with Product ID: %d and Vendor ID: %d", _deviceName, _productId, _vendorId]; + } } - (BOOL)isEqualToDiscoveredNodeData:(DiscoveredNodeData *)other @@ -70,4 +81,19 @@ - (NSUInteger)hash return result; } +- (void)setConnectableVideoPlayer:(VideoPlayer * _Nonnull)videoPlayer +{ + _connectableVideoPlayer = videoPlayer; +} + +- (bool)isPreCommissioned +{ + return _connectableVideoPlayer != nil; +} + +- (VideoPlayer *)getConnectableVideoPlayer +{ + return _connectableVideoPlayer; +} + @end diff --git a/examples/tv-casting-app/darwin/TvCasting/TvCasting/CommissionerDiscoveryView.swift b/examples/tv-casting-app/darwin/TvCasting/TvCasting/CommissionerDiscoveryView.swift index 3ee2ac30d4b724..7a33fc7b19e271 100644 --- a/examples/tv-casting-app/darwin/TvCasting/TvCasting/CommissionerDiscoveryView.swift +++ b/examples/tv-casting-app/darwin/TvCasting/TvCasting/CommissionerDiscoveryView.swift @@ -55,7 +55,16 @@ struct CommissionerDiscoveryView: View { Text("Select a commissioner video player...") ForEach(viewModel.commissioners) { commissioner in NavigationLink( - destination: CommissioningView(_selectedCommissioner: commissioner), + destination: { + if(commissioner.isPreCommissioned()) + { + ConnectionView(_selectedVideoPlayer: commissioner.getConnectableVideoPlayer()) + } + else + { + CommissioningView(_selectedCommissioner: commissioner) + } + }, label: { Text(commissioner.description) } diff --git a/examples/tv-casting-app/darwin/TvCasting/TvCasting/ContentView.swift b/examples/tv-casting-app/darwin/TvCasting/TvCasting/ContentView.swift index e7ca12c9b720cd..b281da172435aa 100644 --- a/examples/tv-casting-app/darwin/TvCasting/TvCasting/ContentView.swift +++ b/examples/tv-casting-app/darwin/TvCasting/TvCasting/ContentView.swift @@ -20,7 +20,6 @@ import SwiftUI struct ContentView: View { var body: some View { NavigationView { - //CommissionerDiscoveryView() StartFromCacheView() } } diff --git a/examples/tv-casting-app/darwin/TvCasting/TvCasting/TvCastingApp.swift b/examples/tv-casting-app/darwin/TvCasting/TvCasting/TvCastingApp.swift index 27dce5b63f55f1..26e4768485d13e 100644 --- a/examples/tv-casting-app/darwin/TvCasting/TvCasting/TvCastingApp.swift +++ b/examples/tv-casting-app/darwin/TvCasting/TvCasting/TvCastingApp.swift @@ -16,12 +16,33 @@ */ import SwiftUI +import os.log @main struct TvCastingApp: App { + let Log = Logger(subsystem: "com.matter.casting", + category: "TvCastingApp") + var body: some Scene { WindowGroup { ContentView() + .onAppear(perform: { + if let castingServerBridge = CastingServerBridge.getSharedInstance() + { + let appParameters: AppParameters = AppParameters() + + var rotatingDeviceIdUniqueId: [UInt8] = [UInt8](repeating: 0, count: 16 ) + for i in (0...15) + { + rotatingDeviceIdUniqueId[i] = UInt8.random(in: 0..<255) + } + appParameters.rotatingDeviceIdUniqueId = Data(rotatingDeviceIdUniqueId) + + castingServerBridge.initApp(appParameters, clientQueue: DispatchQueue.main, initAppStatusHandler: { (result: Bool) -> () in + self.Log.info("initApp result \(result)") + }) + } + }) } } } diff --git a/examples/tv-casting-app/linux/CastingUtils.cpp b/examples/tv-casting-app/linux/CastingUtils.cpp index 760b0435124c47..294339bed585a1 100644 --- a/examples/tv-casting-app/linux/CastingUtils.cpp +++ b/examples/tv-casting-app/linux/CastingUtils.cpp @@ -41,7 +41,9 @@ CHIP_ERROR DiscoverCommissioners() CHIP_ERROR RequestCommissioning(int index) { - const Dnssd::DiscoveredNodeData * selectedCommissioner = CastingServer::GetInstance()->GetDiscoveredCommissioner(index); + chip::Optional associatedConnectableVideoPlayer; + const Dnssd::DiscoveredNodeData * selectedCommissioner = + CastingServer::GetInstance()->GetDiscoveredCommissioner(index, associatedConnectableVideoPlayer); if (selectedCommissioner == nullptr) { ChipLogError(AppServer, "No such commissioner with index %d exists", index); @@ -89,11 +91,19 @@ void InitCommissioningFlow(intptr_t commandArg) // Display discovered commissioner TVs to ask user to select one for (int i = 0; i < CHIP_DEVICE_CONFIG_MAX_DISCOVERED_NODES; i++) { - const Dnssd::DiscoveredNodeData * commissioner = CastingServer::GetInstance()->GetDiscoveredCommissioner(i); + chip::Optional associatedConnectableVideoPlayer; + const Dnssd::DiscoveredNodeData * commissioner = + CastingServer::GetInstance()->GetDiscoveredCommissioner(i, associatedConnectableVideoPlayer); if (commissioner != nullptr) { ChipLogProgress(AppServer, "Discovered Commissioner #%d", commissionerCount++); commissioner->LogDetail(); + if (associatedConnectableVideoPlayer.HasValue()) + { + TargetVideoPlayerInfo * targetVideoPlayerInfo = associatedConnectableVideoPlayer.Value(); + ChipLogProgress(AppServer, "Previously connected with nodeId 0x" ChipLogFormatX64 " fabricIndex: %d", + ChipLogValueX64(targetVideoPlayerInfo->GetNodeId()), targetVideoPlayerInfo->GetFabricIndex()); + } } } diff --git a/examples/tv-casting-app/tv-casting-common/BUILD.gn b/examples/tv-casting-app/tv-casting-common/BUILD.gn index 1c356d5cb36b9e..179fa86602367a 100644 --- a/examples/tv-casting-app/tv-casting-common/BUILD.gn +++ b/examples/tv-casting-app/tv-casting-common/BUILD.gn @@ -47,6 +47,7 @@ chip_data_model("tv-casting-common") { "${chip_root}/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp", "commands/clusters/ModelCommand.cpp", "commands/common/CHIPCommand.cpp", + "include/AppParams.h", "include/ApplicationBasic.h", "include/ApplicationLauncher.h", "include/CastingServer.h", @@ -57,11 +58,13 @@ chip_data_model("tv-casting-common") { "include/MediaBase.h", "include/MediaCommandBase.h", "include/MediaPlayback.h", + "include/MediaReadBase.h", "include/MediaSubscriptionBase.h", "include/PersistenceManager.h", "include/TargetEndpointInfo.h", "include/TargetNavigator.h", "include/TargetVideoPlayerInfo.h", + "src/AppParams.cpp", "src/ApplicationLauncher.cpp", "src/CastingServer.cpp", "src/Channel.cpp", diff --git a/examples/tv-casting-app/tv-casting-common/include/AppParams.h b/examples/tv-casting-app/tv-casting-common/include/AppParams.h new file mode 100644 index 00000000000000..7a42c09b501dda --- /dev/null +++ b/examples/tv-casting-app/tv-casting-common/include/AppParams.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. + */ + +#pragma once + +#include +#include + +/** + * @brief Parameters passed to the CastingServer at the time of startup (i.e. init call) + */ +class AppParams +{ +public: + AppParams() {} +#if CHIP_ENABLE_ROTATING_DEVICE_ID + AppParams(chip::Optional rotatingDeviceIdUniqueId); + void SetRotatingDeviceIdUniqueId(chip::Optional rotatingDeviceIdUniqueId); + chip::Optional GetRotatingDeviceIdUniqueId(); +#endif // CHIP_ENABLE_ROTATING_DEVICE_ID + +private: +#if CHIP_ENABLE_ROTATING_DEVICE_ID + // if this Optional.hasValue = false, a random one is generated by CastingServer.Init() + chip::Optional mRotatingDeviceIdUniqueId; +#endif // CHIP_ENABLE_ROTATING_DEVICE_ID +}; diff --git a/examples/tv-casting-app/tv-casting-common/include/ApplicationBasic.h b/examples/tv-casting-app/tv-casting-common/include/ApplicationBasic.h index d30d659782b18a..ec009de429a8e6 100644 --- a/examples/tv-casting-app/tv-casting-common/include/ApplicationBasic.h +++ b/examples/tv-casting-app/tv-casting-common/include/ApplicationBasic.h @@ -16,6 +16,7 @@ * limitations under the License. */ +#include "MediaReadBase.h" #include "MediaSubscriptionBase.h" #include @@ -71,3 +72,54 @@ class AllowedVendorListSubscriber public: AllowedVendorListSubscriber() : MediaSubscriptionBase(chip::app::Clusters::ApplicationBasic::Id) {} }; + +// READER CLASSES + +class VendorNameReader : public MediaReadBase +{ +public: + VendorNameReader() : MediaReadBase(chip::app::Clusters::ApplicationBasic::Id) {} +}; + +class VendorIDReader : public MediaReadBase +{ +public: + VendorIDReader() : MediaReadBase(chip::app::Clusters::ApplicationBasic::Id) {} +}; + +class ApplicationNameReader : public MediaReadBase +{ +public: + ApplicationNameReader() : MediaReadBase(chip::app::Clusters::ApplicationBasic::Id) {} +}; + +class ProductIDReader : public MediaReadBase +{ +public: + ProductIDReader() : MediaReadBase(chip::app::Clusters::ApplicationBasic::Id) {} +}; + +class ApplicationReader : public MediaReadBase +{ +public: + ApplicationReader() : MediaReadBase(chip::app::Clusters::ApplicationBasic::Id) {} +}; + +class StatusReader : public MediaReadBase +{ +public: + StatusReader() : MediaReadBase(chip::app::Clusters::ApplicationBasic::Id) {} +}; + +class ApplicationVersionReader + : public MediaReadBase +{ +public: + ApplicationVersionReader() : MediaReadBase(chip::app::Clusters::ApplicationBasic::Id) {} +}; + +class AllowedVendorListReader : public MediaReadBase +{ +public: + AllowedVendorListReader() : MediaReadBase(chip::app::Clusters::ApplicationBasic::Id) {} +}; diff --git a/examples/tv-casting-app/tv-casting-common/include/CHIPProjectAppConfig.h b/examples/tv-casting-app/tv-casting-common/include/CHIPProjectAppConfig.h index bc50cb335e274f..ca3b9bd3ca5be8 100644 --- a/examples/tv-casting-app/tv-casting-common/include/CHIPProjectAppConfig.h +++ b/examples/tv-casting-app/tv-casting-common/include/CHIPProjectAppConfig.h @@ -53,3 +53,5 @@ // Enable some test-only interaction model APIs. #define CONFIG_BUILD_FOR_HOST_UNIT_TEST 1 + +#define CHIP_ENABLE_ROTATING_DEVICE_ID 1 diff --git a/examples/tv-casting-app/tv-casting-common/include/CastingServer.h b/examples/tv-casting-app/tv-casting-common/include/CastingServer.h index b77e2bd320604b..375ede1f6b8af3 100644 --- a/examples/tv-casting-app/tv-casting-common/include/CastingServer.h +++ b/examples/tv-casting-app/tv-casting-common/include/CastingServer.h @@ -18,6 +18,7 @@ #pragma once +#include "AppParams.h" #include "ApplicationBasic.h" #include "ApplicationLauncher.h" #include "Channel.h" @@ -51,10 +52,11 @@ class CastingServer void operator=(const CastingServer &) = delete; static CastingServer * GetInstance(); - void Init(); + CHIP_ERROR Init(AppParams * AppParams = nullptr); CHIP_ERROR DiscoverCommissioners(); - const chip::Dnssd::DiscoveredNodeData * GetDiscoveredCommissioner(int index); + const chip::Dnssd::DiscoveredNodeData * + GetDiscoveredCommissioner(int index, chip::Optional & outAssociatedConnectableVideoPlayer); CHIP_ERROR OpenBasicCommissioningWindow(std::function commissioningCompleteCallback, std::function onConnectionSuccess, std::function onConnectionFailure, @@ -333,6 +335,55 @@ class CastingServer chip::Controller::ReadResponseFailureCallback failureFn, uint16_t minInterval, uint16_t maxInterval, chip::Controller::SubscriptionEstablishedCallback onSubscriptionEstablished); + CHIP_ERROR + ApplicationBasic_ReadVendorName(TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::VendorName::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn); + CHIP_ERROR + ApplicationBasic_ReadVendorID(TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::VendorID::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn); + CHIP_ERROR ApplicationBasic_ReadApplicationName( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::ApplicationName::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn); + CHIP_ERROR + ApplicationBasic_ReadProductID(TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::ProductID::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn); + CHIP_ERROR + ApplicationBasic_ReadApplication(TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::Application::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn); + CHIP_ERROR + ApplicationBasic_ReadStatus(TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::Status::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn); + CHIP_ERROR ApplicationBasic_ReadApplicationVersion( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::ApplicationVersion::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn); + CHIP_ERROR ApplicationBasic_ReadAllowedVendorList( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::AllowedVendorList::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn); + /* * @brief Channel cluster */ @@ -361,6 +412,8 @@ class CastingServer uint16_t mTargetVideoPlayerProductId = 0; uint16_t mTargetVideoPlayerDeviceType = 0; char mTargetVideoPlayerDeviceName[chip::Dnssd::kMaxDeviceNameLen + 1] = {}; + size_t mTargetVideoPlayerNumIPs = 0; // number of valid IP addresses + chip::Inet::IPAddress mTargetVideoPlayerIpAddress[chip::Dnssd::CommonResolutionData::kMaxIPAddresses]; chip::Controller::CommissionableNodeController mCommissionableNodeController; std::function mCommissioningCompleteCallback; @@ -441,6 +494,15 @@ class CastingServer ApplicationVersionSubscriber mApplicationVersionSubscriber; AllowedVendorListSubscriber mAllowedVendorListSubscriber; + VendorNameReader mVendorNameReader; + VendorIDReader mVendorIDReader; + ApplicationNameReader mApplicationNameReader; + ProductIDReader mProductIDReader; + ApplicationReader mApplicationReader; + StatusReader mStatusReader; + ApplicationVersionReader mApplicationVersionReader; + AllowedVendorListReader mAllowedVendorListReader; + /* * @brief Channel cluster */ diff --git a/examples/tv-casting-app/tv-casting-common/include/MediaReadBase.h b/examples/tv-casting-app/tv-casting-common/include/MediaReadBase.h new file mode 100644 index 00000000000000..3003a08a348f70 --- /dev/null +++ b/examples/tv-casting-app/tv-casting-common/include/MediaReadBase.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. + */ +#pragma once + +#include "MediaBase.h" + +template +class MediaReadBase : public MediaBase +{ +public: + MediaReadBase(chip::ClusterId clusterId) : MediaBase(clusterId) {} + + CHIP_ERROR ReadAttribute(void * context, + chip::Controller::ReadResponseSuccessCallback successFn, + chip::Controller::ReadResponseFailureCallback failureFn) + { + VerifyOrDieWithMsg(mTargetVideoPlayerInfo != nullptr, AppServer, "Target unknown"); + + auto deviceProxy = mTargetVideoPlayerInfo->GetOperationalDeviceProxy(); + ReturnErrorCodeIf(deviceProxy == nullptr || !deviceProxy->ConnectionReady(), CHIP_ERROR_PEER_NODE_NOT_FOUND); + + MediaClusterBase cluster(*deviceProxy->GetExchangeManager(), deviceProxy->GetSecureSession().Value(), mClusterId, + mTvEndpoint); + + return cluster.template ReadAttribute(context, successFn, failureFn); + } +}; diff --git a/examples/tv-casting-app/tv-casting-common/include/PersistenceManager.h b/examples/tv-casting-app/tv-casting-common/include/PersistenceManager.h index d9505e00391126..b1e7bd6c58130d 100644 --- a/examples/tv-casting-app/tv-casting-common/include/PersistenceManager.h +++ b/examples/tv-casting-app/tv-casting-common/include/PersistenceManager.h @@ -44,16 +44,20 @@ class PersistenceManager kEndpointIdTag, kClusterIdsContainerTag, kClusterIdTag, - kCastingDataVersionTag, + kCurrentCastingDataVersionTag, kVideoPlayerVendorIdTag, kVideoPlayerProductIdTag, kVideoPlayerDeviceTypeIdTag, kVideoPlayerDeviceNameTag, + kVideoPlayerNumIPsTag, + kVideoPlayerIPAddressTag, + kIpAddressesContainerTag, kContextTagMaxNum = UINT8_MAX }; - constexpr static size_t kCastingDataMaxBytes = 1024 * 100; // 100 KBs - constexpr static char * kCastingDataKey = (char *) "com.matter.casting"; - constexpr static uint32_t kCastingDataVersion = 1; + constexpr static size_t kCastingDataMaxBytes = 1024 * 100; // 100 KBs + constexpr static char * kCastingDataKey = (char *) "com.matter.casting"; + constexpr static uint32_t kCurrentCastingDataVersion = 1; + constexpr static uint32_t kSupportedCastingDataVersions[1] = { 1 }; }; diff --git a/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h b/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h index da58e8db11b63e..0f423e2aeb459a 100644 --- a/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h +++ b/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h @@ -43,6 +43,9 @@ class TargetVideoPlayerInfo chip::NodeId GetNodeId() const { return mNodeId; } chip::FabricIndex GetFabricIndex() const { return mFabricIndex; } const char * GetDeviceName() const { return mDeviceName; } + size_t GetNumIPs() const { return mNumIPs; } + const chip::Inet::IPAddress * GetIpAddresses() const { return mIpAddress; } + bool IsSameAs(const chip::Dnssd::DiscoveredNodeData * discoveredNodeData); chip::OperationalDeviceProxy * GetOperationalDeviceProxy() { @@ -56,7 +59,8 @@ class TargetVideoPlayerInfo CHIP_ERROR Initialize(chip::NodeId nodeId, chip::FabricIndex fabricIndex, std::function onConnectionSuccess, std::function onConnectionFailure, uint16_t vendorId = 0, uint16_t productId = 0, - uint16_t deviceType = 0, const char * deviceName = {}); + uint16_t deviceType = 0, const char * deviceName = {}, size_t numIPs = 0, + chip::Inet::IPAddress * ipAddressList = nullptr); CHIP_ERROR FindOrEstablishCASESession(std::function onConnectionSuccess, std::function onConnectionFailure); TargetEndpointInfo * GetOrAddEndpoint(chip::EndpointId endpointId); @@ -107,6 +111,8 @@ class TargetVideoPlayerInfo uint16_t mProductId = 0; uint16_t mDeviceType = 0; char mDeviceName[chip::Dnssd::kMaxDeviceNameLen + 1] = {}; + size_t mNumIPs = 0; // number of valid IP addresses + chip::Inet::IPAddress mIpAddress[chip::Dnssd::CommonResolutionData::kMaxIPAddresses]; chip::Callback::Callback mOnConnectedCallback; chip::Callback::Callback mOnConnectionFailureCallback; diff --git a/examples/tv-casting-app/tv-casting-common/src/AppParams.cpp b/examples/tv-casting-app/tv-casting-common/src/AppParams.cpp new file mode 100644 index 00000000000000..62a98feda4375f --- /dev/null +++ b/examples/tv-casting-app/tv-casting-common/src/AppParams.cpp @@ -0,0 +1,36 @@ +/* + * + * 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 "AppParams.h" + +#if CHIP_ENABLE_ROTATING_DEVICE_ID +AppParams::AppParams(chip::Optional rotatingDeviceIdUniqueId) +{ + mRotatingDeviceIdUniqueId = rotatingDeviceIdUniqueId; +} + +void AppParams::SetRotatingDeviceIdUniqueId(chip::Optional rotatingDeviceIdUniqueId) +{ + mRotatingDeviceIdUniqueId = rotatingDeviceIdUniqueId; +} + +chip::Optional AppParams::GetRotatingDeviceIdUniqueId() +{ + return mRotatingDeviceIdUniqueId; +} +#endif // CHIP_ENABLE_ROTATING_DEVICE_ID diff --git a/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp b/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp index 7891070728abfe..505f578086dd71 100644 --- a/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp +++ b/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp @@ -25,20 +25,7 @@ using namespace chip::app::Clusters::ContentLauncher::Commands; CastingServer * CastingServer::castingServer_ = nullptr; -CastingServer::CastingServer() -{ -#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) - // generate and set a random uniqueId for generating rotatingId - uint8_t rotatingDeviceIdUniqueId[chip::DeviceLayer::ConfigurationManager::kRotatingDeviceIDUniqueIDLength]; - for (size_t i = 0; i < sizeof(rotatingDeviceIdUniqueId); i++) - { - rotatingDeviceIdUniqueId[i] = chip::Crypto::GetRandU8(); - } - - ByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId); - chip::DeviceLayer::ConfigurationMgr().SetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan); -#endif // CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) -} +CastingServer::CastingServer() {} CastingServer * CastingServer::GetInstance() { @@ -49,20 +36,44 @@ CastingServer * CastingServer::GetInstance() return castingServer_; } -void CastingServer::Init() +CHIP_ERROR CastingServer::Init(AppParams * AppParams) { if (mInited) { - return; + return CHIP_NO_ERROR; + } + +#if CHIP_ENABLE_ROTATING_DEVICE_ID + // if this class's client provided a RotatingDeviceIdUniqueId, use that + if (AppParams != nullptr && AppParams->GetRotatingDeviceIdUniqueId().HasValue()) + { + ByteSpan rotatingDeviceIdUniqueId(AppParams->GetRotatingDeviceIdUniqueId().Value()); + chip::DeviceLayer::ConfigurationMgr().SetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueId); + } +#ifdef CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID + else + { + // otherwise, generate and set a random uniqueId for generating rotatingId + uint8_t rotatingDeviceIdUniqueId[chip::DeviceLayer::ConfigurationManager::kRotatingDeviceIDUniqueIDLength]; + for (size_t i = 0; i < sizeof(rotatingDeviceIdUniqueId); i++) + { + rotatingDeviceIdUniqueId[i] = chip::Crypto::GetRandU8(); + } + + // ByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId); + chip::DeviceLayer::ConfigurationMgr().SetRotatingDeviceIdUniqueId(ByteSpan(rotatingDeviceIdUniqueId)); } +#endif // CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID +#endif // CHIP_ENABLE_ROTATING_DEVICE_ID // Initialize binding handlers - ReturnOnFailure(InitBindingHandlers()); + ReturnErrorOnFailure(InitBindingHandlers()); // Add callback to send Content casting commands after commissioning completes - ReturnOnFailure(DeviceLayer::PlatformMgrImpl().AddEventHandler(DeviceEventCallback, 0)); + ReturnErrorOnFailure(DeviceLayer::PlatformMgrImpl().AddEventHandler(DeviceEventCallback, 0)); mInited = true; + return CHIP_NO_ERROR; } CHIP_ERROR CastingServer::InitBindingHandlers() @@ -88,6 +99,12 @@ CHIP_ERROR CastingServer::TargetVideoPlayerInfoInit(NodeId nodeId, FabricIndex f CHIP_ERROR CastingServer::DiscoverCommissioners() { + TargetVideoPlayerInfo * connectableVideoPlayerList = ReadCachedTargetVideoPlayerInfos(); + if (connectableVideoPlayerList == nullptr || !connectableVideoPlayerList[0].IsInitialized()) + { + ChipLogProgress(AppServer, "No cached video players found during discovery"); + } + // Send discover commissioners request return mCommissionableNodeController.DiscoverCommissioners( Dnssd::DiscoveryFilter(Dnssd::DiscoveryFilterType::kDeviceType, static_cast(35))); @@ -120,15 +137,32 @@ CHIP_ERROR CastingServer::SendUserDirectedCommissioningRequest(Dnssd::Discovered mTargetVideoPlayerVendorId = selectedCommissioner->commissionData.vendorId; mTargetVideoPlayerProductId = selectedCommissioner->commissionData.productId; mTargetVideoPlayerDeviceType = selectedCommissioner->commissionData.deviceType; + mTargetVideoPlayerNumIPs = selectedCommissioner->resolutionData.numIPs; + for (size_t i = 0; i < mTargetVideoPlayerNumIPs && i < chip::Dnssd::CommonResolutionData::kMaxIPAddresses; i++) + { + mTargetVideoPlayerIpAddress[i] = selectedCommissioner->resolutionData.ipAddress[i]; + } chip::Platform::CopyString(mTargetVideoPlayerDeviceName, chip::Dnssd::kMaxDeviceNameLen + 1, selectedCommissioner->commissionData.deviceName); return CHIP_NO_ERROR; } #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT -const Dnssd::DiscoveredNodeData * CastingServer::GetDiscoveredCommissioner(int index) +const Dnssd::DiscoveredNodeData * +CastingServer::GetDiscoveredCommissioner(int index, chip::Optional & outAssociatedConnectableVideoPlayer) { - return mCommissionableNodeController.GetDiscoveredCommissioner(index); + const Dnssd::DiscoveredNodeData * discoveredNodeData = mCommissionableNodeController.GetDiscoveredCommissioner(index); + if (discoveredNodeData != nullptr) + { + for (size_t i = 0; i < kMaxCachedVideoPlayers && mCachedTargetVideoPlayerInfo[i].IsInitialized(); i++) + { + if (mCachedTargetVideoPlayerInfo[i].IsSameAs(discoveredNodeData)) + { + outAssociatedConnectableVideoPlayer = MakeOptional(&mCachedTargetVideoPlayerInfo[i]); + } + } + } + return discoveredNodeData; } void CastingServer::ReadServerClustersForNode(NodeId nodeId) @@ -301,7 +335,8 @@ void CastingServer::DeviceEventCallback(const DeviceLayer::ChipDeviceEvent * eve CastingServer::GetInstance()->mOnConnectionSuccessClientCallback, CastingServer::GetInstance()->mOnConnectionFailureClientCallback, CastingServer::GetInstance()->mTargetVideoPlayerVendorId, CastingServer::GetInstance()->mTargetVideoPlayerProductId, - CastingServer::GetInstance()->mTargetVideoPlayerDeviceType, CastingServer::GetInstance()->mTargetVideoPlayerDeviceName); + CastingServer::GetInstance()->mTargetVideoPlayerDeviceType, CastingServer::GetInstance()->mTargetVideoPlayerDeviceName, + CastingServer::GetInstance()->mTargetVideoPlayerNumIPs, CastingServer::GetInstance()->mTargetVideoPlayerIpAddress); CastingServer::GetInstance()->mCommissioningCompleteCallback(err); } @@ -823,6 +858,97 @@ CHIP_ERROR CastingServer::ApplicationBasic_SubscribeToAllowedVendorList( onSubscriptionEstablished); } +CHIP_ERROR CastingServer::ApplicationBasic_ReadVendorName( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::VendorName::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn) +{ + ReturnErrorOnFailure(mVendorNameReader.SetTarget(mActiveTargetVideoPlayerInfo, endpoint->GetEndpointId())); + return mVendorNameReader.ReadAttribute(context, successFn, failureFn); +} + +CHIP_ERROR +CastingServer::ApplicationBasic_ReadVendorID( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::VendorID::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn) +{ + ReturnErrorOnFailure(mVendorIDReader.SetTarget(mActiveTargetVideoPlayerInfo, endpoint->GetEndpointId())); + return mVendorIDReader.ReadAttribute(context, successFn, failureFn); +} + +CHIP_ERROR CastingServer::ApplicationBasic_ReadApplicationName( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::ApplicationName::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn) +{ + ReturnErrorOnFailure(mApplicationNameReader.SetTarget(mActiveTargetVideoPlayerInfo, endpoint->GetEndpointId())); + return mApplicationNameReader.ReadAttribute(context, successFn, failureFn); +} + +CHIP_ERROR +CastingServer::ApplicationBasic_ReadProductID( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::ProductID::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn) +{ + ReturnErrorOnFailure(mProductIDReader.SetTarget(mActiveTargetVideoPlayerInfo, endpoint->GetEndpointId())); + return mProductIDReader.ReadAttribute(context, successFn, failureFn); +} + +CHIP_ERROR CastingServer::ApplicationBasic_ReadApplication( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::Application::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn) +{ + ReturnErrorOnFailure(mApplicationReader.SetTarget(mActiveTargetVideoPlayerInfo, endpoint->GetEndpointId())); + return mApplicationReader.ReadAttribute(context, successFn, failureFn); +} + +CHIP_ERROR +CastingServer::ApplicationBasic_ReadStatus( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::Status::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn) +{ + ReturnErrorOnFailure(mStatusReader.SetTarget(mActiveTargetVideoPlayerInfo, endpoint->GetEndpointId())); + return mStatusReader.ReadAttribute(context, successFn, failureFn); +} + +CHIP_ERROR CastingServer::ApplicationBasic_ReadApplicationVersion( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::ApplicationVersion::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn) +{ + ReturnErrorOnFailure(mApplicationVersionReader.SetTarget(mActiveTargetVideoPlayerInfo, endpoint->GetEndpointId())); + return mApplicationVersionReader.ReadAttribute(context, successFn, failureFn); +} + +CHIP_ERROR CastingServer::ApplicationBasic_ReadAllowedVendorList( + TargetEndpointInfo * endpoint, void * context, + chip::Controller::ReadResponseSuccessCallback< + chip::app::Clusters::ApplicationBasic::Attributes::AllowedVendorList::TypeInfo::DecodableArgType> + successFn, + chip::Controller::ReadResponseFailureCallback failureFn) +{ + ReturnErrorOnFailure(mAllowedVendorListReader.SetTarget(mActiveTargetVideoPlayerInfo, endpoint->GetEndpointId())); + return mAllowedVendorListReader.ReadAttribute(context, successFn, failureFn); +} + /* * @brief Channel cluster */ diff --git a/examples/tv-casting-app/tv-casting-common/src/PersistenceManager.cpp b/examples/tv-casting-app/tv-casting-common/src/PersistenceManager.cpp index 0d71d28ca83a38..a57415d68c7582 100644 --- a/examples/tv-casting-app/tv-casting-common/src/PersistenceManager.cpp +++ b/examples/tv-casting-app/tv-casting-common/src/PersistenceManager.cpp @@ -71,7 +71,7 @@ CHIP_ERROR PersistenceManager::WriteAllVideoPlayers(TargetVideoPlayerInfo videoP TLV::TLVType outerContainerType = TLV::kTLVType_Structure; ReturnErrorOnFailure(tlvWriter.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType)); - ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(kCastingDataVersionTag), kCastingDataVersion)); + ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(kCurrentCastingDataVersionTag), kCurrentCastingDataVersion)); TLV::TLVType videoPlayersContainerType = TLV::kTLVType_Array; // Video Players container starts @@ -92,6 +92,27 @@ CHIP_ERROR PersistenceManager::WriteAllVideoPlayers(TargetVideoPlayerInfo videoP ReturnErrorOnFailure(tlvWriter.PutBytes(TLV::ContextTag(kVideoPlayerDeviceNameTag), (const uint8_t *) videoPlayer->GetDeviceName(), static_cast(strlen(videoPlayer->GetDeviceName()) + 1))); + ReturnErrorOnFailure( + tlvWriter.Put(TLV::ContextTag(kVideoPlayerNumIPsTag), static_cast(videoPlayer->GetNumIPs()))); + const Inet::IPAddress * ipAddress = videoPlayer->GetIpAddresses(); + if (ipAddress != nullptr && videoPlayer->GetNumIPs() > 0) + { + TLV::TLVType ipAddressesContainerType = TLV::kTLVType_Array; + // IP Addresses container starts + ReturnErrorOnFailure(tlvWriter.StartContainer(TLV::ContextTag(kIpAddressesContainerTag), TLV::kTLVType_Structure, + ipAddressesContainerType)); + for (size_t i = 0; i < videoPlayer->GetNumIPs() && i < chip::Dnssd::CommonResolutionData::kMaxIPAddresses; i++) + { + char ipAddressStr[Inet::IPAddress::kMaxStringLength]; + ipAddress[i].ToString(ipAddressStr, Inet::IPAddress::kMaxStringLength); + ReturnErrorOnFailure(tlvWriter.PutBytes(TLV::ContextTag(kVideoPlayerIPAddressTag), + (const uint8_t *) ipAddressStr, + static_cast(strlen(ipAddressStr) + 1))); + } + // IP Addresses container ends + ReturnErrorOnFailure(tlvWriter.EndContainer(ipAddressesContainerType)); + } + TargetEndpointInfo * endpoints = videoPlayer->GetEndpoints(); if (endpoints != nullptr) { @@ -132,7 +153,7 @@ CHIP_ERROR PersistenceManager::WriteAllVideoPlayers(TargetVideoPlayerInfo videoP ReturnErrorOnFailure(tlvWriter.Finalize()); ChipLogProgress(AppServer, "PersistenceManager::WriteAllVideoPlayers TLV(CastingData).LengthWritten: %d bytes and version: %d", - tlvWriter.GetLengthWritten(), kCastingDataVersion); + tlvWriter.GetLengthWritten(), kCurrentCastingDataVersion); return chip::DeviceLayer::PersistedStorage::KeyValueStoreMgr().Put(kCastingDataKey, castingData, tlvWriter.GetLengthWritten()); } @@ -162,7 +183,7 @@ CHIP_ERROR PersistenceManager::ReadAllVideoPlayers(TargetVideoPlayerInfo outVide ReturnErrorOnFailure(reader.Next()); TLV::Tag outerContainerTag = reader.GetTag(); uint8_t outerContainerTagTagNum = static_cast(TLV::TagNumFromTag(outerContainerTag)); - VerifyOrReturnError(outerContainerTagTagNum == kCastingDataVersionTag, CHIP_ERROR_INVALID_TLV_TAG); + VerifyOrReturnError(outerContainerTagTagNum == kCurrentCastingDataVersionTag, CHIP_ERROR_INVALID_TLV_TAG); uint32_t version; ReturnErrorOnFailure(reader.Get(version)); ChipLogProgress(AppServer, "PersistenceManager::ReadAllVideoPlayers TLV(CastingData) version: %d", version); @@ -178,6 +199,8 @@ CHIP_ERROR PersistenceManager::ReadAllVideoPlayers(TargetVideoPlayerInfo outVide uint16_t productId = 0; uint16_t deviceType = 0; char deviceName[chip::Dnssd::kMaxDeviceNameLen + 1] = {}; + size_t numIPs = 0; + Inet::IPAddress ipAddress[chip::Dnssd::CommonResolutionData::kMaxIPAddresses]; CHIP_ERROR err; while ((err = reader.Next()) == CHIP_NO_ERROR) { @@ -188,47 +211,91 @@ CHIP_ERROR PersistenceManager::ReadAllVideoPlayers(TargetVideoPlayerInfo outVide return CHIP_ERROR_INVALID_TLV_TAG; } - uint8_t viewPlayersContainerTagNum = static_cast(TLV::TagNumFromTag(videoPlayersContainerTag)); - if (viewPlayersContainerTagNum == kNodeIdTag) + uint8_t videoPlayersContainerTagNum = static_cast(TLV::TagNumFromTag(videoPlayersContainerTag)); + if (videoPlayersContainerTagNum == kNodeIdTag) { ReturnErrorOnFailure(reader.Get(nodeId)); continue; } - if (viewPlayersContainerTagNum == kFabricIndexTag) + if (videoPlayersContainerTagNum == kFabricIndexTag) { ReturnErrorOnFailure(reader.Get(fabricIndex)); continue; } - if (viewPlayersContainerTagNum == kVideoPlayerVendorIdTag) + if (videoPlayersContainerTagNum == kVideoPlayerVendorIdTag) { ReturnErrorOnFailure(reader.Get(vendorId)); continue; } - if (viewPlayersContainerTagNum == kVideoPlayerProductIdTag) + if (videoPlayersContainerTagNum == kVideoPlayerProductIdTag) { ReturnErrorOnFailure(reader.Get(productId)); continue; } - if (viewPlayersContainerTagNum == kVideoPlayerDeviceTypeIdTag) + if (videoPlayersContainerTagNum == kVideoPlayerDeviceTypeIdTag) { ReturnErrorOnFailure(reader.Get(deviceType)); continue; } - if (viewPlayersContainerTagNum == kVideoPlayerDeviceNameTag) + if (videoPlayersContainerTagNum == kVideoPlayerDeviceNameTag) { ReturnErrorOnFailure(reader.GetBytes(reinterpret_cast(deviceName), chip::Dnssd::kMaxDeviceNameLen + 1)); continue; } - if (viewPlayersContainerTagNum == kContentAppEndpointsContainerTag) + if (videoPlayersContainerTagNum == kVideoPlayerNumIPsTag) + { + ReturnErrorOnFailure(reader.Get(reinterpret_cast(numIPs))); + continue; + } + + if (videoPlayersContainerTagNum == kIpAddressesContainerTag) + { + // Entering IP Addresses container + TLV::TLVType ipAddressesContainerType = TLV::kTLVType_Array; + ReturnErrorOnFailure(reader.EnterContainer(ipAddressesContainerType)); + + size_t ipCount = 0; + while ((err = reader.Next()) == CHIP_NO_ERROR) + { + TLV::Tag ipAddressesContainerTag = reader.GetTag(); + if (!TLV::IsContextTag(ipAddressesContainerTag)) + { + ChipLogError(AppServer, "Unexpected non-context TLV tag."); + return CHIP_ERROR_INVALID_TLV_TAG; + } + + uint8_t ipAddressesContainerTagNum = static_cast(TLV::TagNumFromTag(ipAddressesContainerTag)); + if (ipAddressesContainerTagNum == kVideoPlayerIPAddressTag) + { + char ipAddressStr[Inet::IPAddress::kMaxStringLength]; + ReturnErrorOnFailure( + reader.GetBytes(reinterpret_cast(ipAddressStr), Inet::IPAddress::kMaxStringLength)); + + Inet::IPAddress addressInet; + VerifyOrReturnError(Inet::IPAddress::FromString(ipAddressStr, addressInet), CHIP_ERROR_INVALID_TLV_ELEMENT); + ipAddress[ipCount] = addressInet; + ipCount++; + continue; + } + } + if (err == CHIP_END_OF_TLV) + { + // Exiting IP Addresses container + ReturnErrorOnFailure(reader.ExitContainer(ipAddressesContainerType)); + continue; + } + } + + if (videoPlayersContainerTagNum == kContentAppEndpointsContainerTag) { outVideoPlayers[videoPlayerIndex].Initialize(nodeId, fabricIndex, nullptr, nullptr, vendorId, productId, deviceType, - deviceName); + deviceName, numIPs, ipAddress); // Entering Content App Endpoints container TLV::TLVType contentAppEndpointArrayContainerType = TLV::kTLVType_Array; ReturnErrorOnFailure(reader.EnterContainer(contentAppEndpointArrayContainerType)); diff --git a/examples/tv-casting-app/tv-casting-common/src/TargetVideoPlayerInfo.cpp b/examples/tv-casting-app/tv-casting-common/src/TargetVideoPlayerInfo.cpp index ff85e20eaaa0dd..70609f328fc5ef 100644 --- a/examples/tv-casting-app/tv-casting-common/src/TargetVideoPlayerInfo.cpp +++ b/examples/tv-casting-app/tv-casting-common/src/TargetVideoPlayerInfo.cpp @@ -24,7 +24,8 @@ CASEClientPool gCASEClientPool; CHIP_ERROR TargetVideoPlayerInfo::Initialize(NodeId nodeId, FabricIndex fabricIndex, std::function onConnectionSuccess, std::function onConnectionFailure, uint16_t vendorId, - uint16_t productId, uint16_t deviceType, const char * deviceName) + uint16_t productId, uint16_t deviceType, const char * deviceName, size_t numIPs, + chip::Inet::IPAddress * ipAddress) { ChipLogProgress(NotSpecified, "TargetVideoPlayerInfo nodeId=0x" ChipLogFormatX64 " fabricIndex=%d", ChipLogValueX64(nodeId), fabricIndex); @@ -33,6 +34,12 @@ CHIP_ERROR TargetVideoPlayerInfo::Initialize(NodeId nodeId, FabricIndex fabricIn mVendorId = vendorId; mProductId = productId; mDeviceType = deviceType; + mNumIPs = numIPs; + for (size_t i = 0; i < numIPs && i < chip::Dnssd::CommonResolutionData::kMaxIPAddresses; i++) + { + mIpAddress[i] = ipAddress[i]; + } + chip::Platform::CopyString(mDeviceName, chip::Dnssd::kMaxDeviceNameLen + 1, deviceName); for (auto & endpointInfo : mEndpoints) { @@ -118,3 +125,47 @@ void TargetVideoPlayerInfo::PrintInfo() } } } + +bool TargetVideoPlayerInfo::IsSameAs(const chip::Dnssd::DiscoveredNodeData * discoveredNodeData) +{ + // return false because 'this' VideoPlayer is not null + if (discoveredNodeData == nullptr) + { + return false; + } + + // return false because deviceNames are different + if (strcmp(mDeviceName, discoveredNodeData->commissionData.deviceName) != 0) + { + return false; + } + + // return false because not even a single IP Address matches + if (mNumIPs > 0) + { + bool matchFound = false; + for (size_t i = 0; i < mNumIPs && i < chip::Dnssd::CommonResolutionData::kMaxIPAddresses; i++) + { + for (size_t j = 0; + j < discoveredNodeData->resolutionData.numIPs && j < chip::Dnssd::CommonResolutionData::kMaxIPAddresses; j++) + { + if (mIpAddress[i] == discoveredNodeData->resolutionData.ipAddress[j]) + { + matchFound = true; + break; + } + } + if (matchFound) + { + break; + } + } + + if (!matchFound) + { + return false; + } + } + + return true; +} diff --git a/integrations/cloudbuild/build-all.yaml b/integrations/cloudbuild/build-all.yaml index 40ecf820ee845c..0071bcb413d320 100644 --- a/integrations/cloudbuild/build-all.yaml +++ b/integrations/cloudbuild/build-all.yaml @@ -34,8 +34,8 @@ steps: --target android-arm64-tv-casting-app --target android-arm64-tv-server --target android-x64-chip-tool - --target bl602-light - --target bouffalolab-BL706-IoT-DVK-light-rpc + --target bouffalolab-bl602-iot-matter-v1-light + --target bouffalolab-xt-zb6-devkit-light-rpc --target cc13x2x7_26x2x7-lock-ftd --target cc13x2x7_26x2x7-lock-mtd --target cc13x2x7_26x2x7-shell @@ -74,6 +74,14 @@ steps: --target k32w-light-no-ota --target k32w-lock --target k32w-shell + build + --create-archives /workspace/artifacts/ + - name: "connectedhomeip/chip-build-vscode:0.6.03" + env: + - PW_ENVIRONMENT_ROOT=/pwenv + args: + - >- + ./scripts/build/build_examples.py --enable-flashbundle --target linux-arm64-all-clusters-clang --target linux-arm64-all-clusters-app-nodeps --target linux-arm64-all-clusters-app-nodeps-ipv6only diff --git a/integrations/docker/images/chip-build-nrf-platform/Dockerfile b/integrations/docker/images/chip-build-nrf-platform/Dockerfile index 280534cac6c9fe..4e8d66447c3a98 100644 --- a/integrations/docker/images/chip-build-nrf-platform/Dockerfile +++ b/integrations/docker/images/chip-build-nrf-platform/Dockerfile @@ -2,7 +2,7 @@ ARG VERSION=latest FROM connectedhomeip/chip-build:${VERSION} as build # Compatible Nordic Connect SDK revision. -ARG NCS_REVISION=v2.0.2 +ARG NCS_REVISION=v2.1.1 RUN set -x \ && apt-get update \ diff --git a/integrations/docker/images/chip-build-openiotsdk/Dockerfile b/integrations/docker/images/chip-build-openiotsdk/Dockerfile new file mode 100644 index 00000000000000..d3daf90439b5d3 --- /dev/null +++ b/integrations/docker/images/chip-build-openiotsdk/Dockerfile @@ -0,0 +1,52 @@ +ARG VERSION=latest +FROM connectedhomeip/chip-build:${VERSION} as build + +RUN set -x \ + && apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -fy --no-install-recommends \ + wget=1.20.3-1ubuntu2 \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/ \ + && : # last line + +SHELL ["/bin/bash", "-o", "pipefail", "-c"] + +# ------------------------------------------------------------------------------ +# Download ARM GCC toolchain 10.3-2021.10 +RUN set -x \ + && wget -q https://developer.arm.com/-/media/Files/downloads/gnu-rm/10.3-2021.10/gcc-arm-none-eabi-10.3-2021.10-x86_64-linux.tar.bz2 \ + && tar -xjf gcc-arm-none-eabi-10.3-2021.10-x86_64-linux.tar.bz2 -C /opt \ + && rm -r gcc-arm-none-eabi-10.3-2021.10-x86_64-linux.tar.bz2 \ + && : # last line + +# ------------------------------------------------------------------------------ +# Install FVP Corstone 300 +RUN set -x \ + && wget -q https://developer.arm.com/-/media/Arm%20Developer%20Community/Downloads/OSS/FVP/Corstone-300/FVP_Corstone_SSE-300_11.16_26.tgz \ + && tar -xzf FVP_Corstone_SSE-300_11.16_26.tgz \ + && ./FVP_Corstone_SSE-300.sh --i-agree-to-the-contained-eula -d /opt/FVP_Corstone_SSE-300 -f --no-interactive \ + && rm -r FVP_Corstone_SSE-300_11.16_26.tgz FVP_Corstone_SSE-300.sh license_terms \ + && : # last line + +FROM connectedhomeip/chip-build:${VERSION} + +COPY --from=build /opt/gcc-arm-none-eabi-10.3-2021.10/ /opt/gcc-arm-none-eabi-10.3-2021.10/ +COPY --from=build /opt/FVP_Corstone_SSE-300/ /opt/FVP_Corstone_SSE-300/ + +# Required packages for building, running and testing +RUN set -x \ + && apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -fy \ + expect \ + telnet \ + srecord \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/ \ + && : # last line + +# ------------------------------------------------------------------------------ +# Configure environment variables +ENV FVP_CORSTONE_300_PATH=/opt/FVP_Corstone_SSE-300 +ENV ARM_GCC_TOOLCHAIN_PATH=/opt/gcc-arm-none-eabi-10.3-2021.10 + +ENV PATH="${PATH}:${FVP_CORSTONE_300_PATH}/models/Linux64_GCC-6.4:${ARM_GCC_TOOLCHAIN_PATH}/bin" diff --git a/integrations/docker/images/chip-build-openiotsdk/build.sh b/integrations/docker/images/chip-build-openiotsdk/build.sh new file mode 120000 index 00000000000000..fcb4d4ee75d531 --- /dev/null +++ b/integrations/docker/images/chip-build-openiotsdk/build.sh @@ -0,0 +1 @@ +../../build.sh \ No newline at end of file diff --git a/integrations/docker/images/chip-build-openiotsdk/run.sh b/integrations/docker/images/chip-build-openiotsdk/run.sh new file mode 120000 index 00000000000000..ccbd3501b330d9 --- /dev/null +++ b/integrations/docker/images/chip-build-openiotsdk/run.sh @@ -0,0 +1 @@ +../../run.sh \ No newline at end of file diff --git a/integrations/docker/images/chip-build-openiotsdk/version b/integrations/docker/images/chip-build-openiotsdk/version new file mode 120000 index 00000000000000..a4280acd348e7f --- /dev/null +++ b/integrations/docker/images/chip-build-openiotsdk/version @@ -0,0 +1 @@ +../chip-build/version \ No newline at end of file diff --git a/integrations/docker/images/chip-build-vscode/Dockerfile b/integrations/docker/images/chip-build-vscode/Dockerfile index 669d00f80138f1..d3c4dc78efe992 100644 --- a/integrations/docker/images/chip-build-vscode/Dockerfile +++ b/integrations/docker/images/chip-build-vscode/Dockerfile @@ -12,6 +12,7 @@ FROM connectedhomeip/chip-build-ameba:${VERSION} AS ameba FROM connectedhomeip/chip-build-k32w:${VERSION} AS k32w FROM connectedhomeip/chip-build-imx:${VERSION} AS imx FROM connectedhomeip/chip-build-ti:${VERSION} AS ti +FROM connectedhomeip/chip-build-openiotsdk:${VERSION} AS openiotsdk FROM connectedhomeip/chip-build-zap:${VERSION} AS zap FROM connectedhomeip/chip-build:${VERSION} @@ -47,6 +48,9 @@ COPY --from=imx /opt/fsl-imx-xwayland /opt/fsl-imx-xwayland COPY --from=ti /opt/ti/sysconfig_1.13.0 /opt/ti/sysconfig_1.13.0 +COPY --from=openiotsdk /opt/gcc-arm-none-eabi-10.3-2021.10/ /opt/gcc-arm-none-eabi-10.3-2021.10/ +COPY --from=openiotsdk /opt/FVP_Corstone_SSE-300/ /opt/FVP_Corstone_SSE-300/ + COPY --from=zap /opt/zap /opt/zap # Android license file "acceping" is done by writing license hashes @@ -66,6 +70,17 @@ RUN set -x \ && rm -rf /var/lib/apt/lists/* \ && : # last line +# Required for the Open IoT SDK platform +RUN set -x \ + && apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -fy \ + expect \ + telnet \ + srecord \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/ \ + && : # last line + # Required for the Bouffalolab platform RUN set -x \ && pip3 install bflb-iot-tool \ @@ -95,3 +110,6 @@ ENV ZEPHYR_TOOLCHAIN_VARIANT=gnuarmemb ENV TIZEN_VERSION 6.0 ENV TIZEN_SDK_ROOT /opt/tizen-sdk ENV TIZEN_SDK_SYSROOT $TIZEN_SDK_ROOT/platforms/tizen-$TIZEN_VERSION/mobile/rootstraps/mobile-$TIZEN_VERSION-device.core + +ENV FVP_CORSTONE_300_PATH=/opt/FVP_Corstone_SSE-300 +ENV ARM_GCC_TOOLCHAIN_PATH=/opt/gcc-arm-none-eabi-10.3-2021.10 diff --git a/integrations/docker/images/chip-build/Dockerfile b/integrations/docker/images/chip-build/Dockerfile index 861f5ecb2df4e7..782aa74f64afea 100644 --- a/integrations/docker/images/chip-build/Dockerfile +++ b/integrations/docker/images/chip-build/Dockerfile @@ -69,12 +69,12 @@ RUN set -x \ && git lfs install \ && : # last line -# Cmake (Mbed OS requires >=3.19.0-rc3 version which is not available in Ubuntu 20.04 repository) +# Cmake v3.23.1 RUN set -x \ && (cd /tmp \ - && wget --progress=dot:giga https://github.com/Kitware/CMake/releases/download/v3.19.3/cmake-3.19.3-Linux-x86_64.sh \ - && sh cmake-3.19.3-Linux-x86_64.sh --exclude-subdir --prefix=/usr/local \ - && rm -rf cmake-3.19.3-Linux-x86_64.sh) \ + && wget --progress=dot:giga https://github.com/Kitware/CMake/releases/download/v3.23.1/cmake-3.23.1-Linux-x86_64.sh \ + && sh cmake-3.23.1-Linux-x86_64.sh --exclude-subdir --prefix=/usr/local \ + && rm -rf cmake-3.23.1-Linux-x86_64.sh) \ && exec bash \ && : # last line diff --git a/integrations/docker/images/chip-build/version b/integrations/docker/images/chip-build/version index b288fd5e8ac786..a7be338c347fae 100644 --- a/integrations/docker/images/chip-build/version +++ b/integrations/docker/images/chip-build/version @@ -1 +1 @@ -0.6.03 Version bump reason: [Ameba] Replace C2 notify with indicate as required by Matter spec +0.6.05 Version bump reason: [nrfconnect] Update nRF Connect SDK version. diff --git a/scripts/build/BUILD.gn b/scripts/build/BUILD.gn index 9ea50936d5382a..60356666c0f6ae 100644 --- a/scripts/build/BUILD.gn +++ b/scripts/build/BUILD.gn @@ -41,7 +41,6 @@ pw_python_package("build_examples") { "builders/__init__.py", "builders/ameba.py", "builders/android.py", - "builders/bl602.py", "builders/bouffalolab.py", "builders/builder.py", "builders/efr32.py", diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index cd5c8cd87ceaa4..71440e607c8c97 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -34,7 +34,6 @@ from builders.qpg import QpgApp, QpgBoard, QpgBuilder from builders.telink import TelinkApp, TelinkBoard, TelinkBuilder from builders.tizen import TizenApp, TizenBoard, TizenBuilder -from builders.bl602 import Bl602App, Bl602Board, Bl602Builder from builders.bouffalolab import BouffalolabApp, BouffalolabBoard, BouffalolabBuilder from builders.imx import IMXApp, IMXBuilder from builders.genio import GenioApp, GenioBuilder @@ -442,21 +441,15 @@ def BuildTizenTarget(): return target -def BuildBl602Target(): - target = BuildTarget('bl602', Bl602Builder) - - target.AppendFixedTargets([ - TargetPart('light', board=Bl602Board.BL602BOARD, app=Bl602App.LIGHT), - ]) - - return target - - def BuildBouffalolabTarget(): target = BuildTarget('bouffalolab', BouffalolabBuilder) # Boards target.AppendFixedTargets([ + TargetPart('BL602-IoT-Matter-V1', board=BouffalolabBoard.BL602_IoT_Matter_V1, module_type="BL602"), + TargetPart('BL602-IOT-DVK-3S', board=BouffalolabBoard.BL602_IOT_DVK_3S, module_type="BL602"), + TargetPart('BL602-NIGHT-LIGHT', board=BouffalolabBoard.BL602_NIGHT_LIGHT, module_type="BL602"), + TargetPart('XT-ZB6-DevKit', board=BouffalolabBoard.BL706_IoT_DVK, module_type="BL706C-22"), TargetPart('BL706-IoT-DVK', board=BouffalolabBoard.BL706_IoT_DVK, module_type="BL706C-22"), TargetPart('BL706-NIGHT-LIGHT', board=BouffalolabBoard.BL706_NIGHT_LIGHT, module_type="BL702"), ]) @@ -466,6 +459,8 @@ def BuildBouffalolabTarget(): TargetPart('light', app=BouffalolabApp.LIGHT), ]) + target.AppendModifier('shell', enable_shell=True) + target.AppendModifier('115200', baudrate=115200) target.AppendModifier('rpc', enable_rpcs=True) return target @@ -516,7 +511,6 @@ def BuildTelinkTarget(): BUILD_TARGETS = [ BuildAmebaTarget(), BuildAndroidTarget(), - BuildBl602Target(), BuildBouffalolabTarget(), Buildcc13x2x7_26x2x7Target(), BuildCyw30739Target(), diff --git a/scripts/build/builders/bl602.py b/scripts/build/builders/bl602.py deleted file mode 100644 index f8fd4cacf32a5f..00000000000000 --- a/scripts/build/builders/bl602.py +++ /dev/null @@ -1,89 +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. - -import os -import platform -from enum import Enum, auto - -from .gn import GnBuilder - - -class Bl602App(Enum): - LOCK = auto() - LIGHT = auto() - ALL_CLUSTERS = auto() - - def ExampleName(self): - if self == Bl602App.LIGHT: - return 'lighting-app' - else: - raise Exception('Unknown app type: %r' % self) - - def AppNamePrefix(self): - if self == Bl602App.LIGHT: - return 'chip-bl602-lighting-example' - else: - raise Exception('Unknown app type: %r' % self) - - def FlashBundleName(self): - if self == Bl602App.LOCK: - return 'lighting_app.flashbundle.txt' - else: - raise Exception('Unknown app type: %r' % self) - - -class Bl602Board(Enum): - BL602BOARD = 1 - - def GnArgName(self): - if self == Bl602Board.BL602BOARD: - return 'BL-HWC-G1' - - -class Bl602Builder(GnBuilder): - - def __init__(self, - root, - runner, - app: Bl602App = Bl602App.LIGHT, - board: Bl602Board = Bl602Board.BL602BOARD): - super(Bl602Builder, self).__init__( - root=os.path.join(root, 'examples', - app.ExampleName(), 'bouffalolab', 'bl602'), - runner=runner) - - self.argsOpt = [] - - toolchain = os.path.join(root, '../../examples/platform/bouffalolab/common/toolchain') - toolchain = 'custom_toolchain="{}:riscv_gcc"'.format(toolchain) - if toolchain: - self.argsOpt.append(toolchain) - - self.app = app - self.board = board - - def GnBuildArgs(self): - return self.argsOpt + ['bl602_board="%s"' % self.board.GnArgName()] - - def build_outputs(self): - items = { - '%s.out' % self.app.AppNamePrefix(): - os.path.join(self.output_dir, '%s.out' % - self.app.AppNamePrefix()), - '%s.out.map' % self.app.AppNamePrefix(): - os.path.join(self.output_dir, - '%s.out.map' % self.app.AppNamePrefix()), - } - - return items diff --git a/scripts/build/builders/bouffalolab.py b/scripts/build/builders/bouffalolab.py index b391251093653f..2137949a325ff2 100644 --- a/scripts/build/builders/bouffalolab.py +++ b/scripts/build/builders/bouffalolab.py @@ -42,11 +42,23 @@ def FlashBundleName(self): class BouffalolabBoard(Enum): - BL706_IoT_DVK = 1 - BL706_NIGHT_LIGHT = 2 + BL602_IoT_Matter_V1 = auto() + BL602_IOT_DVK_3S = auto() + BL602_NIGHT_LIGHT = auto() + XT_ZB6_DevKit = auto() + BL706_IoT_DVK = auto() + BL706_NIGHT_LIGHT = auto() def GnArgName(self): - if self == BouffalolabBoard.BL706_IoT_DVK: + if self == BouffalolabBoard.BL602_IoT_Matter_V1: + return 'BL602-IoT-Matter-V1' + elif self == BouffalolabBoard.BL602_IOT_DVK_3S: + return 'BL602-IOT-DVK-3S' + elif self == BouffalolabBoard.BL602_NIGHT_LIGHT: + return 'BL602-NIGHT-LIGHT' + elif self == BouffalolabBoard.XT_ZB6_DevKit: + return 'XT-ZB6-DevKit' + elif self == BouffalolabBoard.BL706_IoT_DVK: return 'BL706-IoT-DVK' elif self == BouffalolabBoard.BL706_NIGHT_LIGHT: return 'BL706-NIGHT-LIGHT' @@ -63,6 +75,8 @@ def __init__(self, board: BouffalolabBoard = BouffalolabBoard.BL706_IoT_DVK, enable_rpcs: bool = False, module_type: str = "BL706C-22", + baudrate=2000000, + enable_shell: bool = False ): bouffalo_chip = "bl702" if "BL70" in module_type else "bl602" @@ -83,7 +97,12 @@ def __init__(self, self.board = board self.argsOpt.append('board=\"{}\"'.format(self.board.GnArgName())) - self.argsOpt.append('module_type=\"{}\"'.format(module_type)) + self.argsOpt.append('baudrate=\"{}\"'.format(baudrate)) + + if bouffalo_chip == "bl702": + self.argsOpt.append('module_type=\"{}\"'.format(module_type)) + if enable_shell and not enable_rpcs: + self.argsOpt.append('chip_build_libshell=true') if enable_rpcs: self.argsOpt.append('import("//with_pw_rpc.gni")') diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index 8073f89ff0dfa6..90c216a9afb0f9 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -1,7 +1,6 @@ ameba-amebad-{all-clusters,all-clusters-minimal,light,pigweed} 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} -bl602-light -bouffalolab-{bl706-iot-dvk,bl706-night-light}-light[-rpc] +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] cc13x2x7_26x2x7-{all-clusters,all-clusters-minimal,lock,pump,pump-controller,shell}[-ftd][-mtd] cyw30739-cyw930739m2evb_01-{light,lock,ota-requestor}[-no-progress-logging] efr32-{brd4161a,brd4187c,brd4163a,brd4164a,brd4166a,brd4170a,brd4186a,brd4187a,brd4304a}-{window-covering,switch,unit-test,light,lock}[-rpc][-with-ota-requestor] diff --git a/scripts/checkout_submodules.py b/scripts/checkout_submodules.py index ebea028957dfcf..c5967949b9cd3a 100755 --- a/scripts/checkout_submodules.py +++ b/scripts/checkout_submodules.py @@ -45,6 +45,7 @@ 'webos', 'mw320', 'genio', + 'openiotsdk', ]) Module = namedtuple('Module', 'name path platforms') diff --git a/scripts/constraints.txt b/scripts/constraints.txt index f29bbc7d5a4337..de47efb650bebd 100644 --- a/scripts/constraints.txt +++ b/scripts/constraints.txt @@ -234,7 +234,14 @@ pyserial==3.5 # mbed-tools # mobly pytest==6.2.5 ; platform_machine != "aarch64" and sys_platform == "linux" - # via -r requirements.mbed.txt + # via + # -r requirements.mbed.txt + # pytest-json-report + # pytest-metadata +pytest-json-report==1.5.0 + # via -r requirements.openiotsdk.txt +pytest-metadata==2.0.2 + # via pytest-json-report python-dateutil==2.8.1 # via # pandas diff --git a/scripts/examples/gn_bl602_example.sh b/scripts/examples/gn_bl602_example.sh deleted file mode 100755 index 9ae95a0a960d2d..00000000000000 --- a/scripts/examples/gn_bl602_example.sh +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env bash - -# -# 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. -# - -set -e - -BL602_BOARD=BL-HWC-G1 - -# Build script for GN examples GitHub workflow. - -MATTER_ROOT=$(dirname "$(readlink -f "$0")")/../../ - -source "$(dirname "$0")/../../scripts/activate.sh" - -USAGE="./scripts/examples/gn_bl602_example.sh example_dir output_dir" - -if [ $# -lt 2 ]; then - echo "Usage: $USAGE" - exit 1 -fi - -EXAMPLE_DIR=examples/$1/bouffalolab/bl602/ -shift -OUTPUT_DIR=$1 -shift - -GN_ARGS=() - -NINJA_ARGS=() - -for arg; do - case $arg in - -v) - NINJA_ARGS+=(-v) - ;; - *=*) - GN_ARGS+=("$arg") - ;; - *import*) - GN_ARGS+=("$arg") - ;; - *) - echo >&2 "invalid argument: $arg" - exit 2 - ;; - esac -done - -gn gen --fail-on-unused-args --root="$EXAMPLE_DIR" "$OUTPUT_DIR" --args="${GN_ARGS[*]} custom_toolchain=\"$MATTER_ROOT/examples/platform/bouffalolab/common/toolchain:riscv_gcc\"" - -ninja -C "$OUTPUT_DIR" "${NINJA_ARGS[@]}" diff --git a/scripts/examples/gn_bouffalolab_example.sh b/scripts/examples/gn_bouffalolab_example.sh index f04307607ba30b..a719563f38cb03 100755 --- a/scripts/examples/gn_bouffalolab_example.sh +++ b/scripts/examples/gn_bouffalolab_example.sh @@ -23,29 +23,23 @@ set -e MATTER_ROOT=$(dirname "$(readlink -f "$0")")/../../ source "$MATTER_ROOT/scripts/activate.sh" -# export BL_IOT_SDK_PATH=$MATTER_ROOT/third_party/bouffalolab/repo +bl602_boards=("BL602-IoT-Matter-V1" "BL602-NIGHT-LIGHT") +bl602_module_type="BL602" -# if [[ "$OSTYPE" == "linux-gnu"* ]]; then -# export PATH="$BL_IOT_SDK_PATH/toolchain/riscv/Linux/bin:$PATH" -# elif [[ "$OSTYPE" == "darwin"* ]]; then -# export PATH="$BL_IOT_SDK_PATH/toolchain/riscv/Darwin/bin:$PATH" -# fi - -bl702_boards=("BL706-IoT-DVK" "BL706-NIGHT-LIGHT") +bl702_boards=("XT-ZB6-DevKit" "BL706-IoT-DVK" "BL706-NIGHT-LIGHT") bl702_modules=("BL702" "BL706C-22") bl702_module_type="BL706C-22" print_help() { + bl602_boards_help="" + for board in "${bl602_boards[@]}"; do + bl602_boards_help=$bl602_boards_help$board"\n " + done bl702_boards_help="" for board in "${bl702_boards[@]}"; do bl702_boards_help=$bl702_boards_help$board"\n " done - bl702_modules_help="" - for module in "${bl702_modules[@]}"; do - bl702_modules_help=$bl702_modules_help$module"\n " - done - echo -e "Build script for Bouffalolab Matter examples Format: ./scripts/examples/gn_bouffalolab_example.sh [] @@ -59,6 +53,7 @@ print_help() { Identifier of the board for which this app is built Currently Supported : + $bl602_boards_help $bl702_boards_help - optional noteworthy build options for Bouffalolab IOT Matter examples chip_build_libshell @@ -80,8 +75,7 @@ print_help() { baudrate UART baudrate for log output and UART shell command, e.g, baudrate=2000000, by default. module_type - Bouffalolab chip module, e.g, module_type=\"BL706C-22\". Currently Supported: - $bl702_modules_help + Bouffalolab chip module. " } @@ -120,7 +114,14 @@ else shift done - if [[ "${bl702_boards[@]}" =~ "$board_name" ]]; then + if [[ "${bl602_boards[@]}" =~ "$board_name" ]]; then + bouffalo_chip="bl602" + + optArgs=board=\"$board_name\"" "$optArgs + optArgs=module_type=\"$bl602_module_type\"" "$optArgs + optArgs=baudrate=\"$baudrate\"" "$optArgs + + elif [[ "${bl702_boards[@]}" =~ "$board_name" ]]; then bouffalo_chip="bl702" optArgs=board=\"$board_name\"" "$optArgs diff --git a/scripts/flashing/bl602_firmware_utils.py b/scripts/flashing/bl602_firmware_utils.py deleted file mode 100755 index a07e7dbf51c3e2..00000000000000 --- a/scripts/flashing/bl602_firmware_utils.py +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env python3 -# 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. -"""Flash an BL602 device. - -This is layered so that a caller can perform individual operations -through an `Flasher` instance, or operations according to a command line. -For `Flasher`, see the class documentation. For the parse_command() -interface or standalone execution: - -usage: bl602_firmware_utils.py [-h] [--verbose] [--erase] [--application FILE] - [--verify_application] [--reset] [--skip_reset] - [--commander FILE] [--device DEVICE] - [--serialno SERIAL] - -Flash BL602 device - -optional arguments: - -h, --help show this help message and exit - -configuration: - --verbose, -v Report more verbosely - --commander FILE File name of the commander executable - --device DEVICE, -d DEVICE - Device family or platform to target - --serialno SERIAL, -s SERIAL - Serial number of device to flash - -operations: - --erase Erase device - --application FILE Flash an image - --verify_application, --verify-application - Verify the image after flashing - --reset Reset device after flashing - --skip_reset, --skip-reset - Do not reset device after flashing -""" - -import sys - -import firmware_utils - -# Additional options that can be use to configure an `Flasher` -# object (as dictionary keys) and/or passed as command line options. -BL602_OPTIONS = { - # Configuration options define properties used in flashing operations. - 'configuration': { - # Tool configuration options. - 'commander': { - 'help': 'File name of the commander executable', - 'default': 'commander', - 'argparse': { - 'metavar': 'FILE' - }, - 'verify': ['{commander}', '--version'], - 'error': - """\ - Unable to execute {commander}. - - Please ensure that this tool is installed and - available. See the BL602 example README for - installation instructions. - - """, - }, - 'device': { - 'help': 'Device family or platform to target', - 'default': 'BL602', - 'alias': ['-d'], - 'argparse': { - 'metavar': 'DEVICE' - }, - }, - 'serialno': { - 'help': 'Serial number of device to flash', - 'default': None, - 'alias': ['-s'], - 'argparse': { - 'metavar': 'SERIAL' - }, - }, - }, -} - - -class Flasher(firmware_utils.Flasher): - """Manage bl602 flashing.""" - - def __init__(self, **options): - super().__init__(platform='BL602', module=__name__, **options) - self.define_options(BL602_OPTIONS) - - # Common command line arguments for commander device subcommands. - DEVICE_ARGUMENTS = [{'optional': 'serialno'}, {'optional': 'device'}] - - def erase(self): - """Perform `commander device masserase`.""" - return self.run_tool( - 'commander', ['device', 'masserase', self.DEVICE_ARGUMENTS], - name='Erase device') - - def verify(self, image): - """Verify image.""" - return self.run_tool( - 'commander', - ['verify', self.DEVICE_ARGUMENTS, image], - name='Verify', - pass_message='Verified', - fail_message='Not verified', - fail_level=2) - - def flash(self, image): - """Flash image.""" - return self.run_tool( - 'commander', - ['flash', self.DEVICE_ARGUMENTS, image], - name='Flash') - - def reset(self): - """Reset the device.""" - return self.run_tool( - 'commander', - ['device', 'reset', self.DEVICE_ARGUMENTS], - name='Reset') - - def actions(self): - """Perform actions on the device according to self.option.""" - self.log(3, 'Options:', self.option) - - if self.option.erase: - if self.erase().err: - return self - - application = self.optional_file(self.option.application) - if application: - if self.flash(application).err: - return self - if self.option.verify_application: - if self.verify(application).err: - return self - if self.option.reset is None: - self.option.reset = True - - if self.option.reset: - if self.reset().err: - return self - - return self - - -if __name__ == '__main__': - sys.exit(Flasher().flash_command(sys.argv)) diff --git a/scripts/flashing/bouffalolab_firmware_utils.py b/scripts/flashing/bouffalolab_firmware_utils.py index 01473dcc04c3ba..9bbccde7621265 100644 --- a/scripts/flashing/bouffalolab_firmware_utils.py +++ b/scripts/flashing/bouffalolab_firmware_utils.py @@ -19,7 +19,8 @@ import pathlib import firmware_utils -from bflb_iot_tool.__main__ import run_main +import bflb_iot_tool +import bflb_iot_tool.__main__ # Additional options that can be use to configure an `Flasher` @@ -98,6 +99,28 @@ def __init__(self, **options): super().__init__(platform=None, module=__name__, **options) self.define_options(BOUFFALO_OPTIONS) + def get_boot_image(self, config_path): + + boot_image_guess = None + + for root, dirs, files in os.walk(config_path, topdown=False): + for name in files: + if name == "boot2_isp_release.bin": + return os.path.join(root, name) + elif not boot_image_guess and name.find("release") >= 0: + boot_image_guess = os.path.join(root, name) + + return boot_image_guess + + def get_dts_file(self, config_path, xtal_value): + + for root, dirs, files in os.walk(config_path, topdown=False): + for name in files: + if name.find(xtal_value) >= 0: + return os.path.join(config_path, name) + + return None + def verify(self): """Not supported""" self.log(0, "Verification is done after image flashed.") @@ -110,6 +133,8 @@ def actions(self): """Perform actions on the device according to self.option.""" self.log(3, 'Options:', self.option) + tool_path = os.path.dirname(bflb_iot_tool.__file__) + options_keys = BOUFFALO_OPTIONS["configuration"].keys() arguments = [__file__] work_dir = None @@ -121,6 +146,12 @@ def actions(self): if self.option.verify_application: self.verify() + chip_name = None + chip_config_path = None + boot_image = None + dts_path = None + xtal_value = None + command_args = {} for (key, value) in dict(vars(self.option)).items(): @@ -147,20 +178,45 @@ def actions(self): else: arg = ("--{}={}".format(key, value)).strip() + if key == "chipname": + chip_name = value + elif key == "xtal": + xtal_value = value + elif key == "dts": + dts_path = value + arguments.append(arg) + print(key, value) + + print(dts_path, xtal_value) + if not dts_path and xtal_value: + chip_config_path = os.path.join(tool_path, "chips", chip_name, "device_tree") + dts_path = self.get_dts_file(chip_config_path, xtal_value) + arguments.append("--dts") + arguments.append(dts_path) + if self.option.erase: arguments.append("--erase") + if chip_name == "bl602": + chip_config_path = os.path.join(tool_path, "chips", chip_name, "builtin_imgs") + boot_image = self.get_boot_image(chip_config_path) + arguments.append("--boot2") + arguments.append(boot_image) + os.chdir(work_dir) arguments[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', arguments[0]) sys.argv = arguments - run_main() + print("arguments", arguments) + bflb_iot_tool.__main__.run_main() return self if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(Flasher().flash_command(sys.argv)) diff --git a/scripts/python.json b/scripts/python.json index 06db285a2607c8..0df6cc494ab40a 100644 --- a/scripts/python.json +++ b/scripts/python.json @@ -4,11 +4,6 @@ "path": "infra/3pp/tools/cpython3/${platform}", "platforms": ["mac-amd64", "windows-amd64"], "tags": ["version:2@3.9.5.chromium.19"] - }, - { - "path": "fuchsia/third_party/cmake/${platform}", - "platforms": ["mac-amd64", "linux-amd64"], - "tags": ["version:3.20.20210428-g857373c"] } ] } diff --git a/scripts/requirements.openiotsdk.txt b/scripts/requirements.openiotsdk.txt new file mode 100644 index 00000000000000..319312169ae92e --- /dev/null +++ b/scripts/requirements.openiotsdk.txt @@ -0,0 +1 @@ +pytest-json-report>=1.5.0 \ No newline at end of file diff --git a/scripts/requirements.txt b/scripts/requirements.txt index e33963c48c2a42..21a3bb5f5cf0a0 100644 --- a/scripts/requirements.txt +++ b/scripts/requirements.txt @@ -11,6 +11,9 @@ virtualenv # bouffalolab -r requirements.bouffalolab.txt +# openiotsdk +-r requirements.openiotsdk.txt + # cirque tests requests>=2.24.0 diff --git a/src/app/tests/TestReadInteraction.cpp b/src/app/tests/TestReadInteraction.cpp index 5ce4a3c33407c5..fc9e37964ef9dc 100644 --- a/src/app/tests/TestReadInteraction.cpp +++ b/src/app/tests/TestReadInteraction.cpp @@ -1565,8 +1565,6 @@ void TestReadInteraction::TestSubscribeRoundtrip(nlTestSuite * apSuite, void * a delegate.mGotEventResponse = false; delegate.mNumAttributeResponse = 0; - printf("HereHere\n"); - err = engine->GetReportingEngine().SetDirty(dirtyPath1); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); err = engine->GetReportingEngine().SetDirty(dirtyPath2); @@ -1918,13 +1916,16 @@ void TestReadInteraction::TestSubscribeWildcard(nlTestSuite * apSuite, void * ap err = engine->GetReportingEngine().SetDirty(dirtyPath); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - // - // Not sure why I had to add this, and didn't have cycles to figure out why. - // Tracked in Issue #17528. + // We need to DrainAndServiceIO() until attribute callback will be called. + // This is not correct behavior and is tracked in Issue #17528. // - ctx.DrainAndServiceIO(); + int last; + do + { + last = delegate.mNumAttributeResponse; + ctx.DrainAndServiceIO(); + } while (last != delegate.mNumAttributeResponse); NL_TEST_ASSERT(apSuite, delegate.mGotReport); // Mock endpoint3 has 13 attributes in total, and we subscribed twice. diff --git a/src/app/util/af-event.cpp b/src/app/util/af-event.cpp index 2a4ae5e1eb27d7..6e381149c083b8 100644 --- a/src/app/util/af-event.cpp +++ b/src/app/util/af-event.cpp @@ -180,17 +180,6 @@ EmberStatus emberAfScheduleClusterTick(EndpointId endpoint, ClusterId clusterId, (sleepControl == EMBER_AF_STAY_AWAKE ? EMBER_AF_STAY_AWAKE : EMBER_AF_OK_TO_SLEEP)); } -EmberStatus emberAfScheduleClientTickExtended(EndpointId endpoint, ClusterId clusterId, uint32_t delayMs, - EmberAfEventPollControl pollControl, EmberAfEventSleepControl sleepControl) -{ - return emberAfScheduleTickExtended(endpoint, clusterId, EMBER_AF_CLIENT_CLUSTER_TICK, delayMs, pollControl, sleepControl); -} - -EmberStatus emberAfScheduleClientTick(EndpointId endpoint, ClusterId clusterId, uint32_t delayMs) -{ - return emberAfScheduleClientTickExtended(endpoint, clusterId, delayMs, EMBER_AF_LONG_POLL, EMBER_AF_OK_TO_SLEEP); -} - EmberStatus emberAfScheduleServerTickExtended(EndpointId endpoint, ClusterId clusterId, uint32_t delayMs, EmberAfEventPollControl pollControl, EmberAfEventSleepControl sleepControl) { @@ -213,11 +202,6 @@ EmberStatus emberAfDeactivateClusterTick(EndpointId endpoint, ClusterId clusterI return EMBER_BAD_ARGUMENT; } -EmberStatus emberAfDeactivateClientTick(EndpointId endpoint, ClusterId clusterId) -{ - return emberAfDeactivateClusterTick(endpoint, clusterId, EMBER_AF_CLIENT_CLUSTER_TICK); -} - EmberStatus emberAfDeactivateServerTick(EndpointId endpoint, ClusterId clusterId) { return emberAfDeactivateClusterTick(endpoint, clusterId, EMBER_AF_SERVER_CLUSTER_TICK); diff --git a/src/app/util/af.h b/src/app/util/af.h index 04c8f08492444f..043c5e80ebe5bb 100644 --- a/src/app/util/af.h +++ b/src/app/util/af.h @@ -61,15 +61,6 @@ static constexpr uint16_t kEmberInvalidEndpointIndex = 0xFFFF; */ const EmberAfAttributeMetadata * emberAfLocateAttributeMetadata(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId); - -/** - * @brief Returns true if endpoint contains the ZCL cluster with specified id. - * - * This function returns true regardless of whether - * the endpoint contains server, client or both in the Zigbee cluster Library. - */ -bool emberAfContainsCluster(chip::EndpointId endpoint, chip::ClusterId clusterId); - /** * @brief Returns true if endpoint contains the ZCL server with specified id. * @@ -89,14 +80,6 @@ bool emberAfContainsServer(chip::EndpointId endpoint, chip::ClusterId clusterId) */ bool emberAfContainsServerFromIndex(uint16_t index, chip::ClusterId clusterId); -/** - * @brief Returns true if endpoint contains the ZCL client with specified id. - * - * This function returns true if - * the endpoint contains client of a given cluster. - */ -bool emberAfContainsClient(chip::EndpointId endpoint, chip::ClusterId clusterId); - /** * @brief write an attribute, performing all the checks. * @@ -120,22 +103,6 @@ EmberAfStatus emberAfWriteAttribute(chip::EndpointId endpoint, chip::ClusterId c // TODO: Remove this define. #define emberAfWriteServerAttribute emberAfWriteAttribute -/** - * @brief Function that test the success of attribute write. - * - * This function returns success if attribute write would be successful. - * It does not actually write anything, just validates for read-only and - * data-type. - * - * @param endpoint Zigbee endpoint number - * @param cluster Cluster ID of the sought cluster. - * @param attributeID Attribute ID of the sought attribute. - * @param dataPtr Location where attribute will be written from. - * @param dataType ZCL attribute type. - */ -EmberAfStatus emberAfVerifyAttributeWrite(chip::EndpointId endpoint, chip::ClusterId cluster, chip::AttributeId attributeID, - uint8_t * dataPtr, EmberAfAttributeType dataType); - /** * @brief Read the attribute value, performing all the checks. * @@ -216,12 +183,6 @@ uint16_t emberAfIndexFromEndpoint(chip::EndpointId endpoint); */ uint16_t emberAfIndexFromEndpointIncludingDisabledEndpoints(chip::EndpointId endpoint); -/** - * Returns the endpoint index within a given cluster (Client-side), - * looking only for standard clusters. - */ -uint16_t emberAfFindClusterClientEndpointIndex(chip::EndpointId endpoint, chip::ClusterId clusterId); - /** * Returns the endpoint index within a given cluster (Server-side), * looking only for standard clusters. @@ -291,11 +252,6 @@ uint8_t * emberAfGetString(uint8_t * message, uint16_t currentIndex, uint16_t ms * @brief Function that extracts a ZCL long string from the message buffer */ uint8_t * emberAfGetLongString(uint8_t * message, uint16_t currentIndex, uint16_t msgLen); -/* - * @brief Function that extracts a ZCL Date from the message buffer and returns it - * in the given destination. Returns the number of bytes copied. - */ -uint8_t emberAfGetDate(uint8_t * message, uint16_t currentIndex, uint16_t msgLen, EmberAfDate * destination); /** * @brief Macro for consistency, that extracts single byte out of the message @@ -332,30 +288,11 @@ void emberAfCopyString(uint8_t * dest, const uint8_t * src, size_t size); */ void emberAfCopyLongString(uint8_t * dest, const uint8_t * src, size_t size); -/* - * @brief Function that determines the size of a zigbee Cluster Library - * attribute value (where the attribute could be non-string, string, or long - * string). For strings, the size includes the length of the string plus the - * number of the string's length prefix byte(s). - */ -uint16_t emberAfAttributeValueSize(chip::ClusterId clusterId, chip::AttributeId attributeId, EmberAfAttributeType dataType, - const uint8_t * buffer); - /** @} END Attribute Storage */ /** @name Device Control */ // @{ -/** - * @brief Function that checks if endpoint is enabled. - * - * This function returns true if device at a given endpoint is - * enabled. At startup all endpoints are enabled. - * - * @param endpoint Zigbee endpoint number - */ -bool emberAfIsDeviceEnabled(chip::EndpointId endpoint); - /** * @brief Function that checks if endpoint is identifying * @@ -406,37 +343,6 @@ bool emberAfIsThisDataTypeAStringType(EmberAfAttributeType dataType); /** @brief Returns true if a given ZCL data type is a list type. */ bool emberAfIsThisDataTypeAListType(EmberAfAttributeType dataType); -/** - * @brief The mask applied by ::emberAfNextSequence when generating ZCL - * sequence numbers. - */ -#define EMBER_AF_ZCL_SEQUENCE_MASK 0x7F - -/** - * @brief The mask applied to generated message tags used by the framework when sending messages via EZSP. - * Customers who call ezspSend functions directly must use message tags outside this mask - */ -#define EMBER_AF_MESSAGE_TAG_MASK 0x7F - -/** - * @brief Increments the ZCL sequence number and returns the value. - * - * ZCL messages have sequence numbers so that they can be matched up with other - * messages in the transaction. To avoid conflicts with sequence numbers - * generated independently by the application, this API returns sequence - * numbers with the high bit clear. If the application generates its own - * sequence numbers, it should use numbers with the high bit set. - * - * @return The next ZCL sequence number. - */ -uint8_t emberAfNextSequence(void); - -/** - * @brief Retrieves the last sequence number that was used. - * - */ -uint8_t emberAfGetLastSequenceNumber(void); - /** * @brief Simple integer comparison function. * Compares two values of a known length as integers. @@ -456,136 +362,22 @@ int8_t emberAfCompareValues(const uint8_t * val1, const uint8_t * val2, uint16_t */ void emberAfGetEui64(EmberEUI64 returnEui64); -#if (BIGENDIAN_CPU) || defined(EZSP_HOST) -// Normally this is provided by the stack code, but on the host -// it is provided by the application code. -void emberReverseMemCopy(uint8_t * dest, const uint8_t * src, uint16_t length); -#endif - /** * @brief Returns the node ID of the local node. */ EmberNodeId emberAfGetNodeId(void); -#if defined(DOXYGEN_SHOULD_SKIP_THIS) || defined(EZSP_HOST) -/** - * @brief Generates a random key (link, network, or master). - */ -EmberStatus emberAfGenerateRandomKey(EmberKeyData * result); -#else -#define emberAfGenerateRandomKey(result) emberGenerateRandomKey(result) -#endif - -/** - * @brief Returns the PAN ID of the local node. - */ -EmberPanId emberAfGetPanId(void); - -/** - * @brief Returns the radioChannel of the current network - */ -uint8_t emberAfGetRadioChannel(void); - -/* - * @brief Returns a binding index that matches the current incoming message, if - * known. - */ -uint8_t emberAfGetBindingIndex(void); - -/* - * @brief Returns an address index that matches the current incoming message, - * if known. - */ -uint8_t emberAfGetAddressIndex(void); - /** * @brief Returns the current network state. This call caches the results * on the host to prevent frequent EZSP transactions. */ EmberNetworkStatus emberAfNetworkState(void); -/** - * @brief Returns the current network parameters. - */ -EmberStatus emberAfGetNetworkParameters(EmberNodeType * nodeType, EmberNetworkParameters * parameters); - -/** - * @brief Returns the current node type. - */ -EmberStatus emberAfGetNodeType(EmberNodeType * nodeType); - -/** - */ -#define EMBER_AF_REJOIN_DUE_TO_END_DEVICE_MOVE 0xA0 -#define EMBER_AF_REJOIN_DUE_TO_TC_KEEPALIVE_FAILURE 0xA1 -#define EMBER_AF_REJOIN_DUE_TO_CLI_COMMAND 0xA2 -#define EMBER_AF_REJOIN_DUE_TO_WWAH_CONNECTIVITY_MANAGER 0xA3 - -#define EMBER_AF_REJOIN_FIRST_REASON EMBER_AF_REJOIN_DUE_TO_END_DEVICE_MOVE -#define EMBER_AF_REJOIN_LAST_REASON EMBER_AF_REJOIN_DUE_TO_END_DEVICE_MOVE - -/** - * @brief Enables local permit join and optionally broadcasts the ZDO - * Mgmt_Permit_Join_req message. This API can be called from any device - * type and still return EMBER_SUCCESS. If the API is called from an - * end device, the permit association bit will just be left off. - * - * @param duration the duration that the permit join bit will remain on - * and other devices will be able to join the current network. - * @param broadcastMgmtPermitJoin whether or not to broadcast the ZDO - * Mgmt_Permit_Join_req message. - * - * @returns status of whether or not permit join was enabled. - */ -EmberStatus emberAfPermitJoin(uint8_t duration, bool broadcastMgmtPermitJoin); - -#ifdef DOXYGEN_SHOULD_SKIP_THIS -/** - * @brief Enables local permit join and broadcasts the ZDO - * Mgmt_Permit_Join_req message. This API can be called from any device - * type and still return EMBER_SUCCESS. If the API is called from an - * end device, the permit association bit will just be left off. - * - * @param duration the duration that the permit join bit will remain on - * and other devices will be able to join the current network. - * - * @returns status of whether or not permit join was enabled. - */ -EmberStatus emberAfBroadcastPermitJoin(uint8_t duration); -#else -#define emberAfBroadcastPermitJoin(duration) emberAfPermitJoin((duration), true) -#endif - /** @} END Miscellaneous */ /** @name Sleep Control */ //@{ -/** - * @brief A function used to add a task to the task register. - */ -#define emberAfAddToCurrentAppTasks(x) emberAfAddToCurrentAppTasksCallback(x) - -/** - * @brief A function used to remove a task from the task register. - */ -#define emberAfRemoveFromCurrentAppTasks(x) emberAfRemoveFromCurrentAppTasksCallback(x) - -/** - * @brief A macro used to retrieve the bitmask of all application - * frameowrk tasks currently in progress. This can be useful for debugging if - * some task is holding the device out of hibernation. - */ -#define emberAfCurrentAppTasks() emberAfGetCurrentAppTasksCallback() - -/** - * @brief a function used to run the application framework's - * event mechanism. This function passes the application - * framework's event tables to the ember stack's event - * processing code. - */ -void emberAfRunEvents(void); - /** * @brief Friendly define for use in the scheduling or canceling client events * with emberAfScheduleClusterTick() and emberAfDeactivateClusterTick(). @@ -645,36 +437,6 @@ EmberStatus emberAfScheduleTickExtended(chip::EndpointId endpoint, chip::Cluster EmberStatus emberAfScheduleClusterTick(chip::EndpointId endpoint, chip::ClusterId clusterId, bool isClient, uint32_t delayMs, EmberAfEventSleepControl sleepControl); -/** - * @brief A function used to schedule a cluster client event. This function - * is a wrapper for ::emberAfScheduleTickExtended. - * - * @param endpoint the endpoint of the event to be scheduled - * @param clusterId the cluster id of the event to be scheduled - * @param delayMs the number of milliseconds until the event should be called. - * @param pollControl ::EMBER_AF_SHORT_POLL if the cluster needs to short poll - * or ::EMBER_AF_LONG_POLL otherwise. - * @param sleepControl ::EMBER_AF_STAY_AWAKE if the cluster needs to stay awake - * or EMBER_AF_OK_TO_SLEEP otherwise. - * - * @return EMBER_SUCCESS if the event was scheduled or an error otherwise. - */ -EmberStatus emberAfScheduleClientTickExtended(chip::EndpointId endpoint, chip::ClusterId clusterId, uint32_t delayMs, - EmberAfEventPollControl pollControl, EmberAfEventSleepControl sleepControl); - -/** - * @brief A function used to schedule a cluster client event. This function - * is a wrapper for ::emberAfScheduleClientTickExtended. It indicates that - * the cluster client on the given endpoint can long poll and can sleep. - * - * @param endpoint the endpoint of the event to be scheduled. - * @param clusterId the cluster id of the event to be scheduled. - * @param delayMs the number of milliseconds until the event should be called. - * - * @return EMBER_SUCCESS if the event was scheduled or an error otherwise. - */ -EmberStatus emberAfScheduleClientTick(chip::EndpointId endpoint, chip::ClusterId clusterId, uint32_t delayMs); - /** * @brief A function used to schedule a cluster server event. This function * is a wrapper for ::emberAfScheduleTickExtended. @@ -721,17 +483,6 @@ EmberStatus emberAfScheduleServerTick(chip::EndpointId endpoint, chip::ClusterId */ EmberStatus emberAfDeactivateClusterTick(chip::EndpointId endpoint, chip::ClusterId clusterId, bool isClient); -/** - * @brief A function used to deactivate a cluster client event. This function - * is a wrapper for ::emberAfDeactivateClusterTick. - * - * @param endpoint the endpoint of the event to be deactivated. - * @param clusterId the cluster id of the event to be deactivated. - * - * @return EMBER_SUCCESS if the event was deactivated or an error otherwise. - */ -EmberStatus emberAfDeactivateClientTick(chip::EndpointId endpoint, chip::ClusterId clusterId); - /** * @brief A function used to deactivate a cluster server event. This function * is a wrapper for ::emberAfDeactivateClusterTick. @@ -758,180 +509,11 @@ EmberStatus emberAfDeactivateServerTick(chip::EndpointId endpoint, chip::Cluster */ EmberStatus emberEventControlSetDelayMS(EmberEventControl * control, uint32_t delayMs); -/** - * @brief Sets the ::EmberEventControl to run "delayQs" quarter seconds in the - * future. The 'quarter seconds' are actually 256 milliseconds long. This - * function first verifies that the delay is within the acceptable range before - * scheduling the event. - * - * @param control a pointer to the event control. - * @param delayQs the number of quarter seconds until the next event. - * - * @return If delayQs is less than or equal to - ::EMBER_MAX_EVENT_CONTROL_DELAY_QS, this function will schedule the - event and return ::EMBER_SUCCESS. Otherwise it will return - ::EMBER_BAD_ARGUMENT. - */ -EmberStatus emberAfEventControlSetDelayQS(EmberEventControl * control, uint32_t delayQs); - -/** - * @brief Sets the ::EmberEventControl for the current network, and only - * the current network, as inactive. See ::emberEventControlSetInactive. - */ -void emberAfNetworkEventControlSetInactive(EmberEventControl * controls); -/** - * @brief Returns true if the event for the current network, and only the - * current network, is active. See ::emberEventControlGetActive. - */ -bool emberAfNetworkEventControlGetActive(EmberEventControl * controls); -/** - * @brief Sets the ::EmberEventControl for the current network, and only - * current network, to run at the next available opportunity. See - * ::emberEventControlSetActive. - */ -void emberAfNetworkEventControlSetActive(EmberEventControl * controls); -/** - * @brief Sets the ::EmberEventControl for the current network, and only the - * current network, to run "delayMs" milliseconds in the future. See - * ::emberEventControlSetDelayMS. - */ -EmberStatus emberAfNetworkEventControlSetDelayMS(EmberEventControl * controls, uint32_t delayMs); -#ifdef DOXYGEN_SHOULD_SKIP_THIS -/** - * @brief Sets the ::EmberEventControl for the current network, and only the - * current network, to run "delayMs" milliseconds in the future. See - * ::emberEventControlSetDelayMS. - */ -EmberStatus emberAfNetworkEventControlSetDelay(EmberEventControl * controls, uint32_t delayMs); -#else -#define emberAfNetworkEventControlSetDelay(controls, delayMs) emberAfNetworkEventControlSetDelayMS(controls, delayMs); -#endif -/** - * @brief Sets the ::EmberEventControl for the current network, and only the - * current network, to run "delayM" minutes in the future. See - * ::emberAfEventControlSetDelayMinutes. - */ -EmberStatus emberAfNetworkEventControlSetDelayMinutes(EmberEventControl * controls, uint16_t delayM); - -/** - * @brief Sets the ::EmberEventControl for the specified endpoint as inactive. - * See ::emberEventControlSetInactive. - */ -EmberStatus emberAfEndpointEventControlSetInactive(EmberEventControl * controls, chip::EndpointId endpoint); -/** - * @brief Returns true if the event for the current number is active. See - * ::emberEventControlGetActive. - */ -bool emberAfEndpointEventControlGetActive(EmberEventControl * controls, chip::EndpointId endpoint); -/** - * @brief Sets the ::EmberEventControl for the specified endpoint to run at the - * next available opportunity. See ::emberEventControlSetActive. - */ -EmberStatus emberAfEndpointEventControlSetActive(EmberEventControl * controls, chip::EndpointId endpoint); -/** - * @brief Sets the ::EmberEventControl for the specified endpoint to run - * "delayMs" milliseconds in the future. See ::emberEventControlSetDelayMS. - */ -EmberStatus emberAfEndpointEventControlSetDelayMS(EmberEventControl * controls, chip::EndpointId endpoint, uint32_t delayMs); -#ifdef DOXYGEN_SHOULD_SKIP_THIS -/** - * @brief Sets the ::EmberEventControl for the specified endpoint to run - * "delayMs" milliseconds in the future. See ::emberEventControlSetDelayMS. - */ -EmberStatus emberAfEndpointEventControlSetDelay(EmberEventControl * controls, chip::EndpointId endpoint, uint32_t delayMs); -#else -#define emberAfEndpointEventControlSetDelay(controls, endpoint, delayMs) \ - emberAfEndpointEventControlSetDelayMS(controls, endpoint, delayMs); -#endif -/** - * @brief Sets the ::EmberEventControl for the specified endpoint to run - * "delayQs" quarter seconds in the future. See - * ::emberAfEventControlSetDelayQS. - */ -EmberStatus emberAfEndpointEventControlSetDelayQS(EmberEventControl * controls, chip::EndpointId endpoint, uint32_t delayQs); -/** - * @brief Sets the ::EmberEventControl for the specified endpoint to run - * "delayM" minutes in the future. See ::emberAfEventControlSetDelayMinutes. - */ -EmberStatus emberAfEndpointEventControlSetDelayMinutes(EmberEventControl * controls, chip::EndpointId endpoint, uint16_t delayM); - -/** - * @brief A function used to retrieve the number of milliseconds until - * the next event scheduled in the application framework's event - * mechanism. - * @param maxMs the maximum number of milliseconds until the next - * event. - * @return The number of milliseconds until the next event or - * maxMs if no event is scheduled before then. - */ -uint32_t emberAfMsToNextEvent(uint32_t maxMs); - -/** @brief This is the same as the function emberAfMsToNextEvent() with the - * following addition. If returnIndex is non-NULL it returns the index - * of the event that is ready to fire next. - */ -uint32_t emberAfMsToNextEventExtended(uint32_t maxMs, uint8_t * returnIndex); - -/** - * @brief A function used to retrieve the number of quarter seconds until - * the next event scheduled in the application framework's event - * mechanism. This function will round down and will return 0 if the - * next event must fire within a quarter second. - * @param maxQS, the maximum number of quarter seconds until the next - * event. - * @return The number of quarter seconds until the next event or - * maxQS if no event is scheduled before then. - */ -#define emberAfQSToNextEvent(maxQS) \ - (emberAfMsToNextEvent(maxQS * MILLISECOND_TICKS_PER_QUARTERSECOND) / MILLISECOND_TICKS_PER_QUARTERSECOND) - -/** - * @brief A function for retrieving the most restrictive sleep - * control value for all scheduled events. This function is - * used by emberAfOkToNap and emberAfOkToHibernate to makes sure - * that there are no events scheduled which will keep the device - * from hibernating or napping. - * @return The most restrictive sleep control value for all - * scheduled events or the value returned by - * emberAfGetDefaultSleepControl() - * if no events are currently scheduled. The default - * sleep control value is initialized to - * EMBER_AF_OK_TO_HIBERNATE but can be changed at any - * time using the emberAfSetDefaultSleepControl() function. - */ -#define emberAfGetCurrentSleepControl() emberAfGetCurrentSleepControlCallback() - -/** - * @brief A function for setting the default sleep control - * value against which all scheduled event sleep control - * values will be evaluated. This can be used to keep - * a device awake for an extended period of time by setting - * the default to EMBER_AF_STAY_AWAKE and then resetting - * the value to EMBER_AF_OK_TO_HIBERNATE once the wake - * period is complete. - */ -#define emberAfSetDefaultSleepControl(x) emberAfSetDefaultSleepControlCallback(x) - -/** - * @brief A function used to retrieve the default sleep control against - * which all event sleep control values are evaluated. The - * default sleep control value is initialized to - * EMBER_AF_OK_TO_HIBERNATE but can be changed by the application - * at any time using the emberAfSetDefaultSleepControl() function. - * @return The current default sleep control value. - */ -#define emberAfGetDefaultSleepControl() emberAfGetDefaultSleepControlCallback() - /** @} END Sleep Control */ /** @name Messaging */ // @{ -/** - * @brief Sends end device binding request. - */ -EmberStatus emberAfSendEndDeviceBind(chip::EndpointId endpoint); - /** * @brief Sends a default response to a cluster command. * @@ -968,18 +550,6 @@ EmberApsFrame * emberAfGetCommandApsFrame(void); */ void emberAfSetCommandEndpoints(chip::EndpointId sourceEndpoint, chip::EndpointId destinationEndpoint); -/** - * @brief Friendly define for use in discovering client clusters with - * ::emberAfFindDevicesByCluster(). - */ -#define EMBER_AF_CLIENT_CLUSTER_DISCOVERY false - -/** - * @brief Friendly define for use in discovering server clusters with - * ::emberAfFindDevicesByCluster(). - */ -#define EMBER_AF_SERVER_CLUSTER_DISCOVERY true - /** * @brief Use this function to find devices in the network with endpoints * matching a given cluster ID in their descriptors. @@ -1007,98 +577,6 @@ void emberAfSetCommandEndpoints(chip::EndpointId sourceEndpoint, chip::EndpointI EmberStatus emberAfFindDevicesByCluster(EmberNodeId target, chip::ClusterId clusterId, bool serverCluster, EmberAfServiceDiscoveryCallback * callback); -/** - * @brief Use this function to find all of the given in and out clusters - * implemented on a devices given endpoint. Target should only be the - * short address of a specific device. - * - * With this function a single service discovery is initiated and the response - * is passed back to the passed callback. - * - * @param target The destination node ID for the discovery. This should be a - * specific node's ID and should not be a broadcast address. - * @param targetEndpoint The endpoint to target with the discovery process. - * @param callback Function pointer for the callback function triggered when - * the discovery is returned. - */ -EmberStatus emberAfFindClustersByDeviceAndEndpoint(EmberNodeId target, uint8_t targetEndpoint, - EmberAfServiceDiscoveryCallback * callback); - -/** - * @brief Use this function to initiate a discovery for the IEEE address - * of the specified node id. This will send a unicast sent to the target - * node ID. - */ -EmberStatus emberAfFindIeeeAddress(EmberNodeId shortAddress, EmberAfServiceDiscoveryCallback * callback); - -/** - * @brief Use this function to initiate a discovery for the short ID of the - * specified long address. This will send a broadcast to all - * rx-on-when-idle devices (non-sleepies). - */ -EmberStatus emberAfFindNodeId(EmberEUI64 longAddress, EmberAfServiceDiscoveryCallback * callback); - -/** - * @brief Initiate an Active Endpoint request ZDO message to the target node ID. - */ -EmberStatus emberAfFindActiveEndpoints(EmberNodeId target, EmberAfServiceDiscoveryCallback * callback); - -/** - * @brief Use this function to add an entry for a remote device to the address - * table. - * - * If the EUI64 already exists in the address table, the index of the existing - * entry will be returned. Otherwise, a new entry will be created and the new - * new index will be returned. The framework will remember how many times the - * returned index has been referenced. When the address table entry is no - * longer needed, the application should remove its reference by calling - * ::emberAfRemoveAddressTableEntry. - * - * @param longId The EUI64 of the remote device. - * @param shortId The node id of the remote device or ::EMBER_UNKNOWN_NODE_ID - * if the node id is currently unknown. - * @return The index of the address table entry for this remove device or - * ::EMBER_NULL_ADDRESS_TABLE_INDEX if an error occurred (e.g., the address - * table is full). - */ -uint8_t emberAfAddAddressTableEntry(EmberEUI64 longId, EmberNodeId shortId); - -/** - * @brief Use this function to add an entry for a remote device to the address - * table at a specific location. - * - * The framework will remember how many times an address table index has been - * referenced through ::emberAfAddAddressTableEntry. If the reference count - * for the index passed to this function is not zero, the entry will be not - * changed. When the address table entry is no longer needed, the application - * should remove its reference by calling ::emberAfRemoveAddressTableEntry. - * - * @param index The index of the address table entry. - * @param longId The EUI64 of the remote device. - * @param shortId The node id of the remote device or ::EMBER_UNKNOWN_NODE_ID - * if the node id is currently unknown. - * @return ::EMBER_SUCCESS if the address table entry was successfully set, - * ::EMBER_ADDRESS_TABLE_ENTRY_IS_ACTIVE if any messages are being sent using - * the existing entry at that index or the entry is still referenced in the - * framework, or ::EMBER_ADDRESS_TABLE_INDEX_OUT_OF_RANGE if the index is out - * of range. - */ -EmberStatus emberAfSetAddressTableEntry(uint8_t index, EmberEUI64 longId, EmberNodeId shortId); - -/** - * @brief Use this function to remove a specific entry from the address table. - * - * The framework will remember how many times an address table index has been - * referenced through ::emberAfAddAddressTableEntry and - * ::emberAfSetAddressTableEntry. The address table entry at this index will - * not actually be removed until its reference count reaches zero. - * - * @param index The index of the address table entry. - * @return ::EMBER_SUCCESS if the address table entry was successfully removed - * or ::EMBER_ADDRESS_TABLE_INDEX_OUT_OF_RANGE if the index is out of range. - */ -EmberStatus emberAfRemoveAddressTableEntry(uint8_t index); - #if !defined(DOXYGEN_SHOULD_SKIP_THIS) /** * @brief Use this macro to retrieve the current command. This @@ -1119,54 +597,6 @@ extern EmberAfClusterCommand * emAfCurrentCommand; */ #define emberAfCurrentEndpoint() (emberAfCurrentCommand()->apsFrame->destinationEndpoint) -#ifdef DOXYGEN_SHOULD_SKIP_THIS -/** @brief Use this function to initiate key establishment with a remote node. - * ::emberAfKeyEstablishmentCallback will be called as events occur and when - * key establishment completes. - * - * @param nodeId The node id of the remote device. - * @param endpoint The endpoint on the remote device. - * @return ::EMBER_SUCCESS if key establishment was initiated successfully - */ -EmberStatus emberAfInitiateKeyEstablishment(EmberNodeId nodeId, chip::EndpointId endpoint); - -/** @brief Use this function to initiate key establishment with a remote node on - * a different PAN. ::emberAfInterPanKeyEstablishmentCallback will be called - * as events occur and when key establishment completes. - * - * @param panId The PAN id of the remote device. - * @param eui64 The EUI64 of the remote device. - * @return ::EMBER_SUCCESS if key establishment was initiated successfully - */ -EmberStatus emberAfInitiateInterPanKeyEstablishment(EmberPanId panId, const EmberEUI64 eui64); - -/** @brief Use this function to tell if the device is in the process of - * performing key establishment. - * - * @return ::true if key establishment is in progress. - */ -bool emberAfPerformingKeyEstablishment(void); - -/** @brief Use this function to initiate partner link key exchange with a - * remote node. - * - * @param target The node id of the remote device. - * @param endpoint The key establishment endpoint of the remote device. - * @param callback The callback that should be called when the partner link - * key exchange completes. - * @return ::EMBER_SUCCESS if the partner link key exchange was initiated - * successfully. - */ -EmberStatus emberAfInitiatePartnerLinkKeyExchange(EmberNodeId target, chip::EndpointId endpoint, - EmberAfPartnerLinkKeyExchangeCallback * callback); -#else -#define emberAfInitiateKeyEstablishment(nodeId, endpoint) emberAfInitiateKeyEstablishmentCallback(nodeId, endpoint) -#define emberAfInitiateInterPanKeyEstablishment(panId, eui64) emberAfInitiateInterPanKeyEstablishmentCallback(panId, eui64) -#define emberAfPerformingKeyEstablishment() emberAfPerformingKeyEstablishmentCallback() -#define emberAfInitiatePartnerLinkKeyExchange(target, endpoint, callback) \ - emberAfInitiatePartnerLinkKeyExchangeCallback(target, endpoint, callback) -#endif - /** @} END Messaging */ /** @name ZCL macros */ @@ -1204,56 +634,6 @@ EmberStatus emberAfInitiatePartnerLinkKeyExchange(EmberNodeId target, chip::Endp /** @} END ZCL macros */ -/** @name Network utility functions */ -// ${ - -/** @brief Use this function to form a new network using the specified network - * parameters. - * - * @param parameters Specification of the new network. - * @return An ::EmberStatus value that indicates either the successful formation - * of the new network or the reason that the network formation failed. - */ -EmberStatus emberAfFormNetwork(EmberNetworkParameters * parameters); - -/** @brief Use this function to associate with the network using the specified - * network parameters. - * - * @param parameters Specification of the network with which the node should - * associate. - * @return An ::EmberStatus value that indicates either that the association - * process began successfully or the reason for failure. - */ -EmberStatus emberAfJoinNetwork(EmberNetworkParameters * parameters); - -#ifdef DOXYGEN_SHOULD_SKIP_THIS -/** @brief Use this function to find an unused PAN id and form a new network. - * - * @return An ::EmberStatus value that indicates either the process begin - * successfully or the reason for failure. - */ -EmberStatus emberAfFindUnusedPanIdAndForm(void); -/** @brief Use this function to find a joinable network and join it. - * - * @return An ::EmberStatus value that indicates either the process begin - * successfully or the reason for failure. - */ -EmberStatus emberAfStartSearchForJoinableNetwork(void); -#else -#define emberAfFindUnusedPanIdAndForm() emberAfFindUnusedPanIdAndFormCallback() -#define emberAfStartSearchForJoinableNetwork() emberAfStartSearchForJoinableNetworkCallback() -#endif - -/** @brief Basic initialization API to be invoked before ::emberAfMain. - */ -void emberAfMainInit(void); - -/** @brief This function effectively serves as the application main. - */ -int emberAfMain(MAIN_FUNCTION_PARAMETERS); - -/** @} End network utility functions */ - /** @} END addtogroup */ #if !defined(DOXYGEN_SHOULD_SKIP_THIS) @@ -1264,11 +644,6 @@ int emberAfMain(MAIN_FUNCTION_PARAMETERS); #endif #endif -/** @brief The maximum power level that can be used by the chip. - */ -// Note: This is a #define for now but could be a real function call in the future. -#define emberAfMaxPowerLevel() (3) - /** * @brief API for parsing a cluster-specific message. Implemented by * generated code. diff --git a/src/app/util/attribute-size-util.cpp b/src/app/util/attribute-size-util.cpp index 5cb95313dce574..f8cf9507f11b53 100644 --- a/src/app/util/attribute-size-util.cpp +++ b/src/app/util/attribute-size-util.cpp @@ -37,43 +37,3 @@ uint8_t emberAfGetDataSize(uint8_t dataType) return 0; } - -uint16_t emberAfAttributeValueSize(ClusterId clusterId, AttributeId attrId, EmberAfAttributeType dataType, const uint8_t * buffer) -{ - // If the dataType is a string or long string, refer to the buffer for the - // string's length prefix; size is string length plus number of prefix bytes. - // If non-string, determine size from dataType. If dataType is unrecognized, - // return zero. - // - // Note: A non-empty long string has max length 0xFFFE, and adding 2 for its - // length prefix would roll a uint16_t back to zero. Choosing not to - // expand return type to uint32_t just to accommodate that one case. - uint16_t dataSize = 0; - if (emberAfIsThisDataTypeAStringType(dataType)) - { - if (buffer != nullptr) - { - if (emberAfIsStringAttributeType(dataType)) - { - // size is string length plus 1-byte length prefix - dataSize = static_cast(static_cast(emberAfStringLength(buffer)) + 1u); - } - else - { - // size is long string length plus 2-byte length prefix - dataSize = static_cast(emberAfLongStringLength(buffer) + 2u); - } - } - } - else if (emberAfIsThisDataTypeAListType(dataType)) - { - // Just claim to have a length and nothing else. - dataSize = 2; - } - else - { - dataSize = (uint16_t) emberAfGetDataSize(dataType); - } - - return dataSize; -} diff --git a/src/app/util/attribute-storage.cpp b/src/app/util/attribute-storage.cpp index 6f037518f8d80d..b051abaadea0dc 100644 --- a/src/app/util/attribute-storage.cpp +++ b/src/app/util/attribute-storage.cpp @@ -295,42 +295,6 @@ bool emberAfIsThisDataTypeAListType(EmberAfAttributeType dataType) return dataType == ZCL_ARRAY_ATTRIBUTE_TYPE; } -// This function is used to call the per-cluster default response callback -void emberAfClusterDefaultResponseCallback(EndpointId endpoint, ClusterId clusterId, CommandId commandId, EmberAfStatus status, - uint8_t clientServerMask) -{ - const EmberAfCluster * cluster = emberAfFindCluster(endpoint, clusterId, clientServerMask); - if (cluster != nullptr) - { - EmberAfGenericClusterFunction f = emberAfFindClusterFunction(cluster, CLUSTER_MASK_DEFAULT_RESPONSE_FUNCTION); - if (f != nullptr) - { - ((EmberAfDefaultResponseFunction) f)(endpoint, commandId, status); - } - } -} - -// This function is used to call the per-cluster message sent callback -void emberAfClusterMessageSentCallback(const MessageSendDestination & destination, EmberApsFrame * apsFrame, uint16_t msgLen, - uint8_t * message, EmberStatus status) -{ - if (apsFrame != nullptr && message != nullptr && msgLen != 0) - { - const EmberAfCluster * cluster = emberAfFindCluster( - apsFrame->sourceEndpoint, apsFrame->clusterId, - (((message[0] & ZCL_FRAME_CONTROL_DIRECTION_MASK) == ZCL_FRAME_CONTROL_SERVER_TO_CLIENT) ? CLUSTER_MASK_SERVER - : CLUSTER_MASK_CLIENT)); - if (cluster != nullptr) - { - EmberAfGenericClusterFunction f = emberAfFindClusterFunction(cluster, CLUSTER_MASK_MESSAGE_SENT_FUNCTION); - if (f != nullptr) - { - ((EmberAfMessageSentFunction) f)(destination, apsFrame, msgLen, message, status); - } - } - } -} - // This function is used to call the per-cluster attribute changed callback void emAfClusterAttributeChangedCallback(const app::ConcreteAttributePath & attributePath) { @@ -699,25 +663,12 @@ uint8_t emberAfClusterIndex(EndpointId endpoint, ClusterId clusterId, EmberAfClu return 0xFF; } -// Returns whether the given endpoint has the client or server of the given -// cluster on it. -bool emberAfContainsCluster(EndpointId endpoint, ClusterId clusterId) -{ - return (emberAfFindCluster(endpoint, clusterId, 0) != nullptr); -} - // Returns whether the given endpoint has the server of the given cluster on it. bool emberAfContainsServer(EndpointId endpoint, ClusterId clusterId) { return (emberAfFindCluster(endpoint, clusterId, CLUSTER_MASK_SERVER) != nullptr); } -// Returns whether the given endpoint has the client of the given cluster on it. -bool emberAfContainsClient(EndpointId endpoint, ClusterId clusterId) -{ - return (emberAfFindCluster(endpoint, clusterId, CLUSTER_MASK_CLIENT) != nullptr); -} - // This will find the first server that has the clusterId given from the index of endpoint. bool emberAfContainsServerFromIndex(uint16_t index, ClusterId clusterId) { @@ -792,12 +743,6 @@ uint16_t emberAfFindClusterServerEndpointIndex(EndpointId endpoint, ClusterId cl return findClusterEndpointIndex(endpoint, clusterId, CLUSTER_MASK_SERVER); } -// Client wrapper for findClusterEndpointIndex -uint16_t emberAfFindClusterClientEndpointIndex(EndpointId endpoint, ClusterId clusterId) -{ - return findClusterEndpointIndex(endpoint, clusterId, CLUSTER_MASK_CLIENT); -} - // Returns the endpoint index within a given cluster static uint16_t findClusterEndpointIndex(EndpointId endpoint, ClusterId clusterId, uint8_t mask) { diff --git a/src/app/util/attribute-storage.h b/src/app/util/attribute-storage.h index 28d4588e944ba9..81722dd21da2ad 100644 --- a/src/app/util/attribute-storage.h +++ b/src/app/util/attribute-storage.h @@ -154,6 +154,9 @@ chip::Optional emberAfGetNthClusterId(chip::EndpointId endpoint uint8_t emberAfGetClustersFromEndpoint(chip::EndpointId endpoint, chip::ClusterId * clusterList, uint8_t listLen, bool server); // Returns cluster within the endpoint, or NULL if it isn't there +// +// TODO: we likely now only have mask as CLUSTER_MASK_SERVER so this +// method should be renamed to emberAfFindServerCluster or similar and simplify the code. const EmberAfCluster * emberAfFindCluster(chip::EndpointId endpoint, chip::ClusterId clusterId, EmberAfClusterMask mask); // Returns cluster within the endpoint; Does not ignore disabled endpoints @@ -187,15 +190,6 @@ void emAfClusterAttributeChangedCallback(const chip::app::ConcreteAttributePath EmberAfStatus emAfClusterPreAttributeChangedCallback(const chip::app::ConcreteAttributePath & attributePath, EmberAfAttributeType attributeType, uint16_t size, uint8_t * value); -// Calls the default response callback for a specific cluster. -// with the EMBER_NULL_MANUFACTURER_CODE -void emberAfClusterDefaultResponseCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::CommandId commandId, - EmberAfStatus status, uint8_t clientServerMask); - -// Calls the message sent callback for a specific cluster. -void emberAfClusterMessageSentCallback(const chip::MessageSendDestination & destination, EmberApsFrame * apsFrame, uint16_t msgLen, - uint8_t * message, EmberStatus status); - // Checks a cluster mask byte against ticks passed bitmask // returns true if the mask matches a passed interval bool emberAfCheckTick(EmberAfClusterMask mask, uint8_t passedMask); diff --git a/src/app/util/attribute-table.cpp b/src/app/util/attribute-table.cpp index 3d4466980570d1..2a86c16fec77fe 100644 --- a/src/app/util/attribute-table.cpp +++ b/src/app/util/attribute-table.cpp @@ -67,14 +67,6 @@ EmberAfStatus emberAfWriteAttribute(EndpointId endpoint, ClusterId cluster, Attr false); // just test? } -EmberAfStatus emberAfVerifyAttributeWrite(EndpointId endpoint, ClusterId cluster, AttributeId attributeID, uint8_t * dataPtr, - EmberAfAttributeType dataType) -{ - return emAfWriteAttribute(endpoint, cluster, attributeID, dataPtr, dataType, - false, // override read-only? - true); // just test? -} - EmberAfStatus emberAfReadAttribute(EndpointId endpoint, ClusterId cluster, AttributeId attributeID, uint8_t * dataPtr, uint16_t readLength) { diff --git a/src/app/util/common.h b/src/app/util/common.h index d1e2f315e8d263..f78ae87d61da35 100644 --- a/src/app/util/common.h +++ b/src/app/util/common.h @@ -21,7 +21,6 @@ #include #include #include -#include #include #include diff --git a/src/app/util/message.cpp b/src/app/util/message.cpp index bdbcb3c58d29e6..86175ca4f2006a 100644 --- a/src/app/util/message.cpp +++ b/src/app/util/message.cpp @@ -253,18 +253,3 @@ uint16_t emberAfLongStringLength(const uint8_t * buffer) uint16_t length = emberAfGetInt16u(buffer, 0, 2); return (length == 0xFFFF ? 0 : length); } - -uint8_t emberAfGetDate(uint8_t * message, uint16_t currentIndex, uint16_t msgLen, EmberAfDate * destination) -{ - if ((currentIndex + 4) > msgLen) - { - emberAfDebugPrintln("GetDate, %x bytes short", 4); - emberAfDebugFlush(); - return 0; - } - destination->year = message[(currentIndex + 0)]; - destination->month = message[(currentIndex + 1)]; - destination->dayOfMonth = message[(currentIndex + 2)]; - destination->dayOfWeek = message[(currentIndex + 3)]; - return 4; -} diff --git a/src/app/util/time-util.h b/src/app/util/time-util.h deleted file mode 100644 index b4918f16eb2e70..00000000000000 --- a/src/app/util/time-util.h +++ /dev/null @@ -1,135 +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. - */ - -#pragma once - -#include - -#include - -#define SECONDS_IN_MINUTE 60 -#define SECONDS_IN_HOUR 3600 -#define SECONDS_IN_DAY (SECONDS_IN_MINUTE * 60 * 24) -#define SECONDS_IN_WEEK (SECONDS_IN_DAY * 7) -#define DURATION_FOREVER_U32 0xFFFFFFFFU - -/** - * @brief ZCL Date comparison function. - * The results are undefined for dates that contain the do not care value - * in any of the subfields. - * @return -1, if val1 is smaller - * 0, if they are the same - * 1, if val2 is smaller - */ -int8_t emberAfCompareDates(EmberAfDate * date1, EmberAfDate * date2); - -/** - * @brief function that copies a ZigBee Date into a buffer - */ -void emberAfCopyDate(uint8_t * data, uint16_t index, EmberAfDate * src); - -/** - * @brief Decode the given uint32_t into a ZCL Date object where - * the uint32_t is formatted as follows: - * - * (0xFF000000 & value) = year - * (0x00FF0000 & value) = month - * (0x0000FF00 & value) = day of month - * (0x000000FF & value) = day of week - * - */ -void emberAfDecodeDate(uint32_t src, EmberAfDate * dest); - -/** - * @brief Encode and return the given ZCL Date object as an uint32_t. - * Refer to emberAFDecodeDate for details on how the information is stored - * within an uint32_t. - */ -uint32_t emberAfEncodeDate(EmberAfDate * date); - -/** - * @brief Fills the a time structure based on the passed UTC time. - * - */ -void emberAfFillTimeStructFromUtc(uint32_t utcTime, EmberAfTimeStruct * returnTime); -/** - * @brief Returns the number of days in the month specified in the EmberAfTimeStruct. - * - */ -uint8_t emberAfGetNumberDaysInMonth(EmberAfTimeStruct * time); - -/** - * @brief Calculate a UTC time from the passed time structure. - * - */ -uint32_t emberAfGetUtcFromTimeStruct(EmberAfTimeStruct * time); - -/** - * @brief Determine the week day (Monday=0 ... Sunday=6) based on - * a specified UTC time. - */ -uint8_t emberAfGetWeekdayFromUtc(uint32_t utcTime); - -/** - * @brief Sets current time. - * Convenience function for setting the time to a value. - * If the time server cluster is implemented on this device, - * then this call will be passed along to the time cluster server - * which will update the time. Otherwise the emberAfSetTimeCallback - * is called, which in the case of the stub does nothing. - * - * @param utcTime A ZigBee time, the number of seconds since the - * year 2000. - */ -void emberAfSetTime(uint32_t utcTime); - -/** - * @brief Retrieves current time. - * - * Convienience function for retrieving the current time. - * If the time server cluster is implemented, then the time - * is retrieved from that cluster's time attribute. Otherwise, - * the emberAfGetCurrentTimeCallback is called. - * - * A real time is expected to in the ZigBee time format, the number - * of seconds since the year 2000. - */ -uint32_t emberAfGetCurrentTime(void); - -/** - * @brief Prints time. - * - * Convenience function for all clusters to print time. - * This function expects to be passed a ZigBee time which - * is the number of seconds since the year 2000. If - * EMBER_AF_PRINT_CORE is defined, this function will print - * a human readable time from the passed value. If not, this - * function will print nothing. - * - * @param utcTime A ZigBee time, the number of seconds since the - * year 2000. - */ -void emberAfPrintTime(uint32_t utcTime); - -/** - * @brief Prints the time in ISO 8601 format - * yyyy-mm-dd hh:mm:ss - * - * @param utcTime A ZigBee time, the number of seconds since the - * year 2000. - */ -void emberAfPrintTimeIsoFormat(uint32_t utcTime); diff --git a/src/app/util/types_stub.h b/src/app/util/types_stub.h index d098c323e27e8d..56f15a23efedb4 100644 --- a/src/app/util/types_stub.h +++ b/src/app/util/types_stub.h @@ -297,27 +297,6 @@ typedef struct * node might play in a network. */ -#ifdef DOXYGEN_SHOULD_SKIP_THIS -enum EmberNodeType -#else -typedef uint8_t EmberNodeType; -enum -#endif -{ - /** The device is not joined. */ - EMBER_UNKNOWN_DEVICE = 0, - /** Will relay messages and can act as a parent to other nodes. */ - EMBER_COORDINATOR = 1, - /** Will relay messages and can act as a parent to other nodes. */ - EMBER_ROUTER = 2, - /** Communicates only with its parent and will not relay messages. */ - EMBER_END_DEVICE = 3, - /** An end device whose radio can be turned off to save power. - * The application must call ::emberPollForData() to receive messages. - */ - EMBER_SLEEPY_END_DEVICE = 4, -}; - /** * @brief Defines the possible incoming message types. */ @@ -722,19 +701,6 @@ typedef struct EmberVersionType type; } EmberVersion; -/** @brief This structure contains information about child nodes. - * - */ -typedef struct -{ - EmberEUI64 eui64; - EmberNodeType type; - EmberNodeId id; - uint8_t phy; - uint8_t power; - uint8_t timeout; -} EmberChildData; - /** * @brief A distinguished network ID that will never be assigned * to any node. This value is used when getting the remote node ID diff --git a/src/app/util/util.cpp b/src/app/util/util.cpp index 1ba17a0e935967..c00d36bdcc4750 100644 --- a/src/app/util/util.cpp +++ b/src/app/util/util.cpp @@ -84,24 +84,6 @@ EMBER_AF_GENERATED_PLUGIN_TICK_FUNCTION_DECLARATIONS //------------------------------------------------------------------------------ // Device enabled/disabled functions -bool emberAfIsDeviceEnabled(EndpointId endpoint) -{ - uint16_t index; -#ifdef ZCL_USING_BASIC_CLUSTER_DEVICE_ENABLED_ATTRIBUTE - bool deviceEnabled; - if (emberAfReadServerAttribute(endpoint, ZCL_BASIC_CLUSTER_ID, ZCL_DEVICE_ENABLED_ATTRIBUTE_ID, (uint8_t *) &deviceEnabled, - sizeof(deviceEnabled)) == EMBER_ZCL_STATUS_SUCCESS) - { - return deviceEnabled; - } -#endif - index = emberAfIndexFromEndpoint(endpoint); - if (index != 0xFFFF && index < sizeof(afDeviceEnabled)) - { - return afDeviceEnabled[index]; - } - return false; -} void emberAfSetDeviceEnabled(EndpointId endpoint, bool enabled) { @@ -292,16 +274,6 @@ uint16_t emberAfGetMfgCodeFromCurrentCommand(void) return EMBER_AF_NULL_MANUFACTURER_CODE; } -uint8_t emberAfNextSequence(void) -{ - return ((++emberAfSequenceNumber) & EMBER_AF_ZCL_SEQUENCE_MASK); -} - -uint8_t emberAfGetLastSequenceNumber(void) -{ - return (emberAfSequenceNumber & EMBER_AF_ZCL_SEQUENCE_MASK); -} - // the caller to the library can set a flag to say do not respond to the // next ZCL message passed in to the library. Passing true means disable // the reply for the next ZCL message. Setting to false re-enables the @@ -572,34 +544,6 @@ bool emberAfIsTypeSigned(EmberAfAttributeType dataType) return (dataType >= ZCL_INT8S_ATTRIBUTE_TYPE && dataType <= ZCL_INT64S_ATTRIBUTE_TYPE); } -EmberStatus emberAfEndpointEventControlSetInactive(EmberEventControl * controls, EndpointId endpoint) -{ - uint16_t index = emberAfIndexFromEndpoint(endpoint); - if (index == 0xFFFF) - { - return EMBER_INVALID_ENDPOINT; - } - emberEventControlSetInactive(&controls[index]); - return EMBER_SUCCESS; -} - -bool emberAfEndpointEventControlGetActive(EmberEventControl * controls, EndpointId endpoint) -{ - uint16_t index = emberAfIndexFromEndpoint(endpoint); - return (index != 0xFFFF && emberEventControlGetActive(&controls[index])); -} - -EmberStatus emberAfEndpointEventControlSetActive(EmberEventControl * controls, EndpointId endpoint) -{ - uint16_t index = emberAfIndexFromEndpoint(endpoint); - if (index == 0xFFFF) - { - return EMBER_INVALID_ENDPOINT; - } - emberEventControlSetActive(&controls[index]); - return EMBER_SUCCESS; -} - uint8_t emberAfAppendCharacters(uint8_t * zclString, uint8_t zclStringMaxLen, const uint8_t * appendingChars, uint8_t appendingCharsLen) { diff --git a/src/app/zap-templates/templates/app/callback-stub-src.zapt b/src/app/zap-templates/templates/app/callback-stub-src.zapt index 8e8ce31bce288a..8b39bc49cbb875 100644 --- a/src/app/zap-templates/templates/app/callback-stub-src.zapt +++ b/src/app/zap-templates/templates/app/callback-stub-src.zapt @@ -35,10 +35,6 @@ void __attribute__((weak)) emberAf{{asUpperCamelCase name}}ClusterInitCallback(E // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback( EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, @@ -95,11 +91,6 @@ EmberAfStatus __attribute__((weak)) emberAfExternalAttributeWriteCallback( return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback( EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) @@ -109,12 +100,6 @@ bool __attribute__((weak)) emberAfGetEndpointInfoCallback( void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) emberAfInterpanSendMessageCallback( - EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/src/app/zap-templates/templates/app/callback.zapt b/src/app/zap-templates/templates/app/callback.zapt index 9c296dbf8939fb..4f379bd3471e8a 100644 --- a/src/app/zap-templates/templates/app/callback.zapt +++ b/src/app/zap-templates/templates/app/callback.zapt @@ -155,29 +155,6 @@ bool emberAf{{asUpperCamelCase parent.label}}Cluster{{asUpperCamelCase name}}Cal {{/zcl_commands}} {{/zcl_clusters}} -/** @brief Add To Current App Tasks - * - * This function is only useful to sleepy end devices. This function will note - * the passed item as part of a set of tasks the application has outstanding - * (e.g. message sent requiring APS acknwoledgement). This will affect how the - * application behaves with regard to sleeping and polling. Until the - * outstanding task is completed, the device may poll more frequently and sleep - * less often. - */ -void emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks); - -/** @brief Remove From Current App Tasks - * - * This function is only useful to sleepy end devices. This function will - * remove the passed item from the set of tasks the application has outstanding - * (e.g. message sent requiring APS acknwoledgement). This will affect how the - * application behaves with regard to sleeping and polling. Removing the item - * from the list of outstanding tasks may allow the device to sleep longer and - * poll less frequently. If there are other outstanding tasks the system may - * still have to stay away and poll more often. - */ -void emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks); - /** @brief Allow Network Write Attribute * * This function is called by the application framework before it writes an @@ -346,17 +323,6 @@ EmberAfStatus emberAfExternalAttributeWriteCallback(chip::EndpointId endpoint, c const EmberAfAttributeMetadata * attributeMetadata, uint8_t * buffer); -/** @brief Get Current Time - * - * This callback is called when device attempts to get current time from the - * hardware. If this device has means to retrieve exact time, then this method - * should implement it. If the callback can't provide the exact time it should - * return 0 to indicate failure. Default action is to return 0, which indicates - * that device does not have access to real time. - * - */ -uint32_t emberAfGetCurrentTimeCallback(); - /** @brief Get Endpoint Info * * This function is a callback to an application implemented endpoint that @@ -384,18 +350,6 @@ bool emberAfGetEndpointInfoCallback(chip::EndpointId endpoint, uint8_t * returnN */ void emberAfRegistrationAbortCallback(); -/** @brief Interpan Send Message - * - * This function will send a raw MAC message with interpan frame format using - * the passed parameters. - * - * @param header Interpan header info Ver.: always - * @param messageLength The length of the message received or to send Ver.: - * always - * @param message The message data received or to send. Ver.: always - */ -EmberStatus emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message); - /** @brief Start Move * * This function is called to initiate the process for a device to move (rejoin) diff --git a/src/ble/BLEEndPoint.cpp b/src/ble/BLEEndPoint.cpp index cfbc86d491464b..1b35f0777b2fcd 100644 --- a/src/ble/BLEEndPoint.cpp +++ b/src/ble/BLEEndPoint.cpp @@ -54,7 +54,7 @@ #undef CHIP_BLE_END_POINT_DEBUG_LOGGING_ENABLED #ifdef CHIP_BLE_END_POINT_DEBUG_LOGGING_ENABLED -#define ChipLogDebugBleEndPoint(MOD, MSG, ...) ChipLogError(MOD, MSG, ## __VA_ARGS__) +#define ChipLogDebugBleEndPoint(MOD, MSG, ...) ChipLogDetail(MOD, MSG, ## __VA_ARGS__) #else #define ChipLogDebugBleEndPoint(MOD, MSG, ...) #endif diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 6b71c9fbbd9fcd..af628edc572cc3 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -686,6 +686,7 @@ CHIP_ERROR DeviceCommissioner::EstablishPASEConnection(NodeId remoteDeviceId, Re mDeviceInPASEEstablishment = device; device->Init(GetControllerDeviceInitParams(), remoteDeviceId, peerAddress); + device->UpdateDeviceData(params.GetPeerAddress(), params.GetMRPConfig()); #if CONFIG_NETWORK_LAYER_BLE if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle) @@ -706,8 +707,7 @@ CHIP_ERROR DeviceCommissioner::EstablishPASEConnection(NodeId remoteDeviceId, Re } } #endif - // TODO: In some cases like PASE over IP, SAI and SII values from commissionable node service should be used - session = mSystemState->SessionMgr()->CreateUnauthenticatedSession(params.GetPeerAddress(), device->GetRemoteMRPConfig()); + session = mSystemState->SessionMgr()->CreateUnauthenticatedSession(params.GetPeerAddress(), params.GetMRPConfig()); VerifyOrExit(session.HasValue(), err = CHIP_ERROR_NO_MEMORY); // Allocate the exchange immediately before calling PASESession::Pair. diff --git a/src/controller/SetUpCodePairer.cpp b/src/controller/SetUpCodePairer.cpp index 2f13f629a3e680..64b2459ce5faeb 100644 --- a/src/controller/SetUpCodePairer.cpp +++ b/src/controller/SetUpCodePairer.cpp @@ -344,6 +344,19 @@ void SetUpCodePairer::NotifyCommissionableDeviceDiscovered(const Dnssd::Discover Transport::PeerAddress::UDP(nodeData.resolutionData.ipAddress[0], nodeData.resolutionData.port, interfaceId); mDiscoveredParameters.emplace(); mDiscoveredParameters.back().SetPeerAddress(peerAddress); + + if (nodeData.resolutionData.mrpRetryIntervalIdle.HasValue()) + { + auto interval = nodeData.resolutionData.mrpRetryIntervalIdle.Value(); + mDiscoveredParameters.back().SetIdleInterval(interval); + } + + if (nodeData.resolutionData.mrpRetryIntervalActive.HasValue()) + { + auto interval = nodeData.resolutionData.mrpRetryIntervalActive.Value(); + mDiscoveredParameters.back().SetActiveInterval(interval); + } + ConnectToDiscoveredDevice(); } diff --git a/src/controller/python/BUILD.gn b/src/controller/python/BUILD.gn index 60988c5239d974..7031bdf08aa361 100644 --- a/src/controller/python/BUILD.gn +++ b/src/controller/python/BUILD.gn @@ -70,6 +70,7 @@ shared_library("ChipDeviceCtrl") { "chip/internal/ChipThreadWork.h", "chip/internal/CommissionerImpl.cpp", "chip/logging/LoggingRedirect.cpp", + "chip/native/PyChipError.cpp", "chip/utils/DeviceProxyUtils.cpp", ] } else { diff --git a/src/controller/python/ChipCommissionableNodeController-ScriptBinding.cpp b/src/controller/python/ChipCommissionableNodeController-ScriptBinding.cpp index 0fd3df5de89bec..12277183e52b6d 100644 --- a/src/controller/python/ChipCommissionableNodeController-ScriptBinding.cpp +++ b/src/controller/python/ChipCommissionableNodeController-ScriptBinding.cpp @@ -24,6 +24,7 @@ */ #include +#include #include #include #include @@ -33,29 +34,27 @@ using namespace chip; using namespace chip::Controller; -static_assert(std::is_same::value, "python assumes CHIP_ERROR maps to c_uint32"); - extern "C" { -ChipError::StorageType +PyChipError pychip_CommissionableNodeController_NewController(chip::Controller::CommissionableNodeController ** outCommissionableNodeCtrl); -ChipError::StorageType +PyChipError pychip_CommissionableNodeController_DeleteController(chip::Controller::CommissionableNodeController * commissionableNodeCtrl); -ChipError::StorageType +PyChipError pychip_CommissionableNodeController_DiscoverCommissioners(chip::Controller::CommissionableNodeController * commissionableNodeCtrl); void pychip_CommissionableNodeController_PrintDiscoveredCommissioners( chip::Controller::CommissionableNodeController * commissionableNodeCtrl); } -ChipError::StorageType +PyChipError pychip_CommissionableNodeController_NewController(chip::Controller::CommissionableNodeController ** outCommissionableNodeCtrl) { *outCommissionableNodeCtrl = new (std::nothrow) chip::Controller::CommissionableNodeController(); - VerifyOrReturnError(*outCommissionableNodeCtrl != nullptr, CHIP_ERROR_NO_MEMORY.AsInteger()); - return CHIP_NO_ERROR.AsInteger(); + VerifyOrReturnError(*outCommissionableNodeCtrl != nullptr, ToPyChipError(CHIP_ERROR_NO_MEMORY)); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType +PyChipError pychip_CommissionableNodeController_DeleteController(chip::Controller::CommissionableNodeController * commissionableNodeCtrl) { if (commissionableNodeCtrl != nullptr) @@ -63,13 +62,13 @@ pychip_CommissionableNodeController_DeleteController(chip::Controller::Commissio delete commissionableNodeCtrl; } - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType +PyChipError pychip_CommissionableNodeController_DiscoverCommissioners(chip::Controller::CommissionableNodeController * commissionableNodeCtrl) { - return commissionableNodeCtrl->DiscoverCommissioners().AsInteger(); + return ToPyChipError(commissionableNodeCtrl->DiscoverCommissioners()); } void pychip_CommissionableNodeController_PrintDiscoveredCommissioners( diff --git a/src/controller/python/ChipDeviceController-Discovery.cpp b/src/controller/python/ChipDeviceController-Discovery.cpp index f4aaaed81bdf49..36da3a8eedb0d1 100644 --- a/src/controller/python/ChipDeviceController-Discovery.cpp +++ b/src/controller/python/ChipDeviceController-Discovery.cpp @@ -24,6 +24,7 @@ */ #include +#include #include #include #include @@ -49,8 +50,8 @@ bool pychip_DeviceController_HasDiscoveredCommissionableNode(Controller::DeviceC return false; } -ChipError::StorageType pychip_DeviceController_DiscoverCommissionableNodes(Controller::DeviceCommissioner * devCtrl, - const uint8_t filterType, const char * filterParam) +PyChipError pychip_DeviceController_DiscoverCommissionableNodes(Controller::DeviceCommissioner * devCtrl, const uint8_t filterType, + const char * filterParam) { Dnssd::DiscoveryFilter filter(static_cast(filterType)); switch (static_cast(filterType)) @@ -67,7 +68,7 @@ ChipError::StorageType pychip_DeviceController_DiscoverCommissionableNodes(Contr unsigned long long int numericalArg = strtoull(filterParam, nullptr, 0); if ((numericalArg == ULLONG_MAX) && (errno == ERANGE)) { - return CHIP_ERROR_INVALID_ARGUMENT.AsInteger(); + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); } filter.code = static_cast(numericalArg); break; @@ -82,10 +83,10 @@ ChipError::StorageType pychip_DeviceController_DiscoverCommissionableNodes(Contr filter.instanceName = filterParam; break; default: - return CHIP_ERROR_INVALID_ARGUMENT.AsInteger(); + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); } - return devCtrl->DiscoverCommissionableNodes(filter).AsInteger(); + return ToPyChipError(devCtrl->DiscoverCommissionableNodes(filter)); } void pychip_DeviceController_IterateDiscoveredCommissionableNodes(Controller::DeviceCommissioner * devCtrl, diff --git a/src/controller/python/ChipDeviceController-IssueNocChain.cpp b/src/controller/python/ChipDeviceController-IssueNocChain.cpp index 39a3952e0fb0f7..fe5b8ecc3919b0 100644 --- a/src/controller/python/ChipDeviceController-IssueNocChain.cpp +++ b/src/controller/python/ChipDeviceController-IssueNocChain.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -33,7 +34,7 @@ using namespace chip; extern "C" { typedef void (*pychip_DeviceController_IssueNOCChainCallbackPythonCallback)( - PyObject * context, ChipError::StorageType status, const uint8_t * noc, size_t nocLen, const uint8_t * icac, size_t icacLen, + PyObject * context, PyChipError status, const uint8_t * noc, size_t nocLen, const uint8_t * icac, size_t icacLen, const uint8_t * rcac, size_t rcacLen, const uint8_t * ipk, size_t ipkLen, NodeId adminSubject); static pychip_DeviceController_IssueNOCChainCallbackPythonCallback pychip_DeviceController_IssueNOCChainCallbackPythonCallbackFunct; @@ -44,9 +45,8 @@ void pychip_DeviceController_SetIssueNOCChainCallbackPythonCallback( pychip_DeviceController_IssueNOCChainCallbackPythonCallbackFunct = callback; } -ChipError::StorageType pychip_DeviceController_IssueNOCChain(chip::Controller::DeviceCommissioner * devCtrl, - PyObject * pythonContext, uint8_t * NOCSRElements, - size_t NOCSRElementsLen, NodeId nodeId); +PyChipError pychip_DeviceController_IssueNOCChain(chip::Controller::DeviceCommissioner * devCtrl, PyObject * pythonContext, + uint8_t * NOCSRElements, size_t NOCSRElementsLen, NodeId nodeId); } void pychip_DeviceController_IssueNOCChainCallback(void * context, CHIP_ERROR status, const ByteSpan & noc, const ByteSpan & icac, @@ -90,25 +90,22 @@ void pychip_DeviceController_IssueNOCChainCallback(void * context, CHIP_ERROR st if (err == CHIP_NO_ERROR) { pychip_DeviceController_IssueNOCChainCallbackPythonCallbackFunct( - context, err.AsInteger(), chipNocSpan.data(), chipNocSpan.size(), chipIcacSpan.data(), chipIcacSpan.size(), + context, ToPyChipError(err), chipNocSpan.data(), chipNocSpan.size(), chipIcacSpan.data(), chipIcacSpan.size(), chipRcacSpan.data(), chipRcacSpan.size(), ipkData.data(), ipk.HasValue() ? ipkData.size() : 0, adminSubject.ValueOr(kUndefinedNodeId)); } else { - pychip_DeviceController_IssueNOCChainCallbackPythonCallbackFunct(context, err.AsInteger(), nullptr, 0, nullptr, 0, nullptr, - 0, nullptr, 0, 0); + pychip_DeviceController_IssueNOCChainCallbackPythonCallbackFunct(context, ToPyChipError(err), nullptr, 0, nullptr, 0, + nullptr, 0, nullptr, 0, 0); } } -ChipError::StorageType pychip_DeviceController_IssueNOCChain(chip::Controller::DeviceCommissioner * devCtrl, - PyObject * pythonContext, uint8_t * NOCSRElements, - size_t NOCSRElementsLen, NodeId nodeId) +PyChipError pychip_DeviceController_IssueNOCChain(chip::Controller::DeviceCommissioner * devCtrl, PyObject * pythonContext, + uint8_t * NOCSRElements, size_t NOCSRElementsLen, NodeId nodeId) { - return devCtrl - ->IssueNOCChain( - ByteSpan(NOCSRElements, NOCSRElementsLen), nodeId, - /* Note: Memory leak here. This is a quick and a bit dirty PoC */ - new Callback::Callback(pychip_DeviceController_IssueNOCChainCallback, pythonContext)) - .AsInteger(); + return ToPyChipError(devCtrl->IssueNOCChain( + ByteSpan(NOCSRElements, NOCSRElementsLen), nodeId, + /* Note: Memory leak here. This is a quick and a bit dirty PoC */ + new Callback::Callback(pychip_DeviceController_IssueNOCChainCallback, pythonContext))); } diff --git a/src/controller/python/ChipDeviceController-ScriptBinding.cpp b/src/controller/python/ChipDeviceController-ScriptBinding.cpp index 05e0abf8b04585..a7659e60d21f4b 100644 --- a/src/controller/python/ChipDeviceController-ScriptBinding.cpp +++ b/src/controller/python/ChipDeviceController-ScriptBinding.cpp @@ -54,6 +54,7 @@ #include #include #include +#include #include #include @@ -82,12 +83,10 @@ using namespace chip::Controller; using namespace chip::Credentials; using namespace chip::DeviceLayer; -static_assert(std::is_same::value, "python assumes CHIP_ERROR maps to c_uint32"); - extern "C" { typedef void (*ConstructBytesArrayFunct)(const uint8_t * dataBuf, uint32_t dataLen); typedef void (*LogMessageFunct)(uint64_t time, uint64_t timeUS, const char * moduleName, uint8_t category, const char * msg); -typedef void (*DeviceAvailableFunc)(DeviceProxy * device, ChipError::StorageType err); +typedef void (*DeviceAvailableFunc)(DeviceProxy * device, PyChipError err); typedef void (*ChipThreadTaskRunnerFunct)(intptr_t context); } @@ -111,79 +110,71 @@ chip::NodeId kDefaultLocalDeviceId = chip::kTestControllerNodeId; chip::NodeId kRemoteDeviceId = chip::kTestDeviceNodeId; extern "C" { -ChipError::StorageType pychip_DeviceController_StackInit(Controller::Python::StorageAdapter * storageAdapter, - bool enableServerInteractions); -ChipError::StorageType pychip_DeviceController_StackShutdown(); - -ChipError::StorageType pychip_DeviceController_NewDeviceController(chip::Controller::DeviceCommissioner ** outDevCtrl, - chip::NodeId localDeviceId, bool useTestCommissioner); -ChipError::StorageType pychip_DeviceController_DeleteDeviceController(chip::Controller::DeviceCommissioner * devCtrl); -ChipError::StorageType pychip_DeviceController_GetAddressAndPort(chip::Controller::DeviceCommissioner * devCtrl, - chip::NodeId nodeId, char * outAddress, uint64_t maxAddressLen, - uint16_t * outPort); -ChipError::StorageType pychip_DeviceController_GetCompressedFabricId(chip::Controller::DeviceCommissioner * devCtrl, - uint64_t * outFabricId); -ChipError::StorageType pychip_DeviceController_GetFabricId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outFabricId); -ChipError::StorageType pychip_DeviceController_GetNodeId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outNodeId); +PyChipError pychip_DeviceController_StackInit(Controller::Python::StorageAdapter * storageAdapter, bool enableServerInteractions); +PyChipError pychip_DeviceController_StackShutdown(); + +PyChipError pychip_DeviceController_NewDeviceController(chip::Controller::DeviceCommissioner ** outDevCtrl, + chip::NodeId localDeviceId, bool useTestCommissioner); +PyChipError pychip_DeviceController_DeleteDeviceController(chip::Controller::DeviceCommissioner * devCtrl); +PyChipError pychip_DeviceController_GetAddressAndPort(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId, + char * outAddress, uint64_t maxAddressLen, uint16_t * outPort); +PyChipError pychip_DeviceController_GetCompressedFabricId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outFabricId); +PyChipError pychip_DeviceController_GetFabricId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outFabricId); +PyChipError pychip_DeviceController_GetNodeId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outNodeId); // Rendezvous -ChipError::StorageType pychip_DeviceController_ConnectBLE(chip::Controller::DeviceCommissioner * devCtrl, uint16_t discriminator, - uint32_t setupPINCode, chip::NodeId nodeid); -ChipError::StorageType pychip_DeviceController_ConnectIP(chip::Controller::DeviceCommissioner * devCtrl, const char * peerAddrStr, - uint32_t setupPINCode, chip::NodeId nodeid); -ChipError::StorageType pychip_DeviceController_ConnectWithCode(chip::Controller::DeviceCommissioner * devCtrl, - const char * onboardingPayload, chip::NodeId nodeid); -ChipError::StorageType pychip_DeviceController_SetThreadOperationalDataset(const char * threadOperationalDataset, uint32_t size); -ChipError::StorageType pychip_DeviceController_SetWiFiCredentials(const char * ssid, const char * credentials); -ChipError::StorageType pychip_DeviceController_CloseSession(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid); -ChipError::StorageType pychip_DeviceController_EstablishPASESessionIP(chip::Controller::DeviceCommissioner * devCtrl, - const char * peerAddrStr, uint32_t setupPINCode, - chip::NodeId nodeid); -ChipError::StorageType pychip_DeviceController_Commission(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid); - -ChipError::StorageType -pychip_DeviceController_DiscoverCommissionableNodesLongDiscriminator(chip::Controller::DeviceCommissioner * devCtrl, - uint16_t long_discriminator); -ChipError::StorageType pychip_DeviceController_DiscoverAllCommissionableNodes(chip::Controller::DeviceCommissioner * devCtrl); - -ChipError::StorageType -pychip_DeviceController_DiscoverCommissionableNodesShortDiscriminator(chip::Controller::DeviceCommissioner * devCtrl, - uint16_t short_discriminator); -ChipError::StorageType pychip_DeviceController_DiscoverCommissionableNodesVendor(chip::Controller::DeviceCommissioner * devCtrl, - uint16_t vendor); -ChipError::StorageType pychip_DeviceController_DiscoverCommissionableNodesDeviceType(chip::Controller::DeviceCommissioner * devCtrl, - uint16_t device_type); -ChipError::StorageType -pychip_DeviceController_DiscoverCommissionableNodesCommissioningEnabled(chip::Controller::DeviceCommissioner * devCtrl); - -ChipError::StorageType pychip_DeviceController_OnNetworkCommission(chip::Controller::DeviceCommissioner * devCtrl, uint64_t nodeId, - uint32_t setupPasscode, const uint8_t filterType, - const char * filterParam); - -ChipError::StorageType pychip_DeviceController_PostTaskOnChipThread(ChipThreadTaskRunnerFunct callback, void * pythonContext); - -ChipError::StorageType pychip_DeviceController_OpenCommissioningWindow(chip::Controller::DeviceCommissioner * devCtrl, - chip::NodeId nodeid, uint16_t timeout, uint32_t iteration, - uint16_t discriminator, uint8_t optionInt); +PyChipError pychip_DeviceController_ConnectBLE(chip::Controller::DeviceCommissioner * devCtrl, uint16_t discriminator, + uint32_t setupPINCode, chip::NodeId nodeid); +PyChipError pychip_DeviceController_ConnectIP(chip::Controller::DeviceCommissioner * devCtrl, const char * peerAddrStr, + uint32_t setupPINCode, chip::NodeId nodeid); +PyChipError pychip_DeviceController_ConnectWithCode(chip::Controller::DeviceCommissioner * devCtrl, const char * onboardingPayload, + chip::NodeId nodeid); +PyChipError pychip_DeviceController_SetThreadOperationalDataset(const char * threadOperationalDataset, uint32_t size); +PyChipError pychip_DeviceController_SetWiFiCredentials(const char * ssid, const char * credentials); +PyChipError pychip_DeviceController_CloseSession(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid); +PyChipError pychip_DeviceController_EstablishPASESessionIP(chip::Controller::DeviceCommissioner * devCtrl, const char * peerAddrStr, + uint32_t setupPINCode, chip::NodeId nodeid); +PyChipError pychip_DeviceController_Commission(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid); + +PyChipError pychip_DeviceController_DiscoverCommissionableNodesLongDiscriminator(chip::Controller::DeviceCommissioner * devCtrl, + uint16_t long_discriminator); +PyChipError pychip_DeviceController_DiscoverAllCommissionableNodes(chip::Controller::DeviceCommissioner * devCtrl); + +PyChipError pychip_DeviceController_DiscoverCommissionableNodesShortDiscriminator(chip::Controller::DeviceCommissioner * devCtrl, + uint16_t short_discriminator); +PyChipError pychip_DeviceController_DiscoverCommissionableNodesVendor(chip::Controller::DeviceCommissioner * devCtrl, + uint16_t vendor); +PyChipError pychip_DeviceController_DiscoverCommissionableNodesDeviceType(chip::Controller::DeviceCommissioner * devCtrl, + uint16_t device_type); +PyChipError pychip_DeviceController_DiscoverCommissionableNodesCommissioningEnabled(chip::Controller::DeviceCommissioner * devCtrl); + +PyChipError pychip_DeviceController_OnNetworkCommission(chip::Controller::DeviceCommissioner * devCtrl, uint64_t nodeId, + uint32_t setupPasscode, const uint8_t filterType, const char * filterParam); + +PyChipError pychip_DeviceController_PostTaskOnChipThread(ChipThreadTaskRunnerFunct callback, void * pythonContext); + +PyChipError pychip_DeviceController_OpenCommissioningWindow(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid, + uint16_t timeout, uint32_t iteration, uint16_t discriminator, + uint8_t optionInt); void pychip_DeviceController_PrintDiscoveredDevices(chip::Controller::DeviceCommissioner * devCtrl); bool pychip_DeviceController_GetIPForDiscoveredDevice(chip::Controller::DeviceCommissioner * devCtrl, int idx, char * addrStr, uint32_t len); // Pairing Delegate -ChipError::StorageType +PyChipError pychip_ScriptDevicePairingDelegate_SetKeyExchangeCallback(chip::Controller::DeviceCommissioner * devCtrl, chip::Controller::DevicePairingDelegate_OnPairingCompleteFunct callback); -ChipError::StorageType pychip_ScriptDevicePairingDelegate_SetCommissioningCompleteCallback( +PyChipError pychip_ScriptDevicePairingDelegate_SetCommissioningCompleteCallback( chip::Controller::DeviceCommissioner * devCtrl, chip::Controller::DevicePairingDelegate_OnCommissioningCompleteFunct callback); -ChipError::StorageType pychip_ScriptDevicePairingDelegate_SetCommissioningStatusUpdateCallback( +PyChipError pychip_ScriptDevicePairingDelegate_SetCommissioningStatusUpdateCallback( chip::Controller::DeviceCommissioner * devCtrl, chip::Controller::DevicePairingDelegate_OnCommissioningStatusUpdateFunct callback); // BLE -ChipError::StorageType pychip_DeviceCommissioner_CloseBleConnection(chip::Controller::DeviceCommissioner * devCtrl); +PyChipError pychip_DeviceCommissioner_CloseBleConnection(chip::Controller::DeviceCommissioner * devCtrl); uint8_t pychip_DeviceController_GetLogFilter(); void pychip_DeviceController_SetLogFilter(uint8_t category); @@ -192,18 +183,18 @@ const char * pychip_Stack_ErrorToString(ChipError::StorageType err); const char * pychip_Stack_StatusReportToString(uint32_t profileId, uint16_t statusCode); void pychip_Stack_SetLogFunct(LogMessageFunct logFunct); -ChipError::StorageType pychip_GetConnectedDeviceByNodeId(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId, - DeviceAvailableFunc callback); -ChipError::StorageType pychip_FreeOperationalDeviceProxy(chip::OperationalDeviceProxy * deviceProxy); -ChipError::StorageType pychip_GetLocalSessionId(chip::OperationalDeviceProxy * deviceProxy, uint16_t * localSessionId); -ChipError::StorageType pychip_GetNumSessionsToPeer(chip::OperationalDeviceProxy * deviceProxy, uint32_t * numSessions); -ChipError::StorageType pychip_GetDeviceBeingCommissioned(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId, - CommissioneeDeviceProxy ** proxy); -ChipError::StorageType pychip_ExpireSessions(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId); +PyChipError pychip_GetConnectedDeviceByNodeId(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId, + DeviceAvailableFunc callback); +PyChipError pychip_FreeOperationalDeviceProxy(chip::OperationalDeviceProxy * deviceProxy); +PyChipError pychip_GetLocalSessionId(chip::OperationalDeviceProxy * deviceProxy, uint16_t * localSessionId); +PyChipError pychip_GetNumSessionsToPeer(chip::OperationalDeviceProxy * deviceProxy, uint32_t * numSessions); +PyChipError pychip_GetDeviceBeingCommissioned(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId, + CommissioneeDeviceProxy ** proxy); +PyChipError pychip_ExpireSessions(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId); uint64_t pychip_GetCommandSenderHandle(chip::DeviceProxy * device); -chip::ChipError::StorageType pychip_InteractionModel_ShutdownSubscription(SubscriptionId subscriptionId); +PyChipError pychip_InteractionModel_ShutdownSubscription(SubscriptionId subscriptionId); // // Storage @@ -229,8 +220,7 @@ void pychip_Storage_ShutdownAdapter(chip::Controller::Python::StorageAdapter * s delete storageAdapter; } -ChipError::StorageType pychip_DeviceController_StackInit(Controller::Python::StorageAdapter * storageAdapter, - bool enableServerInteractions) +PyChipError pychip_DeviceController_StackInit(Controller::Python::StorageAdapter * storageAdapter, bool enableServerInteractions) { VerifyOrDie(storageAdapter != nullptr); @@ -239,10 +229,10 @@ ChipError::StorageType pychip_DeviceController_StackInit(Controller::Python::Sto factoryParams.fabricIndependentStorage = storageAdapter; sGroupDataProvider.SetStorageDelegate(storageAdapter); - ReturnErrorOnFailure(sGroupDataProvider.Init().AsInteger()); + PyReturnErrorOnFailure(ToPyChipError(sGroupDataProvider.Init())); factoryParams.groupDataProvider = &sGroupDataProvider; - ReturnErrorOnFailure(sPersistentStorageOpCertStore.Init(storageAdapter).AsInteger()); + PyReturnErrorOnFailure(ToPyChipError(sPersistentStorageOpCertStore.Init(storageAdapter))); factoryParams.opCertStore = &sPersistentStorageOpCertStore; factoryParams.enableServerInteractions = enableServerInteractions; @@ -253,7 +243,7 @@ ChipError::StorageType pychip_DeviceController_StackInit(Controller::Python::Sto static chip::DeviceLayer::TestOnlyCommissionableDataProvider TestOnlyCommissionableDataProvider; chip::DeviceLayer::SetCommissionableDataProvider(&TestOnlyCommissionableDataProvider); - ReturnErrorOnFailure(DeviceControllerFactory::GetInstance().Init(factoryParams).AsInteger()); + PyReturnErrorOnFailure(ToPyChipError(DeviceControllerFactory::GetInstance().Init(factoryParams))); // // In situations where all the controller instances get shutdown, the entire stack is then also @@ -270,19 +260,19 @@ ChipError::StorageType pychip_DeviceController_StackInit(Controller::Python::Sto // Finally, start up the main Matter thread. Any further interactions with the stack // will now need to happen on the Matter thread, OR protected with the stack lock. // - ReturnErrorOnFailure(chip::DeviceLayer::PlatformMgr().StartEventLoopTask().AsInteger()); + PyReturnErrorOnFailure(ToPyChipError(chip::DeviceLayer::PlatformMgr().StartEventLoopTask())); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_DeviceController_StackShutdown() +PyChipError pychip_DeviceController_StackShutdown() { ChipLogError(Controller, "Shutting down the stack..."); // // Let's stop the Matter thread, and wait till the event loop has stopped. // - ReturnErrorOnFailure(chip::DeviceLayer::PlatformMgr().StopEventLoopTask().AsInteger()); + PyReturnErrorOnFailure(ToPyChipError(chip::DeviceLayer::PlatformMgr().StopEventLoopTask())); // // There is the symmetric call to match the Retain called at stack initialization @@ -292,38 +282,36 @@ ChipError::StorageType pychip_DeviceController_StackShutdown() DeviceControllerFactory::GetInstance().Shutdown(); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_DeviceController_GetAddressAndPort(chip::Controller::DeviceCommissioner * devCtrl, - chip::NodeId nodeId, char * outAddress, uint64_t maxAddressLen, - uint16_t * outPort) +PyChipError pychip_DeviceController_GetAddressAndPort(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId, + char * outAddress, uint64_t maxAddressLen, uint16_t * outPort) { Inet::IPAddress address; - ReturnErrorOnFailure(devCtrl->GetPeerAddressAndPort(nodeId, address, *outPort).AsInteger()); + PyReturnErrorOnFailure(ToPyChipError(devCtrl->GetPeerAddressAndPort(nodeId, address, *outPort))); VerifyOrReturnError(address.ToString(outAddress, static_cast(maxAddressLen)), - CHIP_ERROR_BUFFER_TOO_SMALL.AsInteger()); + ToPyChipError(CHIP_ERROR_BUFFER_TOO_SMALL)); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_DeviceController_GetCompressedFabricId(chip::Controller::DeviceCommissioner * devCtrl, - uint64_t * outFabricId) +PyChipError pychip_DeviceController_GetCompressedFabricId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outFabricId) { *outFabricId = devCtrl->GetCompressedFabricId(); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_DeviceController_GetFabricId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outFabricId) +PyChipError pychip_DeviceController_GetFabricId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outFabricId) { *outFabricId = devCtrl->GetFabricId(); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_DeviceController_GetNodeId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outNodeId) +PyChipError pychip_DeviceController_GetNodeId(chip::Controller::DeviceCommissioner * devCtrl, uint64_t * outNodeId) { *outNodeId = devCtrl->GetNodeId(); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } const char * pychip_DeviceController_ErrorToString(ChipError::StorageType err) @@ -353,44 +341,41 @@ void pychip_DeviceController_SetLogFilter(uint8_t category) #endif } -ChipError::StorageType pychip_DeviceController_ConnectBLE(chip::Controller::DeviceCommissioner * devCtrl, uint16_t discriminator, - uint32_t setupPINCode, chip::NodeId nodeid) +PyChipError pychip_DeviceController_ConnectBLE(chip::Controller::DeviceCommissioner * devCtrl, uint16_t discriminator, + uint32_t setupPINCode, chip::NodeId nodeid) { - return devCtrl - ->PairDevice(nodeid, - chip::RendezvousParameters() - .SetPeerAddress(Transport::PeerAddress(Transport::Type::kBle)) - .SetSetupPINCode(setupPINCode) - .SetDiscriminator(discriminator), - sCommissioningParameters) - .AsInteger(); + return ToPyChipError(devCtrl->PairDevice(nodeid, + chip::RendezvousParameters() + .SetPeerAddress(Transport::PeerAddress(Transport::Type::kBle)) + .SetSetupPINCode(setupPINCode) + .SetDiscriminator(discriminator), + sCommissioningParameters)); } -ChipError::StorageType pychip_DeviceController_ConnectIP(chip::Controller::DeviceCommissioner * devCtrl, const char * peerAddrStr, - uint32_t setupPINCode, chip::NodeId nodeid) +PyChipError pychip_DeviceController_ConnectIP(chip::Controller::DeviceCommissioner * devCtrl, const char * peerAddrStr, + uint32_t setupPINCode, chip::NodeId nodeid) { chip::Inet::IPAddress peerAddr; chip::Transport::PeerAddress addr; chip::RendezvousParameters params = chip::RendezvousParameters().SetSetupPINCode(setupPINCode); - VerifyOrReturnError(chip::Inet::IPAddress::FromString(peerAddrStr, peerAddr), CHIP_ERROR_INVALID_ARGUMENT.AsInteger()); + VerifyOrReturnError(chip::Inet::IPAddress::FromString(peerAddrStr, peerAddr), ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT)); // TODO: IP rendezvous should use TCP connection. addr.SetTransportType(chip::Transport::Type::kUdp).SetIPAddress(peerAddr); params.SetPeerAddress(addr).SetDiscriminator(0); - return devCtrl->PairDevice(nodeid, params, sCommissioningParameters).AsInteger(); + return ToPyChipError(devCtrl->PairDevice(nodeid, params, sCommissioningParameters)); } -ChipError::StorageType pychip_DeviceController_ConnectWithCode(chip::Controller::DeviceCommissioner * devCtrl, - const char * onboardingPayload, chip::NodeId nodeid) +PyChipError pychip_DeviceController_ConnectWithCode(chip::Controller::DeviceCommissioner * devCtrl, const char * onboardingPayload, + chip::NodeId nodeid) { - return devCtrl->PairDevice(nodeid, onboardingPayload, sCommissioningParameters).AsInteger(); + return ToPyChipError(devCtrl->PairDevice(nodeid, onboardingPayload, sCommissioningParameters)); } -ChipError::StorageType pychip_DeviceController_OnNetworkCommission(chip::Controller::DeviceCommissioner * devCtrl, uint64_t nodeId, - uint32_t setupPasscode, const uint8_t filterType, - const char * filterParam) +PyChipError pychip_DeviceController_OnNetworkCommission(chip::Controller::DeviceCommissioner * devCtrl, uint64_t nodeId, + uint32_t setupPasscode, const uint8_t filterType, const char * filterParam) { Dnssd::DiscoveryFilter filter(static_cast(filterType)); switch (static_cast(filterType)) @@ -407,7 +392,7 @@ ChipError::StorageType pychip_DeviceController_OnNetworkCommission(chip::Control unsigned long long int numericalArg = strtoull(filterParam, nullptr, 0); if ((numericalArg == ULLONG_MAX) && (errno == ERANGE)) { - return CHIP_ERROR_INVALID_ARGUMENT.AsInteger(); + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); } filter.code = static_cast(numericalArg); break; @@ -422,37 +407,37 @@ ChipError::StorageType pychip_DeviceController_OnNetworkCommission(chip::Control filter.instanceName = filterParam; break; default: - return CHIP_ERROR_INVALID_ARGUMENT.AsInteger(); + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); } sPairingDeviceDiscoveryDelegate.Init(nodeId, setupPasscode, sCommissioningParameters, &sPairingDelegate, devCtrl); devCtrl->RegisterDeviceDiscoveryDelegate(&sPairingDeviceDiscoveryDelegate); - return devCtrl->DiscoverCommissionableNodes(filter).AsInteger(); + return ToPyChipError(devCtrl->DiscoverCommissionableNodes(filter)); } -ChipError::StorageType pychip_DeviceController_SetThreadOperationalDataset(const char * threadOperationalDataset, uint32_t size) +PyChipError pychip_DeviceController_SetThreadOperationalDataset(const char * threadOperationalDataset, uint32_t size) { - ReturnErrorCodeIf(!sThreadBuf.Alloc(size), CHIP_ERROR_NO_MEMORY.AsInteger()); + ReturnErrorCodeIf(!sThreadBuf.Alloc(size), ToPyChipError(CHIP_ERROR_NO_MEMORY)); memcpy(sThreadBuf.Get(), threadOperationalDataset, size); sCommissioningParameters.SetThreadOperationalDataset(ByteSpan(sThreadBuf.Get(), size)); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_DeviceController_SetWiFiCredentials(const char * ssid, const char * credentials) +PyChipError pychip_DeviceController_SetWiFiCredentials(const char * ssid, const char * credentials) { size_t ssidSize = strlen(ssid); - ReturnErrorCodeIf(!sSsidBuf.Alloc(ssidSize), CHIP_ERROR_NO_MEMORY.AsInteger()); + ReturnErrorCodeIf(!sSsidBuf.Alloc(ssidSize), ToPyChipError(CHIP_ERROR_NO_MEMORY)); memcpy(sSsidBuf.Get(), ssid, ssidSize); size_t credsSize = strlen(credentials); - ReturnErrorCodeIf(!sCredsBuf.Alloc(credsSize), CHIP_ERROR_NO_MEMORY.AsInteger()); + ReturnErrorCodeIf(!sCredsBuf.Alloc(credsSize), ToPyChipError(CHIP_ERROR_NO_MEMORY)); memcpy(sCredsBuf.Get(), credentials, credsSize); sCommissioningParameters.SetWiFiCredentials( chip::Controller::WiFiCredentials(ByteSpan(sSsidBuf.Get(), ssidSize), ByteSpan(sCredsBuf.Get(), credsSize))); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_DeviceController_CloseSession(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid) +PyChipError pychip_DeviceController_CloseSession(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid) { // // Since we permit multiple controllers per fabric and each is associated with a unique fabric index, closing a session @@ -466,115 +451,108 @@ ChipError::StorageType pychip_DeviceController_CloseSession(chip::Controller::De } }); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_DeviceController_EstablishPASESessionIP(chip::Controller::DeviceCommissioner * devCtrl, - const char * peerAddrStr, uint32_t setupPINCode, - chip::NodeId nodeid) +PyChipError pychip_DeviceController_EstablishPASESessionIP(chip::Controller::DeviceCommissioner * devCtrl, const char * peerAddrStr, + uint32_t setupPINCode, chip::NodeId nodeid) { chip::Inet::IPAddress peerAddr; chip::Transport::PeerAddress addr; RendezvousParameters params = chip::RendezvousParameters().SetSetupPINCode(setupPINCode); - VerifyOrReturnError(chip::Inet::IPAddress::FromString(peerAddrStr, peerAddr), CHIP_ERROR_INVALID_ARGUMENT.AsInteger()); + VerifyOrReturnError(chip::Inet::IPAddress::FromString(peerAddrStr, peerAddr), ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT)); addr.SetTransportType(chip::Transport::Type::kUdp).SetIPAddress(peerAddr); params.SetPeerAddress(addr).SetDiscriminator(0); - return devCtrl->EstablishPASEConnection(nodeid, params).AsInteger(); + return ToPyChipError(devCtrl->EstablishPASEConnection(nodeid, params)); } -ChipError::StorageType pychip_DeviceController_Commission(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid) +PyChipError pychip_DeviceController_Commission(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid) { CommissioningParameters params; - return devCtrl->Commission(nodeid, params).AsInteger(); + return ToPyChipError(devCtrl->Commission(nodeid, params)); } -ChipError::StorageType pychip_DeviceController_DiscoverAllCommissionableNodes(chip::Controller::DeviceCommissioner * devCtrl) +PyChipError pychip_DeviceController_DiscoverAllCommissionableNodes(chip::Controller::DeviceCommissioner * devCtrl) { Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kNone, static_cast(0)); - return devCtrl->DiscoverCommissionableNodes(filter).AsInteger(); + return ToPyChipError(devCtrl->DiscoverCommissionableNodes(filter)); } -ChipError::StorageType -pychip_DeviceController_DiscoverCommissionableNodesLongDiscriminator(chip::Controller::DeviceCommissioner * devCtrl, - uint16_t long_discriminator) +PyChipError pychip_DeviceController_DiscoverCommissionableNodesLongDiscriminator(chip::Controller::DeviceCommissioner * devCtrl, + uint16_t long_discriminator) { Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kLongDiscriminator, long_discriminator); - return devCtrl->DiscoverCommissionableNodes(filter).AsInteger(); + return ToPyChipError(devCtrl->DiscoverCommissionableNodes(filter)); } -ChipError::StorageType -pychip_DeviceController_DiscoverCommissionableNodesShortDiscriminator(chip::Controller::DeviceCommissioner * devCtrl, - uint16_t short_discriminator) +PyChipError pychip_DeviceController_DiscoverCommissionableNodesShortDiscriminator(chip::Controller::DeviceCommissioner * devCtrl, + uint16_t short_discriminator) { Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kShortDiscriminator, short_discriminator); - return devCtrl->DiscoverCommissionableNodes(filter).AsInteger(); + return ToPyChipError(devCtrl->DiscoverCommissionableNodes(filter)); } -ChipError::StorageType pychip_DeviceController_DiscoverCommissionableNodesVendor(chip::Controller::DeviceCommissioner * devCtrl, - uint16_t vendor) +PyChipError pychip_DeviceController_DiscoverCommissionableNodesVendor(chip::Controller::DeviceCommissioner * devCtrl, + uint16_t vendor) { Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kVendorId, vendor); - return devCtrl->DiscoverCommissionableNodes(filter).AsInteger(); + return ToPyChipError(devCtrl->DiscoverCommissionableNodes(filter)); } -ChipError::StorageType pychip_DeviceController_DiscoverCommissionableNodesDeviceType(chip::Controller::DeviceCommissioner * devCtrl, - uint16_t device_type) +PyChipError pychip_DeviceController_DiscoverCommissionableNodesDeviceType(chip::Controller::DeviceCommissioner * devCtrl, + uint16_t device_type) { Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kDeviceType, device_type); - return devCtrl->DiscoverCommissionableNodes(filter).AsInteger(); + return ToPyChipError(devCtrl->DiscoverCommissionableNodes(filter)); } -ChipError::StorageType -pychip_DeviceController_DiscoverCommissionableNodesCommissioningEnabled(chip::Controller::DeviceCommissioner * devCtrl) +PyChipError pychip_DeviceController_DiscoverCommissionableNodesCommissioningEnabled(chip::Controller::DeviceCommissioner * devCtrl) { Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kCommissioningMode); - return devCtrl->DiscoverCommissionableNodes(filter).AsInteger(); + return ToPyChipError(devCtrl->DiscoverCommissionableNodes(filter)); } -ChipError::StorageType pychip_DeviceController_OpenCommissioningWindow(chip::Controller::DeviceCommissioner * devCtrl, - chip::NodeId nodeid, uint16_t timeout, uint32_t iteration, - uint16_t discriminator, uint8_t optionInt) +PyChipError pychip_DeviceController_OpenCommissioningWindow(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeid, + uint16_t timeout, uint32_t iteration, uint16_t discriminator, + uint8_t optionInt) { const auto option = static_cast(optionInt); if (option == Controller::CommissioningWindowOpener::CommissioningWindowOption::kOriginalSetupCode) { - return Controller::AutoCommissioningWindowOpener::OpenBasicCommissioningWindow(devCtrl, nodeid, - System::Clock::Seconds16(timeout)) - .AsInteger(); + return ToPyChipError(Controller::AutoCommissioningWindowOpener::OpenBasicCommissioningWindow( + devCtrl, nodeid, System::Clock::Seconds16(timeout))); } if (option == Controller::CommissioningWindowOpener::CommissioningWindowOption::kTokenWithRandomPIN) { SetupPayload payload; - return Controller::AutoCommissioningWindowOpener::OpenCommissioningWindow( - devCtrl, nodeid, System::Clock::Seconds16(timeout), iteration, discriminator, NullOptional, NullOptional, - payload) - .AsInteger(); + return ToPyChipError(Controller::AutoCommissioningWindowOpener::OpenCommissioningWindow( + devCtrl, nodeid, System::Clock::Seconds16(timeout), iteration, discriminator, NullOptional, NullOptional, payload)); } - return CHIP_ERROR_INVALID_ARGUMENT.AsInteger(); + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); } -ChipError::StorageType +PyChipError pychip_ScriptDevicePairingDelegate_SetKeyExchangeCallback(chip::Controller::DeviceCommissioner * devCtrl, chip::Controller::DevicePairingDelegate_OnPairingCompleteFunct callback) { sPairingDelegate.SetKeyExchangeCallback(callback); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_ScriptDevicePairingDelegate_SetCommissioningCompleteCallback( +PyChipError pychip_ScriptDevicePairingDelegate_SetCommissioningCompleteCallback( chip::Controller::DeviceCommissioner * devCtrl, chip::Controller::DevicePairingDelegate_OnCommissioningCompleteFunct callback) { sPairingDelegate.SetCommissioningCompleteCallback(callback); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_ScriptDevicePairingDelegate_SetCommissioningStatusUpdateCallback( +PyChipError pychip_ScriptDevicePairingDelegate_SetCommissioningStatusUpdateCallback( chip::Controller::DeviceCommissioner * devCtrl, chip::Controller::DevicePairingDelegate_OnCommissioningStatusUpdateFunct callback) { sPairingDelegate.SetCommissioningStatusUpdateCallback(callback); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } const char * pychip_Stack_ErrorToString(ChipError::StorageType err) @@ -600,14 +578,14 @@ struct GetDeviceCallbacks { auto * self = static_cast(context); auto * operationalDeviceProxy = new OperationalDeviceProxy(&exchangeMgr, sessionHandle); - self->mCallback(operationalDeviceProxy, CHIP_NO_ERROR.AsInteger()); + self->mCallback(operationalDeviceProxy, ToPyChipError(CHIP_NO_ERROR)); delete self; } static void OnConnectionFailureFn(void * context, const ScopedNodeId & peerId, CHIP_ERROR error) { auto * self = static_cast(context); - self->mCallback(nullptr, error.AsInteger()); + self->mCallback(nullptr, ToPyChipError(error)); delete self; } @@ -617,70 +595,70 @@ struct GetDeviceCallbacks }; } // anonymous namespace -ChipError::StorageType pychip_GetConnectedDeviceByNodeId(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId, - DeviceAvailableFunc callback) +PyChipError pychip_GetConnectedDeviceByNodeId(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId, + DeviceAvailableFunc callback) { - VerifyOrReturnError(devCtrl != nullptr, CHIP_ERROR_INVALID_ARGUMENT.AsInteger()); + VerifyOrReturnError(devCtrl != nullptr, ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT)); auto * callbacks = new GetDeviceCallbacks(callback); - return devCtrl->GetConnectedDevice(nodeId, &callbacks->mOnSuccess, &callbacks->mOnFailure).AsInteger(); + return ToPyChipError(devCtrl->GetConnectedDevice(nodeId, &callbacks->mOnSuccess, &callbacks->mOnFailure)); } -ChipError::StorageType pychip_FreeOperationalDeviceProxy(chip::OperationalDeviceProxy * deviceProxy) +PyChipError pychip_FreeOperationalDeviceProxy(chip::OperationalDeviceProxy * deviceProxy) { if (deviceProxy != nullptr) { delete deviceProxy; } - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_GetLocalSessionId(chip::OperationalDeviceProxy * deviceProxy, uint16_t * localSessionId) +PyChipError pychip_GetLocalSessionId(chip::OperationalDeviceProxy * deviceProxy, uint16_t * localSessionId) { - VerifyOrReturnError(deviceProxy->GetSecureSession().HasValue(), CHIP_ERROR_MISSING_SECURE_SESSION.AsInteger()); - VerifyOrReturnError(localSessionId != nullptr, CHIP_ERROR_INVALID_ARGUMENT.AsInteger()); + VerifyOrReturnError(deviceProxy->GetSecureSession().HasValue(), ToPyChipError(CHIP_ERROR_MISSING_SECURE_SESSION)); + VerifyOrReturnError(localSessionId != nullptr, ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT)); *localSessionId = deviceProxy->GetSecureSession().Value()->AsSecureSession()->GetLocalSessionId(); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_GetNumSessionsToPeer(chip::OperationalDeviceProxy * deviceProxy, uint32_t * numSessions) +PyChipError pychip_GetNumSessionsToPeer(chip::OperationalDeviceProxy * deviceProxy, uint32_t * numSessions) { - VerifyOrReturnError(deviceProxy->GetSecureSession().HasValue(), CHIP_ERROR_MISSING_SECURE_SESSION.AsInteger()); - VerifyOrReturnError(numSessions != nullptr, CHIP_ERROR_INVALID_ARGUMENT.AsInteger()); + VerifyOrReturnError(deviceProxy->GetSecureSession().HasValue(), ToPyChipError(CHIP_ERROR_MISSING_SECURE_SESSION)); + VerifyOrReturnError(numSessions != nullptr, ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT)); *numSessions = 0; deviceProxy->GetExchangeManager()->GetSessionManager()->ForEachMatchingSession( deviceProxy->GetPeerScopedNodeId(), [numSessions](auto * session) { (*numSessions)++; }); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_GetDeviceBeingCommissioned(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId, - CommissioneeDeviceProxy ** proxy) +PyChipError pychip_GetDeviceBeingCommissioned(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId, + CommissioneeDeviceProxy ** proxy) { - return devCtrl->GetDeviceBeingCommissioned(nodeId, proxy).AsInteger(); + return ToPyChipError(devCtrl->GetDeviceBeingCommissioned(nodeId, proxy)); } // This is a method called VERY seldom, just for RemoveFabric/UpdateNOC -ChipError::StorageType pychip_ExpireSessions(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId) +PyChipError pychip_ExpireSessions(chip::Controller::DeviceCommissioner * devCtrl, chip::NodeId nodeId) { - VerifyOrReturnError((devCtrl != nullptr) && (devCtrl->SessionMgr() != nullptr), CHIP_ERROR_INVALID_ARGUMENT.AsInteger()); + VerifyOrReturnError((devCtrl != nullptr) && (devCtrl->SessionMgr() != nullptr), ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT)); // // Since we permit multiple controllers on the same fabric each associated with a different fabric index, expiring a session // needs to correctly expire sessions on other controllers on matching fabrics as well. // devCtrl->SessionMgr()->ExpireAllSessionsOnLogicalFabric(ScopedNodeId(nodeId, devCtrl->GetFabricIndex())); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_DeviceCommissioner_CloseBleConnection(chip::Controller::DeviceCommissioner * devCtrl) +PyChipError pychip_DeviceCommissioner_CloseBleConnection(chip::Controller::DeviceCommissioner * devCtrl) { #if CONFIG_NETWORK_LAYER_BLE devCtrl->CloseBleConnection(); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); #else - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE.AsInteger(); + return ToPyChipError(CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); #endif } @@ -700,12 +678,12 @@ void pychip_Stack_SetLogFunct(LogMessageFunct logFunct) // like using the log module. } -ChipError::StorageType pychip_DeviceController_PostTaskOnChipThread(ChipThreadTaskRunnerFunct callback, void * pythonContext) +PyChipError pychip_DeviceController_PostTaskOnChipThread(ChipThreadTaskRunnerFunct callback, void * pythonContext) { if (callback == nullptr || pythonContext == nullptr) { - return CHIP_ERROR_INVALID_ARGUMENT.AsInteger(); + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); } PlatformMgr().ScheduleWork(callback, reinterpret_cast(pythonContext)); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } diff --git a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp index e98b68ace56446..67cc6abdb01702 100644 --- a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp +++ b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.cpp @@ -19,6 +19,7 @@ #include "ChipDeviceController-ScriptDevicePairingDelegate.h" #include "lib/support/TypeTraits.h" +#include namespace chip { namespace Controller { @@ -53,7 +54,7 @@ void ScriptDevicePairingDelegate::OnPairingComplete(CHIP_ERROR error) { if (mOnPairingCompleteCallback != nullptr) { - mOnPairingCompleteCallback(error.AsInteger()); + mOnPairingCompleteCallback(ToPyChipError(error)); } } @@ -61,7 +62,7 @@ void ScriptDevicePairingDelegate::OnCommissioningComplete(NodeId nodeId, CHIP_ER { if (mOnCommissioningCompleteCallback != nullptr) { - mOnCommissioningCompleteCallback(nodeId, error.AsInteger()); + mOnCommissioningCompleteCallback(nodeId, ToPyChipError(error)); } } diff --git a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h index 24991ffa5f73ca..cc41b30d3eb4b1 100644 --- a/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h +++ b/src/controller/python/ChipDeviceController-ScriptDevicePairingDelegate.h @@ -26,13 +26,14 @@ #pragma once #include +#include namespace chip { namespace Controller { extern "C" { -typedef void (*DevicePairingDelegate_OnPairingCompleteFunct)(ChipError::StorageType err); -typedef void (*DevicePairingDelegate_OnCommissioningCompleteFunct)(NodeId nodeId, ChipError::StorageType err); +typedef void (*DevicePairingDelegate_OnPairingCompleteFunct)(PyChipError err); +typedef void (*DevicePairingDelegate_OnCommissioningCompleteFunct)(NodeId nodeId, PyChipError err); // Used for testing by OpCredsBinding typedef void (*DevicePairingDelegate_OnCommissioningSuccessFunct)(PeerId peerId); diff --git a/src/controller/python/OpCredsBinding.cpp b/src/controller/python/OpCredsBinding.cpp index 2787b096307e59..ef92b2c163b575 100644 --- a/src/controller/python/OpCredsBinding.cpp +++ b/src/controller/python/OpCredsBinding.cpp @@ -36,6 +36,7 @@ #include #include +#include #include #include #include @@ -43,8 +44,6 @@ using namespace chip; -static_assert(std::is_same::value, "python assumes CHIP_ERROR maps to c_uint32"); - using Py_GenerateNOCChainFunc = void (*)(void * pyContext, const char * csrElements, const char * attestationSignature, const char * dac, const char * pai, const char * paa, Controller::OnNOCChainGeneration onNocChainGenerationFunc); @@ -320,19 +319,17 @@ void pychip_OnCommissioningStatusUpdate(chip::PeerId peerId, chip::Controller::C return sTestCommissioner.OnCommissioningStatusUpdate(peerId, stageCompleted, err); } -ChipError::StorageType pychip_OpCreds_AllocateController(OpCredsContext * context, - chip::Controller::DeviceCommissioner ** outDevCtrl, FabricId fabricId, - chip::NodeId nodeId, chip::VendorId adminVendorId, - const char * paaTrustStorePath, bool useTestCommissioner, - bool enableServerInteractions, CASEAuthTag * caseAuthTags, - uint32_t caseAuthTagLen) +PyChipError pychip_OpCreds_AllocateController(OpCredsContext * context, chip::Controller::DeviceCommissioner ** outDevCtrl, + FabricId fabricId, chip::NodeId nodeId, chip::VendorId adminVendorId, + const char * paaTrustStorePath, bool useTestCommissioner, + bool enableServerInteractions, CASEAuthTag * caseAuthTags, uint32_t caseAuthTagLen) { ChipLogDetail(Controller, "Creating New Device Controller"); - VerifyOrReturnError(context != nullptr, CHIP_ERROR_INVALID_ARGUMENT.AsInteger()); + VerifyOrReturnError(context != nullptr, ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT)); auto devCtrl = std::make_unique(); - VerifyOrReturnError(devCtrl != nullptr, CHIP_ERROR_NO_MEMORY.AsInteger()); + VerifyOrReturnError(devCtrl != nullptr, ToPyChipError(CHIP_ERROR_NO_MEMORY)); if (paaTrustStorePath == nullptr) { @@ -347,18 +344,18 @@ ChipError::StorageType pychip_OpCreds_AllocateController(OpCredsContext * contex chip::Crypto::P256Keypair ephemeralKey; CHIP_ERROR err = ephemeralKey.Initialize(); - VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger()); + VerifyOrReturnError(err == CHIP_NO_ERROR, ToPyChipError(err)); chip::Platform::ScopedMemoryBuffer noc; - ReturnErrorCodeIf(!noc.Alloc(Controller::kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY.AsInteger()); + ReturnErrorCodeIf(!noc.Alloc(Controller::kMaxCHIPDERCertLength), ToPyChipError(CHIP_ERROR_NO_MEMORY)); MutableByteSpan nocSpan(noc.Get(), Controller::kMaxCHIPDERCertLength); chip::Platform::ScopedMemoryBuffer icac; - ReturnErrorCodeIf(!icac.Alloc(Controller::kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY.AsInteger()); + ReturnErrorCodeIf(!icac.Alloc(Controller::kMaxCHIPDERCertLength), ToPyChipError(CHIP_ERROR_NO_MEMORY)); MutableByteSpan icacSpan(icac.Get(), Controller::kMaxCHIPDERCertLength); chip::Platform::ScopedMemoryBuffer rcac; - ReturnErrorCodeIf(!rcac.Alloc(Controller::kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY.AsInteger()); + ReturnErrorCodeIf(!rcac.Alloc(Controller::kMaxCHIPDERCertLength), ToPyChipError(CHIP_ERROR_NO_MEMORY)); MutableByteSpan rcacSpan(rcac.Get(), Controller::kMaxCHIPDERCertLength); CATValues catValues; @@ -367,13 +364,13 @@ ChipError::StorageType pychip_OpCreds_AllocateController(OpCredsContext * contex { ChipLogError(Controller, "Too many of CASE Tags (%u) exceeds kMaxSubjectCATAttributeCount", static_cast(caseAuthTagLen)); - return CHIP_ERROR_INVALID_ARGUMENT.AsInteger(); + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); } memcpy(catValues.values.data(), caseAuthTags, caseAuthTagLen * sizeof(CASEAuthTag)); err = context->mAdapter->GenerateNOCChain(nodeId, fabricId, catValues, ephemeralKey.Pubkey(), rcacSpan, icacSpan, nocSpan); - VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger()); + VerifyOrReturnError(err == CHIP_NO_ERROR, ToPyChipError(err)); Controller::SetupParams initParams; initParams.pairingDelegate = &sPairingDelegate; @@ -395,14 +392,14 @@ ChipError::StorageType pychip_OpCreds_AllocateController(OpCredsContext * contex } err = Controller::DeviceControllerFactory::GetInstance().SetupCommissioner(initParams, *devCtrl); - VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger()); + VerifyOrReturnError(err == CHIP_NO_ERROR, ToPyChipError(err)); // Setup IPK in Group Data Provider for controller after Commissioner init which sets-up the fabric table entry uint8_t compressedFabricId[sizeof(uint64_t)] = { 0 }; chip::MutableByteSpan compressedFabricIdSpan(compressedFabricId); err = devCtrl->GetCompressedFabricIdBytes(compressedFabricIdSpan); - VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger()); + VerifyOrReturnError(err == CHIP_NO_ERROR, ToPyChipError(err)); ChipLogProgress(Support, "Setting up group data for Fabric Index %u with Compressed Fabric ID:", static_cast(devCtrl->GetFabricIndex())); @@ -411,20 +408,20 @@ ChipError::StorageType pychip_OpCreds_AllocateController(OpCredsContext * contex chip::ByteSpan defaultIpk = chip::GroupTesting::DefaultIpkValue::GetDefaultIpk(); err = chip::Credentials::SetSingleIpkEpochKey(&sGroupDataProvider, devCtrl->GetFabricIndex(), defaultIpk, compressedFabricIdSpan); - VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger()); + VerifyOrReturnError(err == CHIP_NO_ERROR, ToPyChipError(err)); *outDevCtrl = devCtrl.release(); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -ChipError::StorageType pychip_OpCreds_SetMaximallyLargeCertsUsed(OpCredsContext * context, bool enabled) +PyChipError pychip_OpCreds_SetMaximallyLargeCertsUsed(OpCredsContext * context, bool enabled) { - VerifyOrReturnError(context != nullptr && context->mAdapter != nullptr, CHIP_ERROR_INCORRECT_STATE.AsInteger()); + VerifyOrReturnError(context != nullptr && context->mAdapter != nullptr, ToPyChipError(CHIP_ERROR_INCORRECT_STATE)); context->mAdapter->SetMaximallyLargeCertsUsed(enabled); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } void pychip_OpCreds_FreeDelegate(OpCredsContext * context) @@ -432,7 +429,7 @@ void pychip_OpCreds_FreeDelegate(OpCredsContext * context) Platform::Delete(context); } -ChipError::StorageType pychip_DeviceController_DeleteDeviceController(chip::Controller::DeviceCommissioner * devCtrl) +PyChipError pychip_DeviceController_DeleteDeviceController(chip::Controller::DeviceCommissioner * devCtrl) { if (devCtrl != nullptr) { @@ -440,7 +437,7 @@ ChipError::StorageType pychip_DeviceController_DeleteDeviceController(chip::Cont delete devCtrl; } - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } bool pychip_TestCommissionerUsed() diff --git a/src/controller/python/chip/CertificateAuthority.py b/src/controller/python/chip/CertificateAuthority.py index 7f40f0cd016100..b6f283129a1a31 100644 --- a/src/controller/python/chip/CertificateAuthority.py +++ b/src/controller/python/chip/CertificateAuthority.py @@ -22,6 +22,7 @@ from dataclasses import dataclass, field from typing import * from ctypes import * +from chip.native import PyChipError from rich.pretty import pprint import json import logging @@ -74,7 +75,7 @@ def __init__(self, chipStack: ChipStack.ChipStack, caIndex: int, persistentStora self._Handle().pychip_OpCreds_InitializeDelegate.restype = c_void_p self._Handle().pychip_OpCreds_InitializeDelegate.argtypes = [ctypes.py_object, ctypes.c_uint32, ctypes.c_void_p] - self._Handle().pychip_OpCreds_SetMaximallyLargeCertsUsed.restype = c_uint32 + self._Handle().pychip_OpCreds_SetMaximallyLargeCertsUsed.restype = PyChipError self._Handle().pychip_OpCreds_SetMaximallyLargeCertsUsed.argtypes = [ctypes.c_void_p, ctypes.c_bool] if (persistentStorage is None): @@ -191,12 +192,9 @@ def maximizeCertChains(self) -> bool: @maximizeCertChains.setter def maximizeCertChains(self, enabled: bool): - res = self._chipStack.Call( + self._chipStack.Call( lambda: self._Handle().pychip_OpCreds_SetMaximallyLargeCertsUsed(ctypes.c_void_p(self._closure), ctypes.c_bool(enabled)) - ) - - if res != 0: - raise self._chipStack.ErrorToException(res) + ).raise_on_error() self._maximizeCertChains = enabled diff --git a/src/controller/python/chip/ChipCommissionableNodeCtrl.py b/src/controller/python/chip/ChipCommissionableNodeCtrl.py index c1d47dd64b91c0..9a3bcc2c6f40a0 100644 --- a/src/controller/python/chip/ChipCommissionableNodeCtrl.py +++ b/src/controller/python/chip/ChipCommissionableNodeCtrl.py @@ -28,6 +28,7 @@ from ctypes import * from .ChipStack import * from .exceptions import * +from .native import PyChipError __all__ = ["ChipCommissionableNodeController"] @@ -53,10 +54,8 @@ def __init__(self, chipStack: ChipStack): self._InitLib() commissionableNodeCtrl = c_void_p(None) - res = self._dmLib.pychip_CommissionableNodeController_NewController( - pointer(commissionableNodeCtrl)) - if res != 0: - raise self._ChipStack.ErrorToException(res) + self._dmLib.pychip_CommissionableNodeController_NewController( + pointer(commissionableNodeCtrl)).raise_on_error() self.commissionableNodeCtrl = commissionableNodeCtrl self._ChipStack.commissionableNodeCtrl = commissionableNodeCtrl @@ -68,16 +67,16 @@ def __del__(self): self.commissionableNodeCtrl = None def PrintDiscoveredCommissioners(self): - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_CommissionableNodeController_PrintDiscoveredCommissioners( self.commissionableNodeCtrl) ) def DiscoverCommissioners(self): - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_CommissionableNodeController_DiscoverCommissioners( self.commissionableNodeCtrl) - ) + ).raise_on_error() # ----- Private Members ----- def _InitLib(self): @@ -86,15 +85,15 @@ def _InitLib(self): self._dmLib.pychip_CommissionableNodeController_NewController.argtypes = [ POINTER(c_void_p)] - self._dmLib.pychip_CommissionableNodeController_NewController.restype = c_uint32 + self._dmLib.pychip_CommissionableNodeController_NewController.restype = PyChipError self._dmLib.pychip_CommissionableNodeController_DeleteController.argtypes = [ c_void_p] - self._dmLib.pychip_CommissionableNodeController_DeleteController.restype = c_uint32 + self._dmLib.pychip_CommissionableNodeController_DeleteController.restype = PyChipError self._dmLib.pychip_CommissionableNodeController_DiscoverCommissioners.argtypes = [ c_void_p] - self._dmLib.pychip_CommissionableNodeController_DiscoverCommissioners.restype = c_uint32 + self._dmLib.pychip_CommissionableNodeController_DiscoverCommissioners.restype = PyChipError self._dmLib.pychip_CommissionableNodeController_PrintDiscoveredCommissioners.argtypes = [ c_void_p] diff --git a/src/controller/python/chip/ChipDeviceCtrl.py b/src/controller/python/chip/ChipDeviceCtrl.py index 4547567680f404..9c07108acc45cb 100644 --- a/src/controller/python/chip/ChipDeviceCtrl.py +++ b/src/controller/python/chip/ChipDeviceCtrl.py @@ -42,6 +42,7 @@ from . import clusters as Clusters from .FabricAdmin import FabricAdmin from . import discovery +from .native import PyChipError import enum import threading import typing @@ -54,19 +55,19 @@ __all__ = ["ChipDeviceController"] -_DevicePairingDelegate_OnPairingCompleteFunct = CFUNCTYPE(None, c_uint32) +_DevicePairingDelegate_OnPairingCompleteFunct = CFUNCTYPE(None, PyChipError) _DevicePairingDelegate_OnCommissioningCompleteFunct = CFUNCTYPE( - None, c_uint64, c_uint32) + None, c_uint64, PyChipError) _DevicePairingDelegate_OnCommissioningStatusUpdateFunct = CFUNCTYPE( - None, c_uint64, c_uint8, c_uint32) + None, c_uint64, c_uint8, PyChipError) # void (*)(Device *, CHIP_ERROR). # # CHIP_ERROR is actually signed, so using c_uint32 is weird, but everything # else seems to do it. -_DeviceAvailableFunct = CFUNCTYPE(None, c_void_p, c_uint32) +_DeviceAvailableFunct = CFUNCTYPE(None, c_void_p, PyChipError) _IssueNOCChainCallbackPythonCallbackFunct = CFUNCTYPE( - None, py_object, c_uint32, c_void_p, c_size_t, c_void_p, c_size_t, c_void_p, c_size_t, c_void_p, c_size_t, c_uint64) + None, py_object, PyChipError, c_void_p, c_size_t, c_void_p, c_size_t, c_void_p, c_size_t, c_void_p, c_size_t, c_uint64) _ChipDeviceController_IterateDiscoveredCommissionableNodesFunct = CFUNCTYPE(None, c_char_p, c_size_t) @@ -81,9 +82,9 @@ class NOCChain: @_IssueNOCChainCallbackPythonCallbackFunct -def _IssueNOCChainCallbackPythonCallback(devCtrl, status: int, noc: c_void_p, nocLen: int, icac: c_void_p, icacLen: int, rcac: c_void_p, rcacLen: int, ipk: c_void_p, ipkLen: int, adminSubject: int): +def _IssueNOCChainCallbackPythonCallback(devCtrl, status: PyChipError, noc: c_void_p, nocLen: int, icac: c_void_p, icacLen: int, rcac: c_void_p, rcacLen: int, ipk: c_void_p, ipkLen: int, adminSubject: int): nocChain = NOCChain(None, None, None, None, 0) - if status == 0: + if status.is_success: nocBytes = None if nocLen > 0: nocBytes = string_at(noc, nocLen)[:] @@ -170,26 +171,26 @@ def deviceProxy(self) -> ctypes.c_void_p: @property def localSessionId(self) -> int: self._dmLib.pychip_GetLocalSessionId.argtypes = [ctypes.c_void_p, POINTER(ctypes.c_uint16)] - self._dmLib.pychip_GetLocalSessionId.restype = ctypes.c_uint32 + self._dmLib.pychip_GetLocalSessionId.restype = PyChipError localSessionId = ctypes.c_uint16(0) builtins.chipStack.Call( lambda: self._dmLib.pychip_GetLocalSessionId(self._deviceProxy, pointer(localSessionId)) - ) + ).raise_on_error() return localSessionId.value @property def numTotalSessions(self) -> int: self._dmLib.pychip_GetNumSessionsToPeer.argtypes = [ctypes.c_void_p, POINTER(ctypes.c_uint32)] - self._dmLib.pychip_GetNumSessionsToPeer.restype = ctypes.c_uint32 + self._dmLib.pychip_GetNumSessionsToPeer.restype = PyChipError numSessions = ctypes.c_uint32(0) builtins.chipStack.Call( lambda: self._dmLib.pychip_GetNumSessionsToPeer(self._deviceProxy, pointer(numSessions)) - ) + ).raise_on_error() return numSessions.value @@ -219,16 +220,13 @@ def __init__(self, opCredsContext: ctypes.c_void_p, fabricId: int, nodeId: int, self._dmLib.pychip_OpCreds_AllocateController.argtypes = [c_void_p, POINTER( c_void_p), c_uint64, c_uint64, c_uint16, c_char_p, c_bool, c_bool, POINTER(c_uint32), c_uint32] - self._dmLib.pychip_OpCreds_AllocateController.restype = c_uint32 + self._dmLib.pychip_OpCreds_AllocateController.restype = PyChipError # TODO(erjiaqing@): Figure out how to control enableServerInteractions for a single device controller (node) - res = self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_OpCreds_AllocateController(c_void_p( opCredsContext), pointer(devCtrl), fabricId, nodeId, adminVendorId, c_char_p(None if len(paaTrustStorePath) == 0 else str.encode(paaTrustStorePath)), useTestCommissioner, self._ChipStack.enableServerInteractions, c_catTags, len(catTags)) - ) - - if res != 0: - raise self._ChipStack.ErrorToException(res) + ).raise_on_error() self.devCtrl = devCtrl self._fabricAdmin = fabricAdmin @@ -245,21 +243,21 @@ def __init__(self, opCredsContext: ctypes.c_void_p, fabricId: int, nodeId: int, self._Cluster.InitLib(self._dmLib) def HandleCommissioningComplete(nodeid, err): - if err != 0: - print("Failed to commission: {}".format(err)) - else: + if err.is_success: print("Commissioning complete") + else: + print("Failed to commission: {}".format(err)) + self.state = DCState.IDLE self._ChipStack.callbackRes = err self._ChipStack.commissioningEventRes = err self._ChipStack.commissioningCompleteEvent.set() self._ChipStack.completeEvent.set() - def HandlePASEEstablishmentComplete(err): - if err != 0: + def HandlePASEEstablishmentComplete(err: PyChipError): + if err.is_success: print("Failed to establish secure session to device: {}".format(err)) - self._ChipStack.callbackRes = self._ChipStack.ErrorToException( - err) + self._ChipStack.callbackRes = err.to_exception() else: print("Established secure session with Device") @@ -272,7 +270,7 @@ def HandlePASEEstablishmentComplete(err): else: # When commissioning, getting an error during key exhange # needs to unblock the entire commissioning flow. - if err != 0: + if not err.is_success: HandleCommissioningComplete(0, err) self.cbHandlePASEEstablishmentCompleteFunct = _DevicePairingDelegate_OnPairingCompleteFunct( @@ -333,7 +331,7 @@ def Shutdown(self): self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_DeleteDeviceController( self.devCtrl) - ) + ).raise_on_error() self.devCtrl = None ChipDeviceController.activeList.remove(self) @@ -374,18 +372,6 @@ def IsConnected(self): self.devCtrl) ) - def ConnectBle(self, bleConnection): - self.CheckIsActive() - - self._ChipStack.CallAsync( - lambda: self._dmLib.pychip_DeviceController_ValidateBTP( - self.devCtrl, - bleConnection, - self._ChipStack.cbHandleComplete, - self._ChipStack.cbHandleError, - ) - ) - def ConnectBLE(self, discriminator, setupPinCode, nodeid): self.CheckIsActive() @@ -395,19 +381,19 @@ def ConnectBLE(self, discriminator, setupPinCode, nodeid): self._ChipStack.CallAsync( lambda: self._dmLib.pychip_DeviceController_ConnectBLE( self.devCtrl, discriminator, setupPinCode, nodeid) - ) + ).raise_on_error() if not self._ChipStack.commissioningCompleteEvent.isSet(): # Error 50 is a timeout return False - return self._ChipStack.commissioningEventRes == 0 + return self._ChipStack.commissioningEventRes.is_success def CloseBLEConnection(self): self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceCommissioner_CloseBleConnection( self.devCtrl) - ) + ).raise_on_error() def ExpireSessions(self, nodeid): """Close all sessions with `nodeid` (if any existed) so that sessions get re-established. @@ -419,18 +405,16 @@ def ExpireSessions(self, nodeid): """ self.CheckIsActive() - res = self._ChipStack.Call(lambda: self._dmLib.pychip_ExpireSessions(self.devCtrl, nodeid)) - if res != 0: - raise self._ChipStack.ErrorToException(res) + self._ChipStack.Call(lambda: self._dmLib.pychip_ExpireSessions(self.devCtrl, nodeid)).raise_on_error() # TODO: This needs to be called MarkSessionDefunct def CloseSession(self, nodeid): self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_CloseSession( self.devCtrl, nodeid) - ) + ).raise_on_error() def EstablishPASESessionIP(self, ipaddr: str, setupPinCode: int, nodeid: int): self.CheckIsActive() @@ -576,18 +560,18 @@ def CommissionWiFi(self, discriminator, setupPinCode, nodeId, ssid: str, credent def SetWiFiCredentials(self, ssid: str, credentials: str): self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_SetWiFiCredentials( ssid.encode("utf-8"), credentials.encode("utf-8")) - ) + ).raise_on_error() def SetThreadOperationalDataset(self, threadOperationalDataset): self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_SetThreadOperationalDataset( threadOperationalDataset, len(threadOperationalDataset)) - ) + ).raise_on_error() def ResolveNode(self, nodeid): self.CheckIsActive() @@ -600,6 +584,7 @@ def GetAddressAndPort(self, nodeid): address = create_string_buffer(64) port = c_uint16(0) + # Intentially return None instead of raising exceptions on error error = self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_GetAddressAndPort( self.devCtrl, nodeid, address, 64, pointer(port)) @@ -628,12 +613,9 @@ def DiscoverCommissionableNodes(self, filterType: discovery.FilterType = discove if isinstance(filter, int): filter = str(filter) - res = self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_DiscoverCommissionableNodes( - self.devCtrl, int(filterType), str(filter).encode("utf-8") + b"\x00")) - - if res != 0: - raise self._ChipStack.ErrorToException(res) + self.devCtrl, int(filterType), str(filter).encode("utf-8") + b"\x00")).raise_on_error() if timeoutSecond != 0: if stopOnFirst: @@ -652,57 +634,57 @@ def DiscoverCommissionableNodesLongDiscriminator(self, long_discriminator): ''' self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesLongDiscriminator( self.devCtrl, long_discriminator) - ) + ).raise_on_error() def DiscoverCommissionableNodesShortDiscriminator(self, short_discriminator): ''' Deprecated, use DiscoverCommissionableNodes ''' self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesShortDiscriminator( self.devCtrl, short_discriminator) - ) + ).raise_on_error() def DiscoverCommissionableNodesVendor(self, vendor): ''' Deprecated, use DiscoverCommissionableNodes ''' self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesVendor( self.devCtrl, vendor) - ) + ).raise_on_error() def DiscoverCommissionableNodesDeviceType(self, device_type): ''' Deprecated, use DiscoverCommissionableNodes ''' self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesDeviceType( self.devCtrl, device_type) - ) + ).raise_on_error() def DiscoverCommissionableNodesCommissioningEnabled(self): ''' Deprecated, use DiscoverCommissionableNodes ''' self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesCommissioningEnabled( self.devCtrl) - ) + ).raise_on_error() def PrintDiscoveredDevices(self): ''' Deprecated, use GetCommissionableNodes ''' self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_PrintDiscoveredDevices( self.devCtrl) ) @@ -723,15 +705,6 @@ def HandleDevice(deviceJson, deviceJsonLen): return self._ChipStack.Call(lambda: GetDevices(self)) - def ParseQRCode(self, qrCode, output): - self.CheckIsActive() - - print(output) - return self._ChipStack.Call( - lambda: self._dmLib.pychip_DeviceController_ParseQRCode( - qrCode, output) - ) - def GetIPForDiscoveredDevice(self, idx, addrStr, length): self.CheckIsActive() @@ -745,36 +718,30 @@ def DiscoverAllCommissioning(self): ''' self.CheckIsActive() - return self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_DiscoverAllCommissionableNodes( self.devCtrl) - ) + ).raise_on_error() def OpenCommissioningWindow(self, nodeid, timeout, iteration, discriminator, option): self.CheckIsActive() - res = self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_OpenCommissioningWindow( self.devCtrl, nodeid, timeout, iteration, discriminator, option) - ) - - if res != 0: - raise self._ChipStack.ErrorToException(res) + ).raise_on_error() def GetCompressedFabricId(self): self.CheckIsActive() fabricid = c_uint64(0) - res = self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_GetCompressedFabricId( self.devCtrl, pointer(fabricid)) - ) + ).raise_on_error() - if res == 0: - return fabricid.value - else: - raise self._ChipStack.ErrorToException(res) + return fabricid.value def GetFabricIdInternal(self): """Get the fabric ID from the object. Only used to validate cached value from property.""" @@ -782,15 +749,12 @@ def GetFabricIdInternal(self): fabricid = c_uint64(0) - res = self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_GetFabricId( self.devCtrl, pointer(fabricid)) - ) + ).raise_on_error() - if res == 0: - return fabricid.value - else: - raise self._ChipStack.ErrorToException(res) + return fabricid.value def GetNodeIdInternal(self) -> int: """Get the node ID from the object. Only used to validate cached value from property.""" @@ -798,15 +762,12 @@ def GetNodeIdInternal(self) -> int: nodeid = c_uint64(0) - res = self._ChipStack.Call( + self._ChipStack.Call( lambda: self._dmLib.pychip_DeviceController_GetNodeId( self.devCtrl, pointer(nodeid)) - ) + ).raise_on_error() - if res == 0: - return nodeid.value - else: - raise self._ChipStack.ErrorToException(res) + return nodeid.value def GetClusterHandler(self): self.CheckIsActive() @@ -834,14 +795,12 @@ def DeviceAvailableCallback(device, err): if allowPASE: res = self._ChipStack.Call(lambda: self._dmLib.pychip_GetDeviceBeingCommissioned( self.devCtrl, nodeid, byref(returnDevice)), timeoutMs) - if res == 0: + if res.is_success: print('Using PASE connection') return DeviceProxyWrapper(returnDevice) - res = self._ChipStack.Call(lambda: self._dmLib.pychip_GetConnectedDeviceByNodeId( - self.devCtrl, nodeid, DeviceAvailableCallback), timeoutMs) - if res != 0: - raise self._ChipStack.ErrorToException(res) + self._ChipStack.Call(lambda: self._dmLib.pychip_GetConnectedDeviceByNodeId( + self.devCtrl, nodeid, DeviceAvailableCallback), timeoutMs).raise_on_error() # The callback might have been received synchronously (during self._ChipStack.Call()). # Check if the device is already set before waiting for the callback. @@ -856,7 +815,7 @@ def DeviceAvailableCallback(device, err): raise TimeoutError("Timed out waiting for DNS-SD resolution") if returnDevice.value is None: - raise self._ChipStack.ErrorToException(returnErr) + returnErr.raise_on_error() return DeviceProxyWrapper(returnDevice, self._dmLib) @@ -889,14 +848,12 @@ async def SendCommand(self, nodeid: int, endpoint: int, payload: ClusterObjects. future = eventLoop.create_future() device = self.GetConnectedDeviceSync(nodeid, timeoutMs=interactionTimeoutMs) - res = ClusterCommand.SendCommand( + ClusterCommand.SendCommand( future, eventLoop, responseType, device.deviceProxy, ClusterCommand.CommandPath( EndpointId=endpoint, ClusterId=payload.cluster_id, CommandId=payload.command_id, - ), payload, timedRequestTimeoutMs=timedRequestTimeoutMs, interactionTimeoutMs=interactionTimeoutMs) - if res != 0: - future.set_exception(self._ChipStack.ErrorToException(res)) + ), payload, timedRequestTimeoutMs=timedRequestTimeoutMs, interactionTimeoutMs=interactionTimeoutMs).raise_on_error() return await future async def WriteAttribute(self, nodeid: int, attributes: typing.List[typing.Tuple[int, ClusterObjects.ClusterAttributeDescriptor, int]], timedRequestTimeoutMs: int = None, interactionTimeoutMs: int = None): @@ -928,10 +885,8 @@ async def WriteAttribute(self, nodeid: int, attributes: typing.List[typing.Tuple attrs.append(ClusterAttribute.AttributeWriteRequest( v[0], v[1], v[2], 1, v[1].value)) - res = ClusterAttribute.WriteAttributes( - future, eventLoop, device.deviceProxy, attrs, timedRequestTimeoutMs=timedRequestTimeoutMs, interactionTimeoutMs=interactionTimeoutMs) - if res != 0: - raise self._ChipStack.ErrorToException(res) + ClusterAttribute.WriteAttributes( + future, eventLoop, device.deviceProxy, attrs, timedRequestTimeoutMs=timedRequestTimeoutMs, interactionTimeoutMs=interactionTimeoutMs).raise_on_error() return await future def _parseAttributePathTuple(self, pathTuple: typing.Union[ @@ -1110,10 +1065,8 @@ async def Read(self, nodeid: int, attributes: typing.List[typing.Union[ eventPaths = [self._parseEventPathTuple( v) for v in events] if events else None - res = ClusterAttribute.Read(future=future, eventLoop=eventLoop, device=device.deviceProxy, devCtrl=self, attributes=attributePaths, dataVersionFilters=clusterDataVersionFilters, events=eventPaths, returnClusterObject=returnClusterObject, - subscriptionParameters=ClusterAttribute.SubscriptionParameters(reportInterval[0], reportInterval[1]) if reportInterval else None, fabricFiltered=fabricFiltered, keepSubscriptions=keepSubscriptions) - if res != 0: - raise self._ChipStack.ErrorToException(res) + ClusterAttribute.Read(future=future, eventLoop=eventLoop, device=device.deviceProxy, devCtrl=self, attributes=attributePaths, dataVersionFilters=clusterDataVersionFilters, events=eventPaths, returnClusterObject=returnClusterObject, + subscriptionParameters=ClusterAttribute.SubscriptionParameters(reportInterval[0], reportInterval[1]) if reportInterval else None, fabricFiltered=fabricFiltered, keepSubscriptions=keepSubscriptions).raise_on_error() return await future async def ReadAttribute(self, nodeid: int, attributes: typing.List[typing.Union[ @@ -1302,60 +1255,61 @@ def _InitLib(self): self._dmLib.pychip_DeviceController_DeleteDeviceController.argtypes = [ c_void_p] - self._dmLib.pychip_DeviceController_DeleteDeviceController.restype = c_uint32 + self._dmLib.pychip_DeviceController_DeleteDeviceController.restype = PyChipError self._dmLib.pychip_DeviceController_ConnectBLE.argtypes = [ c_void_p, c_uint16, c_uint32, c_uint64] - self._dmLib.pychip_DeviceController_ConnectBLE.restype = c_uint32 + self._dmLib.pychip_DeviceController_ConnectBLE.restype = PyChipError self._dmLib.pychip_DeviceController_ConnectIP.argtypes = [ c_void_p, c_char_p, c_uint32, c_uint64] self._dmLib.pychip_DeviceController_SetThreadOperationalDataset.argtypes = [ c_char_p, c_uint32] - self._dmLib.pychip_DeviceController_SetThreadOperationalDataset.restype = c_uint32 + self._dmLib.pychip_DeviceController_SetThreadOperationalDataset.restype = PyChipError self._dmLib.pychip_DeviceController_SetWiFiCredentials.argtypes = [ c_char_p, c_char_p] - self._dmLib.pychip_DeviceController_SetWiFiCredentials.restype = c_uint32 + self._dmLib.pychip_DeviceController_SetWiFiCredentials.restype = PyChipError self._dmLib.pychip_DeviceController_Commission.argtypes = [ c_void_p, c_uint64] - self._dmLib.pychip_DeviceController_Commission.restype = c_uint32 + self._dmLib.pychip_DeviceController_Commission.restype = PyChipError self._dmLib.pychip_DeviceController_OnNetworkCommission.argtypes = [c_void_p, c_uint64, c_uint32, c_uint8, c_char_p] - self._dmLib.pychip_DeviceController_OnNetworkCommission.restype = c_uint32 + self._dmLib.pychip_DeviceController_OnNetworkCommission.restype = PyChipError - self._dmLib.pychip_DeviceController_DiscoverAllCommissionableNodes.argtypes = [ + self._dmLib.pychip_DeviceController_DiscoverCommissionableNodes.argtypes = [ c_void_p, c_uint8, c_char_p] - self._dmLib.pychip_DeviceController_DiscoverAllCommissionableNodes.restype = c_uint32 + self._dmLib.pychip_DeviceController_DiscoverCommissionableNodes.restype = PyChipError self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesLongDiscriminator.argtypes = [ c_void_p, c_uint16] - self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesLongDiscriminator.restype = c_uint32 + self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesLongDiscriminator.restype = PyChipError self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesShortDiscriminator.argtypes = [ c_void_p, c_uint16] - self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesShortDiscriminator.restype = c_uint32 + self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesShortDiscriminator.restype = PyChipError self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesVendor.argtypes = [ c_void_p, c_uint16] - self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesVendor.restype = c_uint32 + self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesVendor.restype = PyChipError self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesDeviceType.argtypes = [ c_void_p, c_uint16] - self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesDeviceType.restype = c_uint32 + self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesDeviceType.restype = PyChipError self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesCommissioningEnabled.argtypes = [ c_void_p] - self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesCommissioningEnabled.restype = c_uint32 + self._dmLib.pychip_DeviceController_DiscoverCommissionableNodesCommissioningEnabled.restype = PyChipError self._dmLib.pychip_DeviceController_EstablishPASESessionIP.argtypes = [ c_void_p, c_char_p, c_uint32, c_uint64] - self._dmLib.pychip_DeviceController_EstablishPASESessionIP.restype = c_uint32 + self._dmLib.pychip_DeviceController_EstablishPASESessionIP.restype = PyChipError self._dmLib.pychip_DeviceController_DiscoverAllCommissionableNodes.argtypes = [ c_void_p] + self._dmLib.pychip_DeviceController_DiscoverAllCommissionableNodes.restype = PyChipError self._dmLib.pychip_DeviceController_PrintDiscoveredDevices.argtypes = [ c_void_p] self._dmLib.pychip_DeviceController_PrintDiscoveredDevices.argtypes = [ @@ -1369,65 +1323,67 @@ def _InitLib(self): self._dmLib.pychip_DeviceController_ConnectIP.argtypes = [ c_void_p, c_char_p, c_uint32, c_uint64] - self._dmLib.pychip_DeviceController_ConnectIP.restype = c_uint32 + self._dmLib.pychip_DeviceController_ConnectIP.restype = PyChipError self._dmLib.pychip_DeviceController_ConnectWithCode.argtypes = [ c_void_p, c_char_p, c_uint64] - self._dmLib.pychip_DeviceController_ConnectWithCode.restype = c_uint32 + self._dmLib.pychip_DeviceController_ConnectWithCode.restype = PyChipError self._dmLib.pychip_DeviceController_CloseSession.argtypes = [ c_void_p, c_uint64] - self._dmLib.pychip_DeviceController_CloseSession.restype = c_uint32 + self._dmLib.pychip_DeviceController_CloseSession.restype = PyChipError self._dmLib.pychip_DeviceController_GetAddressAndPort.argtypes = [ c_void_p, c_uint64, c_char_p, c_uint64, POINTER(c_uint16)] - self._dmLib.pychip_DeviceController_GetAddressAndPort.restype = c_uint32 + self._dmLib.pychip_DeviceController_GetAddressAndPort.restype = PyChipError self._dmLib.pychip_ScriptDevicePairingDelegate_SetKeyExchangeCallback.argtypes = [ c_void_p, _DevicePairingDelegate_OnPairingCompleteFunct] - self._dmLib.pychip_ScriptDevicePairingDelegate_SetKeyExchangeCallback.restype = c_uint32 + self._dmLib.pychip_ScriptDevicePairingDelegate_SetKeyExchangeCallback.restype = PyChipError self._dmLib.pychip_ScriptDevicePairingDelegate_SetCommissioningCompleteCallback.argtypes = [ c_void_p, _DevicePairingDelegate_OnCommissioningCompleteFunct] - self._dmLib.pychip_ScriptDevicePairingDelegate_SetCommissioningCompleteCallback.restype = c_uint32 + self._dmLib.pychip_ScriptDevicePairingDelegate_SetCommissioningCompleteCallback.restype = PyChipError self._dmLib.pychip_ScriptDevicePairingDelegate_SetCommissioningStatusUpdateCallback.argtypes = [ c_void_p, _DevicePairingDelegate_OnCommissioningStatusUpdateFunct] - self._dmLib.pychip_ScriptDevicePairingDelegate_SetCommissioningCompleteCallback.restype = c_uint32 + self._dmLib.pychip_ScriptDevicePairingDelegate_SetCommissioningCompleteCallback.restype = PyChipError self._dmLib.pychip_GetConnectedDeviceByNodeId.argtypes = [ c_void_p, c_uint64, _DeviceAvailableFunct] - self._dmLib.pychip_GetConnectedDeviceByNodeId.restype = c_uint32 + self._dmLib.pychip_GetConnectedDeviceByNodeId.restype = PyChipError self._dmLib.pychip_FreeOperationalDeviceProxy.argtypes = [ c_void_p] - self._dmLib.pychip_FreeOperationalDeviceProxy.restype = c_uint32 + self._dmLib.pychip_FreeOperationalDeviceProxy.restype = PyChipError self._dmLib.pychip_GetDeviceBeingCommissioned.argtypes = [ c_void_p, c_uint64, c_void_p] - self._dmLib.pychip_GetDeviceBeingCommissioned.restype = c_uint32 + self._dmLib.pychip_GetDeviceBeingCommissioned.restype = PyChipError self._dmLib.pychip_ExpireSessions.argtypes = [c_void_p, c_uint64] - self._dmLib.pychip_ExpireSessions.restype = c_uint32 + self._dmLib.pychip_ExpireSessions.restype = PyChipError self._dmLib.pychip_DeviceCommissioner_CloseBleConnection.argtypes = [ c_void_p] - self._dmLib.pychip_DeviceCommissioner_CloseBleConnection.restype = c_uint32 + self._dmLib.pychip_DeviceCommissioner_CloseBleConnection.restype = PyChipError self._dmLib.pychip_GetCommandSenderHandle.argtypes = [c_void_p] self._dmLib.pychip_GetCommandSenderHandle.restype = c_uint64 self._dmLib.pychip_DeviceController_GetCompressedFabricId.argtypes = [ c_void_p, POINTER(c_uint64)] - self._dmLib.pychip_DeviceController_GetCompressedFabricId.restype = c_uint32 + self._dmLib.pychip_DeviceController_GetCompressedFabricId.restype = PyChipError self._dmLib.pychip_DeviceController_OpenCommissioningWindow.argtypes = [ c_void_p, c_uint64, c_uint16, c_uint32, c_uint16, c_uint8] - self._dmLib.pychip_DeviceController_OpenCommissioningWindow.restype = c_uint32 + self._dmLib.pychip_DeviceController_OpenCommissioningWindow.restype = PyChipError self._dmLib.pychip_TestCommissionerUsed.argtypes = [] self._dmLib.pychip_TestCommissionerUsed.restype = c_bool self._dmLib.pychip_TestCommissioningCallbacks.argtypes = [] + self._dmLib.pychip_TestCommissioningCallbacks.restype = c_bool + self._dmLib.pychip_ResetCommissioningTests.argtypes = [] self._dmLib.pychip_TestPaseConnection.argtypes = [c_uint64] @@ -1441,8 +1397,17 @@ def _InitLib(self): self._dmLib.pychip_DeviceController_IssueNOCChain.argtypes = [ c_void_p, py_object, c_char_p, c_size_t, c_uint64 ] - self._dmLib.pychip_DeviceController_IssueNOCChain.restype = c_uint32 + self._dmLib.pychip_DeviceController_IssueNOCChain.restype = PyChipError self._dmLib.pychip_DeviceController_SetIssueNOCChainCallbackPythonCallback.argtypes = [ _IssueNOCChainCallbackPythonCallbackFunct] self._dmLib.pychip_DeviceController_SetIssueNOCChainCallbackPythonCallback.restype = None + + self._dmLib.pychip_DeviceController_GetNodeId.argtypes = [c_void_p, POINTER(c_uint64)] + self._dmLib.pychip_DeviceController_GetNodeId.restype = PyChipError + + self._dmLib.pychip_DeviceController_GetFabricId.argtypes = [c_void_p, POINTER(c_uint64)] + self._dmLib.pychip_DeviceController_GetFabricId.restype = PyChipError + + self._dmLib.pychip_DeviceController_GetLogFilter = [None] + self._dmLib.pychip_DeviceController_GetLogFilter = c_uint8 diff --git a/src/controller/python/chip/ChipStack.py b/src/controller/python/chip/ChipStack.py index 77d36b39d511c0..3ca313be08214d 100644 --- a/src/controller/python/chip/ChipStack.py +++ b/src/controller/python/chip/ChipStack.py @@ -47,6 +47,7 @@ from .clusters.CHIPClusters import * import chip.native +from chip.native import PyChipError __all__ = [ "DeviceStatusStruct", @@ -269,8 +270,7 @@ def HandleChipThreadRun(callback): # Initialize the chip stack. res = self._ChipStackLib.pychip_DeviceController_StackInit( self._persistentStorage.GetSdkStorageObject(), enableServerInteractions) - if res != 0: - raise self.ErrorToException(res) + res.raise_on_error() im.InitIMDelegate() ClusterAttribute.Init() @@ -328,7 +328,7 @@ def setLogFunct(self, logFunct): self._ChipStackLib.pychip_Stack_SetLogFunct(logFunct) def Shutdown(self): - self.Call(lambda: self._ChipStackLib.pychip_DeviceController_StackShutdown()) + self.Call(lambda: self._ChipStackLib.pychip_DeviceController_StackShutdown()).raise_on_error() # # We only shutdown the persistent storage layer AFTER we've shut down the stack, @@ -377,9 +377,9 @@ def CallAsync(self, callFunct): with self.networkLock: res = self.PostTaskOnChipThread(callFunct).Wait() - if res != 0: + if not res.is_success: self.completeEvent.set() - raise self.ErrorToException(res) + raise res.to_exception() while not self.completeEvent.isSet(): if self.blockingCB: self.blockingCB() @@ -398,9 +398,9 @@ def PostTaskOnChipThread(self, callFunct) -> AsyncCallableHandle: pythonapi.Py_IncRef(py_object(callObj)) res = self._ChipStackLib.pychip_DeviceController_PostTaskOnChipThread( self.cbHandleChipThreadRun, py_object(callObj)) - if res != 0: + if not res.is_success: pythonapi.Py_DecRef(py_object(callObj)) - raise self.ErrorToException(res) + raise res.to_exception() return callObj def ErrorToException(self, err, devStatusPtr=None): @@ -450,9 +450,9 @@ def _loadLib(self): self._chipDLLPath = chip.native.FindNativeLibraryPath() self._ChipStackLib.pychip_DeviceController_StackInit.argtypes = [c_void_p, c_bool] - self._ChipStackLib.pychip_DeviceController_StackInit.restype = c_uint32 + self._ChipStackLib.pychip_DeviceController_StackInit.restype = PyChipError self._ChipStackLib.pychip_DeviceController_StackShutdown.argtypes = [] - self._ChipStackLib.pychip_DeviceController_StackShutdown.restype = c_uint32 + self._ChipStackLib.pychip_DeviceController_StackShutdown.restype = PyChipError self._ChipStackLib.pychip_Stack_StatusReportToString.argtypes = [ c_uint32, c_uint16, @@ -462,8 +462,8 @@ def _loadLib(self): self._ChipStackLib.pychip_Stack_ErrorToString.restype = c_char_p self._ChipStackLib.pychip_Stack_SetLogFunct.argtypes = [ _LogMessageFunct] - self._ChipStackLib.pychip_Stack_SetLogFunct.restype = c_uint32 + self._ChipStackLib.pychip_Stack_SetLogFunct.restype = PyChipError self._ChipStackLib.pychip_DeviceController_PostTaskOnChipThread.argtypes = [ _ChipThreadTaskRunnerFunct, py_object] - self._ChipStackLib.pychip_DeviceController_PostTaskOnChipThread.restype = c_uint32 + self._ChipStackLib.pychip_DeviceController_PostTaskOnChipThread.restype = PyChipError diff --git a/src/controller/python/chip/clusters/Attribute.py b/src/controller/python/chip/clusters/Attribute.py index 0fa3530d36ab41..d7608f8d3c53a9 100644 --- a/src/controller/python/chip/clusters/Attribute.py +++ b/src/controller/python/chip/clusters/Attribute.py @@ -31,6 +31,7 @@ import chip.exceptions import chip.interaction_model import chip.tlv +from chip.native import PyChipError from enum import Enum, unique import inspect import sys @@ -708,8 +709,8 @@ def handleEventData(self, header: EventHeader, path: EventPath, data: bytes, sta except Exception as ex: logging.exception(ex) - def handleError(self, chipError: int): - self._resultError = chipError + def handleError(self, chipError: PyChipError): + self._resultError = chipError.code def _handleSubscriptionEstablished(self, subscriptionId): if not self._future.done(): @@ -729,13 +730,13 @@ def handleSubscriptionEstablished(self, subscriptionId): self._event_loop.call_soon_threadsafe( self._handleSubscriptionEstablished, subscriptionId) - def handleResubscriptionAttempted(self, terminationCause: int, nextResubscribeIntervalMsec: int): + def handleResubscriptionAttempted(self, terminationCause: PyChipError, nextResubscribeIntervalMsec: int): if (self._subscription_handler._onResubscriptionAttemptedCb_isAsync): self._event_loop.create_task(self._subscription_handler._onResubscriptionAttemptedCb( - self._subscription_handler, terminationCause, nextResubscribeIntervalMsec)) + self._subscription_handler, terminationCause.code, nextResubscribeIntervalMsec)) else: self._event_loop.call_soon_threadsafe( - self._subscription_handler._onResubscriptionAttemptedCb, self._subscription_handler, terminationCause, nextResubscribeIntervalMsec) + self._subscription_handler._onResubscriptionAttemptedCb, self._subscription_handler, terminationCause.code, nextResubscribeIntervalMsec) def _handleReportBegin(self): pass @@ -800,7 +801,7 @@ def handleResponse(self, path: AttributePath, status: int): except: self._resultData.append(AttributeWriteResult(Path=path, Status=status)) - def handleError(self, chipError: int): + def handleError(self, chipError: PyChipError): self._resultError = chipError def _handleDone(self): @@ -810,7 +811,7 @@ def _handleDone(self): # move on, possibly invalidating the provided _event_loop. # if self._resultError is not None: - self._future.set_exception(chip.exceptions.ChipStackError(self._resultError)) + self._future.set_exception(self._resultError.to_exception()) else: self._future.set_result(self._resultData) @@ -828,11 +829,11 @@ def handleDone(self): _OnReadAttributeDataCallbackFunct = CFUNCTYPE( None, py_object, c_uint32, c_uint16, c_uint32, c_uint32, c_uint8, c_void_p, c_size_t) _OnSubscriptionEstablishedCallbackFunct = CFUNCTYPE(None, py_object, c_uint32) -_OnResubscriptionAttemptedCallbackFunct = CFUNCTYPE(None, py_object, c_uint32, c_uint32) +_OnResubscriptionAttemptedCallbackFunct = CFUNCTYPE(None, py_object, PyChipError, c_uint32) _OnReadEventDataCallbackFunct = CFUNCTYPE( None, py_object, c_uint16, c_uint32, c_uint32, c_uint64, c_uint8, c_uint64, c_uint8, c_void_p, c_size_t, c_uint8) _OnReadErrorCallbackFunct = CFUNCTYPE( - None, py_object, c_uint32) + None, py_object, PyChipError) _OnReadDoneCallbackFunct = CFUNCTYPE( None, py_object) _OnReportBeginCallbackFunct = CFUNCTYPE( @@ -862,12 +863,12 @@ def _OnSubscriptionEstablishedCallback(closure, subscriptionId): @_OnResubscriptionAttemptedCallbackFunct -def _OnResubscriptionAttemptedCallback(closure, terminationCause: int, nextResubscribeIntervalMsec: int): +def _OnResubscriptionAttemptedCallback(closure, terminationCause: PyChipError, nextResubscribeIntervalMsec: int): closure.handleResubscriptionAttempted(terminationCause, nextResubscribeIntervalMsec) @_OnReadErrorCallbackFunct -def _OnReadErrorCallback(closure, chiperror: int): +def _OnReadErrorCallback(closure, chiperror: PyChipError): closure.handleError(chiperror) @@ -889,7 +890,7 @@ def _OnReadDoneCallback(closure): _OnWriteResponseCallbackFunct = CFUNCTYPE( None, py_object, c_uint16, c_uint32, c_uint32, c_uint16) _OnWriteErrorCallbackFunct = CFUNCTYPE( - None, py_object, c_uint32) + None, py_object, PyChipError) _OnWriteDoneCallbackFunct = CFUNCTYPE( None, py_object) @@ -901,7 +902,7 @@ def _OnWriteResponseCallback(closure, endpoint: int, cluster: int, attribute: in @_OnWriteErrorCallbackFunct -def _OnWriteErrorCallback(closure, chiperror: int): +def _OnWriteErrorCallback(closure, chiperror: PyChipError): closure.handleError(chiperror) @@ -910,7 +911,7 @@ def _OnWriteDoneCallback(closure): closure.handleDone() -def WriteAttributes(future: Future, eventLoop, device, attributes: List[AttributeWriteRequest], timedRequestTimeoutMs: int = None, interactionTimeoutMs: int = None) -> int: +def WriteAttributes(future: Future, eventLoop, device, attributes: List[AttributeWriteRequest], timedRequestTimeoutMs: int = None, interactionTimeoutMs: int = None) -> PyChipError: handle = chip.native.GetLibraryHandle() writeargs = [] @@ -936,7 +937,7 @@ def WriteAttributes(future: Future, eventLoop, device, attributes: List[Attribut res = builtins.chipStack.Call( lambda: handle.pychip_WriteClient_WriteAttributes( ctypes.py_object(transaction), device, ctypes.c_uint16(0 if timedRequestTimeoutMs is None else timedRequestTimeoutMs), ctypes.c_uint16(0 if interactionTimeoutMs is None else interactionTimeoutMs), ctypes.c_size_t(len(attributes)), *writeargs)) - if res != 0: + if not res.is_success: ctypes.pythonapi.Py_DecRef(ctypes.py_object(transaction)) return res @@ -951,7 +952,7 @@ def WriteAttributes(future: Future, eventLoop, device, attributes: List[Attribut ) -def Read(future: Future, eventLoop, device, devCtrl, attributes: List[AttributePath] = None, dataVersionFilters: List[DataVersionFilter] = None, events: List[EventPath] = None, returnClusterObject: bool = True, subscriptionParameters: SubscriptionParameters = None, fabricFiltered: bool = True, keepSubscriptions: bool = False) -> int: +def Read(future: Future, eventLoop, device, devCtrl, attributes: List[AttributePath] = None, dataVersionFilters: List[DataVersionFilter] = None, events: List[EventPath] = None, returnClusterObject: bool = True, subscriptionParameters: SubscriptionParameters = None, fabricFiltered: bool = True, keepSubscriptions: bool = False) -> PyChipError: if (not attributes) and dataVersionFilters: raise ValueError( "Must provide valid attribute list when data version filters is not null") @@ -1047,7 +1048,7 @@ def Read(future: Future, eventLoop, device, devCtrl, attributes: List[AttributeP transaction.SetClientObjPointers(readClientObj, readCallbackObj) - if res != 0: + if not res.is_success: ctypes.pythonapi.Py_DecRef(ctypes.py_object(transaction)) return res @@ -1068,10 +1069,10 @@ def Init(): if not handle.pychip_WriteClient_InitCallbacks.argtypes: setter = chip.native.NativeLibraryHandleMethodArguments(handle) - handle.pychip_WriteClient_WriteAttributes.restype = c_uint32 + handle.pychip_WriteClient_WriteAttributes.restype = PyChipError setter.Set('pychip_WriteClient_InitCallbacks', None, [ _OnWriteResponseCallbackFunct, _OnWriteErrorCallbackFunct, _OnWriteDoneCallbackFunct]) - handle.pychip_ReadClient_Read.restype = c_uint32 + handle.pychip_ReadClient_Read.restype = PyChipError setter.Set('pychip_ReadClient_InitCallbacks', None, [ _OnReadAttributeDataCallbackFunct, _OnReadEventDataCallbackFunct, _OnSubscriptionEstablishedCallbackFunct, _OnResubscriptionAttemptedCallbackFunct, _OnReadErrorCallbackFunct, _OnReadDoneCallbackFunct, _OnReportBeginCallbackFunct, _OnReportEndCallbackFunct]) diff --git a/src/controller/python/chip/clusters/Command.py b/src/controller/python/chip/clusters/Command.py index 74101d4edb47cf..83026866e1b0e7 100644 --- a/src/controller/python/chip/clusters/Command.py +++ b/src/controller/python/chip/clusters/Command.py @@ -26,6 +26,7 @@ from .ClusterObjects import ClusterCommand import chip.exceptions import chip.interaction_model +from chip.native import PyChipError import inspect import sys @@ -99,12 +100,11 @@ def handleResponse(self, path: CommandPath, status: Status, response: bytes): self._event_loop.call_soon_threadsafe( self._handleResponse, path, status, response) - def _handleError(self, imError: Status, chipError: int, exception: Exception): + def _handleError(self, imError: Status, chipError: PyChipError, exception: Exception): if exception: self._future.set_exception(exception) elif chipError != 0: - self._future.set_exception( - chip.exceptions.ChipStackError(chipError)) + self._future.set_exception(chipError.to_exception()) else: try: self._future.set_exception( @@ -114,7 +114,7 @@ def _handleError(self, imError: Status, chipError: int, exception: Exception): self._future.set_exception(chip.interaction_model.InteractionModelError( chip.interaction_model.Status.Failure)) - def handleError(self, status: Status, chipError: int): + def handleError(self, status: Status, chipError: PyChipError): self._event_loop.call_soon_threadsafe( self._handleError, status, chipError, None ) @@ -123,7 +123,7 @@ def handleError(self, status: Status, chipError: int): _OnCommandSenderResponseCallbackFunct = CFUNCTYPE( None, py_object, c_uint16, c_uint32, c_uint32, c_uint16, c_uint8, c_void_p, c_uint32) _OnCommandSenderErrorCallbackFunct = CFUNCTYPE( - None, py_object, c_uint16, c_uint8, c_uint32) + None, py_object, c_uint16, c_uint8, PyChipError) _OnCommandSenderDoneCallbackFunct = CFUNCTYPE( None, py_object) @@ -136,7 +136,7 @@ def _OnCommandSenderResponseCallback(closure, endpoint: int, cluster: int, comma @_OnCommandSenderErrorCallbackFunct -def _OnCommandSenderErrorCallback(closure, imStatus: int, clusterStatus: int, chiperror: int): +def _OnCommandSenderErrorCallback(closure, imStatus: int, clusterStatus: int, chiperror: PyChipError): closure.handleError(Status(imStatus, clusterStatus), chiperror) @@ -145,7 +145,7 @@ def _OnCommandSenderDoneCallback(closure): ctypes.pythonapi.Py_DecRef(ctypes.py_object(closure)) -def SendCommand(future: Future, eventLoop, responseType: Type, device, commandPath: CommandPath, payload: ClusterCommand, timedRequestTimeoutMs: int = None, interactionTimeoutMs: int = None) -> int: +def SendCommand(future: Future, eventLoop, responseType: Type, device, commandPath: CommandPath, payload: ClusterCommand, timedRequestTimeoutMs: int = None, interactionTimeoutMs: int = None) -> PyChipError: ''' Send a cluster-object encapsulated command to a device and does the following: - On receipt of a successful data response, returns the cluster-object equivalent through the provided future. - None (on a successful response containing no data) @@ -183,7 +183,7 @@ def Init(): setter = chip.native.NativeLibraryHandleMethodArguments(handle) setter.Set('pychip_CommandSender_SendCommand', - c_uint32, [py_object, c_void_p, c_uint16, c_uint32, c_uint32, c_char_p, c_size_t, c_uint16]) + PyChipError, [py_object, c_void_p, c_uint16, c_uint32, c_uint32, c_char_p, c_size_t, c_uint16]) setter.Set('pychip_CommandSender_InitCallbacks', None, [ _OnCommandSenderResponseCallbackFunct, _OnCommandSenderErrorCallbackFunct, _OnCommandSenderDoneCallbackFunct]) diff --git a/src/controller/python/chip/clusters/attribute.cpp b/src/controller/python/chip/clusters/attribute.cpp index 0c90495ae4bf00..b847a200df315b 100644 --- a/src/controller/python/chip/clusters/attribute.cpp +++ b/src/controller/python/chip/clusters/attribute.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include @@ -74,9 +75,9 @@ using OnReadEventDataCallback = void (*)(PyObject * appContext, chip:: uint8_t timestampType, uint8_t * data, uint32_t dataLen, std::underlying_type_t imstatus); using OnSubscriptionEstablishedCallback = void (*)(PyObject * appContext, SubscriptionId subscriptionId); -using OnResubscriptionAttemptedCallback = void (*)(PyObject * appContext, uint32_t aTerminationCause, +using OnResubscriptionAttemptedCallback = void (*)(PyObject * appContext, PyChipError aTerminationCause, uint32_t aNextResubscribeIntervalMsec); -using OnReadErrorCallback = void (*)(PyObject * appContext, uint32_t chiperror); +using OnReadErrorCallback = void (*)(PyObject * appContext, PyChipError chiperror); using OnReadDoneCallback = void (*)(PyObject * appContext); using OnReportBeginCallback = void (*)(PyObject * appContext); using OnReportEndCallback = void (*)(PyObject * appContext); @@ -148,7 +149,7 @@ class ReadClientCallback : public ReadClient::Callback CHIP_ERROR OnResubscriptionNeeded(ReadClient * apReadClient, CHIP_ERROR aTerminationCause) override { ReturnErrorOnFailure(ReadClient::Callback::OnResubscriptionNeeded(apReadClient, aTerminationCause)); - gOnResubscriptionAttemptedCallback(mAppContext, aTerminationCause.AsInteger(), + gOnResubscriptionAttemptedCallback(mAppContext, ToPyChipError(aTerminationCause), apReadClient->ComputeTimeTillNextSubscription()); return CHIP_NO_ERROR; } @@ -192,7 +193,7 @@ class ReadClientCallback : public ReadClient::Callback to_underlying(apStatus == nullptr ? Protocols::InteractionModel::Status::Success : apStatus->mStatus)); } - void OnError(CHIP_ERROR aError) override { gOnReadErrorCallback(mAppContext, aError.AsInteger()); } + void OnError(CHIP_ERROR aError) override { gOnReadErrorCallback(mAppContext, ToPyChipError(aError)); } void OnReportBegin() override { gOnReportBeginCallback(mAppContext); } void OnDeallocatePaths(chip::app::ReadPrepareParams && aReadPrepareParams) override @@ -244,18 +245,16 @@ struct __attribute__((packed)) PyReadAttributeParams }; // Encodes n attribute write requests, follows 3 * n arguments, in the (AttributeWritePath*=void *, uint8_t*, size_t) order. -chip::ChipError::StorageType pychip_WriteClient_WriteAttributes(void * appContext, DeviceProxy * device, - uint16_t timedWriteTimeoutMs, uint16_t interactionTimeoutMs, - size_t n, ...); -chip::ChipError::StorageType pychip_ReadClient_ReadAttributes(void * appContext, ReadClient ** pReadClient, - ReadClientCallback ** pCallback, DeviceProxy * device, - uint8_t * readParamsBuf, size_t n, size_t total, ...); +PyChipError pychip_WriteClient_WriteAttributes(void * appContext, DeviceProxy * device, uint16_t timedWriteTimeoutMs, + uint16_t interactionTimeoutMs, size_t n, ...); +PyChipError pychip_ReadClient_ReadAttributes(void * appContext, ReadClient ** pReadClient, ReadClientCallback ** pCallback, + DeviceProxy * device, uint8_t * readParamsBuf, size_t n, size_t total, ...); } using OnWriteResponseCallback = void (*)(PyObject * appContext, chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, std::underlying_type_t imstatus); -using OnWriteErrorCallback = void (*)(PyObject * appContext, uint32_t chiperror); +using OnWriteErrorCallback = void (*)(PyObject * appContext, PyChipError chiperror); using OnWriteDoneCallback = void (*)(PyObject * appContext); OnWriteResponseCallback gOnWriteResponseCallback = nullptr; @@ -277,7 +276,7 @@ class WriteClientCallback : public WriteClient::Callback void OnError(const WriteClient * apWriteClient, CHIP_ERROR aProtocolError) override { - gOnWriteErrorCallback(mAppContext, aProtocolError.AsInteger()); + gOnWriteErrorCallback(mAppContext, ToPyChipError(aProtocolError)); } void OnDone(WriteClient * apWriteClient) override @@ -323,9 +322,8 @@ void pychip_ReadClient_InitCallbacks(OnReadAttributeDataCallback onReadAttribute gOnReportEndCallback = onReportEndCallback; } -chip::ChipError::StorageType pychip_WriteClient_WriteAttributes(void * appContext, DeviceProxy * device, - uint16_t timedWriteTimeoutMs, uint16_t interactionTimeoutMs, - size_t n, ...) +PyChipError pychip_WriteClient_WriteAttributes(void * appContext, DeviceProxy * device, uint16_t timedWriteTimeoutMs, + uint16_t interactionTimeoutMs, size_t n, ...) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -374,7 +372,7 @@ chip::ChipError::StorageType pychip_WriteClient_WriteAttributes(void * appContex exit: va_end(args); - return err.AsInteger(); + return ToPyChipError(err); } void pychip_ReadClient_Abort(ReadClient * apReadClient, ReadClientCallback * apCallback) @@ -391,9 +389,9 @@ void pychip_ReadClient_OverrideLivenessTimeout(ReadClient * pReadClient, uint32_ pReadClient->OverrideLivenessTimeout(System::Clock::Milliseconds32(livenessTimeoutMs)); } -chip::ChipError::StorageType pychip_ReadClient_Read(void * appContext, ReadClient ** pReadClient, ReadClientCallback ** pCallback, - DeviceProxy * device, uint8_t * readParamsBuf, size_t numAttributePaths, - size_t numDataversionFilters, size_t numEventPaths, ...) +PyChipError pychip_ReadClient_Read(void * appContext, ReadClient ** pReadClient, ReadClientCallback ** pCallback, + DeviceProxy * device, uint8_t * readParamsBuf, size_t numAttributePaths, + size_t numDataversionFilters, size_t numEventPaths, ...) { CHIP_ERROR err = CHIP_NO_ERROR; PyReadAttributeParams pyParams = {}; @@ -496,6 +494,6 @@ chip::ChipError::StorageType pychip_ReadClient_Read(void * appContext, ReadClien exit: va_end(args); - return err.AsInteger(); + return ToPyChipError(err); } } diff --git a/src/controller/python/chip/clusters/command.cpp b/src/controller/python/chip/clusters/command.cpp index 342e624698ed18..9c4686b9000317 100644 --- a/src/controller/python/chip/clusters/command.cpp +++ b/src/controller/python/chip/clusters/command.cpp @@ -23,6 +23,7 @@ #include #include +#include #include #include @@ -32,11 +33,9 @@ using namespace chip::app; using PyObject = void *; extern "C" { -chip::ChipError::StorageType pychip_CommandSender_SendCommand(void * appContext, DeviceProxy * device, - uint16_t timedRequestTimeoutMs, chip::EndpointId endpointId, - chip::ClusterId clusterId, chip::CommandId commandId, - const uint8_t * payload, size_t length, - uint16_t interactionTimeoutMs); +PyChipError pychip_CommandSender_SendCommand(void * appContext, DeviceProxy * device, uint16_t timedRequestTimeoutMs, + chip::EndpointId endpointId, chip::ClusterId clusterId, chip::CommandId commandId, + const uint8_t * payload, size_t length, uint16_t interactionTimeoutMs); } namespace chip { @@ -48,7 +47,7 @@ using OnCommandSenderResponseCallback = void (*)(PyObject appContext, chip::Endp chip::ClusterStatus clusterStatus, const uint8_t * payload, uint32_t length); using OnCommandSenderErrorCallback = void (*)(PyObject appContext, std::underlying_type_t status, - chip::ClusterStatus clusterStatus, uint32_t chiperror); + chip::ClusterStatus clusterStatus, PyChipError chiperror); using OnCommandSenderDoneCallback = void (*)(PyObject appContext); OnCommandSenderResponseCallback gOnCommandSenderResponseCallback = nullptr; @@ -96,7 +95,7 @@ class CommandSenderCallback : public CommandSender::Callback // for the error code, because otherwise // the callee will think we have a stack // exception. - aProtocolError.IsIMStatus() ? 0 : aProtocolError.AsInteger()); + aProtocolError.IsIMStatus() ? ToPyChipError(CHIP_NO_ERROR) : ToPyChipError(aProtocolError)); } void OnDone(CommandSender * apCommandSender) override @@ -125,14 +124,13 @@ void pychip_CommandSender_InitCallbacks(OnCommandSenderResponseCallback onComman gOnCommandSenderDoneCallback = onCommandSenderDoneCallback; } -chip::ChipError::StorageType pychip_CommandSender_SendCommand(void * appContext, DeviceProxy * device, - uint16_t timedRequestTimeoutMs, chip::EndpointId endpointId, - chip::ClusterId clusterId, chip::CommandId commandId, - const uint8_t * payload, size_t length, uint16_t interactionTimeoutMs) +PyChipError pychip_CommandSender_SendCommand(void * appContext, DeviceProxy * device, uint16_t timedRequestTimeoutMs, + chip::EndpointId endpointId, chip::ClusterId clusterId, chip::CommandId commandId, + const uint8_t * payload, size_t length, uint16_t interactionTimeoutMs) { CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrReturnError(device->GetSecureSession().HasValue(), CHIP_ERROR_MISSING_SECURE_SESSION.AsInteger()); + VerifyOrReturnError(device->GetSecureSession().HasValue(), ToPyChipError(CHIP_ERROR_MISSING_SECURE_SESSION)); std::unique_ptr callback = std::make_unique(appContext); std::unique_ptr sender = std::make_unique(callback.get(), device->GetExchangeManager(), @@ -164,6 +162,6 @@ chip::ChipError::StorageType pychip_CommandSender_SendCommand(void * appContext, callback.release(); exit: - return err.AsInteger(); + return ToPyChipError(err); } } diff --git a/src/controller/python/chip/discovery/NodeResolution.cpp b/src/controller/python/chip/discovery/NodeResolution.cpp index 2bf44a2a01ccab..8f92477f1c1ef0 100644 --- a/src/controller/python/chip/discovery/NodeResolution.cpp +++ b/src/controller/python/chip/discovery/NodeResolution.cpp @@ -16,6 +16,7 @@ */ #include +#include #include #include #include @@ -25,13 +26,11 @@ using namespace chip; using namespace chip::Dnssd; -static_assert(std::is_same::value, "python assumes CHIP_ERROR maps to c_uint32"); - namespace { // callback types shared with python code (see ptyhon code in chip.discovery.types) using DiscoverSuccessCallback = void (*)(uint64_t fabricId, uint64_t nodeId, uint32_t interfaceId, const char * ip, uint16_t port); -using DiscoverFailureCallback = void (*)(uint64_t fabricId, uint64_t nodeId, ChipError::StorageType error_code); +using DiscoverFailureCallback = void (*)(uint64_t fabricId, uint64_t nodeId, PyChipError error_code); class PythonResolverDelegate : public OperationalResolveDelegate { @@ -62,7 +61,7 @@ class PythonResolverDelegate : public OperationalResolveDelegate { if (mFailureCallback != nullptr) { - mFailureCallback(peerId.GetCompressedFabricId(), peerId.GetNodeId(), error.AsInteger()); + mFailureCallback(peerId.GetCompressedFabricId(), peerId.GetNodeId(), ToPyChipError(error)); } else { @@ -88,7 +87,7 @@ extern "C" void pychip_discovery_set_callbacks(DiscoverSuccessCallback success, gPythonResolverDelegate.SetFailureCallback(failure); } -extern "C" ChipError::StorageType pychip_discovery_resolve(uint64_t fabricId, uint64_t nodeId) +extern "C" PyChipError pychip_discovery_resolve(uint64_t fabricId, uint64_t nodeId) { CHIP_ERROR result = CHIP_NO_ERROR; @@ -101,5 +100,5 @@ extern "C" ChipError::StorageType pychip_discovery_resolve(uint64_t fabricId, ui chip::Inet::IPAddressType::kAny); }); - return result.AsInteger(); + return ToPyChipError(result); } diff --git a/src/controller/python/chip/discovery/__init__.py b/src/controller/python/chip/discovery/__init__.py index a6897949c26813..d41325f5ff5a8d 100644 --- a/src/controller/python/chip/discovery/__init__.py +++ b/src/controller/python/chip/discovery/__init__.py @@ -24,6 +24,7 @@ from chip.discovery.library_handle import _GetDiscoveryLibraryHandle from chip.discovery.types import DiscoverSuccessCallback_t, DiscoverFailureCallback_t +from chip.native import PyChipError class FilterType(enum.IntEnum): @@ -201,10 +202,10 @@ def _DiscoverSuccess(fabric: int, node: int, interface: int, ip: str, port: int @DiscoverFailureCallback_t -def _DiscoverFailure(fabric: int, node: int, errorCode: int): +def _DiscoverFailure(fabric: int, node: int, errorCode: PyChipError): # Many discovery errors currently do not include a useful node/fabric id # hence we just log and rely on discovery timeouts to return 'no data' - logging.error("Discovery failure, error %d", errorCode) + logging.error("Discovery failure, error %d", errorCode.code) def FindAddressAsync(fabricid: int, nodeid: int, callback, timeout_ms=1000): diff --git a/src/controller/python/chip/discovery/library_handle.py b/src/controller/python/chip/discovery/library_handle.py index edf31631e3ac78..19ad5e8954181c 100644 --- a/src/controller/python/chip/discovery/library_handle.py +++ b/src/controller/python/chip/discovery/library_handle.py @@ -17,6 +17,7 @@ import chip.native import ctypes from chip.discovery.types import DiscoverSuccessCallback_t, DiscoverFailureCallback_t +from chip.native import PyChipError def _GetDiscoveryLibraryHandle() -> ctypes.CDLL: @@ -33,7 +34,7 @@ def _GetDiscoveryLibraryHandle() -> ctypes.CDLL: if not handle.pychip_discovery_resolve.argtypes: setter = chip.native.NativeLibraryHandleMethodArguments(handle) - setter.Set('pychip_discovery_resolve', ctypes.c_uint32, + setter.Set('pychip_discovery_resolve', PyChipError, [ctypes.c_uint64, ctypes.c_uint64]) setter.Set('pychip_discovery_set_callbacks', None, [ DiscoverSuccessCallback_t, DiscoverFailureCallback_t]) diff --git a/src/controller/python/chip/discovery/types.py b/src/controller/python/chip/discovery/types.py index 775c2420559bbf..34868b804f1bfc 100644 --- a/src/controller/python/chip/discovery/types.py +++ b/src/controller/python/chip/discovery/types.py @@ -15,6 +15,7 @@ # from ctypes import CFUNCTYPE, c_char_p, c_uint16, c_uint32, c_uint64 +from chip.native import PyChipError DiscoverSuccessCallback_t = CFUNCTYPE( @@ -30,5 +31,5 @@ None, # void return c_uint64, # fabric id c_uint64, # node id - c_uint32, # CHIP_ERROR error code + PyChipError, # CHIP_ERROR error code ) diff --git a/src/controller/python/chip/interaction_model/Delegate.cpp b/src/controller/python/chip/interaction_model/Delegate.cpp index 20ce1d2747b678..827d753b68cfc2 100644 --- a/src/controller/python/chip/interaction_model/Delegate.cpp +++ b/src/controller/python/chip/interaction_model/Delegate.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -49,15 +50,13 @@ void pychip_InteractionModelDelegate_SetOnWriteResponseStatusCallback(PythonInte extern "C" { -static_assert(std::is_same::value, "python assumes CHIP_ERROR maps to c_uint32"); - -chip::ChipError::StorageType pychip_InteractionModel_GetCommandSenderHandle(uint64_t * commandSender) +PyChipError pychip_InteractionModel_GetCommandSenderHandle(uint64_t * commandSender) { chip::app::CommandSender * commandSenderObj = nullptr; - VerifyOrReturnError(commandSender != nullptr, CHIP_ERROR_INVALID_ARGUMENT.AsInteger()); + VerifyOrReturnError(commandSender != nullptr, ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT)); commandSenderObj = new (std::nothrow) chip::app::CommandSender(nullptr, nullptr); - VerifyOrReturnError(commandSenderObj != nullptr, (CHIP_ERROR_NO_MEMORY).AsInteger()); + VerifyOrReturnError(commandSenderObj != nullptr, ToPyChipError((CHIP_ERROR_NO_MEMORY))); *commandSender = reinterpret_cast(commandSenderObj); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } } diff --git a/src/controller/python/chip/internal/CommissionerImpl.cpp b/src/controller/python/chip/internal/CommissionerImpl.cpp index 260a9c026dd641..96ab90f44b8ae2 100644 --- a/src/controller/python/chip/internal/CommissionerImpl.cpp +++ b/src/controller/python/chip/internal/CommissionerImpl.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -203,22 +204,20 @@ extern "C" chip::Controller::DeviceCommissioner * pychip_internal_Commissioner_N return result.release(); } -static_assert(std::is_same::value, "python assumes CHIP_ERROR maps to c_uint32"); - /// Returns CHIP_ERROR corresponding to an UnpairDevice call -extern "C" chip::ChipError::StorageType pychip_internal_Commissioner_Unpair(chip::Controller::DeviceCommissioner * commissioner, - uint64_t remoteDeviceId) +extern "C" PyChipError pychip_internal_Commissioner_Unpair(chip::Controller::DeviceCommissioner * commissioner, + uint64_t remoteDeviceId) { CHIP_ERROR err; chip::python::ChipMainThreadScheduleAndWait([&]() { err = commissioner->UnpairDevice(remoteDeviceId); }); - return err.AsInteger(); + return ToPyChipError(err); } -extern "C" chip::ChipError::StorageType -pychip_internal_Commissioner_BleConnectForPairing(chip::Controller::DeviceCommissioner * commissioner, uint64_t remoteNodeId, - uint32_t pinCode, uint16_t discriminator) +extern "C" PyChipError pychip_internal_Commissioner_BleConnectForPairing(chip::Controller::DeviceCommissioner * commissioner, + uint64_t remoteNodeId, uint32_t pinCode, + uint16_t discriminator) { CHIP_ERROR err; @@ -234,5 +233,5 @@ pychip_internal_Commissioner_BleConnectForPairing(chip::Controller::DeviceCommis err = commissioner->PairDevice(remoteNodeId, params); }); - return err.AsInteger(); + return ToPyChipError(err); } diff --git a/src/controller/python/chip/native/CommonStackInit.cpp b/src/controller/python/chip/native/CommonStackInit.cpp index f01bcf8799fbfb..8a149412a73944 100644 --- a/src/controller/python/chip/native/CommonStackInit.cpp +++ b/src/controller/python/chip/native/CommonStackInit.cpp @@ -31,6 +31,7 @@ #include #include +#include #include #include #include @@ -40,8 +41,6 @@ using namespace chip; -static_assert(std::is_same::value, "python assumes CHIP_ERROR maps to c_uint32"); - extern "C" { struct __attribute__((packed)) PyCommonStackInitParams @@ -60,19 +59,19 @@ void pychip_CauseCrash() *ptr = 0; } -ChipError::StorageType pychip_CommonStackInit(const PyCommonStackInitParams * aParams) +PyChipError pychip_CommonStackInit(const PyCommonStackInitParams * aParams) { - ReturnErrorOnFailure(Platform::MemoryInit().AsInteger()); + PyReturnErrorOnFailure(ToPyChipError(Platform::MemoryInit())); #if CHIP_DEVICE_LAYER_TARGET_LINUX && CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE // By default, Linux device is configured as a BLE peripheral while the controller needs a BLE central. - ReturnErrorOnFailure( - DeviceLayer::Internal::BLEMgrImpl().ConfigureBle(aParams->mBluetoothAdapterId, /* BLE central */ true).AsInteger()); + PyReturnErrorOnFailure( + ToPyChipError(DeviceLayer::Internal::BLEMgrImpl().ConfigureBle(aParams->mBluetoothAdapterId, /* BLE central */ true))); #endif - ReturnErrorOnFailure(DeviceLayer::PlatformMgr().InitChipStack().AsInteger()); + PyReturnErrorOnFailure(ToPyChipError(DeviceLayer::PlatformMgr().InitChipStack())); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } void pychip_CommonStackShutdown() diff --git a/src/controller/python/chip/native/PyChipError.cpp b/src/controller/python/chip/native/PyChipError.cpp new file mode 100644 index 00000000000000..58309c1a061fa7 --- /dev/null +++ b/src/controller/python/chip/native/PyChipError.cpp @@ -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. + */ + +#include "PyChipError.h" + +#include + +#include + +using namespace chip; +using namespace chip::DeviceLayer; + +void pychip_FormatError(PyChipError * apError, char * apBuf, uint32_t aBufSize) +{ + // Note: ChipError::AsString is not thread safe since it accesses a global (and mutable) variable for holding the formatted + // string. + // TODO: We should consider providing an API for putting the string into a user provided buffer to avoid potential race + // conditions. +#if CHIP_STACK_LOCK_TRACKING_ENABLED + if (!PlatformMgr().IsChipStackLockedByCurrentThread()) + { + PlatformMgr().LockChipStack(); + snprintf(apBuf, aBufSize, "%s", CHIP_ERROR(apError->mCode, apError->mFile, apError->mLine).AsString()); + PlatformMgr().UnlockChipStack(); + } + else +#endif + { + snprintf(apBuf, aBufSize, "%s", CHIP_ERROR(apError->mCode, apError->mFile, apError->mLine).AsString()); + } +} diff --git a/src/controller/python/chip/native/PyChipError.h b/src/controller/python/chip/native/PyChipError.h new file mode 100644 index 00000000000000..ed36c4c3e10fb2 --- /dev/null +++ b/src/controller/python/chip/native/PyChipError.h @@ -0,0 +1,89 @@ +/* + * + * 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 + +// Note: We can use a constructor here to avoid "ToPyChipError", but it will result in compilers warning for incompatible with C +// linkage. +struct PyChipError +{ + uint32_t mCode; + uint32_t mLine; + const char * mFile; +}; + +// To avoid the error message "user-defined type 'PyChipError' which is incompatible with C" + +inline bool operator!(const PyChipError & aError) +{ + return aError.mCode != 0; +} + +inline bool operator==(const PyChipError & aError, const CHIP_ERROR & aOther) +{ + return aError.mCode == aOther.AsInteger(); +} + +inline bool operator==(const CHIP_ERROR & aOther, const PyChipError & aError) +{ + return aError.mCode == aOther.AsInteger(); +} + +inline bool operator!=(const PyChipError & aError, const CHIP_ERROR & aOther) +{ + return !(aError.mCode == aOther.AsInteger()); +} + +inline bool operator!=(const CHIP_ERROR & aOther, const PyChipError & aError) +{ + return !(aError.mCode == aOther.AsInteger()); +} + +inline PyChipError ToPyChipError(const CHIP_ERROR & aError) +{ + return PyChipError + { + .mCode = aError.AsInteger(), +#if CHIP_CONFIG_ERROR_SOURCE + .mLine = aError.GetLine(), .mFile = aError.GetFile(), +#else + .mLine = 0, .mFile = nullptr, +#endif + }; +} + +// A version of ReturnErrorOnFailure which can use PyChipError as expr +// Note: we should consider implement operator == for CHIP_ERROR then we can overload it easily. +#define PyReturnErrorOnFailure(expr) \ + do \ + { \ + auto __err = (expr); \ + if (__err != CHIP_NO_ERROR) \ + { \ + return __err; \ + } \ + } while (false) + +static_assert(std::is_same::value, + "python assumes CHIP_ERROR maps to c_uint32"); + +extern "C" { +void pychip_FormatError(PyChipError * apError, char * apBuf, uint32_t aBufSize); +} diff --git a/src/controller/python/chip/native/__init__.py b/src/controller/python/chip/native/__init__.py index f0c175237e7b8a..1810c18c62f69d 100644 --- a/src/controller/python/chip/native/__init__.py +++ b/src/controller/python/chip/native/__init__.py @@ -3,6 +3,9 @@ import os import platform import construct +import chip.exceptions +import typing +import enum NATIVE_LIBRARY_BASE_NAME = "_ChipDeviceCtrl.so" @@ -18,6 +21,100 @@ def _AllDirsToRoot(dir): dir = parent +class ErrorRange(enum.IntEnum): + ''' The enum of chip::ChipError::Range + ''' + SDK = 0x0 + OS = 0x1 + POSIX = 0x2 + LWIP = 0x3 + OPENTHREAD = 0x4 + PLATFROM = 0x5 + + +class ErrorSDKPart(enum.IntEnum): + ''' The enum of chip::ChipError::SDKPart + ''' + CORE = 0 + INET = 1 + DEVICE = 2 + ASN1 = 3 + BLE = 4 + IM_GLOBAL_STATUS = 5 + IM_CLUSTER_STATUS = 6 + APPLICATION = 7 + + +class PyChipError(ctypes.Structure): + ''' The ChipError for Python library. + + We are using the following struct for passing the infomations of CHIP_ERROR between C++ and Python: + + ```c + struct PyChipError + { + uint32_t mCode; + uint32_t mLine; + const char * mFile; + }; + ``` + ''' + _fields_ = [('code', ctypes.c_uint32), ('line', ctypes.c_uint32), ('file', ctypes.c_void_p)] + + def raise_on_error(self) -> None: + if self.code != 0: + raise self.to_exception() + + @property + def is_success(self) -> bool: + return self.code == 0 + + @property + def is_sdk_error(self) -> bool: + return self.range == ErrorRange.SDK + + @property + def range(self) -> ErrorRange: + return ErrorRange((self.code >> 24) & 0xFF) + + @property + def value(self) -> int: + return (self.code) & 0xFFFFFF + + @property + def sdk_part(self) -> ErrorSDKPart: + if not self.is_sdk_error: + return None + return ErrorSDKPart((self.code >> 8) & 0x07) + + @property + def sdk_code(self) -> int: + if not self.is_sdk_error: + return None + return self.code & 0xFF + + def to_exception(self) -> typing.Union[None, chip.exceptions.ChipStackError]: + if not self.is_success: + return chip.exceptions.ChipStackError(self.code, str(self)) + + def __str__(self): + buf = ctypes.create_string_buffer(256) + GetLibraryHandle().pychip_FormatError(ctypes.pointer(self), buf, 256) + return buf.value.decode() + + def __eq__(self, other): + if isinstance(other, int): + return self.code == other + if isinstance(other, PyChipError): + return self.code == other.code + if isinstance(other, chip.exceptions.ChipStackError): + return self.code == other.err + raise ValueError(f"Cannot compare PyChipError with {type(other)}") + + def __ne__(self, other): + return not self == other + + def FindNativeLibraryPath() -> str: """Find the native CHIP dll/so path.""" @@ -79,7 +176,8 @@ def _GetLibraryHandle(shouldInit: bool) -> ctypes.CDLL: raise Exception("Common stack has not been initialized!") _nativeLibraryHandle = ctypes.CDLL(FindNativeLibraryPath()) setter = NativeLibraryHandleMethodArguments(_nativeLibraryHandle) - setter.Set("pychip_CommonStackInit", ctypes.c_uint32, [ctypes.c_char_p]) + setter.Set("pychip_CommonStackInit", PyChipError, [ctypes.c_char_p]) + setter.Set("pychip_FormatError", None, [ctypes.POINTER(PyChipError), ctypes.c_char_p, ctypes.c_uint32]) return _nativeLibraryHandle diff --git a/src/controller/python/chip/setup_payload/Generator.cpp b/src/controller/python/chip/setup_payload/Generator.cpp index 4211fc3248dfb6..4481a404462394 100644 --- a/src/controller/python/chip/setup_payload/Generator.cpp +++ b/src/controller/python/chip/setup_payload/Generator.cpp @@ -15,6 +15,7 @@ * limitations under the License. */ +#include #include #include #include @@ -24,11 +25,9 @@ using namespace chip; -static_assert(std::is_same::value, "python assumes CHIP_ERROR maps to c_uint32"); - -extern "C" ChipError::StorageType pychip_SetupPayload_PrintOnboardingCodes(uint32_t passcode, uint16_t vendorId, uint16_t productId, - uint16_t discriminator, uint8_t customFlow, - uint8_t capabilities, uint8_t version) +extern "C" PyChipError pychip_SetupPayload_PrintOnboardingCodes(uint32_t passcode, uint16_t vendorId, uint16_t productId, + uint16_t discriminator, uint8_t customFlow, uint8_t capabilities, + uint8_t version) { std::string QRCode; std::string manualPairingCode; @@ -55,16 +54,16 @@ extern "C" ChipError::StorageType pychip_SetupPayload_PrintOnboardingCodes(uint3 break; default: ChipLogError(SetupPayload, "Invalid Custom Flow"); - return CHIP_ERROR_INVALID_ARGUMENT.AsInteger(); + return ToPyChipError(CHIP_ERROR_INVALID_ARGUMENT); } CHIP_ERROR err = ManualSetupPayloadGenerator(payload).payloadDecimalStringRepresentation(manualPairingCode); - VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger()); + VerifyOrReturnError(err == CHIP_NO_ERROR, ToPyChipError(err)); ChipLogProgress(SetupPayload, "Manual pairing code: [%s]", manualPairingCode.c_str()); err = QRCodeSetupPayloadGenerator(payload).payloadBase38Representation(QRCode); - VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger()); + VerifyOrReturnError(err == CHIP_NO_ERROR, ToPyChipError(err)); ChipLogProgress(SetupPayload, "SetupQRCode: [%s]", QRCode.c_str()); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } diff --git a/src/controller/python/chip/setup_payload/Parser.cpp b/src/controller/python/chip/setup_payload/Parser.cpp index 83266f1fc4c469..c48dc3f3722c13 100644 --- a/src/controller/python/chip/setup_payload/Parser.cpp +++ b/src/controller/python/chip/setup_payload/Parser.cpp @@ -15,6 +15,7 @@ * limitations under the License. */ +#include #include #include #include @@ -24,8 +25,6 @@ using namespace chip; -static_assert(std::is_same::value, "python assumes CHIP_ERROR maps to c_uint32"); - namespace { using AttributeVisitor = void (*)(const char * attrName, const char * attrValue); @@ -69,25 +68,24 @@ void YieldSetupPayloadAttributes(const SetupPayload & payload, AttributeVisitor } // namespace -extern "C" ChipError::StorageType pychip_SetupPayload_ParseQrCode(const char * qrCode, AttributeVisitor attrVisitor, - VendorAttributeVisitor vendorAttrVisitor) +extern "C" PyChipError pychip_SetupPayload_ParseQrCode(const char * qrCode, AttributeVisitor attrVisitor, + VendorAttributeVisitor vendorAttrVisitor) { SetupPayload payload; CHIP_ERROR err = QRCodeSetupPayloadParser(qrCode).populatePayload(payload); - VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger()); + VerifyOrReturnError(err == CHIP_NO_ERROR, ToPyChipError(err)); YieldSetupPayloadAttributes(payload, attrVisitor, vendorAttrVisitor); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } -extern "C" ChipError::StorageType pychip_SetupPayload_ParseManualPairingCode(const char * manualPairingCode, - AttributeVisitor attrVisitor, - VendorAttributeVisitor vendorAttrVisitor) +extern "C" PyChipError pychip_SetupPayload_ParseManualPairingCode(const char * manualPairingCode, AttributeVisitor attrVisitor, + VendorAttributeVisitor vendorAttrVisitor) { SetupPayload payload; CHIP_ERROR err = ManualSetupPayloadParser(manualPairingCode).populatePayload(payload); - VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger()); + VerifyOrReturnError(err == CHIP_NO_ERROR, ToPyChipError(err)); YieldSetupPayloadAttributes(payload, attrVisitor, vendorAttrVisitor); - return CHIP_NO_ERROR.AsInteger(); + return ToPyChipError(CHIP_NO_ERROR); } diff --git a/src/controller/python/chip/utils/DeviceProxyUtils.cpp b/src/controller/python/chip/utils/DeviceProxyUtils.cpp index ea6add7a039609..d3bb2c6e65e204 100644 --- a/src/controller/python/chip/utils/DeviceProxyUtils.cpp +++ b/src/controller/python/chip/utils/DeviceProxyUtils.cpp @@ -27,13 +27,12 @@ #include "system/SystemClock.h" #include +#include #include #include using namespace chip; -static_assert(std::is_same::value, "python assumes CHIP_ERROR maps to c_uint32"); - extern "C" { /** diff --git a/src/controller/python/test/test_scripts/base.py b/src/controller/python/test/test_scripts/base.py index cab2f665ffe65d..ca4c30a4a5a93b 100644 --- a/src/controller/python/test/test_scripts/base.py +++ b/src/controller/python/test/test_scripts/base.py @@ -931,11 +931,7 @@ async def OnResubscriptionSucceeded(transaction): def TestCloseSession(self, nodeid: int): self.logger.info(f"Closing sessions with device {nodeid}") try: - err = self.devCtrl.CloseSession(nodeid) - if err != 0: - self.logger.exception( - f"Failed to close sessions with device {nodeid}: {err}") - return False + self.devCtrl.CloseSession(nodeid) return True except Exception as ex: self.logger.exception( diff --git a/src/controller/tests/TestEventChunking.cpp b/src/controller/tests/TestEventChunking.cpp index 6764bb95e307c3..d0132301360844 100644 --- a/src/controller/tests/TestEventChunking.cpp +++ b/src/controller/tests/TestEventChunking.cpp @@ -542,10 +542,10 @@ nlTestSuite sSuite = } // namespace -int TestReadChunkingTests() +int TestEventChunkingTests() { gSuite = &sSuite; return chip::ExecuteTestsWithContext(&sSuite); } -CHIP_REGISTER_TEST_SUITE(TestReadChunkingTests) +CHIP_REGISTER_TEST_SUITE(TestEventChunkingTests) diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 43099ba10efbab..d9f3a0725b16bb 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -2643,8 +2643,8 @@ void TestReadInteraction::TestReadHandler_MultipleSubscriptionsWithDataVersionFi numSuccessCalls == (app::InteractionModelEngine::kReadHandlerPoolSize + 1); }); - ChipLogError(Zcl, "Success call cnt: %u (expect %u) subscription cnt: %u (expect %u)", numSuccessCalls, - uint32_t(app::InteractionModelEngine::kReadHandlerPoolSize + 1), numSubscriptionEstablishedCalls, + ChipLogError(Zcl, "Success call cnt: %" PRIu32 " (expect %" PRIu32 ") subscription cnt: %" PRIu32 " (expect %" PRIu32 ")", + numSuccessCalls, uint32_t(app::InteractionModelEngine::kReadHandlerPoolSize + 1), numSubscriptionEstablishedCalls, uint32_t(app::InteractionModelEngine::kReadHandlerPoolSize + 1)); NL_TEST_ASSERT(apSuite, numSuccessCalls == (app::InteractionModelEngine::kReadHandlerPoolSize + 1)); diff --git a/src/inet/tests/TestInetCommonPosix.cpp b/src/inet/tests/TestInetCommonPosix.cpp index 216c8c6315b7ec..e7e658e0252a2c 100644 --- a/src/inet/tests/TestInetCommonPosix.cpp +++ b/src/inet/tests/TestInetCommonPosix.cpp @@ -37,6 +37,7 @@ #include "TestInetCommon.h" #include "TestInetCommonOptions.h" +#include #include #include diff --git a/src/lib/support/CHIPArgParser.cpp b/src/lib/support/CHIPArgParser.cpp index dc9aaf17cdadbc..85aa4dba0f8bdd 100644 --- a/src/lib/support/CHIPArgParser.cpp +++ b/src/lib/support/CHIPArgParser.cpp @@ -292,6 +292,11 @@ bool ParseArgs(const char * progName, int argc, char * const argv[], OptionSet * OptionSet * curOptSet; OptionDef * curOpt; bool handlerRes; +#if CHIP_CONFIG_NON_POSIX_LONG_OPT + int lastOptIndex = 0; + int subOptIndex = 0; + int currentOptIndex = 0; +#endif // CHIP_CONFIG_NON_POSIX_LONG_OPT // The getopt() functions do not support recursion, so exit immediately with an // error if called recursively. @@ -345,7 +350,36 @@ bool ParseArgs(const char * progName, int argc, char * const argv[], OptionSet * // Attempt to match the current option argument (argv[optind]) against the defined long and short options. optarg = nullptr; optopt = 0; - id = getopt_long(argc, argv, shortOpts, longOpts, &optIndex); +#if CHIP_CONFIG_NON_POSIX_LONG_OPT + // to check if index has changed + lastOptIndex = currentOptIndex; + // optind will not increment on error, this is why we need to keep track of the current option + // this is for use when getopt_long fails to find the option and we need to print the error + currentOptIndex = optind; + // if it's the first run, optind is not set and we need to find the first option ourselves + if (!currentOptIndex) + { + while (currentOptIndex < argc) + { + currentOptIndex++; + if (*argv[currentOptIndex] == '-') + { + break; + } + } + } + // similarly we need to keep track of short opts index for groups like "-fba" + // if the index has not changed that means we are still analysing the same group + if (lastOptIndex != currentOptIndex) + { + subOptIndex = 0; + } + else + { + subOptIndex++; + } +#endif // CHIP_CONFIG_NON_POSIX_LONG_OPT + id = getopt_long(argc, argv, shortOpts, longOpts, &optIndex); // Stop if there are no more options. if (id == -1) @@ -356,10 +390,35 @@ bool ParseArgs(const char * progName, int argc, char * const argv[], OptionSet * { if (ignoreUnknown) continue; +#if CHIP_CONFIG_NON_POSIX_LONG_OPT + // getopt_long doesn't tell us if the option which failed to match is long or short so check + bool isLongOption = false; + if (strlen(argv[currentOptIndex]) > 2 && argv[currentOptIndex][1] == '-') + { + isLongOption = true; + } + if (optopt == 0 || isLongOption) + { + // getopt_long function incorrectly treats unknown long option as short opt group + if (subOptIndex == 0) + { + PrintArgError("%s: Unknown option: %s\n", progName, argv[currentOptIndex]); + } + } + else if (optopt == '?') + { + PrintArgError("%s: Unknown option: -%c\n", progName, argv[currentOptIndex][subOptIndex + 1]); + } + else + { + PrintArgError("%s: Unknown option: -%c\n", progName, optopt); + } +#else if (optopt != 0) PrintArgError("%s: Unknown option: -%c\n", progName, optopt); else PrintArgError("%s: Unknown option: %s\n", progName, argv[optind - 1]); +#endif // CHIP_CONFIG_NON_POSIX_LONG_OPT goto done; } @@ -369,7 +428,11 @@ bool ParseArgs(const char * progName, int argc, char * const argv[], OptionSet * { // NOTE: with the way getopt_long() works, it is impossible to tell whether the option that // was missing an argument was a long option or a short option. +#if CHIP_CONFIG_NON_POSIX_LONG_OPT + PrintArgError("%s: Missing argument for %s option\n", progName, argv[currentOptIndex]); +#else PrintArgError("%s: Missing argument for %s option\n", progName, argv[optind - 1]); +#endif // CHIP_CONFIG_NON_POSIX_LONG_OPT goto done; } diff --git a/src/lib/support/jsontlv/TlvJson.cpp b/src/lib/support/jsontlv/TlvJson.cpp index 2639b743733908..e7044da118f0b0 100644 --- a/src/lib/support/jsontlv/TlvJson.cpp +++ b/src/lib/support/jsontlv/TlvJson.cpp @@ -95,7 +95,7 @@ void InsertKeyValue(Json::Value & json, const KeyContext & keyContext, T val) } else if (keyContext.keyType == KeyContext::kStructField) { - snprintf(keyBuf, sizeof(keyBuf), "%" PRIu32, keyContext.key); + snprintf(keyBuf, sizeof(keyBuf), "%u", keyContext.key); json[keyBuf] = val; } else diff --git a/src/lib/support/tests/TestBytesToHex.cpp b/src/lib/support/tests/TestBytesToHex.cpp index ddd92772e16412..f99fed9f1b6cbc 100644 --- a/src/lib/support/tests/TestBytesToHex.cpp +++ b/src/lib/support/tests/TestBytesToHex.cpp @@ -433,8 +433,10 @@ const nlTest sTests[] = { NL_TEST_DEF("TestBytesToHexErrors", TestBytesToHexErrors), // NL_TEST_DEF("TestBytesToHexUint64", TestBytesToHexUint64), // NL_TEST_DEF("TestHexToBytesAndUint", TestHexToBytesAndUint), // - NL_TEST_DEF("TestLogBufferAsHex", TestLogBufferAsHex), // - NL_TEST_SENTINEL() // +#ifdef CHIP_PROGRESS_LOGGING + NL_TEST_DEF("TestLogBufferAsHex", TestLogBufferAsHex), // +#endif + NL_TEST_SENTINEL() // }; } // namespace diff --git a/src/lib/support/tests/TestCHIPArgParser.cpp b/src/lib/support/tests/TestCHIPArgParser.cpp index 00a24eedbac619..b5674d3e8a5bfa 100644 --- a/src/lib/support/tests/TestCHIPArgParser.cpp +++ b/src/lib/support/tests/TestCHIPArgParser.cpp @@ -137,7 +137,7 @@ static size_t sCallbackRecordCount = 0; static OptionDef sOptionSetA_Defs[] = { { "foo", kNoArgument, '1' }, - { "bar", kNoArgument, 1001 }, + { "bar", kNoArgument, 1002 }, { "baz", kArgumentRequired, 'Z' }, { } }; @@ -350,7 +350,7 @@ static void SimpleParseTest_VariousShortAndLongWithArgs() VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetA, '1', "--foo", nullptr); VerifyHandleOptionCallback(1, __FUNCTION__, &sOptionSetB, 1000, "--run", "run-value"); VerifyHandleOptionCallback(2, __FUNCTION__, &sOptionSetB, 's', "-s", nullptr); - VerifyHandleOptionCallback(3, __FUNCTION__, &sOptionSetA, 1001, "--bar", nullptr); + VerifyHandleOptionCallback(3, __FUNCTION__, &sOptionSetA, 1002, "--bar", nullptr); VerifyHandleOptionCallback(4, __FUNCTION__, &sOptionSetA, '1', "-1", nullptr); VerifyHandleOptionCallback(5, __FUNCTION__, &sOptionSetA, 'Z', "-Z", "baz-value"); VerifyHandleOptionCallback(6, __FUNCTION__, &sOptionSetB, 1000, "--run", "run-value-2"); @@ -779,7 +779,12 @@ int TestCHIPArgParser(void) UnknownOptionTest_UnknownShortOptionBeforeKnown(); UnknownOptionTest_UnknownLongOptionAfterArgs(); UnknownOptionTest_IgnoreUnknownShortOption(); + + /* Skip this test because the parser successfully captures all the options + but the error reporting is incorrect in this case due to long_opt limitations */ +#ifndef CHIP_CONFIG_NON_POSIX_LONG_OPT UnknownOptionTest_IgnoreUnknownLongOption(); +#endif // !CHIP_CONFIG_NON_POSIX_LONG_OPT MissingValueTest_MissingShortOptionValue(); MissingValueTest_MissingLongOptionValue(); diff --git a/src/platform/Darwin/CHIPPlatformConfig.h b/src/platform/Darwin/CHIPPlatformConfig.h index 4b11bfefca9f66..e3e1a99aebe5a1 100644 --- a/src/platform/Darwin/CHIPPlatformConfig.h +++ b/src/platform/Darwin/CHIPPlatformConfig.h @@ -59,10 +59,6 @@ #define CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS 1 #endif // CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS -// TODO - Fine tune MRP default parameters for Darwin platform -#define CHIP_CONFIG_MRP_DEFAULT_INITIAL_RETRY_INTERVAL (15000) -#define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL (2000_ms32) - #ifndef CHIP_CONFIG_KVS_PATH #define CHIP_CONFIG_KVS_PATH "/tmp/chip_kvs" #endif // CHIP_CONFIG_KVS_PATH diff --git a/src/platform/bouffalolab/BL702/ThreadStackManagerImpl.cpp b/src/platform/bouffalolab/BL702/ThreadStackManagerImpl.cpp index 73a96a90a6e853..be9d29619aae4f 100644 --- a/src/platform/bouffalolab/BL702/ThreadStackManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702/ThreadStackManagerImpl.cpp @@ -48,6 +48,9 @@ CHIP_ERROR ThreadStackManagerImpl::InitThreadStack(otInstance * otInst) { CHIP_ERROR err = CHIP_NO_ERROR; + ot_alarmInit(); + ot_radioInit(); + // Initialize the generic implementation base classes. err = GenericThreadStackManagerImpl_FreeRTOS::DoInit(); SuccessOrExit(err); diff --git a/src/platform/bouffalolab/BL702/bl702Config.cpp b/src/platform/bouffalolab/BL702/bl702Config.cpp index 0c51dd6d9afbbc..809ed940e9d6c4 100644 --- a/src/platform/bouffalolab/BL702/bl702Config.cpp +++ b/src/platform/bouffalolab/BL702/bl702Config.cpp @@ -207,23 +207,10 @@ CHIP_ERROR BL702Config::ReadKVS(const char * key, void * value, size_t value_siz ef_port_env_lock(); - char * p = (char *) malloc((sizeof(KCONFIG_SECT_KVS) + strlen(key) + sizeof(size_t))); - if (!p) - { - ef_port_env_unlock(); - return CHIP_ERROR_NO_MEMORY; - } - - memcpy(p, KCONFIG_SECT_KVS, sizeof(KCONFIG_SECT_KVS) - 1); - p[sizeof(KCONFIG_SECT_KVS) - 1] = '_'; - strcpy(p + sizeof(KCONFIG_SECT_KVS), key); - - if (true == ef_get_env_obj(p, &node)) + if (true == ef_get_env_obj(key, &node)) { - if (offset_bytes > node.value_len) { - free(p); ef_port_env_unlock(); return CHIP_ERROR_INVALID_ARGUMENT; } @@ -256,13 +243,11 @@ CHIP_ERROR BL702Config::ReadKVS(const char * key, void * value, size_t value_siz } } - free(p); ef_port_env_unlock(); return CHIP_NO_ERROR; } - free(p); ef_port_env_unlock(); return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; @@ -274,23 +259,11 @@ CHIP_ERROR BL702Config::WriteKVS(const char * key, const void * value, size_t va ef_port_env_lock(); - char * p = (char *) malloc((sizeof(KCONFIG_SECT_KVS) + strlen(key) + sizeof(size_t))); - if (!p) - { - ef_port_env_unlock(); - return CHIP_ERROR_NO_MEMORY; - } - - memcpy(p, KCONFIG_SECT_KVS, sizeof(KCONFIG_SECT_KVS) - 1); - p[sizeof(KCONFIG_SECT_KVS) - 1] = '_'; - strcpy(p + sizeof(KCONFIG_SECT_KVS), key); - if (value && value_size) { - ret = ef_set_env_blob(p, value, value_size); + ret = ef_set_env_blob(key, value, value_size); } - free(p); ef_port_env_unlock(); if (ret == EF_NO_ERR) @@ -307,20 +280,8 @@ CHIP_ERROR BL702Config::ClearKVS(const char * key) { ef_port_env_lock(); - char * p = (char *) malloc((sizeof(KCONFIG_SECT_KVS) + strlen(key) + sizeof(size_t))); - if (!p) - { - ef_port_env_unlock(); - return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - memcpy(p, KCONFIG_SECT_KVS, sizeof(KCONFIG_SECT_KVS) - 1); - p[sizeof(KCONFIG_SECT_KVS) - 1] = '_'; - strcpy(p + sizeof(KCONFIG_SECT_KVS), key); - - ef_del_env(p); + ef_del_env(key); - free(p); ef_port_env_unlock(); return CHIP_NO_ERROR; diff --git a/src/platform/bouffalolab/BL702/bl702Config.h b/src/platform/bouffalolab/BL702/bl702Config.h index 967dfcdfcf8aa7..dc9450f4986c61 100644 --- a/src/platform/bouffalolab/BL702/bl702Config.h +++ b/src/platform/bouffalolab/BL702/bl702Config.h @@ -25,13 +25,7 @@ namespace chip { namespace DeviceLayer { namespace Internal { -#define KCONFIG_SECT_FACTORY "chip-factory" -#define KCONFIG_SECT_CONFIG "chip-config" -#define KCONFIG_SECT_COUTNER "chip-counter" -#define KCONFIG_SECT_KVS "chip-kvs" -#define KCONFIG_SECT_PSV "chip-psv" -#define KCONFIG_MAX_LEN sizeof(KCONFIG_SECT_FACTORY) - +#define KCONFIG_SECT_PSV "PSV" /** * Provides functions and definitions for accessing device configuration information on the BL702 platform. * @@ -45,41 +39,41 @@ class BL702Config /** Key definitions for well-known keys */ /** Manufacturing config keys, which should be saved in a specified place */ - static constexpr const char * kConfigKey_SerialNum = (KCONFIG_SECT_FACTORY "_serial-num"); - static constexpr const char * kConfigKey_MfrDeviceId = (KCONFIG_SECT_FACTORY "_device-id"); - static constexpr const char * kConfigKey_MfrDeviceCert = (KCONFIG_SECT_FACTORY "_device-cert"); - static constexpr const char * kConfigKey_MfrDeviceICACerts = (KCONFIG_SECT_FACTORY "_device-ca-certs"); - static constexpr const char * kConfigKey_MfrDevicePrivateKey = (KCONFIG_SECT_FACTORY "_device-key"); - static constexpr const char * kConfigKey_ManufacturingDate = (KCONFIG_SECT_FACTORY "_mfg-date"); - static constexpr const char * kConfigKey_SetupPinCode = (KCONFIG_SECT_FACTORY "_pin-code"); - static constexpr const char * kConfigKey_SetupDiscriminator = (KCONFIG_SECT_FACTORY "_discriminator"); - static constexpr const char * kConfigKey_Spake2pIterationCount = (KCONFIG_SECT_FACTORY "_iteration-count"); - static constexpr const char * kConfigKey_Spake2pSalt = (KCONFIG_SECT_FACTORY "_salt"); - static constexpr const char * kConfigKey_Spake2pVerifier = (KCONFIG_SECT_FACTORY "_verifier"); - static constexpr const char * kConfigKey_UniqueId = (KCONFIG_SECT_FACTORY "_unique-id"); + static constexpr const char * kConfigKey_SerialNum = ("serial-num"); + static constexpr const char * kConfigKey_MfrDeviceId = ("device-id"); + static constexpr const char * kConfigKey_MfrDeviceCert = ("device-cert"); + static constexpr const char * kConfigKey_MfrDeviceICACerts = ("device-ca-certs"); + static constexpr const char * kConfigKey_MfrDevicePrivateKey = ("device-key"); + static constexpr const char * kConfigKey_ManufacturingDate = ("mfg-date"); + static constexpr const char * kConfigKey_SetupPinCode = ("pin-code"); + static constexpr const char * kConfigKey_SetupDiscriminator = ("discriminator"); + static constexpr const char * kConfigKey_Spake2pIterationCount = ("iteration-count"); + static constexpr const char * kConfigKey_Spake2pSalt = ("salt"); + static constexpr const char * kConfigKey_Spake2pVerifier = ("verifier"); + static constexpr const char * kConfigKey_UniqueId = ("unique-id"); /** Config keys, which should be droped after a factory reset */ - static constexpr const char * kConfigKey_FabricId = (KCONFIG_SECT_CONFIG "_fabric-id"); - static constexpr const char * kConfigKey_ServiceConfig = (KCONFIG_SECT_CONFIG "_service-config"); - static constexpr const char * kConfigKey_PairedAccountId = (KCONFIG_SECT_CONFIG "_account-id"); - static constexpr const char * kConfigKey_ServiceId = (KCONFIG_SECT_CONFIG "_service-id"); - static constexpr const char * kConfigKey_FabricSecret = (KCONFIG_SECT_CONFIG "_fabric-secret"); - static constexpr const char * kConfigKey_HardwareVersion = (KCONFIG_SECT_CONFIG "_hardware-rev"); - static constexpr const char * kConfigKey_LastUsedEpochKeyId = (KCONFIG_SECT_CONFIG "_last-ek-id"); - static constexpr const char * kConfigKey_FailSafeArmed = (KCONFIG_SECT_CONFIG "_fail-safe-armed"); - static constexpr const char * kConfigKey_WiFiStationSecType = (KCONFIG_SECT_CONFIG "_sta-sec-type"); - static constexpr const char * kConfigKey_RegulatoryLocation = (KCONFIG_SECT_CONFIG "_regulatory-location"); - static constexpr const char * kConfigKey_CountryCode = (KCONFIG_SECT_CONFIG "_country-code"); - static constexpr const char * kConfigKey_ActiveLocale = (KCONFIG_SECT_CONFIG "_active-locale"); - static constexpr const char * kConfigKey_Breadcrumb = (KCONFIG_SECT_CONFIG "_breadcrumb"); - static constexpr const char * kConfigKey_GroupKeyIndex = (KCONFIG_SECT_CONFIG "_group-key-index"); - static constexpr const char * kBLConfigKey_wifissid = (KCONFIG_SECT_CONFIG "blConfig_wifi-ssid"); - static constexpr const char * kBLConfigKey_wifipassword = (KCONFIG_SECT_CONFIG "blConfig_wifi-pwd"); + static constexpr const char * kConfigKey_FabricId = ("fabric-id"); + static constexpr const char * kConfigKey_ServiceConfig = ("service-config"); + static constexpr const char * kConfigKey_PairedAccountId = ("account-id"); + static constexpr const char * kConfigKey_ServiceId = ("service-id"); + static constexpr const char * kConfigKey_FabricSecret = ("fabric-secret"); + static constexpr const char * kConfigKey_HardwareVersion = ("hardware-rev"); + static constexpr const char * kConfigKey_LastUsedEpochKeyId = ("last-ek-id"); + static constexpr const char * kConfigKey_FailSafeArmed = ("fail-safe-armed"); + static constexpr const char * kConfigKey_WiFiStationSecType = ("sta-sec-type"); + static constexpr const char * kConfigKey_RegulatoryLocation = ("regulatory-location"); + static constexpr const char * kConfigKey_CountryCode = ("country-code"); + static constexpr const char * kConfigKey_ActiveLocale = ("active-locale"); + static constexpr const char * kConfigKey_Breadcrumb = ("breadcrumb"); + static constexpr const char * kConfigKey_GroupKeyIndex = ("group-key-index"); + static constexpr const char * kBLConfigKey_wifissid = ("blConfig_wifi-ssid"); + static constexpr const char * kBLConfigKey_wifipassword = ("blConfig_wifi-pwd"); /** Counter Keys, diagnostic information */ - static constexpr const char * kCounterKey_BootCount = (KCONFIG_SECT_COUTNER "_boot-count"); - static constexpr const char * kCounterKey_TotalOperationalHours = (KCONFIG_SECT_COUTNER "_total-hours"); - static constexpr const char * kCounterKey_UpTime = (KCONFIG_SECT_COUTNER "_up-time"); + static constexpr const char * kCounterKey_BootCount = ("boot-count"); + static constexpr const char * kCounterKey_TotalOperationalHours = ("total-hours"); + static constexpr const char * kCounterKey_UpTime = ("up-time"); static CHIP_ERROR Init(void); diff --git a/src/protocols/secure_channel/PASESession.cpp b/src/protocols/secure_channel/PASESession.cpp index 05fc3b38915983..67b462fa860838 100644 --- a/src/protocols/secure_channel/PASESession.cpp +++ b/src/protocols/secure_channel/PASESession.cpp @@ -212,6 +212,10 @@ CHIP_ERROR PASESession::Pair(SessionManager & sessionManager, uint32_t peerSetUp mRole = CryptoContext::SessionRole::kInitiator; mExchangeCtxt = exchangeCtxt; + + // When commissioning starts, the peer is assumed to be active. + mExchangeCtxt->GetSessionHandle()->AsUnauthenticatedSession()->MarkActiveRx(); + mExchangeCtxt->SetResponseTimeout(kSpake2p_Response_Timeout + mExchangeCtxt->GetSessionHandle()->GetAckTimeout()); mLocalMRPConfig = mrpLocalConfig; diff --git a/src/protocols/secure_channel/RendezvousParameters.h b/src/protocols/secure_channel/RendezvousParameters.h index a5b76ed40482ee..ddc1281dd9d0e8 100644 --- a/src/protocols/secure_channel/RendezvousParameters.h +++ b/src/protocols/secure_channel/RendezvousParameters.h @@ -24,6 +24,7 @@ #endif // CONFIG_NETWORK_LAYER_BLE #include +#include #include namespace chip { @@ -31,6 +32,9 @@ namespace chip { // The largest supported value for Rendezvous discriminators const uint16_t kMaxRendezvousDiscriminatorValue = 0xFFF; +// The largest supported value for sleepy idle interval and sleepy active interval +constexpr uint32_t kMaxSleepyInterval = 3600000; + class RendezvousParameters { public: @@ -93,6 +97,28 @@ class RendezvousParameters bool HasConnectionObject() const { return false; } #endif // CONFIG_NETWORK_LAYER_BLE + bool HasMRPConfig() const { return mMRPConfig.HasValue(); } + ReliableMessageProtocolConfig GetMRPConfig() const { return mMRPConfig.ValueOr(GetDefaultMRPConfig()); } + RendezvousParameters & SetIdleInterval(System::Clock::Milliseconds32 interval) + { + if (!mMRPConfig.HasValue()) + { + mMRPConfig.Emplace(GetDefaultMRPConfig()); + } + mMRPConfig.Value().mIdleRetransTimeout = interval; + return *this; + } + + RendezvousParameters & SetActiveInterval(System::Clock::Milliseconds32 interval) + { + if (!mMRPConfig.HasValue()) + { + mMRPConfig.Emplace(GetDefaultMRPConfig()); + } + mMRPConfig.Value().mActiveRetransTimeout = interval; + return *this; + } + private: Transport::PeerAddress mPeerAddress; ///< the peer node address uint32_t mSetupPINCode = 0; ///< the target peripheral setup PIN Code @@ -101,6 +127,8 @@ class RendezvousParameters Spake2pVerifier mPASEVerifier; bool mHasPASEVerifier = false; + Optional mMRPConfig; + #if CONFIG_NETWORK_LAYER_BLE Ble::BleLayer * mBleLayer = nullptr; BLE_CONNECTION_OBJECT mConnectionObject = BLE_CONNECTION_UNINITIALIZED; diff --git a/src/transport/GroupSession.h b/src/transport/GroupSession.h index 2bc2d82345e151..bd3ab1931c2c7c 100644 --- a/src/transport/GroupSession.h +++ b/src/transport/GroupSession.h @@ -66,7 +66,7 @@ class IncomingGroupSession : public Session, public ReferenceCounted #endif -HOSAL_UART_DEV_DECL(uart_stdio, 0, 16, 7, 115200); +HOSAL_UART_DEV_DECL(uart_stdio, 0, 16, 7, CHIP_UART_BAUDRATE); extern uint8_t _heap_start; extern uint8_t _heap_size; // @suppress("Type cannot be resolved") diff --git a/third_party/bouffalolab/bl702/bl702_executable.gni b/third_party/bouffalolab/bl702/bl702_executable.gni index 7fa34fa759a46a..8d72c59b48acf7 100644 --- a/third_party/bouffalolab/bl702/bl702_executable.gni +++ b/third_party/bouffalolab/bl702/bl702_executable.gni @@ -42,7 +42,6 @@ template("bl702_executable") { "${chip_root}/scripts/flashing/bouffalolab_firmware_utils.py", "${chip_root}/scripts/flashing/firmware_utils.py", - "${chip_root}/examples/platform/bouffalolab/bl702/flash_config/bl_factory_params_IoTKitA_32M.dts", "${chip_root}/examples/platform/bouffalolab/bl702/flash_config/partition_cfg_2M.toml", ] copy(flashing_runtime_target) { @@ -61,10 +60,6 @@ template("bl702_executable") { flashing_options += [ "--pt" ] flashing_options += [ rebase_path("partition_cfg_2M.toml", root_out_dir, root_out_dir) ] - flashing_options += [ "--dts" ] - flashing_options += [ rebase_path("bl_factory_params_IoTKitA_32M.dts", - root_out_dir, - root_out_dir) ] flashing_options += [ "--ota" ] flashing_options += [ "ota_images/" ] diff --git a/third_party/bouffalolab/repo b/third_party/bouffalolab/repo index 9563086f233769..dc526317d2903c 160000 --- a/third_party/bouffalolab/repo +++ b/third_party/bouffalolab/repo @@ -1 +1 @@ -Subproject commit 9563086f233769db0163163307272f739d969cca +Subproject commit dc526317d2903c4d3a8466226983ce34dc8f23d1 diff --git a/third_party/mbedtls/repo b/third_party/mbedtls/repo index e5ae132d8742de..9abd09822cd8ae 160000 --- a/third_party/mbedtls/repo +++ b/third_party/mbedtls/repo @@ -1 +1 @@ -Subproject commit e5ae132d8742de5fc9548f8c52155031dd4d5dc6 +Subproject commit 9abd09822cd8ae6235887a050fd0dc8606401d79 diff --git a/third_party/open-iot-sdk/sdk b/third_party/open-iot-sdk/sdk new file mode 160000 index 00000000000000..e71066cfbe4e1d --- /dev/null +++ b/third_party/open-iot-sdk/sdk @@ -0,0 +1 @@ +Subproject commit e71066cfbe4e1dc21bcf0a88840ea8e88625de24 diff --git a/third_party/open-iot-sdk/storage b/third_party/open-iot-sdk/storage new file mode 160000 index 00000000000000..b5e4edc1b65ada --- /dev/null +++ b/third_party/open-iot-sdk/storage @@ -0,0 +1 @@ +Subproject commit b5e4edc1b65adafbe6f646c474bc8c206cd8370a diff --git a/zzz_generated/all-clusters-app/zap-generated/callback-stub.cpp b/zzz_generated/all-clusters-app/zap-generated/callback-stub.cpp index 79eb5a24243274..09b308d2728d12 100644 --- a/zzz_generated/all-clusters-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/all-clusters-app/zap-generated/callback-stub.cpp @@ -552,10 +552,6 @@ void __attribute__((weak)) emberAfWindowCoveringClusterInitCallback(EndpointId e // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -603,11 +599,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -616,12 +607,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/all-clusters-minimal-app/zap-generated/callback-stub.cpp b/zzz_generated/all-clusters-minimal-app/zap-generated/callback-stub.cpp index 1e748d603d754d..7e0e1471ee4836 100644 --- a/zzz_generated/all-clusters-minimal-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/all-clusters-minimal-app/zap-generated/callback-stub.cpp @@ -512,10 +512,6 @@ void __attribute__((weak)) emberAfWindowCoveringClusterInitCallback(EndpointId e // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -563,11 +559,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -576,12 +567,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/app-common/app-common/zap-generated/callback.h b/zzz_generated/app-common/app-common/zap-generated/callback.h index 8a674cd17d6c30..7e04ce7f7a70db 100644 --- a/zzz_generated/app-common/app-common/zap-generated/callback.h +++ b/zzz_generated/app-common/app-common/zap-generated/callback.h @@ -8926,29 +8926,6 @@ bool emberAfFaultInjectionClusterFailRandomlyAtFaultCallback( chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, const chip::app::Clusters::FaultInjection::Commands::FailRandomlyAtFault::DecodableType & commandData); -/** @brief Add To Current App Tasks - * - * This function is only useful to sleepy end devices. This function will note - * the passed item as part of a set of tasks the application has outstanding - * (e.g. message sent requiring APS acknwoledgement). This will affect how the - * application behaves with regard to sleeping and polling. Until the - * outstanding task is completed, the device may poll more frequently and sleep - * less often. - */ -void emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks); - -/** @brief Remove From Current App Tasks - * - * This function is only useful to sleepy end devices. This function will - * remove the passed item from the set of tasks the application has outstanding - * (e.g. message sent requiring APS acknwoledgement). This will affect how the - * application behaves with regard to sleeping and polling. Removing the item - * from the list of outstanding tasks may allow the device to sleep longer and - * poll less frequently. If there are other outstanding tasks the system may - * still have to stay away and poll more often. - */ -void emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks); - /** @brief Allow Network Write Attribute * * This function is called by the application framework before it writes an @@ -9116,17 +9093,6 @@ EmberAfStatus emberAfExternalAttributeReadCallback(chip::EndpointId endpoint, ch EmberAfStatus emberAfExternalAttributeWriteCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, const EmberAfAttributeMetadata * attributeMetadata, uint8_t * buffer); -/** @brief Get Current Time - * - * This callback is called when device attempts to get current time from the - * hardware. If this device has means to retrieve exact time, then this method - * should implement it. If the callback can't provide the exact time it should - * return 0 to indicate failure. Default action is to return 0, which indicates - * that device does not have access to real time. - * - */ -uint32_t emberAfGetCurrentTimeCallback(); - /** @brief Get Endpoint Info * * This function is a callback to an application implemented endpoint that @@ -9155,18 +9121,6 @@ bool emberAfGetEndpointInfoCallback(chip::EndpointId endpoint, uint8_t * returnN */ void emberAfRegistrationAbortCallback(); -/** @brief Interpan Send Message - * - * This function will send a raw MAC message with interpan frame format using - * the passed parameters. - * - * @param header Interpan header info Ver.: always - * @param messageLength The length of the message received or to send Ver.: - * always - * @param message The message data received or to send. Ver.: always - */ -EmberStatus emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message); - /** @brief Start Move * * This function is called to initiate the process for a device to move (rejoin) diff --git a/zzz_generated/bridge-app/zap-generated/callback-stub.cpp b/zzz_generated/bridge-app/zap-generated/callback-stub.cpp index d8149a41611f21..541da14da7d700 100644 --- a/zzz_generated/bridge-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/bridge-app/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-noip_rootnode_dimmablelight_bCwGYSDpoe/zap-generated/callback-stub.cpp b/zzz_generated/chef-noip_rootnode_dimmablelight_bCwGYSDpoe/zap-generated/callback-stub.cpp index b92b03791f095b..f460822e248777 100644 --- a/zzz_generated/chef-noip_rootnode_dimmablelight_bCwGYSDpoe/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-noip_rootnode_dimmablelight_bCwGYSDpoe/zap-generated/callback-stub.cpp @@ -256,10 +256,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -307,11 +303,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -320,12 +311,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_colortemperaturelight_hbUnzYVeyn/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_colortemperaturelight_hbUnzYVeyn/zap-generated/callback-stub.cpp index 2d5c943fb30d95..92618dd1a0f3b7 100644 --- a/zzz_generated/chef-rootnode_colortemperaturelight_hbUnzYVeyn/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_colortemperaturelight_hbUnzYVeyn/zap-generated/callback-stub.cpp @@ -208,10 +208,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -259,11 +255,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -272,12 +263,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_contactsensor_lFAGG1bfRO/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_contactsensor_lFAGG1bfRO/zap-generated/callback-stub.cpp index 0048f359fa28fd..4aa191ee7068a3 100644 --- a/zzz_generated/chef-rootnode_contactsensor_lFAGG1bfRO/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_contactsensor_lFAGG1bfRO/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_dimmablelight_bCwGYSDpoe/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_dimmablelight_bCwGYSDpoe/zap-generated/callback-stub.cpp index 6fd5c04396147f..14cd7146e757cf 100644 --- a/zzz_generated/chef-rootnode_dimmablelight_bCwGYSDpoe/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_dimmablelight_bCwGYSDpoe/zap-generated/callback-stub.cpp @@ -264,10 +264,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -315,11 +311,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -328,12 +319,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_doorlock_aNKYAreMXE/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_doorlock_aNKYAreMXE/zap-generated/callback-stub.cpp index 3b3dc275a244c9..3e7b15e961b1c0 100644 --- a/zzz_generated/chef-rootnode_doorlock_aNKYAreMXE/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_doorlock_aNKYAreMXE/zap-generated/callback-stub.cpp @@ -248,10 +248,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -299,11 +295,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -312,12 +303,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_extendedcolorlight_8lcaaYJVAa/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_extendedcolorlight_8lcaaYJVAa/zap-generated/callback-stub.cpp index 5203681136bcdb..285fd0785c31b0 100644 --- a/zzz_generated/chef-rootnode_extendedcolorlight_8lcaaYJVAa/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_extendedcolorlight_8lcaaYJVAa/zap-generated/callback-stub.cpp @@ -264,10 +264,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -315,11 +311,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -328,12 +319,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_fan_7N2TobIlOX/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_fan_7N2TobIlOX/zap-generated/callback-stub.cpp index 384f59484f7d6a..645b260573ac4b 100644 --- a/zzz_generated/chef-rootnode_fan_7N2TobIlOX/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_fan_7N2TobIlOX/zap-generated/callback-stub.cpp @@ -232,10 +232,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -283,11 +279,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -296,12 +287,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_flowsensor_1zVxHedlaV/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_flowsensor_1zVxHedlaV/zap-generated/callback-stub.cpp index e67653133c0dc2..97a91da04dceb1 100644 --- a/zzz_generated/chef-rootnode_flowsensor_1zVxHedlaV/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_flowsensor_1zVxHedlaV/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_heatingcoolingunit_ncdGai1E5a/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_heatingcoolingunit_ncdGai1E5a/zap-generated/callback-stub.cpp index 83427624f287f4..90490e899dc32a 100644 --- a/zzz_generated/chef-rootnode_heatingcoolingunit_ncdGai1E5a/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_heatingcoolingunit_ncdGai1E5a/zap-generated/callback-stub.cpp @@ -272,10 +272,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -323,11 +319,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -336,12 +327,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_humiditysensor_Xyj4gda6Hb/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_humiditysensor_Xyj4gda6Hb/zap-generated/callback-stub.cpp index 5b01c84b47b28d..11bf6c75676817 100644 --- a/zzz_generated/chef-rootnode_humiditysensor_Xyj4gda6Hb/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_humiditysensor_Xyj4gda6Hb/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_lightsensor_lZQycTFcJK/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_lightsensor_lZQycTFcJK/zap-generated/callback-stub.cpp index 5c1c2b4c85b0fe..b49ff9c7a1c649 100644 --- a/zzz_generated/chef-rootnode_lightsensor_lZQycTFcJK/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_lightsensor_lZQycTFcJK/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_occupancysensor_iHyVgifZuo/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_occupancysensor_iHyVgifZuo/zap-generated/callback-stub.cpp index f59b1abac8ceab..214bd4b6730dd3 100644 --- a/zzz_generated/chef-rootnode_occupancysensor_iHyVgifZuo/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_occupancysensor_iHyVgifZuo/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_onofflight_bbs1b7IaOV/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_onofflight_bbs1b7IaOV/zap-generated/callback-stub.cpp index 0c08973fe4c214..e2abf8824dff23 100644 --- a/zzz_generated/chef-rootnode_onofflight_bbs1b7IaOV/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_onofflight_bbs1b7IaOV/zap-generated/callback-stub.cpp @@ -256,10 +256,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -307,11 +303,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -320,12 +311,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_onofflightswitch_FsPlMr090Q/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_onofflightswitch_FsPlMr090Q/zap-generated/callback-stub.cpp index 165c3d1c54a5de..8982536e30bf4c 100644 --- a/zzz_generated/chef-rootnode_onofflightswitch_FsPlMr090Q/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_onofflightswitch_FsPlMr090Q/zap-generated/callback-stub.cpp @@ -248,10 +248,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -299,11 +295,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -312,12 +303,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_onoffpluginunit_Wtf8ss5EBY/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_onoffpluginunit_Wtf8ss5EBY/zap-generated/callback-stub.cpp index 165c3d1c54a5de..8982536e30bf4c 100644 --- a/zzz_generated/chef-rootnode_onoffpluginunit_Wtf8ss5EBY/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_onoffpluginunit_Wtf8ss5EBY/zap-generated/callback-stub.cpp @@ -248,10 +248,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -299,11 +295,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -312,12 +303,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_pressuresensor_s0qC9wLH4k/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_pressuresensor_s0qC9wLH4k/zap-generated/callback-stub.cpp index 9a94176c2694b4..16b27602629f9b 100644 --- a/zzz_generated/chef-rootnode_pressuresensor_s0qC9wLH4k/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_pressuresensor_s0qC9wLH4k/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_speaker_RpzeXdimqA/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_speaker_RpzeXdimqA/zap-generated/callback-stub.cpp index 6e356bf49c9130..9793b4ca0c6a0a 100644 --- a/zzz_generated/chef-rootnode_speaker_RpzeXdimqA/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_speaker_RpzeXdimqA/zap-generated/callback-stub.cpp @@ -248,10 +248,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -299,11 +295,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -312,12 +303,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_temperaturesensor_Qy1zkNW7c3/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_temperaturesensor_Qy1zkNW7c3/zap-generated/callback-stub.cpp index 44e831a55c94db..e09cdf1416122b 100644 --- a/zzz_generated/chef-rootnode_temperaturesensor_Qy1zkNW7c3/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_temperaturesensor_Qy1zkNW7c3/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_thermostat_bm3fb8dhYi/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_thermostat_bm3fb8dhYi/zap-generated/callback-stub.cpp index e65961f1fbfef8..a1d62f5d4d669c 100644 --- a/zzz_generated/chef-rootnode_thermostat_bm3fb8dhYi/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_thermostat_bm3fb8dhYi/zap-generated/callback-stub.cpp @@ -288,10 +288,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -339,11 +335,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -352,12 +343,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/chef-rootnode_windowcovering_RLCxaGi9Yx/zap-generated/callback-stub.cpp b/zzz_generated/chef-rootnode_windowcovering_RLCxaGi9Yx/zap-generated/callback-stub.cpp index f5e18ae9e2bcf9..21eca132a41332 100644 --- a/zzz_generated/chef-rootnode_windowcovering_RLCxaGi9Yx/zap-generated/callback-stub.cpp +++ b/zzz_generated/chef-rootnode_windowcovering_RLCxaGi9Yx/zap-generated/callback-stub.cpp @@ -248,10 +248,6 @@ void __attribute__((weak)) emberAfWindowCoveringClusterInitCallback(EndpointId e // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -299,11 +295,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -312,12 +303,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/contact-sensor-app/zap-generated/callback-stub.cpp b/zzz_generated/contact-sensor-app/zap-generated/callback-stub.cpp index c61d4b45f26c1b..ab1c733d78636f 100644 --- a/zzz_generated/contact-sensor-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/contact-sensor-app/zap-generated/callback-stub.cpp @@ -232,10 +232,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -283,11 +279,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -296,12 +287,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/controller-clusters/zap-generated/callback-stub.cpp b/zzz_generated/controller-clusters/zap-generated/callback-stub.cpp index 8258822775bbef..be2affbb2af6ed 100644 --- a/zzz_generated/controller-clusters/zap-generated/callback-stub.cpp +++ b/zzz_generated/controller-clusters/zap-generated/callback-stub.cpp @@ -560,10 +560,6 @@ void __attribute__((weak)) emberAfWindowCoveringClusterInitCallback(EndpointId e // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -611,11 +607,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -624,12 +615,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/dynamic-bridge-app/zap-generated/callback-stub.cpp b/zzz_generated/dynamic-bridge-app/zap-generated/callback-stub.cpp index d8149a41611f21..541da14da7d700 100644 --- a/zzz_generated/dynamic-bridge-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/dynamic-bridge-app/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/light-switch-app/zap-generated/callback-stub.cpp b/zzz_generated/light-switch-app/zap-generated/callback-stub.cpp index 1e70ab52a91a1d..897c9de6977933 100644 --- a/zzz_generated/light-switch-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/light-switch-app/zap-generated/callback-stub.cpp @@ -256,10 +256,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -307,11 +303,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -320,12 +311,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/lighting-app/nxp/zap-generated/callback-stub.cpp b/zzz_generated/lighting-app/nxp/zap-generated/callback-stub.cpp index b809a1f1b65cb6..ec1aaf37f421aa 100644 --- a/zzz_generated/lighting-app/nxp/zap-generated/callback-stub.cpp +++ b/zzz_generated/lighting-app/nxp/zap-generated/callback-stub.cpp @@ -176,10 +176,6 @@ void __attribute__((weak)) emberAfThreadNetworkDiagnosticsClusterInitCallback(En // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -227,11 +223,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -240,12 +231,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/lighting-app/zap-generated/callback-stub.cpp b/zzz_generated/lighting-app/zap-generated/callback-stub.cpp index 20850267856b32..24622a8683a9d6 100644 --- a/zzz_generated/lighting-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/lighting-app/zap-generated/callback-stub.cpp @@ -256,10 +256,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -307,11 +303,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -320,12 +311,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/lock-app/zap-generated/callback-stub.cpp b/zzz_generated/lock-app/zap-generated/callback-stub.cpp index 40b8a2a845ac46..93b96e4f0843bb 100644 --- a/zzz_generated/lock-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/lock-app/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/log-source-app/zap-generated/callback-stub.cpp b/zzz_generated/log-source-app/zap-generated/callback-stub.cpp index 5470d69131e3ae..48229d6cdb8258 100644 --- a/zzz_generated/log-source-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/log-source-app/zap-generated/callback-stub.cpp @@ -80,10 +80,6 @@ void __attribute__((weak)) emberAfOperationalCredentialsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -131,11 +127,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -144,12 +135,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/ota-provider-app/zap-generated/callback-stub.cpp b/zzz_generated/ota-provider-app/zap-generated/callback-stub.cpp index d20319aac67bb5..020697569e3d72 100644 --- a/zzz_generated/ota-provider-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/ota-provider-app/zap-generated/callback-stub.cpp @@ -144,10 +144,6 @@ void __attribute__((weak)) emberAfUserLabelClusterInitCallback(EndpointId endpoi // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -195,11 +191,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -208,12 +199,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/ota-requestor-app/zap-generated/callback-stub.cpp b/zzz_generated/ota-requestor-app/zap-generated/callback-stub.cpp index b0e6e30fa06011..576efe9e06c48a 100644 --- a/zzz_generated/ota-requestor-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/ota-requestor-app/zap-generated/callback-stub.cpp @@ -184,10 +184,6 @@ void __attribute__((weak)) emberAfUserLabelClusterInitCallback(EndpointId endpoi // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -235,11 +231,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -248,12 +239,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/placeholder/app1/zap-generated/callback-stub.cpp b/zzz_generated/placeholder/app1/zap-generated/callback-stub.cpp index 07638a5e37f466..3df9eb37e5199b 100644 --- a/zzz_generated/placeholder/app1/zap-generated/callback-stub.cpp +++ b/zzz_generated/placeholder/app1/zap-generated/callback-stub.cpp @@ -320,10 +320,6 @@ void __attribute__((weak)) emberAfWindowCoveringClusterInitCallback(EndpointId e // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -371,11 +367,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -384,12 +375,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/placeholder/app2/zap-generated/callback-stub.cpp b/zzz_generated/placeholder/app2/zap-generated/callback-stub.cpp index 07638a5e37f466..3df9eb37e5199b 100644 --- a/zzz_generated/placeholder/app2/zap-generated/callback-stub.cpp +++ b/zzz_generated/placeholder/app2/zap-generated/callback-stub.cpp @@ -320,10 +320,6 @@ void __attribute__((weak)) emberAfWindowCoveringClusterInitCallback(EndpointId e // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -371,11 +367,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -384,12 +375,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/pump-app/zap-generated/callback-stub.cpp b/zzz_generated/pump-app/zap-generated/callback-stub.cpp index e9fde2c7b8c439..9e7655fd485314 100644 --- a/zzz_generated/pump-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/pump-app/zap-generated/callback-stub.cpp @@ -208,10 +208,6 @@ void __attribute__((weak)) emberAfThreadNetworkDiagnosticsClusterInitCallback(En // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -259,11 +255,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -272,12 +263,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/pump-controller-app/zap-generated/callback-stub.cpp b/zzz_generated/pump-controller-app/zap-generated/callback-stub.cpp index 056f140ef38382..2d6f8da65eec40 100644 --- a/zzz_generated/pump-controller-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/pump-controller-app/zap-generated/callback-stub.cpp @@ -192,10 +192,6 @@ void __attribute__((weak)) emberAfThreadNetworkDiagnosticsClusterInitCallback(En // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -243,11 +239,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -256,12 +247,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/temperature-measurement-app/zap-generated/callback-stub.cpp b/zzz_generated/temperature-measurement-app/zap-generated/callback-stub.cpp index aed58a11790ccc..0117b746c3266c 100644 --- a/zzz_generated/temperature-measurement-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/temperature-measurement-app/zap-generated/callback-stub.cpp @@ -192,10 +192,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -243,11 +239,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -256,12 +247,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/thermostat/zap-generated/callback-stub.cpp b/zzz_generated/thermostat/zap-generated/callback-stub.cpp index 46ed91ffbe0fef..9a26400abe2037 100644 --- a/zzz_generated/thermostat/zap-generated/callback-stub.cpp +++ b/zzz_generated/thermostat/zap-generated/callback-stub.cpp @@ -248,10 +248,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -299,11 +295,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -312,12 +303,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/tv-app/zap-generated/callback-stub.cpp b/zzz_generated/tv-app/zap-generated/callback-stub.cpp index 7ec58577fea388..6f69c615598cec 100644 --- a/zzz_generated/tv-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/tv-app/zap-generated/callback-stub.cpp @@ -328,10 +328,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -379,11 +375,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -392,12 +383,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/tv-casting-app/zap-generated/callback-stub.cpp b/zzz_generated/tv-casting-app/zap-generated/callback-stub.cpp index 4ad54800c7a76f..83a5e52f00c4ac 100644 --- a/zzz_generated/tv-casting-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/tv-casting-app/zap-generated/callback-stub.cpp @@ -360,10 +360,6 @@ void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(Endp // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -411,11 +407,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -424,12 +415,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false; diff --git a/zzz_generated/window-app/zap-generated/callback-stub.cpp b/zzz_generated/window-app/zap-generated/callback-stub.cpp index 4f583b0d46ac58..401d2b68b1cda8 100644 --- a/zzz_generated/window-app/zap-generated/callback-stub.cpp +++ b/zzz_generated/window-app/zap-generated/callback-stub.cpp @@ -240,10 +240,6 @@ void __attribute__((weak)) emberAfWindowCoveringClusterInitCallback(EndpointId e // Non-Cluster Related Callbacks // -void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - -void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} - EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t * value, uint8_t type) @@ -291,11 +287,6 @@ emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, return EMBER_ZCL_STATUS_FAILURE; } -uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() -{ - return 0; -} - bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { @@ -304,12 +295,6 @@ emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex void __attribute__((weak)) emberAfRegistrationAbortCallback() {} -EmberStatus __attribute__((weak)) -emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) -{ - return EMBER_LIBRARY_NOT_PRESENT; -} - bool __attribute__((weak)) emberAfStartMoveCallback() { return false;