From 23228658f0bf52f475f61bc6fa196f5e8af9a47e Mon Sep 17 00:00:00 2001 From: Alex Tsitsiura Date: Fri, 2 Dec 2022 11:26:09 +0200 Subject: [PATCH] [Telink] Use latest Zephyr (SDK 0.15.2) & migrate to Zephyr BLE implementation & Update every image to 0.6.17 (#23827) * [Telink] Migrate to Telink Zephyr BLE implementation * [Telink] Rework to generic build configuration * [Telink] Fix problems for all apps after rebase Zephyr * [Telink] Telink update to latest Zephyr with BLE impl & Update every image to 0.6.17 * [Telink] Restyle * [Telink] code review fixes * [Telink] Fix build of ota-requstor-app * [Telink] increase build timeout for k32w * Fix BLE device name Function bt_enable() from zephyr resets device name to default value * Restyled by clang-format Co-authored-by: Andrii Bilynskyi Co-authored-by: Restyled.io --- .devcontainer/devcontainer.json | 2 +- .github/workflows/bloat_check.yaml | 2 +- .github/workflows/build.yaml | 6 +- .github/workflows/chef.yaml | 6 +- .github/workflows/cirque.yaml | 4 +- .github/workflows/doxygen.yaml | 2 +- .github/workflows/examples-ameba.yaml | 2 +- .github/workflows/examples-bouffalolab.yaml | 4 +- .../workflows/examples-cc13x2x7_26x2x7.yaml | 2 +- .github/workflows/examples-efr32.yaml | 2 +- .github/workflows/examples-esp32.yaml | 4 +- .github/workflows/examples-infineon.yaml | 2 +- .github/workflows/examples-k32w.yaml | 4 +- .github/workflows/examples-linux-arm.yaml | 2 +- .github/workflows/examples-linux-imx.yaml | 2 +- .../workflows/examples-linux-standalone.yaml | 2 +- .github/workflows/examples-mbed.yaml | 2 +- .github/workflows/examples-mw320.yaml | 2 +- .github/workflows/examples-nrfconnect.yaml | 2 +- .github/workflows/examples-qpg.yaml | 2 +- .github/workflows/examples-telink.yaml | 2 +- .github/workflows/examples-tizen.yaml | 2 +- .github/workflows/full-android.yaml | 2 +- .github/workflows/fuzzing-build.yaml | 2 +- .github/workflows/lint.yml | 2 +- .github/workflows/qemu.yaml | 2 +- .github/workflows/release_artifacts.yaml | 4 +- .github/workflows/smoketest-android.yaml | 2 +- .github/workflows/tests.yaml | 6 +- .github/workflows/unit_integration_test.yaml | 2 +- .github/workflows/zap_regeneration.yaml | 2 +- .github/workflows/zap_templates.yaml | 2 +- .gitmodules | 4 - build_overrides/telink.gni | 18 - config/telink/app/zephyr.conf | 22 +- config/telink/chip-gn/BUILD.gn | 14 +- config/telink/chip-module/CMakeLists.txt | 14 +- config/telink/chip-module/Kconfig | 6 - .../all-clusters-app/telink/CMakeLists.txt | 2 - .../telink/include/CHIPProjectConfig.h | 9 - examples/all-clusters-app/telink/prj.conf | 1 - .../telink/CMakeLists.txt | 2 - .../telink/include/CHIPProjectConfig.h | 9 - .../all-clusters-minimal-app/telink/prj.conf | 1 - .../light-switch-app/telink/CMakeLists.txt | 2 - .../telink/include/CHIPProjectConfig.h | 7 - examples/light-switch-app/telink/prj.conf | 1 - examples/lighting-app/telink/CMakeLists.txt | 2 - .../telink/include/CHIPProjectConfig.h | 12 +- examples/lighting-app/telink/prj.conf | 1 - .../telink/src/LightingManager.cpp | 2 +- .../ota-requestor-app/telink/CMakeLists.txt | 2 - .../telink/include/CHIPProjectConfig.h | 9 - examples/ota-requestor-app/telink/prj.conf | 1 - examples/thermostat/telink/CMakeLists.txt | 2 - .../telink/include/CHIPProjectConfig.h | 7 - examples/thermostat/telink/prj.conf | 1 - integrations/cloudbuild/build-all.yaml | 6 +- integrations/cloudbuild/build-coverage.yaml | 4 +- integrations/cloudbuild/chef.yaml | 6 +- integrations/cloudbuild/smoke-test.yaml | 14 +- src/controller/AutoCommissioner.cpp | 2 +- src/platform/Zephyr/CHIPDevicePlatformEvent.h | 2 +- src/platform/telink/BLEManagerImpl.cpp | 1239 +++++++---------- src/platform/telink/BLEManagerImpl.h | 123 +- src/platform/telink/BUILD.gn | 8 +- src/platform/telink/BlePlatformConfig.h | 8 +- .../telink/CHIPDevicePlatformConfig.h | 10 +- src/platform/telink/CHIPDevicePlatformEvent.h | 76 +- src/platform/telink/CHIPPlatformConfig.h | 28 +- src/platform/telink/FactoryDataProvider.h | 15 +- src/platform/telink/OTAImageProcessorImpl.cpp | 4 +- third_party/telink_sdk/BUILD.gn | 47 - third_party/telink_sdk/repo | 1 - 74 files changed, 714 insertions(+), 1116 deletions(-) delete mode 100644 build_overrides/telink.gni delete mode 100644 third_party/telink_sdk/BUILD.gn delete mode 160000 third_party/telink_sdk/repo diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index b5da6c153e4d7f..e40199d5f54307 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -17,7 +17,7 @@ "build": { "dockerfile": "Dockerfile", "args": { - "BUILD_VERSION": "0.6.06" + "BUILD_VERSION": "0.6.17" } }, "remoteUser": "vscode", diff --git a/.github/workflows/bloat_check.yaml b/.github/workflows/bloat_check.yaml index 8646c1c0f0550d..a1fe8de3a4a367 100644 --- a/.github/workflows/bloat_check.yaml +++ b/.github/workflows/bloat_check.yaml @@ -30,7 +30,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 steps: - uses: Wandalen/wretry.action@v1.0.36 diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 4a3ce8550c2e7e..3b2904617233a7 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -32,7 +32,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 volumes: - "/tmp/log_output:/tmp/test_logs" options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 @@ -133,7 +133,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 volumes: - "/tmp/log_output:/tmp/test_logs" options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 @@ -303,7 +303,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 volumes: - "/tmp/log_output:/tmp/test_logs" options: --sysctl "net.ipv6.conf.all.disable_ipv6=0 diff --git a/.github/workflows/chef.yaml b/.github/workflows/chef.yaml index 8f06a341f15dd7..d33d64e5baf429 100644 --- a/.github/workflows/chef.yaml +++ b/.github/workflows/chef.yaml @@ -29,7 +29,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 options: --user root steps: @@ -57,7 +57,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32:0.6.06 + image: connectedhomeip/chip-build-esp32:0.6.17 options: --user root steps: @@ -85,7 +85,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-nrf-platform:0.6.06 + image: connectedhomeip/chip-build-nrf-platform:0.6.17 options: --user root steps: diff --git a/.github/workflows/cirque.yaml b/.github/workflows/cirque.yaml index 950650638a14b9..459089b5286af5 100644 --- a/.github/workflows/cirque.yaml +++ b/.github/workflows/cirque.yaml @@ -29,7 +29,7 @@ jobs: timeout-minutes: 90 env: - DOCKER_RUN_VERSION: 0.6.06 + DOCKER_RUN_VERSION: 0.6.17 GITHUB_CACHE_PATH: /tmp/cirque-cache/ runs-on: ubuntu-latest @@ -38,7 +38,7 @@ jobs: # need to run with privilege, which isn't supported by job.XXX.contaner # https://github.com/actions/container-action/issues/2 # container: - # image: connectedhomeip/chip-build-cirque:0.6.06 + # image: connectedhomeip/chip-build-cirque:0.6.17 # volumes: # - "/tmp:/tmp" # - "/dev/pts:/dev/pts" diff --git a/.github/workflows/doxygen.yaml b/.github/workflows/doxygen.yaml index 675690ac97337c..5e654add16df04 100644 --- a/.github/workflows/doxygen.yaml +++ b/.github/workflows/doxygen.yaml @@ -82,7 +82,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build-doxygen:0.6.06 + image: connectedhomeip/chip-build-doxygen:0.6.17 if: github.actor != 'restyled-io[bot]' diff --git a/.github/workflows/examples-ameba.yaml b/.github/workflows/examples-ameba.yaml index e46876ba3aba3b..16f1dac307801f 100644 --- a/.github/workflows/examples-ameba.yaml +++ b/.github/workflows/examples-ameba.yaml @@ -32,7 +32,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-ameba:0.6.06 + image: connectedhomeip/chip-build-ameba:0.6.17 options: --user root steps: diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index 8e137c4738b281..2fbee87d14b155 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -31,7 +31,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-bouffalolab:0.6.12 + image: connectedhomeip/chip-build-bouffalolab:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: @@ -87,7 +87,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-bouffalolab:0.6.12 + image: connectedhomeip/chip-build-bouffalolab:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-cc13x2x7_26x2x7.yaml b/.github/workflows/examples-cc13x2x7_26x2x7.yaml index d1ebf8a7cca703..192c1ce4e5b965 100644 --- a/.github/workflows/examples-cc13x2x7_26x2x7.yaml +++ b/.github/workflows/examples-cc13x2x7_26x2x7.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-ti:0.6.06 + image: connectedhomeip/chip-build-ti:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-efr32.yaml b/.github/workflows/examples-efr32.yaml index d245cea56323f5..7ec57b528f8ec9 100644 --- a/.github/workflows/examples-efr32.yaml +++ b/.github/workflows/examples-efr32.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-efr32:0.6.06 + image: connectedhomeip/chip-build-efr32:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-esp32.yaml b/.github/workflows/examples-esp32.yaml index 9299ac3822c684..d58631614fc1d3 100644 --- a/.github/workflows/examples-esp32.yaml +++ b/.github/workflows/examples-esp32.yaml @@ -31,7 +31,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32:0.6.06 + image: connectedhomeip/chip-build-esp32:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -137,7 +137,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32:0.6.06 + image: connectedhomeip/chip-build-esp32:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-infineon.yaml b/.github/workflows/examples-infineon.yaml index 1f9fb326fe49d9..a5424b626892d6 100644 --- a/.github/workflows/examples-infineon.yaml +++ b/.github/workflows/examples-infineon.yaml @@ -32,7 +32,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-infineon:0.6.06 + image: connectedhomeip/chip-build-infineon:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-k32w.yaml b/.github/workflows/examples-k32w.yaml index 8df18b8485cf1b..890debf6989f57 100644 --- a/.github/workflows/examples-k32w.yaml +++ b/.github/workflows/examples-k32w.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-k32w:0.6.06 + image: connectedhomeip/chip-build-k32w:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: @@ -67,7 +67,7 @@ jobs: .environment/gn_out/.ninja_log .environment/pigweed-venv/*.log - name: Build examples - timeout-minutes: 30 + timeout-minutes: 40 run: | scripts/run_in_build_env.sh "\ ./scripts/build/build_examples.py \ diff --git a/.github/workflows/examples-linux-arm.yaml b/.github/workflows/examples-linux-arm.yaml index d43cfd557adcb6..deb4c5b83870b8 100644 --- a/.github/workflows/examples-linux-arm.yaml +++ b/.github/workflows/examples-linux-arm.yaml @@ -31,7 +31,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-crosscompile:0.6.06 + image: connectedhomeip/chip-build-crosscompile:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-linux-imx.yaml b/.github/workflows/examples-linux-imx.yaml index dbae52ae17833f..b10825a43506f0 100644 --- a/.github/workflows/examples-linux-imx.yaml +++ b/.github/workflows/examples-linux-imx.yaml @@ -31,7 +31,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-imx:0.6.06 + image: connectedhomeip/chip-build-imx:0.6.17 steps: - uses: Wandalen/wretry.action@v1.0.36 diff --git a/.github/workflows/examples-linux-standalone.yaml b/.github/workflows/examples-linux-standalone.yaml index 12f35418695f73..0d9a6f65ab124b 100644 --- a/.github/workflows/examples-linux-standalone.yaml +++ b/.github/workflows/examples-linux-standalone.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-mbed.yaml b/.github/workflows/examples-mbed.yaml index 442d520103e252..40df18d434ef59 100644 --- a/.github/workflows/examples-mbed.yaml +++ b/.github/workflows/examples-mbed.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-mbed-os:0.6.06 + image: connectedhomeip/chip-build-mbed-os:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-mw320.yaml b/.github/workflows/examples-mw320.yaml index 091a624a88d3b4..c0b8c9c53a987e 100755 --- a/.github/workflows/examples-mw320.yaml +++ b/.github/workflows/examples-mw320.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-nrfconnect.yaml b/.github/workflows/examples-nrfconnect.yaml index 4b9430d38a4b96..8aaeb88d833534 100644 --- a/.github/workflows/examples-nrfconnect.yaml +++ b/.github/workflows/examples-nrfconnect.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-nrf-platform:0.6.06 + image: connectedhomeip/chip-build-nrf-platform:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-qpg.yaml b/.github/workflows/examples-qpg.yaml index c5f97823e34d53..813318c8441aad 100644 --- a/.github/workflows/examples-qpg.yaml +++ b/.github/workflows/examples-qpg.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-telink.yaml b/.github/workflows/examples-telink.yaml index d4f1a9bd8f0991..eac0d95ba6dae8 100644 --- a/.github/workflows/examples-telink.yaml +++ b/.github/workflows/examples-telink.yaml @@ -32,7 +32,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-telink:0.6.06 + image: connectedhomeip/chip-build-telink:0.6.17 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-tizen.yaml b/.github/workflows/examples-tizen.yaml index 05fae3cba514fb..5776927bfcaaea 100644 --- a/.github/workflows/examples-tizen.yaml +++ b/.github/workflows/examples-tizen.yaml @@ -32,7 +32,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-tizen:0.6.06 + image: connectedhomeip/chip-build-tizen:0.6.17 options: --user root volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/full-android.yaml b/.github/workflows/full-android.yaml index dc038407f8edb7..457d727ce856bb 100644 --- a/.github/workflows/full-android.yaml +++ b/.github/workflows/full-android.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-android:0.6.06 + image: connectedhomeip/chip-build-android:0.6.17 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/fuzzing-build.yaml b/.github/workflows/fuzzing-build.yaml index 1999f806dc6329..c654404df084cc 100644 --- a/.github/workflows/fuzzing-build.yaml +++ b/.github/workflows/fuzzing-build.yaml @@ -31,7 +31,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 7e468d2e0acb87..c9f4fe41ac64e8 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -28,7 +28,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 steps: - uses: Wandalen/wretry.action@v1.0.36 diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index 8eb3b87abb441e..08e4c59f7a2ad6 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32-qemu:0.6.06 + image: connectedhomeip/chip-build-esp32-qemu:0.6.17 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/release_artifacts.yaml b/.github/workflows/release_artifacts.yaml index 4795f36bdcc6c5..e208c3df6c1cf2 100644 --- a/.github/workflows/release_artifacts.yaml +++ b/.github/workflows/release_artifacts.yaml @@ -29,7 +29,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build-esp32:0.6.06 + image: connectedhomeip/chip-build-esp32:0.6.17 steps: - uses: Wandalen/wretry.action@v1.0.36 @@ -75,7 +75,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build-efr32:0.6.06 + image: connectedhomeip/chip-build-efr32:0.6.17 steps: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout diff --git a/.github/workflows/smoketest-android.yaml b/.github/workflows/smoketest-android.yaml index 5874ba9f40c0db..63aaa6790efd68 100644 --- a/.github/workflows/smoketest-android.yaml +++ b/.github/workflows/smoketest-android.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-android:0.6.06 + image: connectedhomeip/chip-build-android:0.6.17 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 7382354870e6b3..ea0dc5d1e2806a 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -44,7 +44,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" @@ -347,7 +347,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" @@ -420,7 +420,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" diff --git a/.github/workflows/unit_integration_test.yaml b/.github/workflows/unit_integration_test.yaml index d1067b10e6bb94..959815a7963816 100644 --- a/.github/workflows/unit_integration_test.yaml +++ b/.github/workflows/unit_integration_test.yaml @@ -37,7 +37,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.06 + image: connectedhomeip/chip-build:0.6.17 volumes: - "/tmp/log_output:/tmp/test_logs" options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" diff --git a/.github/workflows/zap_regeneration.yaml b/.github/workflows/zap_regeneration.yaml index de120fdf4ce363..525ad2df160bf7 100644 --- a/.github/workflows/zap_regeneration.yaml +++ b/.github/workflows/zap_regeneration.yaml @@ -28,7 +28,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build:0.6.15 + image: connectedhomeip/chip-build:0.6.17 defaults: run: shell: sh diff --git a/.github/workflows/zap_templates.yaml b/.github/workflows/zap_templates.yaml index 1e7713b13c1b27..a806b6f605471b 100644 --- a/.github/workflows/zap_templates.yaml +++ b/.github/workflows/zap_templates.yaml @@ -29,7 +29,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build:0.6.15 + image: connectedhomeip/chip-build:0.6.17 defaults: run: shell: sh diff --git a/.gitmodules b/.gitmodules index 1d0e33d8b1f0f4..f211ca385789ff 100644 --- a/.gitmodules +++ b/.gitmodules @@ -220,10 +220,6 @@ path = third_party/infineon/psoc6/psoc6_sdk/libs/serial-flash url = https://github.com/Infineon/serial-flash platforms = infineon -[submodule "third_party/telink_sdk/repo"] - path = third_party/telink_sdk/repo - url = https://github.com/telink-semi/telink_b91_ble_single_connection_sdk_matter - platforms = telink [submodule "ti_simplelink_sdk"] path = third_party/ti_simplelink_sdk/repo_cc13xx_cc26xx url = https://github.com/TexasInstruments/cc13xx_cc26xx_sdk.git diff --git a/build_overrides/telink.gni b/build_overrides/telink.gni deleted file mode 100644 index 528fdc1c892f0c..00000000000000 --- a/build_overrides/telink.gni +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright (c) 2020-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. - -declare_args() { - # Root directory for Telink SDK. - telink_sdk_build_root = "//third_party/telink_sdk" -} diff --git a/config/telink/app/zephyr.conf b/config/telink/app/zephyr.conf index bd920eff8b4d49..1303fb6f060257 100644 --- a/config/telink/app/zephyr.conf +++ b/config/telink/app/zephyr.conf @@ -15,7 +15,6 @@ # CONFIG_CHIP=y - CONFIG_STD_CPP14=y # Logging @@ -31,6 +30,7 @@ CONFIG_NETWORKING=y CONFIG_NET_CONFIG_SETTINGS=y CONFIG_NET_SOCKETS=y CONFIG_NET_SOCKETS_POSIX_NAMES=n +CONFIG_NET_CONFIG_INIT_TIMEOUT=0 # Disable TCP and IPv4 (TCP disabled to avoid heavy traffic) CONFIG_NET_TCP=n @@ -58,7 +58,16 @@ CONFIG_NET_BUF_RX_COUNT=32 CONFIG_NET_BUF_TX_COUNT=32 # Bluetooth Low Energy configs -CONFIG_BT=n +CONFIG_BT=y +CONFIG_BT_DEBUG_LOG=n +CONFIG_BT_PERIPHERAL=y +CONFIG_BT_MAX_CONN=1 +CONFIG_BT_DEVICE_NAME_DYNAMIC=y +CONFIG_BT_GATT_DYNAMIC_DB=y +# CONFIG_BT_DEVICE_NAME_MAX=15 +CONFIG_BT_L2CAP_TX_MTU=247 +CONFIG_BT_BUF_ACL_RX_SIZE=251 +CONFIG_BT_BUF_ACL_TX_SIZE=251 # L2 OpenThread enabling CONFIG_NET_L2_OPENTHREAD=y @@ -66,7 +75,6 @@ CONFIG_OPENTHREAD_DEBUG=y CONFIG_OPENTHREAD_L2_DEBUG=y CONFIG_OPENTHREAD_L2_LOG_LEVEL_INF=y -CONFIG_NET_CONFIG_IEEE802154_DEV_NAME="IEEE802154_b91" CONFIG_NET_CONFIG_MY_IPV6_ADDR="fdde:ad00:beef::1" CONFIG_NET_CONFIG_PEER_IPV6_ADDR="fdde:ad00:beef::2" @@ -96,9 +104,6 @@ CONFIG_MBEDTLS_USER_CONFIG_FILE="telink-mbedtls-config.h" CONFIG_MBEDTLS_HEAP_SIZE=0 CONFIG_OPENTHREAD_EXTERNAL_HEAP=y -# Switch on Telink SDK -CONFIG_TELINK_BLE_LIB=y - # Config dynamic interrupts to have posibility to switch between BLE/Thread radio drivers CONFIG_DYNAMIC_INTERRUPTS=y @@ -108,4 +113,7 @@ CONFIG_SETTINGS_NVS_SECTOR_SIZE_MULT=8 # Shell settings CONFIG_SHELL=n -CONFIG_SHELL_BACKEND_SERIAL_RX_RING_BUFFER_SIZE=255 \ No newline at end of file +CONFIG_SHELL_BACKEND_SERIAL_RX_RING_BUFFER_SIZE=255 + +# Legacy +CONFIG_LEGACY_INCLUDE_PATH=y diff --git a/config/telink/chip-gn/BUILD.gn b/config/telink/chip-gn/BUILD.gn index 0d95e8a18e88a8..784c4ceab2563b 100644 --- a/config/telink/chip-gn/BUILD.gn +++ b/config/telink/chip-gn/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Project CHIP Authors +# Copyright (c) 2022 Project CHIP Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,9 +14,8 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/telink.gni") -import("${build_root}/chip/tests.gni") +import("${chip_root}/build/chip/tests.gni") assert(current_os == "zephyr") @@ -24,15 +23,8 @@ declare_args() { chip_build_example_providers = false } -declare_args() { - chip_build_pw_rpc_lib = false -} - group("telink") { - deps = [ - "${chip_root}/src/lib", - "${telink_sdk_build_root}", - ] + deps = [ "${chip_root}/src/lib" ] if (chip_build_tests) { deps += [ "${chip_root}/src:tests" ] diff --git a/config/telink/chip-module/CMakeLists.txt b/config/telink/chip-module/CMakeLists.txt index 6a48424b7f4832..b2f3da1eb9d135 100644 --- a/config/telink/chip-module/CMakeLists.txt +++ b/config/telink/chip-module/CMakeLists.txt @@ -129,10 +129,6 @@ if (CONFIG_CHIP_LIB_SHELL) list(APPEND CHIP_LIBRARIES -lCHIPShell) endif() -if (CONFIG_TELINK_BLE_LIB) - list(APPEND CHIP_LIBRARIES -lB91_ble_lib) -endif() - # Set up CHIP project configuration file if (CONFIG_CHIP_PROJECT_CONFIG) @@ -197,6 +193,7 @@ chip_gn_arg_string("zephyr_cxx" ${CMAKE_CXX_COMPILER chip_gn_arg_bool ("is_debug" CONFIG_DEBUG) chip_gn_arg_bool ("chip_enable_openthread" CONFIG_NET_L2_OPENTHREAD) chip_gn_arg_bool ("chip_openthread_ftd" CONFIG_OPENTHREAD_FTD) +chip_gn_arg_bool ("chip_config_network_layer_ble" CONFIG_BT) chip_gn_arg_bool ("chip_inet_config_enable_ipv4" CONFIG_NET_IPV4) chip_gn_arg_bool ("chip_enable_ota_requestor" CONFIG_CHIP_OTA_REQUESTOR) chip_gn_arg_bool ("chip_build_tests" CONFIG_CHIP_BUILD_TESTS) @@ -276,7 +273,8 @@ target_include_directories(chip INTERFACE ${CHIP_ROOT}/src/include ${CHIP_ROOT}/src/lib ${CHIP_ROOT}/third_party/nlassert/repo/include - ${CHIP_ROOT}/third_party/telink_sdk + ${CHIP_ROOT}/third_party/nlio/repo/include + ${CHIP_ROOT}/zzz_generated/app-common ${CMAKE_CURRENT_BINARY_DIR}/gen/include ) target_link_directories(chip INTERFACE ${CMAKE_CURRENT_BINARY_DIR}/lib) @@ -288,10 +286,6 @@ if (CONFIG_CHIP_EXAMPLE_DEVICE_INFO_PROVIDER) target_include_directories(chip INTERFACE ${CHIP_ROOT}/examples/providers) endif() -if (CONFIG_TELINK_BLE_LIB) - target_link_directories(chip INTERFACE ${CHIP_ROOT}/third_party/telink_sdk/repo/eagle_ble_sdk/proj_lib) -endif() - target_link_libraries(chip INTERFACE -Wl,--start-group ${CHIP_LIBRARIES} -Wl,--end-group) add_dependencies(chip chip-gn) @@ -308,7 +302,7 @@ if (CONFIG_CHIP_OTA_IMAGE_BUILD) add_custom_target(west_sign ALL COMMAND - west sign -t imgtool -p ${ZEPHYR_BASE}/../bootloader/mcuboot/scripts/imgtool.py -d ${PROJECT_BINARY_DIR}/.. -- --key ${ZEPHYR_BASE}/../bootloader/mcuboot/root-rsa-2048.pem + west sign -t imgtool -p ${ZEPHYR_BASE}/../bootloader/mcuboot/scripts/imgtool.py -d ${PROJECT_BINARY_DIR}/.. -- --pad-header --key ${ZEPHYR_BASE}/../bootloader/mcuboot/root-rsa-2048.pem ) add_custom_target(merge_mcuboot ALL diff --git a/config/telink/chip-module/Kconfig b/config/telink/chip-module/Kconfig index f216280df7e583..db442126a2c14e 100644 --- a/config/telink/chip-module/Kconfig +++ b/config/telink/chip-module/Kconfig @@ -16,12 +16,6 @@ rsource "../../zephyr/Kconfig" -config TELINK_BLE_LIB - bool "Include third party Telink BLE SDK" - default n - help - Include third party Telink BLE SDK - # See config/zephyr/Kconfig for full definition config CHIP_OTA_REQUESTOR bool diff --git a/examples/all-clusters-app/telink/CMakeLists.txt b/examples/all-clusters-app/telink/CMakeLists.txt index 553dcc8113bb53..6e9dd95f0e84ec 100644 --- a/examples/all-clusters-app/telink/CMakeLists.txt +++ b/examples/all-clusters-app/telink/CMakeLists.txt @@ -18,7 +18,6 @@ cmake_minimum_required(VERSION 3.13.1) set(BOARD tlsr9518adk80d) get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/third_party/connectedhomeip REALPATH) -get_filename_component(NLIO_ROOT ${CHIP_ROOT}/third_party/nlio/repo/include REALPATH) get_filename_component(TELINK_COMMON ${CHIP_ROOT}/examples/platform/telink REALPATH) get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH) get_filename_component(ALL_CLUSTERS_COMMON_DIR ${CHIP_ROOT}/examples/all-clusters-app/all-clusters-common REALPATH) @@ -41,7 +40,6 @@ target_include_directories(app PRIVATE ${ALL_CLUSTERS_COMMON_DIR}/include ${GEN_DIR}/app-common ${GEN_DIR}/all-clusters-app - ${NLIO_ROOT} ${TELINK_COMMON}/util/include) add_definitions( diff --git a/examples/all-clusters-app/telink/include/CHIPProjectConfig.h b/examples/all-clusters-app/telink/include/CHIPProjectConfig.h index 9cfa65977d1717..2fda70c57da9dc 100644 --- a/examples/all-clusters-app/telink/include/CHIPProjectConfig.h +++ b/examples/all-clusters-app/telink/include/CHIPProjectConfig.h @@ -31,18 +31,9 @@ #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 -/** - * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - * - * Enable support for Chip-over-BLE (CHIPoBLE). - */ -#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 - /** * CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE * * Reduce packet buffer pool size to 8 (default 15) to reduce ram consumption */ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 8 - -#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 diff --git a/examples/all-clusters-app/telink/prj.conf b/examples/all-clusters-app/telink/prj.conf index 01b93d52feba2c..6c7821f2c87ec7 100644 --- a/examples/all-clusters-app/telink/prj.conf +++ b/examples/all-clusters-app/telink/prj.conf @@ -30,7 +30,6 @@ CONFIG_OPENTHREAD_PANID=4660 CONFIG_OPENTHREAD_CHANNEL=15 CONFIG_OPENTHREAD_NETWORK_NAME="OpenThreadDemo" CONFIG_OPENTHREAD_XPANID="11:11:11:11:22:22:22:22" -CONFIG_NET_CONFIG_IEEE802154_DEV_NAME="IEEE802154_b91" # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/all-clusters-minimal-app/telink/CMakeLists.txt b/examples/all-clusters-minimal-app/telink/CMakeLists.txt index ecf0efd6aff84a..9f0c60f81af439 100644 --- a/examples/all-clusters-minimal-app/telink/CMakeLists.txt +++ b/examples/all-clusters-minimal-app/telink/CMakeLists.txt @@ -18,7 +18,6 @@ cmake_minimum_required(VERSION 3.13.1) set(BOARD tlsr9518adk80d) get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/third_party/connectedhomeip REALPATH) -get_filename_component(NLIO_ROOT ${CHIP_ROOT}/third_party/nlio/repo/include REALPATH) get_filename_component(TELINK_COMMON ${CHIP_ROOT}/examples/platform/telink REALPATH) get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH) get_filename_component(ALL_CLUSTERS_COMMON_DIR ${CHIP_ROOT}/examples/all-clusters-app/all-clusters-common REALPATH) @@ -41,7 +40,6 @@ target_include_directories(app PRIVATE ${ALL_CLUSTERS_COMMON_DIR}/include ${GEN_DIR}/app-common ${GEN_DIR}/all-clusters-minimal-app - ${NLIO_ROOT} ${TELINK_COMMON}/util/include) add_definitions( diff --git a/examples/all-clusters-minimal-app/telink/include/CHIPProjectConfig.h b/examples/all-clusters-minimal-app/telink/include/CHIPProjectConfig.h index 9cfa65977d1717..2fda70c57da9dc 100644 --- a/examples/all-clusters-minimal-app/telink/include/CHIPProjectConfig.h +++ b/examples/all-clusters-minimal-app/telink/include/CHIPProjectConfig.h @@ -31,18 +31,9 @@ #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 -/** - * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - * - * Enable support for Chip-over-BLE (CHIPoBLE). - */ -#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 - /** * CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE * * Reduce packet buffer pool size to 8 (default 15) to reduce ram consumption */ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 8 - -#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 diff --git a/examples/all-clusters-minimal-app/telink/prj.conf b/examples/all-clusters-minimal-app/telink/prj.conf index 791807a463a9e0..0d56373b56dffe 100644 --- a/examples/all-clusters-minimal-app/telink/prj.conf +++ b/examples/all-clusters-minimal-app/telink/prj.conf @@ -30,7 +30,6 @@ CONFIG_OPENTHREAD_PANID=4660 CONFIG_OPENTHREAD_CHANNEL=15 CONFIG_OPENTHREAD_NETWORK_NAME="OpenThreadDemo" CONFIG_OPENTHREAD_XPANID="11:11:11:11:22:22:22:22" -CONFIG_NET_CONFIG_IEEE802154_DEV_NAME="IEEE802154_b91" # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/light-switch-app/telink/CMakeLists.txt b/examples/light-switch-app/telink/CMakeLists.txt index 892190ddf4b59f..40b9490510d47a 100755 --- a/examples/light-switch-app/telink/CMakeLists.txt +++ b/examples/light-switch-app/telink/CMakeLists.txt @@ -18,7 +18,6 @@ cmake_minimum_required(VERSION 3.13.1) set(BOARD tlsr9518adk80d) get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/third_party/connectedhomeip REALPATH) -get_filename_component(NLIO_ROOT ${CHIP_ROOT}/third_party/nlio/repo/include REALPATH) get_filename_component(TELINK_COMMON ${CHIP_ROOT}/examples/platform/telink REALPATH) get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH) @@ -39,7 +38,6 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/light-switch-app - ${NLIO_ROOT} ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) diff --git a/examples/light-switch-app/telink/include/CHIPProjectConfig.h b/examples/light-switch-app/telink/include/CHIPProjectConfig.h index ade0219ab5da91..2fda70c57da9dc 100755 --- a/examples/light-switch-app/telink/include/CHIPProjectConfig.h +++ b/examples/light-switch-app/telink/include/CHIPProjectConfig.h @@ -31,13 +31,6 @@ #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 -/** - * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - * - * Enable support for Chip-over-BLE (CHIPoBLE). - */ -#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 - /** * CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE * diff --git a/examples/light-switch-app/telink/prj.conf b/examples/light-switch-app/telink/prj.conf index 1366c5f0e952fb..54b941ef6b2fc5 100755 --- a/examples/light-switch-app/telink/prj.conf +++ b/examples/light-switch-app/telink/prj.conf @@ -33,7 +33,6 @@ CONFIG_OPENTHREAD_PANID=4660 CONFIG_OPENTHREAD_CHANNEL=15 CONFIG_OPENTHREAD_NETWORK_NAME="OpenThreadDemo" CONFIG_OPENTHREAD_XPANID="11:11:11:11:22:22:22:22" -CONFIG_NET_CONFIG_IEEE802154_DEV_NAME="IEEE802154_b91" # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/lighting-app/telink/CMakeLists.txt b/examples/lighting-app/telink/CMakeLists.txt index 1cf675a23bab7b..5beea781359c18 100644 --- a/examples/lighting-app/telink/CMakeLists.txt +++ b/examples/lighting-app/telink/CMakeLists.txt @@ -18,7 +18,6 @@ cmake_minimum_required(VERSION 3.13.1) set(BOARD tlsr9518adk80d) get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/third_party/connectedhomeip REALPATH) -get_filename_component(NLIO_ROOT ${CHIP_ROOT}/third_party/nlio/repo/include REALPATH) get_filename_component(TELINK_COMMON ${CHIP_ROOT}/examples/platform/telink REALPATH) get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH) @@ -39,7 +38,6 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/lighting-app - ${NLIO_ROOT} ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) diff --git a/examples/lighting-app/telink/include/CHIPProjectConfig.h b/examples/lighting-app/telink/include/CHIPProjectConfig.h index 43adb45f85f50b..76d4372a80703f 100644 --- a/examples/lighting-app/telink/include/CHIPProjectConfig.h +++ b/examples/lighting-app/telink/include/CHIPProjectConfig.h @@ -31,12 +31,10 @@ #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 -/** - * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - * - * Enable support for Chip-over-BLE (CHIPoBLE). - */ -#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 +// Switching from Thread child to router may cause a few second packet stall. +// Until this is improved in OpenThread we need to increase the retransmission +// interval to survive the stall. +#define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL (1000_ms32) /** * CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE @@ -44,5 +42,3 @@ * Reduce packet buffer pool size to 8 (default 15) to reduce ram consumption */ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 8 - -#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 diff --git a/examples/lighting-app/telink/prj.conf b/examples/lighting-app/telink/prj.conf index 3de670dd34bf07..25a0a15bccd265 100644 --- a/examples/lighting-app/telink/prj.conf +++ b/examples/lighting-app/telink/prj.conf @@ -33,7 +33,6 @@ CONFIG_OPENTHREAD_PANID=4660 CONFIG_OPENTHREAD_CHANNEL=15 CONFIG_OPENTHREAD_NETWORK_NAME="OpenThreadDemo" CONFIG_OPENTHREAD_XPANID="11:11:11:11:22:22:22:22" -CONFIG_NET_CONFIG_IEEE802154_DEV_NAME="IEEE802154_b91" # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/lighting-app/telink/src/LightingManager.cpp b/examples/lighting-app/telink/src/LightingManager.cpp index 3aad922a3516af..1c0cea74bb5cce 100644 --- a/examples/lighting-app/telink/src/LightingManager.cpp +++ b/examples/lighting-app/telink/src/LightingManager.cpp @@ -132,5 +132,5 @@ void LightingManager::UpdateLight() const uint8_t maxEffectiveLevel = mMaxLevel - mMinLevel; const uint8_t effectiveLevel = mState == kState_On ? chip::min(mLevel - mMinLevel, maxEffectiveLevel) : 0; - pwm_pin_set_usec(mPwmDevice, mPwmChannel, kPwmWidthUs, kPwmWidthUs * effectiveLevel / maxEffectiveLevel, 0); + pwm_set(mPwmDevice, mPwmChannel, PWM_USEC(kPwmWidthUs), PWM_USEC(kPwmWidthUs * effectiveLevel / maxEffectiveLevel), 0); } diff --git a/examples/ota-requestor-app/telink/CMakeLists.txt b/examples/ota-requestor-app/telink/CMakeLists.txt index c30aa60e529cdb..6b634ce3eb5dbc 100644 --- a/examples/ota-requestor-app/telink/CMakeLists.txt +++ b/examples/ota-requestor-app/telink/CMakeLists.txt @@ -18,7 +18,6 @@ cmake_minimum_required(VERSION 3.13.1) set(BOARD tlsr9518adk80d) get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/third_party/connectedhomeip REALPATH) -get_filename_component(NLIO_ROOT ${CHIP_ROOT}/third_party/nlio/repo/include REALPATH) get_filename_component(TELINK_COMMON ${CHIP_ROOT}/examples/platform/telink REALPATH) get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH) @@ -39,7 +38,6 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/ota-requestor-app - ${NLIO_ROOT} ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) diff --git a/examples/ota-requestor-app/telink/include/CHIPProjectConfig.h b/examples/ota-requestor-app/telink/include/CHIPProjectConfig.h index 9cfa65977d1717..2fda70c57da9dc 100644 --- a/examples/ota-requestor-app/telink/include/CHIPProjectConfig.h +++ b/examples/ota-requestor-app/telink/include/CHIPProjectConfig.h @@ -31,18 +31,9 @@ #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 -/** - * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - * - * Enable support for Chip-over-BLE (CHIPoBLE). - */ -#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 - /** * CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE * * Reduce packet buffer pool size to 8 (default 15) to reduce ram consumption */ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 8 - -#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 diff --git a/examples/ota-requestor-app/telink/prj.conf b/examples/ota-requestor-app/telink/prj.conf index 7f270da20b8e5f..c801f50ac570a7 100755 --- a/examples/ota-requestor-app/telink/prj.conf +++ b/examples/ota-requestor-app/telink/prj.conf @@ -30,7 +30,6 @@ CONFIG_OPENTHREAD_PANID=4660 CONFIG_OPENTHREAD_CHANNEL=15 CONFIG_OPENTHREAD_NETWORK_NAME="OpenThreadDemo" CONFIG_OPENTHREAD_XPANID="11:11:11:11:22:22:22:22" -CONFIG_NET_CONFIG_IEEE802154_DEV_NAME="IEEE802154_b91" # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=y diff --git a/examples/thermostat/telink/CMakeLists.txt b/examples/thermostat/telink/CMakeLists.txt index 78b4f7c7dcf883..6d00c892a2ed72 100755 --- a/examples/thermostat/telink/CMakeLists.txt +++ b/examples/thermostat/telink/CMakeLists.txt @@ -18,7 +18,6 @@ cmake_minimum_required(VERSION 3.13.1) set(BOARD tlsr9518adk80d) get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/third_party/connectedhomeip REALPATH) -get_filename_component(NLIO_ROOT ${CHIP_ROOT}/third_party/nlio/repo/include REALPATH) get_filename_component(TELINK_COMMON ${CHIP_ROOT}/examples/platform/telink REALPATH) get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH) @@ -39,7 +38,6 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/thermostat - ${NLIO_ROOT} ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) diff --git a/examples/thermostat/telink/include/CHIPProjectConfig.h b/examples/thermostat/telink/include/CHIPProjectConfig.h index ade0219ab5da91..2fda70c57da9dc 100755 --- a/examples/thermostat/telink/include/CHIPProjectConfig.h +++ b/examples/thermostat/telink/include/CHIPProjectConfig.h @@ -31,13 +31,6 @@ #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 -/** - * CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - * - * Enable support for Chip-over-BLE (CHIPoBLE). - */ -#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 - /** * CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE * diff --git a/examples/thermostat/telink/prj.conf b/examples/thermostat/telink/prj.conf index ad1e20d32e9b78..f07c4e4ca70f3d 100755 --- a/examples/thermostat/telink/prj.conf +++ b/examples/thermostat/telink/prj.conf @@ -30,7 +30,6 @@ CONFIG_OPENTHREAD_PANID=4660 CONFIG_OPENTHREAD_CHANNEL=15 CONFIG_OPENTHREAD_NETWORK_NAME="OpenThreadDemo" CONFIG_OPENTHREAD_XPANID="11:11:11:11:22:22:22:22" -CONFIG_NET_CONFIG_IEEE802154_DEV_NAME="IEEE802154_b91" # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/integrations/cloudbuild/build-all.yaml b/integrations/cloudbuild/build-all.yaml index e0dbcfaa61467c..c1110599d1fe59 100644 --- a/integrations/cloudbuild/build-all.yaml +++ b/integrations/cloudbuild/build-all.yaml @@ -6,7 +6,7 @@ steps: - "--init" - "--recursive" id: Submodules - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -21,7 +21,7 @@ steps: path: /pwenv timeout: 900s - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -76,7 +76,7 @@ steps: --target k32w-shell build --create-archives /workspace/artifacts/ - - name: "connectedhomeip/chip-build-vscode:0.6.03" + - name: "connectedhomeip/chip-build-vscode:0.6.17" env: - PW_ENVIRONMENT_ROOT=/pwenv args: diff --git a/integrations/cloudbuild/build-coverage.yaml b/integrations/cloudbuild/build-coverage.yaml index cc85632b50e7e5..a5cfc4d22661e2 100644 --- a/integrations/cloudbuild/build-coverage.yaml +++ b/integrations/cloudbuild/build-coverage.yaml @@ -7,7 +7,7 @@ steps: - "--recursive" id: Submodules - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -22,7 +22,7 @@ steps: path: /pwenv timeout: 900s - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" env: - PW_ENVIRONMENT_ROOT=/pwenv args: diff --git a/integrations/cloudbuild/chef.yaml b/integrations/cloudbuild/chef.yaml index 7fcdb111ed8e0f..859f2c97ebe1ad 100644 --- a/integrations/cloudbuild/chef.yaml +++ b/integrations/cloudbuild/chef.yaml @@ -1,5 +1,5 @@ steps: - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -12,7 +12,7 @@ steps: path: /pwenv timeout: 2700s - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -26,7 +26,7 @@ steps: - name: pwenv path: /pwenv - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" env: - PW_ENVIRONMENT_ROOT=/pwenv args: diff --git a/integrations/cloudbuild/smoke-test.yaml b/integrations/cloudbuild/smoke-test.yaml index a5d491519965b2..658279648c61ca 100644 --- a/integrations/cloudbuild/smoke-test.yaml +++ b/integrations/cloudbuild/smoke-test.yaml @@ -1,5 +1,5 @@ steps: - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" entrypoint: "bash" args: - "-c" @@ -7,7 +7,7 @@ steps: git config --global --add safe.directory "*" git submodule update --init --recursive id: Submodules - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -22,7 +22,7 @@ steps: path: /pwenv timeout: 900s - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" id: ESP32 env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -41,7 +41,7 @@ steps: - name: pwenv path: /pwenv - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" id: NRFConnect env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -62,7 +62,7 @@ steps: - name: pwenv path: /pwenv - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" id: EFR32 env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -84,7 +84,7 @@ steps: - name: pwenv path: /pwenv - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" id: Linux env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -142,7 +142,7 @@ steps: - name: pwenv path: /pwenv - - name: "connectedhomeip/chip-build-vscode:0.6.06" + - name: "connectedhomeip/chip-build-vscode:0.6.17" id: Android env: - PW_ENVIRONMENT_ROOT=/pwenv diff --git a/src/controller/AutoCommissioner.cpp b/src/controller/AutoCommissioner.cpp index 579d9c2d31dab1..982f62765bace6 100644 --- a/src/controller/AutoCommissioner.cpp +++ b/src/controller/AutoCommissioner.cpp @@ -109,7 +109,7 @@ CHIP_ERROR AutoCommissioner::SetCommissioningParameters(const CommissioningParam if (params.GetCountryCode().HasValue()) { - auto & code = params.GetCountryCode().Value(); + auto code = params.GetCountryCode().Value(); MutableCharSpan copiedCode(mCountryCode); if (CopyCharSpanToMutableCharSpan(code, copiedCode) == CHIP_NO_ERROR) { diff --git a/src/platform/Zephyr/CHIPDevicePlatformEvent.h b/src/platform/Zephyr/CHIPDevicePlatformEvent.h index 5687945287c2b1..ff329ec7590ea0 100644 --- a/src/platform/Zephyr/CHIPDevicePlatformEvent.h +++ b/src/platform/Zephyr/CHIPDevicePlatformEvent.h @@ -25,7 +25,7 @@ #include -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/telink/BLEManagerImpl.cpp b/src/platform/telink/BLEManagerImpl.cpp index d07b2ca3a30459..d22a2a8ddbec08 100644 --- a/src/platform/telink/BLEManagerImpl.cpp +++ b/src/platform/telink/BLEManagerImpl.cpp @@ -18,31 +18,32 @@ /** * @file * Provides an implementation of the BLEManager singleton object - * for the Telink platform. + * for Telink platforms. */ -/* this file behaves like a config.h, comes first */ + #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include -#include -#include +#include +#include #include #include +#include +#include +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING +#include +#endif -/*Includes for ieee802154 switchings */ -#define DT_DRV_COMPAT telink_b91_zb -#include -#include +#include +#include +#include +#include +#include -/* Telink headers */ -#include "drivers.h" -#include "ext_driver/ext_misc.h" -#include "stack/ble/ble.h" -#include "tl_common.h" -#include "types.h" +// Includes for ieee802154 switchings +#include using namespace ::chip; using namespace ::chip::Ble; @@ -54,80 +55,16 @@ namespace Internal { namespace { -typedef enum -{ - ATT_H_START = 0, - - /* GAP service */ - GenericAccess_PS_H, // UUID: 2800, VALUE: uuid 1800 - GenericAccess_DeviceName_CD_H, // UUID: 2803, VALUE: Prop: Read | Notify - GenericAccess_DeviceName_DP_H, // UUID: 2A00, VALUE: device name - GenericAccess_Appearance_CD_H, // UUID: 2803, VALUE: Prop: Read - GenericAccess_Appearance_DP_H, // UUID: 2A01, VALUE: appearance - CONN_PARAM_CD_H, // UUID: 2803, VALUE: Prop: Read - CONN_PARAM_DP_H, // UUID: 2A04, VALUE: connParameter - - /* GATT service */ - GenericAttribute_PS_H, // UUID: 2800, VALUE: uuid 1801 - GenericAttribute_ServiceChanged_CD_H, // UUID: 2803, VALUE: Prop: Indicate - GenericAttribute_ServiceChanged_DP_H, // UUID: 2A05, VALUE: service change - GenericAttribute_ServiceChanged_CCB_H, // UUID: 2902, VALUE: serviceChangeCCC - - /* Matter service */ - Matter_PS_H, - Matter_RX_CD_H, - Matter_RX_DP_H, - Matter_TX_CD_H, - Matter_TX_DP_H, - Matter_TX_CCC_H, - - ATT_END_H, - -} ATT_HANDLE; - -typedef struct -{ - /** Minimum value for the connection event (interval. 0x0006 - 0x0C80 * 1.25 ms) */ - u16 intervalMin; - /** Maximum value for the connection event (interval. 0x0006 - 0x0C80 * 1.25 ms) */ - u16 intervalMax; - /** Number of LL latency connection events (0x0000 - 0x03e8) */ - u16 latency; - /** Connection Timeout (0x000A - 0x0C80 * 10 ms) */ - u16 timeout; -} gap_periConnectParams_t; - -#define CHIP_MAC_LEN 6 -#define CHIP_MTU_SIZE 244 -#define CHIP_MAX_ADV_DATA_LEN 31 -#define CHIP_MAX_RESPONSE_DATA_LEN 31 -#define CHIP_SHORT_UUID_LEN 2 - -#define CHIP_ADE_DATA_LEN_FLAGS 0x02 -#define CHIP_ADV_DATA_TYPE_FLAGS 0x01 -#define CHIP_ADV_DATA_FLAGS 0x06 -#define CHIP_ADV_DATA_TYPE_UUID 0x03 -#define CHIP_ADV_DATA_TYPE_NAME 0x09 -#define CHIP_ADV_DATA_TYPE_SERVICE_DATA 0x16 -#define CHIP_ADV_SERVICE_DATA_LEN (sizeof(ChipBLEDeviceIdentificationInfo) + CHIP_SHORT_UUID_LEN + 1) - -#define CHIP_BLE_TX_FIFO_SIZE 48 -#define CHIP_BLE_TX_FIFO_NUM 33 -#define CHIP_BLE_RX_FIFO_SIZE 48 -#define CHIP_BLE_RX_FIFO_NUM 8 - -#define CHIP_BLE_THREAD_STACK_SIZE 2048 -#define CHIP_BLE_THREAD_PRIORITY 2 - -#define CHIP_BLE_DISCONNECT_REASON 8 - -#define CHIP_RF_PACKET_HEADER_SIZE 3 - -#define STIMER_IRQ_NUM 1 -#define RF_IRQ_NUM 15 - -#define CHIP_RX_CHAR_UUID 0x11, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18 -#define CHIP_TX_CHAR_UUID 0x12, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18 +const bt_uuid_128 UUID128_CHIPoBLEChar_RX = + BT_UUID_INIT_128(0x11, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18); +const bt_uuid_128 UUID128_CHIPoBLEChar_TX = + BT_UUID_INIT_128(0x12, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18); +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING +const bt_uuid_128 UUID128_CHIPoBLEChar_C3 = + BT_UUID_INIT_128(0x04, 0x8F, 0x21, 0x83, 0x8A, 0x74, 0x7D, 0xB8, 0xF2, 0x45, 0x72, 0x87, 0x38, 0x02, 0x63, 0x64); +#endif + +bt_uuid_16 UUID16_CHIPoBLEService = BT_UUID_INIT_16(0xFFF6); const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x11 } }; @@ -135,39 +72,80 @@ const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0 const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x12 } }; -static const uint8_t matterServiceUUID[CHIP_SHORT_UUID_LEN] = { 0xF6, 0xFF }; // service UUID +_bt_gatt_ccc CHIPoBLEChar_TX_CCC = BT_GATT_CCC_INITIALIZER(nullptr, BLEManagerImpl::HandleTXCCCWrite, nullptr); + +// clang-format off + +struct bt_gatt_attr sChipoBleAttributes[] = { + BT_GATT_PRIMARY_SERVICE(&UUID16_CHIPoBLEService.uuid), + BT_GATT_CHARACTERISTIC(&UUID128_CHIPoBLEChar_RX.uuid, + BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + nullptr, BLEManagerImpl::HandleRXWrite, nullptr), + BT_GATT_CHARACTERISTIC(&UUID128_CHIPoBLEChar_TX.uuid, + BT_GATT_CHRC_INDICATE, + BT_GATT_PERM_NONE, + nullptr, nullptr, nullptr), + BT_GATT_CCC_MANAGED(&CHIPoBLEChar_TX_CCC, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE), +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + BT_GATT_CHARACTERISTIC(&UUID128_CHIPoBLEChar_C3.uuid, + BT_GATT_CHRC_READ, + BT_GATT_PERM_READ, + BLEManagerImpl::HandleC3Read, nullptr, nullptr), +#endif +}; -} // unnamed namespace +struct bt_gatt_service sChipoBleService = BT_GATT_SERVICE(sChipoBleAttributes); -BLEManagerImpl BLEManagerImpl::sInstance; +// clang-format on -void rf_irq_handler(const void * paramiter) -{ - irq_blt_sdk_handler(); -} +// Index of the CCC descriptor in the CHIPoBLE_Service array of attributes. +// This value should be adjusted accordingly if the service declaration changes. +constexpr int kCHIPoBLE_CCC_AttributeIndex = 3; -void stimer_irq_handler(const void * paramiter) +CHIP_ERROR InitRandomStaticAddress() { - irq_blt_sdk_handler(); -} + // Generate a random static address for the default identity. + // This must be done before bt_enable() as after that updating the default identity is not possible. + int error = 0; + bt_addr_le_t addr; -void BLEManagerImpl::BleEntry(void *, void *, void *) -{ - while (true) + // generating the address + addr.type = BT_ADDR_LE_RANDOM; + error = sys_csrand_get(addr.a.val, sizeof(addr.a.val)); + BT_ADDR_SET_STATIC(&addr.a); + + if (error) { - blt_sdk_main_loop(); + ChipLogError(DeviceLayer, "Failed to create BLE address: %d", error); + return System::MapErrorZephyr(error); + } - k_msleep(10); + error = bt_id_create(&addr, nullptr); + + if (error < 0) + { + ChipLogError(DeviceLayer, "Failed to create BLE identity: %d", error); + return System::MapErrorZephyr(error); } + + ChipLogProgress(DeviceLayer, "BLE address: %02X:%02X:%02X:%02X:%02X:%02X", addr.a.val[5], addr.a.val[4], addr.a.val[3], + addr.a.val[2], addr.a.val[1], addr.a.val[0]); + return CHIP_NO_ERROR; } -/* Thread for running BLE main loop */ -K_THREAD_DEFINE(chipBleThread, CHIP_BLE_THREAD_STACK_SIZE, BLEManagerImpl::BleEntry, NULL, NULL, NULL, CHIP_BLE_THREAD_PRIORITY, 0, - 0); +} // unnamed namespace + +BLEManagerImpl BLEManagerImpl::sInstance; + +bool ThreadConnectivityReady; +bool BLERadioInitialized; CHIP_ERROR BLEManagerImpl::_Init() { ThreadConnectivityReady = false; + BLERadioInitialized = false; + mconId = NULL; mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); @@ -176,11 +154,20 @@ CHIP_ERROR BLEManagerImpl::_Init() memset(mSubscribedConns, 0, sizeof(mSubscribedConns)); + ReturnErrorOnFailure(InitRandomStaticAddress()); + // int err = bt_enable(NULL); // Can't init BLE stack here due to abscense of non-cuncurrent mode + // VerifyOrReturnError(err == 0, MapErrorZephyr(err)); + + memset(&mConnCallbacks, 0, sizeof(mConnCallbacks)); + mConnCallbacks.connected = HandleConnect; + mConnCallbacks.disconnected = HandleDisconnect; + + bt_conn_cb_register(&mConnCallbacks); + // Initialize the CHIP BleLayer. ReturnErrorOnFailure(BleLayer::Init(this, this, &DeviceLayer::SystemLayer())); - // Suspend BLE Task - k_thread_suspend(chipBleThread); + PlatformMgr().ScheduleWork(DriveBLEState, 0); return CHIP_NO_ERROR; } @@ -225,6 +212,20 @@ void BLEManagerImpl::DriveBLEState() err = StopAdvertising(); SuccessOrExit(err); } + + // If no connections are active unregister also CHIPoBLE GATT service + if (NumConnections() == 0 && mFlags.Has(Flags::kChipoBleGattServiceRegister)) + { + // Unregister CHIPoBLE service to not allow discovering it when pairing is disabled. + if (bt_gatt_service_unregister(&sChipoBleService) != 0) + { + ChipLogError(DeviceLayer, "Failed to unregister CHIPoBLE GATT service"); + } + else + { + mFlags.Clear(Flags::kChipoBleGattServiceRegister); + } + } } exit: @@ -235,432 +236,89 @@ void BLEManagerImpl::DriveBLEState() } } -int BLEManagerImpl::RxWriteCallback(uint16_t connHandle, void * p) -{ - rf_packet_att_t * packet = (rf_packet_att_t *) p; - size_t dataLen = packet->l2capLen - CHIP_RF_PACKET_HEADER_SIZE; - ChipDeviceEvent event; - - PacketBufferHandle packetBuf = PacketBufferHandle::NewWithData(packet->dat, dataLen); - - // If successful... - if (packetBuf.IsNull()) - { - ChipLogError(DeviceLayer, "Failed to allocate buffer"); - - return 0; - } - - // Arrange to post a CHIPoBLERXWriteEvent event to the CHIP queue. - event.Type = DeviceEventType::kPlatformTelinkBleRXWrite; - event.Platform.BleRXWriteEvent.connHandle = connHandle; - event.Platform.BleRXWriteEvent.Data = std::move(packetBuf).UnsafeRelease(); - - PlatformMgr().PostEventOrDie(&event); - - return 0; -} - -void BLEManagerImpl::ConnectCallback(uint8_t bleEvent, uint8_t * data, int len) -{ - ChipDeviceEvent event; - ble_sts_t status = BLE_SUCCESS; - - event.Type = DeviceEventType::kPlatformTelinkBleConnected; - event.Platform.BleConnEvent.connHandle = BLS_CONN_HANDLE; - event.Platform.BleConnEvent.HciResult = BLE_SUCCESS; - - PlatformMgr().PostEventOrDie(&event); -} - -void BLEManagerImpl::DisconnectCallback(uint8_t bleEvent, uint8_t * data, int len) -{ - ChipDeviceEvent event; - - event.Type = DeviceEventType::kPlatformTelinkBleDisconnected; - event.Platform.BleConnEvent.connHandle = BLS_CONN_HANDLE; - event.Platform.BleConnEvent.HciResult = *data; // Reason of disconnection stored in first data byte - - PlatformMgr().PostEventOrDie(&event); -} - -int BLEManagerImpl::TxCccWriteCallback(uint16_t connHandle, void * p) +struct BLEManagerImpl::ServiceData { - ChipDeviceEvent event; - rf_packet_att_t * packet = (rf_packet_att_t *) p; - int dataLen = packet->rf_len - CHIP_RF_PACKET_HEADER_SIZE; - uint16_t value = *((uint16_t *) packet->dat); - - event.Type = DeviceEventType::kPlatformTelinkBleCCCWrite; - event.Platform.BleCCCWriteEvent.connHandle = connHandle; - event.Platform.BleCCCWriteEvent.Value = value; - - PlatformMgr().PostEventOrDie(&event); - - return 0; -} - -int BLEManagerImpl::GapEventHandler(uint32_t gapEvent, uint8_t * data, int size) -{ - ChipDeviceEvent event; - - if ((gapEvent & 0xFF) == GAP_EVT_GATT_HANDLE_VLAUE_CONFIRM) - { - /* Send TX complete event if everything is fine */ - event.Type = DeviceEventType::kPlatformTelinkBleTXComplete; - event.Platform.BleTXCompleteEvent.connHandle = BLS_CONN_HANDLE; - - PlatformMgr().PostEventOrDie(&event); - } - - return 0; -} + uint8_t uuid[2]; + ChipBLEDeviceIdentificationInfo deviceIdInfo; +} __attribute__((packed)); -CHIP_ERROR BLEManagerImpl::_InitStack(void) +CHIP_ERROR BLEManagerImpl::StartAdvertising(void) { - CHIP_ERROR err = CHIP_NO_ERROR; + int err = 0; - uint8_t macPublic[CHIP_MAC_LEN] = { 0 }; - uint8_t macRandomStatic[CHIP_MAC_LEN] = { 0 }; - int ret = 0; + // At first run always select fast advertising, on the next attempt slow down interval. + const uint32_t intervalMin = mFlags.Has(Flags::kFastAdvertisingEnabled) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN + : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MIN; + const uint32_t intervalMax = mFlags.Has(Flags::kFastAdvertisingEnabled) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX + : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX; if (ConnectivityMgr().IsThreadProvisioned()) { - ChipLogProgress(DeviceLayer, "Thread Provisioned. Ignore"); - - return CHIP_ERROR_INCORRECT_STATE; - } - - /* Reset Radio */ - rf_radio_reset(); - - /* Reset DMA */ - rf_reset_dma(); - - /* Init Radio driver */ - ble_radio_init(); - - /* Generate MAC address if it does not exist or read it from flash if it is exist already */ - blc_initMacAddress(CFG_ADR_MAC_1M_FLASH, macPublic, macRandomStatic); - - /* Init interrupts and DMA for BLE module ??? */ - blc_ll_initBasicMCU(); - - /* Setup MAC Address */ - blc_ll_initStandby_module(macPublic); - - /* Init advertisement */ - blc_ll_initAdvertising_module(); - - /* Init slave role */ - blc_ll_initSlaveRole_module(); - - /* Init connection mode */ - blc_ll_initConnection_module(); - - /* Init GAP */ - err = _InitGap(); - SuccessOrExit(err); - - /* Resetup stimer interrupt to handle BLE stack */ - ret = irq_connect_dynamic(STIMER_IRQ_NUM + CONFIG_2ND_LVL_ISR_TBL_OFFSET, 2, stimer_irq_handler, NULL, 0); - ChipLogDetail(DeviceLayer, "Stimer IRQ assigned vector %d", ret); - - /* Resetup rf interrupt to handle BLE stack */ - ret = irq_connect_dynamic(RF_IRQ_NUM + CONFIG_2ND_LVL_ISR_TBL_OFFSET, 2, rf_irq_handler, NULL, 0); - ChipLogDetail(DeviceLayer, "RF IRQ assigned vector %d", ret); - -exit: - - return err; -} - -CHIP_ERROR BLEManagerImpl::_InitGap(void) -{ - ble_sts_t status = BLE_SUCCESS; - /* Fifo buffers */ - static u8 txFifoBuff[CHIP_BLE_TX_FIFO_SIZE * CHIP_BLE_TX_FIFO_NUM] = { 0 }; - static u8 rxFifoBuff[CHIP_BLE_RX_FIFO_SIZE * CHIP_BLE_RX_FIFO_NUM] = { 0 }; - - status = blc_ll_initAclConnTxFifo(txFifoBuff, CHIP_BLE_TX_FIFO_SIZE, CHIP_BLE_TX_FIFO_NUM); - if (status != BLE_SUCCESS) - { - ChipLogError(DeviceLayer, "Fail to init BLE TX FIFO. Error %d", status); - - return CHIP_ERROR_INCORRECT_STATE; - } - - status = blc_ll_initAclConnRxFifo(rxFifoBuff, CHIP_BLE_RX_FIFO_SIZE, CHIP_BLE_RX_FIFO_NUM); - if (status != BLE_SUCCESS) - { - ChipLogError(DeviceLayer, "Fail to init BLE RX FIFO. Error %d", status); - - return CHIP_ERROR_INCORRECT_STATE; - } - - status = blc_controller_check_appBufferInitialization(); - if (status != BLE_SUCCESS) - { - ChipLogError(DeviceLayer, "Buffer initialization check failed. Error %d", status); - - return CHIP_ERROR_INCORRECT_STATE; - } - - /* Init GAP */ - blc_gap_peripheral_init(); - - /* Set up GATT Services */ - _InitGatt(); - - /* L2CAP Initialization */ - blc_l2cap_register_handler((void *) blc_l2cap_packet_receive); - - /* Setup connect/terminate callbacks */ - bls_app_registerEventCallback(BLT_EV_FLAG_CONNECT, BLEManagerImpl::ConnectCallback); - bls_app_registerEventCallback(BLT_EV_FLAG_TERMINATE, BLEManagerImpl::DisconnectCallback); - - /* Add GAP event handler to handle indication send */ - blc_gap_registerHostEventHandler(BLEManagerImpl::GapEventHandler); - blc_gap_setEventMask(GAP_EVT_MASK_GATT_HANDLE_VLAUE_CONFIRM); - - /* Set MTU */ - status = blc_att_setRxMtuSize(CHIP_MTU_SIZE); - if (status != BLE_SUCCESS) - { - ChipLogError(DeviceLayer, "Fail to set MTU size. Error %d", status); - - return CHIP_ERROR_INCORRECT_STATE; - } - - return CHIP_NO_ERROR; -} - -void BLEManagerImpl::_InitGatt(void) -{ - /* UUIDs */ - static const u16 primaryServiceUUID = GATT_UUID_PRIMARY_SERVICE; - static const u16 gapServiceUUID = SERVICE_UUID_GENERIC_ACCESS; - static const u16 characterUUID = GATT_UUID_CHARACTER; - static const u16 devNameUUID = GATT_UUID_DEVICE_NAME; - static const u16 gattServiceUUID = SERVICE_UUID_GENERIC_ATTRIBUTE; - static const u16 serviceChangeUUID = GATT_UUID_SERVICE_CHANGE; - static const u16 clientCharacterCfgUUID = GATT_UUID_CLIENT_CHAR_CFG; - static const u16 devServiceUUID = SERVICE_UUID_DEVICE_INFORMATION; - static const u16 appearanceUUID = GATT_UUID_APPEARANCE; - static const u16 periConnParamUUID = GATT_UUID_PERI_CONN_PARAM; - static const u8 MatterRxCharUUID[] = WRAPPING_BRACES(CHIP_RX_CHAR_UUID); - static const u8 MatterTxCharUUID[] = WRAPPING_BRACES(CHIP_TX_CHAR_UUID); - - /* Characteristics */ - static const u8 devNameCharVal[] = { CHAR_PROP_READ | CHAR_PROP_NOTIFY, U16_LO(GenericAccess_DeviceName_DP_H), - U16_HI(GenericAccess_DeviceName_DP_H), U16_LO(GATT_UUID_DEVICE_NAME), - U16_HI(GATT_UUID_DEVICE_NAME) }; - - static const u8 appearanceCharVal[] = { CHAR_PROP_READ, U16_LO(GenericAccess_Appearance_DP_H), - U16_HI(GenericAccess_Appearance_DP_H), U16_LO(GATT_UUID_APPEARANCE), - U16_HI(GATT_UUID_APPEARANCE) }; - - static const u8 periConnParamCharVal[] = { CHAR_PROP_READ, U16_LO(CONN_PARAM_DP_H), U16_HI(CONN_PARAM_DP_H), - U16_LO(GATT_UUID_PERI_CONN_PARAM), U16_HI(GATT_UUID_PERI_CONN_PARAM) }; - - static const u8 serviceChangeCharVal[] = { CHAR_PROP_INDICATE, U16_LO(GenericAttribute_ServiceChanged_DP_H), - U16_HI(GenericAttribute_ServiceChanged_DP_H), U16_LO(GATT_UUID_SERVICE_CHANGE), - U16_HI(GATT_UUID_SERVICE_CHANGE) }; - - static const u8 MatterRxCharVal[] = { CHAR_PROP_WRITE | CHAR_PROP_WRITE_WITHOUT_RSP, U16_LO(Matter_RX_DP_H), - U16_HI(Matter_RX_DP_H), CHIP_RX_CHAR_UUID }; - - static const u8 MatterTxCharVal[] = { CHAR_PROP_INDICATE, U16_LO(Matter_TX_DP_H), U16_HI(Matter_TX_DP_H), CHIP_TX_CHAR_UUID }; - - /* Values */ - static const u16 appearance = GAP_APPEARE_UNKNOWN; - static const gap_periConnectParams_t periConnParameters = { 8, 11, 0, 1000 }; - static u16 serviceChangeVal[2] = { 0 }; - static u8 serviceChangeCCC[2] = { 0 }; - static u8 matterTxCCC[2] = { 0 }; - - static const attribute_t gattTable[] = { - /* Total number of attributes */ - { ATT_END_H - 1, 0, 0, 0, 0, 0 }, - - /* 0001 - 0007 GAP service */ - { 7, ATT_PERMISSIONS_READ, 2, 2, (u8 *) (&primaryServiceUUID), (u8 *) (&gapServiceUUID), 0 }, - { 0, ATT_PERMISSIONS_READ, 2, sizeof(devNameCharVal), (u8 *) (&characterUUID), (u8 *) (devNameCharVal), 0 }, - { 0, ATT_PERMISSIONS_READ, 2, (u32) kMaxDeviceNameLength, (u8 *) (&devNameUUID), (u8 *) (mDeviceName), 0 }, - { 0, ATT_PERMISSIONS_READ, 2, sizeof(appearanceCharVal), (u8 *) (&characterUUID), (u8 *) (appearanceCharVal), 0 }, - { 0, ATT_PERMISSIONS_READ, 2, sizeof(appearance), (u8 *) (&appearanceUUID), (u8 *) (&appearance), 0 }, - { 0, ATT_PERMISSIONS_READ, 2, sizeof(periConnParamCharVal), (u8 *) (&characterUUID), (u8 *) (periConnParamCharVal), 0 }, - { 0, ATT_PERMISSIONS_READ, 2, sizeof(periConnParameters), (u8 *) (&periConnParamUUID), (u8 *) (&periConnParameters), 0 }, - - /* 0008 - 000b GATT */ - { 4, ATT_PERMISSIONS_READ, 2, 2, (u8 *) (&primaryServiceUUID), (u8 *) (&gattServiceUUID), 0 }, - { 0, ATT_PERMISSIONS_READ, 2, sizeof(serviceChangeCharVal), (u8 *) (&characterUUID), (u8 *) (serviceChangeCharVal), 0 }, - { 0, ATT_PERMISSIONS_READ, 2, sizeof(serviceChangeVal), (u8 *) (&serviceChangeUUID), (u8 *) (&serviceChangeVal), 0 }, - { 0, ATT_PERMISSIONS_RDWR, 2, sizeof(serviceChangeCCC), (u8 *) (&clientCharacterCfgUUID), (u8 *) (serviceChangeCCC), 0 }, - - /* 000c - 0011 Matter service */ - { 6, ATT_PERMISSIONS_READ, 2, 2, (u8 *) (&primaryServiceUUID), (u8 *) (&matterServiceUUID), 0 }, - { 0, ATT_PERMISSIONS_READ, 2, sizeof(MatterRxCharVal), (u8 *) (&characterUUID), (u8 *) (MatterRxCharVal), 0 }, - { 0, ATT_PERMISSIONS_RDWR, 16, sizeof(mRxDataBuff), (u8 *) (&MatterRxCharUUID), mRxDataBuff, RxWriteCallback, NULL }, - { 0, ATT_PERMISSIONS_READ, 2, sizeof(MatterTxCharVal), (u8 *) (&characterUUID), (u8 *) (MatterTxCharVal), 0 }, - { 0, ATT_PERMISSIONS_RDWR, 16, sizeof(mTxDataBuff), (u8 *) (&MatterTxCharUUID), mTxDataBuff, 0 }, - { 0, ATT_PERMISSIONS_RDWR, 2, sizeof(matterTxCCC), (u8 *) (&clientCharacterCfgUUID), (u8 *) (matterTxCCC), - TxCccWriteCallback, NULL } - }; - - bls_att_setAttributeTable((u8 *) gattTable); -} - -CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) -{ - ble_sts_t status = BLE_SUCCESS; - CHIP_ERROR err = CHIP_NO_ERROR; - uint8_t index = 0; - uint8_t devNameLen = 0; - ChipBLEDeviceIdentificationInfo deviceIdInfo; - u8 adv[CHIP_MAX_ADV_DATA_LEN] = { 0 }; - u8 srsp[CHIP_MAX_RESPONSE_DATA_LEN] = { 0 }; - - ChipLogProgress(DeviceLayer, "BLEManagerImpl::ConfigureAdvertisingData"); - - /* Get BLE device identification info */ - err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(deviceIdInfo); - SuccessOrExit(err); - - /* Check device name */ - if (!mFlags.Has(Flags::kDeviceNameSet)) - { - err = _SetDeviceName("TelinkMatter"); - SuccessOrExit(err); - } - - /* Fulfill BLE advertisement data */ - /* Set flags */ - adv[index++] = CHIP_ADE_DATA_LEN_FLAGS; - adv[index++] = CHIP_ADV_DATA_TYPE_FLAGS; - adv[index++] = CHIP_ADV_DATA_FLAGS; - - /* Set Service Data */ - adv[index++] = CHIP_ADV_SERVICE_DATA_LEN; - adv[index++] = CHIP_ADV_DATA_TYPE_SERVICE_DATA; - adv[index++] = matterServiceUUID[0]; - adv[index++] = matterServiceUUID[1]; - memcpy(&adv[index], (void *) &deviceIdInfo, sizeof(deviceIdInfo)); - index += sizeof(deviceIdInfo); - - /* Set device name */ - devNameLen = strlen(mDeviceName); - adv[index++] = devNameLen + 1; - adv[index++] = CHIP_ADV_DATA_TYPE_NAME; - memcpy(&adv[index], mDeviceName, devNameLen); - index += devNameLen; - - /* Set advetisment data */ - status = bls_ll_setAdvData(adv, index); - if (status != BLE_SUCCESS) - { - ChipLogError(DeviceLayer, "Fail to set BLE advertisement data. Error %d", status); - - return CHIP_ERROR_INCORRECT_STATE; - } - - index = 0; - srsp[index++] = CHIP_SHORT_UUID_LEN + 1; - srsp[index++] = CHIP_ADV_DATA_TYPE_UUID; - srsp[index++] = matterServiceUUID[0]; - srsp[index++] = matterServiceUUID[1]; - - /* Set scan response data */ - status = bls_ll_setScanRspData(srsp, sizeof(srsp)); - if (status != BLE_SUCCESS) - { - ChipLogError(DeviceLayer, "Fail to set BLE scan response data. Error %d", status); + ChipLogProgress(DeviceLayer, "Thread provisioned. Start advertisement not possible"); return CHIP_ERROR_INCORRECT_STATE; } -exit: - return err; -} - -CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrReturnError(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, - CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - - if (mFlags.Has(Flags::kAdvertisingEnabled) != val) + if (!BLERadioInitialized) { - ChipLogDetail(DeviceLayer, "CHIPoBLE advertising set to %s", val ? "on" : "off"); + char bt_dev_name[CONFIG_BT_DEVICE_NAME_MAX]; + strncpy(bt_dev_name, bt_get_name(), sizeof(bt_dev_name)); + /* Block IEEE802154 */ + /* @todo: move to RadioSwitch module*/ + const struct device * radio_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_ieee802154)); + __ASSERT(radio_dev != NULL, "Fail to get radio device"); + b91_deinit(radio_dev); - mFlags.Set(Flags::kAdvertisingEnabled, val); - PlatformMgr().ScheduleWork(DriveBLEState, 0); + /* Init BLE stack */ + err = bt_enable(NULL); + VerifyOrReturnError(err == 0, MapErrorZephyr(err)); + (void) bt_set_name(bt_dev_name); + BLERadioInitialized = true; } - return err; -} + bt_le_adv_param advParams = + BT_LE_ADV_PARAM_INIT(BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME, intervalMin, intervalMax, nullptr); -CHIP_ERROR BLEManagerImpl::StartAdvertising(void) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - ble_sts_t status = BLE_SUCCESS; - - /* At first run always select fast advertising, on the next attempt slow down interval. */ - u16 intervalMin = mFlags.Has(Flags::kFastAdvertisingEnabled) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN - : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MIN; - u16 intervalMax = mFlags.Has(Flags::kFastAdvertisingEnabled) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX - : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX; - - if (ConnectivityMgr().IsThreadProvisioned()) - { - ChipLogProgress(DeviceLayer, "Thread provisioned. Start advertisement not possible"); - - return CHIP_ERROR_INCORRECT_STATE; - } + // Define advertising and, if BLE device name is set, scan response data + ServiceData serviceData; + const uint8_t advFlags = BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR; + const bt_data advertisingData[] = { BT_DATA(BT_DATA_FLAGS, &advFlags, sizeof(advFlags)), + BT_DATA(BT_DATA_SVC_DATA16, &serviceData, sizeof(serviceData)) }; - /* Block IEEE802154 */ - /* @todo: move to RadioSwitch module*/ - const struct device * radio_dev = device_get_binding(CONFIG_NET_CONFIG_IEEE802154_DEV_NAME); - __ASSERT(radio_dev != NULL, "Fail to get radio device"); - b91_deinit(radio_dev); + const char * deviceName = bt_get_name(); + const uint8_t deviceNameSize = static_cast(strlen(deviceName)); + const bt_data scanResponseData[] = { BT_DATA(BT_DATA_NAME_COMPLETE, deviceName, deviceNameSize) }; + const bt_data * scanResponseDataPtr = deviceNameSize > 0 ? scanResponseData : nullptr; + const size_t scanResponseDataLen = deviceNameSize > 0 ? ARRAY_SIZE(scanResponseData) : 0u; - /* It is time to init BLE stack */ - err = _InitStack(); - if (err != CHIP_NO_ERROR) + // Register dynamically CHIPoBLE GATT service + if (!mFlags.Has(Flags::kChipoBleGattServiceRegister)) { - ChipLogError(DeviceLayer, "Fail to init BLE stack"); + err = bt_gatt_service_register(&sChipoBleService); - return err; - } + if (err != 0) + ChipLogError(DeviceLayer, "Failed to register CHIPoBLE GATT service"); - /* Configure CHIP BLE advertisement data */ - err = ConfigureAdvertisingData(); - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Fail to config BLE advertisement data"); + VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - return err; + mFlags.Set(Flags::kChipoBleGattServiceRegister); } - /* Setup advertisement parameters */ - status = bls_ll_setAdvParam(intervalMin, intervalMax, ADV_TYPE_CONNECTABLE_UNDIRECTED, OWN_ADDRESS_PUBLIC, 0, NULL, - BLT_ENABLE_ADV_ALL, ADV_FP_NONE); - if (status != BLE_SUCCESS) - { - ChipLogError(DeviceLayer, "Fail to set BLE advertisement parameters. Error %d", status); + // Initialize service data + static_assert(sizeof(serviceData) == 10, "Size of BLE advertisement data changed! Was that intentional?"); + chip::Encoding::LittleEndian::Put16(serviceData.uuid, UUID16_CHIPoBLEService.val); + ReturnErrorOnFailure(ConfigurationMgr().GetBLEDeviceIdentificationInfo(serviceData.deviceIdInfo)); - return CHIP_ERROR_INCORRECT_STATE; - } +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + ReturnErrorOnFailure(PrepareC3CharData()); +#endif - /* Enable advertisement */ - status = bls_ll_setAdvEnable(BLC_ADV_ENABLE); - if (status != BLE_SUCCESS) - { - ChipLogError(DeviceLayer, "Fail to start BLE advertisement. Error %d", status); + // Restart advertising + err = bt_le_adv_stop(); + VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - return CHIP_ERROR_INCORRECT_STATE; - } + err = bt_le_adv_start(&advParams, advertisingData, ARRAY_SIZE(advertisingData), scanResponseDataPtr, scanResponseDataLen); + VerifyOrReturnError(err == 0, MapErrorZephyr(err)); // Transition to the Advertising state... if (!mFlags.Has(Flags::kAdvertising)) @@ -686,16 +344,11 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) } } - /* Start BLE Task */ - k_thread_resume(chipBleThread); - - return err; + return CHIP_NO_ERROR; } CHIP_ERROR BLEManagerImpl::StopAdvertising(void) { - ble_sts_t status = BLE_SUCCESS; - if (ConnectivityMgr().IsThreadProvisioned()) { ChipLogProgress(DeviceLayer, "Thread provisioned. Advertisement already stopped at this stage"); @@ -703,14 +356,8 @@ CHIP_ERROR BLEManagerImpl::StopAdvertising(void) return CHIP_ERROR_INCORRECT_STATE; } - /* Disable advertisement */ - status = bls_ll_setAdvEnable(BLC_ADV_DISABLE); - if (status != BLE_SUCCESS) - { - ChipLogError(DeviceLayer, "Fail to stop BLE advertisement. Error %d", status); - - return CHIP_ERROR_INCORRECT_STATE; - } + int err = bt_le_adv_stop(); + VerifyOrReturnError(err == 0, MapErrorZephyr(err)); // Transition to the not Advertising state... if (mFlags.Has(Flags::kAdvertising)) @@ -735,6 +382,22 @@ CHIP_ERROR BLEManagerImpl::StopAdvertising(void) return CHIP_NO_ERROR; } +CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) +{ + VerifyOrReturnError(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, + CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); + + if (mFlags.Has(Flags::kAdvertisingEnabled) != val) + { + ChipLogDetail(DeviceLayer, "CHIPoBLE advertising set to %s", val ? "on" : "off"); + + mFlags.Set(Flags::kAdvertisingEnabled, val); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + } + + return CHIP_NO_ERROR; +} + CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode) { switch (mode) @@ -755,47 +418,190 @@ CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode) CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) { - if (strlen(mDeviceName) >= bufSize) - { - return CHIP_ERROR_BUFFER_TOO_SMALL; - } - strcpy(buf, mDeviceName); + Platform::CopyString(buf, bufSize, bt_get_name()); return CHIP_NO_ERROR; } -CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * devName) +CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) { - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported) { - ChipLogError(DeviceLayer, "Unsupported"); - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } - if (devName == NULL || devName[0] == 0) + ChipLogDetail(DeviceLayer, "Device name set to: %s", deviceName); + return MapErrorZephyr(bt_set_name(deviceName)); +} + +CHIP_ERROR BLEManagerImpl::HandleGAPConnect(const ChipDeviceEvent * event) +{ + const BleConnEventType * connEvent = &event->Platform.BleConnEvent; + + if (connEvent->HciResult == BT_HCI_ERR_SUCCESS) + { + ChipLogProgress(DeviceLayer, "BLE connection established (ConnId: 0x%02x)", bt_conn_index(connEvent->BtConn)); + mGAPConns++; + } + else { - ChipLogError(DeviceLayer, "Invalid name"); + ChipLogError(DeviceLayer, "BLE connection failed (reason: 0x%02x)", connEvent->HciResult); + } - return CHIP_ERROR_INVALID_ARGUMENT; + ChipLogProgress(DeviceLayer, "Current number of connections: %u/%u", NumConnections(), CONFIG_BT_MAX_CONN); + + mFlags.Set(Flags::kAdvertisingRefreshNeeded); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + + mconId = connEvent->BtConn; + bt_conn_unref(connEvent->BtConn); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLEManagerImpl::HandleGAPDisconnect(const ChipDeviceEvent * event) +{ + const BleConnEventType * connEvent = &event->Platform.BleConnEvent; + + ChipLogProgress(DeviceLayer, "BLE GAP connection terminated (reason 0x%02x)", connEvent->HciResult); + + mGAPConns--; + + // If indications were enabled for this connection, record that they are now disabled and + // notify the BLE Layer of a disconnect. + if (UnsetSubscribed(connEvent->BtConn)) + { + CHIP_ERROR disconReason; + switch (connEvent->HciResult) + { + case BT_HCI_ERR_REMOTE_USER_TERM_CONN: + // Do not treat proper connection termination as an error and exit. + VerifyOrExit(!ConfigurationMgr().IsFullyProvisioned(), ); + disconReason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; + break; + case BT_HCI_ERR_LOCALHOST_TERM_CONN: + disconReason = BLE_ERROR_APP_CLOSED_CONNECTION; + break; + default: + disconReason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT; + break; + } + HandleConnectionError(connEvent->BtConn, disconReason); } - if (strlen(devName) >= kMaxDeviceNameLength) +exit: + // Unref bt_conn before scheduling DriveBLEState. + bt_conn_unref(connEvent->BtConn); + + ChipLogProgress(DeviceLayer, "Current number of connections: %u/%u", NumConnections(), CONFIG_BT_MAX_CONN); + + ChipDeviceEvent disconnectEvent; + disconnectEvent.Type = DeviceEventType::kCHIPoBLEConnectionClosed; + ReturnErrorOnFailure(PlatformMgr().PostEvent(&disconnectEvent)); + + // Force a reconfiguration of advertising in case we switched to non-connectable mode when + // the BLE connection was established. + mFlags.Set(Flags::kAdvertisingRefreshNeeded); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLEManagerImpl::HandleTXCharCCCDWrite(const ChipDeviceEvent * event) +{ + const BleCCCWriteEventType * writeEvent = &event->Platform.BleCCCWriteEvent; + + ChipLogDetail(DeviceLayer, "ConnId: 0x%02x, New CCCD value: 0x%04x", bt_conn_index(writeEvent->BtConn), writeEvent->Value); + + // If the client has requested to enable indications and if it is not yet subscribed + if (writeEvent->Value == BT_GATT_CCC_INDICATE && SetSubscribed(writeEvent->BtConn)) { - ChipLogError(DeviceLayer, "BLE device name is to long"); + // Alert the BLE layer that CHIPoBLE "subscribe" has been received and increment the bt_conn reference counter. + HandleSubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); - return CHIP_ERROR_INVALID_ARGUMENT; + ChipLogProgress(DeviceLayer, "CHIPoBLE connection established (ConnId: 0x%02x, GATT MTU: %u)", + bt_conn_index(writeEvent->BtConn), GetMTU(writeEvent->BtConn)); + + // Post a CHIPoBLEConnectionEstablished event to the DeviceLayer and the application. + { + ChipDeviceEvent conEstEvent; + conEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; + ReturnErrorOnFailure(PlatformMgr().PostEvent(&conEstEvent)); + } } + else + { + if (UnsetSubscribed(writeEvent->BtConn)) + { + HandleUnsubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + } + } + + bt_conn_unref(writeEvent->BtConn); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLEManagerImpl::HandleRXCharWrite(const ChipDeviceEvent * event) +{ + const BleC1WriteEventType * c1WriteEvent = &event->Platform.BleC1WriteEvent; - strcpy(mDeviceName, devName); - mFlags.Set(Flags::kDeviceNameSet); + ChipLogDetail(DeviceLayer, "Write request received for CHIPoBLE RX characteristic (ConnId 0x%02x)", + bt_conn_index(c1WriteEvent->BtConn)); - ChipLogProgress(DeviceLayer, "Setting device name to : \"%s\"", devName); + HandleWriteReceived(c1WriteEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, + PacketBufferHandle::Adopt(c1WriteEvent->Data)); + bt_conn_unref(c1WriteEvent->BtConn); return CHIP_NO_ERROR; } +CHIP_ERROR BLEManagerImpl::HandleTXCharComplete(const ChipDeviceEvent * event) +{ + const BleC2IndDoneEventType * c2IndDoneEvent = &event->Platform.BleC2IndDoneEvent; + + ChipLogDetail(DeviceLayer, "Indication for CHIPoBLE TX characteristic done (ConnId 0x%02x, result 0x%02x)", + bt_conn_index(c2IndDoneEvent->BtConn), c2IndDoneEvent->Result); + + // Signal the BLE Layer that the outstanding indication is complete. + HandleIndicationConfirmation(c2IndDoneEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + bt_conn_unref(c2IndDoneEvent->BtConn); + + return CHIP_NO_ERROR; +} + +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING +CHIP_ERROR BLEManagerImpl::PrepareC3CharData() +{ + CHIP_ERROR err = CHIP_NO_ERROR; + BitFlags additionalDataFields; + AdditionalDataPayloadGeneratorParams additionalDataPayloadParams; + +#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) + uint8_t rotatingDeviceIdUniqueId[ConfigurationManager::kRotatingDeviceIDUniqueIDLength] = {}; + MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId); + + err = DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan); + SuccessOrExit(err); + err = ConfigurationMgr().GetLifetimeCounter(additionalDataPayloadParams.rotatingDeviceIdLifetimeCounter); + SuccessOrExit(err); + additionalDataPayloadParams.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan; + additionalDataFields.Set(AdditionalDataFields::RotatingDeviceId); +#endif /* CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) */ + + err = AdditionalDataPayloadGenerator().generateAdditionalDataPayload(additionalDataPayloadParams, c3CharDataBufferHandle, + additionalDataFields); + +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "Failed to generate TLV encoded Additional Data (%s)", __func__); + } + + return err; +} +#endif + void BLEManagerImpl::HandleBLEAdvertisementIntervalChange(System::Layer * layer, void * param) { BLEMgr().SetAdvertisingMode(BLEAdvertisingMode::kSlowAdvertising); @@ -808,27 +614,23 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) switch (event->Type) { - case DeviceEventType::kPlatformTelinkBleConnected: + case DeviceEventType::kPlatformZephyrBleConnected: err = HandleGAPConnect(event); break; - case DeviceEventType::kPlatformTelinkBleDisconnected: + case DeviceEventType::kPlatformZephyrBleDisconnected: err = HandleGAPDisconnect(event); break; - case DeviceEventType::kPlatformTelinkBleDisconnectRequest: - err = HandleDisconnectRequest(event); + case DeviceEventType::kPlatformZephyrBleCCCWrite: + err = HandleTXCharCCCDWrite(event); break; - case DeviceEventType::kPlatformTelinkBleRXWrite: + case DeviceEventType::kPlatformZephyrBleC1WriteEvent: err = HandleRXCharWrite(event); break; - case DeviceEventType::kPlatformTelinkBleCCCWrite: - err = HandleTXCharCCCDWrite(event); - break; - - case DeviceEventType::kPlatformTelinkBleTXComplete: + case DeviceEventType::kPlatformZephyrBleC2IndDoneEvent: err = HandleTXCharComplete(event); break; @@ -845,216 +647,261 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) break; default: - ChipLogDetail(DeviceLayer, "Event: Unknown (0x%04x)", event->Type); + break; } if (err != CHIP_NO_ERROR) { - ChipLogError(DeviceLayer, "Fail to handle 0x%04x event. Error: %s", event->Type, ErrorStr(err)); + ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %" CHIP_ERROR_FORMAT, err.Format()); mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; PlatformMgr().ScheduleWork(DriveBLEState, 0); } } -bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) +uint16_t BLEManagerImpl::_NumConnections(void) { - return false; + return mGAPConns; } -bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) +bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) { - return false; + ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (ConnId %02x)", bt_conn_index(conId)); + return bt_conn_disconnect(conId, BT_HCI_ERR_REMOTE_USER_TERM_CONN) == 0; } -bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) +uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const { - return false; + return bt_gatt_get_mtu(conId); } -uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const +bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) { - return blc_att_getEffectiveMtuSize(conId); + ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); + return true; +} + +bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) +{ + ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); + return true; } bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, PacketBufferHandle pBuf) { - ble_sts_t status = BLE_SUCCESS; + CHIP_ERROR err = CHIP_NO_ERROR; + int status = 0; + uint8_t index = bt_conn_index(conId); + bt_gatt_indicate_params * params = &mIndicateParams[index]; - do - { - if (status != BLE_SUCCESS) - { - k_msleep(1); - } - status = blc_gatt_pushHandleValueIndicate(conId, Matter_TX_DP_H, pBuf->Start(), pBuf->DataLength()); - } while (status == GATT_ERR_DATA_PENDING_DUE_TO_SERVICE_DISCOVERY_BUSY); - if (status != BLE_SUCCESS) - { - ChipLogError(DeviceLayer, "Fail to send indication. Error %d", status); + VerifyOrExit(IsSubscribed(conId) == true, err = CHIP_ERROR_INVALID_ARGUMENT); + + ChipLogDetail(DeviceLayer, "Sending indication for CHIPoBLE TX characteristic (ConnId %02x, len %u)", index, + pBuf->DataLength()); + + params->uuid = nullptr; + params->attr = &sChipoBleAttributes[kCHIPoBLE_CCC_AttributeIndex]; + params->func = HandleTXIndicated; + params->data = pBuf->Start(); + params->len = pBuf->DataLength(); - return false; + status = bt_gatt_indicate(conId, params); + VerifyOrExit(status == 0, err = MapErrorZephyr(status)); + +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %" CHIP_ERROR_FORMAT, err.Format()); } - return true; + return err == CHIP_NO_ERROR; } bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, PacketBufferHandle pBuf) { - ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendWriteRequest() not supported"); - return false; + ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); + return true; } bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, PacketBufferHandle pBuf) { - ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendReadRequest() not supported"); - return false; + ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); + return true; } bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const ChipBleUUID * svcId, const ChipBleUUID * charId) { - ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendReadResponse() not supported"); - return false; + ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); + return true; } -/* @todo: move to RadioSwitch module */ -void BLEManagerImpl::SwitchToIeee802154(void) +void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) { - int result = 0; + CloseConnection(conId); +} - ChipLogProgress(DeviceLayer, "BLEManagerImpl::Switch to IEEE802154"); +bool BLEManagerImpl::IsSubscribed(bt_conn * conn) +{ + return mSubscribedConns[bt_conn_index(conn)]; +} - /* Stop BLE */ - _SetAdvertisingEnabled(false); +bool BLEManagerImpl::SetSubscribed(bt_conn * conn) +{ + uint8_t index = bt_conn_index(conn); + bool isSubscribed = mSubscribedConns[index]; + mSubscribedConns[index] = true; - /* Stop BLE task */ - k_thread_suspend(chipBleThread); + // If we were not subscribed previously, increment the reference counter of the connection. + if (!isSubscribed) + { + bt_conn_ref(conn); + } - /* Reset Radio */ - rf_radio_reset(); + return !isSubscribed; +} - /* Reset DMA */ - rf_reset_dma(); +bool BLEManagerImpl::UnsetSubscribed(bt_conn * conn) +{ + uint8_t index = bt_conn_index(conn); + bool isSubscribed = mSubscribedConns[index]; + mSubscribedConns[index] = false; - const struct device * radio_dev = device_get_binding(CONFIG_NET_CONFIG_IEEE802154_DEV_NAME); - __ASSERT(radio_dev != NULL, "Fail to get radio device"); + // If we were subscribed previously, decrement the reference counter of the connection. + if (isSubscribed) + { + bt_conn_unref(conn); + } - /* Init IEEE802154 */ - result = b91_init(radio_dev); - __ASSERT(result == 0, "Fail to init IEEE802154 radio. Error: %d", result); + return isSubscribed; } -void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) {} - -uint16_t BLEManagerImpl::_NumConnections(void) +ssize_t BLEManagerImpl::HandleRXWrite(struct bt_conn * conId, const struct bt_gatt_attr * attr, const void * buf, uint16_t len, + uint16_t offset, uint8_t flags) { - return mGAPConns; -} + ChipDeviceEvent event; + PacketBufferHandle packetBuf = PacketBufferHandle::NewWithData(buf, len); -/// @todo implement multicinnection subscription -CHIP_ERROR BLEManagerImpl::SetSubscribed(uint16_t conId) -{ + if (!packetBuf.IsNull()) + { + // Arrange to post a CHIPoBLERXWriteEvent event to the CHIP queue. + event.Type = DeviceEventType::kPlatformZephyrBleC1WriteEvent; + event.Platform.BleC1WriteEvent.BtConn = bt_conn_ref(conId); + event.Platform.BleC1WriteEvent.Data = std::move(packetBuf).UnsafeRelease(); + } + + // If we failed to allocate a buffer, post a kPlatformZephyrBleOutOfBuffersEvent event. + else + { + event.Type = DeviceEventType::kPlatformZephyrBleOutOfBuffersEvent; + } - mSubscribedConns[0] = true; + PlatformMgr().PostEventOrDie(&event); - return CHIP_NO_ERROR; + return len; } -/// @todo implement multicinnection subscription -bool BLEManagerImpl::UnsetSubscribed(uint16_t conId) +ssize_t BLEManagerImpl::HandleTXCCCWrite(struct bt_conn * conId, const struct bt_gatt_attr * attr, uint16_t value) { + ChipDeviceEvent event; - mSubscribedConns[0] = false; + if (value != BT_GATT_CCC_INDICATE && value != 0) + { + return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED); + } - return true; + event.Type = DeviceEventType::kPlatformZephyrBleCCCWrite; + event.Platform.BleCCCWriteEvent.BtConn = bt_conn_ref(conId); + event.Platform.BleCCCWriteEvent.Value = value; + + PlatformMgr().PostEventOrDie(&event); + + return sizeof(value); } -/// @todo implement multicinnection subscription -bool BLEManagerImpl::IsSubscribed(uint16_t conId) +void BLEManagerImpl::HandleTXIndicated(struct bt_conn * conId, struct bt_gatt_indicate_params * attr, uint8_t err) { - return mSubscribedConns[0]; + ChipDeviceEvent event; + + event.Type = DeviceEventType::kPlatformZephyrBleC2IndDoneEvent; + event.Platform.BleC2IndDoneEvent.BtConn = bt_conn_ref(conId); + event.Platform.BleC2IndDoneEvent.Result = err; + + PlatformMgr().PostEventOrDie(&event); } -CHIP_ERROR BLEManagerImpl::HandleGAPConnect(const ChipDeviceEvent * event) +void BLEManagerImpl::HandleConnect(struct bt_conn * conId, uint8_t err) { - const BleConnEventType * connEvent = &event->Platform.BleConnEvent; + ChipDeviceEvent event; - ChipLogProgress(DeviceLayer, "BLE connection established (ConnId: 0x%02x)", connEvent->connHandle); - mGAPConns++; - ChipLogProgress(DeviceLayer, "Current number of connections: %u/%u", NumConnections(), kMaxConnections); + PlatformMgr().LockChipStack(); - mFlags.Set(Flags::kAdvertisingRefreshNeeded); - PlatformMgr().ScheduleWork(DriveBLEState, 0); + // Don't handle BLE connecting events when it is not related to CHIPoBLE + VerifyOrExit(sInstance.mFlags.Has(Flags::kChipoBleGattServiceRegister), ); - return CHIP_NO_ERROR; -} + event.Type = DeviceEventType::kPlatformZephyrBleConnected; + event.Platform.BleConnEvent.BtConn = bt_conn_ref(conId); + event.Platform.BleConnEvent.HciResult = err; -CHIP_ERROR BLEManagerImpl::HandleGAPDisconnect(const ChipDeviceEvent * event) -{ - const BleConnEventType * connEvent = &event->Platform.BleConnEvent; + PlatformMgr().PostEventOrDie(&event); - ChipLogProgress(DeviceLayer, "BLE GAP connection terminated (reason 0x%02x)", connEvent->HciResult); +exit: + PlatformMgr().UnlockChipStack(); +} - mGAPConns--; +void BLEManagerImpl::HandleDisconnect(struct bt_conn * conId, uint8_t reason) +{ + ChipDeviceEvent event; - ChipLogProgress(DeviceLayer, "Current number of connections: %u/%u", NumConnections(), kMaxConnections); + PlatformMgr().LockChipStack(); - // Unsubscribe - if (UnsetSubscribed(connEvent->connHandle)) - { - HandleUnsubscribeReceived(connEvent->connHandle, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); - } + // Don't handle BLE disconnecting events when it is not related to CHIPoBLE + VerifyOrExit(sInstance.mFlags.Has(Flags::kChipoBleGattServiceRegister), ); - ChipDeviceEvent disconnectEvent; - disconnectEvent.Type = DeviceEventType::kCHIPoBLEConnectionClosed; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&disconnectEvent)); + event.Type = DeviceEventType::kPlatformZephyrBleDisconnected; + event.Platform.BleConnEvent.BtConn = bt_conn_ref(conId); + event.Platform.BleConnEvent.HciResult = reason; - // Force a reconfiguration of advertising in case we switched to non-connectable mode when - // the BLE connection was established. - mFlags.Set(Flags::kAdvertisingRefreshNeeded); - PlatformMgr().ScheduleWork(DriveBLEState, 0); + PlatformMgr().PostEventOrDie(&event); - return CHIP_NO_ERROR; +exit: + PlatformMgr().UnlockChipStack(); } -CHIP_ERROR BLEManagerImpl::HandleDisconnectRequest(const ChipDeviceEvent * event) +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING +ssize_t BLEManagerImpl::HandleC3Read(struct bt_conn * conId, const struct bt_gatt_attr * attr, void * buf, uint16_t len, + uint16_t offset) { - ble_sts_t status = BLE_SUCCESS; - uint16_t handle = event->Platform.BleConnEvent.connHandle; - uint8_t reason = event->Platform.BleConnEvent.HciResult; - - ChipLogDetail(DeviceLayer, "HandleDisconnectRequest"); + ChipLogDetail(DeviceLayer, "Read request received for CHIPoBLE C3 (ConnId 0x%02x)", bt_conn_index(conId)); - /* Trigger disconnect. DisconnectCallback call occures on completion */ - status = blc_ll_disconnect(handle, reason); - if (status != BLE_SUCCESS && status != LL_ERR_CONNECTION_NOT_ESTABLISH) + if (sInstance.c3CharDataBufferHandle.IsNull()) { - ChipLogError(DeviceLayer, "Fail to disconnect. Error %d", status); - - return CHIP_ERROR_INCORRECT_STATE; + return 0; } - // Force a reconfiguration of advertising in case we switched to non-connectable mode when - // the BLE connection was established. - mFlags.Set(Flags::kAdvertisingRefreshNeeded); - PlatformMgr().ScheduleWork(DriveBLEState, 0); + return bt_gatt_attr_read(conId, attr, buf, len, offset, sInstance.c3CharDataBufferHandle->Start(), + sInstance.c3CharDataBufferHandle->DataLength()); +} +#endif - return CHIP_NO_ERROR; +void BLEManagerImpl::BLEConnDisconnect(System::Layer * layer, void * param) +{ + int error = bt_conn_disconnect(BLEMgrImpl().mconId, BT_HCI_ERR_LOCALHOST_TERM_CONN); + if (error) + { + ChipLogError(DeviceLayer, "Failed to close BLE connection, error: %d", error); + } } CHIP_ERROR BLEManagerImpl::HandleOperationalNetworkEnabled(const ChipDeviceEvent * event) { - ChipDeviceEvent disconnectEvent; ChipLogDetail(DeviceLayer, "HandleOperationalNetworkEnabled"); - disconnectEvent.Type = DeviceEventType::kPlatformTelinkBleDisconnectRequest; - disconnectEvent.Platform.BleConnEvent.connHandle = BLS_CONN_HANDLE; - disconnectEvent.Platform.BleConnEvent.HciResult = CHIP_BLE_DISCONNECT_REASON; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&disconnectEvent)); + // Start timer to close BLE connection. + DeviceLayer::SystemLayer().StartTimer(System::Clock::Milliseconds32(20), BLEConnDisconnect, this); return CHIP_NO_ERROR; } @@ -1094,61 +941,27 @@ CHIP_ERROR BLEManagerImpl::HandleBleConnectionClosed(const ChipDeviceEvent * eve return CHIP_NO_ERROR; } -CHIP_ERROR BLEManagerImpl::HandleRXCharWrite(const ChipDeviceEvent * event) -{ - const BleRXWriteEventType * writeEvent = &event->Platform.BleRXWriteEvent; - - ChipLogDetail(DeviceLayer, "Write request received for CHIPoBLE RX (ConnId 0x%02x)", writeEvent->connHandle); - - HandleWriteReceived(writeEvent->connHandle, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, - PacketBufferHandle::Adopt(writeEvent->Data)); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::HandleTXCharComplete(const ChipDeviceEvent * event) -{ - const BleTXCompleteEventType * completeEvent = &event->Platform.BleTXCompleteEvent; - - ChipLogDetail(DeviceLayer, "Notification for CHIPoBLE TX done (ConnId 0x%02x)", completeEvent->connHandle); - - // Signal the BLE Layer that the outstanding notification is complete. - HandleIndicationConfirmation(completeEvent->connHandle, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::HandleTXCharCCCDWrite(const ChipDeviceEvent * event) +/* @todo: move to RadioSwitch module */ +void BLEManagerImpl::SwitchToIeee802154(void) { - const BleCCCWriteEventType * writeEvent = &event->Platform.BleCCCWriteEvent; + int result = 0; - ChipLogDetail(DeviceLayer, "ConnId: 0x%02x, New CCCD value: 0x%04x", writeEvent->connHandle, writeEvent->Value); + ChipLogProgress(DeviceLayer, "BLEManagerImpl::Switch to IEEE802154"); - /* If the client has requested to enable notifications and if it is not yet subscribed */ - if (writeEvent->Value != 0 && SetSubscribed(writeEvent->connHandle) == CHIP_NO_ERROR) - { - /* Alert the BLE layer that CHIPoBLE "subscribe" has been received and increment the bt_conn reference counter. */ - HandleSubscribeReceived(writeEvent->connHandle, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); + /* Stop BLE */ + StopAdvertising(); - ChipLogProgress(DeviceLayer, "CHIPoBLE connection established (ConnId: 0x%02x, GATT MTU: %d)", writeEvent->connHandle, - GetMTU(writeEvent->connHandle)); + /* Deinit BLE stack */ + bt_disable(); + // irq_disable(IRQ1_SYSTIMER); + BLERadioInitialized = false; - /* Post a CHIPoBLEConnectionEstablished event to the DeviceLayer and the application. */ - { - ChipDeviceEvent conEstEvent; - conEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&conEstEvent)); - } - } - else - { - if (UnsetSubscribed(writeEvent->connHandle)) - { - HandleUnsubscribeReceived(writeEvent->connHandle, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); - } - } + const struct device * radio_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_ieee802154)); + __ASSERT(radio_dev != NULL, "Fail to get radio device"); - return CHIP_NO_ERROR; + /* Init IEEE802154 */ + result = b91_init(radio_dev); + __ASSERT(result == 0, "Fail to init IEEE802154 radio. Error: %d", result); } } // namespace Internal diff --git a/src/platform/telink/BLEManagerImpl.h b/src/platform/telink/BLEManagerImpl.h index d1b79718b347b7..f6fcbf87c8e584 100644 --- a/src/platform/telink/BLEManagerImpl.h +++ b/src/platform/telink/BLEManagerImpl.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,13 +18,20 @@ /** * @file * Provides an implementation of the BLEManager object - * for Telink platform. + * for Telink platforms, by including Zephyr platform + * implementation. */ #pragma once #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#include +#include +#include + +#include + namespace chip { namespace DeviceLayer { namespace Internal { @@ -32,7 +39,7 @@ namespace Internal { using namespace chip::Ble; /** - * Concrete implementation of the BLEManager singleton object for the platform. + * Concrete implementation of the BLEManager singleton object for the Zephyr platforms. */ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePlatformDelegate, private BleApplicationDelegate { @@ -41,10 +48,10 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla friend BLEManager; private: - // Members that implement the BLEManager internal interface. + // ===== Members that implement the BLEManager internal interface. CHIP_ERROR _Init(void); - void _Shutdown(); + void _Shutdown() {} bool _IsAdvertisingEnabled(void); CHIP_ERROR _SetAdvertisingEnabled(bool val); bool _IsAdvertising(void); @@ -55,7 +62,7 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla void _OnPlatformEvent(const ChipDeviceEvent * event); BleLayer * _GetBleLayer(void); - // Members that implement virtual methods on BlePlatformDelegate. + // ===== Members that implement virtual methods on BlePlatformDelegate. bool SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) override; bool UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) override; @@ -70,62 +77,42 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla bool SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const ChipBleUUID * svcId, const ChipBleUUID * charId) override; - // Members that implement virtual methods on BleApplicationDelegate. + // ===== Members that implement virtual methods on BleApplicationDelegate. void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) override; - // Members for internal use by the following friends. - - friend BLEManager & BLEMgr(void); - friend BLEManagerImpl & BLEMgrImpl(void); - - static BLEManagerImpl sInstance; - - // Private members reserved for use by this class only. + // ===== Private members reserved for use by this class only. - enum class Flags : uint16_t + enum class Flags : uint8_t { - kAsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ - kAdvertisingEnabled = 0x0002, /**< The application has enabled CHIPoBLE advertising. */ - kFastAdvertisingEnabled = 0x0004, /**< The application has enabled fast advertising. */ - kAdvertising = 0x0008, /**< The system is currently CHIPoBLE advertising. */ - kAdvertisingRefreshNeeded = 0x0010, /**< The advertising state/configuration state in the BLE layer needs to be updated. */ - kDeviceNameSet = 0x0020, /**< The device name has been set. */ - kRestartAdvertising = 0x0040, /**< The advertising will be restarted when stop advertising confirmation is received and this - flag is set*/ + kAsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ + kAdvertisingEnabled = 0x0002, /**< The application has enabled CHIPoBLE advertising. */ + kFastAdvertisingEnabled = 0x0004, /**< The application has enabled fast advertising. */ + kAdvertising = 0x0008, /**< The system is currently CHIPoBLE advertising. */ + kAdvertisingRefreshNeeded = + 0x0010, /**< The advertising state/configuration has changed, but the SoftDevice has yet to be updated. */ + kChipoBleGattServiceRegister = 0x0020, /**< The system has currently CHIPoBLE GATT service registered. */ }; - enum - { - kMaxConnections = BLE_LAYER_NUM_BLE_ENDPOINTS, - kMaxDeviceNameLength = 16, - kMaxAdvertisementDataSetSize = 31, - kMaxRxDataBuffSize = 20, - kMaxTxDataBuffSize = 20 - }; + struct ServiceData; - CHIPoBLEServiceMode mServiceMode; BitFlags mFlags; - char mDeviceName[kMaxDeviceNameLength + 1]; uint16_t mGAPConns; - bool mSubscribedConns[kMaxConnections]; - uint8_t mAdvDataBuf[kMaxAdvertisementDataSetSize]; - uint8_t mScanRespDataBuf[kMaxAdvertisementDataSetSize]; - uint8_t mRxDataBuff[kMaxRxDataBuffSize]; - uint8_t mTxDataBuff[kMaxRxDataBuffSize]; - bool ThreadConnectivityReady; + CHIPoBLEServiceMode mServiceMode; + bool mSubscribedConns[CONFIG_BT_MAX_CONN]; + bt_gatt_indicate_params mIndicateParams[CONFIG_BT_MAX_CONN]; + bt_conn_cb mConnCallbacks; + bt_conn * mconId; +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + PacketBufferHandle c3CharDataBufferHandle; +#endif void DriveBLEState(void); - CHIP_ERROR ConfigureAdvertisingData(void); + CHIP_ERROR ConfigureAdvertising(void); CHIP_ERROR StartAdvertising(void); CHIP_ERROR StopAdvertising(void); - CHIP_ERROR SetSubscribed(uint16_t conId); - bool UnsetSubscribed(uint16_t conId); - bool IsSubscribed(uint16_t conId); - CHIP_ERROR HandleGAPConnect(const ChipDeviceEvent * event); CHIP_ERROR HandleGAPDisconnect(const ChipDeviceEvent * event); - CHIP_ERROR HandleDisconnectRequest(const ChipDeviceEvent * event); CHIP_ERROR HandleRXCharWrite(const ChipDeviceEvent * event); CHIP_ERROR HandleTXCharCCCDWrite(const ChipDeviceEvent * event); CHIP_ERROR HandleTXCharComplete(const ChipDeviceEvent * event); @@ -140,33 +127,43 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla */ CHIP_ERROR HandleThreadStateChange(const ChipDeviceEvent * event); CHIP_ERROR HandleOperationalNetworkEnabled(const ChipDeviceEvent * event); + static void BLEConnDisconnect(chip::System::Layer * aLayer, void * aAppState); + +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + CHIP_ERROR PrepareC3CharData(); +#endif + bool IsSubscribed(bt_conn * conn); + bool SetSubscribed(bt_conn * conn); + bool UnsetSubscribed(bt_conn * conn); + uint32_t GetAdvertisingInterval(); - /* Callbacks from BLE stack*/ static void DriveBLEState(intptr_t arg); + // Below callbacks run from the system workqueue context and have a limited stack capacity. + static void HandleTXIndicated(bt_conn * conn, bt_gatt_indicate_params * attr, uint8_t err); + static void HandleConnect(bt_conn * conn, uint8_t err); + static void HandleDisconnect(bt_conn * conn, uint8_t reason); static void HandleBLEAdvertisementIntervalChange(System::Layer * layer, void * param); - /* Handlers for stack events */ - static void CancelBleAdvTimeoutTimer(void); - static void StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs); + // ===== Members for internal use by the following friends. + + friend BLEManager & BLEMgr(void); + friend BLEManagerImpl & BLEMgrImpl(void); - /* Other init functions */ - CHIP_ERROR _InitStack(void); - void _InitGatt(void); - CHIP_ERROR _InitGap(void); + static BLEManagerImpl sInstance; public: - static int RxWriteCallback(uint16_t connHandle, void * p); - static int TxCccWriteCallback(uint16_t connHandle, void * p); - static void ConnectCallback(uint8_t event, uint8_t * data, int len); - static void DisconnectCallback(uint8_t event, uint8_t * data, int len); - static int GapEventHandler(uint32_t event, uint8_t * data, int size); + // Below callbacks are public in order to be visible from the global scope. + static ssize_t HandleRXWrite(bt_conn * conn, const bt_gatt_attr * attr, const void * buf, uint16_t len, uint16_t offset, + uint8_t flags); + static ssize_t HandleTXCCCWrite(bt_conn * conn, const bt_gatt_attr * attr, uint16_t value); + +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + static ssize_t HandleC3Read(struct bt_conn * conn, const struct bt_gatt_attr * attr, void * buf, uint16_t len, uint16_t offset); +#endif /* Switch to IEEE802154 interface. @todo: remove to other module? */ void SwitchToIeee802154(void); - - /* BLE thread entry */ - static void BleEntry(void *, void *, void *); }; /** @@ -184,7 +181,7 @@ inline BLEManager & BLEMgr(void) * Returns the platform-specific implementation of the BLEManager singleton object. * * Internal components can use this to gain access to features of the BLEManager - * that are specific to the platform. + * that are specific to the Zephyr platforms. */ inline BLEManagerImpl & BLEMgrImpl(void) { diff --git a/src/platform/telink/BUILD.gn b/src/platform/telink/BUILD.gn index 1a4c90395dbe7c..da7e1f39e57d0d 100644 --- a/src/platform/telink/BUILD.gn +++ b/src/platform/telink/BUILD.gn @@ -13,7 +13,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("//build_overrides/telink.gni") import("${chip_root}/src/platform/device.gni") import("${chip_root}/src/platform/telink/args.gni") @@ -48,18 +47,13 @@ static_library("telink") { "SystemPlatformConfig.h", ] - deps = [] - public = [ "${chip_root}/src/credentials/CHIPCert.h", "${chip_root}/src/credentials/CertificationDeclaration.h", "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", ] - public_deps = [ - "${chip_root}/src/platform:platform_base", - "${telink_sdk_build_root}", - ] + public_deps = [ "${chip_root}/src/platform:platform_base" ] if (chip_enable_factory_data) { sources += [ diff --git a/src/platform/telink/BlePlatformConfig.h b/src/platform/telink/BlePlatformConfig.h index 6b451d7b88c1ca..8667470deffb68 100644 --- a/src/platform/telink/BlePlatformConfig.h +++ b/src/platform/telink/BlePlatformConfig.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,10 +24,12 @@ #pragma once +#include + // ==================== Platform Adaptations ==================== -#define BLE_CONNECTION_OBJECT uint16_t -#define BLE_CONNECTION_UNINITIALIZED ((uint16_t) 0xFFFF) +#define BLE_CONNECTION_OBJECT bt_conn * +#define BLE_CONNECTION_UNINITIALIZED nullptr #define BLE_MAX_RECEIVE_WINDOW_SIZE 5 // ========== Platform-specific Configuration Overrides ========= diff --git a/src/platform/telink/CHIPDevicePlatformConfig.h b/src/platform/telink/CHIPDevicePlatformConfig.h index 6af8812f70d5a8..28c93f1d4e6ee9 100644 --- a/src/platform/telink/CHIPDevicePlatformConfig.h +++ b/src/platform/telink/CHIPDevicePlatformConfig.h @@ -92,6 +92,8 @@ #define CHIP_DEVICE_CONFIG_ENABLE_THREAD CONFIG_NET_L2_OPENTHREAD +#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE CONFIG_BT + // ========== Platform-specific Configuration ========= // These are configuration options that are unique to Zephyr platforms. @@ -175,7 +177,7 @@ // ========== Platform-specific Configuration Overrides ========= #ifndef CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY -#define CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY (K_PRIO_COOP(CONFIG_NUM_COOP_PRIORITIES - 1)) +#define CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY (K_PRIO_PREEMPT(1)) #endif // CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY #ifndef CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE @@ -195,15 +197,17 @@ #endif // CONFIG_CHIP_ENABLE_PAIRING_AUTOSTART #ifdef CONFIG_CHIP_ENABLE_DNSSD_SRP -#define CHIP_DEVICE_CONFIG_ENABLE_MDNS 1 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 -#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DISCOVERY 1 #ifdef CONFIG_CHIP_ENABLE_DNS_CLIENT #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_DNS_CLIENT 1 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_COMMISSIONABLE_DISCOVERY 1 #endif // CONFIG_CHIP_ENABLE_DNS_CLIENT #endif // CONFIG_CHIP_ENABLE_DNSSD_SRP +#ifdef CONFIG_CHIP_COMMISSIONABLE_DEVICE_TYPE +#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DEVICE_TYPE 1 +#endif // CONFIG_CHIP_COMMISSIONABLE_DEVICE_TYPE + #ifdef CONFIG_CHIP_DEVICE_TYPE #define CHIP_DEVICE_CONFIG_DEVICE_TYPE CONFIG_CHIP_DEVICE_TYPE #endif // CONFIG_CHIP_DEVICE_TYPE diff --git a/src/platform/telink/CHIPDevicePlatformEvent.h b/src/platform/telink/CHIPDevicePlatformEvent.h index b04059508c1bf6..a1f53347bc9c5a 100644 --- a/src/platform/telink/CHIPDevicePlatformEvent.h +++ b/src/platform/telink/CHIPDevicePlatformEvent.h @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,76 +24,4 @@ #pragma once -#include - -#include - -namespace chip { -namespace DeviceLayer { - -namespace DeviceEventType { - -/** - * Enumerates Telink platform-specific event types that are visible to the application. - */ -enum PublicPlatformSpecificEventTypes -{ - /* None currently defined */ -}; - -/** - * Enumerates Telink platform-specific event types that are internal to the chip Device Layer. - */ -enum InternalPlatformSpecificEventTypes -{ - kPlatformTelinkEvent = kRange_InternalPlatformSpecific, - kPlatformTelinkBleConnected, - kPlatformTelinkBleDisconnected, - kPlatformTelinkBleDisconnectRequest, - kPlatformTelinkBleCCCWrite, - kPlatformTelinkBleRXWrite, - kPlatformTelinkBleTXComplete, - kPlatformTelinkBleOutOfBuffersEvent, -}; - -} // namespace DeviceEventType - -struct BleConnEventType -{ - uint16_t connHandle; - uint8_t HciResult; -}; - -struct BleCCCWriteEventType -{ - uint16_t connHandle; - uint16_t Value; -}; - -struct BleRXWriteEventType -{ - uint16_t connHandle; - ::chip::System::PacketBuffer * Data; -}; - -struct BleTXCompleteEventType -{ - uint16_t connHandle; -}; - -/** - * Represents platform-specific event information for Zephyr platforms. - */ -struct ChipDevicePlatformEvent final -{ - union - { - BleConnEventType BleConnEvent; - BleCCCWriteEventType BleCCCWriteEvent; - BleRXWriteEventType BleRXWriteEvent; - BleTXCompleteEventType BleTXCompleteEvent; - }; -}; - -} // namespace DeviceLayer -} // namespace chip +#include diff --git a/src/platform/telink/CHIPPlatformConfig.h b/src/platform/telink/CHIPPlatformConfig.h index 85cc1c85736c75..f78ab8791d1253 100644 --- a/src/platform/telink/CHIPPlatformConfig.h +++ b/src/platform/telink/CHIPPlatformConfig.h @@ -30,24 +30,24 @@ #define CHIP_CONFIG_PERSISTED_STORAGE_KEY_TYPE const char * #define CHIP_CONFIG_PERSISTED_STORAGE_MAX_KEY_LENGTH 2 -/** - * @def CHIP_CONFIG_MAX_FABRICS - * - * @brief - * Maximum number of fabrics the device can participate in. Each fabric can - * provision the device with its unique operational credentials and manage - * its own access control lists. - */ -#ifndef CHIP_CONFIG_MAX_FABRICS -#define CHIP_CONFIG_MAX_FABRICS 5 // 4 fabrics + 1 for rotation slack -#endif +#define CHIP_CONFIG_LIFETIIME_PERSISTED_COUNTER_KEY "rc" // ==================== Security Adaptations ==================== +#ifdef CONFIG_CHIP_CRYPTO_PSA +#define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(psa_hash_operation_t) +#elif defined(CONFIG_CC3XX_BACKEND) +// Size of the statically allocated context for SHA256 operations in CryptoPAL +// determined empirically. +#define CHIP_CONFIG_SHA256_CONTEXT_SIZE 244 +#else +#define CHIP_CONFIG_SHA256_CONTEXT_SIZE 208 +#endif + // ==================== General Configuration Overrides ==================== #ifndef CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS -#define CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS 16 +#define CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS 8 #endif // CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS #ifndef CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS @@ -61,3 +61,7 @@ #ifndef CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS #define CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS 1 #endif // CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS + +#ifndef CHIP_CONFIG_MAX_FABRICS +#define CHIP_CONFIG_MAX_FABRICS 5 +#endif diff --git a/src/platform/telink/FactoryDataProvider.h b/src/platform/telink/FactoryDataProvider.h index 040a0d44ca9ba8..829831e554aa33 100644 --- a/src/platform/telink/FactoryDataProvider.h +++ b/src/platform/telink/FactoryDataProvider.h @@ -34,8 +34,8 @@ struct InternalFlashFactoryData { CHIP_ERROR GetFactoryDataPartition(uint8_t *& data, size_t & dataSize) { - data = reinterpret_cast(FLASH_AREA_OFFSET(factory_data)); - dataSize = FLASH_AREA_SIZE(factory_data); + data = reinterpret_cast(FIXED_PARTITION_OFFSET(factory_partition)); + dataSize = FIXED_PARTITION_SIZE(factory_partition); return CHIP_NO_ERROR; } @@ -46,7 +46,8 @@ struct ExternalFlashFactoryData { CHIP_ERROR GetFactoryDataPartition(uint8_t *& data, size_t & dataSize) { - int ret = flash_read(mFlashDevice, FLASH_AREA_OFFSET(factory_data), mFactoryDataBuffer, FLASH_AREA_SIZE(factory_data)); + int ret = flash_read(mFlashDevice, FIXED_PARTITION_OFFSET(factory_partition), mFactoryDataBuffer, + FIXED_PARTITION_SIZE(factory_partition)); if (ret != 0) { @@ -54,7 +55,7 @@ struct ExternalFlashFactoryData } data = mFactoryDataBuffer; - dataSize = FLASH_AREA_SIZE(factory_data); + dataSize = FIXED_PARTITION_SIZE(factory_partition); return CHIP_NO_ERROR; } @@ -62,7 +63,7 @@ struct ExternalFlashFactoryData CHIP_ERROR ProtectFactoryDataPartitionAgainstWrite() { return CHIP_ERROR_NOT_IMPLEMENTED; } const struct device * mFlashDevice = DEVICE_DT_GET(DT_CHOSEN(zephyr_flash_controller)); - uint8_t mFactoryDataBuffer[FLASH_AREA_SIZE(factory_data)]; + uint8_t mFactoryDataBuffer[FIXED_PARTITION_SIZE(factory_partition)]; }; template @@ -107,8 +108,8 @@ class FactoryDataProvider : public chip::Credentials::DeviceAttestationCredentia CHIP_ERROR GetEnableKey(MutableByteSpan & enableKey); private: - static constexpr uint16_t kFactoryDataPartitionSize = FLASH_AREA_SIZE(factory_data); - static constexpr uint32_t kFactoryDataPartitionAddress = FLASH_AREA_OFFSET(factory_data); + static constexpr uint16_t kFactoryDataPartitionSize = FIXED_PARTITION_SIZE(factory_partition); + static constexpr uint32_t kFactoryDataPartitionAddress = FIXED_PARTITION_OFFSET(factory_partition); static constexpr uint8_t kDACPrivateKeyLength = 32; static constexpr uint8_t kDACPublicKeyLength = 65; diff --git a/src/platform/telink/OTAImageProcessorImpl.cpp b/src/platform/telink/OTAImageProcessorImpl.cpp index f0c3c4de5cdd35..b5649820dace72 100644 --- a/src/platform/telink/OTAImageProcessorImpl.cpp +++ b/src/platform/telink/OTAImageProcessorImpl.cpp @@ -52,8 +52,8 @@ CHIP_ERROR OTAImageProcessorImpl::PrepareDownloadImpl() return System::MapErrorZephyr(-EFAULT); } - int err = - stream_flash_init(&stream, flash_dev, mBuffer, sizeof(mBuffer), FLASH_AREA_OFFSET(image_1), FLASH_AREA_SIZE(image_1), NULL); + int err = stream_flash_init(&stream, flash_dev, mBuffer, sizeof(mBuffer), FIXED_PARTITION_OFFSET(slot1_partition), + FIXED_PARTITION_SIZE(slot1_partition), NULL); if (err) { diff --git a/third_party/telink_sdk/BUILD.gn b/third_party/telink_sdk/BUILD.gn deleted file mode 100644 index ac8b84a8177e0a..00000000000000 --- a/third_party/telink_sdk/BUILD.gn +++ /dev/null @@ -1,47 +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. - -import("//build_overrides/telink.gni") - -config("telink_sdk_config") { - include_dirs = [ - "${telink_sdk_build_root}/repo/eagle_ble_sdk", - "${telink_sdk_build_root}/repo/eagle_ble_sdk/drivers/B91", - "${telink_sdk_build_root}/repo/eagle_ble_sdk/stack/ble", - "${telink_sdk_build_root}/repo/eagle_ble_sdk/stack/ble/controller", - "${telink_sdk_build_root}/repo/eagle_ble_sdk/vendor/common", - ] - - libs = [ - "${telink_sdk_build_root}/repo/eagle_ble_sdk/proj_lib/libB91_ble_lib.a", - ] - - defines = [ - "USE_ZEPHYR_HAL_HEADERS", - "MCU_CORE_TYPE = MCU_CORE_9518", - ] - - cflags = [] -} - -source_set("telink_sdk") { - sources = [ - "${telink_sdk_build_root}/repo/eagle_ble_sdk/common/utility.c", - "${telink_sdk_build_root}/repo/eagle_ble_sdk/drivers/B91/aes.c", - "${telink_sdk_build_root}/repo/eagle_ble_sdk/drivers/B91/ext_driver/software_pa.c", - "${telink_sdk_build_root}/repo/eagle_ble_sdk/vendor/common/blt_common.c", - ] - - public_configs = [ ":telink_sdk_config" ] -} diff --git a/third_party/telink_sdk/repo b/third_party/telink_sdk/repo deleted file mode 160000 index 6a3cb0a3615cf7..00000000000000 --- a/third_party/telink_sdk/repo +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 6a3cb0a3615cf7f2f0418440d3ae9d93f6f3e595