From 2436705cabb9c9643fc829963008403db129de6f Mon Sep 17 00:00:00 2001 From: Alex Tsitsiura Date: Fri, 6 Jan 2023 22:27:52 +0200 Subject: [PATCH] [Telink] Update apps and configs & Update Telink image to 0.6.27 (#24200) * [Telink] Rework flash partitions & use swap move algorithm * [Telink] Removed timer to BLE disconnect * [Telink] Rework flash partitions & use swap move algorithm * [Telink] Use latest Telink mcuboot changes * [Telink] Enable reboot system when fault happened * [Telink] Rework system status LED loop and made the Factory-Reset Button more user friendly * [Telink] Revert submodule change * [Telink] Added last changes also to the Thermostat example * [Telink] Restyled * [Telink] Add contact sensor app example * [Telink] Add new target for CI * [Telink] Fix device re-pairing * [Telink] Enable NVS lookup cache * [Telink] Update every image to 0.6.27 * [Telink] Ordered by alphabet targets * [Telink] Fix example name * Revert "[Telink] Update every image to 0.6.27" This reverts commit 6df90e712929e7e6dc5eb68b68a2ac75d9a47a61. * [Telink] Update Telink image to 0.6.27 Co-authored-by: Serhii Salamakha Co-authored-by: Andrii Bilynskyi --- .github/workflows/examples-telink.yaml | 12 +- .vscode/tasks.json | 1 + config/telink/app/zephyr.conf | 6 + config/telink/chip-module/CMakeLists.txt | 18 +- .../telink/include/AppEvent.h | 12 + .../all-clusters-app/telink/include/AppTask.h | 6 + .../all-clusters-app/telink/src/AppTask.cpp | 104 +++- .../telink/include/AppEvent.h | 12 + .../telink/include/AppTask.h | 6 + .../telink/src/AppTask.cpp | 102 +++- examples/contact-sensor-app/telink/.gitignore | 1 + .../contact-sensor-app/telink/CMakeLists.txt | 64 +++ examples/contact-sensor-app/telink/Readme.md | 159 ++++++ .../telink/include/AppConfig.h | 37 ++ .../telink/include/AppEvent.h | 57 ++ .../telink/include/AppTask.h | 107 ++++ .../telink/include/CHIPProjectConfig.h | 39 ++ .../telink/include/ContactSensorManager.h | 62 +++ examples/contact-sensor-app/telink/prj.conf | 58 ++ .../contact-sensor-app/telink/src/AppTask.cpp | 524 ++++++++++++++++++ .../telink/src/ContactSensorManager.cpp | 87 +++ .../telink/src/ZclCallbacks.cpp | 56 ++ .../contact-sensor-app/telink/src/main.cpp | 82 +++ .../telink/third_party/connectedhomeip | 1 + .../telink/include/AppEvent.h | 7 + .../light-switch-app/telink/include/AppTask.h | 6 + .../light-switch-app/telink/src/AppTask.cpp | 109 +++- .../lighting-app/telink/include/AppEvent.h | 7 + .../lighting-app/telink/include/AppTask.h | 7 +- examples/lighting-app/telink/src/AppTask.cpp | 114 +++- .../telink/include/AppEvent.h | 7 + .../telink/include/AppTask.h | 6 + .../ota-requestor-app/telink/src/AppTask.cpp | 104 +++- .../telink/util/include/ButtonManager.h | 3 +- .../platform/telink/util/include/LEDWidget.h | 11 +- .../telink/util/src/ButtonManager.cpp | 21 +- .../platform/telink/util/src/LEDWidget.cpp | 59 +- examples/thermostat/telink/include/AppEvent.h | 7 + examples/thermostat/telink/include/AppTask.h | 6 + examples/thermostat/telink/src/AppTask.cpp | 107 +++- scripts/build/build/targets.py | 1 + scripts/build/builders/telink.py | 5 + .../build/testdata/all_targets_linux_x64.txt | 2 +- scripts/tools/telink/mfg_tool.py | 2 +- scripts/tools/telink/readme.md | 2 +- src/platform/telink/BLEManagerImpl.cpp | 15 +- src/platform/telink/BLEManagerImpl.h | 1 - 47 files changed, 2055 insertions(+), 167 deletions(-) create mode 100644 examples/contact-sensor-app/telink/.gitignore create mode 100755 examples/contact-sensor-app/telink/CMakeLists.txt create mode 100755 examples/contact-sensor-app/telink/Readme.md create mode 100755 examples/contact-sensor-app/telink/include/AppConfig.h create mode 100755 examples/contact-sensor-app/telink/include/AppEvent.h create mode 100644 examples/contact-sensor-app/telink/include/AppTask.h create mode 100755 examples/contact-sensor-app/telink/include/CHIPProjectConfig.h create mode 100644 examples/contact-sensor-app/telink/include/ContactSensorManager.h create mode 100755 examples/contact-sensor-app/telink/prj.conf create mode 100644 examples/contact-sensor-app/telink/src/AppTask.cpp create mode 100644 examples/contact-sensor-app/telink/src/ContactSensorManager.cpp create mode 100644 examples/contact-sensor-app/telink/src/ZclCallbacks.cpp create mode 100755 examples/contact-sensor-app/telink/src/main.cpp create mode 120000 examples/contact-sensor-app/telink/third_party/connectedhomeip diff --git a/.github/workflows/examples-telink.yaml b/.github/workflows/examples-telink.yaml index 9e5737c84828f9..28d5c7faf03f4f 100644 --- a/.github/workflows/examples-telink.yaml +++ b/.github/workflows/examples-telink.yaml @@ -35,8 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - # TODO: update this to connectedhomeip/chip-build-vscode:0.6.27 once we can compile - image: connectedhomeip/chip-build-telink:0.6.18 + image: connectedhomeip/chip-build-telink:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -76,6 +75,15 @@ jobs: out/telink-tlsr9518adk80d-all-clusters-minimal/zephyr/zephyr.elf \ /tmp/bloat_reports/ + - name: Build example Telink Contact Sensor App + run: | + ./scripts/run_in_build_env.sh \ + "./scripts/build/build_examples.py --target 'telink-tlsr9518adk80d-contact-sensor' build" + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ + telink tlsr9518adk80d contact-sensor-app \ + out/telink-tlsr9518adk80d-contact-sensor/zephyr/zephyr.elf \ + /tmp/bloat_reports/ + - name: Build example Telink Lighting App run: | ./scripts/run_in_build_env.sh \ diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 2dfa9587570c4d..32db085151c081 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -638,6 +638,7 @@ "qpg-qpg6100-lock", "telink-tlsr9518adk80d-all-clusters", "telink-tlsr9518adk80d-all-clusters-minimal", + "telink-tlsr9518adk80d-contact-sensor", "telink-tlsr9518adk80d-light", "telink-tlsr9518adk80d-light-switch", "telink-tlsr9518adk80d-ota-requestor", diff --git a/config/telink/app/zephyr.conf b/config/telink/app/zephyr.conf index 0bb8ffeca65103..9d02f8f06d4b31 100644 --- a/config/telink/app/zephyr.conf +++ b/config/telink/app/zephyr.conf @@ -118,6 +118,12 @@ CONFIG_DYNAMIC_INTERRUPTS=y # nvs_sector_size = flash_page_size * mult = 256 * 8 = 2048 CONFIG_SETTINGS_NVS_SECTOR_SIZE_MULT=8 +# Enable NVS lookup cache +CONFIG_NVS_LOOKUP_CACHE=y + +# Reboot system when fault happened +CONFIG_TELINK_B91_REBOOT_ON_FAULT=y + # Shell settings CONFIG_SHELL=n CONFIG_SHELL_BACKEND_SERIAL_RX_RING_BUFFER_SIZE=255 diff --git a/config/telink/chip-module/CMakeLists.txt b/config/telink/chip-module/CMakeLists.txt index 2328ef28c13893..4f1ed485c156b4 100644 --- a/config/telink/chip-module/CMakeLists.txt +++ b/config/telink/chip-module/CMakeLists.txt @@ -297,21 +297,14 @@ add_dependencies(chip chip-gn) if (CONFIG_CHIP_OTA_IMAGE_BUILD) add_custom_target(build_mcuboot ALL COMMAND - west build -b tlsr9518adk80d -d build_mcuboot ${ZEPHYR_BASE}/../bootloader/mcuboot/boot/zephyr - ) - - 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 - BYPRODUCTS - ${PROJECT_BINARY_DIR}/zephyr.signed.bin + west build -b tlsr9518adk80d -d build_mcuboot ${ZEPHYR_BASE}/../bootloader/mcuboot/boot/zephyr -- -DCONFIG_BOOT_SWAP_USING_MOVE=y ) add_custom_target(merge_mcuboot ALL COMMAND dd if=${PROJECT_BINARY_DIR}/../modules/chip-module/build_mcuboot/zephyr/zephyr.bin of=${PROJECT_BINARY_DIR}/zephyr.bin COMMAND - dd if=${PROJECT_BINARY_DIR}/zephyr.signed.bin of=${PROJECT_BINARY_DIR}/zephyr.bin bs=1024 seek=96 + dd if=${PROJECT_BINARY_DIR}/zephyr.signed.bin of=${PROJECT_BINARY_DIR}/zephyr.bin bs=1024 seek=76 ) chip_ota_image(chip-ota-image @@ -319,15 +312,14 @@ if (CONFIG_CHIP_OTA_IMAGE_BUILD) OUTPUT_FILE ${PROJECT_BINARY_DIR}/zephyr-ota.bin ) - add_dependencies(west_sign ${ZEPHYR_FINAL_EXECUTABLE}) - add_dependencies(merge_mcuboot west_sign) - add_dependencies(chip-ota-image west_sign) + add_dependencies(merge_mcuboot ${ZEPHYR_FINAL_EXECUTABLE}) + add_dependencies(chip-ota-image ${ZEPHYR_FINAL_EXECUTABLE}) endif() if (CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE) add_custom_target(merge_factory_data ALL COMMAND - dd if=${PROJECT_BINARY_DIR}/factory/factory_data.bin of=${PROJECT_BINARY_DIR}/zephyr.bin bs=1024 seek=2000 + dd if=${PROJECT_BINARY_DIR}/factory/factory_data.bin of=${PROJECT_BINARY_DIR}/zephyr.bin bs=1024 seek=1040 ) if (CONFIG_CHIP_OTA_IMAGE_BUILD) add_dependencies(merge_factory_data merge_mcuboot) diff --git a/examples/all-clusters-app/telink/include/AppEvent.h b/examples/all-clusters-app/telink/include/AppEvent.h index 000f3e8653d3ff..54250995e06ca8 100644 --- a/examples/all-clusters-app/telink/include/AppEvent.h +++ b/examples/all-clusters-app/telink/include/AppEvent.h @@ -23,11 +23,15 @@ struct AppEvent; typedef void (*EventHandler)(AppEvent *); +class LEDWidget; + struct AppEvent { enum AppEventTypes { kEventType_Button = 0, + kEventType_Timer, + kEventType_UpdateLedState, }; uint16_t Type; @@ -38,6 +42,14 @@ struct AppEvent { uint8_t Action; } ButtonEvent; + struct + { + void * Context; + } TimerEvent; + struct + { + LEDWidget * LedWidget; + } UpdateLedStateEvent; }; EventHandler Handler; diff --git a/examples/all-clusters-app/telink/include/AppTask.h b/examples/all-clusters-app/telink/include/AppTask.h index d893794235fb47..7787968458b867 100644 --- a/examples/all-clusters-app/telink/include/AppTask.h +++ b/examples/all-clusters-app/telink/include/AppTask.h @@ -19,6 +19,7 @@ #pragma once #include "AppEvent.h" +#include "LEDWidget.h" #include @@ -43,15 +44,20 @@ class AppTask void DispatchEvent(AppEvent * event); static void UpdateStatusLED(); + static void LEDStateUpdateHandler(LEDWidget * ledWidget); static void FactoryResetButtonEventHandler(void); static void StartThreadButtonEventHandler(void); static void StartBleAdvButtonEventHandler(void); static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + static void FactoryResetTimerTimeoutCallback(k_timer * timer); + + static void FactoryResetTimerEventHandler(AppEvent * aEvent); static void FactoryResetHandler(AppEvent * aEvent); static void StartThreadHandler(AppEvent * aEvent); static void StartBleAdvHandler(AppEvent * aEvent); + static void UpdateLedStateEventHandler(AppEvent * aEvent); static void InitButtons(void); diff --git a/examples/all-clusters-app/telink/src/AppTask.cpp b/examples/all-clusters-app/telink/src/AppTask.cpp index f5b8cac574c23a..9f831beecfaf9b 100644 --- a/examples/all-clusters-app/telink/src/AppTask.cpp +++ b/examples/all-clusters-app/telink/src/AppTask.cpp @@ -21,7 +21,6 @@ #include "AppConfig.h" #include "AppEvent.h" #include "ButtonManager.h" -#include "LEDWidget.h" #include "binding-handler.h" #include #include @@ -48,12 +47,13 @@ LOG_MODULE_DECLARE(app); namespace { - -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); +k_timer sFactoryResetTimer; LEDWidget sStatusLED; @@ -61,10 +61,11 @@ Button sFactoryResetButton; Button sThreadStartButton; Button sBleAdvStartButton; -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; +bool sIsThreadProvisioned = false; +bool sIsThreadEnabled = false; +bool sIsThreadAttached = false; +bool sHaveBLEConnections = false; +bool sIsFactoryResetTimerActive = false; chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; @@ -108,6 +109,17 @@ using namespace ::chip::DeviceLayer::Internal; AppTask AppTask::sAppTask; +class AppFabricTableDelegate : public FabricTable::Delegate +{ + void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) + { + if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + } +}; + constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; CHIP_ERROR AppTask::Init() @@ -118,12 +130,17 @@ CHIP_ERROR AppTask::Init() // Initialize status LED LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); sStatusLED.Init(SYSTEM_STATE_LED_PIN); UpdateStatusLED(); InitButtons(); + // Initialize function button timer + k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); + k_timer_user_data_set(&sFactoryResetTimer, this); + // Init ZCL Data Model and start server static chip::CommonCaseDeviceServerInitParams initParams; (void) initParams.InitializeStaticResourcesBeforeServerInit(); @@ -168,6 +185,13 @@ CHIP_ERROR AppTask::Init() return ret; } + ret = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); + if (ret != CHIP_NO_ERROR) + { + LOG_ERR("AppFabricTableDelegate fail"); + return ret; + } + return CHIP_NO_ERROR; } @@ -192,8 +216,6 @@ CHIP_ERROR AppTask::StartApp() DispatchEvent(&event); ret = k_msgq_get(&sAppEventQueue, &event, K_NO_WAIT); } - - sStatusLED.Animate(); } } @@ -209,8 +231,16 @@ void AppTask::FactoryResetButtonEventHandler(void) void AppTask::FactoryResetHandler(AppEvent * aEvent) { - LOG_INF("FactoryResetHandler"); - chip::Server::GetInstance().ScheduleFactoryReset(); + if (!sIsFactoryResetTimerActive) + { + k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetTriggerTimeout), K_NO_WAIT); + sIsFactoryResetTimerActive = true; + } + else + { + k_timer_stop(&sFactoryResetTimer); + sIsFactoryResetTimerActive = false; + } } void AppTask::StartThreadButtonEventHandler(void) @@ -272,6 +302,23 @@ void AppTask::StartBleAdvHandler(AppEvent * aEvent) } } +void AppTask::UpdateLedStateEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type == AppEvent::kEventType_UpdateLedState) + { + aEvent->UpdateLedStateEvent.LedWidget->UpdateState(); + } +} + +void AppTask::LEDStateUpdateHandler(LEDWidget * ledWidget) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateLedStateEventHandler; + event.UpdateLedStateEvent.LedWidget = ledWidget; + sAppTask.PostEvent(&event); +} + void AppTask::UpdateStatusLED() { if (sIsThreadProvisioned && sIsThreadEnabled) @@ -342,11 +389,36 @@ void AppTask::DispatchEvent(AppEvent * aEvent) } } +void AppTask::FactoryResetTimerTimeoutCallback(k_timer * timer) +{ + if (!timer) + { + return; + } + + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.Handler = FactoryResetTimerEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::FactoryResetTimerEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type != AppEvent::kEventType_Timer) + { + return; + } + + sIsFactoryResetTimerActive = false; + LOG_INF("FactoryResetHandler"); + chip::Server::GetInstance().ScheduleFactoryReset(); +} + void AppTask::InitButtons(void) { - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); + sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, true, FactoryResetButtonEventHandler); + sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, false, StartThreadButtonEventHandler); + sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, false, StartBleAdvButtonEventHandler); ButtonManagerInst().AddButton(sFactoryResetButton); ButtonManagerInst().AddButton(sThreadStartButton); diff --git a/examples/all-clusters-minimal-app/telink/include/AppEvent.h b/examples/all-clusters-minimal-app/telink/include/AppEvent.h index 000f3e8653d3ff..54250995e06ca8 100644 --- a/examples/all-clusters-minimal-app/telink/include/AppEvent.h +++ b/examples/all-clusters-minimal-app/telink/include/AppEvent.h @@ -23,11 +23,15 @@ struct AppEvent; typedef void (*EventHandler)(AppEvent *); +class LEDWidget; + struct AppEvent { enum AppEventTypes { kEventType_Button = 0, + kEventType_Timer, + kEventType_UpdateLedState, }; uint16_t Type; @@ -38,6 +42,14 @@ struct AppEvent { uint8_t Action; } ButtonEvent; + struct + { + void * Context; + } TimerEvent; + struct + { + LEDWidget * LedWidget; + } UpdateLedStateEvent; }; EventHandler Handler; diff --git a/examples/all-clusters-minimal-app/telink/include/AppTask.h b/examples/all-clusters-minimal-app/telink/include/AppTask.h index d6a02734a40e74..7d0168759055d0 100644 --- a/examples/all-clusters-minimal-app/telink/include/AppTask.h +++ b/examples/all-clusters-minimal-app/telink/include/AppTask.h @@ -19,6 +19,7 @@ #pragma once #include "AppEvent.h" +#include "LEDWidget.h" #include @@ -43,13 +44,18 @@ class AppTask void DispatchEvent(AppEvent * event); static void UpdateStatusLED(); + static void LEDStateUpdateHandler(LEDWidget * ledWidget); static void FactoryResetButtonEventHandler(void); static void StartBleAdvButtonEventHandler(void); static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + static void FactoryResetTimerTimeoutCallback(k_timer * timer); + + static void FactoryResetTimerEventHandler(AppEvent * aEvent); static void FactoryResetHandler(AppEvent * aEvent); static void StartBleAdvHandler(AppEvent * aEvent); + static void UpdateLedStateEventHandler(AppEvent * aEvent); static void InitButtons(void); diff --git a/examples/all-clusters-minimal-app/telink/src/AppTask.cpp b/examples/all-clusters-minimal-app/telink/src/AppTask.cpp index 8ecf29eda06939..4d0f29cb87efea 100644 --- a/examples/all-clusters-minimal-app/telink/src/AppTask.cpp +++ b/examples/all-clusters-minimal-app/telink/src/AppTask.cpp @@ -21,7 +21,6 @@ #include "AppConfig.h" #include "AppEvent.h" #include "ButtonManager.h" -#include "LEDWidget.h" #include "binding-handler.h" #include #include @@ -45,22 +44,24 @@ LOG_MODULE_DECLARE(app); namespace { - -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); +k_timer sFactoryResetTimer; LEDWidget sStatusLED; Button sFactoryResetButton; Button sBleAdvStartButton; -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; +bool sIsThreadProvisioned = false; +bool sIsThreadEnabled = false; +bool sIsThreadAttached = false; +bool sHaveBLEConnections = false; +bool sIsFactoryResetTimerActive = false; } // namespace @@ -71,6 +72,17 @@ using namespace ::chip::DeviceLayer::Internal; AppTask AppTask::sAppTask; +class AppFabricTableDelegate : public FabricTable::Delegate +{ + void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) + { + if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + } +}; + constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; CHIP_ERROR AppTask::Init() @@ -81,12 +93,17 @@ CHIP_ERROR AppTask::Init() // Initialize status LED LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); sStatusLED.Init(SYSTEM_STATE_LED_PIN); UpdateStatusLED(); InitButtons(); + // Initialize function button timer + k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); + k_timer_user_data_set(&sFactoryResetTimer, this); + // Init ZCL Data Model and start server static chip::CommonCaseDeviceServerInitParams initParams; (void) initParams.InitializeStaticResourcesBeforeServerInit(); @@ -128,6 +145,13 @@ CHIP_ERROR AppTask::Init() return ret; } + ret = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); + if (ret != CHIP_NO_ERROR) + { + LOG_ERR("AppFabricTableDelegate fail"); + return ret; + } + return CHIP_NO_ERROR; } @@ -152,8 +176,6 @@ CHIP_ERROR AppTask::StartApp() DispatchEvent(&event); ret = k_msgq_get(&sAppEventQueue, &event, K_NO_WAIT); } - - sStatusLED.Animate(); } } @@ -169,8 +191,16 @@ void AppTask::FactoryResetButtonEventHandler(void) void AppTask::FactoryResetHandler(AppEvent * aEvent) { - LOG_INF("FactoryResetHandler"); - chip::Server::GetInstance().ScheduleFactoryReset(); + if (!sIsFactoryResetTimerActive) + { + k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetTriggerTimeout), K_NO_WAIT); + sIsFactoryResetTimerActive = true; + } + else + { + k_timer_stop(&sFactoryResetTimer); + sIsFactoryResetTimerActive = false; + } } void AppTask::StartBleAdvButtonEventHandler(void) @@ -206,6 +236,23 @@ void AppTask::StartBleAdvHandler(AppEvent * aEvent) } } +void AppTask::UpdateLedStateEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type == AppEvent::kEventType_UpdateLedState) + { + aEvent->UpdateLedStateEvent.LedWidget->UpdateState(); + } +} + +void AppTask::LEDStateUpdateHandler(LEDWidget * ledWidget) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateLedStateEventHandler; + event.UpdateLedStateEvent.LedWidget = ledWidget; + sAppTask.PostEvent(&event); +} + void AppTask::UpdateStatusLED() { if (sIsThreadProvisioned && sIsThreadEnabled) @@ -276,10 +323,35 @@ void AppTask::DispatchEvent(AppEvent * aEvent) } } +void AppTask::FactoryResetTimerTimeoutCallback(k_timer * timer) +{ + if (!timer) + { + return; + } + + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.Handler = FactoryResetTimerEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::FactoryResetTimerEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type != AppEvent::kEventType_Timer) + { + return; + } + + sIsFactoryResetTimerActive = false; + LOG_INF("FactoryResetHandler"); + chip::Server::GetInstance().ScheduleFactoryReset(); +} + void AppTask::InitButtons(void) { - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); + sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, true, FactoryResetButtonEventHandler); + sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, false, StartBleAdvButtonEventHandler); ButtonManagerInst().AddButton(sFactoryResetButton); ButtonManagerInst().AddButton(sBleAdvStartButton); diff --git a/examples/contact-sensor-app/telink/.gitignore b/examples/contact-sensor-app/telink/.gitignore new file mode 100644 index 00000000000000..84c048a73cc2e5 --- /dev/null +++ b/examples/contact-sensor-app/telink/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/examples/contact-sensor-app/telink/CMakeLists.txt b/examples/contact-sensor-app/telink/CMakeLists.txt new file mode 100755 index 00000000000000..b75ad4764331b4 --- /dev/null +++ b/examples/contact-sensor-app/telink/CMakeLists.txt @@ -0,0 +1,64 @@ +# +# Copyright (c) 2022 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +cmake_minimum_required(VERSION 3.13.1) + +set(BOARD tlsr9518adk80d) + +get_filename_component(CHIP_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/third_party/connectedhomeip REALPATH) +get_filename_component(TELINK_COMMON ${CHIP_ROOT}/examples/platform/telink REALPATH) +get_filename_component(GEN_DIR ${CHIP_ROOT}/zzz_generated/ REALPATH) + +set(CONF_FILE ${CHIP_ROOT}/config/telink/app/zephyr.conf prj.conf) + +# Load NCS/Zephyr build system +list(APPEND ZEPHYR_EXTRA_MODULES ${CHIP_ROOT}/config/telink/chip-module) +find_package(Zephyr HINTS $ENV{ZEPHYR_BASE}) + +project(chip-telink-contact-sensor-example) + +include(${CHIP_ROOT}/config/telink/app/enable-gnu-std.cmake) +include(${CHIP_ROOT}/src/app/chip_data_model.cmake) + +target_compile_options(app PRIVATE -fpermissive) + +target_include_directories(app PRIVATE + include + ${GEN_DIR}/app-common + ${GEN_DIR}/contact-sensor-app + ${TELINK_COMMON}/util/include) + +add_definitions( + "-DCHIP_ADDRESS_RESOLVE_IMPL_INCLUDE_HEADER=" +) + +target_sources(app PRIVATE + src/AppTask.cpp + src/ContactSensorManager.cpp + src/main.cpp + src/ZclCallbacks.cpp + ${GEN_DIR}/contact-sensor-app/zap-generated/IMClusterCommandHandler.cpp + ${TELINK_COMMON}/util/src/LEDWidget.cpp + ${TELINK_COMMON}/util/src/ButtonManager.cpp + ${TELINK_COMMON}/util/src/ThreadUtil.cpp) + +chip_configure_data_model(app + INCLUDE_SERVER + ZAP_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../contact-sensor-common/contact-sensor-app.zap +) + +if(CONFIG_CHIP_OTA_REQUESTOR) + target_sources(app PRIVATE ${TELINK_COMMON}/util/src/OTAUtil.cpp) +endif() diff --git a/examples/contact-sensor-app/telink/Readme.md b/examples/contact-sensor-app/telink/Readme.md new file mode 100755 index 00000000000000..31b004dd7aaa5b --- /dev/null +++ b/examples/contact-sensor-app/telink/Readme.md @@ -0,0 +1,159 @@ +# Matter Telink Contact Sensor Example Application + +You can use this example as a reference for creating your own application. + +![Telink B91 EVK](http://wiki.telink-semi.cn/wiki/assets/Hardware/B91_Generic_Starter_Kit_Hardware_Guide/connection_chart.png) + +## Build and flash + +1. Pull docker image from repository: + + ```bash + $ docker pull connectedhomeip/chip-build-telink:latest + ``` + +1. Run docker container: + + ```bash + $ docker run -it --rm -v ${CHIP_BASE}:/root/chip -v /dev/bus/usb:/dev/bus/usb --device-cgroup-rule "c 189:* rmw" connectedhomeip/chip-build-telink:latest + ``` + + here `${CHIP_BASE}` is directory which contains CHIP repo files **!!!Pay + attention that OUTPUT_DIR should contains ABSOLUTE path to output dir** + +1. Activate the build environment: + + ```bash + $ source ./scripts/activate.sh + ``` + +1. In the example dir run: + + ```bash + $ west build + ``` + +1. Flash binary: + + ``` + $ west flash --erase + ``` + +## Usage + +### UART + +To get output from device, connect UART to following pins: + +| Name | Pin | +| :--: | :---------------------------- | +| RX | PB3 (pin 17 of J34 connector) | +| TX | PB2 (pin 16 of J34 connector) | +| GND | GND | + +### Buttons + +The following buttons are available on **tlsr9518adk80d** board: + +| Name | Function | Description | +| :------- | :--------------------- | :----------------------------------------------------------------------------------------------------- | +| Button 1 | Factory reset | Perform factory reset to forget currently commissioned Thread network and back to uncommissioned state | +| Button 2 | Toggle Contact State | Manually triggers the Contact Sensor State | +| Button 3 | NA | NA | +| Button 4 | Open commission window | The button is opening commissioning window to perform commissioning over BLE | + +### LEDs + +**Red** LED indicates current state of Thread network. It ables to be in +following states: + +| State | Description | +| :-------------------------- | :--------------------------------------------------------------------------- | +| Blinks with short pulses | Device is not commissioned to Thread, Thread is disabled | +| Blinls with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | +| Blinks with whde pulses | Device commissioned and joined to thread network as CHILD | + +**Blue** LED shows current state of Contact Sensor + +### CHIP tool commands + +1. Build + [chip-tool cli](https://github.com/project-chip/connectedhomeip/blob/master/examples/chip-tool/README.md) + +2. Pair with device + + ``` + ${CHIP_TOOL_DIR}/chip-tool pairing ble-thread ${NODE_ID} hex:${DATASET} ${PIN_CODE} ${DISCRIMINATOR} + ``` + + Example: + + ``` + ./chip-tool pairing ble-thread 1234 hex:0e080000000000010000000300000f35060004001fffe0020811111111222222220708fd61f77bd3df233e051000112233445566778899aabbccddeeff030e4f70656e54687265616444656d6f010212340410445f2b5ca6f2a93a55ce570a70efeecb0c0402a0fff8 20202021 3840 + ``` + +### OTA with Linux OTA Provider + +OTA feature enabled by default only for ota-requestor-app example. To enable OTA +feature for another Telink example: + +- set CONFIG_CHIP_OTA_REQUESTOR=y in corresponding "prj.conf" configuration + file. + +After build application with enabled OTA feature, use next binary files: + +- zephyr.bin - main binary to flash PCB (Use 2MB PCB). +- zephyr-ota.bin - binary for OTA Provider + +All binaries has the same SW version. To test OTA “zephyr-ota.bin” should have +higher SW version than base SW. Set CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=2 in +corresponding “prj.conf” configuration file. + +Usage of OTA: + +- Build the [Linux OTA Provider](../../ota-provider-app/linux) + + ``` + ./scripts/examples/gn_build_example.sh examples/ota-provider-app/linux out/ota-provider-app chip_config_network_layer_ble=false + ``` + +- Run the Linux OTA Provider with OTA image. + + ``` + ./chip-ota-provider-app -f zephyr-ota.bin + ``` + +- Provision the Linux OTA Provider using chip-tool + + ``` + ./chip-tool pairing onnetwork ${OTA_PROVIDER_NODE_ID} 20202021 + ``` + + here: + + - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider + +- Configure the ACL of the ota-provider-app to allow access + + ``` + ./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null}, {"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": null, "targets": null}]' ${OTA_PROVIDER_NODE_ID} 0 + ``` + + here: + + - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider + +- Use the chip-tool to announce the ota-provider-app to start the OTA process + + ``` + ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ``` + + here: + + - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider + - \${DEVICE_NODE_ID} is the node id of paired device + +Once the transfer is complete, OTA requestor sends ApplyUpdateRequest command to +OTA provider for applying the image. Device will restart on successful +application of OTA image. diff --git a/examples/contact-sensor-app/telink/include/AppConfig.h b/examples/contact-sensor-app/telink/include/AppConfig.h new file mode 100755 index 00000000000000..01128b76e4d929 --- /dev/null +++ b/examples/contact-sensor-app/telink/include/AppConfig.h @@ -0,0 +1,37 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// ---- Contact Sensor Example App Config ---- + +// Buttons config +#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) + +#define BUTTON_PIN_1 2 +#define BUTTON_PIN_3 3 +#define BUTTON_PIN_4 1 +#define BUTTON_PIN_2 0 + +// LEDs config +// System led config +#define SYSTEM_STATE_LED_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) +#define SYSTEM_STATE_LED_PIN 7 + +// Contact state led +#define CONTACT_STATE_LED_PIN 4 diff --git a/examples/contact-sensor-app/telink/include/AppEvent.h b/examples/contact-sensor-app/telink/include/AppEvent.h new file mode 100755 index 00000000000000..4051ba31cbb465 --- /dev/null +++ b/examples/contact-sensor-app/telink/include/AppEvent.h @@ -0,0 +1,57 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +struct AppEvent; +typedef void (*EventHandler)(AppEvent *); + +class LEDWidget; + +struct AppEvent +{ + enum AppEventTypes + { + kEventType_Button = 0, + kEventType_Timer, + kEventType_UpdateLedState, + kEventType_Contact, + }; + + uint16_t Type; + + union + { + struct + { + uint8_t Action; + } ButtonEvent; + struct + { + uint8_t Action; + } ContactEvent; + struct + { + LEDWidget * LedWidget; + } UpdateLedStateEvent; + }; + + EventHandler Handler; +}; diff --git a/examples/contact-sensor-app/telink/include/AppTask.h b/examples/contact-sensor-app/telink/include/AppTask.h new file mode 100644 index 00000000000000..ad6f98c7c2cf66 --- /dev/null +++ b/examples/contact-sensor-app/telink/include/AppTask.h @@ -0,0 +1,107 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "AppEvent.h" +#include "ContactSensorManager.h" +#include "LEDWidget.h" + +#include + +#include + +#if CONFIG_CHIP_FACTORY_DATA +#include +#endif + +#include + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) + +struct k_timer; + +class AppTask +{ +public: + CHIP_ERROR StartApp(void); + + void PostContactActionRequest(ContactSensorManager::Action aAction); + void PostEvent(AppEvent * event); + void UpdateClusterState(void); + void UpdateDeviceState(void); + + bool IsSyncClusterToButtonAction(void); + void SetSyncClusterToButtonAction(bool value); + +private: + friend AppTask & GetAppTask(void); + CHIP_ERROR Init(void); + + void DispatchEvent(AppEvent * event); + + static void OnStateChanged(ContactSensorManager::State aState); + + static void UpdateClusterStateInternal(intptr_t arg); + static void UpdateDeviceStateInternal(intptr_t arg); + + static void UpdateStatusLED(void); + static void LEDStateUpdateHandler(LEDWidget * ledWidget); + static void FactoryResetButtonEventHandler(void); + static void StartBleAdvButtonEventHandler(void); + static void ToggleContactStateButtonEventHandler(void); + + static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + + static void FactoryResetTimerTimeoutCallback(k_timer * timer); + + static void FactoryResetTimerEventHandler(AppEvent * aEvent); + static void FactoryResetHandler(AppEvent * aEvent); + static void StartBleAdvHandler(AppEvent * aEvent); + static void ContactActionEventHandler(AppEvent * aEvent); + static void UpdateLedStateEventHandler(AppEvent * aEvent); + + static void InitButtons(void); + + static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + + bool mSyncClusterToButtonAction = false; + + static AppTask sAppTask; + +#if CONFIG_CHIP_FACTORY_DATA + // chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; + chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; +#endif +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} + +inline bool AppTask::IsSyncClusterToButtonAction() +{ + return mSyncClusterToButtonAction; +} + +inline void AppTask::SetSyncClusterToButtonAction(bool value) +{ + mSyncClusterToButtonAction = value; +} diff --git a/examples/contact-sensor-app/telink/include/CHIPProjectConfig.h b/examples/contact-sensor-app/telink/include/CHIPProjectConfig.h new file mode 100755 index 00000000000000..2fda70c57da9dc --- /dev/null +++ b/examples/contact-sensor-app/telink/include/CHIPProjectConfig.h @@ -0,0 +1,39 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +// Use a default pairing code if one hasn't been provisioned in flash. +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 + +/** + * 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 diff --git a/examples/contact-sensor-app/telink/include/ContactSensorManager.h b/examples/contact-sensor-app/telink/include/ContactSensorManager.h new file mode 100644 index 00000000000000..0f735288b6ee39 --- /dev/null +++ b/examples/contact-sensor-app/telink/include/ContactSensorManager.h @@ -0,0 +1,62 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "AppEvent.h" + +class ContactSensorManager +{ +public: + enum class Action : uint8_t + { + kSignalDetected = 0, + kSignalLost, + kInvalid + }; + + enum class State : uint8_t + { + kContactClosed = 0, + kContactOpened, + kInvalid + }; + + int Init(); + bool IsContactClosed(); + void InitiateAction(Action aAction); + + typedef void (*CallbackStateChanged)(State aState); + void SetCallback(CallbackStateChanged aCallbackStateChanged); + + static void HandleAction(AppEvent * aEvent); + +private: + friend ContactSensorManager & ContactSensorMgr(void); + State mState; + CallbackStateChanged mCallbackStateChanged; + static ContactSensorManager sContactSensor; +}; + +inline ContactSensorManager & ContactSensorMgr(void) +{ + return ContactSensorManager::sContactSensor; +} diff --git a/examples/contact-sensor-app/telink/prj.conf b/examples/contact-sensor-app/telink/prj.conf new file mode 100755 index 00000000000000..6c4ad9d8975f05 --- /dev/null +++ b/examples/contact-sensor-app/telink/prj.conf @@ -0,0 +1,58 @@ +# +# Copyright (c) 2022 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This sample uses sample-defaults.conf to set options common for all +# samples. This file should contain only options specific for this sample +# or overrides of default values. + +# enable GPIO +CONFIG_GPIO=y + +# OpenThread configs +CONFIG_OPENTHREAD_MTD=y +CONFIG_OPENTHREAD_FTD=n + +# Default OpenThread network settings +CONFIG_OPENTHREAD_PANID=4660 +CONFIG_OPENTHREAD_CHANNEL=15 +CONFIG_OPENTHREAD_NETWORK_NAME="OpenThreadDemo" +CONFIG_OPENTHREAD_XPANID="11:11:11:11:22:22:22:22" + +# Disable Matter OTA DFU +CONFIG_CHIP_OTA_REQUESTOR=n + +# CHIP configuration +CONFIG_CHIP_PROJECT_CONFIG="include/CHIPProjectConfig.h" +CONFIG_CHIP_OPENTHREAD_CONFIG="../../platform/telink/project_include/OpenThreadConfig.h" + +CONFIG_CHIP_DEVICE_VENDOR_ID=65521 +# 32774 == 0x8006 (example contact-sensor-app) +CONFIG_CHIP_DEVICE_PRODUCT_ID=32769 +CONFIG_CHIP_DEVICE_TYPE=65535 + +CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=1 +CONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING="2022" + +# Enable CHIP pairing automatically on application start. +CONFIG_CHIP_ENABLE_PAIRING_AUTOSTART=y + +# CHIP shell +CONFIG_CHIP_LIB_SHELL=n + +# Disable factory data support. +CONFIG_CHIP_FACTORY_DATA=n +CONFIG_CHIP_FACTORY_DATA_BUILD=n +CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n \ No newline at end of file diff --git a/examples/contact-sensor-app/telink/src/AppTask.cpp b/examples/contact-sensor-app/telink/src/AppTask.cpp new file mode 100644 index 00000000000000..a2dc322fcc50de --- /dev/null +++ b/examples/contact-sensor-app/telink/src/AppTask.cpp @@ -0,0 +1,524 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" + +#include "AppConfig.h" +#include "AppEvent.h" +#include "ButtonManager.h" + +#include "ThreadUtil.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if CONFIG_CHIP_OTA_REQUESTOR +#include "OTAUtil.h" +#endif + +#include +#include + +LOG_MODULE_DECLARE(app); + +using namespace ::chip; +using namespace ::chip::app; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; + +namespace { + +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; + +// NOTE! This key is for test/certification only and should not be available in production devices! +// If CONFIG_CHIP_FACTORY_DATA is enabled, this value is read from the factory data. +uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, + 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; + +K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); +k_timer sFactoryResetTimer; + +LEDWidget sStatusLED; +LEDWidget sContactSensorLED; + +Button sFactoryResetButton; +Button sToggleContactStateButton; +Button sBleAdvStartButton; + +bool sIsThreadProvisioned = false; +bool sIsThreadEnabled = false; +bool sIsThreadAttached = false; +bool sHaveBLEConnections = false; +bool sIsFactoryResetTimerActive = false; + +chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; + +void OnIdentifyTriggerEffect(Identify * identify) +{ + switch (identify->mCurrentEffectIdentifier) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); + break; + default: + ChipLogProgress(Zcl, "No identifier effect"); + break; + } + return; +} + +Identify sIdentify = { + chip::EndpointId{ 1 }, + [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStart"); }, + [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStop"); }, + EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, + OnIdentifyTriggerEffect, +}; + +} // namespace + +AppTask AppTask::sAppTask; + +class AppFabricTableDelegate : public FabricTable::Delegate +{ + void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) + { + if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + } +}; + +CHIP_ERROR AppTask::Init() +{ + CHIP_ERROR err; + + LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + // Initialize status LED + LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); + sStatusLED.Init(SYSTEM_STATE_LED_PIN); + + UpdateStatusLED(); + + sContactSensorLED.Init(CONTACT_STATE_LED_PIN); + sContactSensorLED.Set(ContactSensorMgr().IsContactClosed()); + + UpdateDeviceState(); + + InitButtons(); + + // Initialize function button timer + k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); + k_timer_user_data_set(&sFactoryResetTimer, this); + + // Initialize CHIP server +#if CONFIG_CHIP_FACTORY_DATA + ReturnErrorOnFailure(mFactoryDataProvider.Init()); + SetDeviceInstanceInfoProvider(&mFactoryDataProvider); + SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider); + SetCommissionableDataProvider(&mFactoryDataProvider); + // Read EnableKey from the factory data. + MutableByteSpan enableKey(sTestEventTriggerEnableKey); + err = mFactoryDataProvider.GetEnableKey(enableKey); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("GetEnableKey fail"); + memset(sTestEventTriggerEnableKey, 0, sizeof(sTestEventTriggerEnableKey)); + } +#else + SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif + + static CommonCaseDeviceServerInitParams initParams; + // static OTATestEventTriggerDelegate testEventTriggerDelegate{ ByteSpan(sTestEventTriggerEnableKey) }; + (void) initParams.InitializeStaticResourcesBeforeServerInit(); + // initParams.testEventTriggerDelegate = &testEventTriggerDelegate; + ReturnErrorOnFailure(chip::Server::GetInstance().Init(initParams)); + + gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); + chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); + +#if CONFIG_CHIP_OTA_REQUESTOR + InitBasicOTARequestor(); +#endif + + ConfigurationMgr().LogDeviceConfig(); + PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); + + // Add CHIP event handler and start CHIP thread. + // Note that all the initialization code should happen prior to this point to avoid data races + // between the main and the CHIP threads. + PlatformMgr().AddEventHandler(ChipEventHandler, 0); + + ContactSensorMgr().SetCallback(OnStateChanged); + + err = ConnectivityMgr().SetBLEDeviceName("TelinkSensor"); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("SetBLEDeviceName fail"); + return err; + } + + err = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("AppFabricTableDelegate fail"); + return err; + } + + return CHIP_NO_ERROR; +} + +void AppTask::OnStateChanged(ContactSensorManager::State aState) +{ + // If the contact state was changed, update LED state and cluster state (only if button was pressed). + // - turn on the contact LED if contact sensor is in closed state. + // - turn off the lock LED if contact sensor is in opened state. + if (ContactSensorManager::State::kContactClosed == aState) + { + LOG_INF("Contact state changed to CLOSED"); + sContactSensorLED.Set(true); + } + else if (ContactSensorManager::State::kContactOpened == aState) + { + LOG_INF("Contact state changed to OPEN"); + sContactSensorLED.Set(false); + } + + if (sAppTask.IsSyncClusterToButtonAction()) + { + sAppTask.UpdateClusterState(); + } +} + +CHIP_ERROR AppTask::StartApp(void) +{ + CHIP_ERROR err = Init(); + + if (err != CHIP_NO_ERROR) + { + LOG_ERR("AppTask Init fail"); + return err; + } + + AppEvent event = {}; + + while (true) + { + int ret = k_msgq_get(&sAppEventQueue, &event, K_MSEC(10)); + + while (!ret) + { + DispatchEvent(&event); + ret = k_msgq_get(&sAppEventQueue, &event, K_NO_WAIT); + } + } +} + +void AppTask::PostContactActionRequest(ContactSensorManager::Action aAction) +{ + AppEvent event; + event.Type = AppEvent::kEventType_Contact; + event.ContactEvent.Action = static_cast(aAction); + event.Handler = ContactActionEventHandler; + + sAppTask.PostEvent(&event); +} + +void AppTask::ToggleContactStateButtonEventHandler(void) +{ + AppEvent event; + + event.Type = AppEvent::kEventType_Button; + event.ButtonEvent.Action = kButtonPushEvent; + event.Handler = ContactActionEventHandler; + + sAppTask.PostEvent(&event); +} + +void AppTask::FactoryResetButtonEventHandler(void) +{ + AppEvent event; + + event.Type = AppEvent::kEventType_Button; + event.ButtonEvent.Action = kButtonPushEvent; + event.Handler = FactoryResetHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::FactoryResetHandler(AppEvent * aEvent) +{ + if (!sIsFactoryResetTimerActive) + { + k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetTriggerTimeout), K_NO_WAIT); + sIsFactoryResetTimerActive = true; + } + else + { + k_timer_stop(&sFactoryResetTimer); + sIsFactoryResetTimerActive = false; + } +} + +void AppTask::UpdateClusterStateInternal(intptr_t arg) +{ + uint8_t newValue = ContactSensorMgr().IsContactClosed(); + + ChipLogProgress(NotSpecified, "emberAfWriteAttribute : %d", newValue); + + // write the new boolean state value + EmberAfStatus status = emberAfWriteAttribute(1, ZCL_BOOLEAN_STATE_CLUSTER_ID, ZCL_STATE_VALUE_ATTRIBUTE_ID, + (uint8_t *) &newValue, ZCL_BOOLEAN_ATTRIBUTE_TYPE); + if (status != EMBER_ZCL_STATUS_SUCCESS) + { + ChipLogError(NotSpecified, "ERR: updating boolean status value %x", status); + } +} + +void AppTask::ContactActionEventHandler(AppEvent * aEvent) +{ + ContactSensorManager::Action action = ContactSensorManager::Action::kInvalid; + CHIP_ERROR err = CHIP_NO_ERROR; + + ChipLogProgress(NotSpecified, "ContactActionEventHandler"); + + if (aEvent->Type == AppEvent::kEventType_Contact) + { + action = static_cast(aEvent->ContactEvent.Action); + } + else if (aEvent->Type == AppEvent::kEventType_Button) + { + if (ContactSensorMgr().IsContactClosed()) + { + action = ContactSensorManager::Action::kSignalLost; + } + else + { + action = ContactSensorManager::Action::kSignalDetected; + } + + sAppTask.SetSyncClusterToButtonAction(true); + } + else + { + err = APP_ERROR_UNHANDLED_EVENT; + action = ContactSensorManager::Action::kInvalid; + } + + if (err == CHIP_NO_ERROR) + { + ContactSensorMgr().InitiateAction(action); + } +} + +void AppTask::StartBleAdvButtonEventHandler(void) +{ + AppEvent event; + + event.Type = AppEvent::kEventType_Button; + event.ButtonEvent.Action = kButtonPushEvent; + event.Handler = StartBleAdvHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::StartBleAdvHandler(AppEvent * aEvent) +{ + LOG_INF("StartBleAdvHandler"); + + // Don't allow on starting Matter service BLE advertising after Thread provisioning. + if (ConnectivityMgr().IsThreadProvisioned()) + { + LOG_INF("Device already commissioned"); + return; + } + + if (ConnectivityMgr().IsBLEAdvertisingEnabled()) + { + LOG_INF("BLE adv already enabled"); + return; + } + + if (chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() != CHIP_NO_ERROR) + { + LOG_ERR("OpenBasicCommissioningWindow fail"); + } +} + +void AppTask::UpdateLedStateEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type == AppEvent::kEventType_UpdateLedState) + { + aEvent->UpdateLedStateEvent.LedWidget->UpdateState(); + } +} + +void AppTask::LEDStateUpdateHandler(LEDWidget * ledWidget) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateLedStateEventHandler; + event.UpdateLedStateEvent.LedWidget = ledWidget; + sAppTask.PostEvent(&event); +} + +void AppTask::UpdateStatusLED(void) +{ + if (sIsThreadProvisioned && sIsThreadEnabled) + { + if (sIsThreadAttached) + { + sStatusLED.Blink(950, 50); + } + else + { + sStatusLED.Blink(100, 100); + } + } + else + { + sStatusLED.Blink(50, 950); + } +} + +void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) +{ + switch (event->Type) + { + case DeviceEventType::kCHIPoBLEAdvertisingChange: + sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; + UpdateStatusLED(); + break; + case DeviceEventType::kThreadStateChange: + sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); + sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); + sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); + UpdateStatusLED(); + break; + case DeviceEventType::kThreadConnectivityChange: +#if CONFIG_CHIP_OTA_REQUESTOR + if (event->ThreadConnectivityChange.Result == kConnectivity_Established) + { + InitBasicOTARequestor(); + } +#endif + break; + default: + break; + } +} + +void AppTask::PostEvent(AppEvent * aEvent) +{ + if (k_msgq_put(&sAppEventQueue, aEvent, K_NO_WAIT) != 0) + { + LOG_INF("PostEvent fail"); + } +} + +void AppTask::DispatchEvent(AppEvent * aEvent) +{ + if (aEvent->Handler) + { + aEvent->Handler(aEvent); + } + else + { + LOG_INF("Dropping event without handler"); + } +} + +void AppTask::UpdateClusterState(void) +{ + PlatformMgr().ScheduleWork(UpdateClusterStateInternal, 0); +} + +void AppTask::FactoryResetTimerTimeoutCallback(k_timer * timer) +{ + if (!timer) + { + return; + } + + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.Handler = FactoryResetTimerEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::FactoryResetTimerEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type != AppEvent::kEventType_Timer) + { + return; + } + + sIsFactoryResetTimerActive = false; + LOG_INF("FactoryResetHandler"); + chip::Server::GetInstance().ScheduleFactoryReset(); +} + +void AppTask::InitButtons(void) +{ + sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, true, FactoryResetButtonEventHandler); + sToggleContactStateButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_1, false, ToggleContactStateButtonEventHandler); + sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, false, StartBleAdvButtonEventHandler); + + ButtonManagerInst().AddButton(sFactoryResetButton); + ButtonManagerInst().AddButton(sToggleContactStateButton); + ButtonManagerInst().AddButton(sBleAdvStartButton); +} + +void AppTask::UpdateDeviceState(void) +{ + PlatformMgr().ScheduleWork(UpdateDeviceStateInternal, 0); +} + +void AppTask::UpdateDeviceStateInternal(intptr_t arg) +{ + bool stateValueAttrValue = 0; + + /* get boolean state attribute value */ + (void) emberAfReadAttribute(1, ZCL_BOOLEAN_STATE_CLUSTER_ID, ZCL_STATE_VALUE_ATTRIBUTE_ID, (uint8_t *) &stateValueAttrValue, 1); + + ChipLogProgress(NotSpecified, "emberAfReadAttribute : %d", stateValueAttrValue); + sContactSensorLED.Set(stateValueAttrValue); +} diff --git a/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp b/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp new file mode 100644 index 00000000000000..b555e4e0a2c958 --- /dev/null +++ b/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp @@ -0,0 +1,87 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ContactSensorManager.h" + +#include "AppConfig.h" +#include "AppTask.h" + +#include + +#include +#include +#include + +LOG_MODULE_DECLARE(app); + +ContactSensorManager ContactSensorManager::sContactSensor; + +int ContactSensorManager::Init() +{ + int err = 0; + + mState = State::kContactOpened; + mCallbackStateChanged = nullptr; + + return err; +} + +void ContactSensorManager::SetCallback(CallbackStateChanged aCallbackStateChanged) +{ + mCallbackStateChanged = aCallbackStateChanged; +} + +bool ContactSensorManager::IsContactClosed() +{ + return mState == State::kContactClosed; +} + +void ContactSensorManager::InitiateAction(Action aAction) +{ + AppEvent event; + event.Type = AppEvent::kEventType_Contact; + event.ContactEvent.Action = static_cast(aAction); + event.Handler = HandleAction; + GetAppTask().PostEvent(&event); +} + +void ContactSensorManager::HandleAction(AppEvent * aEvent) +{ + Action action = static_cast(aEvent->ContactEvent.Action); + // Change current state based on action: + // - if state is closed and action is signal lost, change state to opened + // - if state is opened and action is signal detected, change state to closed + // - else, the state/action combination does not change the state. + if (sContactSensor.mState == State::kContactClosed && action == Action::kSignalLost) + { + sContactSensor.mState = State::kContactOpened; + } + else if (sContactSensor.mState == State::kContactOpened && action == Action::kSignalDetected) + { + sContactSensor.mState = State::kContactClosed; + } + + if (sContactSensor.mCallbackStateChanged != nullptr) + { + sContactSensor.mCallbackStateChanged(sContactSensor.mState); + } + else + { + LOG_ERR("Callback for state change was not set. Please set an appropriate callback."); + } +} diff --git a/examples/contact-sensor-app/telink/src/ZclCallbacks.cpp b/examples/contact-sensor-app/telink/src/ZclCallbacks.cpp new file mode 100644 index 00000000000000..89d6aed77f16d2 --- /dev/null +++ b/examples/contact-sensor-app/telink/src/ZclCallbacks.cpp @@ -0,0 +1,56 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" + +#include +#include +#include +#include + +using namespace chip; +using namespace chip::app::Clusters; + +void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size, + uint8_t * value) +{ + ClusterId clusterId = attributePath.mClusterId; + AttributeId attributeId = attributePath.mAttributeId; + ChipLogProgress(Zcl, "Cluster callback: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + + if (clusterId == BooleanState::Id && attributeId == BooleanState::Attributes::StateValue::Id) + { + ChipLogProgress(Zcl, "Cluster BooleanState: attribute StateValue set to %u", *value); + AppTask & task = GetAppTask(); + if (task.IsSyncClusterToButtonAction()) + { + task.SetSyncClusterToButtonAction(false); + } + else + { + task.PostContactActionRequest(*value ? ContactSensorManager::Action::kSignalDetected + : ContactSensorManager::Action::kSignalLost); + } + } +} + +void emberAfBooleanStateClusterInitCallback(EndpointId endpoint) +{ + ChipLogProgress(Zcl, "emberAfBooleanStateClusterInitCallback"); + GetAppTask().UpdateClusterState(); +} diff --git a/examples/contact-sensor-app/telink/src/main.cpp b/examples/contact-sensor-app/telink/src/main.cpp new file mode 100755 index 00000000000000..e71632de12fddb --- /dev/null +++ b/examples/contact-sensor-app/telink/src/main.cpp @@ -0,0 +1,82 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "AppTask.h" + +#include +#include + +#include + +LOG_MODULE_REGISTER(app); + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::DeviceLayer; + +int main(void) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + err = chip::Platform::MemoryInit(); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("MemoryInit fail"); + goto exit; + } + + err = PlatformMgr().InitChipStack(); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("InitChipStack fail"); + goto exit; + } + + err = PlatformMgr().StartEventLoopTask(); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("StartEventLoopTask fail"); + goto exit; + } + + err = ThreadStackMgr().InitThreadStack(); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("InitThreadStack fail"); + goto exit; + } + +#ifdef CONFIG_OPENTHREAD_MTD_SED + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice); +#elif CONFIG_OPENTHREAD_MTD + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice); +#else + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); +#endif + if (err != CHIP_NO_ERROR) + { + LOG_ERR("SetThreadDeviceType fail"); + goto exit; + } + + err = GetAppTask().StartApp(); + +exit: + LOG_ERR("Exit err %" CHIP_ERROR_FORMAT, err.Format()); + return (err == CHIP_NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/examples/contact-sensor-app/telink/third_party/connectedhomeip b/examples/contact-sensor-app/telink/third_party/connectedhomeip new file mode 120000 index 00000000000000..c866b86874994d --- /dev/null +++ b/examples/contact-sensor-app/telink/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../.. \ No newline at end of file diff --git a/examples/light-switch-app/telink/include/AppEvent.h b/examples/light-switch-app/telink/include/AppEvent.h index ed69564c270adb..9a6fd3060c1685 100755 --- a/examples/light-switch-app/telink/include/AppEvent.h +++ b/examples/light-switch-app/telink/include/AppEvent.h @@ -23,12 +23,15 @@ struct AppEvent; typedef void (*EventHandler)(AppEvent *); +class LEDWidget; + struct AppEvent { enum AppEventTypes { kEventType_Button = 0, kEventType_Timer, + kEventType_UpdateLedState, kEventType_Lighting, kEventType_Install, }; @@ -50,6 +53,10 @@ struct AppEvent uint8_t Action; int32_t Actor; } LightingEvent; + struct + { + LEDWidget * LedWidget; + } UpdateLedStateEvent; }; EventHandler Handler; diff --git a/examples/light-switch-app/telink/include/AppTask.h b/examples/light-switch-app/telink/include/AppTask.h index 6cf0a330cf2317..6509613e3741b8 100755 --- a/examples/light-switch-app/telink/include/AppTask.h +++ b/examples/light-switch-app/telink/include/AppTask.h @@ -19,6 +19,7 @@ #pragma once #include "AppEvent.h" +#include "LEDWidget.h" #include @@ -60,6 +61,7 @@ class AppTask void DispatchEvent(AppEvent * event); static void UpdateStatusLED(); + static void LEDStateUpdateHandler(LEDWidget * ledWidget); static void SwitchActionButtonEventHandler(void); static void FactoryResetButtonEventHandler(void); static void StartThreadButtonEventHandler(void); @@ -67,10 +69,14 @@ class AppTask static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + static void FactoryResetTimerTimeoutCallback(k_timer * timer); + + static void FactoryResetTimerEventHandler(AppEvent * aEvent); static void FactoryResetHandler(AppEvent * aEvent); static void StartThreadHandler(AppEvent * aEvent); static void SwitchActionEventHandler(AppEvent * aEvent); static void StartBleAdvHandler(AppEvent * aEvent); + static void UpdateLedStateEventHandler(AppEvent * aEvent); static void InitButtons(void); diff --git a/examples/light-switch-app/telink/src/AppTask.cpp b/examples/light-switch-app/telink/src/AppTask.cpp index c5a77caae8f701..5b7817831ed68a 100644 --- a/examples/light-switch-app/telink/src/AppTask.cpp +++ b/examples/light-switch-app/telink/src/AppTask.cpp @@ -21,7 +21,6 @@ #include "AppConfig.h" #include "AppEvent.h" #include "ButtonManager.h" -#include "LEDWidget.h" #include "binding-handler.h" #include "ThreadUtil.h" @@ -54,10 +53,10 @@ using namespace ::chip::Credentials; using namespace ::chip::DeviceLayer; namespace { - -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; // NOTE! This key is for test/certification only and should not be available in production devices! // If CONFIG_CHIP_FACTORY_DATA is enabled, this value is read from the factory data. @@ -65,6 +64,7 @@ uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); +k_timer sFactoryResetTimer; LEDWidget sStatusLED; @@ -73,10 +73,11 @@ Button sSwitchButton; Button sThreadStartButton; Button sBleAdvStartButton; -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; +bool sIsThreadProvisioned = false; +bool sIsThreadEnabled = false; +bool sIsThreadAttached = false; +bool sHaveBLEConnections = false; +bool sIsFactoryResetTimerActive = false; chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; @@ -115,6 +116,17 @@ Identify sIdentify = { AppTask AppTask::sAppTask; +class AppFabricTableDelegate : public FabricTable::Delegate +{ + void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) + { + if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + } +}; + CHIP_ERROR AppTask::Init() { CHIP_ERROR err; @@ -123,12 +135,17 @@ CHIP_ERROR AppTask::Init() // Initialize status LED LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); sStatusLED.Init(SYSTEM_STATE_LED_PIN); UpdateStatusLED(); InitButtons(); + // Initialize function button timer + k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); + k_timer_user_data_set(&sFactoryResetTimer, this); + // Initialize CHIP server #if CONFIG_CHIP_FACTORY_DATA ReturnErrorOnFailure(mFactoryDataProvider.Init()); @@ -180,9 +197,17 @@ CHIP_ERROR AppTask::Init() if (err != CHIP_NO_ERROR) { LOG_ERR("SetBLEDeviceName fail"); + return err; + } + + err = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("AppFabricTableDelegate fail"); + return err; } - return err; + return CHIP_NO_ERROR; } CHIP_ERROR AppTask::StartApp() @@ -206,8 +231,6 @@ CHIP_ERROR AppTask::StartApp() DispatchEvent(&event); ret = k_msgq_get(&sAppEventQueue, &event, K_NO_WAIT); } - - sStatusLED.Animate(); } } @@ -245,8 +268,16 @@ void AppTask::FactoryResetButtonEventHandler(void) void AppTask::FactoryResetHandler(AppEvent * aEvent) { - LOG_INF("FactoryResetHandler"); - chip::Server::GetInstance().ScheduleFactoryReset(); + if (!sIsFactoryResetTimerActive) + { + k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetTriggerTimeout), K_NO_WAIT); + sIsFactoryResetTimerActive = true; + } + else + { + k_timer_stop(&sFactoryResetTimer); + sIsFactoryResetTimerActive = false; + } } void AppTask::StartThreadButtonEventHandler(void) @@ -308,6 +339,23 @@ void AppTask::StartBleAdvHandler(AppEvent * aEvent) } } +void AppTask::UpdateLedStateEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type == AppEvent::kEventType_UpdateLedState) + { + aEvent->UpdateLedStateEvent.LedWidget->UpdateState(); + } +} + +void AppTask::LEDStateUpdateHandler(LEDWidget * ledWidget) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateLedStateEventHandler; + event.UpdateLedStateEvent.LedWidget = ledWidget; + sAppTask.PostEvent(&event); +} + void AppTask::UpdateStatusLED() { if (sIsThreadProvisioned && sIsThreadEnabled) @@ -386,12 +434,37 @@ void AppTask::DispatchEvent(AppEvent * aEvent) void AppTask::UpdateClusterState() {} +void AppTask::FactoryResetTimerTimeoutCallback(k_timer * timer) +{ + if (!timer) + { + return; + } + + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.Handler = FactoryResetTimerEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::FactoryResetTimerEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type != AppEvent::kEventType_Timer) + { + return; + } + + sIsFactoryResetTimerActive = false; + LOG_INF("FactoryResetHandler"); + chip::Server::GetInstance().ScheduleFactoryReset(); +} + void AppTask::InitButtons(void) { - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sSwitchButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_1, SwitchActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); + sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, true, FactoryResetButtonEventHandler); + sSwitchButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_1, false, SwitchActionButtonEventHandler); + sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, false, StartThreadButtonEventHandler); + sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, false, StartBleAdvButtonEventHandler); ButtonManagerInst().AddButton(sFactoryResetButton); ButtonManagerInst().AddButton(sSwitchButton); diff --git a/examples/lighting-app/telink/include/AppEvent.h b/examples/lighting-app/telink/include/AppEvent.h index 548d737f5c65d7..1766b5d77577a1 100644 --- a/examples/lighting-app/telink/include/AppEvent.h +++ b/examples/lighting-app/telink/include/AppEvent.h @@ -23,12 +23,15 @@ struct AppEvent; typedef void (*EventHandler)(AppEvent *); +class LEDWidget; + struct AppEvent { enum AppEventTypes { kEventType_Button = 0, kEventType_Timer, + kEventType_UpdateLedState, kEventType_Lighting, kEventType_Install, }; @@ -50,6 +53,10 @@ struct AppEvent uint8_t Action; int32_t Actor; } LightingEvent; + struct + { + LEDWidget * LedWidget; + } UpdateLedStateEvent; }; EventHandler Handler; diff --git a/examples/lighting-app/telink/include/AppTask.h b/examples/lighting-app/telink/include/AppTask.h index 09ba6ef240f26c..26575805d70a5d 100644 --- a/examples/lighting-app/telink/include/AppTask.h +++ b/examples/lighting-app/telink/include/AppTask.h @@ -19,8 +19,8 @@ #pragma once #include "AppEvent.h" +#include "LEDWidget.h" #include "LightingManager.h" - #include #if CONFIG_CHIP_FACTORY_DATA @@ -65,6 +65,7 @@ class AppTask void DispatchEvent(AppEvent * event); static void UpdateStatusLED(); + static void LEDStateUpdateHandler(LEDWidget * ledWidget); static void LightingActionButtonEventHandler(void); static void FactoryResetButtonEventHandler(void); static void StartThreadButtonEventHandler(void); @@ -72,10 +73,14 @@ class AppTask static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + static void FactoryResetTimerTimeoutCallback(k_timer * timer); + + static void FactoryResetTimerEventHandler(AppEvent * aEvent); static void FactoryResetHandler(AppEvent * aEvent); static void StartThreadHandler(AppEvent * aEvent); static void LightingActionEventHandler(AppEvent * aEvent); static void StartBleAdvHandler(AppEvent * aEvent); + static void UpdateLedStateEventHandler(AppEvent * aEvent); static void ButtonEventHandler(ButtonId_t btnId, bool btnPressed); static void InitButtons(void); diff --git a/examples/lighting-app/telink/src/AppTask.cpp b/examples/lighting-app/telink/src/AppTask.cpp index 2a311a2a052413..f7866db456c370 100644 --- a/examples/lighting-app/telink/src/AppTask.cpp +++ b/examples/lighting-app/telink/src/AppTask.cpp @@ -21,8 +21,6 @@ #include "AppConfig.h" #include "AppEvent.h" #include "ButtonManager.h" -#include "LEDWidget.h" -#include "LightingManager.h" #include "ThreadUtil.h" @@ -55,12 +53,12 @@ using namespace ::chip::Credentials; using namespace ::chip::DeviceLayer; namespace { - -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; +constexpr uint8_t kDefaultMinLevel = 0; +constexpr uint8_t kDefaultMaxLevel = 254; // NOTE! This key is for test/certification only and should not be available in production devices! // If CONFIG_CHIP_FACTORY_DATA is enabled, this value is read from the factory data. @@ -68,6 +66,7 @@ uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); +k_timer sFactoryResetTimer; LEDWidget sStatusLED; @@ -76,10 +75,11 @@ Button sLightingButton; Button sThreadStartButton; Button sBleAdvStartButton; -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; +bool sIsThreadProvisioned = false; +bool sIsThreadEnabled = false; +bool sIsThreadAttached = false; +bool sHaveBLEConnections = false; +bool sIsFactoryResetTimerActive = false; chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; @@ -118,18 +118,34 @@ Identify sIdentify = { AppTask AppTask::sAppTask; +class AppFabricTableDelegate : public FabricTable::Delegate +{ + void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) + { + if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + } +}; + CHIP_ERROR AppTask::Init() { LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); // Initialize status LED LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); sStatusLED.Init(SYSTEM_STATE_LED_PIN); UpdateStatusLED(); InitButtons(); + // Initialize function button timer + k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); + k_timer_user_data_set(&sFactoryResetTimer, this); + // Init lighting manager uint8_t minLightLevel = kDefaultMinLevel; Clusters::LevelControl::Attributes::MinLevel::Get(1, &minLightLevel); @@ -188,9 +204,17 @@ CHIP_ERROR AppTask::Init() if (err != CHIP_NO_ERROR) { LOG_ERR("SetBLEDeviceName fail"); + return err; + } + + err = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("AppFabricTableDelegate fail"); + return err; } - return err; + return CHIP_NO_ERROR; } CHIP_ERROR AppTask::StartApp() @@ -214,8 +238,6 @@ CHIP_ERROR AppTask::StartApp() DispatchEvent(&event); ret = k_msgq_get(&sAppEventQueue, &event, K_NO_WAIT); } - - sStatusLED.Animate(); } } @@ -263,8 +285,16 @@ void AppTask::FactoryResetButtonEventHandler(void) void AppTask::FactoryResetHandler(AppEvent * aEvent) { - LOG_INF("FactoryResetHandler"); - chip::Server::GetInstance().ScheduleFactoryReset(); + if (!sIsFactoryResetTimerActive) + { + k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetTriggerTimeout), K_NO_WAIT); + sIsFactoryResetTimerActive = true; + } + else + { + k_timer_stop(&sFactoryResetTimer); + sIsFactoryResetTimerActive = false; + } } void AppTask::StartThreadButtonEventHandler(void) @@ -326,6 +356,23 @@ void AppTask::StartBleAdvHandler(AppEvent * aEvent) } } +void AppTask::UpdateLedStateEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type == AppEvent::kEventType_UpdateLedState) + { + aEvent->UpdateLedStateEvent.LedWidget->UpdateState(); + } +} + +void AppTask::LEDStateUpdateHandler(LEDWidget * ledWidget) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateLedStateEventHandler; + event.UpdateLedStateEvent.LedWidget = ledWidget; + sAppTask.PostEvent(&event); +} + void AppTask::UpdateStatusLED() { if (sIsThreadProvisioned && sIsThreadEnabled) @@ -456,6 +503,31 @@ void AppTask::UpdateClusterState() } } +void AppTask::FactoryResetTimerTimeoutCallback(k_timer * timer) +{ + if (!timer) + { + return; + } + + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.Handler = FactoryResetTimerEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::FactoryResetTimerEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type != AppEvent::kEventType_Timer) + { + return; + } + + sIsFactoryResetTimerActive = false; + LOG_INF("FactoryResetHandler"); + chip::Server::GetInstance().ScheduleFactoryReset(); +} + void AppTask::ButtonEventHandler(ButtonId_t btnId, bool btnPressed) { if (!btnPressed) @@ -482,10 +554,10 @@ void AppTask::ButtonEventHandler(ButtonId_t btnId, bool btnPressed) void AppTask::InitButtons(void) { - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sLightingButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_1, LightingActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); + sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, true, FactoryResetButtonEventHandler); + sLightingButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_1, false, LightingActionButtonEventHandler); + sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, false, StartThreadButtonEventHandler); + sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, false, StartBleAdvButtonEventHandler); ButtonManagerInst().AddButton(sFactoryResetButton); ButtonManagerInst().AddButton(sLightingButton); diff --git a/examples/ota-requestor-app/telink/include/AppEvent.h b/examples/ota-requestor-app/telink/include/AppEvent.h index ed69564c270adb..9a6fd3060c1685 100644 --- a/examples/ota-requestor-app/telink/include/AppEvent.h +++ b/examples/ota-requestor-app/telink/include/AppEvent.h @@ -23,12 +23,15 @@ struct AppEvent; typedef void (*EventHandler)(AppEvent *); +class LEDWidget; + struct AppEvent { enum AppEventTypes { kEventType_Button = 0, kEventType_Timer, + kEventType_UpdateLedState, kEventType_Lighting, kEventType_Install, }; @@ -50,6 +53,10 @@ struct AppEvent uint8_t Action; int32_t Actor; } LightingEvent; + struct + { + LEDWidget * LedWidget; + } UpdateLedStateEvent; }; EventHandler Handler; diff --git a/examples/ota-requestor-app/telink/include/AppTask.h b/examples/ota-requestor-app/telink/include/AppTask.h index 712212e38fd80d..a8b5c2dd3e7a93 100755 --- a/examples/ota-requestor-app/telink/include/AppTask.h +++ b/examples/ota-requestor-app/telink/include/AppTask.h @@ -19,6 +19,7 @@ #pragma once #include "AppEvent.h" +#include "LEDWidget.h" #include @@ -56,15 +57,20 @@ class AppTask void DispatchEvent(AppEvent * event); static void UpdateStatusLED(); + static void LEDStateUpdateHandler(LEDWidget * ledWidget); static void FactoryResetButtonEventHandler(void); static void StartThreadButtonEventHandler(void); static void StartBleAdvButtonEventHandler(void); static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + static void FactoryResetTimerTimeoutCallback(k_timer * timer); + + static void FactoryResetTimerEventHandler(AppEvent * aEvent); static void FactoryResetHandler(AppEvent * aEvent); static void StartThreadHandler(AppEvent * aEvent); static void StartBleAdvHandler(AppEvent * aEvent); + static void UpdateLedStateEventHandler(AppEvent * aEvent); static void InitButtons(void); diff --git a/examples/ota-requestor-app/telink/src/AppTask.cpp b/examples/ota-requestor-app/telink/src/AppTask.cpp index 8343e3ddc38f65..15f3c6f17ff274 100644 --- a/examples/ota-requestor-app/telink/src/AppTask.cpp +++ b/examples/ota-requestor-app/telink/src/AppTask.cpp @@ -21,7 +21,6 @@ #include "AppConfig.h" #include "AppEvent.h" #include "ButtonManager.h" -#include "LEDWidget.h" #include #include @@ -56,12 +55,13 @@ LOG_MODULE_DECLARE(app); namespace { - -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); +k_timer sFactoryResetTimer; LEDWidget sStatusLED; @@ -69,10 +69,11 @@ Button sFactoryResetButton; Button sThreadStartButton; Button sBleAdvStartButton; -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; +bool sIsThreadProvisioned = false; +bool sIsThreadEnabled = false; +bool sIsThreadAttached = false; +bool sHaveBLEConnections = false; +bool sIsFactoryResetTimerActive = false; chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; @@ -116,6 +117,17 @@ using namespace ::chip::DeviceLayer::Internal; AppTask AppTask::sAppTask; +class AppFabricTableDelegate : public FabricTable::Delegate +{ + void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) + { + if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + } +}; + constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; CHIP_ERROR AppTask::Init() @@ -126,12 +138,17 @@ CHIP_ERROR AppTask::Init() // Initialize status LED LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); sStatusLED.Init(SYSTEM_STATE_LED_PIN); UpdateStatusLED(); InitButtons(); + // Initialize function button timer + k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); + k_timer_user_data_set(&sFactoryResetTimer, this); + // Init ZCL Data Model and start server static chip::CommonCaseDeviceServerInitParams initParams; (void) initParams.InitializeStaticResourcesBeforeServerInit(); @@ -167,6 +184,13 @@ CHIP_ERROR AppTask::Init() return ret; } + ret = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); + if (ret != CHIP_NO_ERROR) + { + LOG_ERR("AppFabricTableDelegate fail"); + return ret; + } + return CHIP_NO_ERROR; } @@ -191,8 +215,6 @@ CHIP_ERROR AppTask::StartApp() DispatchEvent(&event); ret = k_msgq_get(&sAppEventQueue, &event, K_NO_WAIT); } - - sStatusLED.Animate(); } } @@ -208,8 +230,16 @@ void AppTask::FactoryResetButtonEventHandler(void) void AppTask::FactoryResetHandler(AppEvent * aEvent) { - LOG_INF("FactoryResetHandler"); - chip::Server::GetInstance().ScheduleFactoryReset(); + if (!sIsFactoryResetTimerActive) + { + k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetTriggerTimeout), K_NO_WAIT); + sIsFactoryResetTimerActive = true; + } + else + { + k_timer_stop(&sFactoryResetTimer); + sIsFactoryResetTimerActive = false; + } } void AppTask::StartThreadButtonEventHandler(void) @@ -271,6 +301,23 @@ void AppTask::StartBleAdvHandler(AppEvent * aEvent) } } +void AppTask::UpdateLedStateEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type == AppEvent::kEventType_UpdateLedState) + { + aEvent->UpdateLedStateEvent.LedWidget->UpdateState(); + } +} + +void AppTask::LEDStateUpdateHandler(LEDWidget * ledWidget) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateLedStateEventHandler; + event.UpdateLedStateEvent.LedWidget = ledWidget; + sAppTask.PostEvent(&event); +} + void AppTask::UpdateStatusLED() { if (sIsThreadProvisioned && sIsThreadEnabled) @@ -341,11 +388,36 @@ void AppTask::DispatchEvent(AppEvent * aEvent) } } +void AppTask::FactoryResetTimerTimeoutCallback(k_timer * timer) +{ + if (!timer) + { + return; + } + + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.Handler = FactoryResetTimerEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::FactoryResetTimerEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type != AppEvent::kEventType_Timer) + { + return; + } + + sIsFactoryResetTimerActive = false; + LOG_INF("FactoryResetHandler"); + chip::Server::GetInstance().ScheduleFactoryReset(); +} + void AppTask::InitButtons(void) { - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); + sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, true, FactoryResetButtonEventHandler); + sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, false, StartThreadButtonEventHandler); + sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, false, StartBleAdvButtonEventHandler); ButtonManagerInst().AddButton(sFactoryResetButton); ButtonManagerInst().AddButton(sThreadStartButton); diff --git a/examples/platform/telink/util/include/ButtonManager.h b/examples/platform/telink/util/include/ButtonManager.h index 9c164fd7120c82..c728d59a5ea48d 100644 --- a/examples/platform/telink/util/include/ButtonManager.h +++ b/examples/platform/telink/util/include/ButtonManager.h @@ -26,7 +26,7 @@ class Button { public: - void Configure(const struct device * port, gpio_pin_t outPin, gpio_pin_t inPin, void (*callback)(void)); + void Configure(const struct device * port, gpio_pin_t outPin, gpio_pin_t inPin, bool intBothLevel, void (*callback)(void)); void Poll(Button * previous); void SetCallback(void (*callback)(void)); @@ -38,6 +38,7 @@ class Button gpio_pin_t mOutPin; gpio_pin_t mInPin; int mPreviousState = STATE_LOW; + bool mIntBothLevel = false; void (*mCallback)(void) = NULL; }; diff --git a/examples/platform/telink/util/include/LEDWidget.h b/examples/platform/telink/util/include/LEDWidget.h index e851c03ccc04e2..b1e25d4f91a703 100644 --- a/examples/platform/telink/util/include/LEDWidget.h +++ b/examples/platform/telink/util/include/LEDWidget.h @@ -19,25 +19,32 @@ #include #include +#include class LEDWidget { public: + typedef void (*LEDWidgetStateUpdateHandler)(LEDWidget * ledWidget); + static void InitGpio(const device * port); + static void SetStateUpdateCallback(LEDWidgetStateUpdateHandler stateUpdateCb); const static struct device * mPort; void Init(gpio_pin_t gpioNum); void Set(bool state); void Invert(void); void Blink(uint32_t changeRateMS); void Blink(uint32_t onTimeMS, uint32_t offTimeMS); - void Animate(); + void UpdateState(); private: - int64_t mLastChangeTimeMS; uint32_t mBlinkOnTimeMS; uint32_t mBlinkOffTimeMS; gpio_pin_t mGPIONum; bool mState; + k_timer mLedTimer; + + static void LedStateTimerHandler(k_timer * timer); void DoSet(bool state); + void ScheduleStateChange(); }; diff --git a/examples/platform/telink/util/src/ButtonManager.cpp b/examples/platform/telink/util/src/ButtonManager.cpp index 9afc6ed0f2493d..21decd38b54298 100644 --- a/examples/platform/telink/util/src/ButtonManager.cpp +++ b/examples/platform/telink/util/src/ButtonManager.cpp @@ -29,14 +29,15 @@ LOG_MODULE_REGISTER(ButtonManager); ButtonManager ButtonManager::sInstance; -void Button::Configure(const struct device * port, gpio_pin_t outPin, gpio_pin_t inPin, void (*callback)(void)) +void Button::Configure(const struct device * port, gpio_pin_t outPin, gpio_pin_t inPin, bool intBothLevel, void (*callback)(void)) { __ASSERT(device_is_ready(port), "%s is not ready\n", port->name); - mPort = port; - mOutPin = outPin; - mInPin = inPin; - mCallback = callback; + mPort = port; + mOutPin = outPin; + mInPin = inPin; + mIntBothLevel = intBothLevel; + mCallback = callback; } int Button::Init(void) @@ -91,19 +92,15 @@ void Button::Poll(Button * previous) ret = gpio_pin_get(mPort, mInPin); assert(ret >= 0); - if (ret == STATE_HIGH && mPreviousState != STATE_HIGH) + if ((mIntBothLevel && ret != mPreviousState) || (!mIntBothLevel && ret == STATE_HIGH && ret != mPreviousState)) { - mPreviousState = STATE_HIGH; - if (mCallback != NULL) { mCallback(); } } - else if (ret == STATE_LOW) - { - mPreviousState = STATE_LOW; - } + + mPreviousState = ret; k_msleep(10); } diff --git a/examples/platform/telink/util/src/LEDWidget.cpp b/examples/platform/telink/util/src/LEDWidget.cpp index 3b97fe64375058..cefb8bbc1cb2a0 100644 --- a/examples/platform/telink/util/src/LEDWidget.cpp +++ b/examples/platform/telink/util/src/LEDWidget.cpp @@ -21,6 +21,7 @@ #include const struct device * LEDWidget::mPort = NULL; +static LEDWidget::LEDWidgetStateUpdateHandler sStateUpdateCallback; void LEDWidget::InitGpio(const device * port) { @@ -28,17 +29,25 @@ void LEDWidget::InitGpio(const device * port) __ASSERT(device_is_ready(mPort), "%s is not ready\n", mPort->name); } +void LEDWidget::SetStateUpdateCallback(LEDWidgetStateUpdateHandler stateUpdateCb) +{ + if (stateUpdateCb) + sStateUpdateCallback = stateUpdateCb; +} + void LEDWidget::Init(gpio_pin_t gpioNum) { - mLastChangeTimeMS = 0; - mBlinkOnTimeMS = 0; - mBlinkOffTimeMS = 0; - mGPIONum = gpioNum; - mState = false; + mBlinkOnTimeMS = 0; + mBlinkOffTimeMS = 0; + mGPIONum = gpioNum; + mState = false; int ret = gpio_pin_configure(mPort, mGPIONum, GPIO_OUTPUT_ACTIVE); __ASSERT(ret >= 0, "GPIO pin %d configure - fail. Status%d\n", mGPIONum, ret); + k_timer_init(&mLedTimer, &LEDWidget::LedStateTimerHandler, nullptr); + k_timer_user_data_set(&mLedTimer, this); + Set(false); } @@ -49,7 +58,8 @@ void LEDWidget::Invert(void) void LEDWidget::Set(bool state) { - mLastChangeTimeMS = mBlinkOnTimeMS = mBlinkOffTimeMS = 0; + k_timer_stop(&mLedTimer); + mBlinkOnTimeMS = mBlinkOffTimeMS = 0; DoSet(state); } @@ -60,29 +70,42 @@ void LEDWidget::Blink(uint32_t changeRateMS) void LEDWidget::Blink(uint32_t onTimeMS, uint32_t offTimeMS) { + k_timer_stop(&mLedTimer); + mBlinkOnTimeMS = onTimeMS; mBlinkOffTimeMS = offTimeMS; - Animate(); -} -void LEDWidget::Animate() -{ if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0) { - int64_t nowMS = k_uptime_get(); - int64_t stateDurMS = mState ? mBlinkOnTimeMS : mBlinkOffTimeMS; - - if (nowMS > mLastChangeTimeMS + stateDurMS) - { - DoSet(!mState); - mLastChangeTimeMS = nowMS; - } + DoSet(!mState); + ScheduleStateChange(); } } +void LEDWidget::ScheduleStateChange() +{ + k_timer_start(&mLedTimer, K_MSEC(mState ? mBlinkOnTimeMS : mBlinkOffTimeMS), K_NO_WAIT); +} + void LEDWidget::DoSet(bool state) { mState = state; int ret = gpio_pin_set(mPort, mGPIONum, state); __ASSERT(ret >= 0, "GPIO pin %d set -fail. Status: %d\n", mGPIONum, ret); } + +void LEDWidget::UpdateState() +{ + /* Prevent from keep updating the state if LED was set to solid On/Off value */ + if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0) + { + DoSet(!mState); + ScheduleStateChange(); + } +} + +void LEDWidget::LedStateTimerHandler(k_timer * timer) +{ + if (sStateUpdateCallback) + sStateUpdateCallback(reinterpret_cast(timer->user_data)); +} diff --git a/examples/thermostat/telink/include/AppEvent.h b/examples/thermostat/telink/include/AppEvent.h index 21933d1d03d1d3..07a10228175763 100755 --- a/examples/thermostat/telink/include/AppEvent.h +++ b/examples/thermostat/telink/include/AppEvent.h @@ -23,12 +23,15 @@ struct AppEvent; typedef void (*EventHandler)(AppEvent *); +class LEDWidget; + struct AppEvent { enum AppEventTypes { kEventType_Button = 0, kEventType_Timer, + kEventType_UpdateLedState, kEventType_Thermostat, kEventType_Install, }; @@ -45,6 +48,10 @@ struct AppEvent { void * Context; } TimerEvent; + struct + { + LEDWidget * LedWidget; + } UpdateLedStateEvent; }; EventHandler Handler; diff --git a/examples/thermostat/telink/include/AppTask.h b/examples/thermostat/telink/include/AppTask.h index 8a3322d11d1342..18edadc0436845 100755 --- a/examples/thermostat/telink/include/AppTask.h +++ b/examples/thermostat/telink/include/AppTask.h @@ -19,6 +19,7 @@ #pragma once #include "AppEvent.h" +#include "LEDWidget.h" #include "SensorManager.h" #include "TemperatureManager.h" @@ -50,15 +51,20 @@ class AppTask void DispatchEvent(AppEvent * event); static void UpdateStatusLED(); + static void LEDStateUpdateHandler(LEDWidget * ledWidget); static void FactoryResetButtonEventHandler(void); static void StartThreadButtonEventHandler(void); static void StartBleAdvButtonEventHandler(void); static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + static void FactoryResetTimerTimeoutCallback(k_timer * timer); + + static void FactoryResetTimerEventHandler(AppEvent * aEvent); static void FactoryResetHandler(AppEvent * aEvent); static void StartThreadHandler(AppEvent * aEvent); static void StartBleAdvHandler(AppEvent * aEvent); + static void UpdateLedStateEventHandler(AppEvent * aEvent); static void InitButtons(void); diff --git a/examples/thermostat/telink/src/AppTask.cpp b/examples/thermostat/telink/src/AppTask.cpp index e56092d65262a1..96caac3e06e2bd 100644 --- a/examples/thermostat/telink/src/AppTask.cpp +++ b/examples/thermostat/telink/src/AppTask.cpp @@ -21,7 +21,6 @@ #include "AppConfig.h" #include "AppEvent.h" #include "ButtonManager.h" -#include "LEDWidget.h" #include "ThreadUtil.h" @@ -53,10 +52,10 @@ using namespace ::chip::Credentials; using namespace ::chip::DeviceLayer; namespace { - -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; +constexpr int kFactoryResetTriggerTimeout = 2000; +constexpr int kAppEventQueueSize = 10; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; // NOTE! This key is for test/certification only and should not be available in production devices! // If CONFIG_CHIP_FACTORY_DATA is enabled, this value is read from the factory data. @@ -64,6 +63,7 @@ uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); +k_timer sFactoryResetTimer; LEDWidget sStatusLED; @@ -71,10 +71,11 @@ Button sFactoryResetButton; Button sThreadStartButton; Button sBleAdvStartButton; -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; +bool sIsThreadProvisioned = false; +bool sIsThreadEnabled = false; +bool sIsThreadAttached = false; +bool sHaveBLEConnections = false; +bool sIsFactoryResetTimerActive = false; chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; @@ -113,6 +114,17 @@ Identify sIdentify = { AppTask AppTask::sAppTask; +class AppFabricTableDelegate : public FabricTable::Delegate +{ + void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) + { + if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + } +}; + CHIP_ERROR AppTask::Init() { CHIP_ERROR err; @@ -121,12 +133,17 @@ CHIP_ERROR AppTask::Init() // Initialize status LED LEDWidget::InitGpio(SYSTEM_STATE_LED_PORT); + LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); sStatusLED.Init(SYSTEM_STATE_LED_PIN); UpdateStatusLED(); InitButtons(); + // Initialize function button timer + k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); + k_timer_user_data_set(&sFactoryResetTimer, this); + // Initialize CHIP server #if CONFIG_CHIP_FACTORY_DATA ReturnErrorOnFailure(mFactoryDataProvider.Init()); @@ -183,9 +200,17 @@ CHIP_ERROR AppTask::Init() if (err != CHIP_NO_ERROR) { LOG_ERR("SetBLEDeviceName fail"); + return err; + } + + err = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("AppFabricTableDelegate fail"); + return err; } - return err; + return CHIP_NO_ERROR; } CHIP_ERROR AppTask::StartApp() @@ -209,8 +234,6 @@ CHIP_ERROR AppTask::StartApp() DispatchEvent(&event); ret = k_msgq_get(&sAppEventQueue, &event, K_NO_WAIT); } - - sStatusLED.Animate(); } } @@ -232,8 +255,16 @@ void AppTask::FactoryResetButtonEventHandler(void) void AppTask::FactoryResetHandler(AppEvent * aEvent) { - LOG_INF("FactoryResetHandler"); - chip::Server::GetInstance().ScheduleFactoryReset(); + if (!sIsFactoryResetTimerActive) + { + k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetTriggerTimeout), K_NO_WAIT); + sIsFactoryResetTimerActive = true; + } + else + { + k_timer_stop(&sFactoryResetTimer); + sIsFactoryResetTimerActive = false; + } } void AppTask::StartThreadButtonEventHandler(void) @@ -295,6 +326,23 @@ void AppTask::StartBleAdvHandler(AppEvent * aEvent) } } +void AppTask::UpdateLedStateEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type == AppEvent::kEventType_UpdateLedState) + { + aEvent->UpdateLedStateEvent.LedWidget->UpdateState(); + } +} + +void AppTask::LEDStateUpdateHandler(LEDWidget * ledWidget) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateLedStateEventHandler; + event.UpdateLedStateEvent.LedWidget = ledWidget; + sAppTask.PostEvent(&event); +} + void AppTask::UpdateStatusLED() { if (sIsThreadProvisioned && sIsThreadEnabled) @@ -363,11 +411,36 @@ void AppTask::DispatchEvent(AppEvent * aEvent) void AppTask::UpdateClusterState() {} +void AppTask::FactoryResetTimerTimeoutCallback(k_timer * timer) +{ + if (!timer) + { + return; + } + + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.Handler = FactoryResetTimerEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::FactoryResetTimerEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type != AppEvent::kEventType_Timer) + { + return; + } + + sIsFactoryResetTimerActive = false; + LOG_INF("FactoryResetHandler"); + chip::Server::GetInstance().ScheduleFactoryReset(); +} + void AppTask::InitButtons(void) { - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); + sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, true, FactoryResetButtonEventHandler); + sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, false, StartThreadButtonEventHandler); + sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, false, StartBleAdvButtonEventHandler); ButtonManagerInst().AddButton(sFactoryResetButton); ButtonManagerInst().AddButton(sThreadStartButton); diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index 2e1dff050641d6..bd7dc36231c699 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -527,6 +527,7 @@ def BuildTelinkTarget(): target.AppendFixedTargets([ TargetPart('all-clusters', app=TelinkApp.ALL_CLUSTERS), TargetPart('all-clusters-minimal', app=TelinkApp.ALL_CLUSTERS_MINIMAL), + TargetPart('contact-sensor', app=TelinkApp.CONTACT_SENSOR), TargetPart('light', app=TelinkApp.LIGHT), TargetPart('light-switch', app=TelinkApp.SWITCH), TargetPart('ota-requestor', app=TelinkApp.OTA_REQUESTOR), diff --git a/scripts/build/builders/telink.py b/scripts/build/builders/telink.py index 32a9bf85c3187e..5be30cb72ceb80 100644 --- a/scripts/build/builders/telink.py +++ b/scripts/build/builders/telink.py @@ -23,6 +23,7 @@ class TelinkApp(Enum): ALL_CLUSTERS = auto() ALL_CLUSTERS_MINIMAL = auto() + CONTACT_SENSOR = auto() LIGHT = auto() SWITCH = auto() OTA_REQUESTOR = auto() @@ -33,6 +34,8 @@ def ExampleName(self): return 'all-clusters-app' elif self == TelinkApp.ALL_CLUSTERS_MINIMAL: return 'all-clusters-minimal-app' + elif self == TelinkApp.CONTACT_SENSOR: + return 'contact-sensor-app' elif self == TelinkApp.LIGHT: return 'lighting-app' elif self == TelinkApp.SWITCH: @@ -49,6 +52,8 @@ def AppNamePrefix(self): return 'chip-telink-all-clusters-example' elif self == TelinkApp.ALL_CLUSTERS_MINIMAL: return 'chip-telink-all-clusters-minimal-example' + elif self == TelinkApp.CONTACT_SENSOR: + return 'chip-telink-contact-sensor-example' elif self == TelinkApp.LIGHT: return 'chip-telink-lighting-example' elif self == TelinkApp.SWITCH: diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index 2fbf8d8813520f..015f917dac3200 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -18,5 +18,5 @@ nrf-{nrf5340dk,nrf52840dk,nrf52840dongle}-{all-clusters,all-clusters-minimal,loc nrf-native-posix-64-tests qpg-qpg6105-{lock,light,shell,persistent-storage} tizen-arm-{all-clusters,all-clusters-minimal,chip-tool,light}[-no-ble][-no-wifi][-asan][-ubsan] -telink-tlsr9518adk80d-{all-clusters,all-clusters-minimal,light,light-switch,ota-requestor,thermostat} +telink-tlsr9518adk80d-{all-clusters,all-clusters-minimal,contact-sensor,light,light-switch,ota-requestor,thermostat} openiotsdk-{shell,lock} diff --git a/scripts/tools/telink/mfg_tool.py b/scripts/tools/telink/mfg_tool.py index 2c4390c0d0eed3..fc3f1eb596d27c 100644 --- a/scripts/tools/telink/mfg_tool.py +++ b/scripts/tools/telink/mfg_tool.py @@ -644,7 +644,7 @@ def base64_str(s): return base64.b64decode(s) basic_args.add_argument('--part_number', type=str, required=False, help='Provide human-readable product number') part_gen_args = parser.add_argument_group('Partition generator options') - part_gen_args.add_argument('--offset', type=allow_any_int, default=0x1F4000, + part_gen_args.add_argument('--offset', type=allow_any_int, default=0x104000, help='Partition offset - an address in devices NVM memory, where factory data will be stored') part_gen_args.add_argument('--size', type=allow_any_int, default=0x1000, help='The maximum partition size') diff --git a/scripts/tools/telink/readme.md b/scripts/tools/telink/readme.md index d3539b590d3591..4bb4a8a32a9d1c 100644 --- a/scripts/tools/telink/readme.md +++ b/scripts/tools/telink/readme.md @@ -187,7 +187,7 @@ You can try one of these factory partition FW on developing stage. > [v1.0-branch](https://github.com/telink-semi/zephyr/blob/telink_matter_v1.0-branch/boards/riscv/tlsr9518adk80d/tlsr9518adk80d.dts) > is `0xF4000` and for > [master branch](https://github.com/telink-semi/zephyr/blob/telink_matter/boards/riscv/tlsr9518adk80d/tlsr9518adk80d.dts) - > is `0x1F4000`. You can check the `factory_partition` reg at + > is `0x104000`. You can check the `factory_partition` reg at > `tlsr9518adk80d.dts` for details. For example, the `factory_data_bin` with serial number diff --git a/src/platform/telink/BLEManagerImpl.cpp b/src/platform/telink/BLEManagerImpl.cpp index f11d3c087678b6..fdb120ef9414e6 100644 --- a/src/platform/telink/BLEManagerImpl.cpp +++ b/src/platform/telink/BLEManagerImpl.cpp @@ -886,24 +886,17 @@ ssize_t BLEManagerImpl::HandleC3Read(struct bt_conn * conId, const struct bt_gat } #endif -void BLEManagerImpl::BLEConnDisconnect(System::Layer * layer, void * param) +CHIP_ERROR BLEManagerImpl::HandleOperationalNetworkEnabled(const ChipDeviceEvent * event) { + ChipLogDetail(DeviceLayer, "HandleOperationalNetworkEnabled"); + int error = bt_conn_disconnect(BLEMgrImpl().mconId, BT_HCI_ERR_LOCALHOST_TERM_CONN); if (error) { ChipLogError(DeviceLayer, "Close BLEConn err: %d", error); } -} -CHIP_ERROR BLEManagerImpl::HandleOperationalNetworkEnabled(const ChipDeviceEvent * event) -{ - - ChipLogDetail(DeviceLayer, "HandleOperationalNetworkEnabled"); - - // Start timer to close BLE connection. - DeviceLayer::SystemLayer().StartTimer(System::Clock::Milliseconds32(20), BLEConnDisconnect, this); - - return CHIP_NO_ERROR; + return MapErrorZephyr(error); } CHIP_ERROR BLEManagerImpl::HandleThreadStateChange(const ChipDeviceEvent * event) diff --git a/src/platform/telink/BLEManagerImpl.h b/src/platform/telink/BLEManagerImpl.h index f6fcbf87c8e584..9937e1212724e2 100644 --- a/src/platform/telink/BLEManagerImpl.h +++ b/src/platform/telink/BLEManagerImpl.h @@ -127,7 +127,6 @@ 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();