diff --git a/.github/workflows/examples-infineon.yaml b/.github/workflows/examples-infineon.yaml index b3f3e946e53b49..262f2fcc7cd42f 100644 --- a/.github/workflows/examples-infineon.yaml +++ b/.github/workflows/examples-infineon.yaml @@ -141,7 +141,8 @@ jobs: "./scripts/build/build_examples.py \ --target cyw30739-cyw930739m2evb_01-light \ --target cyw30739-cyw930739m2evb_01-lock \ - --target cyw30739-cyw930739m2evb_01-ota-requestor-no-progress-logging \ + --target cyw30739-cyw930739m2evb_01-ota-requestor \ + --target cyw30739-cyw930739m2evb_01-switch \ build \ --copy-artifacts-to out/artifacts \ " @@ -163,8 +164,15 @@ jobs: timeout-minutes: 5 run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - cyw30739 cyw930739m2evb_01 ota-requestor-no-progress-logging \ - out/artifacts/cyw30739-cyw930739m2evb_01-ota-requestor-no-progress-logging/chip-cyw30739-ota-requestor-example.elf \ + cyw30739 cyw930739m2evb_01 ota-requestor \ + out/artifacts/cyw30739-cyw930739m2evb_01-ota-requestor/chip-cyw30739-ota-requestor-example.elf \ + /tmp/bloat_reports/ + - name: Get switch size stats + timeout-minutes: 5 + run: | + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ + cyw30739 cyw930739m2evb_01 switch \ + out/artifacts/cyw30739-cyw930739m2evb_01-switch/chip-cyw30739-light-switch-example.elf \ /tmp/bloat_reports/ - name: Uploading Size Reports uses: actions/upload-artifact@v3 diff --git a/.github/workflows/examples-linux-standalone.yaml b/.github/workflows/examples-linux-standalone.yaml index fc40301b2b9249..f2931055be403e 100644 --- a/.github/workflows/examples-linux-standalone.yaml +++ b/.github/workflows/examples-linux-standalone.yaml @@ -179,6 +179,17 @@ jobs: linux debug bridge-app \ out/linux-x64-bridge/chip-bridge-app \ /tmp/bloat_reports/ + - name: Build example Dynamic Bridge + timeout-minutes: 10 + run: | + ./scripts/run_in_build_env.sh \ + "./scripts/build/build_examples.py \ + --target linux-x64-dynamic-bridge-ipv6only \ + build" + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ + linux debug dynamic-bridge-app-ipv6only \ + out/linux-x64-dynamic-bridge-ipv6only/dynamic-chip-bridge-app \ + /tmp/bloat_reports/ - name: Build example OTA Provider timeout-minutes: 10 run: | diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index 9cff443cfeb0c3..3883512f0d729b 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -135,6 +135,6 @@ jobs: run: | ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ - --target tizen-arm-tests-no-ble \ + --target tizen-arm-tests-no-ble-no-thread \ build " diff --git a/.vscode/settings.json b/.vscode/settings.json index a8e2b99d4e8a70..93e190d66f5cae 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -168,5 +168,6 @@ "files.trimFinalNewlines": true, "C_Cpp.default.cppStandard": "gnu++14", "C_Cpp.default.cStandard": "gnu11", - "cmake.configureOnOpen": false + "cmake.configureOnOpen": false, + "search.followSymlinks": false } diff --git a/build/chip/fuzz_test.gni b/build/chip/fuzz_test.gni index 7d40a70851a222..7b683be047d913 100644 --- a/build/chip/fuzz_test.gni +++ b/build/chip/fuzz_test.gni @@ -15,10 +15,11 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") import("${build_root}/config/compiler/compiler.gni") +import("${chip_root}/build/chip/tests.gni") declare_args() { - enable_fuzz_test_targets = - is_clang && (current_os == "linux" || current_os == "mac") + enable_fuzz_test_targets = is_clang && chip_build_tests && + (current_os == "linux" || current_os == "mac") } # Define a fuzz target for chip. diff --git a/config/nrfconnect/chip-module/Kconfig.features b/config/nrfconnect/chip-module/Kconfig.features index 99d13e9d56aa59..0501e351681e9a 100644 --- a/config/nrfconnect/chip-module/Kconfig.features +++ b/config/nrfconnect/chip-module/Kconfig.features @@ -171,4 +171,27 @@ config CHIP_WIFI_CONNECTION_RECOVERY_JITTER a random jitter interval is added to it to avoid periodicity. The random jitter is selected within range [-JITTER; +JITTER]. +config CHIP_ICD_SUBSCRIPTION_HANDLING + bool "Enables platform specific handling of ICD subscriptions" + help + Enables platform specific implementation that handles ICD subscription requests + and selects subscription report interval value considering maximum interval preferred + by the publisher. + +if CHIP_ICD_SUBSCRIPTION_HANDLING + +config CHIP_MAX_PREFERRED_SUBSCRIPTION_REPORT_INTERVAL + int "Maximum preferred interval of sending subscription reports (s)" + default 60 + help + Provides maximum preferred interval to be used by a publisher for negotiation + of the final maximum subscription report interval, after receiving a subscription + request from the initiator. This value should be selected as a compromise between + keeping the power consumption low due to not sending reports too often, and allowing + the initiator device to detect the publisher absence reasonably fast due to not sending + the reports too rarely. The current algorithm is to select bigger value from the one + requested by the initiator and the one preferred by the publisher. + +endif # CHIP_ICD_SUBSCRIPTION_HANDLING + endif # CHIP diff --git a/config/openiotsdk/cmake/sdk.cmake b/config/openiotsdk/cmake/sdk.cmake index 25851c2d7ded2f..dbe54d4d122c37 100644 --- a/config/openiotsdk/cmake/sdk.cmake +++ b/config/openiotsdk/cmake/sdk.cmake @@ -42,6 +42,22 @@ FetchContent_Declare( GIT_PROGRESS ON ) +# Apply a patch to TF-M to support GCC 12 +FetchContent_Declare( + trusted-firmware-m + GIT_REPOSITORY https://git.trustedfirmware.org/TF-M/trusted-firmware-m.git + GIT_TAG d0c0a67f1b412e89d09b0987091c12998c4e4660 + GIT_SHALLOW OFF + GIT_PROGRESS ON + # Note: This prevents FetchContent_MakeAvailable() from calling + # add_subdirectory() on the fetched repository. TF-M needs a + # standalone build because it relies on functions defined in its + # own toolchain files and contains paths that reference the + # top-level project instead of its own project. + SOURCE_SUBDIR NONE + PATCH_COMMAND git reset --hard --quiet && git clean --force -dx --quiet && git apply ${CMAKE_CURRENT_LIST_DIR}/tf-m.patch +) + # Open IoT SDK configuration set(IOTSDK_FETCH_LIST mcu-driver-reference-platforms-for-arm diff --git a/config/openiotsdk/cmake/tf-m.patch b/config/openiotsdk/cmake/tf-m.patch new file mode 100644 index 00000000000000..975696d5e63752 --- /dev/null +++ b/config/openiotsdk/cmake/tf-m.patch @@ -0,0 +1,12 @@ +diff --git a/toolchain_GNUARM.cmake b/toolchain_GNUARM.cmake +index d044ed4a5..3d8f64d17 100644 +--- a/toolchain_GNUARM.cmake ++++ b/toolchain_GNUARM.cmake +@@ -71,7 +71,6 @@ macro(tfm_toolchain_reset_linker_flags) + --entry=Reset_Handler + --specs=nano.specs + LINKER:-check-sections +- LINKER:-fatal-warnings + LINKER:--gc-sections + LINKER:--no-wchar-size-warning + ${MEMORY_USAGE_FLAG} diff --git a/config/telink/app/zephyr.conf b/config/telink/app/zephyr.conf index ebf6c3abe5edfc..2a97b363833dcc 100644 --- a/config/telink/app/zephyr.conf +++ b/config/telink/app/zephyr.conf @@ -22,13 +22,15 @@ CONFIG_SERIAL=y CONFIG_LOG=y CONFIG_LOG_MODE_MINIMAL=y CONFIG_PRINTK=y -CONFIG_ASSERT=y +# CONFIG_ASSERT=y CONFIG_CBPRINTF_LIBC_SUBSTS=y # Set the maximum log level (DEBUG) CONFIG_LOG_DEFAULT_LEVEL=4 CONFIG_MATTER_LOG_LEVEL_DBG=y +CONFIG_MCUBOOT_BOOTUTIL_LIB=y CONFIG_MCUBOOT_UTIL_LOG_LEVEL_DBG=y +CONFIG_NET_LOG=y CONFIG_IEEE802154_DRIVER_LOG_LEVEL_DBG=y CONFIG_NVS_LOG_LEVEL_DBG=y CONFIG_OPENTHREAD_LOG_LEVEL_DEBG=y @@ -125,10 +127,6 @@ CONFIG_TELINK_B91_REBOOT_ON_FAULT=y # Shell settings CONFIG_SHELL=n -CONFIG_SHELL_BACKEND_SERIAL_RX_RING_BUFFER_SIZE=255 - -# Legacy -CONFIG_LEGACY_INCLUDE_PATH=y # BLE MAC address CONFIG_B91_BLE_CTRL_MAC_FLASH_ADDR=0x1FE000 diff --git a/config/telink/chip-module/Kconfig b/config/telink/chip-module/Kconfig index 7760b734632648..bce258355feff8 100644 --- a/config/telink/chip-module/Kconfig +++ b/config/telink/chip-module/Kconfig @@ -152,20 +152,20 @@ config CHIP_LOG_SIZE_OPTIMIZATION config CHIP_BUTTON_MANAGER_IRQ_MODE bool "Use GPIO in an IRQ mode instead of polling the GPIO" - default n + default PM help Use GPIO in an IRQ mode to avoid button polling loop and extend the battery lifetime by waking up by GPIO event. GPIO events are working only with GPIO IRQ. This option changes button matrix configuration. config CHIP_ENABLE_APPLICATION_STATUS_LED bool "Enable application status LED" - default y + default !(PM) help Enable application status LED. config CHIP_ENABLE_PM_DURING_BLE bool "Enable PM during BLE operation" - default y + default PM help Enable PM during BLE operation. @@ -175,3 +175,7 @@ config CHIP_OPENTHREAD_TX_POWER default 0 help OpenThread Transmission power in dBm. + +config SHELL_BACKEND_SERIAL_RX_RING_BUFFER_SIZE + int + default 255 if SHELL_BACKEND_SERIAL diff --git a/docs/guides/BUILDING.md b/docs/guides/BUILDING.md index 78ad0ecd0d6e0a..08900d3313e340 100644 --- a/docs/guides/BUILDING.md +++ b/docs/guides/BUILDING.md @@ -55,10 +55,26 @@ sudo apt-get install git gcc g++ pkg-config libssl-dev libdbus-1-dev \ python3-pip unzip libgirepository1.0-dev libcairo2-dev libreadline-dev ``` +#### UI builds + +If building `-with-ui` variant, also install SDL2: + +``` +sudo apt-get install libsdl2-dev +``` + ### Installing prerequisites on macOS On macOS, install Xcode from the Mac App Store. +#### UI builds + +If building `-with-ui` variant, also install SDL2: + +``` +brew install sdl2 +``` + ### Installing prerequisites on Raspberry Pi 4 Complete the following steps: diff --git a/docs/guides/esp32/build_app_and_commission.md b/docs/guides/esp32/build_app_and_commission.md index eeb5f1296b49f2..a9145a2efe7d21 100644 --- a/docs/guides/esp32/build_app_and_commission.md +++ b/docs/guides/esp32/build_app_and_commission.md @@ -198,7 +198,10 @@ $ out/debug/chip-tool pairing onnetwork 12345 20202021 Note: In order to commission an ethernet device, from all-clusters-app enable these config options: select `ESP32-Ethernet-Kit` under `Demo->Device Type` and -select `On-Network` rendezvous mode under `Demo->Rendezvous Mode` +select `On-Network` rendezvous mode under `Demo->Rendezvous Mode`. Currently +default ethernet board supported is IP101, if you want to use other types of +ethernet board then override the current implementation under +`ConnectivityManagerImpl::InitEthernet` #### Commissioning Parameters diff --git a/docs/guides/esp32/factory_data.md b/docs/guides/esp32/factory_data.md index 9818eec9880964..179fb2e315a9c0 100644 --- a/docs/guides/esp32/factory_data.md +++ b/docs/guides/esp32/factory_data.md @@ -34,6 +34,9 @@ Following data can be added to the manufacturing partition using - Fixed Labels - Supported locales - Supported calendar types + - Supported modes + - Note: As per spec at max size of label should be 64 and `\0` will be + added at the end. ### Configuration Options diff --git a/docs/guides/esp32/setup_idf_chip.md b/docs/guides/esp32/setup_idf_chip.md index bd30222934dcb4..13feaee221ca4e 100644 --- a/docs/guides/esp32/setup_idf_chip.md +++ b/docs/guides/esp32/setup_idf_chip.md @@ -13,27 +13,27 @@ step. ### Install Prerequisites -- [Linux](https://docs.espressif.com/projects/esp-idf/en/v4.4.3/esp32/get-started/linux-setup.html) -- [macOS](https://docs.espressif.com/projects/esp-idf/en/v4.4.3/esp32/get-started/macos-setup.html) +- [Linux](https://docs.espressif.com/projects/esp-idf/en/v4.4.4/esp32/get-started/linux-setup.html) +- [macOS](https://docs.espressif.com/projects/esp-idf/en/v4.4.4/esp32/get-started/macos-setup.html) -### Get IDF v4.4.3 +### Get IDF v4.4.4 - Clone ESP-IDF - [v4.4.3 release](https://github.com/espressif/esp-idf/releases/tag/v4.4.3) + [v4.4.4 release](https://github.com/espressif/esp-idf/releases/tag/v4.4.4) ``` - $ git clone -b v4.4.3 --recursive https://github.com/espressif/esp-idf.git + $ git clone -b v4.4.4 --recursive https://github.com/espressif/esp-idf.git $ cd esp-idf $ ./install.sh ``` -- To update an existing esp-idf toolchain to v4.4.3: +- To update an existing esp-idf toolchain to v4.4.4: ``` $ cd path/to/esp-idf $ git fetch origin - $ git checkout v4.4.3 - $ git reset --hard origin/v4.4.3 + $ git checkout v4.4.4 + $ git reset --hard origin/v4.4.4 $ git submodule update --recursive --init $ git clean -fdx $ ./install.sh diff --git a/examples/all-clusters-app/esp32/main/CMakeLists.txt b/examples/all-clusters-app/esp32/main/CMakeLists.txt index 4b2f6a464e2933..70f17774c00d77 100644 --- a/examples/all-clusters-app/esp32/main/CMakeLists.txt +++ b/examples/all-clusters-app/esp32/main/CMakeLists.txt @@ -32,6 +32,7 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/common" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/shell_extension" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/lock" + "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/platform/esp32/mode-support" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/server" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/util" "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/src/app/reporting" @@ -91,6 +92,9 @@ set(SRC_DIRS_LIST "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/all-clusters-app/all-clusters-common/src" ) + +set(EXCLUDE_SRCS "${CMAKE_SOURCE_DIR}/third_party/connectedhomeip/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp") + if (CONFIG_ENABLE_PW_RPC) # Append additional directories for RPC build set(PRIV_INCLUDE_DIRS_LIST "${PRIV_INCLUDE_DIRS_LIST}" @@ -119,7 +123,7 @@ endif() idf_component_register(PRIV_INCLUDE_DIRS ${PRIV_INCLUDE_DIRS_LIST} SRC_DIRS ${SRC_DIRS_LIST} - EXCLUDE_SRCS ${EXCLUDE_SRCS_LIST} + EXCLUDE_SRCS ${EXCLUDE_SRCS} PRIV_REQUIRES ${PRIV_REQUIRES_LIST}) get_filename_component(CHIP_ROOT ${CMAKE_SOURCE_DIR}/third_party/connectedhomeip REALPATH) diff --git a/examples/all-clusters-app/telink/CMakeLists.txt b/examples/all-clusters-app/telink/CMakeLists.txt index 86eee4dbb2373f..584806456e5233 100644 --- a/examples/all-clusters-app/telink/CMakeLists.txt +++ b/examples/all-clusters-app/telink/CMakeLists.txt @@ -61,6 +61,7 @@ target_include_directories(app PRIVATE ${ALL_CLUSTERS_COMMON_DIR}/include ${GEN_DIR}/app-common ${GEN_DIR}/all-clusters-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include) add_definitions( @@ -69,11 +70,12 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp - src/main.cpp src/ZclDoorLockCallbacks.cpp ${ALL_CLUSTERS_COMMON_DIR}/src/static-supported-modes-manager.cpp ${ALL_CLUSTERS_COMMON_DIR}/src/bridged-actions-stub.cpp ${ALL_CLUSTERS_COMMON_DIR}/src/binding-handler.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/all-clusters-app/telink/include/AppConfig.h b/examples/all-clusters-app/telink/include/AppConfig.h index 8eb990230520e6..880f3aa7b98c50 100644 --- a/examples/all-clusters-app/telink/include/AppConfig.h +++ b/examples/all-clusters-app/telink/include/AppConfig.h @@ -19,16 +19,10 @@ #pragma once // ---- All Clusters Application example config ---- +#define APP_USE_EXAMPLE_START_BUTTON 0 +#define APP_USE_THREAD_START_BUTTON 1 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 1 +#define APP_USE_IDENTIFY_PWM 1 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -// 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 -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 -#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) +#include "AppConfigCommon.h" diff --git a/examples/all-clusters-app/telink/include/AppTask.h b/examples/all-clusters-app/telink/include/AppTask.h index 88cc4d8418d177..24e00675e78472 100644 --- a/examples/all-clusters-app/telink/include/AppTask.h +++ b/examples/all-clusters-app/telink/include/AppTask.h @@ -18,71 +18,17 @@ #pragma once -#include "AppEvent.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.h" +#include "AppTaskCommon.h" -#include - -#include - -#if CONFIG_CHIP_FACTORY_DATA -#include -#endif - -#include - -struct k_timer; -struct Identify; - -class AppTask +class AppTask : public AppTaskCommon { -public: - CHIP_ERROR StartApp(void); - - void PostEvent(AppEvent * event); - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); - private: friend AppTask & GetAppTask(void); + friend class AppTaskCommon; - CHIP_ERROR Init(void); - - static void ActionIdentifyStateUpdateHandler(k_timer * timer); - - void DispatchEvent(AppEvent * event); - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - 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 UpdateIdentifyStateEventHandler(AppEvent * aEvent); - - static void InitButtons(void); - - static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + CHIP_ERROR Init(); static AppTask sAppTask; - PWMDevice mPwmIdentifyLed; - -#if CONFIG_CHIP_FACTORY_DATA - chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; -#endif }; inline AppTask & GetAppTask(void) diff --git a/examples/all-clusters-app/telink/prj.conf b/examples/all-clusters-app/telink/prj.conf index bc8ce45c357204..549cf67ea46cdf 100644 --- a/examples/all-clusters-app/telink/prj.conf +++ b/examples/all-clusters-app/telink/prj.conf @@ -26,9 +26,7 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=y -CONFIG_OPENTHREAD_FTD=n CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings @@ -63,13 +61,5 @@ CONFIG_CHIP_FACTORY_DATA=n CONFIG_CHIP_FACTORY_DATA_BUILD=n CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management CONFIG_PM=n -CONFIG_PM_DEVICE=n -CONFIG_CHIP_ENABLE_PM_DURING_BLE=n diff --git a/examples/all-clusters-app/telink/src/AppTask.cpp b/examples/all-clusters-app/telink/src/AppTask.cpp index cffc3cdb6c4426..74f1c4c3ec7494 100644 --- a/examples/all-clusters-app/telink/src/AppTask.cpp +++ b/examples/all-clusters-app/telink/src/AppTask.cpp @@ -17,206 +17,24 @@ */ #include "AppTask.h" - -#include "AppConfig.h" -#include "AppEvent.h" -#include "ButtonManager.h" #include "binding-handler.h" -#include "ThreadUtil.h" - -#include -#include -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL - LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; - -namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kEndpointId = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; -constexpr uint32_t kIdentifyBlinkRateMs = 200; -constexpr uint32_t kIdentifyOkayOnRateMs = 50; -constexpr uint32_t kIdentifyOkayOffRateMs = 950; -constexpr uint32_t kIdentifyFinishOnRateMs = 950; -constexpr uint32_t kIdentifyFinishOffRateMs = 50; -constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; -constexpr uint32_t kIdentifyBreatheRateMs = 1000; - -const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; - -#if CONFIG_CHIP_FACTORY_DATA -// NOTE! This key is for test/certification only and should not be available in production devices! -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; -#endif - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; -#endif - -Button sFactoryResetButton; -Button sThreadStartButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - -void OnIdentifyTriggerEffect(Identify * identify) -{ - AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); -} - -Identify sIdentify = { - kEndpointId, - [](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(); - } - } -}; - -constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; - CHIP_ERROR AppTask::Init(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); - - // Initialize LEDs -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); -#endif - - InitButtons(); - - // Initialize function button timer - k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); - k_timer_user_data_set(&sFactoryResetTimer, this); - - // Initialize PWM Identify led - CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("Green IDENTIFY PWM Device Init fail"); - return err; - } - - sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); - - // 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("mFactoryDataProvider.GetEnableKey() failed. Could not delegate a test event trigger"); - memset(sTestEventTriggerEnableKey, 0, sizeof(sTestEventTriggerEnableKey)); - } -#else - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); -#endif - - static CommonCaseDeviceServerInitParams initParams; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - ReturnErrorOnFailure(chip::Server::GetInstance().Init(initParams)); - gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); - chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); - -#if CONFIG_CHIP_OTA_REQUESTOR - InitBasicOTARequestor(); -#endif - - // We only have network commissioning on endpoint 0. - // Set up a valid Network Commissioning cluster on endpoint 0 is done in - // src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.cpp - emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); - - ConfigurationMgr().LogDeviceConfig(); + InitCommonParts(); // Configure Bindings - err = InitBindingHandlers(); + CHIP_ERROR err = InitBindingHandlers(); if (err != CHIP_NO_ERROR) { LOG_ERR("InitBindingHandlers fail"); return err; } - 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); - err = ConnectivityMgr().SetBLEDeviceName("TelinkApp"); if (err != CHIP_NO_ERROR) { @@ -224,312 +42,5 @@ CHIP_ERROR AppTask::Init(void) 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; } - -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) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&event); - } -} - -void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) -{ - AppEvent event; - event.Type = AppEvent::kEventType_IdentifyStart; - - switch (aEffect) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); - event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; - event.Type = AppEvent::kEventType_IdentifyStop; - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - return; - } - - 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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -void AppTask::StartThreadButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartThreadHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartThreadHandler(AppEvent * aEvent) -{ - LOG_INF("StartThreadHandler"); - if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) - { - // Switch context from BLE to Thread - Internal::BLEManagerImpl sInstance; - sInstance.SwitchToIeee802154(); - StartDefaultThreadNetwork(); - } - else - { - LOG_INF("Device already commissioned"); - } -} - -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadConnectivityChange: -#if CONFIG_CHIP_OTA_REQUESTOR - if (event->ThreadConnectivityChange.Result == kConnectivity_Established) - { - InitBasicOTARequestor(); - } -#endif - break; - default: - break; - } -} - -void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_UpdateLedState; - event.Handler = UpdateIdentifyStateEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) -{ - sAppTask.mPwmIdentifyLed.UpdateAction(); -} - -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::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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - 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); -#endif - - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sThreadStartButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} diff --git a/examples/all-clusters-app/telink/src/main.cpp b/examples/all-clusters-app/telink/src/main.cpp deleted file mode 100644 index dc8216db43d274..00000000000000 --- a/examples/all-clusters-app/telink/src/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright (c) 2022-2023 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, CONFIG_CHIP_APP_LOG_LEVEL); - -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/all-clusters-minimal-app/telink/CMakeLists.txt b/examples/all-clusters-minimal-app/telink/CMakeLists.txt index f5a0eeb9ede2e6..0d7e3a5313b12b 100644 --- a/examples/all-clusters-minimal-app/telink/CMakeLists.txt +++ b/examples/all-clusters-minimal-app/telink/CMakeLists.txt @@ -61,6 +61,7 @@ target_include_directories(app PRIVATE ${ALL_CLUSTERS_COMMON_DIR}/include ${GEN_DIR}/app-common ${GEN_DIR}/all-clusters-minimal-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include) add_definitions( @@ -69,10 +70,11 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp - src/main.cpp ${ALL_CLUSTERS_COMMON_DIR}/src/static-supported-modes-manager.cpp ${ALL_CLUSTERS_COMMON_DIR}/src/bridged-actions-stub.cpp ${ALL_CLUSTERS_COMMON_DIR}/src/binding-handler.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp) diff --git a/examples/all-clusters-minimal-app/telink/include/AppConfig.h b/examples/all-clusters-minimal-app/telink/include/AppConfig.h index 1e0b2ae8e72ec0..10d4d5f281d67a 100644 --- a/examples/all-clusters-minimal-app/telink/include/AppConfig.h +++ b/examples/all-clusters-minimal-app/telink/include/AppConfig.h @@ -18,16 +18,12 @@ #pragma once -// ---- All Clusters Application example config ---- +// ---- All Clusters Minimal Application example config ---- -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#define APP_USE_EXAMPLE_START_BUTTON 0 +#define APP_USE_THREAD_START_BUTTON 0 +#define APP_SET_DEVICE_INFO_PROVIDER 0 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 1 +#define APP_USE_IDENTIFY_PWM 0 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 - -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 +#include "AppConfigCommon.h" diff --git a/examples/all-clusters-minimal-app/telink/include/AppTask.h b/examples/all-clusters-minimal-app/telink/include/AppTask.h index 596f0836d2ea2c..24e00675e78472 100644 --- a/examples/all-clusters-minimal-app/telink/include/AppTask.h +++ b/examples/all-clusters-minimal-app/telink/include/AppTask.h @@ -18,53 +18,16 @@ #pragma once -#include "AppEvent.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif +#include "AppTaskCommon.h" -#include - -#include - -#include - -struct k_timer; - -class AppTask +class AppTask : public AppTaskCommon { -public: - CHIP_ERROR StartApp(); - - void PostEvent(AppEvent * event); - private: friend AppTask & GetAppTask(void); + friend class AppTaskCommon; CHIP_ERROR Init(); - void DispatchEvent(AppEvent * event); - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - 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 InitButtons(void); - - static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); - static AppTask sAppTask; }; diff --git a/examples/all-clusters-minimal-app/telink/prj.conf b/examples/all-clusters-minimal-app/telink/prj.conf index 2c563df99dad1b..90d531fa2b1087 100644 --- a/examples/all-clusters-minimal-app/telink/prj.conf +++ b/examples/all-clusters-minimal-app/telink/prj.conf @@ -23,7 +23,8 @@ CONFIG_GPIO=y # OpenThread configs CONFIG_OPENTHREAD_MTD=y -CONFIG_OPENTHREAD_FTD=n +CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n +CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings CONFIG_OPENTHREAD_PANID=4660 @@ -52,8 +53,8 @@ CONFIG_CHIP_ENABLE_PAIRING_AUTOSTART=y # CHIP shell CONFIG_CHIP_LIB_SHELL=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y +# Disable factory data support. +CONFIG_CHIP_FACTORY_DATA=n +CONFIG_CHIP_FACTORY_DATA_BUILD=n +CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n +CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE=n diff --git a/examples/all-clusters-minimal-app/telink/src/AppTask.cpp b/examples/all-clusters-minimal-app/telink/src/AppTask.cpp index 0dc0bb1a320a0d..93a83af0dbf44b 100644 --- a/examples/all-clusters-minimal-app/telink/src/AppTask.cpp +++ b/examples/all-clusters-minimal-app/telink/src/AppTask.cpp @@ -17,147 +17,24 @@ */ #include "AppTask.h" - -#include "AppConfig.h" -#include "AppEvent.h" -#include "ButtonManager.h" #include "binding-handler.h" -#include "ThreadUtil.h" - -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include - -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL - LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -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; -uint8_t sFactoryResetCntr = 0; - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; -#endif - -Button sFactoryResetButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -} // namespace - -using namespace ::chip; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; -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() { - 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 -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); -#endif - - 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(); - chip::Server::GetInstance().Init(initParams); - - // Initialize device attestation config - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); - -#if CONFIG_CHIP_OTA_REQUESTOR - InitBasicOTARequestor(); -#endif - - // We only have network commissioning on endpoint 0. - // Set up a valid Network Commissioning cluster on endpoint 0 is done in - // src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.cpp - emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); - - ConfigurationMgr().LogDeviceConfig(); + InitCommonParts(); // Configure Bindings - err = InitBindingHandlers(); + CHIP_ERROR err = InitBindingHandlers(); if (err != CHIP_NO_ERROR) { LOG_ERR("InitBindingHandlers fail"); return err; } - 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); - err = ConnectivityMgr().SetBLEDeviceName("TelinkMinApp"); if (err != CHIP_NO_ERROR) { @@ -165,224 +42,5 @@ CHIP_ERROR AppTask::Init() 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; } - -CHIP_ERROR AppTask::StartApp() -{ - CHIP_ERROR err = Init(); - - if (err != CHIP_NO_ERROR) - { - LOG_ERR("AppTask Init fail"); - return err; - } - - AppEvent event = {}; - - while (true) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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) - { - if (sIsThreadAttached) - { - sStatusLED.Blink(950, 50); - } - else - { - sStatusLED.Blink(100, 100); - } - } - else - { - sStatusLED.Blink(50, 950); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - 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 (!aEvent) - return; - if (k_msgq_put(&sAppEventQueue, aEvent, K_NO_WAIT) != 0) - { - LOG_INF("PostEvent fail"); - } -} - -void AppTask::DispatchEvent(AppEvent * aEvent) -{ - if (!aEvent) - return; - if (aEvent->Handler) - { - aEvent->Handler(aEvent); - } - else - { - LOG_INF("Dropping event without handler"); - } -} - -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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); -#endif - - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} diff --git a/examples/all-clusters-minimal-app/telink/src/main.cpp b/examples/all-clusters-minimal-app/telink/src/main.cpp deleted file mode 100644 index dc8216db43d274..00000000000000 --- a/examples/all-clusters-minimal-app/telink/src/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright (c) 2022-2023 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, CONFIG_CHIP_APP_LOG_LEVEL); - -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/bridge-app/esp32/main/main.cpp b/examples/bridge-app/esp32/main/main.cpp index f0762ef631749b..4f92a657949466 100644 --- a/examples/bridge-app/esp32/main/main.cpp +++ b/examples/bridge-app/esp32/main/main.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -361,6 +362,8 @@ const EmberAfDeviceType gBridgedOnOffDeviceTypes[] = { { DEVICE_TYPE_LO_ON_OFF_L static void InitServer(intptr_t context) { + PrintOnboardingCodes(chip::RendezvousInformationFlags(CONFIG_RENDEZVOUS_MODE)); + Esp32AppServer::Init(); // Init ZCL Data Model and CHIP App Server AND Initialize device attestation config // Set starting endpoint id where dynamic endpoints will be assigned, which diff --git a/examples/bridge-app/telink/CMakeLists.txt b/examples/bridge-app/telink/CMakeLists.txt index 52e498d10927fe..46953af249d8b7 100644 --- a/examples/bridge-app/telink/CMakeLists.txt +++ b/examples/bridge-app/telink/CMakeLists.txt @@ -59,6 +59,7 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/bridge-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) @@ -69,10 +70,11 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp - src/main.cpp src/ZclCallbacks.cpp src/Device.cpp src/DeviceCallbacks.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/bridge-app/telink/include/AppConfig.h b/examples/bridge-app/telink/include/AppConfig.h index 88918d553e078d..3f7cccb6807d10 100644 --- a/examples/bridge-app/telink/include/AppConfig.h +++ b/examples/bridge-app/telink/include/AppConfig.h @@ -20,20 +20,12 @@ // ---- Bridge App Example Config ---- -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#define APP_USE_EXAMPLE_START_BUTTON 1 +#define APP_USE_THREAD_START_BUTTON 1 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 0 +#define APP_USE_IDENTIFY_PWM 1 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 - -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 - -// Lighting LED config -#define USE_RGB_PWM 0 +#include "AppConfigCommon.h" #define LIGHTING_PWM_SPEC_RGB_BLUE PWM_DT_SPEC_GET(DT_ALIAS(pwm_led0)) -#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) diff --git a/examples/bridge-app/telink/include/AppTask.h b/examples/bridge-app/telink/include/AppTask.h index 35e9977ebfa0ac..6b8a60df890dbf 100644 --- a/examples/bridge-app/telink/include/AppTask.h +++ b/examples/bridge-app/telink/include/AppTask.h @@ -18,77 +18,30 @@ #pragma once -#include "AppConfig.h" -#include "AppEvent.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif +#include "AppTaskCommon.h" #include "PWMDevice.h" -#include -#if CONFIG_CHIP_FACTORY_DATA -#include -#endif - -#include - -struct k_timer; -struct Identify; - -class AppTask +class AppTask : public AppTaskCommon { public: - CHIP_ERROR StartApp(void); - - void PostEvent(AppEvent * aEvent); void UpdateClusterState(void); + static void InitServer(intptr_t context); PWMDevice & GetPWMDevice(void) { return mPwmRgbBlueLed; } - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); - private: friend AppTask & GetAppTask(void); + friend class AppTaskCommon; + CHIP_ERROR Init(void); static void ActionInitiated(PWMDevice::Action_t aAction, int32_t aActor); static void ActionCompleted(PWMDevice::Action_t aAction, int32_t aActor); - static void ActionIdentifyStateUpdateHandler(k_timer * timer); - - void DispatchEvent(AppEvent * event); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - static void LightingActionButtonEventHandler(void); - 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 LightingActionEventHandler(AppEvent * aEvent); - static void StartBleAdvHandler(AppEvent * aEvent); - static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); - - static void InitButtons(void); - static void InitServer(intptr_t context); - - static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); - static AppTask sAppTask; PWMDevice mPwmRgbBlueLed; - PWMDevice mPwmIdentifyLed; -#if CONFIG_CHIP_FACTORY_DATA - chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; -#endif + static AppTask sAppTask; }; inline AppTask & GetAppTask(void) diff --git a/examples/bridge-app/telink/prj.conf b/examples/bridge-app/telink/prj.conf index 2d69564ad49b85..777ae516050bee 100644 --- a/examples/bridge-app/telink/prj.conf +++ b/examples/bridge-app/telink/prj.conf @@ -26,9 +26,7 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=n -CONFIG_OPENTHREAD_FTD=y CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings @@ -64,15 +62,8 @@ CONFIG_CHIP_FACTORY_DATA_BUILD=n CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management CONFIG_PM=n -CONFIG_PM_DEVICE=n # Custom RF power values CONFIG_B91_BLE_CTRL_RF_POWER_P9P11DBM=y diff --git a/examples/bridge-app/telink/src/AppTask.cpp b/examples/bridge-app/telink/src/AppTask.cpp index 8a9bcd127c7079..8f6bf092a61649 100644 --- a/examples/bridge-app/telink/src/AppTask.cpp +++ b/examples/bridge-app/telink/src/AppTask.cpp @@ -17,123 +17,16 @@ */ #include "AppTask.h" - -#include "AppConfig.h" -#include "AppEvent.h" -#include "ButtonManager.h" #include "Device.h" -#include -#include -#include -#include -#include - -#include "ThreadUtil.h" -#include #include -#include -#include -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include - -#include - -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL +#include +#include LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; - namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kLightEndpointId = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; -constexpr uint32_t kIdentifyBlinkRateMs = 200; -constexpr uint32_t kIdentifyOkayOnRateMs = 50; -constexpr uint32_t kIdentifyOkayOffRateMs = 950; -constexpr uint32_t kIdentifyFinishOnRateMs = 950; -constexpr uint32_t kIdentifyFinishOffRateMs = 50; -constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; -constexpr uint32_t kIdentifyBreatheRateMs = 1000; - const struct pwm_dt_spec sPwmRgbSpecBlueLed = LIGHTING_PWM_SPEC_RGB_BLUE; - -const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; - -#if CONFIG_CHIP_FACTORY_DATA -// NOTE! This key is for test/certification only and should not be available in production devices! -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; -#endif - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; -#endif - -Button sFactoryResetButton; -Button sLightingButton; -Button sThreadStartButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - -void OnIdentifyTriggerEffect(Identify * identify) -{ - AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); -} - -Identify sIdentify = { - kLightEndpointId, - [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStart"); }, - [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStop"); }, - EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, - OnIdentifyTriggerEffect, -}; - } // namespace AppTask AppTask::sAppTask; @@ -496,53 +389,17 @@ bool emberAfActionsClusterInstantActionCallback(app::CommandHandler * commandObj return true; } -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(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); - - // Initialize LEDs -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); -#endif - - 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(kLightEndpointId, &minLightLevel); + Clusters::LevelControl::Attributes::MinLevel::Get(kExampleEndpointId, &minLightLevel); uint8_t maxLightLevel = kDefaultMaxLevel; - Clusters::LevelControl::Attributes::MaxLevel::Get(kLightEndpointId, &maxLightLevel); + Clusters::LevelControl::Attributes::MaxLevel::Get(kExampleEndpointId, &maxLightLevel); - // Initialize PWM LEDs - CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("Green IDENTIFY PWM Device Init fail"); - return err; - } - - err = sAppTask.mPwmRgbBlueLed.Init(&sPwmRgbSpecBlueLed, minLightLevel, maxLightLevel, maxLightLevel); + // Initialize PWM LED + CHIP_ERROR err = sAppTask.mPwmRgbBlueLed.Init(&sPwmRgbSpecBlueLed, minLightLevel, maxLightLevel, maxLightLevel); if (err != CHIP_NO_ERROR) { LOG_ERR("Blue RGB PWM Device Init fail"); @@ -550,44 +407,11 @@ CHIP_ERROR AppTask::Init(void) } sAppTask.mPwmRgbBlueLed.SetCallbacks(ActionInitiated, ActionCompleted, nullptr); - sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); - - // 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; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - ReturnErrorOnFailure(chip::Server::GetInstance().Init(initParams)); - - gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); - chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); -#if CONFIG_CHIP_OTA_REQUESTOR - InitBasicOTARequestor(); +#if APP_USE_EXAMPLE_START_BUTTON + SetExampleButtonCallbacks(LightingActionEventHandler); #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); + InitCommonParts(); err = ConnectivityMgr().SetBLEDeviceName("TelinkLight"); if (err != CHIP_NO_ERROR) @@ -596,13 +420,6 @@ CHIP_ERROR AppTask::Init(void) return err; } - err = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("AppFabricTableDelegate fail"); - return err; - } - memset(gDevices, 0, sizeof(gDevices)); gLight1.SetReachable(true); @@ -623,28 +440,8 @@ CHIP_ERROR AppTask::Init(void) return CHIP_NO_ERROR; } -CHIP_ERROR AppTask::StartApp(void) +void AppTask::InitServer(intptr_t context) { - CHIP_ERROR err = Init(); - - if (err != CHIP_NO_ERROR) - { - LOG_ERR("AppTask Init fail"); - return err; - } - - AppEvent event = {}; - - while (true) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&event); - } -} - -static void AppTask::InitServer(intptr_t context) -{ - // Set starting endpoint id where dynamic endpoints will be assigned, which // will be the next consecutive endpoint id after the last fixed endpoint. gFirstDynamicEndpointId = static_cast( @@ -735,16 +532,6 @@ EmberAfStatus HandleReadTempMeasurementAttribute(DeviceTempSensor * dev, chip::A return EMBER_ZCL_STATUS_SUCCESS; } -void AppTask::LightingActionButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = LightingActionEventHandler; - sAppTask.PostEvent(&event); -} - void AppTask::LightingActionEventHandler(AppEvent * aEvent) { PWMDevice::Action_t action = PWMDevice::INVALID_ACTION; @@ -767,226 +554,6 @@ void AppTask::LightingActionEventHandler(AppEvent * aEvent) } } -void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) -{ - AppEvent event; - event.Type = AppEvent::kEventType_IdentifyStart; - - switch (aEffect) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); - event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; - event.Type = AppEvent::kEventType_IdentifyStop; - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - return; - } - - 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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -void AppTask::StartThreadButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartThreadHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartThreadHandler(AppEvent * aEvent) -{ - LOG_INF("StartThreadHandler"); - if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) - { - // Switch context from BLE to Thread - Internal::BLEManagerImpl sInstance; - sInstance.SwitchToIeee802154(); - StartDefaultThreadNetwork(); - } - else - { - LOG_INF("Device already commissioned"); - } -} - -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadConnectivityChange: -#if CONFIG_CHIP_OTA_REQUESTOR - if (event->ThreadConnectivityChange.Result == kConnectivity_Established) - { - InitBasicOTARequestor(); - } -#endif - break; - default: - break; - } -} - -void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_UpdateLedState; - event.Handler = UpdateIdentifyStateEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) -{ - sAppTask.mPwmIdentifyLed.UpdateAction(); -} - void AppTask::ActionInitiated(PWMDevice::Action_t aAction, int32_t aActor) { if (aAction == PWMDevice::ON_ACTION) @@ -1024,85 +591,21 @@ void AppTask::ActionCompleted(PWMDevice::Action_t aAction, int32_t aActor) } } -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) { bool isTurnedOn = sAppTask.mPwmRgbBlueLed.IsTurnedOn(); // write the new on/off value - EmberAfStatus status = Clusters::OnOff::Attributes::OnOff::Set(kLightEndpointId, isTurnedOn); + EmberAfStatus status = Clusters::OnOff::Attributes::OnOff::Set(kExampleEndpointId, isTurnedOn); if (status != EMBER_ZCL_STATUS_SUCCESS) { LOG_ERR("Update OnOff fail: %x", status); } uint8_t setLevel = sAppTask.mPwmRgbBlueLed.GetLevel(); - status = Clusters::LevelControl::Attributes::CurrentLevel::Set(kLightEndpointId, setLevel); + status = Clusters::LevelControl::Attributes::CurrentLevel::Set(kExampleEndpointId, setLevel); if (status != EMBER_ZCL_STATUS_SUCCESS) { LOG_ERR("Update CurrentLevel fail: %x", status); } } - -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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sLightingButton.Configure(BUTTON_PORT, BUTTON_PIN_2, LightingActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - 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); -#endif - - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sLightingButton); - ButtonManagerInst().AddButton(sThreadStartButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} diff --git a/examples/chef/chef.py b/examples/chef/chef.py index e69d3418fa021d..930309f8ddc07a 100755 --- a/examples/chef/chef.py +++ b/examples/chef/chef.py @@ -615,10 +615,11 @@ def main() -> int: f"\"{truncated_sw_ver_string}\" due to 64 bytes limitation") sw_ver_string = truncated_sw_ver_string - flush_print("Building...") - + flush_print(f"Software Version String: \"{sw_ver_string}\"") flush_print( f"Product ID 0x{options.pid:02X} / Vendor ID 0x{options.vid:02X}") + flush_print("Building...") + shell.run_cmd(f"cd {_CHEF_SCRIPT_PATH}") if (options.build_target == "esp32") or (options.build_target == "nrfconnect") or (options.build_target == "ameba"): diff --git a/examples/chef/efr32/src/main.cpp b/examples/chef/efr32/src/main.cpp index 291337b24c8330..f1aa92f95935d8 100644 --- a/examples/chef/efr32/src/main.cpp +++ b/examples/chef/efr32/src/main.cpp @@ -50,7 +50,7 @@ static chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; int main(void) { init_efrPlatform(); - if (EFR32MatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) + if (SilabsMatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) appError(CHIP_ERROR_INTERNAL); gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); diff --git a/examples/chef/esp32/CMakeLists.txt b/examples/chef/esp32/CMakeLists.txt index f4ea7c13eefede..950e07c59e9d90 100644 --- a/examples/chef/esp32/CMakeLists.txt +++ b/examples/chef/esp32/CMakeLists.txt @@ -46,8 +46,10 @@ idf_build_set_property(COMPILE_OPTIONS "-DCHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID=$ if(NOT ${CONFIG_DEVICE_PRODUCT_NAME} STREQUAL "") idf_build_set_property(COMPILE_OPTIONS "-DCHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME=\"${CONFIG_DEVICE_PRODUCT_NAME}\"" APPEND) endif() +# Forwarding the customized software version string to the ESP32 firmware image if(NOT ${CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING} STREQUAL "") idf_build_set_property(COMPILE_OPTIONS "-DCHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING=\"${CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING}\"" APPEND) + set(PROJECT_VER ${CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING}) endif() idf_build_set_property(COMPILE_OPTIONS "-DCHIP_PLATFORM_ESP32=1" APPEND) diff --git a/examples/chip-tool/commands/common/DeviceScanner.cpp b/examples/chip-tool/commands/common/DeviceScanner.cpp index af3accbbc03b4e..f5c1e39fda7d9d 100644 --- a/examples/chip-tool/commands/common/DeviceScanner.cpp +++ b/examples/chip-tool/commands/common/DeviceScanner.cpp @@ -72,7 +72,7 @@ void DeviceScanner::OnNodeDiscovered(const DiscoveredNodeData & nodeData) } #if CHIP_TOOL_DEVICE_SCANNER_USE_BLE -void DeviceScanner::OnBleScanResult(BLE_CONNECTION_OBJECT connObj, const ChipBLEDeviceIdentificationInfo & info) +void DeviceScanner::OnBleScanAdd(BLE_CONNECTION_OBJECT connObj, const ChipBLEDeviceIdentificationInfo & info) { auto discriminator = info.GetDeviceDiscriminator(); auto vendorId = static_cast(info.GetVendorId()); @@ -85,6 +85,8 @@ void DeviceScanner::OnBleScanResult(BLE_CONNECTION_OBJECT connObj, const ChipBLE DeviceScannerResult result = { params, vendorId, productId, discriminator }; mDiscoveredResults.push_back(result); } + +void DeviceScanner::OnBleScanRemove(BLE_CONNECTION_OBJECT connObj) {} #endif // CHIP_TOOL_DEVICE_SCANNER_USE_BLE CHIP_ERROR DeviceScanner::Get(uint16_t index, RendezvousParameters & params) diff --git a/examples/chip-tool/commands/common/DeviceScanner.h b/examples/chip-tool/commands/common/DeviceScanner.h index 62479a36edba0f..57dd6affc8ef46 100644 --- a/examples/chip-tool/commands/common/DeviceScanner.h +++ b/examples/chip-tool/commands/common/DeviceScanner.h @@ -59,7 +59,8 @@ class DeviceScanner : public chip::Dnssd::CommissioningResolveDelegate #if CHIP_TOOL_DEVICE_SCANNER_USE_BLE /////////// BleScannerDelegate Interface ///////// - void OnBleScanResult(BLE_CONNECTION_OBJECT connObj, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) override; + void OnBleScanAdd(BLE_CONNECTION_OBJECT connObj, const chip::Ble::ChipBLEDeviceIdentificationInfo & info) override; + void OnBleScanRemove(BLE_CONNECTION_OBJECT connObj) override; #endif // CHIP_TOOL_DEVICE_SCANNER_USE_BLE private: diff --git a/examples/common/pigweed/telink/PigweedLoggerMutex.h b/examples/common/pigweed/telink/PigweedLoggerMutex.h index 9a9b7e57d5dfea..1f00287a1581d9 100644 --- a/examples/common/pigweed/telink/PigweedLoggerMutex.h +++ b/examples/common/pigweed/telink/PigweedLoggerMutex.h @@ -20,7 +20,7 @@ #include "PigweedLogger.h" #include "pigweed/RpcService.h" -#include +#include namespace chip { namespace rpc { diff --git a/examples/contact-sensor-app/telink/CMakeLists.txt b/examples/contact-sensor-app/telink/CMakeLists.txt index 8ac2147a9d058b..3f6a32566a3bba 100755 --- a/examples/contact-sensor-app/telink/CMakeLists.txt +++ b/examples/contact-sensor-app/telink/CMakeLists.txt @@ -59,6 +59,7 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/contact-sensor-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include) add_definitions( @@ -68,8 +69,9 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp src/ContactSensorManager.cpp - src/main.cpp src/ZclCallbacks.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/contact-sensor-app/telink/include/AppConfig.h b/examples/contact-sensor-app/telink/include/AppConfig.h old mode 100755 new mode 100644 index d32944992e2cfb..2ab155cd590a67 --- a/examples/contact-sensor-app/telink/include/AppConfig.h +++ b/examples/contact-sensor-app/telink/include/AppConfig.h @@ -18,18 +18,13 @@ #pragma once -// ---- Contact Sensor Example App Config ---- +// ---- All Clusters Application example config ---- +#define APP_USE_EXAMPLE_START_BUTTON 1 +#define APP_USE_THREAD_START_BUTTON 0 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 0 +#define APP_USE_IDENTIFY_PWM 1 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#include "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 - -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 #define CONTACT_STATE_LED 6 -#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) diff --git a/examples/contact-sensor-app/telink/include/AppEvent.h b/examples/contact-sensor-app/telink/include/AppEvent.h deleted file mode 100755 index 5306a8076d0804..00000000000000 --- a/examples/contact-sensor-app/telink/include/AppEvent.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -struct AppEvent; -typedef void (*EventHandler)(AppEvent *); - -class LEDWidget; - -struct AppEvent -{ - enum AppEventTypes - { - kEventType_Button = 0, - kEventType_Timer, - kEventType_UpdateLedState, - kEventType_IdentifyStart, - kEventType_IdentifyStop, - 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 index 8c022cd9a585ea..3ac0028c78e3bb 100644 --- a/examples/contact-sensor-app/telink/include/AppTask.h +++ b/examples/contact-sensor-app/telink/include/AppTask.h @@ -18,37 +18,15 @@ #pragma once -#include "AppEvent.h" +#include "AppTaskCommon.h" #include "ContactSensorManager.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.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; -struct Identify; - -class AppTask +class AppTask : public AppTaskCommon { public: - CHIP_ERROR StartApp(void); - - void PostEvent(AppEvent * event); - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); - void PostContactActionRequest(ContactSensorManager::Action aAction); void UpdateClusterState(void); void UpdateDeviceState(void); @@ -58,50 +36,20 @@ class AppTask private: friend AppTask & GetAppTask(void); + friend class AppTaskCommon; CHIP_ERROR Init(void); - static void ActionIdentifyStateUpdateHandler(k_timer * timer); - - void DispatchEvent(AppEvent * event); - static void OnStateChanged(ContactSensorManager::State aState); static void UpdateClusterStateInternal(intptr_t arg); static void UpdateDeviceStateInternal(intptr_t arg); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - 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 UpdateIdentifyStateEventHandler(AppEvent * aEvent); - - static void InitButtons(void); - - static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); bool mSyncClusterToButtonAction = false; static AppTask sAppTask; - PWMDevice mPwmIdentifyLed; - -#if CONFIG_CHIP_FACTORY_DATA - // chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; - chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; -#endif }; inline AppTask & GetAppTask(void) diff --git a/examples/contact-sensor-app/telink/include/ContactSensorManager.h b/examples/contact-sensor-app/telink/include/ContactSensorManager.h index 0f735288b6ee39..81bf56aefebe5a 100644 --- a/examples/contact-sensor-app/telink/include/ContactSensorManager.h +++ b/examples/contact-sensor-app/telink/include/ContactSensorManager.h @@ -21,7 +21,7 @@ #include #include -#include "AppEvent.h" +#include "AppEventCommon.h" class ContactSensorManager { diff --git a/examples/contact-sensor-app/telink/prj.conf b/examples/contact-sensor-app/telink/prj.conf index 7b643ece5322c4..63794047c764a2 100755 --- a/examples/contact-sensor-app/telink/prj.conf +++ b/examples/contact-sensor-app/telink/prj.conf @@ -26,10 +26,8 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=y -CONFIG_OPENTHREAD_FTD=n -CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 -CONFIG_CHIP_THREAD_SSED=n +CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=y +CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings CONFIG_OPENTHREAD_PANID=4660 @@ -63,13 +61,5 @@ CONFIG_CHIP_FACTORY_DATA=n CONFIG_CHIP_FACTORY_DATA_BUILD=n CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management -CONFIG_PM=n -CONFIG_PM_DEVICE=n -CONFIG_CHIP_ENABLE_PM_DURING_BLE=n +CONFIG_PM=y diff --git a/examples/contact-sensor-app/telink/src/AppTask.cpp b/examples/contact-sensor-app/telink/src/AppTask.cpp index 50c0b4c02b7c97..3486995097d668 100644 --- a/examples/contact-sensor-app/telink/src/AppTask.cpp +++ b/examples/contact-sensor-app/telink/src/AppTask.cpp @@ -18,198 +18,44 @@ #include "AppTask.h" -#include "AppConfig.h" -#include "AppEvent.h" -#include "ButtonManager.h" - -#include "ThreadUtil.h" - -#include #include -#include -#include -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif +#include #include -#include LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; - namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kEndpointId = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; -constexpr uint32_t kIdentifyBlinkRateMs = 200; -constexpr uint32_t kIdentifyOkayOnRateMs = 50; -constexpr uint32_t kIdentifyOkayOffRateMs = 950; -constexpr uint32_t kIdentifyFinishOnRateMs = 950; -constexpr uint32_t kIdentifyFinishOffRateMs = 50; -constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; -constexpr uint32_t kIdentifyBreatheRateMs = 1000; - -const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; - -#if CONFIG_CHIP_FACTORY_DATA -// NOTE! This key is for test/certification only and should not be available in production devices! -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; -#endif - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; - #if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; LEDWidget sContactSensorLED; #endif - -Button sFactoryResetButton; -Button sToggleContactStateButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - -void OnIdentifyTriggerEffect(Identify * identify) -{ - AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); -} - -Identify sIdentify = { - kEndpointId, - [](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(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); +#if APP_USE_EXAMPLE_START_BUTTON + SetExampleButtonCallbacks(ContactActionEventHandler); +#endif + InitCommonParts(); - // Initialize LEDs #if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); - sContactSensorLED.Init(CONTACT_STATE_LED); sContactSensorLED.Set(ContactSensorMgr().IsContactClosed()); #endif UpdateDeviceState(); - InitButtons(); - - // Initialize function button timer - k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); - k_timer_user_data_set(&sFactoryResetTimer, this); - - // Initialize PWM Identify led - CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("Green IDENTIFY PWM Device Init fail"); - return err; - } - - sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); - - // 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"); + CHIP_ERROR 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; } @@ -239,75 +85,6 @@ void AppTask::OnStateChanged(ContactSensorManager::State aState) } } -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) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&event); - } -} - -void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) -{ - AppEvent event; - event.Type = AppEvent::kEventType_IdentifyStart; - - switch (aEffect) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); - event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; - event.Type = AppEvent::kEventType_IdentifyStop; - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - return; - } - - sAppTask.PostEvent(&event); -} - void AppTask::PostContactActionRequest(ContactSensorManager::Action aAction) { AppEvent event; @@ -318,46 +95,6 @@ void AppTask::PostContactActionRequest(ContactSensorManager::Action aAction) 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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - void AppTask::UpdateClusterStateInternal(intptr_t arg) { uint8_t newValue = ContactSensorMgr().IsContactClosed(); @@ -408,187 +145,11 @@ void AppTask::ContactActionEventHandler(AppEvent * aEvent) } } -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadConnectivityChange: -#if CONFIG_CHIP_OTA_REQUESTOR - if (event->ThreadConnectivityChange.Result == kConnectivity_Established) - { - InitBasicOTARequestor(); - } -#endif - break; - default: - break; - } -} - -void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_UpdateLedState; - event.Handler = UpdateIdentifyStateEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) -{ - sAppTask.mPwmIdentifyLed.UpdateAction(); -} - -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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sToggleContactStateButton.Configure(BUTTON_PORT, BUTTON_PIN_2, ToggleContactStateButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sToggleContactStateButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_1, ToggleContactStateButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); -#endif - - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sToggleContactStateButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} - void AppTask::UpdateDeviceState(void) { PlatformMgr().ScheduleWork(UpdateDeviceStateInternal, 0); diff --git a/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp b/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp index c0a7612084d000..a5822df5f8515e 100644 --- a/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp +++ b/examples/contact-sensor-app/telink/src/ContactSensorManager.cpp @@ -24,8 +24,8 @@ #include #include +#include #include -#include LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); diff --git a/examples/contact-sensor-app/telink/src/main.cpp b/examples/contact-sensor-app/telink/src/main.cpp deleted file mode 100755 index 9dd145f55ba0c9..00000000000000 --- a/examples/contact-sensor-app/telink/src/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "AppTask.h" - -#include -#include - -#include - -LOG_MODULE_REGISTER(app, CONFIG_CHIP_APP_LOG_LEVEL); - -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/darwin-framework-tool/BUILD.gn b/examples/darwin-framework-tool/BUILD.gn index 231ebac679b240..67939fcb311f28 100644 --- a/examples/darwin-framework-tool/BUILD.gn +++ b/examples/darwin-framework-tool/BUILD.gn @@ -16,6 +16,7 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") import("${chip_root}/build/chip/tools.gni") +import("${chip_root}/build/config/compiler/compiler.gni") import("${chip_root}/build/config/mac/mac_sdk.gni") import("${chip_root}/examples//chip-tool/chip-tool.gni") @@ -31,6 +32,8 @@ declare_args() { # When config_enable_yaml_tests is false, the Matter SDK options are not available. if (!config_enable_yaml_tests) { chip_inet_config_enable_ipv4 = true + chip_config_network_layer_ble = true + is_clang = false } } @@ -73,10 +76,30 @@ action("build-darwin-framework") { ] } - if (defined(chip_inet_config_enable_ipv4) && !chip_inet_config_enable_ipv4) { + if (defined(chip_inet_config_enable_ipv4) && chip_inet_config_enable_ipv4) { + args += [ "--ipv4" ] + } else { args += [ "--no-ipv4" ] } + if (defined(is_asan) && is_asan) { + args += [ "--asan" ] + } else { + args += [ "--no-asan" ] + } + + if (defined(chip_config_network_layer_ble) && chip_config_network_layer_ble) { + args += [ "--ble" ] + } else { + args += [ "--no-ble" ] + } + + if (defined(is_clang) && is_clang) { + args += [ "--clang" ] + } else { + args += [ "--no-clang" ] + } + output_name = "Matter.framework" outputs = [ "${root_out_dir}/macos_framework_output/Build/Products/${output_sdk_type}/${output_name}", diff --git a/examples/darwin-framework-tool/templates/commands.zapt b/examples/darwin-framework-tool/templates/commands.zapt index 26a1457f8848cf..ae0c239dbf9e57 100644 --- a/examples/darwin-framework-tool/templates/commands.zapt +++ b/examples/darwin-framework-tool/templates/commands.zapt @@ -17,13 +17,13 @@ {{> clusters_header}} -{{#all_user_clusters side='client'}} -{{#unless (wasRemoved (asUpperCamelCase name preserveAcronyms=true))}} +{{#zcl_clusters}} +{{#if (isSupported (asUpperCamelCase name preserveAcronyms=true))}} {{> cluster_header}} {{#zcl_commands}} {{#if (is_str_equal source 'client')}} -{{#unless (wasRemoved (asUpperCamelCase parent.name preserveAcronyms=true) command=(asUpperCamelCase name preserveAcronyms=true))}} +{{#if (isSupported (asUpperCamelCase parent.name preserveAcronyms=true) command=(asUpperCamelCase name preserveAcronyms=true))}} /* * Command {{asUpperCamelCase name}} */ @@ -90,12 +90,12 @@ private: {{/zcl_command_arguments}} }; -{{/unless}} +{{/if}} {{/if}} {{/zcl_commands}} {{#zcl_attributes_server removeKeys='isOptional'}} -{{#unless (wasRemoved (asUpperCamelCase parent.name preserveAcronyms=true) attribute=(asUpperCamelCase name preserveAcronyms=true))}} +{{#if (isSupported (asUpperCamelCase parent.name preserveAcronyms=true) attribute=(asUpperCamelCase name preserveAcronyms=true))}} {{#*inline "cluster"}}Cluster{{asUpperCamelCase parent.name preserveAcronyms=true}}{{/inline}} {{#*inline "attribute"}}Attribute{{asUpperCamelCase name preserveAcronyms=true}}{{/inline}} @@ -247,16 +247,16 @@ public: }; {{/if}} -{{/unless}} +{{/if}} {{/zcl_attributes_server}} -{{/unless}} -{{/all_user_clusters}} +{{/if}} +{{/zcl_clusters}} /*----------------------------------------------------------------------------*\ | Register all Clusters commands | \*----------------------------------------------------------------------------*/ -{{#all_user_clusters side='client'}} -{{#unless (wasRemoved (asUpperCamelCase name preserveAcronyms=true))}} +{{#zcl_clusters}} +{{#if (isSupported (asUpperCamelCase name preserveAcronyms=true))}} void registerCluster{{asUpperCamelCase name}}(Commands & commands) { using namespace chip::app::Clusters::{{asUpperCamelCase name}}; @@ -267,34 +267,34 @@ void registerCluster{{asUpperCamelCase name}}(Commands & commands) make_unique(Id), // {{#zcl_commands}} {{#if (is_str_equal source 'client')}} - {{#unless (wasRemoved (asUpperCamelCase parent.name preserveAcronyms=true) command=(asUpperCamelCase name preserveAcronyms=true))}} + {{#if (isSupported (asUpperCamelCase parent.name preserveAcronyms=true) command=(asUpperCamelCase name preserveAcronyms=true))}} make_unique<{{asUpperCamelCase parent.name}}{{asUpperCamelCase name}}>(), // - {{/unless}} + {{/if}} {{/if}} {{/zcl_commands}} {{#zcl_attributes_server removeKeys='isOptional'}} {{#first}} make_unique(Id), // {{/first}} - {{#unless (wasRemoved (asUpperCamelCase parent.name preserveAcronyms=true) attribute=(asUpperCamelCase name preserveAcronyms=true))}} + {{#if (isSupported (asUpperCamelCase parent.name preserveAcronyms=true) attribute=(asUpperCamelCase name preserveAcronyms=true))}} make_unique(), // - {{/unless}} + {{/if}} {{#first}} make_unique(Id), // {{/first}} - {{#unless (wasRemoved (asUpperCamelCase parent.name preserveAcronyms=true) attribute=(asUpperCamelCase name preserveAcronyms=true))}} + {{#if (isSupported (asUpperCamelCase parent.name preserveAcronyms=true) attribute=(asUpperCamelCase name preserveAcronyms=true))}} {{#if isWritableAttribute}} make_unique(), // {{/if}} - {{/unless}} + {{/if}} {{#first}} make_unique(Id), // {{/first}} - {{#unless (wasRemoved (asUpperCamelCase parent.name preserveAcronyms=true) attribute=(asUpperCamelCase name preserveAcronyms=true))}} + {{#if (isSupported (asUpperCamelCase parent.name preserveAcronyms=true) attribute=(asUpperCamelCase name preserveAcronyms=true))}} {{#if isReportableAttribute}} make_unique(), // {{/if}} - {{/unless}} + {{/if}} {{/zcl_attributes_server}} {{#zcl_events}} {{#first}} @@ -306,8 +306,8 @@ void registerCluster{{asUpperCamelCase name}}(Commands & commands) commands.Register(clusterName, clusterCommands); } -{{/unless}} -{{/all_user_clusters}} +{{/if}} +{{/zcl_clusters}} void registerClusterAny(Commands & commands) { @@ -329,9 +329,9 @@ void registerClusterAny(Commands & commands) void registerClusters(Commands & commands) { registerClusterAny(commands); -{{#all_user_clusters side='client'}} - {{#unless (wasRemoved (asUpperCamelCase name preserveAcronyms=true))}} +{{#zcl_clusters}} + {{#if (isSupported (asUpperCamelCase name preserveAcronyms=true))}} registerCluster{{asUpperCamelCase name}}(commands); - {{/unless}} -{{/all_user_clusters}} + {{/if}} +{{/zcl_clusters}} } diff --git a/examples/dynamic-bridge-app/linux/BUILD.gn b/examples/dynamic-bridge-app/linux/BUILD.gn index 03e3cb4fcee25b..52fe054ecdd571 100644 --- a/examples/dynamic-bridge-app/linux/BUILD.gn +++ b/examples/dynamic-bridge-app/linux/BUILD.gn @@ -61,6 +61,7 @@ executable("dynamic-chip-bridge-app") { "${chip_root}/examples/platform/linux:app-main", "${chip_root}/src/app/tests/suites/credentials:dac_provider", "${chip_root}/src/lib", + "${chip_root}/src/lib/assign", ] include_dirs = [ @@ -116,7 +117,7 @@ executable("dynamic-chip-bridge-app") { output_dir = root_out_dir - configs += ["${chip_root}/src:includes"] + configs += [ "${chip_root}/src:includes" ] } group("linux") { diff --git a/examples/dynamic-bridge-app/linux/main.cpp b/examples/dynamic-bridge-app/linux/main.cpp index d67b7bf0be2edf..e91f8d4d4e95ee 100644 --- a/examples/dynamic-bridge-app/linux/main.cpp +++ b/examples/dynamic-bridge-app/linux/main.cpp @@ -184,12 +184,6 @@ chip::Optional LookupClusterByName(const char * name) return chip::Optional(); } -std::unique_ptr CreateCluster(const char * name) -{ - auto id = LookupClusterByName(name); - return id.HasValue() ? CreateCluster(id.Value()) : nullptr; -} - std::unique_ptr CreateCluster(chip::ClusterId id) { for (const auto & cluster : clusters::kKnownClusters) @@ -202,6 +196,12 @@ std::unique_ptr CreateCluster(chip::ClusterId id) return nullptr; } +std::unique_ptr CreateCluster(const char * name) +{ + auto id = LookupClusterByName(name); + return id.HasValue() ? CreateCluster(id.Value()) : nullptr; +} + CHIP_ERROR TLVWriteValue(chip::TLV::TLVWriter & wr, const Span & v) { return wr.PutString(chip::TLV::AnonymousTag(), v); diff --git a/examples/light-switch-app/infineon/cyw30739/.gn b/examples/light-switch-app/infineon/cyw30739/.gn new file mode 100644 index 00000000000000..90115e4209947e --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/.gn @@ -0,0 +1,28 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + target_os = "cyw30739" + + import("//args.gni") +} diff --git a/examples/light-switch-app/infineon/cyw30739/BUILD.gn b/examples/light-switch-app/infineon/cyw30739/BUILD.gn new file mode 100644 index 00000000000000..0a594386bc9206 --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("//build_overrides/cyw30739_sdk.gni") + +import("${cyw30739_sdk_build_root}/cyw30739_executable.gni") +import("${cyw30739_sdk_build_root}/cyw30739_sdk.gni") + +cyw30739_project_dir = + "${chip_root}/examples/light-switch-app/infineon/cyw30739" +examples_plat_dir = "${chip_root}/examples/platform/infineon/cyw30739" + +declare_args() { + setupPinCode = 20202021 + setupDiscriminator = 3840 +} + +cyw30739_sdk("sdk") { + sources = [ "${cyw30739_project_dir}/include/CHIPProjectConfig.h" ] + + include_dirs = [ + "${cyw30739_project_dir}/include", + "${examples_plat_dir}", + ] + + defines = [ + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + ] +} + +cyw30739_executable("light_switch_app") { + output_name = "chip-cyw30739-light-switch-example.elf" + + sources = [ + "src/AppShellCommands.cpp", + "src/BindingHandler.cpp", + "src/ButtonHandler.cpp", + "src/LightSwitch.cpp", + "src/LightingManager.cpp", + "src/ZclCallbacks.cpp", + "src/main.cpp", + ] + + deps = [ + ":sdk", + "${chip_root}/examples/light-switch-app/light-switch-common", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/examples/shell/shell_common:shell_common", + "${chip_root}/src/lib", + ] + + include_dirs = [ "include" ] + + if (chip_enable_ota_requestor) { + sources += [ + "${examples_plat_dir}/OTAConfig.cpp", + "${examples_plat_dir}/OTAConfig.h", + ] + } +} + +group("cyw30739") { + deps = [ ":light_switch_app" ] +} + +group("default") { + deps = [ ":cyw30739" ] +} diff --git a/examples/light-switch-app/infineon/cyw30739/README.md b/examples/light-switch-app/infineon/cyw30739/README.md new file mode 100644 index 00000000000000..fc45a42a42f9f4 --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/README.md @@ -0,0 +1,216 @@ +# Matter CYW30739 Light Switch Example + +An example showing the use of Matter on the Infineon CYW30739 platform. + +--- + +## Table of Contents + +- [Matter CYW30739 Light Switch Example](#matter-cyw30739-light-switch-example) + - [Table of Contents](#table-of-contents) + - [Introduction](#introduction) + - [Building](#building) + - [Building Options](#building-options) + - [DAC / DAC Key / PAI Certificate / Certificate Declaration](#dac--dac-key--pai-certificate--certificate-declaration) + - [Flashing the Application](#flashing-the-application) + - [Enter Recovery Mode](#enter-recovery-mode) + - [Run Flash Script](#run-flash-script) + - [Running the Complete Example](#running-the-complete-example) + +## Introduction + +The CYW30739 light switch example provides a baseline demonstration of a on-off +light switch device, built using Matter and the Infineon Modustoolbox SDK. It +can be controlled by a Matter controller over Openthread network. + +The CYW30739 device can be commissioned over Bluetooth Low Energy where the +device and the Matter controller will exchange security information with the +Rendez-vous procedure. Target Thread Network information including the active +dataset and CASE credentials are then provided. + +## Building + +- Build the example application: + + ```bash + $ cd ~/connectedhomeip + $ git submodule update --init + $ ./scripts/examples/gn_build_example.sh examples/light-switch-app/infineon/cyw30739 out/light-switch-app + ``` + +- To delete generated executable, libraries and object files use: + + ```bash + $ cd ~/connectedhomeip + $ rm -rf ./out/ + ``` + +- OR use GN/Ninja directly + + ```bash + $ cd ~/connectedhomeip/examples/light-switch-app/infineon/cyw30739 + $ git submodule update --init + $ source third_party/connectedhomeip/scripts/activate.sh + $ gn gen out/debug + $ ninja -C out/debug + ``` + +- To delete generated executable, libraries and object files use: + + ```bash + $ cd ~/connectedhomeip/examples/light-switch-app/infineon/cyw30739 + $ rm -rf out/ + ``` + +## Building Options + +### DAC / DAC Key / PAI Certificate / Certificate Declaration + +Infineon CYW30739 examples use test certifications, keys, and CD by default. For +a production build, manufacturers can provision certifications, keys, and CD by +the following arguments: + +- `matter_dac`, `matter_dac_key`, `matter_pai`, `matter_cd` + + ```bash + $ ./scripts/examples/gn_build_example.sh examples/light-switch-app/infineon/cyw30739 out/light-switch-app \ + 'matter_dac="/path/to/dac.der"' \ + 'matter_dac_key="/path/to/dac_key.der"' \ + 'matter_pai="/path/to/pai.der"' \ + 'matter_cd="/path/to/cd.der"' + ``` + +## Flashing the Application + +### Enter Recovery Mode + +Put the CYW30739 in to the recovery mode before running the flash script. + +1. Press and hold the `RECOVERY` button on the board. +2. Press and hold the `RESET` button on the board. +3. Release the `RESET` button. +4. After one second, release the `RECOVERY` button. + +### Run Flash Script + +- On the command line: + + ```bash + $ cd ~/connectedhomeip/examples/light-switch-app/infineon/cyw30739 + $ python3 out/debug/chip-cyw30739-light-switch-example.flash.py + ``` + +## Running the Complete Example + +- It is assumed here that you already have an OpenThread border router + configured and running. If not see the following guide + [Openthread_border_router](https://github.com/project-chip/connectedhomeip/blob/master/docs/guides/openthread_border_router_pi.md) + for more information on how to setup a border router on a raspberryPi. + +- For this example to work, it is necessary to have a second CYW30739 device + running the lighting app example commissioned on the same OpenThread network + +- If the CYW30739 device is running the light switch example, then + + **Push USER Button** - Sends a Toggle command to bound light app. + + **LED1** - Indicates the current button state. + + **_OnOff Cluster_** - As following commands are app shell commands. + + - 'switch local on' : Lights On LED1 of light-switch device + - 'switch local off' : Lights Off LED1 of light-switch device + - 'switch local toggle' : Makes Toggle LED1 of light-switch device + + - 'switch onoff on' : Sends unicast On command to bound device + - 'switch onoff off' : Sends unicast Off command to bound device + - 'switch onoff toggle' : Sends unicast Toggle command to bound device + + - 'switch groups onoff on' : Sends On group command to bound group + - 'switch groups onoff off' : Sends On group command to bound group + - 'switch groups onoff toggle' : Sends On group command to bound group + +- Here is an example with the CHIPTool for unicast commands only: + + ```bash + chip-tool pairing ble-thread 1 hex: 20202021 3840 + + chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [], "targets": null}, {"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": [], "targets": [{"cluster": 6, "endpoint": 1, "deviceType": null}]}]' 0 + + chip-tool binding write binding '[{"fabricIndex": 1, "node": , "endpoint": 1, "cluster": 6}]' 1 + ``` + + Example: After pairing successfully [lighting-node-id : 1, + light-switch-node-id : 2] + + ```bash + chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null}, {"fabricIndex": 1, + "privilege": 3, "authMode": 2, "subjects": [2], "targets": [{"cluster": 6, "endpoint": 1, "deviceType": null}]}]' 1 0 + + chip-tool binding write binding '[{"fabricIndex": 1, "node": 1, "endpoint": 1, "cluster": 6}]' 2 1 + ``` + +- Here is an example with the CHIPTool for groups commands only: + + Pairing the device + + ```bash + chip-tool pairing ble-thread 1 hex: 20202021 3840 + ``` + + You can use a series of commands after pairing successfully. Here is a + lighting device (node 1) and a light-switch device (node 2) for connection + demonstration. + + ```bash + chip-tool groupkeymanagement key-set-write '{"groupKeySetID": 417, "groupKeySecurityPolicy": 0, "epochKey0":"a0a1a2a3a4a5a6a7a8a9aaabacadaeaf", "epochStartTime0": 1110000,"epochKey1":"b0b1b2b3b4b5b6b7b8b9babbbcbdbebf", "epochStartTime1":1110001,"epochKey2":"c0c1c2c3c4c5c6c7c8c9cacbcccdcecf", "epochStartTime2": 1110002 }' 1 0 + + chip-tool groupkeymanagement write group-key-map '[{"groupId": 257, "groupKeySetID": 417, "fabricIndex": 1}]' 1 0 + + chip-tool groups add-group 257 demo 1 1 + + chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": null, "targets": null}, {"fabricIndex": 1, "privilege": 3, "authMode": 3, "subjects": [257], "targets": null}]' 1 0 + + chip-tool groupkeymanagement key-set-write '{"groupKeySetID": 417, "groupKeySecurityPolicy": 0, "epochKey0":"a0a1a2a3a4a5a6a7a8a9aaabacadaeaf", "epochStartTime0": 1110000,"epochKey1":"b0b1b2b3b4b5b6b7b8b9babbbcbdbebf", "epochStartTime1":1110001,"epochKey2":"c0c1c2c3c4c5c6c7c8c9cacbcccdcecf", "epochStartTime2": 1110002 }' 2 0 + + chip-tool groupkeymanagement write group-key-map '[{"groupId": 257, "groupKeySetID": 417, "fabricIndex": 1}]' 2 0 + + chip-tool groups add-group 257 demo 2 1 + + chip-tool binding write binding '[{"fabricIndex": 1, "group": 257}]' 2 1 + ``` + + Or you can use TestGroupDemoConfig after pairing successfully + + ```bash + chip-tool tests TestGroupDemoConfig --nodeId + + chip-tool tests TestGroupDemoConfig --nodeId + + chip-tool binding write binding '[{"fabricIndex": 1, "group": 257}]' 1 + ``` + + Example: After pairing successfully [lighting-node-id : 1, + light-switch-node-id : 2] + + ```bash + chip-tool tests TestGroupDemoConfig --nodeId 2 + + chip-tool tests TestGroupDemoConfig --nodeId 1 + + chip-tool binding write binding '[{"fabricIndex": 1, "group": 257}]' 2 1 + ``` + + To run the example with unicast and groups commands, run the group + configuration commands and replace the last one with binding this command + + ```bash + chip-tool binding write binding '[{"fabricIndex": 1, "group": 257},{"fabricIndex": 1, "node": , "endpoint": 1, "cluster":6} ]' 1 + ``` + + To acquire the chip-tool node id, read the acl table right after + commissioning + + ```bash + chip-tool accesscontrol read acl 0 + ``` diff --git a/examples/light-switch-app/infineon/cyw30739/args.gni b/examples/light-switch-app/infineon/cyw30739/args.gni new file mode 100644 index 00000000000000..0f3c578940d0ce --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/args.gni @@ -0,0 +1,29 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("${chip_root}/config/standalone/args.gni") +import("${chip_root}/src/platform/Infineon/CYW30739/args.gni") + +cyw30739_sdk_target = get_label_info(":sdk", "label_no_toolchain") + +chip_openthread_ftd = false +enable_sleepy_device = true + +chip_enable_ota_requestor = true + +chip_error_logging = false +chip_progress_logging = false +chip_detail_logging = false +chip_automation_logging = false diff --git a/examples/light-switch-app/infineon/cyw30739/build_overrides b/examples/light-switch-app/infineon/cyw30739/build_overrides new file mode 120000 index 00000000000000..ee19c065d619a2 --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/build_overrides @@ -0,0 +1 @@ +../../../build_overrides/ \ No newline at end of file diff --git a/examples/all-clusters-app/telink/include/AppEvent.h b/examples/light-switch-app/infineon/cyw30739/include/App.h similarity index 52% rename from examples/all-clusters-app/telink/include/AppEvent.h rename to examples/light-switch-app/infineon/cyw30739/include/App.h index b6e45d7d1526c8..2811595e99d143 100644 --- a/examples/all-clusters-app/telink/include/AppEvent.h +++ b/examples/light-switch-app/infineon/cyw30739/include/App.h @@ -15,44 +15,9 @@ * 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_IdentifyStart, - kEventType_IdentifyStop, - }; - - uint16_t Type; - - union - { - struct - { - uint8_t Action; - } ButtonEvent; - struct - { - void * Context; - } TimerEvent; - struct - { - LEDWidget * LedWidget; - } UpdateLedStateEvent; - }; +#include - EventHandler Handler; -}; +CHIP_ERROR StartBLEAdvertisingHandler(); +CHIP_ERROR StopBLEAdvertisingHandler(); diff --git a/examples/platform/silabs/SiWx917/OTAConfig.h b/examples/light-switch-app/infineon/cyw30739/include/AppShellCommands.h similarity index 60% rename from examples/platform/silabs/SiWx917/OTAConfig.h rename to examples/light-switch-app/infineon/cyw30739/include/AppShellCommands.h index cdd2163a10084e..a139b9fb293003 100644 --- a/examples/platform/silabs/SiWx917/OTAConfig.h +++ b/examples/light-switch-app/infineon/cyw30739/include/AppShellCommands.h @@ -18,17 +18,4 @@ #pragma once -#include -#include -#include -#include -#include - -class OTAConfig -{ -public: - OTAConfig(){}; - - static void Init(); - static constexpr uint32_t kInitOTARequestorDelaySec = 3; -}; +void RegisterAppShellCommands(); diff --git a/examples/light-switch-app/infineon/cyw30739/include/BindingHandler.h b/examples/light-switch-app/infineon/cyw30739/include/BindingHandler.h new file mode 100644 index 00000000000000..ef330c7da2c1ea --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/include/BindingHandler.h @@ -0,0 +1,64 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +class BindingHandler +{ +public: + struct BindingData + { + chip::AttributeId attributeId; + chip::EndpointId EndpointId = 1; + chip::CommandId CommandId; + chip::ClusterId ClusterId; + uint8_t Value; + bool IsGroup{ false }; + bool isReadAttribute = false; + }; + + void Init(); + void PrintBindingTable(); + bool IsGroupBound(); + + static void SwitchWorkerHandler(intptr_t); + static void BindingWorkerHandler(intptr_t); + static void OnInvokeCommandFailure(BindingData & aBindingData, CHIP_ERROR aError); + + static BindingHandler & GetInstance() + { + static BindingHandler sBindingHandler; + return sBindingHandler; + } + +private: + static void OnOffProcessCommand(chip::CommandId, const EmberBindingTableEntry &, chip::OperationalDeviceProxy *, void *); + static void LevelControlProcessCommand(chip::CommandId, const EmberBindingTableEntry &, chip::OperationalDeviceProxy *, void *); + static void LightSwitchChangedHandler(const EmberBindingTableEntry &, chip::OperationalDeviceProxy *, void *); + static void LightSwitchContextReleaseHandler(void * context); + static void InitInternal(intptr_t); + + bool mCaseSessionRecovered = false; +}; diff --git a/examples/all-clusters-minimal-app/telink/include/AppEvent.h b/examples/light-switch-app/infineon/cyw30739/include/ButtonHandler.h similarity index 55% rename from examples/all-clusters-minimal-app/telink/include/AppEvent.h rename to examples/light-switch-app/infineon/cyw30739/include/ButtonHandler.h index 54250995e06ca8..c6a5999f96f8d7 100644 --- a/examples/all-clusters-minimal-app/telink/include/AppEvent.h +++ b/examples/light-switch-app/infineon/cyw30739/include/ButtonHandler.h @@ -15,42 +15,14 @@ * 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; +#include -struct AppEvent +typedef enum { - enum AppEventTypes - { - kEventType_Button = 0, - kEventType_Timer, - kEventType_UpdateLedState, - }; - - uint16_t Type; - - union - { - struct - { - uint8_t Action; - } ButtonEvent; - struct - { - void * Context; - } TimerEvent; - struct - { - LEDWidget * LedWidget; - } UpdateLedStateEvent; - }; + ON_OFF_BUTTON, + APP_MAX_BUTTON, +} application_button_t; - EventHandler Handler; -}; +wiced_result_t app_button_init(void); diff --git a/examples/light-switch-app/infineon/cyw30739/include/CHIPProjectConfig.h b/examples/light-switch-app/infineon/cyw30739/include/CHIPProjectConfig.h new file mode 100644 index 00000000000000..522e40755f8bca --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/include/CHIPProjectConfig.h @@ -0,0 +1,66 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * 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 + +/*********************************************************************************** + * Device Identification Configuration + ***********************************************************************************/ +/* The VendorName attribute of the Basic cluster. */ +#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME "Infineon" + +/* The VendorID attribute of the Basic cluster. */ +#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID 0xFFF2 + +/* The ProductName attribute of the Basic cluster. */ +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME "CYW30739 Light-Switch App" + +/* The ProductID attribute of the Basic cluster. */ +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID 0x8002 + +/* The HardwareVersionString attribute of the Basic cluster. */ +#define CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING "30739" + +/* The HardwareVersion attribute of the Basic cluster. */ +#define CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION 30739 + +/* The SoftwareVersionString attribute of the Basic cluster. */ +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "TE7.5" + +/* The SoftwareVersion attribute of the Basic cluster. */ +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 0x0705 + +/* The SerialNumber attribute of the Basic cluster. */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +// -------------------- Test Configuration -------------------- +#define CHIP_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY 1 + +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 + +// ------------------------- Debug use ------------------------- +#define CHIP_DEVICE_CONFIG_ENABLE_LOCAL_LEDSTATUS_DEBUG 1 diff --git a/examples/light-switch-app/infineon/cyw30739/include/LightSwitch.h b/examples/light-switch-app/infineon/cyw30739/include/LightSwitch.h new file mode 100644 index 00000000000000..244c1bcb7b6452 --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/include/LightSwitch.h @@ -0,0 +1,58 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +class LightSwitch +{ +public: + enum class Action : uint8_t + { + Toggle, // Switch state on lighting-app device + On, // Turn on light on lighting-app device + Off // Turn off light on lighting-app device + }; + + enum class Status : uint8_t + { + Toggle = 0, + On, + Off, + Unknown + }; + + void Init(chip::EndpointId aLightDimmerSwitchEndpoint); + void InitiateActionSwitch(Action); + Status GetSwitchStatus(); + void DimmerChangeBrightness(uint16_t kValue); + + chip::EndpointId GetLightSwitchEndpointId() { return mLightSwitchEndpoint; } + + static LightSwitch & GetInstance() + { + static LightSwitch sLightSwitch; + return sLightSwitch; + } + +private: + Status mStatus = Status::Unknown; + chip::EndpointId mLightSwitchEndpoint; +}; diff --git a/examples/platform/silabs/SiWx917/matter_config.h b/examples/light-switch-app/infineon/cyw30739/include/LightingManager.h similarity index 52% rename from examples/platform/silabs/SiWx917/matter_config.h rename to examples/light-switch-app/infineon/cyw30739/include/LightingManager.h index 6b3bb622a075a2..21a3b3871b05d1 100644 --- a/examples/platform/silabs/SiWx917/matter_config.h +++ b/examples/light-switch-app/infineon/cyw30739/include/LightingManager.h @@ -1,7 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2022 Silabs. + * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,20 +15,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#pragma once -#include -#include -#include -#include +#include +#include -class SI917MatterConfig +class LightingManager { public: - static CHIP_ERROR InitMatter(const char * appName); + wiced_result_t Init(); + void Set(bool state, uint8_t pin); + void Blink(wiced_led_t led_pin, uint32_t on_period_ms, uint32_t off_period_ms); + bool IsLightOn(); private: - static CHIP_ERROR InitOpenThread(void); - static void InitWiFi(void); - static void ConnectivityEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); - static void InitOTARequestorHandler(chip::System::Layer * systemLayer, void * appState); + void DoSetLEDOnOff(bool state, uint8_t pin); + + friend LightingManager & LightMgr(void); + + bool usr_LED1_OnOffStatus; + + static LightingManager sLight; }; + +inline LightingManager & LightMgr(void) +{ + return LightingManager::sLight; +} diff --git a/examples/light-switch-app/infineon/cyw30739/src/AppShellCommands.cpp b/examples/light-switch-app/infineon/cyw30739/src/AppShellCommands.cpp new file mode 100644 index 00000000000000..477ce99fa44c0b --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/src/AppShellCommands.cpp @@ -0,0 +1,475 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace chip; +using namespace chip::app; +using namespace chip::Shell; + +using Shell::Engine; +using Shell::shell_command_t; +using Shell::streamer_get; +using Shell::streamer_printf; + +static Engine AppCmdSubCommands; +static Engine AppCmdLocalSubCommands; +static Engine AppCmdOnOffSubCommands; +static Engine AppCmdGroupsSubCommands; +static Engine AppCmdGroupsOnOffSubCommands; +static Engine AppCmdDebugSubCommands; +static Engine AppCmdIdentifySubCommands; +static Engine AppCmdIdentifyReadSubCommands; + +static CHIP_ERROR AppCmdHelpHandler(int argc, char ** argv) +{ + AppCmdSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +static CHIP_ERROR AppCmdCommandHandler(int argc, char ** argv) +{ + if (argc == 0) + { + return AppCmdHelpHandler(argc, argv); + } + + return AppCmdSubCommands.ExecCommand(argc, argv); +} + +namespace Local { + +static CHIP_ERROR OnOffHelpHandler(int argc, char ** argv) +{ + AppCmdLocalSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +static CHIP_ERROR AppCommandHandler(int argc, char ** argv) +{ + if (argc == 0) + { + return OnOffHelpHandler(argc, argv); + } + + return AppCmdLocalSubCommands.ExecCommand(argc, argv); +} + +CHIP_ERROR OnCommandHandler(int argc, char ** argv) +{ + streamer_printf(streamer_get(), "Turning the light on ...\n"); + LightMgr().Set(true, PLATFORM_LED_1); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR OffCommandHandler(int argc, char ** argv) +{ + streamer_printf(streamer_get(), "Turning the light off ...\n"); + LightMgr().Set(false, PLATFORM_LED_1); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR ToggleCommandHandler(int argc, char ** argv) +{ + streamer_printf(streamer_get(), "Toggling the light ...\n"); + if (LightMgr().IsLightOn()) + { + LightMgr().Set(false, PLATFORM_LED_1); + } + else + { + LightMgr().Set(true, PLATFORM_LED_1); + } + + return CHIP_NO_ERROR; +} + +} // namespace Local + +CHIP_ERROR AssignUnicastData(LightSwitch::Status mStatus) +{ + BindingHandler::BindingData * data = Platform::New(); + data->EndpointId = LightSwitch::GetInstance().GetLightSwitchEndpointId(); + switch (mStatus) + { + case LightSwitch::Status::Toggle: + data->CommandId = Clusters::OnOff::Commands::Toggle::Id; + break; + case LightSwitch::Status::On: + data->CommandId = Clusters::OnOff::Commands::On::Id; + break; + case LightSwitch::Status::Off: + data->CommandId = Clusters::OnOff::Commands::Off::Id; + break; + default: + data->CommandId = Clusters::OnOff::Commands::Off::Id; + printf("[unicast] default -> Clusters::OnOff::Commands::Off\n"); + break; + } + data->ClusterId = Clusters::OnOff::Id; + + DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::SwitchWorkerHandler, reinterpret_cast(data)); + return CHIP_NO_ERROR; +} + +namespace Unicast { + +static CHIP_ERROR OnOffHelpHandler(int argc, char ** argv) +{ + AppCmdOnOffSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +static CHIP_ERROR AppCommandHandler(int argc, char ** argv) +{ + if (argc == 0) + { + return OnOffHelpHandler(argc, argv); + } + + return AppCmdOnOffSubCommands.ExecCommand(argc, argv); +} + +CHIP_ERROR OnCommandHandler(int argc, char ** argv) +{ + return AssignUnicastData(LightSwitch::Status::On); +} + +CHIP_ERROR OffCommandHandler(int argc, char ** argv) +{ + return AssignUnicastData(LightSwitch::Status::Off); +} + +CHIP_ERROR ToggleCommandHandler(int argc, char ** argv) +{ + return AssignUnicastData(LightSwitch::Status::Toggle); +} + +} // namespace Unicast + +CHIP_ERROR AssignGroupData(LightSwitch::Status mStatus) +{ + BindingHandler::BindingData * data = Platform::New(); + data->EndpointId = LightSwitch::GetInstance().GetLightSwitchEndpointId(); + switch (mStatus) + { + case LightSwitch::Status::Toggle: + data->CommandId = Clusters::OnOff::Commands::Toggle::Id; + break; + case LightSwitch::Status::On: + data->CommandId = Clusters::OnOff::Commands::On::Id; + break; + case LightSwitch::Status::Off: + data->CommandId = Clusters::OnOff::Commands::Off::Id; + break; + default: + data->CommandId = Clusters::OnOff::Commands::Off::Id; + printf("[group] default -> Clusters::OnOff::Commands::Off\n"); + break; + } + data->ClusterId = Clusters::OnOff::Id; + data->IsGroup = true; + + DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::SwitchWorkerHandler, reinterpret_cast(data)); + return CHIP_NO_ERROR; +} + +namespace Group { + +static CHIP_ERROR AppSwitchHelpHandler(int argc, char ** argv) +{ + AppCmdGroupsSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +static CHIP_ERROR AppCommandHandler(int argc, char ** argv) +{ + if (argc == 0) + { + return AppSwitchHelpHandler(argc, argv); + } + + return AppCmdGroupsSubCommands.ExecCommand(argc, argv); +} + +static CHIP_ERROR OnOffHelpHandler(int argc, char ** argv) +{ + AppCmdGroupsOnOffSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +static CHIP_ERROR OnOffCommandHandler(int argc, char ** argv) +{ + if (argc == 0) + { + return OnOffHelpHandler(argc, argv); + } + + return AppCmdGroupsOnOffSubCommands.ExecCommand(argc, argv); +} + +CHIP_ERROR OnCommandHandler(int argc, char ** argv) +{ + return AssignGroupData(LightSwitch::Status::On); +} + +CHIP_ERROR OffCommandHandler(int argc, char ** argv) +{ + return AssignGroupData(LightSwitch::Status::Off); +} + +CHIP_ERROR ToggleCommandHandler(int argc, char ** argv) +{ + return AssignGroupData(LightSwitch::Status::Toggle); +} + +} // namespace Group + +namespace Identify { + +CHIP_ERROR IdentifyHelpHandler(int argc, char ** argv) +{ + AppCmdIdentifySubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +CHIP_ERROR AppCommandHandler(int argc, char ** argv) +{ + if (argc == 0) + { + return IdentifyHelpHandler(argc, argv); + } + + return AppCmdIdentifySubCommands.ExecCommand(argc, argv); +} + +CHIP_ERROR ReadHelpHandler(int argc, char ** argv) +{ + AppCmdIdentifyReadSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +CHIP_ERROR Read(int argc, char ** argv) +{ + if (argc == 0) + { + return ReadHelpHandler(argc, argv); + } + + return AppCmdIdentifyReadSubCommands.ExecCommand(argc, argv); +} + +CHIP_ERROR ReadAttributeList(int argc, char ** argv) +{ + BindingHandler::BindingData * data = Platform::New(); + data->attributeId = Clusters::Identify::Attributes::AttributeList::Id; + data->ClusterId = Clusters::Identify::Id; + data->isReadAttribute = true; + + DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::SwitchWorkerHandler, reinterpret_cast(data)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR ReadFeatureMap(int argc, char ** argv) +{ + BindingHandler::BindingData * data = Platform::New(); + data->attributeId = Clusters::Identify::Attributes::FeatureMap::Id; + data->ClusterId = Clusters::Identify::Id; + data->isReadAttribute = true; + + DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::SwitchWorkerHandler, reinterpret_cast(data)); + return CHIP_NO_ERROR; +} + +} // namespace Identify + +namespace Debug { + +static CHIP_ERROR DebugHelpHandler(int argc, char ** argv) +{ + AppCmdDebugSubCommands.ForEachCommand(Shell::PrintCommandHelp, nullptr); + return CHIP_NO_ERROR; +} + +static CHIP_ERROR AppCommandHandler(int argc, char ** argv) +{ + if (argc == 0) + { + return DebugHelpHandler(argc, argv); + } + + return AppCmdDebugSubCommands.ExecCommand(argc, argv); +} + +CHIP_ERROR StartBLEAdvertisingDebugCommandHandler(int argc, char * argv[]) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + if ((argc > 0) && (strcmp(argv[0], "start") == 0)) + { + printf("Start BLE advertising ...\n"); + err = StartBLEAdvertisingHandler(); + } + else if ((argc > 0) && (strcmp(argv[0], "stop") == 0)) + { + printf("Stop BLE advertising ...\n"); + err = StopBLEAdvertisingHandler(); + } + else + { + return CHIP_ERROR_INVALID_ARGUMENT; + } + + return err; +} + +static CHIP_ERROR TableDebugCommandHandler(int argc, char ** argv) +{ + BindingHandler::GetInstance().PrintBindingTable(); + return CHIP_NO_ERROR; +} + +/* + * Usage: switch debug bind_group [fabric index] [group id] [cluster id] + */ +CHIP_ERROR GroupBindCommandHandler(int argc, char ** argv) +{ + VerifyOrReturnError(argc == 3, CHIP_ERROR_INVALID_ARGUMENT); + + EmberBindingTableEntry * entry = Platform::New(); + entry->type = EMBER_MULTICAST_BINDING; + entry->local = 1; // Hardcoded to endpoint 1 for now + entry->fabricIndex = atoi(argv[0]); + entry->groupId = atoi(argv[1]); + entry->clusterId.SetValue(atoi(argv[3])); + + DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::BindingWorkerHandler, reinterpret_cast(entry)); + return CHIP_NO_ERROR; +} + +/* + * Usage: switch debug bind_unicast [fabric index] [node id] [endpoint] [cluster id] + */ +CHIP_ERROR UnicastBindCommandHandler(int argc, char ** argv) +{ + VerifyOrReturnError(argc == 4, CHIP_ERROR_INVALID_ARGUMENT); + + EmberBindingTableEntry * entry = Platform::New(); + entry->type = EMBER_UNICAST_BINDING; + entry->local = 1; // Hardcoded to endpoint 1 for now + entry->fabricIndex = atoi(argv[0]); + entry->nodeId = atoi(argv[1]); + entry->remote = atoi(argv[2]); + entry->clusterId.SetValue(atoi(argv[3])); + + DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::BindingWorkerHandler, reinterpret_cast(entry)); + return CHIP_NO_ERROR; +} + +/* + * Usage: switch debug brightness [brightness value] + */ +CHIP_ERROR ChangeBrightnessCommandHandler(int argc, char ** argv) +{ + LightSwitch::GetInstance().DimmerChangeBrightness(atoi(argv[0])); + return CHIP_NO_ERROR; +} + +} // namespace Debug + +void RegisterAppShellCommands() +{ + static const shell_command_t ifxAppCmdSubCommands[] = { + { &AppCmdHelpHandler, "help", "Switch commands" }, + { &Local::AppCommandHandler, "local", "Light-switch on/off local device." }, + { &Unicast::AppCommandHandler, "onoff", "Lightbulb on/off remote device by unicast." }, + { &Group::AppCommandHandler, "groups", "Lightbulb on/off remote device by group." }, + { &Debug::AppCommandHandler, "debug", "Extend the debug command." }, + { &Identify::AppCommandHandler, "identify", "identify read attribute" }, + }; + + static const shell_command_t ifxAppCmdLocalSubCommands[] = { { &Local::OnOffHelpHandler, "help", + "Usage: switch local [on|off|toggle]" }, + { &Local::OnCommandHandler, "on", "Make light on" }, + { &Local::OffCommandHandler, "off", "Make light off" }, + { &Local::ToggleCommandHandler, "toggle", "Toggle the light" } }; + + static const shell_command_t ifxAppCmdOnOffSubCommands[] = { + { &Unicast::OnOffHelpHandler, "help", "Usage: switch onoff [on|off|toggle]" }, + { &Unicast::OnCommandHandler, "on", "Sends on command to bound Lightbulb" }, + { &Unicast::OffCommandHandler, "off", "Sends off command to bound Lightbulb" }, + { &Unicast::ToggleCommandHandler, "toggle", "Sends toggle command to bound Lightbulb" }, + }; + + static const shell_command_t ifxAppCmdGroupsSubCommands[] = { + { &Group::AppSwitchHelpHandler, "help", "Switch a group of bounded Lightbulbs" }, + { &Group::OnOffCommandHandler, "onoff", "Usage: switch groups onoff [on|off|toggle]" }, + }; + + static const shell_command_t ifxAppCmdGroupsOnOffSubCommands[] = { + { &Group::OnOffHelpHandler, "help", "Usage: switch groups onoff [on|off|toggle]" }, + { &Group::OnCommandHandler, "on", "Sends on command to bound Group" }, + { &Group::OffCommandHandler, "off", "Sends off command to bound Group" }, + { &Group::ToggleCommandHandler, "toggle", "Sends toggle command to bound Group" }, + }; + + static const shell_command_t ifxAppCmdDebugSubCommands[] = { + { &Debug::DebugHelpHandler, "help", "Debug use commands " }, + { &Debug::StartBLEAdvertisingDebugCommandHandler, "bleadv", "Usage: switch debug bleadv [start|stop]" }, + { &Debug::TableDebugCommandHandler, "table", "Print a binding table. Usage: switch debug table" }, + { &Debug::GroupBindCommandHandler, "bind_group", "Usage: switch debug bind_group [fabric index] [group id] [cluster id]" }, + { &Debug::UnicastBindCommandHandler, "bind_unicast", + "Usage: switch debug bind_unicast [fabric index] [node id] [endpoint] [cluster id]" }, + { &Debug::ChangeBrightnessCommandHandler, "brightness", + "Change the brightness and range is 0-254. Usage: switch debug brightness [brightness value]" }, + }; + + static const shell_command_t ifxAppCmdIdentifySubCommands[] = { + { &Identify::Read, "read", "Usage: switch identify read " }, + }; + + static const shell_command_t ifxAppCmdIdentifyReadSubCommands[] = { + { &Identify::ReadHelpHandler, "help", "Usage: switch identify read " }, + { &Identify::ReadAttributeList, "attlist", "attribute list attribute" }, + { &Identify::ReadFeatureMap, "featureMap", "featureMap attribute" }, + }; + + static const shell_command_t AppLightSwitchCommand = { + &AppCmdCommandHandler, "switch", "Light switch commands. Usage: switch [local|onoff|groups|debug][identify]" + }; + + AppCmdSubCommands.RegisterCommands(ifxAppCmdSubCommands, ArraySize(ifxAppCmdSubCommands)); + AppCmdLocalSubCommands.RegisterCommands(ifxAppCmdLocalSubCommands, ArraySize(ifxAppCmdLocalSubCommands)); + AppCmdOnOffSubCommands.RegisterCommands(ifxAppCmdOnOffSubCommands, ArraySize(ifxAppCmdOnOffSubCommands)); + AppCmdGroupsSubCommands.RegisterCommands(ifxAppCmdGroupsSubCommands, ArraySize(ifxAppCmdGroupsSubCommands)); + AppCmdGroupsOnOffSubCommands.RegisterCommands(ifxAppCmdGroupsOnOffSubCommands, ArraySize(ifxAppCmdGroupsOnOffSubCommands)); + AppCmdDebugSubCommands.RegisterCommands(ifxAppCmdDebugSubCommands, ArraySize(ifxAppCmdDebugSubCommands)); + AppCmdIdentifySubCommands.RegisterCommands(ifxAppCmdIdentifySubCommands, ArraySize(ifxAppCmdIdentifySubCommands)); + AppCmdIdentifyReadSubCommands.RegisterCommands(ifxAppCmdIdentifyReadSubCommands, ArraySize(ifxAppCmdIdentifyReadSubCommands)); + + Engine::Root().RegisterCommands(&AppLightSwitchCommand, 1); +} diff --git a/examples/light-switch-app/infineon/cyw30739/src/BindingHandler.cpp b/examples/light-switch-app/infineon/cyw30739/src/BindingHandler.cpp new file mode 100644 index 00000000000000..bcf66efb2dd81a --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/src/BindingHandler.cpp @@ -0,0 +1,347 @@ +/* + * + * 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 "controller/ReadInteraction.h" +#include +#include +#include + +using namespace chip; +using namespace chip::app; + +void BindingHandler::Init() +{ + DeviceLayer::PlatformMgr().ScheduleWork(InitInternal); +} + +void BindingHandler::OnInvokeCommandFailure(BindingData & aBindingData, CHIP_ERROR aError) +{ + CHIP_ERROR error; + + if (aError == CHIP_ERROR_TIMEOUT && !BindingHandler::GetInstance().mCaseSessionRecovered) + { + printf("Response timeout for invoked command, trying to recover CASE session.\n"); + + // Set flag to not try recover session multiple times. + BindingHandler::GetInstance().mCaseSessionRecovered = true; + // Allocate new object to make sure its life time will be appropriate. + BindingHandler::BindingData * data = Platform::New(); + *data = aBindingData; + // Establish new CASE session and retrasmit command that was not applied. + error = chip::BindingManager::GetInstance().NotifyBoundClusterChanged(aBindingData.EndpointId, aBindingData.ClusterId, + static_cast(data)); + + if (CHIP_NO_ERROR != error) + { + printf("NotifyBoundClusterChanged failed due to: %" CHIP_ERROR_FORMAT, error.Format()); + return; + } + } + else + { + printf("Binding command was not applied! Reason: %" CHIP_ERROR_FORMAT, aError.Format()); + } +} + +void ProcessIdentifyUnicastBindingRead(BindingHandler::BindingData * data, const EmberBindingTableEntry & binding, + OperationalDeviceProxy * peer_device) +{ + auto onSuccess = [](const ConcreteDataAttributePath & attributePath, const auto & dataResponse) { + ChipLogProgress(NotSpecified, "Read Identify attribute succeeds"); + }; + + auto onFailure = [](const ConcreteDataAttributePath * attributePath, CHIP_ERROR error) { + ChipLogError(NotSpecified, "Read Identify attribute failed: %" CHIP_ERROR_FORMAT, error.Format()); + }; + + VerifyOrDie(peer_device != nullptr && peer_device->ConnectionReady()); + + switch (data->attributeId) + { + case Clusters::Identify::Attributes::AttributeList::Id: + Controller::ReadAttribute( + peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, onSuccess, onFailure); + break; + case Clusters::Identify::Attributes::FeatureMap::Id: + Controller::ReadAttribute( + peer_device->GetExchangeManager(), peer_device->GetSecureSession().Value(), binding.remote, onSuccess, onFailure); + break; + } +} + +void BindingHandler::OnOffProcessCommand(CommandId aCommandId, const EmberBindingTableEntry & aBinding, + OperationalDeviceProxy * aDevice, void * aContext) +{ + CHIP_ERROR ret = CHIP_NO_ERROR; + BindingData * data = reinterpret_cast(aContext); + + auto onSuccess = [](const ConcreteCommandPath & commandPath, const StatusIB & status, const auto & dataResponse) { + printf("Binding command applied successfully!\n"); + // If session was recovered and communication works, reset flag to the initial state. + if (BindingHandler::GetInstance().mCaseSessionRecovered) + BindingHandler::GetInstance().mCaseSessionRecovered = false; + }; + + auto onFailure = [dataRef = *data](CHIP_ERROR aError) mutable { BindingHandler::OnInvokeCommandFailure(dataRef, aError); }; + + if (aDevice) + { + // We are validating connection is ready once here instead of multiple times in each case statement below. + VerifyOrDie(aDevice->ConnectionReady()); + } + + switch (aCommandId) + { + case Clusters::OnOff::Commands::Toggle::Id: + Clusters::OnOff::Commands::Toggle::Type toggleCommand; + if (aDevice) + { + ret = Controller::InvokeCommandRequest(aDevice->GetExchangeManager(), aDevice->GetSecureSession().Value(), + aBinding.remote, toggleCommand, onSuccess, onFailure); + } + else + { + Messaging::ExchangeManager & exchangeMgr = Server::GetInstance().GetExchangeManager(); + ret = Controller::InvokeGroupCommandRequest(&exchangeMgr, aBinding.fabricIndex, aBinding.groupId, toggleCommand); + } + break; + + case Clusters::OnOff::Commands::On::Id: + Clusters::OnOff::Commands::On::Type onCommand; + if (aDevice) + { + ret = Controller::InvokeCommandRequest(aDevice->GetExchangeManager(), aDevice->GetSecureSession().Value(), + aBinding.remote, onCommand, onSuccess, onFailure); + } + else + { + Messaging::ExchangeManager & exchangeMgr = Server::GetInstance().GetExchangeManager(); + ret = Controller::InvokeGroupCommandRequest(&exchangeMgr, aBinding.fabricIndex, aBinding.groupId, onCommand); + } + break; + + case Clusters::OnOff::Commands::Off::Id: + Clusters::OnOff::Commands::Off::Type offCommand; + if (aDevice) + { + ret = Controller::InvokeCommandRequest(aDevice->GetExchangeManager(), aDevice->GetSecureSession().Value(), + aBinding.remote, offCommand, onSuccess, onFailure); + } + else + { + Messaging::ExchangeManager & exchangeMgr = Server::GetInstance().GetExchangeManager(); + ret = Controller::InvokeGroupCommandRequest(&exchangeMgr, aBinding.fabricIndex, aBinding.groupId, offCommand); + } + break; + default: + printf("Invalid binding command data - commandId is not supported\n"); + break; + } + if (CHIP_NO_ERROR != ret) + { + printf("Invoke OnOff Command Request ERROR: %s\n", ErrorStr(ret)); + } +} + +void BindingHandler::LevelControlProcessCommand(CommandId aCommandId, const EmberBindingTableEntry & aBinding, + OperationalDeviceProxy * aDevice, void * aContext) +{ + BindingData * data = reinterpret_cast(aContext); + + auto onSuccess = [](const ConcreteCommandPath & commandPath, const StatusIB & status, const auto & dataResponse) { + printf("Binding command applied successfully!\n"); + // If session was recovered and communication works, reset flag to the initial state. + if (BindingHandler::GetInstance().mCaseSessionRecovered) + BindingHandler::GetInstance().mCaseSessionRecovered = false; + }; + + auto onFailure = [dataRef = *data](CHIP_ERROR aError) mutable { BindingHandler::OnInvokeCommandFailure(dataRef, aError); }; + + CHIP_ERROR ret = CHIP_NO_ERROR; + + if (aDevice) + { + // We are validating connection is ready once here instead of multiple times in each case statement below. + VerifyOrDie(aDevice->ConnectionReady()); + } + + switch (aCommandId) + { + case Clusters::LevelControl::Commands::MoveToLevel::Id: { + Clusters::LevelControl::Commands::MoveToLevel::Type moveToLevelCommand; + moveToLevelCommand.level = data->Value; + if (aDevice) + { + ret = Controller::InvokeCommandRequest(aDevice->GetExchangeManager(), aDevice->GetSecureSession().Value(), + aBinding.remote, moveToLevelCommand, onSuccess, onFailure); + } + else + { + Messaging::ExchangeManager & exchangeMgr = Server::GetInstance().GetExchangeManager(); + ret = Controller::InvokeGroupCommandRequest(&exchangeMgr, aBinding.fabricIndex, aBinding.groupId, moveToLevelCommand); + } + } + break; + default: + printf("Invalid binding command data - commandId is not supported\n"); + break; + } + if (CHIP_NO_ERROR != ret) + { + printf("Invoke Group Command Request ERROR: %s\n", ErrorStr(ret)); + } +} + +void BindingHandler::LightSwitchChangedHandler(const EmberBindingTableEntry & binding, OperationalDeviceProxy * deviceProxy, + void * context) +{ + VerifyOrReturn(context != nullptr, printf("Invalid context for Light switch handler\n");); + BindingData * data = static_cast(context); + + if (binding.type == EMBER_MULTICAST_BINDING && data->IsGroup) + { + switch (data->ClusterId) + { + case Clusters::OnOff::Id: + OnOffProcessCommand(data->CommandId, binding, nullptr, context); + break; + case Clusters::LevelControl::Id: + LevelControlProcessCommand(data->CommandId, binding, nullptr, context); + break; + default: + ChipLogError(NotSpecified, "Invalid binding group command data"); + break; + } + } + else if (binding.type == EMBER_UNICAST_BINDING && !data->IsGroup) + { + switch (data->ClusterId) + { + case Clusters::OnOff::Id: + OnOffProcessCommand(data->CommandId, binding, deviceProxy, context); + break; + case Clusters::LevelControl::Id: + LevelControlProcessCommand(data->CommandId, binding, deviceProxy, context); + break; + case Clusters::Identify::Id: + ProcessIdentifyUnicastBindingRead(data, binding, deviceProxy); + break; + default: + ChipLogError(NotSpecified, "Invalid binding unicast command data"); + break; + } + } +} + +void BindingHandler::LightSwitchContextReleaseHandler(void * context) +{ + VerifyOrReturn(context != nullptr, printf("Invalid context for Light switch context release handler\n");); + + Platform::Delete(static_cast(context)); +} + +void BindingHandler::InitInternal(intptr_t aArg) +{ + CHIP_ERROR ret = CHIP_NO_ERROR; + auto & server = Server::GetInstance(); + + ret = BindingManager::GetInstance().Init( + { &server.GetFabricTable(), server.GetCASESessionManager(), &server.GetPersistentStorage() }); + if (CHIP_NO_ERROR != ret) + { + printf("BindingHandler::InitInternal() run fail, err_code: 0x%" CHIP_ERROR_FORMAT, ret.Format()); + printf("\n"); + } + else + { + BindingManager::GetInstance().RegisterBoundDeviceChangedHandler(LightSwitchChangedHandler); + BindingManager::GetInstance().RegisterBoundDeviceContextReleaseHandler(LightSwitchContextReleaseHandler); + BindingHandler::GetInstance().PrintBindingTable(); + } +} + +bool BindingHandler::IsGroupBound() +{ + BindingTable & bindingTable = BindingTable::GetInstance(); + + for (auto & entry : bindingTable) + { + if (EMBER_MULTICAST_BINDING == entry.type) + { + return true; + } + } + return false; +} + +void BindingHandler::PrintBindingTable() +{ + BindingTable & bindingTable = BindingTable::GetInstance(); + + printf("Binding Table size: [%d]:\n", bindingTable.Size()); + uint8_t i = 0; + for (auto & entry : bindingTable) + { + switch (entry.type) + { + case EMBER_UNICAST_BINDING: + printf("[%d] UNICAST:", i++); + printf("\t\t+ Fabric: %d\n \ + \t+ LocalEndpoint %d \n \ + \t+ ClusterId %d \n \ + \t+ RemoteEndpointId %d \n \ + \t+ NodeId %d \n", + (int) entry.fabricIndex, (int) entry.local, (int) entry.clusterId.Value(), (int) entry.remote, + (int) entry.nodeId); + break; + case EMBER_MULTICAST_BINDING: + printf("[%d] GROUP:", i++); + printf("\t\t+ Fabric: %d\n \ + \t+ LocalEndpoint %d \n \ + \t+ RemoteEndpointId %d \n \ + \t+ GroupId %d \n", + (int) entry.fabricIndex, (int) entry.local, (int) entry.remote, (int) entry.groupId); + break; + case EMBER_UNUSED_BINDING: + printf("[%d] UNUSED", i++); + break; + default: + break; + } + } +} + +void BindingHandler::SwitchWorkerHandler(intptr_t context) +{ + VerifyOrReturn(context != 0, printf("BindingHandler::Invalid switch work data\n")); + + BindingHandler::BindingData * data = reinterpret_cast(context); + printf("Notify Bounded Cluster | endpoint: %d cluster: %ld\n", data->EndpointId, data->ClusterId); + BindingManager::GetInstance().NotifyBoundClusterChanged(data->EndpointId, data->ClusterId, static_cast(data)); + + Platform::Delete(data); +} + +void BindingHandler::BindingWorkerHandler(intptr_t context) +{ + VerifyOrReturn(context != 0, ChipLogError(NotSpecified, "BindingHandler::Invalid binding work data\n")); + EmberBindingTableEntry * entry = reinterpret_cast(context); + AddBindingEntry(*entry); + + Platform::Delete(entry); +} diff --git a/examples/light-switch-app/infineon/cyw30739/src/ButtonHandler.cpp b/examples/light-switch-app/infineon/cyw30739/src/ButtonHandler.cpp new file mode 100644 index 00000000000000..5be809bf53e88e --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/src/ButtonHandler.cpp @@ -0,0 +1,79 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define APP_MAX_BUTTON_DEF 1 + +void app_button_event_handler(const button_manager_button_t * button_mgr, button_manager_event_t event, + button_manager_button_state_t state); + +using namespace chip::app::Clusters; + +static wiced_button_manager_configuration_t app_button_manager_configuration = { + .short_hold_duration = 500, /* msec */ + .medium_hold_duration = 700, + .long_hold_duration = 1500, + .very_long_hold_duration = 2500, + .debounce_duration = 150, /* typically a click takes around ~150-200 ms */ + .double_click_interval = 250, + .continuous_hold_detect = WICED_TRUE, + .event_handler = app_button_event_handler, +}; + +static wiced_button_configuration_t app_button_configurations[APP_MAX_BUTTON_DEF]; +static button_manager_button_t app_buttons[APP_MAX_BUTTON_DEF]; +static button_manager_t app_button_manager; + +wiced_result_t app_button_init(void) +{ + wiced_result_t result = WICED_ERROR; + + memset(app_button_configurations, 0, (sizeof(wiced_button_configuration_t) * APP_MAX_BUTTON_DEF)); + memset(app_buttons, 0, (sizeof(button_manager_button_t) * APP_MAX_BUTTON_DEF)); + + app_button_configurations[ON_OFF_BUTTON].button = PLATFORM_BUTTON_1; + app_button_configurations[ON_OFF_BUTTON].button_event_mask = BUTTON_CLICK_EVENT | BUTTON_HOLDING_EVENT; + app_buttons[ON_OFF_BUTTON].configuration = &app_button_configurations[ON_OFF_BUTTON]; + + result = wiced_button_manager_init(&app_button_manager, &app_button_manager_configuration, app_buttons, 1); + + if (result != WICED_SUCCESS) + { + printf("button_manager_init failed (%d)\n", result); + } + return result; +} + +void app_button_event_handler(const button_manager_button_t * button_mgr, button_manager_event_t event, + button_manager_button_state_t state) +{ + if (button_mgr[0].configuration->button == PLATFORM_BUTTON_1) + { + if (event == BUTTON_CLICK_EVENT && state == BUTTON_STATE_RELEASED) + { + LightSwitch::GetInstance().InitiateActionSwitch(LightSwitch::Action::Toggle); + } + } +} diff --git a/examples/light-switch-app/infineon/cyw30739/src/LightSwitch.cpp b/examples/light-switch-app/infineon/cyw30739/src/LightSwitch.cpp new file mode 100644 index 00000000000000..e3e178456e94f5 --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/src/LightSwitch.cpp @@ -0,0 +1,89 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include + +#define CHIP_DEVICE_CONFIG_BRIGHTNESS_MAXIMUM 254 + +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; + +void LightSwitch::Init(chip::EndpointId aLightDimmerSwitchEndpoint) +{ + BindingHandler::GetInstance().Init(); + mLightSwitchEndpoint = aLightDimmerSwitchEndpoint; +} + +void LightSwitch::InitiateActionSwitch(Action mAction) +{ + BindingHandler::BindingData * data = Platform::New(); + if (data) + { + data->EndpointId = mLightSwitchEndpoint; + data->ClusterId = Clusters::OnOff::Id; + switch (mAction) + { + case Action::Toggle: + data->CommandId = Clusters::OnOff::Commands::Toggle::Id; + mStatus = LightSwitch::Status::Toggle; + break; + case Action::On: + data->CommandId = Clusters::OnOff::Commands::On::Id; + mStatus = LightSwitch::Status::On; + break; + case Action::Off: + data->CommandId = Clusters::OnOff::Commands::Off::Id; + mStatus = LightSwitch::Status::Off; + break; + default: + Platform::Delete(data); + mStatus = LightSwitch::Status::Unknown; + return; + } + data->IsGroup = BindingHandler::GetInstance().IsGroupBound(); + DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::SwitchWorkerHandler, reinterpret_cast(data)); + } +} + +LightSwitch::Status LightSwitch::GetSwitchStatus() +{ + return mStatus; +} + +void LightSwitch::DimmerChangeBrightness(uint16_t kValue) +{ + static uint16_t sBrightness; + BindingHandler::BindingData * data = Platform::New(); + if (data) + { + data->EndpointId = mLightSwitchEndpoint; + data->CommandId = Clusters::LevelControl::Commands::MoveToLevel::Id; + data->ClusterId = Clusters::LevelControl::Id; + // add to brightness vluse to change brightness after call dimmer change. + sBrightness = kValue; + data->Value = + (uint8_t)(sBrightness > CHIP_DEVICE_CONFIG_BRIGHTNESS_MAXIMUM ? CHIP_DEVICE_CONFIG_BRIGHTNESS_MAXIMUM : sBrightness); + data->IsGroup = BindingHandler::GetInstance().IsGroupBound(); + DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::SwitchWorkerHandler, reinterpret_cast(data)); + } +} diff --git a/examples/light-switch-app/infineon/cyw30739/src/LightingManager.cpp b/examples/light-switch-app/infineon/cyw30739/src/LightingManager.cpp new file mode 100644 index 00000000000000..497efd24900daf --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/src/LightingManager.cpp @@ -0,0 +1,97 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +using namespace chip; + +LightingManager LightingManager::sLight; +bool usr_LED1_OnOffStatus = false; + +/* config LED 1 */ +static wiced_led_config_t chip_lighting_led_config_1 = { + .led = PLATFORM_LED_1, + .bright = 50, +}; +/* config LED 2 */ +static wiced_led_config_t chip_lighting_led_config_2 = { + .led = PLATFORM_LED_2, + .bright = 50, +}; + +wiced_result_t LightingManager::Init() +{ + wiced_result_t result; + result = wiced_led_manager_init(&chip_lighting_led_config_1); + if (result != WICED_SUCCESS) + printf("Init LED1 fail (%d)\n", result); + + result = wiced_led_manager_init(&chip_lighting_led_config_2); + if (result != WICED_SUCCESS) + printf("Init LED2 fail (%d)\n", result); + + return result; +} + +void LightingManager::Set(bool state, uint8_t pin) +{ + DoSetLEDOnOff(state, pin); +} + +void LightingManager::Blink(wiced_led_t led_pin, uint32_t on_period_ms, uint32_t off_period_ms) +{ + wiced_led_manager_blink_led(led_pin, on_period_ms, off_period_ms); +} + +bool LightingManager::IsLightOn(void) +{ + return usr_LED1_OnOffStatus; +} + +void LightingManager::DoSetLEDOnOff(bool state, uint8_t pin) +{ + if (pin == PLATFORM_LED_1) + { + usr_LED1_OnOffStatus = state; + if (state) + { + wiced_led_manager_enable_led(PLATFORM_LED_1); + } + else + { + wiced_led_manager_disable_led(PLATFORM_LED_1); + } + } + else if (pin == PLATFORM_LED_2) + { + if (state) + { + wiced_led_manager_enable_led(PLATFORM_LED_2); + } + else + { + wiced_led_manager_disable_led(PLATFORM_LED_2); + } + } + else + { + printf("Invalid pin number\n"); + } +} diff --git a/examples/light-switch-app/infineon/cyw30739/src/ZclCallbacks.cpp b/examples/light-switch-app/infineon/cyw30739/src/ZclCallbacks.cpp new file mode 100644 index 00000000000000..84ca0d61fb8895 --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/src/ZclCallbacks.cpp @@ -0,0 +1,67 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +using namespace chip; +using namespace chip::app::Clusters; +using namespace chip::DeviceLayer; + +void emberAfBasicInformationClusterInitCallback(EndpointId endpoint) +{ + uint16_t year; + uint8_t month; + uint8_t dayOfMonth; + char cString[16] = "00000000"; + + if (GetDeviceInstanceInfoProvider()->GetManufacturingDate(year, month, dayOfMonth) == CHIP_NO_ERROR) + { + snprintf(cString, sizeof(cString), "%04u%02u%02u", year, month, dayOfMonth); + } + BasicInformation::Attributes::ManufacturingDate::Set(endpoint, CharSpan(cString)); +} + +void MatterPostAttributeChangeCallback(const app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size, + uint8_t * value) +{ + switch (attributePath.mClusterId) + { + case Identify::Id: + if (attributePath.mAttributeId == Identify::Attributes::IdentifyTime::Id) + { + uint16_t identifyTime; + if (EMBER_ZCL_STATUS_SUCCESS == Identify::Attributes::IdentifyTime::Get(attributePath.mEndpointId, &identifyTime)) + { + ChipLogProgress(Zcl, "IdentifyTime %u", identifyTime); + return; + } + } + break; + case OnOffSwitchConfiguration::Id: + printf("OnOff Switch Configuration attribute ID: " ChipLogFormatMEI " Type: %u Value: %u, length %u\n", + ChipLogValueMEI(attributePath.mAttributeId), type, *value, size); + return; + default: + printf("Unhandled cluster ID: 0x%04lx\n", attributePath.mClusterId); + return; + } + + printf("ERROR clusterId: 0x%04lx, unknown attribute ID: 0x%04lx\n", attributePath.mClusterId, attributePath.mAttributeId); +} diff --git a/examples/light-switch-app/infineon/cyw30739/src/main.cpp b/examples/light-switch-app/infineon/cyw30739/src/main.cpp new file mode 100644 index 00000000000000..c828788574a40a --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/src/main.cpp @@ -0,0 +1,323 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include + +#include +#include +#include +#include +#include +#include +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; +using namespace ::chip::Shell; + +constexpr chip::EndpointId kLightDimmerSwitchEndpointId = 1; + +static chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; +static FactoryDataProvider sFactoryDataProvider; +static bool sIsThreadProvisioned = false; +static bool sIsThreadEnabled = false; +static bool sIsThreadBLEAdvertising = false; +static bool sHaveBLEConnections = false; + +static void InitApp(intptr_t args); +static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent *, intptr_t); + +// NOTE! This key is for test/certification only and should not be available in production devices! +uint8_t sTestEventTriggerEnableKey[chip::TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, + 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, + 0xcc, 0xdd, 0xee, 0xff }; + +/********************************************************** + * Identify Callbacks + *********************************************************/ + +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; +} + +static Identify gIdentify = { + chip::EndpointId{ 1 }, + [](Identify *) { ChipLogProgress(Zcl, "onIdentifyStart"); }, + [](Identify *) { ChipLogProgress(Zcl, "onIdentifyStop"); }, + EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_NONE, + OnIdentifyTriggerEffect, +}; + +APPLICATION_START() +{ + CHIP_ERROR err; + wiced_result_t result; + + printf("\nChip Light-Switch App starting\n"); + + mbedtls_platform_set_calloc_free(CHIPPlatformMemoryCalloc, CHIPPlatformMemoryFree); + + err = chip::Platform::MemoryInit(); + if (err != CHIP_NO_ERROR) + { + printf("ERROR MemoryInit %ld\n", err.AsInteger()); + } + + result = app_button_init(); + if (result != WICED_SUCCESS) + { + printf("ERROR app_button_init %d\n", result); + } + + /* Init. LED Manager. */ + LightMgr().Init(); + + printf("Initializing CHIP\n"); + err = PlatformMgr().InitChipStack(); + if (err != CHIP_NO_ERROR) + { + printf("ERROR InitChipStack %ld\n", err.AsInteger()); + } + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD + printf("Initializing OpenThread stack\n"); + err = ThreadStackMgr().InitThreadStack(); + if (err != CHIP_NO_ERROR) + { + printf("ERROR InitThreadStack %ld\n", err.AsInteger()); + } +#endif + +#if CHIP_DEVICE_CONFIG_THREAD_FTD + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); +#else // !CHIP_DEVICE_CONFIG_THREAD_FTD +#if CHIP_DEVICE_CONFIG_ENABLE_SED + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice); +#else /* !CHIP_DEVICE_CONFIG_ENABLE_SED */ + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice); +#endif /* CHIP_DEVICE_CONFIG_ENABLE_SED */ +#endif // CHIP_DEVICE_CONFIG_THREAD_FTD + if (err != CHIP_NO_ERROR) + { + printf("ERROR SetThreadDeviceType %ld\n", err.AsInteger()); + } + + PlatformMgr().AddEventHandler(ChipEventHandler, 0); + + printf("Starting event loop task\n"); + err = PlatformMgr().StartEventLoopTask(); + if (err != CHIP_NO_ERROR) + { + printf("ERROR StartEventLoopTask %ld\n", err.AsInteger()); + } + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD + printf("Starting thread task\n"); + err = ThreadStackMgr().StartThreadTask(); + if (err != CHIP_NO_ERROR) + { + printf("ERROR StartThreadTask %ld\n", err.AsInteger()); + } +#endif + + PlatformMgr().ScheduleWork(InitApp, 0); + + const int ret = Engine::Root().Init(); + if (!chip::ChipError::IsSuccess(ret)) + { + printf("ERROR Shell Init %d\n", ret); + } + RegisterAppShellCommands(); + Engine::Root().RunMainLoop(); + + assert(!wiced_rtos_check_for_stack_overflow()); +} + +void InitApp(intptr_t args) +{ + ConfigurationMgr().LogDeviceConfig(); + + // Print QR Code URL + PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); + /* Start CHIP datamodel server */ + static chip::OTATestEventTriggerDelegate testEventTriggerDelegate{ chip::ByteSpan(sTestEventTriggerEnableKey) }; + static chip::CommonCaseDeviceServerInitParams initParams; + (void) initParams.InitializeStaticResourcesBeforeServerInit(); + initParams.testEventTriggerDelegate = &testEventTriggerDelegate; + gExampleDeviceInfoProvider.SetStorageDelegate(initParams.persistentStorageDelegate); + chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); + chip::Inet::EndPointStateOpenThread::OpenThreadEndpointInitParam nativeParams; + nativeParams.lockCb = [] { ThreadStackMgr().LockThreadStack(); }; + nativeParams.unlockCb = [] { ThreadStackMgr().UnlockThreadStack(); }; + nativeParams.openThreadInstancePtr = chip::DeviceLayer::ThreadStackMgrImpl().OTInstance(); + initParams.endpointNativeParams = static_cast(&nativeParams); + chip::Server::GetInstance().Init(initParams); + + SetDeviceAttestationCredentialsProvider(&sFactoryDataProvider); + + LightSwitch::GetInstance().Init(kLightDimmerSwitchEndpointId); + +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + OTAConfig::Init(); +#endif +} + +void UpdateStatusLED() +{ + LightMgr().Set(false, PLATFORM_LED_2); + // Status LED indicates: + // - blinking 1 s - advertising, ready to commission + // - blinking 200 ms - commissioning in progress + // - constant lightning means commissioned with Thread network + if (sIsThreadBLEAdvertising && !sHaveBLEConnections) + { + LightMgr().Blink(PLATFORM_LED_2, 50, 950); + } + else if (sIsThreadProvisioned && sIsThreadEnabled) + { + LightMgr().Set(true, PLATFORM_LED_2); + } + else if (sHaveBLEConnections) + { + LightMgr().Blink(PLATFORM_LED_2, 50, 150); + } + else + { + /* back to default status */ + LightMgr().Set(false, PLATFORM_LED_2); + } +} + +void ChipEventHandler(const ChipDeviceEvent * aEvent, intptr_t arg) +{ +#if CHIP_DEVICE_CONFIG_ENABLE_LOCAL_LEDSTATUS_DEBUG + switch (aEvent->Type) + { + case DeviceEventType::kCHIPoBLEAdvertisingChange: + sIsThreadBLEAdvertising = true; + sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; + UpdateStatusLED(); + break; + case DeviceEventType::kThreadStateChange: + sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); + sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); + UpdateStatusLED(); + break; + case DeviceEventType::kThreadConnectivityChange: + if (aEvent->ThreadConnectivityChange.Result == kConnectivity_Established) + sHaveBLEConnections = true; + break; + default: + if ((ConnectivityMgr().NumBLEConnections() == 0) && (!sIsThreadProvisioned || !sIsThreadEnabled)) + { + printf("[Event] Commissioning with a Thread network has not been done. An error occurred\n"); + sIsThreadBLEAdvertising = false; + sHaveBLEConnections = false; + UpdateStatusLED(); + } + break; + } +#endif /* CHIP_DEVICE_CONFIG_ENABLE_LOCAL_LEDSTATUS_DEBUG */ +} + +CHIP_ERROR StartBLEAdvertisingHandler() +{ + CHIP_ERROR err = CHIP_NO_ERROR; + /// Don't allow on starting Matter service BLE advertising after Thread provisioning. + if (chip::Server::GetInstance().GetFabricTable().FabricCount() != 0) + { + printf("Matter service BLE advertising not started - device is already commissioned\n"); + return err; + } + + if (ConnectivityMgr().IsBLEAdvertisingEnabled()) + { + printf("BLE advertising is already enabled\n"); + return err; + } + else + { + printf("Start BLE advertising...\n"); + err = ConnectivityMgr().SetBLEAdvertisingEnabled(true); + if (err != CHIP_NO_ERROR) + { + printf("Enable BLE advertising failed\n"); + return err; + } + } + + printf("Enabling BLE advertising...\n"); + /* Check Commissioning Window*/ + if (chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() != CHIP_NO_ERROR) + { + printf("OpenBasicCommissioningWindow() failed\n"); + err = CHIP_ERROR_UNEXPECTED_EVENT; + } + + return err; +} + +CHIP_ERROR StopBLEAdvertisingHandler() +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + printf("Stop BLE advertising...\n"); + err = ConnectivityMgr().SetBLEAdvertisingEnabled(false); + if (err != CHIP_NO_ERROR) + { + printf("Disable BLE advertising failed\n"); + return err; + } + return err; +} diff --git a/examples/light-switch-app/infineon/cyw30739/third_party/connectedhomeip b/examples/light-switch-app/infineon/cyw30739/third_party/connectedhomeip new file mode 120000 index 00000000000000..3efed95be5dbe9 --- /dev/null +++ b/examples/light-switch-app/infineon/cyw30739/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../../ \ No newline at end of file diff --git a/examples/light-switch-app/nrfconnect/CMakeLists.txt b/examples/light-switch-app/nrfconnect/CMakeLists.txt index 9e0f317f948fab..7512e45ce45211 100644 --- a/examples/light-switch-app/nrfconnect/CMakeLists.txt +++ b/examples/light-switch-app/nrfconnect/CMakeLists.txt @@ -70,6 +70,10 @@ if(CONFIG_MCUMGR_SMP_BT) target_sources(app PRIVATE ${NRFCONNECT_COMMON}/util/DFUOverSMP.cpp) endif() +if(CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING) + target_sources(app PRIVATE ${NRFCONNECT_COMMON}/util/ICDUtil.cpp) +endif() + chip_configure_data_model(app INCLUDE_SERVER ZAP_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../light-switch-common/light-switch-app.zap diff --git a/examples/light-switch-app/nrfconnect/Kconfig b/examples/light-switch-app/nrfconnect/Kconfig index 52da3138003335..73f8d8cf318a65 100644 --- a/examples/light-switch-app/nrfconnect/Kconfig +++ b/examples/light-switch-app/nrfconnect/Kconfig @@ -47,6 +47,9 @@ config NRF_WIFI_LOW_POWER endif # CHIP_WIFI +config CHIP_ICD_SUBSCRIPTION_HANDLING + default y + rsource "../../../config/nrfconnect/chip-module/Kconfig.features" rsource "../../../config/nrfconnect/chip-module/Kconfig.defaults" source "Kconfig.zephyr" diff --git a/examples/light-switch-app/nrfconnect/main/AppTask.cpp b/examples/light-switch-app/nrfconnect/main/AppTask.cpp index 1adb749a1cc931..4419f8615be960 100644 --- a/examples/light-switch-app/nrfconnect/main/AppTask.cpp +++ b/examples/light-switch-app/nrfconnect/main/AppTask.cpp @@ -44,6 +44,10 @@ #include "OTAUtil.h" #endif +#ifdef CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING +#include +#endif + #include #include #include @@ -219,6 +223,10 @@ CHIP_ERROR AppTask::Init() ConfigurationMgr().LogDeviceConfig(); PrintOnboardingCodes(RendezvousInformationFlags(RendezvousInformationFlag::kBLE)); +#ifdef CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING + chip::app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(&GetICDUtil()); +#endif + // 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. diff --git a/examples/light-switch-app/nrfconnect/main/include/AppTask.h b/examples/light-switch-app/nrfconnect/main/include/AppTask.h index 5c7e2278976c00..4e0a264af03667 100644 --- a/examples/light-switch-app/nrfconnect/main/include/AppTask.h +++ b/examples/light-switch-app/nrfconnect/main/include/AppTask.h @@ -31,6 +31,10 @@ #include "DFUOverSMP.h" #endif +#ifdef CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING +#include "ICDUtil.h" +#endif + #include struct k_timer; diff --git a/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp b/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp index 3ea96abf726399..2fbad4ed4d3286 100644 --- a/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp +++ b/examples/light-switch-app/silabs/SiWx917/src/AppTask.cpp @@ -265,7 +265,7 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) button_event.Handler = SwitchActionEventHandler; sAppTask.PostEvent(&button_event); } - else if (button == SIWx917_BTN0) + else if (button == SIWx917_BTN0 && btnAction == SL_SIMPLE_BUTTON_PRESSED) { button_event.Handler = BaseApplication::ButtonHandler; sAppTask.PostEvent(&button_event); diff --git a/examples/light-switch-app/silabs/SiWx917/src/main.cpp b/examples/light-switch-app/silabs/SiWx917/src/main.cpp index 66f158cd48809e..bdafdfbf61cb08 100644 --- a/examples/light-switch-app/silabs/SiWx917/src/main.cpp +++ b/examples/light-switch-app/silabs/SiWx917/src/main.cpp @@ -51,7 +51,7 @@ static chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; int main(void) { init_ccpPlatform(); - if (SI917MatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) + if (SilabsMatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) { appError(CHIP_ERROR_INTERNAL); } diff --git a/examples/light-switch-app/silabs/efr32/src/main.cpp b/examples/light-switch-app/silabs/efr32/src/main.cpp index 97aff97aea535b..cd16d5f31b0ac2 100644 --- a/examples/light-switch-app/silabs/efr32/src/main.cpp +++ b/examples/light-switch-app/silabs/efr32/src/main.cpp @@ -50,7 +50,7 @@ static chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; int main(void) { init_efrPlatform(); - if (EFR32MatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) + if (SilabsMatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) appError(CHIP_ERROR_INTERNAL); gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); diff --git a/examples/light-switch-app/telink/CMakeLists.txt b/examples/light-switch-app/telink/CMakeLists.txt index 4b3ea23b7c9d39..c7339e9f81b623 100755 --- a/examples/light-switch-app/telink/CMakeLists.txt +++ b/examples/light-switch-app/telink/CMakeLists.txt @@ -59,6 +59,7 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/light-switch-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) @@ -68,9 +69,10 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp - src/main.cpp src/ZclCallbacks.cpp src/binding-handler.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/light-switch-app/telink/include/AppConfig.h b/examples/light-switch-app/telink/include/AppConfig.h old mode 100755 new mode 100644 index d41e4c557b4598..05c6957a92e399 --- a/examples/light-switch-app/telink/include/AppConfig.h +++ b/examples/light-switch-app/telink/include/AppConfig.h @@ -20,15 +20,10 @@ // ---- Light Switch Example App Config ---- -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#define APP_USE_EXAMPLE_START_BUTTON 1 +#define APP_USE_THREAD_START_BUTTON 1 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 0 +#define APP_USE_IDENTIFY_PWM 1 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 - -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 -#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) +#include "AppConfigCommon.h" diff --git a/examples/light-switch-app/telink/include/AppEvent.h b/examples/light-switch-app/telink/include/AppEvent.h deleted file mode 100755 index 72554b4bb54b5a..00000000000000 --- a/examples/light-switch-app/telink/include/AppEvent.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -struct AppEvent; -typedef void (*EventHandler)(AppEvent *); - -class LEDWidget; - -struct AppEvent -{ - enum AppEventTypes - { - kEventType_Button = 0, - kEventType_Timer, - kEventType_UpdateLedState, - kEventType_IdentifyStart, - kEventType_IdentifyStop, - kEventType_Lighting, - kEventType_Install, - }; - - uint16_t Type; - - union - { - struct - { - uint8_t Action; - } ButtonEvent; - struct - { - void * Context; - } TimerEvent; - struct - { - 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 953b677e083cde..12e09eaf9f1a16 100644 --- a/examples/light-switch-app/telink/include/AppTask.h +++ b/examples/light-switch-app/telink/include/AppTask.h @@ -18,86 +18,22 @@ #pragma once -#include "AppEvent.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.h" +#include "AppTaskCommon.h" -#include - -#include - -#if CONFIG_CHIP_FACTORY_DATA -#include -#endif - -#include - -struct k_timer; -struct Identify; - -class AppTask +class AppTask : public AppTaskCommon { public: - CHIP_ERROR StartApp(); - - enum Action_t : uint8_t - { - ON_ACTION = 0, - OFF_ACTION, - LEVEL_ACTION, - - INVALID_ACTION - }; - - void PostLightingActionRequest(Action_t aAction); - void PostEvent(AppEvent * event); void UpdateClusterState(); - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); private: friend AppTask & GetAppTask(void); + friend class AppTaskCommon; CHIP_ERROR Init(void); - static void ActionInitiated(AppTask::Action_t aAction, int32_t aActor); - static void ActionCompleted(AppTask::Action_t aAction, int32_t aActor); - static void ActionIdentifyStateUpdateHandler(k_timer * timer); - - void DispatchEvent(AppEvent * event); - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - static void SwitchActionButtonEventHandler(void); - 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 SwitchActionEventHandler(AppEvent * aEvent); - static void StartBleAdvHandler(AppEvent * aEvent); - static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); - - static void InitButtons(void); - - static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); static AppTask sAppTask; - PWMDevice mPwmIdentifyLed; - -#if CONFIG_CHIP_FACTORY_DATA - chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; -#endif }; inline AppTask & GetAppTask(void) diff --git a/examples/light-switch-app/telink/prj.conf b/examples/light-switch-app/telink/prj.conf index 9b8262eca31d06..baba7213300e00 100755 --- a/examples/light-switch-app/telink/prj.conf +++ b/examples/light-switch-app/telink/prj.conf @@ -26,9 +26,7 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=y -CONFIG_OPENTHREAD_FTD=n -CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 +CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=y CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings @@ -64,13 +62,5 @@ CONFIG_CHIP_FACTORY_DATA_BUILD=n CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management -CONFIG_PM=n -CONFIG_PM_DEVICE=n -CONFIG_CHIP_ENABLE_PM_DURING_BLE=n +CONFIG_PM=y diff --git a/examples/light-switch-app/telink/src/AppTask.cpp b/examples/light-switch-app/telink/src/AppTask.cpp index ffa763dfe5f7b1..b78a09d547d478 100644 --- a/examples/light-switch-app/telink/src/AppTask.cpp +++ b/examples/light-switch-app/telink/src/AppTask.cpp @@ -17,204 +17,27 @@ */ #include "AppTask.h" - -#include "AppConfig.h" -#include "AppEvent.h" -#include "ButtonManager.h" #include "binding-handler.h" -#include "ThreadUtil.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include - -#include - -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL - LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; - -namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kEndpointId = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; -constexpr uint32_t kIdentifyBlinkRateMs = 200; -constexpr uint32_t kIdentifyOkayOnRateMs = 50; -constexpr uint32_t kIdentifyOkayOffRateMs = 950; -constexpr uint32_t kIdentifyFinishOnRateMs = 950; -constexpr uint32_t kIdentifyFinishOffRateMs = 50; -constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; -constexpr uint32_t kIdentifyBreatheRateMs = 1000; - -const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; - -#if CONFIG_CHIP_FACTORY_DATA -// NOTE! This key is for test/certification only and should not be available in production devices! -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; -#endif - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; -#endif - -Button sFactoryResetButton; -Button sSwitchButton; -Button sThreadStartButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - -void OnIdentifyTriggerEffect(Identify * identify) -{ - AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); -} - -Identify sIdentify = { - kEndpointId, - [](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(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); - - // Initialize status LED -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); -#endif - - InitButtons(); - - // Initialize function button timer - k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); - k_timer_user_data_set(&sFactoryResetTimer, this); - - // Initialize PWM Identify led - CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("Green IDENTIFY PWM Device Init fail"); - return err; - } - - sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); - - // 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("mFactoryDataProvider.GetEnableKey() failed. Could not delegate a test event trigger"); - memset(sTestEventTriggerEnableKey, 0, sizeof(sTestEventTriggerEnableKey)); - } -#else - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); -#endif - - static CommonCaseDeviceServerInitParams initParams; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - ReturnErrorOnFailure(chip::Server::GetInstance().Init(initParams)); - gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); - chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); - -#if CONFIG_CHIP_OTA_REQUESTOR - InitBasicOTARequestor(); +#if APP_USE_EXAMPLE_START_BUTTON + SetExampleButtonCallbacks(SwitchActionEventHandler); #endif - - ConfigurationMgr().LogDeviceConfig(); + InitCommonParts(); // Configure Bindings - err = InitBindingHandler(); + CHIP_ERROR err = InitBindingHandler(); if (err != CHIP_NO_ERROR) { LOG_ERR("InitBindingHandler fail"); return err; } - 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); - err = ConnectivityMgr().SetBLEDeviceName("TelinkSwitch"); if (err != CHIP_NO_ERROR) { @@ -222,95 +45,9 @@ CHIP_ERROR AppTask::Init(void) 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; } -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) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&event); - } -} - -void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) -{ - AppEvent event; - event.Type = AppEvent::kEventType_IdentifyStart; - - switch (aEffect) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); - event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; - event.Type = AppEvent::kEventType_IdentifyStop; - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - return; - } - - sAppTask.PostEvent(&event); -} - -void AppTask::SwitchActionButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = SwitchActionEventHandler; - sAppTask.PostEvent(&event); -} - void AppTask::SwitchActionEventHandler(AppEvent * aEvent) { if (aEvent->Type == AppEvent::kEventType_Button) @@ -323,248 +60,4 @@ void AppTask::SwitchActionEventHandler(AppEvent * aEvent) } } -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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -void AppTask::StartThreadButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartThreadHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartThreadHandler(AppEvent * aEvent) -{ - LOG_INF("StartThreadHandler"); - if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) - { - // Switch context from BLE to Thread - Internal::BLEManagerImpl sInstance; - sInstance.SwitchToIeee802154(); - StartDefaultThreadNetwork(); - } - else - { - LOG_INF("Device already commissioned"); - } -} - -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadConnectivityChange: -#if CONFIG_CHIP_OTA_REQUESTOR - if (event->ThreadConnectivityChange.Result == kConnectivity_Established) - { - InitBasicOTARequestor(); - } -#endif - break; - default: - break; - } -} - -void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_UpdateLedState; - event.Handler = UpdateIdentifyStateEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) -{ - sAppTask.mPwmIdentifyLed.UpdateAction(); -} - -void AppTask::ActionInitiated(AppTask::Action_t aAction, int32_t aActor) {} - -void AppTask::ActionCompleted(AppTask::Action_t aAction, int32_t aActor) -{ - if (aActor == AppEvent::kEventType_Button) - { - sAppTask.UpdateClusterState(); - } -} - -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 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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sSwitchButton.Configure(BUTTON_PORT, BUTTON_PIN_2, SwitchActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - 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); -#endif - - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sSwitchButton); - ButtonManagerInst().AddButton(sThreadStartButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} diff --git a/examples/light-switch-app/telink/src/main.cpp b/examples/light-switch-app/telink/src/main.cpp deleted file mode 100755 index 9dd145f55ba0c9..00000000000000 --- a/examples/light-switch-app/telink/src/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "AppTask.h" - -#include -#include - -#include - -LOG_MODULE_REGISTER(app, CONFIG_CHIP_APP_LOG_LEVEL); - -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/lighting-app/bouffalolab/bl602/with_pw_rpc.gni b/examples/lighting-app/bouffalolab/bl602/with_pw_rpc.gni index 9498d4ed99dcdc..ae2a86be69f00f 100644 --- a/examples/lighting-app/bouffalolab/bl602/with_pw_rpc.gni +++ b/examples/lighting-app/bouffalolab/bl602/with_pw_rpc.gni @@ -24,4 +24,9 @@ chip_enable_pw_rpc = true chip_build_pw_trace_lib = false cpp_standard = "gnu++17" -#pw_trace_BACKEND = "$dir_pw_trace_tokenized" + +# pigweed updated to a1bd248 makes compile conversion errors; +# it seems riscv gcc (version > 10) can fixes this issue. +# let's disable strict warnings for RPC enabled for now. +remove_default_configs = [ "$dir_pw_build:strict_warnings" ] +treat_warnings_as_errors = false diff --git a/examples/lighting-app/bouffalolab/bl702/with_pw_rpc.gni b/examples/lighting-app/bouffalolab/bl702/with_pw_rpc.gni index 2739fee2b22f35..72cbc4e25122b6 100644 --- a/examples/lighting-app/bouffalolab/bl702/with_pw_rpc.gni +++ b/examples/lighting-app/bouffalolab/bl702/with_pw_rpc.gni @@ -24,4 +24,9 @@ chip_enable_pw_rpc = true chip_build_pw_trace_lib = false cpp_standard = "gnu++17" -#pw_trace_BACKEND = "$dir_pw_trace_tokenized" + +# pigweed updated to a1bd248 makes compile conversion errors; +# it seems riscv gcc (version > 10) can fixes this issue. +# let's disable strict warnings for RPC enabled for now. +remove_default_configs = [ "$dir_pw_build:strict_warnings" ] +treat_warnings_as_errors = false diff --git a/examples/lighting-app/esp32/main/Kconfig.projbuild b/examples/lighting-app/esp32/main/Kconfig.projbuild index dcf4f825fc5c9a..d994865b7aaee4 100644 --- a/examples/lighting-app/esp32/main/Kconfig.projbuild +++ b/examples/lighting-app/esp32/main/Kconfig.projbuild @@ -60,6 +60,10 @@ menu "Demo" depends on IDF_TARGET_ESP32C6 endchoice + config CHIP_PROJECT_CONFIG + string "CHIP Project Configuration file" + default "main/include/CHIPProjectConfig.h" + choice LED_TYPE prompt "LED type" default LED_TYPE_RMT if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_S3_DEVKITM || DEVICE_TYPE_ESP32H2_DEVKITC || DEVICE_TYPE_ESP32_C6_DEVKITC diff --git a/examples/lighting-app/esp32/main/include/CHIPProjectConfig.h b/examples/lighting-app/esp32/main/include/CHIPProjectConfig.h new file mode 100644 index 00000000000000..559895608a08d0 --- /dev/null +++ b/examples/lighting-app/esp32/main/include/CHIPProjectConfig.h @@ -0,0 +1,47 @@ +/* + * + * Copyright (c) 2023 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 + +/** + * @def CHIP_CONFIG_MAX_FABRICS + * + * @brief + * Maximum number of fabrics the device can participate in. Each fabric can + * provision the device with its unique operational credentials and manage + * its own access control lists. + */ +#define CHIP_CONFIG_MAX_FABRICS 5 // 5 is the minimum number of supported fabrics + +/** + * @def CHIP_IM_MAX_NUM_SUBSCRIPTIONS + * + * @brief Defines the maximum number of ReadHandler for subscriptions, limits the number of active subscription transactions on + * server. + * + */ +#define CHIP_IM_MAX_NUM_SUBSCRIPTIONS 45 diff --git a/examples/lighting-app/infineon/cyw30739/args.gni b/examples/lighting-app/infineon/cyw30739/args.gni index c19de1f1304321..770d2675cd9176 100644 --- a/examples/lighting-app/infineon/cyw30739/args.gni +++ b/examples/lighting-app/infineon/cyw30739/args.gni @@ -19,6 +19,7 @@ import("${chip_root}/src/platform/Infineon/CYW30739/args.gni") cyw30739_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_openthread_ftd = false +enable_sleepy_device = false chip_enable_ota_requestor = true diff --git a/examples/lighting-app/infineon/cyw30739/src/main.cpp b/examples/lighting-app/infineon/cyw30739/src/main.cpp index 74ff57aa959763..f1b28060f5d73f 100644 --- a/examples/lighting-app/infineon/cyw30739/src/main.cpp +++ b/examples/lighting-app/infineon/cyw30739/src/main.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors * Copyright (c) 2019 Google LLC. * All rights reserved. * @@ -142,8 +142,12 @@ APPLICATION_START() #if CHIP_DEVICE_CONFIG_THREAD_FTD err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); -#else // !CHIP_DEVICE_CONFIG_THREAD_FTD +#else // !CHIP_DEVICE_CONFIG_THREAD_FTD +#if CHIP_DEVICE_CONFIG_ENABLE_SED + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice); +#else /* !CHIP_DEVICE_CONFIG_ENABLE_SED */ err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice); +#endif /* CHIP_DEVICE_CONFIG_ENABLE_SED */ #endif // CHIP_DEVICE_CONFIG_THREAD_FTD if (err != CHIP_NO_ERROR) { diff --git a/examples/lighting-app/silabs/SiWx917/data_model/lighting-wifi-app.matter b/examples/lighting-app/silabs/SiWx917/data_model/lighting-wifi-app.matter index 17ae50fd9aeab1..08811edf0b16d4 100644 --- a/examples/lighting-app/silabs/SiWx917/data_model/lighting-wifi-app.matter +++ b/examples/lighting-app/silabs/SiWx917/data_model/lighting-wifi-app.matter @@ -1622,12 +1622,6 @@ endpoint 0 { device type rootdevice = 22, version 1; binding cluster OtaSoftwareUpdateProvider; - server cluster Groups { - ram attribute nameSupport; - ram attribute featureMap default = 0; - ram attribute clusterRevision default = 4; - } - server cluster Descriptor { callback attribute deviceTypeList; callback attribute serverList; diff --git a/examples/lighting-app/silabs/SiWx917/data_model/lighting-wifi-app.zap b/examples/lighting-app/silabs/SiWx917/data_model/lighting-wifi-app.zap index a005282133c0da..9131b9a3819d55 100644 --- a/examples/lighting-app/silabs/SiWx917/data_model/lighting-wifi-app.zap +++ b/examples/lighting-app/silabs/SiWx917/data_model/lighting-wifi-app.zap @@ -1,5 +1,5 @@ { - "featureLevel": 92, + "featureLevel": 95, "creator": "zap", "keyValuePairs": [ { @@ -198,7 +198,7 @@ "mfgCode": null, "define": "GROUPS_CLUSTER", "side": "server", - "enabled": 1, + "enabled": 0, "commands": [ { "name": "AddGroupResponse", @@ -8194,5 +8194,6 @@ "endpointVersion": 1, "deviceIdentifier": 257 } - ] + ], + "log": [] } \ No newline at end of file diff --git a/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp b/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp index 6133df35c33610..8da8003549c216 100644 --- a/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp +++ b/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp @@ -246,7 +246,7 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) button_event.Handler = LightActionEventHandler; sAppTask.PostEvent(&button_event); } - else if (button == SIWx917_BTN0) + else if (button == SIWx917_BTN0 && btnAction == SL_SIMPLE_BUTTON_PRESSED) { button_event.Handler = BaseApplication::ButtonHandler; sAppTask.PostEvent(&button_event); diff --git a/examples/lighting-app/silabs/SiWx917/src/main.cpp b/examples/lighting-app/silabs/SiWx917/src/main.cpp index f1103e3340310c..ce2ae970887a40 100644 --- a/examples/lighting-app/silabs/SiWx917/src/main.cpp +++ b/examples/lighting-app/silabs/SiWx917/src/main.cpp @@ -52,7 +52,7 @@ static chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; int main(void) { init_ccpPlatform(); - if (SI917MatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) + if (SilabsMatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) { appError(CHIP_ERROR_INTERNAL); } diff --git a/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.matter b/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.matter index fa3b3fd6a2b9ca..25f2346c1139d2 100644 --- a/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.matter +++ b/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.matter @@ -1712,12 +1712,6 @@ endpoint 0 { device type rootdevice = 22, version 1; binding cluster OtaSoftwareUpdateProvider; - server cluster Groups { - ram attribute nameSupport; - ram attribute featureMap default = 0; - ram attribute clusterRevision default = 4; - } - server cluster Descriptor { callback attribute deviceTypeList; callback attribute serverList; diff --git a/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.zap b/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.zap index e047beae16bd01..05a948eec9f423 100644 --- a/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.zap +++ b/examples/lighting-app/silabs/efr32/data_model/lighting-thread-app.zap @@ -1,5 +1,5 @@ { - "featureLevel": 92, + "featureLevel": 95, "creator": "zap", "keyValuePairs": [ { @@ -198,7 +198,7 @@ "mfgCode": null, "define": "GROUPS_CLUSTER", "side": "server", - "enabled": 1, + "enabled": 0, "commands": [ { "name": "AddGroupResponse", @@ -7796,5 +7796,6 @@ "endpointVersion": 1, "deviceIdentifier": 257 } - ] + ], + "log": [] } \ No newline at end of file diff --git a/examples/lighting-app/silabs/efr32/data_model/lighting-wifi-app.matter b/examples/lighting-app/silabs/efr32/data_model/lighting-wifi-app.matter index 17ae50fd9aeab1..08811edf0b16d4 100644 --- a/examples/lighting-app/silabs/efr32/data_model/lighting-wifi-app.matter +++ b/examples/lighting-app/silabs/efr32/data_model/lighting-wifi-app.matter @@ -1622,12 +1622,6 @@ endpoint 0 { device type rootdevice = 22, version 1; binding cluster OtaSoftwareUpdateProvider; - server cluster Groups { - ram attribute nameSupport; - ram attribute featureMap default = 0; - ram attribute clusterRevision default = 4; - } - server cluster Descriptor { callback attribute deviceTypeList; callback attribute serverList; diff --git a/examples/lighting-app/silabs/efr32/data_model/lighting-wifi-app.zap b/examples/lighting-app/silabs/efr32/data_model/lighting-wifi-app.zap index a005282133c0da..9131b9a3819d55 100644 --- a/examples/lighting-app/silabs/efr32/data_model/lighting-wifi-app.zap +++ b/examples/lighting-app/silabs/efr32/data_model/lighting-wifi-app.zap @@ -1,5 +1,5 @@ { - "featureLevel": 92, + "featureLevel": 95, "creator": "zap", "keyValuePairs": [ { @@ -198,7 +198,7 @@ "mfgCode": null, "define": "GROUPS_CLUSTER", "side": "server", - "enabled": 1, + "enabled": 0, "commands": [ { "name": "AddGroupResponse", @@ -8194,5 +8194,6 @@ "endpointVersion": 1, "deviceIdentifier": 257 } - ] + ], + "log": [] } \ No newline at end of file diff --git a/examples/lighting-app/silabs/efr32/src/main.cpp b/examples/lighting-app/silabs/efr32/src/main.cpp index 54fccb26ba8f35..73d81d7c2979c5 100644 --- a/examples/lighting-app/silabs/efr32/src/main.cpp +++ b/examples/lighting-app/silabs/efr32/src/main.cpp @@ -52,7 +52,7 @@ static chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; int main(void) { init_efrPlatform(); - if (EFR32MatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) + if (SilabsMatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) appError(CHIP_ERROR_INTERNAL); gExampleDeviceInfoProvider.SetStorageDelegate(&chip::Server::GetInstance().GetPersistentStorage()); diff --git a/examples/lighting-app/telink/CMakeLists.txt b/examples/lighting-app/telink/CMakeLists.txt index e56b1f4515b7cf..16f6dfb4244663 100644 --- a/examples/lighting-app/telink/CMakeLists.txt +++ b/examples/lighting-app/telink/CMakeLists.txt @@ -59,6 +59,7 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/lighting-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) @@ -68,8 +69,9 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp - src/main.cpp src/ZclCallbacks.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/lighting-app/telink/include/AppConfig.h b/examples/lighting-app/telink/include/AppConfig.h index 531cca82215120..eaf1933669106c 100644 --- a/examples/lighting-app/telink/include/AppConfig.h +++ b/examples/lighting-app/telink/include/AppConfig.h @@ -20,17 +20,13 @@ // ---- Lighting Example App Config ---- -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#define APP_USE_EXAMPLE_START_BUTTON 1 +#define APP_USE_THREAD_START_BUTTON 1 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 0 +#define APP_USE_IDENTIFY_PWM 1 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 - -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 +#include "AppConfigCommon.h" // Lighting LED config #define USE_RGB_PWM 0 @@ -40,4 +36,3 @@ #define LIGHTING_PWM_SPEC_RGB_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led1)) #define LIGHTING_PWM_SPEC_RGB_RED PWM_DT_SPEC_GET(DT_ALIAS(pwm_led2)) #endif -#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) diff --git a/examples/lighting-app/telink/include/AppEvent.h b/examples/lighting-app/telink/include/AppEvent.h deleted file mode 100644 index 72554b4bb54b5a..00000000000000 --- a/examples/lighting-app/telink/include/AppEvent.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -struct AppEvent; -typedef void (*EventHandler)(AppEvent *); - -class LEDWidget; - -struct AppEvent -{ - enum AppEventTypes - { - kEventType_Button = 0, - kEventType_Timer, - kEventType_UpdateLedState, - kEventType_IdentifyStart, - kEventType_IdentifyStop, - kEventType_Lighting, - kEventType_Install, - }; - - uint16_t Type; - - union - { - struct - { - uint8_t Action; - } ButtonEvent; - struct - { - void * Context; - } TimerEvent; - struct - { - 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 dbfb0bef4fc63d..7157b5a9d3601d 100644 --- a/examples/lighting-app/telink/include/AppTask.h +++ b/examples/lighting-app/telink/include/AppTask.h @@ -18,37 +18,20 @@ #pragma once -#include "AppConfig.h" -#include "AppEvent.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.h" -#include - -#if CONFIG_CHIP_FACTORY_DATA -#include -#endif +#include "AppTaskCommon.h" #ifdef CONFIG_CHIP_PW_RPC #include "Rpc.h" #endif -#include - -struct k_timer; -struct Identify; - -class AppTask +class AppTask : public AppTaskCommon { public: - CHIP_ERROR StartApp(void); - void SetInitiateAction(PWMDevice::Action_t aAction, int32_t aActor, uint8_t * value); - void PostEvent(AppEvent * aEvent); void UpdateClusterState(void); PWMDevice & GetPWMDevice(void) { return mPwmRgbBlueLed; } +#ifdef CONFIG_CHIP_PW_RPC enum ButtonId_t { kButtonId_LightingAction = 1, @@ -56,59 +39,30 @@ class AppTask kButtonId_StartThread, kButtonId_StartBleAdv } ButtonId; - - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); +#endif private: #ifdef CONFIG_CHIP_PW_RPC friend class chip::rpc::TelinkButton; + static void ButtonEventHandler(ButtonId_t btnId, bool btnPressed); #endif friend AppTask & GetAppTask(void); + friend class AppTaskCommon; + CHIP_ERROR Init(void); static void ActionInitiated(PWMDevice::Action_t aAction, int32_t aActor); static void ActionCompleted(PWMDevice::Action_t aAction, int32_t aActor); - static void ActionIdentifyStateUpdateHandler(k_timer * timer); - void DispatchEvent(AppEvent * event); - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - static void LightingActionButtonEventHandler(void); - 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 LightingActionEventHandler(AppEvent * aEvent); - static void StartBleAdvHandler(AppEvent * aEvent); - static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); - static void ButtonEventHandler(ButtonId_t btnId, bool btnPressed); - static void InitButtons(void); - - static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); - - static AppTask sAppTask; PWMDevice mPwmRgbBlueLed; #if USE_RGB_PWM PWMDevice mPwmRgbGreenLed; PWMDevice mPwmRgbRedLed; #endif - PWMDevice mPwmIdentifyLed; -#if CONFIG_CHIP_FACTORY_DATA - chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; -#endif + static AppTask sAppTask; }; inline AppTask & GetAppTask(void) diff --git a/examples/lighting-app/telink/prj.conf b/examples/lighting-app/telink/prj.conf index 8cf739a92b55ef..90b24645fc5002 100644 --- a/examples/lighting-app/telink/prj.conf +++ b/examples/lighting-app/telink/prj.conf @@ -26,9 +26,7 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=n -CONFIG_OPENTHREAD_FTD=y CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings @@ -64,16 +62,8 @@ CONFIG_CHIP_FACTORY_DATA_BUILD=n CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management CONFIG_PM=n -CONFIG_PM_DEVICE=n -CONFIG_CHIP_ENABLE_PM_DURING_BLE=n # Custom RF power values CONFIG_B91_BLE_CTRL_RF_POWER_P9P11DBM=y diff --git a/examples/lighting-app/telink/src/AppTask.cpp b/examples/lighting-app/telink/src/AppTask.cpp index 47332a53748037..1f512e322dc188 100644 --- a/examples/lighting-app/telink/src/AppTask.cpp +++ b/examples/lighting-app/telink/src/AppTask.cpp @@ -18,178 +18,39 @@ #include "AppTask.h" -#include "AppConfig.h" -#include "AppEvent.h" -#include "ButtonManager.h" #include "ColorFormat.h" +#include "PWMDevice.h" -#include "ThreadUtil.h" - -#include #include -#include -#include -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include - -#include - -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; - namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kLightEndpointId = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; -constexpr uint32_t kIdentifyBlinkRateMs = 200; -constexpr uint32_t kIdentifyOkayOnRateMs = 50; -constexpr uint32_t kIdentifyOkayOffRateMs = 950; -constexpr uint32_t kIdentifyFinishOnRateMs = 950; -constexpr uint32_t kIdentifyFinishOffRateMs = 50; -constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; -constexpr uint32_t kIdentifyBreatheRateMs = 1000; - const struct pwm_dt_spec sPwmRgbSpecBlueLed = LIGHTING_PWM_SPEC_RGB_BLUE; #if USE_RGB_PWM const struct pwm_dt_spec sPwmRgbSpecGreenLed = LIGHTING_PWM_SPEC_RGB_GREEN; const struct pwm_dt_spec sPwmRgbSpecRedLed = LIGHTING_PWM_SPEC_RGB_RED; -#endif -const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; -#if CONFIG_CHIP_FACTORY_DATA -// NOTE! This key is for test/certification only and should not be available in production devices! -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; -#endif - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; -#endif -#if USE_RGB_PWM uint8_t sBrightness; PWMDevice::Action_t sColorAction = PWMDevice::INVALID_ACTION; XyColor_t sXY; HsvColor_t sHSV; CtColor_t sCT; #endif - -Button sFactoryResetButton; -Button sLightingButton; -Button sThreadStartButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - -void OnIdentifyTriggerEffect(Identify * identify) -{ - AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); -} - -Identify sIdentify = { - kLightEndpointId, - [](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(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); - - // Initialize LEDs -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); -#endif - - 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(kLightEndpointId, &minLightLevel); + Clusters::LevelControl::Attributes::MinLevel::Get(kExampleEndpointId, &minLightLevel); uint8_t maxLightLevel = kDefaultMaxLevel; - Clusters::LevelControl::Attributes::MaxLevel::Get(kLightEndpointId, &maxLightLevel); + Clusters::LevelControl::Attributes::MaxLevel::Get(kExampleEndpointId, &maxLightLevel); - // Initialize PWM LEDs - CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("Green IDENTIFY PWM Device Init fail"); - return err; - } - - err = sAppTask.mPwmRgbBlueLed.Init(&sPwmRgbSpecBlueLed, minLightLevel, maxLightLevel, maxLightLevel); + CHIP_ERROR err = sAppTask.mPwmRgbBlueLed.Init(&sPwmRgbSpecBlueLed, minLightLevel, maxLightLevel, maxLightLevel); if (err != CHIP_NO_ERROR) { LOG_ERR("Blue RGB PWM Device Init fail"); @@ -211,44 +72,11 @@ CHIP_ERROR AppTask::Init(void) } #endif sAppTask.mPwmRgbBlueLed.SetCallbacks(ActionInitiated, ActionCompleted, nullptr); - sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); - - // 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; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - ReturnErrorOnFailure(chip::Server::GetInstance().Init(initParams)); - - gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); - chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); - -#if CONFIG_CHIP_OTA_REQUESTOR - InitBasicOTARequestor(); +#if APP_USE_EXAMPLE_START_BUTTON + SetExampleButtonCallbacks(LightingActionEventHandler); #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); + InitCommonParts(); err = ConnectivityMgr().SetBLEDeviceName("TelinkLight"); if (err != CHIP_NO_ERROR) @@ -257,45 +85,9 @@ CHIP_ERROR AppTask::Init(void) 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; } -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) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&event); - } -} - -void AppTask::LightingActionButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = LightingActionEventHandler; - sAppTask.PostEvent(&event); -} - void AppTask::LightingActionEventHandler(AppEvent * aEvent) { PWMDevice::Action_t action = PWMDevice::INVALID_ACTION; @@ -335,225 +127,31 @@ void AppTask::LightingActionEventHandler(AppEvent * aEvent) } } -void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) -{ - AppEvent event; - event.Type = AppEvent::kEventType_IdentifyStart; - - switch (aEffect) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); - event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; - event.Type = AppEvent::kEventType_IdentifyStop; - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - return; - } - - 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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -void AppTask::StartThreadButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartThreadHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartThreadHandler(AppEvent * aEvent) -{ - LOG_INF("StartThreadHandler"); - if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) - { - // Switch context from BLE to Thread - Internal::BLEManagerImpl sInstance; - sInstance.SwitchToIeee802154(); - StartDefaultThreadNetwork(); - } - else - { - LOG_INF("Device already commissioned"); - } -} - -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) +#ifdef CONFIG_CHIP_PW_RPC +void AppTask::ButtonEventHandler(ButtonId_t btnId, bool btnPressed) { - 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()) + if (!btnPressed) { - LOG_INF("BLE adv already enabled"); return; } - if (chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() != CHIP_NO_ERROR) - { - LOG_ERR("OpenBasicCommissioningWindow fail"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) + switch (btnId) { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif + case kButtonId_LightingAction: + ExampleActionButtonEventHandler(); break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif + case kButtonId_FactoryReset: + FactoryResetButtonEventHandler(); break; - case DeviceEventType::kThreadConnectivityChange: -#if CONFIG_CHIP_OTA_REQUESTOR - if (event->ThreadConnectivityChange.Result == kConnectivity_Established) - { - InitBasicOTARequestor(); - } -#endif + case kButtonId_StartThread: + StartThreadButtonEventHandler(); break; - default: + case kButtonId_StartBleAdv: + StartBleAdvButtonEventHandler(); break; } } - -void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_UpdateLedState; - event.Handler = UpdateIdentifyStateEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) -{ - sAppTask.mPwmIdentifyLed.UpdateAction(); -} +#endif void AppTask::ActionInitiated(PWMDevice::Action_t aAction, int32_t aActor) { @@ -592,36 +190,16 @@ void AppTask::ActionCompleted(PWMDevice::Action_t aAction, int32_t aActor) } } -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) { #if USE_RGB_PWM bool isTurnedOn = sAppTask.mPwmRgbRedLed.IsTurnedOn() || sAppTask.mPwmRgbGreenLed.IsTurnedOn() || sAppTask.mPwmRgbBlueLed.IsTurnedOn(); #else - bool isTurnedOn = sAppTask.mPwmRgbBlueLed.IsTurnedOn(); + bool isTurnedOn = sAppTask.mPwmRgbBlueLed.IsTurnedOn(); #endif // write the new on/off value - EmberAfStatus status = Clusters::OnOff::Attributes::OnOff::Set(kLightEndpointId, isTurnedOn); + EmberAfStatus status = Clusters::OnOff::Attributes::OnOff::Set(kExampleEndpointId, isTurnedOn); if (status != EMBER_ZCL_STATUS_SUCCESS) { @@ -642,81 +220,13 @@ void AppTask::UpdateClusterState(void) #else uint8_t setLevel = sAppTask.mPwmRgbBlueLed.GetLevel(); #endif - status = Clusters::LevelControl::Attributes::CurrentLevel::Set(kLightEndpointId, setLevel); + status = Clusters::LevelControl::Attributes::CurrentLevel::Set(kExampleEndpointId, setLevel); if (status != EMBER_ZCL_STATUS_SUCCESS) { LOG_ERR("Update CurrentLevel fail: %x", status); } } -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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::ButtonEventHandler(ButtonId_t btnId, bool btnPressed) -{ - if (!btnPressed) - { - return; - } - - switch (btnId) - { - case kButtonId_LightingAction: - LightingActionButtonEventHandler(); - break; - case kButtonId_FactoryReset: - FactoryResetButtonEventHandler(); - break; - case kButtonId_StartThread: - StartThreadButtonEventHandler(); - break; - case kButtonId_StartBleAdv: - StartBleAdvButtonEventHandler(); - break; - } -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sLightingButton.Configure(BUTTON_PORT, BUTTON_PIN_2, LightingActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - 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); -#endif - - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sLightingButton); - ButtonManagerInst().AddButton(sThreadStartButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} - void AppTask::SetInitiateAction(PWMDevice::Action_t aAction, int32_t aActor, uint8_t * value) { #if USE_RGB_PWM diff --git a/examples/lock-app/infineon/cyw30739/args.gni b/examples/lock-app/infineon/cyw30739/args.gni index c19de1f1304321..770d2675cd9176 100644 --- a/examples/lock-app/infineon/cyw30739/args.gni +++ b/examples/lock-app/infineon/cyw30739/args.gni @@ -19,6 +19,7 @@ import("${chip_root}/src/platform/Infineon/CYW30739/args.gni") cyw30739_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_openthread_ftd = false +enable_sleepy_device = false chip_enable_ota_requestor = true diff --git a/examples/lock-app/infineon/cyw30739/src/main.cpp b/examples/lock-app/infineon/cyw30739/src/main.cpp index be32b550205bf4..551fc31e2e3052 100644 --- a/examples/lock-app/infineon/cyw30739/src/main.cpp +++ b/examples/lock-app/infineon/cyw30739/src/main.cpp @@ -141,10 +141,18 @@ APPLICATION_START() } #endif +#if CHIP_DEVICE_CONFIG_THREAD_FTD err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); +#else // !CHIP_DEVICE_CONFIG_THREAD_FTD +#if CHIP_DEVICE_CONFIG_ENABLE_SED + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice); +#else /* !CHIP_DEVICE_CONFIG_ENABLE_SED */ + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice); +#endif /* CHIP_DEVICE_CONFIG_ENABLE_SED */ +#endif // CHIP_DEVICE_CONFIG_THREAD_FTD if (err != CHIP_NO_ERROR) { - ChipLogError(Zcl, "ERROR SetThreadDeviceType %ld", err.AsInteger()); + printf("ERROR SetThreadDeviceType %ld\n", err.AsInteger()); } ChipLogProgress(Zcl, "Starting event loop task"); diff --git a/examples/lock-app/nrfconnect/CMakeLists.txt b/examples/lock-app/nrfconnect/CMakeLists.txt index 7e7dc3ce49b4f2..4be8f9927b5c22 100644 --- a/examples/lock-app/nrfconnect/CMakeLists.txt +++ b/examples/lock-app/nrfconnect/CMakeLists.txt @@ -71,3 +71,7 @@ endif() if(CONFIG_MCUMGR_SMP_BT) target_sources(app PRIVATE ${NRFCONNECT_COMMON}/util/DFUOverSMP.cpp) endif() + +if(CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING) + target_sources(app PRIVATE ${NRFCONNECT_COMMON}/util/ICDUtil.cpp) +endif() diff --git a/examples/lock-app/nrfconnect/Kconfig b/examples/lock-app/nrfconnect/Kconfig index 622d825f80e3ef..384993c130f77d 100644 --- a/examples/lock-app/nrfconnect/Kconfig +++ b/examples/lock-app/nrfconnect/Kconfig @@ -59,6 +59,9 @@ config NRF_WIFI_LOW_POWER endif # CHIP_WIFI +config CHIP_ICD_SUBSCRIPTION_HANDLING + default y + rsource "../../../config/nrfconnect/chip-module/Kconfig.features" rsource "../../../config/nrfconnect/chip-module/Kconfig.defaults" source "Kconfig.zephyr" diff --git a/examples/lock-app/nrfconnect/main/AppTask.cpp b/examples/lock-app/nrfconnect/main/AppTask.cpp index c6b6a1fd5b6654..61b96e266e6038 100644 --- a/examples/lock-app/nrfconnect/main/AppTask.cpp +++ b/examples/lock-app/nrfconnect/main/AppTask.cpp @@ -45,6 +45,10 @@ #include "OTAUtil.h" #endif +#ifdef CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING +#include +#endif + #include #include #include @@ -212,6 +216,10 @@ CHIP_ERROR AppTask::Init() ConfigurationMgr().LogDeviceConfig(); PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); +#ifdef CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING + chip::app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(&GetICDUtil()); +#endif + // 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. diff --git a/examples/lock-app/nrfconnect/main/include/AppTask.h b/examples/lock-app/nrfconnect/main/include/AppTask.h index 841362ed6ba8ce..402752d6412738 100644 --- a/examples/lock-app/nrfconnect/main/include/AppTask.h +++ b/examples/lock-app/nrfconnect/main/include/AppTask.h @@ -33,6 +33,10 @@ #include "DFUOverSMP.h" #endif +#ifdef CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING +#include "ICDUtil.h" +#endif + struct k_timer; struct Identify; diff --git a/examples/lock-app/silabs/SiWx917/src/AppTask.cpp b/examples/lock-app/silabs/SiWx917/src/AppTask.cpp index bb9d15b6328039..abc276588bdab6 100644 --- a/examples/lock-app/silabs/SiWx917/src/AppTask.cpp +++ b/examples/lock-app/silabs/SiWx917/src/AppTask.cpp @@ -358,7 +358,7 @@ void AppTask::ButtonEventHandler(uint8_t button, uint8_t btnAction) button_event.Handler = LockActionEventHandler; sAppTask.PostEvent(&button_event); } - else if (button == SIWx917_BTN0) + else if (button == SIWx917_BTN0 && btnAction == SL_SIMPLE_BUTTON_PRESSED) { button_event.Handler = BaseApplication::ButtonHandler; sAppTask.PostEvent(&button_event); diff --git a/examples/lock-app/silabs/SiWx917/src/main.cpp b/examples/lock-app/silabs/SiWx917/src/main.cpp index 44ef40f931b19a..d28689ff99cfb5 100644 --- a/examples/lock-app/silabs/SiWx917/src/main.cpp +++ b/examples/lock-app/silabs/SiWx917/src/main.cpp @@ -51,7 +51,7 @@ int main(void) { init_ccpPlatform(); - if (SI917MatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) + if (SilabsMatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) appError(CHIP_ERROR_INTERNAL); gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); diff --git a/examples/lock-app/silabs/efr32/src/main.cpp b/examples/lock-app/silabs/efr32/src/main.cpp index e9fc2130f29009..aef9ed112eb164 100644 --- a/examples/lock-app/silabs/efr32/src/main.cpp +++ b/examples/lock-app/silabs/efr32/src/main.cpp @@ -50,7 +50,7 @@ static chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; int main(void) { init_efrPlatform(); - if (EFR32MatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) + if (SilabsMatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) appError(CHIP_ERROR_INTERNAL); gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); diff --git a/examples/lock-app/telink/CMakeLists.txt b/examples/lock-app/telink/CMakeLists.txt index d424f24bcd19f0..98b3e5de27e567 100755 --- a/examples/lock-app/telink/CMakeLists.txt +++ b/examples/lock-app/telink/CMakeLists.txt @@ -59,6 +59,7 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/lock-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) @@ -68,9 +69,10 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp - src/main.cpp src/ZclCallbacks.cpp src/BoltLockManager.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/lock-app/telink/include/AppConfig.h b/examples/lock-app/telink/include/AppConfig.h old mode 100755 new mode 100644 index a6b0bc0b7f3ddf..ae4c9d5b4fc9c5 --- a/examples/lock-app/telink/include/AppConfig.h +++ b/examples/lock-app/telink/include/AppConfig.h @@ -20,16 +20,12 @@ // ---- Lock Example App Config ---- -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#define APP_USE_EXAMPLE_START_BUTTON 1 +#define APP_USE_THREAD_START_BUTTON 1 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 0 +#define APP_USE_IDENTIFY_PWM 1 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 +#include "AppConfigCommon.h" -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 #define LOCK_STATE_LED 6 -#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) diff --git a/examples/lock-app/telink/include/AppEvent.h b/examples/lock-app/telink/include/AppEvent.h deleted file mode 100644 index 9f2436c592dc8c..00000000000000 --- a/examples/lock-app/telink/include/AppEvent.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * - * Copyright (c) 2023 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_IdentifyStart, - kEventType_IdentifyStop, - kEventType_Lighting, - kEventType_Install, - }; - - uint16_t Type; - - union - { - struct - { - uint8_t Action; - } ButtonEvent; - struct - { - void * Context; - } TimerEvent; - struct - { - LEDWidget * LedWidget; - } UpdateLedStateEvent; - }; - - EventHandler Handler; -}; diff --git a/examples/lock-app/telink/include/AppTask.h b/examples/lock-app/telink/include/AppTask.h index 5f26b3d6895634..c63643ca89ca6d 100644 --- a/examples/lock-app/telink/include/AppTask.h +++ b/examples/lock-app/telink/include/AppTask.h @@ -18,72 +18,24 @@ #pragma once -#include "AppEvent.h" +#include "AppTaskCommon.h" #include "BoltLockManager.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.h" -#include - -#if CONFIG_CHIP_FACTORY_DATA -#include -#endif - -struct k_timer; -struct Identify; - -class AppTask +class AppTask : public AppTaskCommon { public: - CHIP_ERROR StartApp(); - - void PostEvent(AppEvent * event); void UpdateClusterState(BoltLockManager::State state, BoltLockManager::OperationSource source); - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); private: friend AppTask & GetAppTask(void); + friend class AppTaskCommon; CHIP_ERROR Init(void); - static void ActionIdentifyStateUpdateHandler(k_timer * timer); - - void DispatchEvent(AppEvent * event); - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - static void LockActionButtonEventHandler(void); - 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 SwitchActionEventHandler(AppEvent * aEvent); - static void StartBleAdvHandler(AppEvent * aEvent); - static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); - static void LockActionEventHandler(AppEvent * event); static void LockStateChanged(BoltLockManager::State state, BoltLockManager::OperationSource source); - static void InitButtons(void); - static AppTask sAppTask; - PWMDevice mPwmIdentifyLed; - -#if CONFIG_CHIP_FACTORY_DATA - chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; -#endif }; inline AppTask & GetAppTask(void) diff --git a/examples/lock-app/telink/prj.conf b/examples/lock-app/telink/prj.conf index e57b152edb82f8..5de8f1a8f352c1 100755 --- a/examples/lock-app/telink/prj.conf +++ b/examples/lock-app/telink/prj.conf @@ -26,9 +26,7 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=y -CONFIG_OPENTHREAD_FTD=n -CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 +CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=y CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings @@ -63,13 +61,5 @@ CONFIG_CHIP_FACTORY_DATA=n CONFIG_CHIP_FACTORY_DATA_BUILD=n CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management -CONFIG_PM=n -CONFIG_PM_DEVICE=n -CONFIG_CHIP_ENABLE_PM_DURING_BLE=n +CONFIG_PM=y diff --git a/examples/lock-app/telink/src/AppTask.cpp b/examples/lock-app/telink/src/AppTask.cpp index 91fc9540b15faf..ca73a27eda6dd1 100644 --- a/examples/lock-app/telink/src/AppTask.cpp +++ b/examples/lock-app/telink/src/AppTask.cpp @@ -17,299 +17,49 @@ */ #include "AppTask.h" - -#include "AppConfig.h" #include "BoltLockManager.h" -#include "ButtonManager.h" - -#include "ThreadUtil.h" -#include #include -#include -#include -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include - -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; using namespace ::chip::app::Clusters::DoorLock; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kLockEndpointId = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; -constexpr uint32_t kIdentifyBlinkRateMs = 200; -constexpr uint32_t kIdentifyOkayOnRateMs = 50; -constexpr uint32_t kIdentifyOkayOffRateMs = 950; -constexpr uint32_t kIdentifyFinishOnRateMs = 950; -constexpr uint32_t kIdentifyFinishOffRateMs = 50; -constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; -constexpr uint32_t kIdentifyBreatheRateMs = 1000; - -const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; - -#if CONFIG_CHIP_FACTORY_DATA -// NOTE! This key is for test/certification only and should not be available in production devices! -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; -#endif - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; - #if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; LEDWidget sLockLED; #endif - -Button sFactoryResetButton; -Button sLockButton; -Button sThreadStartButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - -void OnIdentifyTriggerEffect(Identify * identify) -{ - AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); -} - -Identify sIdentify = { - kLockEndpointId, - [](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(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); +#if APP_USE_EXAMPLE_START_BUTTON + SetExampleButtonCallbacks(LockActionEventHandler); +#endif + InitCommonParts(); - // Initialize status LED #if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); - sLockLED.Init(LOCK_STATE_LED); sLockLED.Set(BoltLockMgr().IsLocked()); #endif - InitButtons(); - - // Initialize function button timer - k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); - k_timer_user_data_set(&sFactoryResetTimer, this); - - // Initialize PWM Identify led - CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("Green IDENTIFY PWM Device Init fail"); - return err; - } - - sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); - BoltLockMgr().Init(LockStateChanged); - // 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("mFactoryDataProvider.GetEnableKey() failed. Could not delegate a test event trigger"); - memset(sTestEventTriggerEnableKey, 0, sizeof(sTestEventTriggerEnableKey)); - } -#else - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); -#endif - - static CommonCaseDeviceServerInitParams initParams; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - 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); - // Disable auto-relock time feature. - DoorLockServer::Instance().SetAutoRelockTime(kLockEndpointId, 0); + DoorLockServer::Instance().SetAutoRelockTime(kExampleEndpointId, 0); - err = ConnectivityMgr().SetBLEDeviceName("Telink Lock"); + CHIP_ERROR err = ConnectivityMgr().SetBLEDeviceName("Telink Lock"); 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; } -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) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&event); - } -} - -void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) -{ - AppEvent event; - event.Type = AppEvent::kEventType_IdentifyStart; - - switch (aEffect) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); - event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; - event.Type = AppEvent::kEventType_IdentifyStop; - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - return; - } - - sAppTask.PostEvent(&event); -} - -void AppTask::LockActionButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = LockActionEventHandler; - sAppTask.PostEvent(&event); -} - void AppTask::LockActionEventHandler(AppEvent * aEvent) { if (BoltLockMgr().IsLocked()) @@ -322,195 +72,33 @@ void AppTask::LockActionEventHandler(AppEvent * aEvent) } } -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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -void AppTask::StartThreadButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartThreadHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartThreadHandler(AppEvent * aEvent) -{ - LOG_INF("StartThreadHandler"); - if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) - { - // Switch context from BLE to Thread - Internal::BLEManagerImpl sInstance; - sInstance.SwitchToIeee802154(); - StartDefaultThreadNetwork(); - } - else - { - LOG_INF("Device already commissioned"); - } -} - -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadConnectivityChange: -#if CONFIG_CHIP_OTA_REQUESTOR - if (event->ThreadConnectivityChange.Result == kConnectivity_Established) - { - InitBasicOTARequestor(); - } -#endif - break; - default: - break; - } -} - -void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_UpdateLedState; - event.Handler = UpdateIdentifyStateEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) -{ - sAppTask.mPwmIdentifyLed.UpdateAction(); -} - void AppTask::LockStateChanged(BoltLockManager::State state, BoltLockManager::OperationSource source) { switch (state) { case BoltLockManager::State::kLockingInitiated: LOG_INF("Lock action initiated"); +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED sLockLED.Blink(50, 50); +#endif break; case BoltLockManager::State::kLockingCompleted: LOG_INF("Lock action completed"); +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED sLockLED.Set(true); +#endif break; case BoltLockManager::State::kUnlockingInitiated: LOG_INF("Unlock action initiated"); +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED sLockLED.Blink(50, 50); +#endif break; case BoltLockManager::State::kUnlockingCompleted: LOG_INF("Unlock action completed"); +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED sLockLED.Set(false); +#endif break; } @@ -518,26 +106,6 @@ void AppTask::LockStateChanged(BoltLockManager::State state, BoltLockManager::Op sAppTask.UpdateClusterState(state, source); } -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(BoltLockManager::State state, BoltLockManager::OperationSource source) { DlLockState newLockState; @@ -557,64 +125,21 @@ void AppTask::UpdateClusterState(BoltLockManager::State state, BoltLockManager:: SystemLayer().ScheduleLambda([newLockState, source] { chip::app::DataModel::Nullable currentLockState; - chip::app::Clusters::DoorLock::Attributes::LockState::Get(kLockEndpointId, currentLockState); + chip::app::Clusters::DoorLock::Attributes::LockState::Get(kExampleEndpointId, currentLockState); if (currentLockState.IsNull()) { // Initialize lock state with start value, but not invoke lock/unlock. - chip::app::Clusters::DoorLock::Attributes::LockState::Set(kLockEndpointId, newLockState); + chip::app::Clusters::DoorLock::Attributes::LockState::Set(kExampleEndpointId, newLockState); } else { LOG_INF("Updating LockState attribute"); - if (!DoorLockServer::Instance().SetLockState(kLockEndpointId, newLockState, source)) + if (!DoorLockServer::Instance().SetLockState(kExampleEndpointId, newLockState, source)) { LOG_ERR("Failed to update LockState attribute"); } } }); } - -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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sLockButton.Configure(BUTTON_PORT, BUTTON_PIN_2, LockActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sLockButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_1, LockActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); -#endif - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sLockButton); - ButtonManagerInst().AddButton(sThreadStartButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} diff --git a/examples/lock-app/telink/src/BoltLockManager.cpp b/examples/lock-app/telink/src/BoltLockManager.cpp index 3abf145f482653..721fb11e427d72 100644 --- a/examples/lock-app/telink/src/BoltLockManager.cpp +++ b/examples/lock-app/telink/src/BoltLockManager.cpp @@ -19,7 +19,7 @@ #include "BoltLockManager.h" #include "AppConfig.h" -#include "AppEvent.h" +#include "AppEventCommon.h" #include "AppTask.h" #include diff --git a/examples/ota-requestor-app/infineon/cyw30739/args.gni b/examples/ota-requestor-app/infineon/cyw30739/args.gni index e6ec7f5d3636a6..6f4645ad4beb71 100644 --- a/examples/ota-requestor-app/infineon/cyw30739/args.gni +++ b/examples/ota-requestor-app/infineon/cyw30739/args.gni @@ -19,5 +19,6 @@ import("${chip_root}/src/platform/Infineon/CYW30739/args.gni") cyw30739_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_openthread_ftd = false +enable_sleepy_device = false chip_enable_ota_requestor = true diff --git a/examples/ota-requestor-app/infineon/cyw30739/src/main.cpp b/examples/ota-requestor-app/infineon/cyw30739/src/main.cpp index d68f4c70eb0c7f..14ce58809f68dc 100644 --- a/examples/ota-requestor-app/infineon/cyw30739/src/main.cpp +++ b/examples/ota-requestor-app/infineon/cyw30739/src/main.cpp @@ -76,8 +76,12 @@ APPLICATION_START() #if CHIP_DEVICE_CONFIG_THREAD_FTD err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router); -#else // !CHIP_DEVICE_CONFIG_THREAD_FTD +#else // !CHIP_DEVICE_CONFIG_THREAD_FTD +#if CHIP_DEVICE_CONFIG_ENABLE_SED + err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice); +#else /* !CHIP_DEVICE_CONFIG_ENABLE_SED */ err = ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice); +#endif /* CHIP_DEVICE_CONFIG_ENABLE_SED */ #endif // CHIP_DEVICE_CONFIG_THREAD_FTD if (err != CHIP_NO_ERROR) { diff --git a/examples/ota-requestor-app/telink/CMakeLists.txt b/examples/ota-requestor-app/telink/CMakeLists.txt index 9b66cd662f85f2..f9dcafa515b74a 100644 --- a/examples/ota-requestor-app/telink/CMakeLists.txt +++ b/examples/ota-requestor-app/telink/CMakeLists.txt @@ -59,6 +59,7 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/ota-requestor-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) @@ -68,8 +69,9 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp - src/main.cpp src/ZclCallbacks.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/ota-requestor-app/telink/include/AppConfig.h b/examples/ota-requestor-app/telink/include/AppConfig.h index 468e6440d45e3f..ff96590c376749 100644 --- a/examples/ota-requestor-app/telink/include/AppConfig.h +++ b/examples/ota-requestor-app/telink/include/AppConfig.h @@ -20,15 +20,10 @@ // ---- OTA Requestor Example App Config ---- -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#define APP_USE_EXAMPLE_START_BUTTON 0 +#define APP_USE_THREAD_START_BUTTON 1 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 1 +#define APP_USE_IDENTIFY_PWM 1 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 - -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 -#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) +#include "AppConfigCommon.h" diff --git a/examples/ota-requestor-app/telink/include/AppTask.h b/examples/ota-requestor-app/telink/include/AppTask.h index 1a0c2aa4698962..24e00675e78472 100755 --- a/examples/ota-requestor-app/telink/include/AppTask.h +++ b/examples/ota-requestor-app/telink/include/AppTask.h @@ -18,74 +18,17 @@ #pragma once -#include "AppEvent.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.h" +#include "AppTaskCommon.h" -#include - -#include - -#include - -struct k_timer; -struct Identify; - -class AppTask +class AppTask : public AppTaskCommon { -public: - CHIP_ERROR StartApp(void); - - enum Action_t : uint8_t - { - ON_ACTION = 0, - OFF_ACTION, - LEVEL_ACTION, - - INVALID_ACTION - }; - - void PostLightingActionRequest(Action_t aAction); - void PostEvent(AppEvent * event); - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); - private: friend AppTask & GetAppTask(void); - CHIP_ERROR Init(void); - - static void ActionInitiated(AppTask::Action_t aAction, int32_t aActor); - static void ActionCompleted(AppTask::Action_t aAction, int32_t aActor); - static void ActionIdentifyStateUpdateHandler(k_timer * timer); - - void DispatchEvent(AppEvent * event); - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - 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 UpdateIdentifyStateEventHandler(AppEvent * aEvent); - - static void InitButtons(void); + friend class AppTaskCommon; - static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + CHIP_ERROR Init(); static AppTask sAppTask; - PWMDevice mPwmIdentifyLed; }; inline AppTask & GetAppTask(void) diff --git a/examples/ota-requestor-app/telink/prj.conf b/examples/ota-requestor-app/telink/prj.conf index de139770a43d74..c117dd823f3e85 100755 --- a/examples/ota-requestor-app/telink/prj.conf +++ b/examples/ota-requestor-app/telink/prj.conf @@ -26,9 +26,7 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=y -CONFIG_OPENTHREAD_FTD=n CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings @@ -54,16 +52,14 @@ CONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING="2022" # Enable CHIP pairing automatically on application start. CONFIG_CHIP_ENABLE_PAIRING_AUTOSTART=y +# Disable factory data support. +CONFIG_CHIP_FACTORY_DATA=n +CONFIG_CHIP_FACTORY_DATA_BUILD=n +CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n +CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE=n + # CHIP shell CONFIG_CHIP_LIB_SHELL=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management CONFIG_PM=n -CONFIG_PM_DEVICE=n -CONFIG_CHIP_ENABLE_PM_DURING_BLE=n diff --git a/examples/ota-requestor-app/telink/src/AppTask.cpp b/examples/ota-requestor-app/telink/src/AppTask.cpp index 8cc0cea6e3992d..1742873befdf66 100644 --- a/examples/ota-requestor-app/telink/src/AppTask.cpp +++ b/examples/ota-requestor-app/telink/src/AppTask.cpp @@ -18,501 +18,20 @@ #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 -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include - -#include - -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL - LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; - -namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kEndpointId = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; -constexpr uint32_t kIdentifyBlinkRateMs = 200; -constexpr uint32_t kIdentifyOkayOnRateMs = 50; -constexpr uint32_t kIdentifyOkayOffRateMs = 950; -constexpr uint32_t kIdentifyFinishOnRateMs = 950; -constexpr uint32_t kIdentifyFinishOffRateMs = 50; -constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; -constexpr uint32_t kIdentifyBreatheRateMs = 1000; - -const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; -#endif - -Button sFactoryResetButton; -Button sThreadStartButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - -void OnIdentifyTriggerEffect(Identify * identify) -{ - AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); -} - -Identify sIdentify = { - kEndpointId, - [](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(); - } - } -}; - -constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; - CHIP_ERROR AppTask::Init(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); - - // Initialize LEDs -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); -#endif - - 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(); - chip::Server::GetInstance().Init(initParams); - - // Initialize PWM Identify led - CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("Green IDENTIFY PWM Device Init fail"); - return err; - } - - sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); - - // We only have network commissioning on endpoint 0. - // Set up a valid Network Commissioning cluster on endpoint 0 is done in - // src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.cpp - emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); + InitCommonParts(); - // Initialize device attestation config - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); - - gExampleDeviceInfoProvider.SetStorageDelegate(&chip::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); - - err = ConnectivityMgr().SetBLEDeviceName("TelinkOTAReq"); + CHIP_ERROR err = ConnectivityMgr().SetBLEDeviceName("TelinkOTAReq"); 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; } - -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) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&event); - } -} - -void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) -{ - AppEvent event; - event.Type = AppEvent::kEventType_IdentifyStart; - - switch (aEffect) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); - event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; - event.Type = AppEvent::kEventType_IdentifyStop; - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - return; - } - - 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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -void AppTask::StartThreadButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartThreadHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartThreadHandler(AppEvent * aEvent) -{ - LOG_INF("StartThreadHandler"); - if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) - { - // Switch context from BLE to Thread - Internal::BLEManagerImpl sInstance; - sInstance.SwitchToIeee802154(); - StartDefaultThreadNetwork(); - } - else - { - LOG_INF("Device already commissioned"); - } -} - -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadConnectivityChange: -#if CONFIG_CHIP_OTA_REQUESTOR - if (event->ThreadConnectivityChange.Result == kConnectivity_Established) - { - InitBasicOTARequestor(); - } -#endif - break; - default: - break; - } -} - -void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_UpdateLedState; - event.Handler = UpdateIdentifyStateEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) -{ - sAppTask.mPwmIdentifyLed.UpdateAction(); -} - -void AppTask::ActionInitiated(AppTask::Action_t aAction, int32_t aActor) {} - -void AppTask::ActionCompleted(AppTask::Action_t aAction, int32_t aActor) {} - -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::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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - 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); -#endif - - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sThreadStartButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} diff --git a/examples/ota-requestor-app/telink/src/main.cpp b/examples/ota-requestor-app/telink/src/main.cpp deleted file mode 100644 index dc8216db43d274..00000000000000 --- a/examples/ota-requestor-app/telink/src/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright (c) 2022-2023 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, CONFIG_CHIP_APP_LOG_LEVEL); - -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/platform/esp32/common/Esp32AppServer.cpp b/examples/platform/esp32/common/Esp32AppServer.cpp index 448463033c383e..91120707b9504c 100644 --- a/examples/platform/esp32/common/Esp32AppServer.cpp +++ b/examples/platform/esp32/common/Esp32AppServer.cpp @@ -35,6 +35,9 @@ namespace { #if CHIP_DEVICE_CONFIG_ENABLE_WIFI app::Clusters::NetworkCommissioning::Instance sWiFiNetworkCommissioningInstance(0 /* Endpoint Id */, &(NetworkCommissioning::ESPWiFiDriver::GetInstance())); +#elif CHIP_DEVICE_CONFIG_ENABLE_ETHERNET +static app::Clusters::NetworkCommissioning::Instance + sEthernetNetworkCommissioningInstance(0 /* Endpoint Id */, &(NetworkCommissioning::ESPEthernetDriver::GetInstance())); #endif #if CONFIG_TEST_EVENT_TRIGGER_ENABLED diff --git a/examples/platform/esp32/mode-support/static-supported-modes-manager.cpp b/examples/platform/esp32/mode-support/static-supported-modes-manager.cpp new file mode 100644 index 00000000000000..ec752cd8be67ba --- /dev/null +++ b/examples/platform/esp32/mode-support/static-supported-modes-manager.cpp @@ -0,0 +1,209 @@ +/* + * + * Copyright (c) 2023 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 "static-supported-modes-manager.h" +#include +#include +#include + +using namespace chip; +using namespace chip::app::Clusters; +using namespace chip::DeviceLayer::Internal; +using namespace chip::app::Clusters::ModeSelect; +using chip::Protocols::InteractionModel::Status; + +using ModeOptionStructType = Structs::ModeOptionStruct::Type; +using SemanticTag = Structs::SemanticTagStruct::Type; +template +using List = app::DataModel::List; + +const StaticSupportedModesManager StaticSupportedModesManager::instance = StaticSupportedModesManager(); + +SupportedModesManager::ModeOptionsProvider StaticSupportedModesManager::epModeOptionsProviderList[FIXED_ENDPOINT_COUNT]; + +void StaticSupportedModesManager::InitEndpointArray() +{ + for (int i = 0; i < FIXED_ENDPOINT_COUNT; i++) + { + epModeOptionsProviderList[i] = ModeOptionsProvider(); + } +} + +SupportedModesManager::ModeOptionsProvider StaticSupportedModesManager::getModeOptionsProvider(EndpointId endpointId) const +{ + if (epModeOptionsProviderList[endpointId].begin() != nullptr && epModeOptionsProviderList[endpointId].end() != nullptr) + { + return ModeOptionsProvider(epModeOptionsProviderList[endpointId].begin(), epModeOptionsProviderList[endpointId].end()); + } + + ModeOptionStructType * modeOptionStructList = nullptr; + SemanticTag * semanticTags = nullptr; + + char keyBuf[ESP32Config::kMaxConfigKeyNameLength]; + uint32_t supportedModeCount = 0; + + VerifyOrReturnValue(ESP32Config::KeyAllocator::SupportedModesCount(keyBuf, sizeof(keyBuf), endpointId) == CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr)); + ESP32Config::Key countKey(ESP32Config::kConfigNamespace_ChipFactory, keyBuf); + VerifyOrReturnValue(ESP32Config::ReadConfigValue(countKey, supportedModeCount) == CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr)); + + modeOptionStructList = new ModeOptionStructType[supportedModeCount]; + if (modeOptionStructList == nullptr) + { + return ModeOptionsProvider(nullptr, nullptr); + } + + epModeOptionsProviderList[endpointId] = ModeOptionsProvider(modeOptionStructList, modeOptionStructList + supportedModeCount); + + for (int index = 0; index < supportedModeCount; index++) + { + Structs::ModeOptionStruct::Type option; + uint32_t supportedModeMode = 0; + uint32_t semanticTagCount = 0; + size_t outLen = 0; + + memset(keyBuf, 0, sizeof(char) * ESP32Config::kMaxConfigKeyNameLength); + VerifyOrReturnValue(ESP32Config::KeyAllocator::SupportedModesLabel(keyBuf, sizeof(keyBuf), endpointId, index) == + CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + ESP32Config::Key labelKey(ESP32Config::kConfigNamespace_ChipFactory, keyBuf); + VerifyOrReturnValue(ESP32Config::ReadConfigValueStr(labelKey, nullptr, 0, outLen) == CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + + char * modeLabel = new char[outLen + 1]; + if (modeLabel == nullptr) + { + CleanUp(endpointId); + return ModeOptionsProvider(nullptr, nullptr); + } + + VerifyOrReturnValue(ESP32Config::ReadConfigValueStr(labelKey, modeLabel, outLen + 1, outLen) == CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + + memset(keyBuf, 0, sizeof(char) * ESP32Config::kMaxConfigKeyNameLength); + VerifyOrReturnValue(ESP32Config::KeyAllocator::SupportedModesValue(keyBuf, sizeof(keyBuf), endpointId, index) == + CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + ESP32Config::Key modeKey(ESP32Config::kConfigNamespace_ChipFactory, keyBuf); + VerifyOrReturnValue(ESP32Config::ReadConfigValue(labelKey, supportedModeMode) == CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + + memset(keyBuf, 0, sizeof(char) * ESP32Config::kMaxConfigKeyNameLength); + VerifyOrReturnValue(ESP32Config::KeyAllocator::SemanticTagsCount(keyBuf, sizeof(keyBuf), endpointId, index) == + CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + ESP32Config::Key stCountKey(ESP32Config::kConfigNamespace_ChipFactory, keyBuf); + VerifyOrReturnValue(ESP32Config::ReadConfigValue(stCountKey, semanticTagCount) == CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + + semanticTags = new SemanticTag[semanticTagCount]; + if (semanticTags == nullptr) + { + CleanUp(endpointId); + return ModeOptionsProvider(nullptr, nullptr); + } + for (auto stIndex = 0; stIndex < semanticTagCount; stIndex++) + { + + uint32_t semanticTagValue = 0; + uint32_t semanticTagMfgCode = 0; + SemanticTag tag; + + memset(keyBuf, 0, sizeof(char) * ESP32Config::kMaxConfigKeyNameLength); + VerifyOrReturnValue(ESP32Config::KeyAllocator::SemanticTagValue(keyBuf, sizeof(keyBuf), endpointId, index, stIndex) == + CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + ESP32Config::Key stValueKey(ESP32Config::kConfigNamespace_ChipFactory, keyBuf); + VerifyOrReturnValue(ESP32Config::ReadConfigValue(stValueKey, semanticTagValue) == CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + + memset(keyBuf, 0, sizeof(char) * ESP32Config::kMaxConfigKeyNameLength); + VerifyOrReturnValue(ESP32Config::KeyAllocator::SemanticTagMfgCode(keyBuf, sizeof(keyBuf), endpointId, index, stIndex) == + CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + ESP32Config::Key stMfgCodeKey(ESP32Config::kConfigNamespace_ChipFactory, keyBuf); + VerifyOrReturnValue(ESP32Config::ReadConfigValue(stMfgCodeKey, semanticTagMfgCode) == CHIP_NO_ERROR, + ModeOptionsProvider(nullptr, nullptr), CleanUp(endpointId)); + + tag.value = static_cast(semanticTagValue); + tag.mfgCode = static_cast(semanticTagMfgCode); + semanticTags[stIndex] = tag; + } + + option.label = chip::CharSpan::fromCharString(modeLabel); + option.mode = static_cast(supportedModeMode); + option.semanticTags = DataModel::List(semanticTags, semanticTagCount); + + modeOptionStructList[index] = option; + } + + return ModeOptionsProvider(modeOptionStructList, modeOptionStructList + supportedModeCount); +} + +Status StaticSupportedModesManager::getModeOptionByMode(unsigned short endpointId, unsigned char mode, + const ModeOptionStructType ** dataPtr) const +{ + auto modeOptionsProvider = this->getModeOptionsProvider(endpointId); + if (modeOptionsProvider.begin() == nullptr) + { + return Status::UnsupportedCluster; + } + auto * begin = modeOptionsProvider.begin(); + auto * end = modeOptionsProvider.end(); + + for (auto * it = begin; it != end; ++it) + { + auto & modeOption = *it; + if (modeOption.mode == mode) + { + *dataPtr = &modeOption; + return Status::Success; + } + } + emberAfPrintln(EMBER_AF_PRINT_DEBUG, "Cannot find the mode %u", mode); + return Status::InvalidCommand; +} + +const ModeSelect::SupportedModesManager * ModeSelect::getSupportedModesManager() +{ + return &StaticSupportedModesManager::instance; +} + +void StaticSupportedModesManager::FreeSupportedModes(EndpointId endpointId) const +{ + if (epModeOptionsProviderList[endpointId].begin() != nullptr) + { + auto * begin = epModeOptionsProviderList[endpointId].begin(); + auto * end = epModeOptionsProviderList[endpointId].end(); + for (auto * it = begin; it != end; ++it) + { + auto & modeOption = *it; + delete[] modeOption.label.data(); + delete[] modeOption.semanticTags.data(); + } + delete[] begin; + } + epModeOptionsProviderList[endpointId] = ModeOptionsProvider(); +} + +void StaticSupportedModesManager::CleanUp(EndpointId endpointId) const +{ + ChipLogError(Zcl, "Supported mode data is in incorrect format"); + FreeSupportedModes(endpointId); +} diff --git a/examples/platform/esp32/mode-support/static-supported-modes-manager.h b/examples/platform/esp32/mode-support/static-supported-modes-manager.h new file mode 100644 index 00000000000000..689c9d059f4ab7 --- /dev/null +++ b/examples/platform/esp32/mode-support/static-supported-modes-manager.h @@ -0,0 +1,69 @@ +/* + * + * Copyright (c) 2023 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +namespace chip { +namespace app { +namespace Clusters { +namespace ModeSelect { + +class StaticSupportedModesManager : public chip::app::Clusters::ModeSelect::SupportedModesManager +{ +private: + using ModeOptionStructType = Structs::ModeOptionStruct::Type; + using SemanticTag = Structs::SemanticTagStruct::Type; + + static ModeOptionsProvider epModeOptionsProviderList[FIXED_ENDPOINT_COUNT]; + + void InitEndpointArray(); + + void FreeSupportedModes(EndpointId endpointId) const; + +public: + static const StaticSupportedModesManager instance; + + SupportedModesManager::ModeOptionsProvider getModeOptionsProvider(EndpointId endpointId) const override; + + Protocols::InteractionModel::Status getModeOptionByMode(EndpointId endpointId, uint8_t mode, + const ModeOptionStructType ** dataPtr) const override; + + void CleanUp(EndpointId endpointId) const; + + StaticSupportedModesManager() { InitEndpointArray(); } + + ~StaticSupportedModesManager() + { + for (int i = 0; i < FIXED_ENDPOINT_COUNT; i++) + { + FreeSupportedModes(i); + } + } + + static inline const StaticSupportedModesManager & getStaticSupportedModesManagerInstance() { return instance; } +}; + +const SupportedModesManager * getSupportedModesManager(); + +} // namespace ModeSelect +} // namespace Clusters +} // namespace app +} // namespace chip diff --git a/examples/platform/nrfconnect/util/ICDUtil.cpp b/examples/platform/nrfconnect/util/ICDUtil.cpp new file mode 100644 index 00000000000000..fd2130c6c22dcb --- /dev/null +++ b/examples/platform/nrfconnect/util/ICDUtil.cpp @@ -0,0 +1,40 @@ +/* + * + * Copyright (c) 2023 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 "ICDUtil.h" + +ICDUtil ICDUtil::sICDUtil; + +CHIP_ERROR ICDUtil::OnSubscriptionRequested(chip::app::ReadHandler & aReadHandler, chip::Transport::SecureSession & aSecureSession) +{ + uint16_t agreedMaxInterval = CONFIG_CHIP_MAX_PREFERRED_SUBSCRIPTION_REPORT_INTERVAL; + uint16_t requestedMinInterval = 0; + uint16_t requestedMaxInterval = 0; + aReadHandler.GetReportingIntervals(requestedMinInterval, requestedMaxInterval); + + if (requestedMaxInterval > agreedMaxInterval) + { + agreedMaxInterval = requestedMaxInterval; + } + else if (agreedMaxInterval > kSubscriptionMaxIntervalPublisherLimit) + { + agreedMaxInterval = kSubscriptionMaxIntervalPublisherLimit; + } + + return aReadHandler.SetReportingIntervals(agreedMaxInterval); +} diff --git a/examples/temperature-measurement-app/telink/include/AppEvent.h b/examples/platform/nrfconnect/util/include/ICDUtil.h similarity index 52% rename from examples/temperature-measurement-app/telink/include/AppEvent.h rename to examples/platform/nrfconnect/util/include/ICDUtil.h index d38fb150212a85..33db1e97a051ac 100644 --- a/examples/temperature-measurement-app/telink/include/AppEvent.h +++ b/examples/platform/nrfconnect/util/include/ICDUtil.h @@ -1,7 +1,6 @@ /* * * Copyright (c) 2023 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. @@ -18,40 +17,17 @@ #pragma once -#include +#include -struct AppEvent; -typedef void (*EventHandler)(AppEvent *); - -class LEDWidget; - -struct AppEvent +class ICDUtil : public chip::app::ReadHandler::ApplicationCallback { - enum AppEventTypes - { - kEventType_Button = 0, - kEventType_Timer, - kEventType_UpdateLedState, - kEventType_Install, - }; - - uint16_t Type; - - union - { - struct - { - uint8_t Action; - } ButtonEvent; - struct - { - void * Context; - } TimerEvent; - struct - { - LEDWidget * LedWidget; - } UpdateLedStateEvent; - }; - - EventHandler Handler; + CHIP_ERROR OnSubscriptionRequested(chip::app::ReadHandler & aReadHandler, + chip::Transport::SecureSession & aSecureSession) override; + friend ICDUtil & GetICDUtil(); + static ICDUtil sICDUtil; }; + +inline ICDUtil & GetICDUtil() +{ + return ICDUtil::sICDUtil; +} diff --git a/examples/platform/silabs/SiWx917/MemMonitoring.cpp b/examples/platform/silabs/MemMonitoring.cpp similarity index 100% rename from examples/platform/silabs/SiWx917/MemMonitoring.cpp rename to examples/platform/silabs/MemMonitoring.cpp diff --git a/examples/platform/silabs/SiWx917/OTAConfig.cpp b/examples/platform/silabs/OTAConfig.cpp similarity index 100% rename from examples/platform/silabs/SiWx917/OTAConfig.cpp rename to examples/platform/silabs/OTAConfig.cpp diff --git a/examples/platform/silabs/efr32/OTAConfig.h b/examples/platform/silabs/OTAConfig.h similarity index 94% rename from examples/platform/silabs/efr32/OTAConfig.h rename to examples/platform/silabs/OTAConfig.h index cdd2163a10084e..2d5dbcf3635223 100644 --- a/examples/platform/silabs/efr32/OTAConfig.h +++ b/examples/platform/silabs/OTAConfig.h @@ -22,7 +22,7 @@ #include #include #include -#include +#include class OTAConfig { diff --git a/examples/platform/silabs/SiWx917/BUILD.gn b/examples/platform/silabs/SiWx917/BUILD.gn index f10af3deca4d79..098829c4cde527 100644 --- a/examples/platform/silabs/SiWx917/BUILD.gn +++ b/examples/platform/silabs/SiWx917/BUILD.gn @@ -147,14 +147,10 @@ source_set("siwx917-attestation-credentials") { public_configs = [ ":attestation-credentials-config" ] } -source_set("siwx917-factory-data-provider") { - if (siwx917_commissionable_data) { - defines = [ "SIWX917_USE_COMISSIONABLE_DATA=1" ] - } - +source_set("silabs-factory-data-provider") { sources = [ - "SiWx917DeviceDataProvider.cpp", - "SiWx917DeviceDataProvider.h", + "${silabs_common_plat_dir}/SilabsDeviceDataProvider.cpp", + "${silabs_common_plat_dir}/SilabsDeviceDataProvider.h", ] public_deps = [ @@ -162,13 +158,15 @@ source_set("siwx917-factory-data-provider") { "${chip_root}/src/platform:platform_base", "${chip_root}/src/setup_payload", ] + + public_configs = [ ":siwx917-common-config" ] } config("siwx917-common-config") { defines = [ "OTA_PERIODIC_TIMEOUT=${ota_periodic_query_timeout_sec}" ] if (!disable_lcd) { - include_dirs = [ "display" ] + include_dirs = [ "${silabs_common_plat_dir}/display" ] defines += [ "DISPLAY_ENABLED" ] } @@ -178,12 +176,16 @@ config("siwx917-common-config") { } if (chip_enable_ota_requestor) { - defines += [ "EFR32_OTA_ENABLED" ] + defines += [ "SILABS_OTA_ENABLED" ] } if (enable_heap_monitoring) { defines += [ "HEAP_MONITORING" ] } + + if (siwx917_commissionable_data) { + defines += [ "SIWX917_USE_COMISSIONABLE_DATA=1" ] + } } config("silabs-wifi-config") { @@ -264,16 +266,16 @@ source_set("siwx917-common") { if (!disable_lcd) { sources += [ - "display/demo-ui.c", - "display/lcd.cpp", + "${silabs_common_plat_dir}/display/demo-ui.c", + "${silabs_common_plat_dir}/display/lcd.cpp", ] - include_dirs += [ "display" ] + include_dirs += [ "${silabs_common_plat_dir}/display" ] public_deps += [ "${chip_root}/examples/common/QRCode" ] } if (enable_heap_monitoring) { - sources += [ "MemMonitoring.cpp" ] + sources += [ "${silabs_common_plat_dir}/MemMonitoring.cpp" ] } if (chip_enable_wifi) { @@ -291,7 +293,7 @@ source_set("siwx917-common") { # Factory Data Provider if (use_efr32_factory_data_provider) { - public_deps += [ ":siwx917-factory-data-provider" ] + public_deps += [ ":silabs-factory-data-provider" ] } public_deps += [ diff --git a/examples/platform/silabs/SiWx917/BaseApplication.cpp b/examples/platform/silabs/SiWx917/BaseApplication.cpp index b0f3809876ab49..4ed8ea273e0a5f 100644 --- a/examples/platform/silabs/SiWx917/BaseApplication.cpp +++ b/examples/platform/silabs/SiWx917/BaseApplication.cpp @@ -36,7 +36,7 @@ #endif // QR_CODE_ENABLED #endif // DISPLAY_ENABLED -#include "SiWx917DeviceDataProvider.h" +#include "SilabsDeviceDataProvider.h" #include "rsi_board.h" #include "rsi_chip.h" #include "siwx917_utils.h" @@ -214,7 +214,7 @@ CHIP_ERROR BaseApplication::Init(Identify * identifyObj) char qrCodeBuffer[chip::QRCodeBasicSetupPayloadGenerator::kMaxQRCodeBase38RepresentationLength + 1]; chip::MutableCharSpan QRCode(qrCodeBuffer); - if (SIWx917::SIWx917DeviceDataProvider::GetDeviceDataProvider().GetSetupPayload(QRCode) == CHIP_NO_ERROR) + if (Silabs::SilabsDeviceDataProvider::GetDeviceDataProvider().GetSetupPayload(QRCode) == CHIP_NO_ERROR) { // Print setup info on LCD if available #ifdef QR_CODE_ENABLED diff --git a/examples/platform/silabs/SiWx917/LEDWidget.h b/examples/platform/silabs/SiWx917/LEDWidget.h index f033cb26c50f64..596f64af094d7a 100644 --- a/examples/platform/silabs/SiWx917/LEDWidget.h +++ b/examples/platform/silabs/SiWx917/LEDWidget.h @@ -19,9 +19,11 @@ #pragma once -#include "rsi_board.h" #include +extern "C" void RSI_Board_LED_Set(int, int); +extern "C" void RSI_Board_LED_Toggle(int); + class LEDWidget { public: diff --git a/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_m4.c b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_m4.c index 87d998e0e0ddbb..bcedf1c8a52c16 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_m4.c +++ b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_m4.c @@ -92,9 +92,10 @@ void IRQ021_Handler(void) btn1 = 0; sl_button_on_change(1, 1); } - if (RSI_NPSSGPIO_GetPin(NPSS_GPIO_0)) + if (RSI_NPSSGPIO_GetPin(NPSS_GPIO_0) && (!btn0)) { btn0 = 1; + sl_button_on_change(0, 0); } if (!RSI_NPSSGPIO_GetPin(NPSS_GPIO_0) && btn0) { diff --git a/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_timer.c b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_timer.c index e7141d4646060c..023fb47497ca1f 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_timer.c +++ b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_timer.c @@ -23,7 +23,7 @@ #ifdef RSI_WITH_OS /* FreeRTOS includes. */ #include "FreeRTOS.h" -#include "StackMacros.h" +#include "stack_macros.h" #include "task.h" #include "timers.h" diff --git a/examples/platform/silabs/SiWx917/SiWx917/rsi_if.c b/examples/platform/silabs/SiWx917/SiWx917/rsi_if.c index 403dff68ce6a2f..745586a9868852 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/rsi_if.c +++ b/examples/platform/silabs/SiWx917/SiWx917/rsi_if.c @@ -491,14 +491,14 @@ static void wfx_rsi_do_join(void) void wfx_rsi_task(void * arg) { EventBits_t flags; - int32_t status = 0; + int32_t status; TickType_t last_dhcp_poll, now; struct netif * sta_netif; (void) arg; - uint32_t rsi_status = wfx_rsi_init(); - if (rsi_status != RSI_SUCCESS) + status = wfx_rsi_init(); + if (status != RSI_SUCCESS) { - SILABS_LOG("%s: error: wfx_rsi_init with status: %02x", __func__, rsi_status); + SILABS_LOG("%s: error: wfx_rsi_init with status: %02x", __func__, status); return; } wfx_lwip_start(); diff --git a/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h index 1a586931be5f18..09a44344bafb45 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h +++ b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h @@ -89,6 +89,7 @@ int32_t wfx_rsi_get_ap_info(wfx_wifi_scan_result_t * ap); int32_t wfx_rsi_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); int32_t wfx_rsi_reset_count(); int32_t wfx_rsi_disconnect(); +int32_t wfx_rsi_init_platform(); #define SILABS_LOG(...) efr32Log(__VA_ARGS__); #ifdef __cplusplus diff --git a/examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.h b/examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.h deleted file mode 100644 index 2301a21644206d..00000000000000 --- a/examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#pragma once - -#include -#include - -namespace chip { -namespace DeviceLayer { -namespace SIWx917 { - -/** - * @brief This class provides Commissionable data, Device Attestation Credentials, - * and Device Instance Info. - */ - -class SIWx917DeviceDataProvider : public CommissionableDataProvider, - public Internal::GenericDeviceInstanceInfoProvider -{ -public: - SIWx917DeviceDataProvider() : - CommissionableDataProvider(), Internal::GenericDeviceInstanceInfoProvider( - ConfigurationManagerImpl::GetDefaultInstance()) - {} - - static SIWx917DeviceDataProvider & GetDeviceDataProvider(); - CHIP_ERROR GetSetupPayload(MutableCharSpan & payloadBuf); -#ifdef SIWX917_USE_COMISSIONABLE_DATA - void setupPayload(uint8_t * outBuf); - CHIP_ERROR FlashFactoryData(); -#endif /* SIWX917_USE_COMISSIONABLE_DATA */ - // ===== Members functions that implement the CommissionableDataProvider - CHIP_ERROR GetSetupDiscriminator(uint16_t & setupDiscriminator) override; - CHIP_ERROR SetSetupDiscriminator(uint16_t setupDiscriminator) override { return CHIP_ERROR_NOT_IMPLEMENTED; } - CHIP_ERROR GetSpake2pIterationCount(uint32_t & iterationCount) override; - CHIP_ERROR GetSpake2pSalt(MutableByteSpan & saltBuf) override; - CHIP_ERROR GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) override; - // Per spec 5.1.7. Passcode cannot be stored on the device - CHIP_ERROR GetSetupPasscode(uint32_t & setupPasscode) override { return CHIP_ERROR_NOT_IMPLEMENTED; }; - CHIP_ERROR SetSetupPasscode(uint32_t setupPasscode) override { return CHIP_ERROR_NOT_IMPLEMENTED; } - - // ===== Members functions that implement the GenericDeviceInstanceInfoProvider - CHIP_ERROR GetVendorName(char * buf, size_t bufSize) override; - CHIP_ERROR GetVendorId(uint16_t & vendorId) override; - CHIP_ERROR GetProductName(char * buf, size_t bufSize) override; - CHIP_ERROR GetProductId(uint16_t & productId) override; - CHIP_ERROR GetHardwareVersionString(char * buf, size_t bufSize) override; - CHIP_ERROR GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) override; - CHIP_ERROR GetSerialNumber(char * buf, size_t bufSize) override; - CHIP_ERROR GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) override; - CHIP_ERROR GetHardwareVersion(uint16_t & hardwareVersion) override; -}; - -} // namespace SIWx917 -} // namespace DeviceLayer -} // namespace chip diff --git a/examples/platform/silabs/SiWx917/device/src/startup_RS1xxxx.c b/examples/platform/silabs/SiWx917/device/src/startup_RS1xxxx.c index a62ea68bbbef12..db9b05fad220bb 100644 --- a/examples/platform/silabs/SiWx917/device/src/startup_RS1xxxx.c +++ b/examples/platform/silabs/SiWx917/device/src/startup_RS1xxxx.c @@ -37,11 +37,11 @@ __attribute__((section(".co_stack"))) unsigned long pulStack[STACK_SIZE]; #define WEAK __attribute__((weak)) /*----------Declaration of the default fault handlers-------------------------*/ -// #ifndef __START -// extern void _start(void) __attribute__((noreturn)); /* Pre Main (C library entry point) */ -// #else -// extern int __START(void) __attribute__((noreturn)); /* main entry point */ -// #endif +#ifndef __START +extern void _start(void) __attribute__((noreturn)); /* Pre Main (C library entry point) */ +#else +extern int __START(void) __attribute__((noreturn)); /* main entry point */ +#endif /* System exception vector handler */ __attribute__((used)) void WEAK Reset_Handler(void); diff --git a/examples/platform/silabs/SiWx917/display/demo-ui-bitmaps.h b/examples/platform/silabs/SiWx917/display/demo-ui-bitmaps.h deleted file mode 100644 index 4eca9c0c48e7aa..00000000000000 --- a/examples/platform/silabs/SiWx917/display/demo-ui-bitmaps.h +++ /dev/null @@ -1,356 +0,0 @@ -/***************************************************************************/ /** - * @file - * @brief User Interface bitmaps for demo. - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. - *www.silabs.com - ******************************************************************************* - * - * The licensor of this software is Silicon - *Laboratories Inc. Your use of this software is - *governed by the terms of Silicon Labs Master - *Software License Agreement (MSLA) available at - * www.silabs.com/about-us/legal/master-software-license-agreement. - *This software is distributed to you in Source Code - *format and is governed by the sections of the MSLA - *applicable to Source Code. - * - ******************************************************************************/ - -#ifndef SILABS_DEMO_UI_BITMAPS_H -#define SILABS_DEMO_UI_BITMAPS_H - -#define SILICONLABS_BITMAP_WIDTH 128 -#define SILICONLABS_BITMAP_HEIGHT 45 - -#define ZIGBEE_BITMAP_WIDTH 16 -#define ZIGBEE_BITMAP_HEIGHT 16 - -#define RAIL_BITMAP_WIDTH 16 -#define RAIL_BITMAP_HEIGHT 16 - -#define CONNECT_BITMAP_WIDTH 16 -#define CONNECT_BITMAP_HEIGHT 16 - -#define BLUETOOTH_BITMAP_WIDTH 16 -#define BLUETOOTH_BITMAP_HEIGHT 18 - -#define SILABS_BITMAP \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0xf0, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xfd, 0xff, 0xff, 0x01, 0x00, 0x00, 0xc0, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x9f, 0xff, 0xff, 0x3f, 0x00, \ - 0x00, 0x00, 0x00, 0xff, 0xff, 0x1f, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xf3, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0xfe, \ - 0xff, 0x1f, 0xf8, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0x1f, 0xf0, 0xff, \ - 0xff, 0xff, 0x1f, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0x1f, 0xe0, 0xff, 0xff, 0xff, 0xc3, 0xff, \ - 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0x0f, 0xc0, 0xff, 0xff, 0xff, 0xf0, 0xff, 0xff, 0x07, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0xff, 0xff, 0x07, 0xc0, 0xff, 0xff, 0x1f, 0xf8, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, \ - 0xff, 0x01, 0xc0, 0xff, 0xff, 0x07, 0xfc, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x7f, 0x00, 0x80, 0xff, \ - 0xff, 0x01, 0xfe, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x0f, 0x00, 0x80, 0xff, 0x7f, 0x00, 0xff, 0xff, \ - 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x3f, 0x80, 0xff, 0xff, 0xff, 0x00, 0x00, 0xf0, \ - 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x0f, 0x80, 0xff, 0xff, 0xff, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0x01, \ - 0x00, 0x00, 0xc0, 0xff, 0x03, 0xc0, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0xe0, 0xff, \ - 0x01, 0xc0, 0xff, 0xff, 0xff, 0xf1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xe0, 0xff, 0x00, 0xc0, 0xff, 0xff, \ - 0xff, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf0, 0x7f, 0x00, 0x80, 0xff, 0xff, 0xff, 0x0f, 0xfc, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0x07, 0x00, 0xf8, 0x3f, 0x00, 0x80, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, \ - 0x0f, 0x00, 0xfc, 0x1f, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0xc0, 0xff, 0xff, 0xff, 0x0f, 0x00, 0xfe, 0x0f, \ - 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0xff, 0xff, 0xff, 0x1f, 0x00, 0xff, 0x07, 0x00, 0x00, 0xf0, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0x3f, 0xfc, 0xff, 0xff, 0x1f, 0x80, 0xff, 0x07, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0x3f, 0xf8, 0xff, 0xff, 0x1f, 0xc0, 0xff, 0x03, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0x00, 0xf0, 0xff, 0xff, \ - 0x0f, 0xf0, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0x3f, 0x00, 0x00, 0xf0, 0xff, 0xff, 0x0f, 0xfc, 0xff, 0x03, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0x07, 0xfe, 0xff, 0x01, 0x00, 0x00, 0x3f, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0x83, 0xff, 0xff, 0x01, 0x00, 0xc0, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0xfc, 0xff, 0xff, 0xe1, 0xff, 0xff, 0x03, 0x00, 0xf0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, \ - 0xf8, 0xff, 0xff, 0x03, 0x00, 0xf8, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3f, 0xff, 0xff, 0xff, 0x03, \ - 0x00, 0xfe, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xdf, 0xff, 0xff, 0xff, 0x07, 0x00, 0xff, 0xff, 0x01, \ - 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x80, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, \ - 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0xc0, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0x3f, 0xc0, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xc0, 0xff, 0xff, 0xff, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0xff, 0xff, 0xff, \ - 0x1f, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff - -#define THREAD_BITMAP_WIDTH 16 -#define THREAD_BITMAP_HEIGHT 18 - -#define THREAD_BITMAP \ - 0x1F, 0xF8, 0x07, 0xE0, 0x03, 0xCE, 0x01, 0x9F, 0x01, 0xB3, 0x00, 0x33, 0xF0, 0x3F, 0xF8, 0x1F, 0x0C, 0x03, 0x0C, 0x03, 0x18, \ - 0x03, 0x11, 0x83, 0x01, 0x83, 0x03, 0xC3, 0x07, 0xE3, 0x1F, 0xFB, 0x7f, 0xff, 0xff, 0xff - -#define WIFI_BITMAP_WIDTH 18 -#define WIFI_BITMAP_HEIGHT 18 - -#define WIFI_BITMAP \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0xFF, 0x01, 0xE0, 0x03, 0x00, 0xC7, 0xFF, 0xB8, 0xFF, 0xF7, 0x07, 0xF8, 0x0F, 0xC0, 0x3F, \ - 0x3F, 0xFF, 0xFF, 0xFF, 0x3F, 0xFF, 0x7F, 0xF8, 0xFF, 0xE1, 0xFF, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F - -#define MATTER_LOGO_WIDTH 18 -#define MATTER_LOGO_HEIGHT 17 - -#define MATTER_LOGO_BITMAP \ - 0xFF, 0xFF, 0xFF, 0xF3, 0xFF, 0xCF, 0xFF, 0x3F, 0xFF, 0xFF, 0xFC, 0x3F, 0x12, 0xFF, 0x01, 0xFE, 0xFF, 0xFF, 0xF3, 0x3F, 0x8F, \ - 0x7F, 0xFC, 0xFC, 0xFC, 0xE3, 0xF1, 0x87, 0x87, 0xC7, 0xDE, 0x88, 0x33, 0xC7, 0xCF, 0xFC, 0xFF, 0xFF, 0x03 - -// APP Logo, boolean only. must be 64x64 -#if IS_DEMO_SWITCH -#define ON_DEMO_BITMAP \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, \ - 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0xC0, 0xFF, 0xFF, 0x03, 0xF8, 0xFF, 0xFF, 0x1F, 0xE0, 0xFF, 0xFF, \ - 0x07, 0xF8, 0xFF, 0xFF, 0x1F, 0xE0, 0xFF, 0xFF, 0x07, 0xF8, 0xFF, 0xFF, 0x1F, 0xE0, 0xFF, 0xFF, 0x07, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0xE0, 0xFF, 0xFF, 0x07, 0xF8, 0xFF, 0xFF, 0x1F, 0xE0, 0xFF, 0xFF, 0x07, 0xF8, 0xFF, 0xFF, 0x1F, 0xE0, 0xFF, 0xFF, \ - 0x07, 0xF8, 0xFF, 0xFF, 0x1F, 0xE0, 0xFF, 0xFF, 0x07, 0xF8, 0xFF, 0xFF, 0x1F, 0xE0, 0xFF, 0xFF, 0x07, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0xC0, 0xFF, 0xFF, 0x03, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, \ - 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, \ - 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF - -#define OFF_DEMO_BITMAP \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, \ - 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, \ - 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0xF8, 0xFF, 0xFF, 0x1F, 0xFC, 0xFF, 0xFF, 0x3F, 0xF8, 0xFF, 0xFF, 0x1F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0x3C, 0x00, 0x00, 0x3C, 0xFC, 0xFF, 0xFF, 0x3F, 0x3C, 0x00, 0x00, 0x3C, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0x3C, 0x00, 0x00, 0x3C, 0xFC, 0xFF, 0xFF, 0x3F, 0x3C, 0x00, 0x00, 0x3C, 0xFC, 0xFF, 0xFF, 0x3F, 0x3C, 0x00, 0x00, \ - 0x3C, 0xFC, 0xFF, 0xFF, 0x3F, 0x3C, 0x00, 0x00, 0x3C, 0xFC, 0xFF, 0xFF, 0x3F, 0x3C, 0x00, 0x00, 0x3C, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0x3C, 0x00, 0x00, 0x3C, 0xFC, 0xFF, 0xFF, 0x3F, 0x3C, 0x00, 0x00, 0x3C, 0xFC, 0xFF, 0xFF, 0x3F, 0x3C, 0x00, 0x00, \ - 0x3C, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0x3F, 0xF8, 0xFF, 0xFF, 0x1F, 0xFC, 0xFF, 0xFF, \ - 0x3F, 0xF8, 0xFF, 0xFF, 0x1F, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, \ - 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, \ - 0xFF, 0x01, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF -#elif IS_DEMO_LIGHT -#define ON_DEMO_BITMAP \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfc, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfc, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xf3, 0xff, 0xff, \ - 0x8f, 0xff, 0xff, 0xff, 0xff, 0xf1, 0xff, 0xff, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xff, 0xff, 0x1f, 0xfe, 0x07, 0xe0, \ - 0x7f, 0xf8, 0xff, 0xff, 0x3f, 0xfc, 0x00, 0x00, 0x3f, 0xfc, 0xff, 0xff, 0x7f, 0x3c, 0xe0, 0x07, 0x3c, 0xfe, 0xff, 0xff, \ - 0xff, 0x1f, 0xfe, 0x7f, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x0f, 0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xc7, 0xff, 0xff, \ - 0xe3, 0xff, 0xff, 0xff, 0xff, 0xe3, 0xff, 0xff, 0xc7, 0xff, 0xff, 0xff, 0xff, 0xf1, 0xff, 0xff, 0x8f, 0xff, 0xff, 0xff, \ - 0xff, 0xf1, 0xff, 0xff, 0x8f, 0xff, 0xff, 0xff, 0xff, 0xf8, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, \ - 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, \ - 0x7f, 0xfe, 0xff, 0xff, 0x7f, 0xfe, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, \ - 0x7f, 0xfc, 0xff, 0x0f, 0x38, 0xfe, 0xff, 0xff, 0x7f, 0x1c, 0xf0, 0x0f, 0x38, 0xfe, 0x03, 0xc0, 0x7f, 0x1c, 0xf0, 0x0f, \ - 0x38, 0xfe, 0x27, 0xe9, 0x7f, 0x1c, 0xf0, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, \ - 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xe7, 0xe7, 0x7f, 0xfc, 0xff, 0xff, 0x7f, 0xfe, 0xef, 0xf7, 0x7f, 0xfe, 0xff, 0xff, \ - 0x7f, 0xfc, 0xef, 0xf7, 0x3f, 0xfe, 0xff, 0xff, 0xff, 0xfc, 0xef, 0xf3, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xf8, 0xcf, 0xf3, \ - 0x1f, 0xff, 0xff, 0xff, 0xff, 0xf8, 0xdf, 0xfb, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xf1, 0xdf, 0xfb, 0x8f, 0xff, 0xff, 0xff, \ - 0xff, 0xe3, 0x9f, 0xf9, 0xc7, 0xff, 0xff, 0xff, 0xff, 0xc3, 0x9f, 0xf9, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xc7, 0x9f, 0xfd, \ - 0xe3, 0xff, 0xff, 0xff, 0xff, 0x8f, 0xbf, 0xfd, 0xf1, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x3f, 0xfc, 0xf8, 0xff, 0xff, 0xff, \ - 0xff, 0x3f, 0x3e, 0x7c, 0xfc, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0x3f, 0xfe, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0x3f, \ - 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf1, 0x8f, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0xc0, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0x3f, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff - -#define OFF_DEMO_BITMAP \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0xe0, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0xe0, 0x07, 0xfc, 0xff, 0xff, 0xff, \ - 0xff, 0x1f, 0xfe, 0x7f, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x0f, 0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xc7, 0xff, 0xff, \ - 0xe3, 0xff, 0xff, 0xff, 0xff, 0xe3, 0xff, 0xff, 0xc7, 0xff, 0xff, 0xff, 0xff, 0xf1, 0xff, 0xff, 0x8f, 0xff, 0xff, 0xff, \ - 0xff, 0xf1, 0xff, 0xff, 0x8f, 0xff, 0xff, 0xff, 0xff, 0xf8, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, \ - 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, \ - 0x7f, 0xfe, 0xff, 0xff, 0x7f, 0xfe, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, \ - 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, \ - 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, \ - 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0x7f, 0xfc, 0xff, 0xff, 0x7f, 0xfe, 0xff, 0xff, 0x7f, 0xfe, 0xff, 0xff, \ - 0x7f, 0xfc, 0xff, 0xff, 0x3f, 0xfe, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xf8, 0xff, 0xff, \ - 0x1f, 0xff, 0xff, 0xff, 0xff, 0xf8, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xf1, 0xff, 0xff, 0x8f, 0xff, 0xff, 0xff, \ - 0xff, 0xe3, 0xff, 0xff, 0xc7, 0xff, 0xff, 0xff, 0xff, 0xc3, 0xff, 0xff, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xc7, 0xff, 0xff, \ - 0xe3, 0xff, 0xff, 0xff, 0xff, 0x8f, 0xff, 0xff, 0xf1, 0xff, 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xf8, 0xff, 0xff, 0xff, \ - 0xff, 0x3f, 0xfe, 0x7f, 0xfc, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0x3f, 0xfe, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfc, 0x3f, \ - 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf1, 0x8f, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0xc0, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0x3f, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff -#elif IS_DEMO_LOCK -#define ON_DEMO_BITMAP \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0xC0, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, \ - 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0xE0, 0x07, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0xF8, 0x1F, 0xF8, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x0F, 0xFC, 0x3F, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0xFE, 0x7F, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0xFE, 0x7F, \ - 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, \ - 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x80, 0x01, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0xE0, 0x07, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF0, 0x0F, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF8, 0x1F, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF8, 0x1F, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xFC, 0x3F, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0xFC, 0x3F, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF8, 0x1F, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF8, 0x1F, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF0, 0x0F, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xE0, 0x07, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0x80, 0x01, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF - -#define OFF_DEMO_BITMAP \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0xC0, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, \ - 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0xE0, 0x07, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0xF8, 0x1F, 0xF8, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x0F, 0xFC, 0x3F, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0xFE, 0x7F, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0xFE, 0x7F, \ - 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x07, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x80, 0x01, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0xE0, 0x07, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF0, 0x0F, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF8, 0x1F, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF8, 0x1F, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xFC, 0x3F, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0xFC, 0x3F, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF8, 0x1F, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF8, 0x1F, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xF0, 0x0F, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0xE0, 0x07, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0x80, 0x01, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, \ - 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, \ - 0x07, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF -#elif IS_DEMO_THERMOSTAT -#define ON_DEMO_BITMAP \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xE0, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0xC0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC1, 0x83, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xE0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xE0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, \ - 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, \ - 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, \ - 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, \ - 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0xE0, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF -#define OFF_DEMO_BITMAP ON_DEMO_BITMAP - -#else // Unknown demo.... -#define ON_DEMO_BITMAP \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0x7F, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0xC0, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x7F, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, \ - 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0xF0, 0x0F, \ - 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0xFC, 0x3F, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0xFE, 0x7F, 0xFE, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF8, 0x1F, 0xF8, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xF0, \ - 0x0F, 0xFF, 0xFF, 0xFF, 0x7F, 0xE0, 0x07, 0xE0, 0x07, 0xFE, 0xFF, 0xFF, 0x7F, 0xC0, 0x03, 0xC0, 0x03, 0xFE, 0xFF, 0xFF, \ - 0x7F, 0xC0, 0x03, 0xC0, 0x03, 0xFE, 0xFF, 0xFF, 0x3F, 0xC0, 0x03, 0xC0, 0x03, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, \ - 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, \ - 0x8F, 0x01, 0x80, 0x01, 0x80, 0xF1, 0xFF, 0xFF, 0xCF, 0x03, 0xC0, 0x03, 0xC0, 0xF3, 0xFF, 0xFF, 0xEF, 0x07, 0xE0, 0x07, \ - 0xE0, 0xF7, 0xFF, 0xFF, 0xFF, 0x0F, 0xF0, 0x0F, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0xF8, 0x1F, 0xF8, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x3F, 0xFC, 0x3F, 0xFC, 0xFF, 0xFF, 0xFF, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0xFE, 0xFF, 0xFF, 0x3F, 0xFC, 0x3F, 0xFC, \ - 0x3F, 0xFC, 0xFF, 0xFF, 0x1F, 0xF8, 0x1F, 0xF8, 0x1F, 0xF8, 0xFF, 0xFF, 0x1F, 0xF0, 0x0F, 0xF0, 0x0F, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0xE0, 0x07, 0xE0, 0x07, 0xF8, 0xFF, 0xFF, 0x3F, 0xC0, 0x03, 0xC0, 0x03, 0xFC, 0xFF, 0xFF, 0x3F, 0x80, 0x01, 0x80, \ - 0x01, 0xFC, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, \ - 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, 0x00, \ - 0xC0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x1F, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x80, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF - -#define OFF_DEMO_BITMAP \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0x7F, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0xC0, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x7F, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, \ - 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, 0x00, \ - 0xC0, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0xC0, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x01, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, \ - 0x00, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, \ - 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, \ - 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, \ - 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, \ - 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, \ - 0x00, 0xF0, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, \ - 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, \ - 0x00, 0xF0, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, \ - 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, \ - 0x00, 0xFC, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, \ - 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, 0x00, \ - 0xC0, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0x1F, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x80, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF - -#endif - -#endif // SILABS_DEMO_UI_BITMAPS_H diff --git a/examples/platform/silabs/SiWx917/display/demo-ui.c b/examples/platform/silabs/SiWx917/display/demo-ui.c deleted file mode 100644 index 73a8d52ea71090..00000000000000 --- a/examples/platform/silabs/SiWx917/display/demo-ui.c +++ /dev/null @@ -1,136 +0,0 @@ -/** - * @file - * @brief User Interface core logic for demo. - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. - *www.silabs.com - ******************************************************************************* - * - * The licensor of this software is Silicon - *Laboratories Inc. Your use of this software is - *governed by the terms of Silicon Labs Master - *Software License Agreement (MSLA) available at - * www.silabs.com/about-us/legal/master-software-license-agreement. - *This software is distributed to you in Source Code - *format and is governed by the sections of the MSLA - *applicable to Source Code. - * - ******************************************************************************/ - -#include "demo-ui.h" -#include "demo-ui-bitmaps.h" -#include "dmd/dmd.h" -#include "em_types.h" -#include "glib.h" -#include -#include - -// Main Logo and App image -#define SILICONLABS_X_POSITION ((glibContext.pDisplayGeometry->xSize - SILICONLABS_BITMAP_WIDTH) / 2) -#define SILICONLABS_Y_POSITION 0 -#define APP_BITMAP_WIDTH 64 -#define APP_BITMAP_HEIGHT 64 -#define APP_X_POSITION ((glibContext.pDisplayGeometry->xSize - APP_BITMAP_WIDTH) / 2) -#define APP_Y_POSITION (glibContext.pDisplayGeometry->ySize - APP_BITMAP_HEIGHT - 5) -#define PROT1_ID_X_POSITION 1 -#define PROT2_ID_X_POSITION 79 - -// Matter Logo -#define PROT2_BITMAP_WIDTH MATTER_LOGO_WIDTH -#define PROT2_BITMAP_HEIGHT MATTER_LOGO_HEIGHT -#define PROT2_X_POSITION 104 -#define PROT2_Y_POSITION (APP_Y_POSITION + (APP_Y_POSITION / 2)) -#define PROT2_BITMAP (matterLogoBitmap) -#define PROT2_BITMAP_CONN (matterLogoBitmap) - -// Networking Protocol Logo -#ifdef SL_WIFI -#define PROT1_BITMAP_WIDTH WIFI_BITMAP_WIDTH -#define PROT1_BITMAP_HEIGHT WIFI_BITMAP_HEIGHT -#define PROT1_X_POSITION 8 -#define PROT1_Y_POSITION (APP_Y_POSITION + (APP_Y_POSITION / 2)) -#define PROT1_BITMAP (networkBitMap) -#define PROT1_BITMAP_CONN (networkBitMap) -#else -#define PROT1_BITMAP_WIDTH THREAD_BITMAP_WIDTH -#define PROT1_BITMAP_HEIGHT THREAD_BITMAP_HEIGHT -#define PROT1_X_POSITION 8 -#define PROT1_Y_POSITION (APP_Y_POSITION + (APP_Y_POSITION / 2)) -#define PROT1_BITMAP (networkBitMap) -#define PROT1_BITMAP_CONN (networkBitMap) -#endif - -/******************************************************************************* - *************************** LOCAL VARIABLES ******************************** - ******************************************************************************/ -static GLIB_Context_t glibContext; /* Global glib context */ - -static const uint8_t siliconlabsBitmap[] = { SILABS_BITMAP }; -static const uint8_t matterLogoBitmap[] = { MATTER_LOGO_BITMAP }; - -static const uint8_t OnStateBitMap[] = { ON_DEMO_BITMAP }; -static const uint8_t OffStateBitMap[] = { OFF_DEMO_BITMAP }; - -#ifdef SL_WIFI -static const uint8_t networkBitMap[] = { WIFI_BITMAP }; -#else -static const uint8_t networkBitMap[] = { THREAD_BITMAP }; -#endif - -// Future usage -// static const uint8_t unconnectedBitMap[] = { QUESTION_MARK_BITMAP }; - -/******************************************************************************* - ************************** LOCAL FUNCTIONS ******************************** - ******************************************************************************/ -static void demoUIDisplayLogo(void) -{ - GLIB_drawBitmap(&glibContext, SILICONLABS_X_POSITION, SILICONLABS_Y_POSITION, SILICONLABS_BITMAP_WIDTH, - SILICONLABS_BITMAP_HEIGHT, siliconlabsBitmap); -} - -/******************************************************************************* - ************************** GLOBAL FUNCTIONS ******************************* - ******************************************************************************/ -void demoUIInit(GLIB_Context_t * context) -{ - memcpy(&glibContext, context, sizeof(GLIB_Context_t)); -} - -void demoUIDisplayHeader(char * name) -{ - demoUIDisplayLogo(); - if (APP_NAME_MAX_LENGTH >= strlen(name)) - { - GLIB_drawStringOnLine(&glibContext, name, 5, GLIB_ALIGN_CENTER, 0, 0, true); - } - DMD_updateDisplay(); -} - -void demoUIDisplayApp(bool on) -{ - GLIB_drawBitmap(&glibContext, APP_X_POSITION, APP_Y_POSITION, APP_BITMAP_WIDTH, APP_BITMAP_HEIGHT, - (on ? OnStateBitMap : OffStateBitMap)); - DMD_updateDisplay(); -} - -void demoUIDisplayProtocol(demoUIProtocol protocol, bool isConnected) -{ - GLIB_drawBitmap(&glibContext, (protocol == DEMO_UI_PROTOCOL1 ? PROT1_X_POSITION : PROT2_X_POSITION), - (protocol == DEMO_UI_PROTOCOL1 ? PROT1_Y_POSITION : PROT2_Y_POSITION), - (protocol == DEMO_UI_PROTOCOL1 ? PROT1_BITMAP_WIDTH : PROT2_BITMAP_WIDTH), - (protocol == DEMO_UI_PROTOCOL1 ? PROT1_BITMAP_HEIGHT : PROT2_BITMAP_HEIGHT), - (protocol == DEMO_UI_PROTOCOL1 ? (isConnected ? PROT1_BITMAP_CONN : PROT1_BITMAP) - : (isConnected ? PROT2_BITMAP_CONN : PROT2_BITMAP))); - DMD_updateDisplay(); -} - -void demoUIClearMainScreen(uint8_t * name) -{ - GLIB_clear(&glibContext); - demoUIDisplayHeader((char *) name); - demoUIDisplayApp(false); - demoUIDisplayProtocol(DEMO_UI_PROTOCOL1, false); - demoUIDisplayProtocol(DEMO_UI_PROTOCOL2, false); -} diff --git a/examples/platform/silabs/SiWx917/display/lcd.cpp b/examples/platform/silabs/SiWx917/display/lcd.cpp deleted file mode 100644 index 6e1f2d2fe93de3..00000000000000 --- a/examples/platform/silabs/SiWx917/display/lcd.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "demo-ui.h" -#include "lcd.h" - -#include "dmd.h" -#include "glib.h" - -#ifdef QR_CODE_ENABLED -#include "qrcodegen.h" -#endif // QR_CODE_ENABLED - -#include "sl_board_control.h" - -#define LCD_SIZE 128 -#define QR_CODE_VERSION 4 -#define QR_CODE_MODULE_SIZE 3 -#define QR_CODE_BORDER_SIZE 0 - -#ifdef QR_CODE_ENABLED -static uint8_t qrCode[qrcodegen_BUFFER_LEN_FOR_VERSION(QR_CODE_VERSION)]; -static uint8_t workBuffer[qrcodegen_BUFFER_LEN_FOR_VERSION(QR_CODE_VERSION)]; -#endif // QR_CODE_ENABLED - -CHIP_ERROR SilabsLCD::Init(uint8_t * name, bool initialState) -{ - EMSTATUS status; - CHIP_ERROR err = CHIP_NO_ERROR; - - // Check if Name is to long - if (name != nullptr) - { - if (APP_NAME_MAX_LENGTH < strlen((char *) name)) - { - SILABS_LOG("App Name too long"); - return CHIP_ERROR_INVALID_ARGUMENT; - } - else - { - strcpy((char *) mName, (char *) name); - } - } - - /* Enable the memory lcd */ - status = sl_board_enable_display(); - if (status != SL_STATUS_OK) - { - SILABS_LOG("Board Display enable fail %d", status); - err = CHIP_ERROR_INTERNAL; - } - - /* Initialize the DMD module for the DISPLAY device driver. */ - status = DMD_init(0); - if (DMD_OK != status) - { - SILABS_LOG("DMD init failed %d", status); - err = CHIP_ERROR_INTERNAL; - } - - /* Initialize the glib context */ - status = GLIB_contextInit(&glibContext); - if (GLIB_OK != status) - { - SILABS_LOG("Glib context init failed %d", status); - err = CHIP_ERROR_INTERNAL; - } - - glibContext.backgroundColor = White; - glibContext.foregroundColor = Black; - status = GLIB_clear(&glibContext); - if (GLIB_OK != status) - { - SILABS_LOG("Glib clear failed %d", status); - err = CHIP_ERROR_INTERNAL; - } - demoUIInit(&glibContext); - - dState.mainState = initialState; - - return err; -} - -/* This function is necessary because currently glib.h cannot be used within a C++ context. */ -void * SilabsLCD::Context() -{ - return (void *) &glibContext; -} - -int SilabsLCD::Clear() -{ - return GLIB_clear(&glibContext); -} - -int SilabsLCD::DrawPixel(void * pContext, int32_t x, int32_t y) -{ - return GLIB_drawPixel((GLIB_Context_t *) pContext, x, y); -} - -int SilabsLCD::Update(void) -{ - return DMD_updateDisplay(); -} - -void SilabsLCD::WriteDemoUI(bool state) -{ -#ifdef QR_CODE_ENABLED - if (mShowQRCode) - { - mShowQRCode = false; - } -#endif - dState.mainState = state; - WriteDemoUI(); -} - -void SilabsLCD::WriteDemoUI() -{ - Clear(); - if (customUI != nullptr) - { - customUI(&glibContext); - } - else - { - demoUIClearMainScreen(mName); - demoUIDisplayApp(dState.mainState); - } -} - -void SilabsLCD::SetCustomUI(customUICB cb) -{ - customUI = cb; -} - -#ifdef QR_CODE_ENABLED -void SilabsLCD::WriteQRCode() -{ - if (!qrcodegen_encodeText((const char *) mQRCodeBuffer, workBuffer, qrCode, qrcodegen_Ecc_LOW, QR_CODE_VERSION, QR_CODE_VERSION, - qrcodegen_Mask_AUTO, true)) - { - SILABS_LOG("qrcodegen_encodeText() failed"); - return; - } - - const int size = qrcodegen_getSize(qrCode); - - GLIB_clear(&glibContext); - - const int displaySize = (2 * QR_CODE_BORDER_SIZE + size) * QR_CODE_MODULE_SIZE; - const int displayX = (LCD_SIZE - displaySize) / 2; - const int displayY = displayX; - - for (int y = 0; y < size; ++y) - { - for (int x = 0; x < size; ++x) - { - if (qrcodegen_getModule(qrCode, x, y)) - { - LCDFillRect(displayX + (QR_CODE_BORDER_SIZE + x) * QR_CODE_MODULE_SIZE, - displayY + (QR_CODE_BORDER_SIZE + y) * QR_CODE_MODULE_SIZE, QR_CODE_MODULE_SIZE, QR_CODE_MODULE_SIZE); - } - } - } - - DMD_updateDisplay(); -} - -void SilabsLCD::SetQRCode(uint8_t * str, uint32_t size) -{ - if (size < chip::QRCodeBasicSetupPayloadGenerator::kMaxQRCodeBase38RepresentationLength + 1) - { - memcpy(mQRCodeBuffer, str, size); - } -} - -void SilabsLCD::ShowQRCode(bool show, bool forceRefresh) -{ - if (show != mShowQRCode || forceRefresh) - { - (show) ? WriteQRCode() : WriteDemoUI(); - mShowQRCode = show; - } -} - -void SilabsLCD::ToggleQRCode(void) -{ - (mShowQRCode) ? WriteDemoUI() : WriteQRCode(); - mShowQRCode = !mShowQRCode; -} - -void SilabsLCD::LCDFillRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h) -{ - for (int i = 0; i < h; i++) - { - for (int j = 0; j < w; j++) - { - GLIB_drawPixel(&glibContext, x + j, y + i); - } - } -} -#endif // QR_CODE_ENABLED diff --git a/examples/platform/silabs/SiWx917/matter_config.cpp b/examples/platform/silabs/SiWx917/matter_config.cpp index 93c8d3250f9f25..9d6344132ce8f1 100644 --- a/examples/platform/silabs/SiWx917/matter_config.cpp +++ b/examples/platform/silabs/SiWx917/matter_config.cpp @@ -54,10 +54,10 @@ using namespace ::chip::DeviceLayer; #include // If building with the SiWx917-provided crypto backend, we can use the -#include "SiWx917DeviceDataProvider.h" +#include "SilabsDeviceDataProvider.h" -#if EFR32_OTA_ENABLED -void SI917MatterConfig::InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +#if SILABS_OTA_ENABLED +void SilabsMatterConfig::InitOTARequestorHandler(System::Layer * systemLayer, void * appState) { #if 0 // TODO : OTA is not planned now for CCP OTAConfig::Init(); @@ -65,7 +65,7 @@ void SI917MatterConfig::InitOTARequestorHandler(System::Layer * systemLayer, voi } #endif -void SI917MatterConfig::ConnectivityEventCallback(const ChipDeviceEvent * event, intptr_t arg){ +void SilabsMatterConfig::ConnectivityEventCallback(const ChipDeviceEvent * event, intptr_t arg){ // Initialize OTA only when Thread or WiFi connectivity is established /*if (((event->Type == DeviceEventType::kThreadConnectivityChange) && (event->ThreadConnectivityChange.Result == kConnectivity_Established)) || @@ -79,7 +79,7 @@ void SI917MatterConfig::ConnectivityEventCallback(const ChipDeviceEvent * event, SILABS_LOG("Scheduling OTA Requestor initialization") } -CHIP_ERROR SI917MatterConfig::InitMatter(const char * appName) +CHIP_ERROR SilabsMatterConfig::InitMatter(const char * appName) { CHIP_ERROR err; @@ -112,11 +112,11 @@ CHIP_ERROR SI917MatterConfig::InitMatter(const char * appName) } ReturnErrorOnFailure(PlatformMgr().InitChipStack()); - SetDeviceInstanceInfoProvider(&SIWx917::SIWx917DeviceDataProvider::GetDeviceDataProvider()); - SetCommissionableDataProvider(&SIWx917::SIWx917DeviceDataProvider::GetDeviceDataProvider()); + SetDeviceInstanceInfoProvider(&Silabs::SilabsDeviceDataProvider::GetDeviceDataProvider()); + SetCommissionableDataProvider(&Silabs::SilabsDeviceDataProvider::GetDeviceDataProvider()); #ifdef SIWX917_USE_COMISSIONABLE_DATA - err = SIWx917::SIWx917DeviceDataProvider::GetDeviceDataProvider().FlashFactoryData(); + err = Silabs::SilabsDeviceDataProvider::GetDeviceDataProvider().FlashFactoryData(); if (err != CHIP_NO_ERROR) { SILABS_LOG("Flashing to the device failed"); @@ -159,7 +159,7 @@ CHIP_ERROR SI917MatterConfig::InitMatter(const char * appName) } #ifdef SL_WIFI -void SI917MatterConfig::InitWiFi(void) +void SilabsMatterConfig::InitWiFi(void) { #ifdef RS911X_WIFI /* diff --git a/examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.cpp b/examples/platform/silabs/SilabsDeviceDataProvider.cpp similarity index 86% rename from examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.cpp rename to examples/platform/silabs/SilabsDeviceDataProvider.cpp index 30cc5172081c06..585699785937bd 100644 --- a/examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.cpp +++ b/examples/platform/silabs/SilabsDeviceDataProvider.cpp @@ -15,26 +15,30 @@ * limitations under the License. */ -#include "SiWx917DeviceDataProvider.h" -#include "DeviceConfig.h" -#include "siwx917_utils.h" +#include "SilabsDeviceDataProvider.h" #include #include #include -#include #include -#include #include +#ifdef SIWX917_USE_COMISSIONABLE_DATA +#include "DeviceConfig.h" +#include "siwx917_utils.h" +#include +#include +#endif // SIWX917_USE_COMISSIONABLE_DATA + namespace chip { namespace DeviceLayer { -namespace SIWx917 { -#include +namespace Silabs { + // using namespace chip::Credentials; using namespace chip::DeviceLayer::Internal; +// TODO Remove once Commander supports (doesn't erase) NVM3 for 917 #ifdef SIWX917_USE_COMISSIONABLE_DATA -void SIWx917DeviceDataProvider::setupPayload(uint8_t * outBuf) +void SilabsDeviceDataProvider::setupPayload(uint8_t * outBuf) { SetupPayload payload; std::string result; @@ -67,7 +71,7 @@ void SIWx917DeviceDataProvider::setupPayload(uint8_t * outBuf) } // writing to the flash based on the value given in the DeviceConfig.h -CHIP_ERROR SIWx917DeviceDataProvider::FlashFactoryData() +CHIP_ERROR SilabsDeviceDataProvider::FlashFactoryData() { // flashing the value to the nvm3 section of the flash // TODO: remove this once it is removed SiWx917 have the nvm3 simiplicity commander support @@ -164,10 +168,11 @@ CHIP_ERROR SIWx917DeviceDataProvider::FlashFactoryData() return err; } } + return CHIP_NO_ERROR; } #endif -CHIP_ERROR SIWx917DeviceDataProvider::GetSetupDiscriminator(uint16_t & setupDiscriminator) +CHIP_ERROR SilabsDeviceDataProvider::GetSetupDiscriminator(uint16_t & setupDiscriminator) { CHIP_ERROR err; uint32_t setupDiscriminator32; @@ -186,9 +191,10 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetSetupDiscriminator(uint16_t & setupDisc return CHIP_NO_ERROR; } -CHIP_ERROR SIWx917DeviceDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) +CHIP_ERROR SilabsDeviceDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) { CHIP_ERROR err = SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_Spake2pIterationCount, iterationCount); + #if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT) && CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { @@ -199,7 +205,7 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetSpake2pIterationCount(uint32_t & iterat return err; } -CHIP_ERROR SIWx917DeviceDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) +CHIP_ERROR SilabsDeviceDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) { static constexpr size_t kSpake2pSalt_MaxBase64Len = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length) + 1; @@ -208,6 +214,7 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) size_t saltB64Len = 0; err = SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_Spake2pSalt, saltB64, sizeof(saltB64), saltB64Len); + #if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT) if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { @@ -230,7 +237,7 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) return CHIP_NO_ERROR; } -CHIP_ERROR SIWx917DeviceDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) +CHIP_ERROR SilabsDeviceDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) { static constexpr size_t kSpake2pSerializedVerifier_MaxBase64Len = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_VerifierSerialized_Length) + 1; @@ -241,6 +248,7 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetSpake2pVerifier(MutableByteSpan & verif err = SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_Spake2pVerifier, verifierB64, sizeof(verifierB64), verifierB64Len); + #if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER) if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { @@ -262,13 +270,15 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetSpake2pVerifier(MutableByteSpan & verif return CHIP_NO_ERROR; } -CHIP_ERROR SIWx917DeviceDataProvider::GetSetupPayload(MutableCharSpan & payloadBuf) +CHIP_ERROR SilabsDeviceDataProvider::GetSetupPayload(MutableCharSpan & payloadBuf) { CHIP_ERROR err = CHIP_NO_ERROR; uint8_t payloadBitSet[kTotalPayloadDataSizeInBytes] = { 0 }; size_t bitSetLen = 0; + err = SilabsConfig::ReadConfigValueBin(SilabsConfig::kConfigKey_SetupPayloadBitSet, payloadBitSet, kTotalPayloadDataSizeInBytes, bitSetLen); + #if defined(CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE) && CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { @@ -300,18 +310,19 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetSetupPayload(MutableCharSpan & payloadB return err; } -CHIP_ERROR SIWx917DeviceDataProvider::GetVendorName(char * buf, size_t bufSize) +CHIP_ERROR SilabsDeviceDataProvider::GetVendorName(char * buf, size_t bufSize) { size_t vendorNameLen = 0; // without counting null-terminator return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_VendorName, buf, bufSize, vendorNameLen); } -CHIP_ERROR SIWx917DeviceDataProvider::GetVendorId(uint16_t & vendorId) +CHIP_ERROR SilabsDeviceDataProvider::GetVendorId(uint16_t & vendorId) { ChipError err = CHIP_NO_ERROR; uint32_t vendorId32 = 0; err = SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_VendorId, vendorId32); + #if defined(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID) && CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { @@ -325,18 +336,19 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetVendorId(uint16_t & vendorId) return err; } -CHIP_ERROR SIWx917DeviceDataProvider::GetProductName(char * buf, size_t bufSize) +CHIP_ERROR SilabsDeviceDataProvider::GetProductName(char * buf, size_t bufSize) { size_t productNameLen = 0; // without counting null-terminator return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_ProductName, buf, bufSize, productNameLen); } -CHIP_ERROR SIWx917DeviceDataProvider::GetProductId(uint16_t & productId) +CHIP_ERROR SilabsDeviceDataProvider::GetProductId(uint16_t & productId) { ChipError err = CHIP_NO_ERROR; uint32_t productId32 = 0; err = SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_ProductId, productId32); + #if defined(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID) && CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { @@ -350,7 +362,7 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetProductId(uint16_t & productId) return err; } -CHIP_ERROR SIWx917DeviceDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) +CHIP_ERROR SilabsDeviceDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) { size_t hardwareVersionStringLen = 0; // without counting null-terminator CHIP_ERROR err = @@ -365,7 +377,7 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetHardwareVersionString(char * buf, size_ return err; } -CHIP_ERROR SIWx917DeviceDataProvider::GetHardwareVersion(uint16_t & hardwareVersion) +CHIP_ERROR SilabsDeviceDataProvider::GetHardwareVersion(uint16_t & hardwareVersion) { CHIP_ERROR err; uint32_t hardwareVersion32; @@ -383,7 +395,7 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetHardwareVersion(uint16_t & hardwareVers return err; } -CHIP_ERROR SIWx917DeviceDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) +CHIP_ERROR SilabsDeviceDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) { ChipError err = CHIP_ERROR_WRONG_KEY_TYPE; #if CHIP_ENABLE_ROTATING_DEVICE_ID @@ -411,13 +423,13 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpa return err; } -CHIP_ERROR SIWx917DeviceDataProvider::GetSerialNumber(char * buf, size_t bufSize) +CHIP_ERROR SilabsDeviceDataProvider::GetSerialNumber(char * buf, size_t bufSize) { size_t serialNumberLen = 0; // without counting null-terminator return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_SerialNum, buf, bufSize, serialNumberLen); } -CHIP_ERROR SIWx917DeviceDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) +CHIP_ERROR SilabsDeviceDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) { CHIP_ERROR err; constexpr uint8_t kDateStringLength = 10; // YYYY-MM-DD @@ -452,15 +464,32 @@ CHIP_ERROR SIWx917DeviceDataProvider::GetManufacturingDate(uint16_t & year, uint ChipLogError(DeviceLayer, "Invalid manufacturing date: %s", dateStr); } return err; - return CHIP_ERROR_NOT_IMPLEMENTED; } -SIWx917DeviceDataProvider & SIWx917DeviceDataProvider::GetDeviceDataProvider() +CHIP_ERROR SilabsDeviceDataProvider::GetPartNumber(char * buf, size_t bufSize) +{ + size_t partNumberLen = 0; // without counting null-terminator + return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_PartNumber, buf, bufSize, partNumberLen); +} + +CHIP_ERROR SilabsDeviceDataProvider::GetProductURL(char * buf, size_t bufSize) +{ + size_t productUrlLen = 0; // without counting null-terminator + return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_ProductURL, buf, bufSize, productUrlLen); +} + +CHIP_ERROR SilabsDeviceDataProvider::GetProductLabel(char * buf, size_t bufSize) +{ + size_t productLabelLen = 0; // without counting null-terminator + return SilabsConfig::ReadConfigValueStr(SilabsConfig::KConfigKey_ProductLabel, buf, bufSize, productLabelLen); +} + +SilabsDeviceDataProvider & SilabsDeviceDataProvider::GetDeviceDataProvider() { - static SIWx917DeviceDataProvider sDataProvider; + static SilabsDeviceDataProvider sDataProvider; return sDataProvider; } -} // namespace SIWx917 +} // namespace Silabs } // namespace DeviceLayer } // namespace chip diff --git a/examples/platform/silabs/efr32/EFR32DeviceDataProvider.h b/examples/platform/silabs/SilabsDeviceDataProvider.h similarity index 84% rename from examples/platform/silabs/efr32/EFR32DeviceDataProvider.h rename to examples/platform/silabs/SilabsDeviceDataProvider.h index 7426905525df38..8bb04fea7d39f5 100644 --- a/examples/platform/silabs/efr32/EFR32DeviceDataProvider.h +++ b/examples/platform/silabs/SilabsDeviceDataProvider.h @@ -21,25 +21,30 @@ namespace chip { namespace DeviceLayer { -namespace EFR32 { +namespace Silabs { /** * @brief This class provides Commissionable data, Device Attestation Credentials, * and Device Instance Info. */ -class EFR32DeviceDataProvider : public CommissionableDataProvider, - public Internal::GenericDeviceInstanceInfoProvider +class SilabsDeviceDataProvider : public CommissionableDataProvider, + public Internal::GenericDeviceInstanceInfoProvider { public: - EFR32DeviceDataProvider() : + SilabsDeviceDataProvider() : CommissionableDataProvider(), Internal::GenericDeviceInstanceInfoProvider( ConfigurationManagerImpl::GetDefaultInstance()) {} - static EFR32DeviceDataProvider & GetDeviceDataProvider(); - CHIP_ERROR GetSetupPayload(MutableCharSpan & payloadBuf); +// TODO Remove once Commander supports (doesn't erase) NVM3 for 917 +#ifdef SIWX917_USE_COMISSIONABLE_DATA + void setupPayload(uint8_t * outBuf); + CHIP_ERROR FlashFactoryData(); +#endif /* SIWX917_USE_COMISSIONABLE_DATA */ + static SilabsDeviceDataProvider & GetDeviceDataProvider(); + CHIP_ERROR GetSetupPayload(MutableCharSpan & payloadBuf); // ===== Members functions that implement the CommissionableDataProvider CHIP_ERROR GetSetupDiscriminator(uint16_t & setupDiscriminator) override; CHIP_ERROR SetSetupDiscriminator(uint16_t setupDiscriminator) override { return CHIP_ERROR_NOT_IMPLEMENTED; } @@ -65,6 +70,6 @@ class EFR32DeviceDataProvider : public CommissionableDataProvider, CHIP_ERROR GetProductLabel(char * buf, size_t bufSize) override; }; -} // namespace EFR32 +} // namespace Silabs } // namespace DeviceLayer } // namespace chip diff --git a/examples/platform/silabs/efr32/display/demo-ui-bitmaps.h b/examples/platform/silabs/display/demo-ui-bitmaps.h similarity index 100% rename from examples/platform/silabs/efr32/display/demo-ui-bitmaps.h rename to examples/platform/silabs/display/demo-ui-bitmaps.h diff --git a/examples/platform/silabs/efr32/display/demo-ui.c b/examples/platform/silabs/display/demo-ui.c similarity index 100% rename from examples/platform/silabs/efr32/display/demo-ui.c rename to examples/platform/silabs/display/demo-ui.c diff --git a/examples/platform/silabs/SiWx917/display/demo-ui.h b/examples/platform/silabs/display/demo-ui.h similarity index 100% rename from examples/platform/silabs/SiWx917/display/demo-ui.h rename to examples/platform/silabs/display/demo-ui.h diff --git a/examples/platform/silabs/efr32/display/lcd.cpp b/examples/platform/silabs/display/lcd.cpp similarity index 98% rename from examples/platform/silabs/efr32/display/lcd.cpp rename to examples/platform/silabs/display/lcd.cpp index 37ccb0dedbb1d5..561c02451686ee 100644 --- a/examples/platform/silabs/efr32/display/lcd.cpp +++ b/examples/platform/silabs/display/lcd.cpp @@ -71,12 +71,6 @@ CHIP_ERROR SilabsLCD::Init(uint8_t * name, bool initialState) err = CHIP_ERROR_INTERNAL; } -#if (defined(EFR32MG24) && defined(WF200_WIFI)) - if (pr_type != LCD) - { - pr_type = LCD; - } -#endif /* Initialize the DMD module for the DISPLAY device driver. */ status = DMD_init(0); if (DMD_OK != status) diff --git a/examples/platform/silabs/SiWx917/display/lcd.h b/examples/platform/silabs/display/lcd.h similarity index 100% rename from examples/platform/silabs/SiWx917/display/lcd.h rename to examples/platform/silabs/display/lcd.h diff --git a/examples/platform/silabs/efr32/BUILD.gn b/examples/platform/silabs/efr32/BUILD.gn index aaa3213138e8eb..fd33406f6911b1 100644 --- a/examples/platform/silabs/efr32/BUILD.gn +++ b/examples/platform/silabs/efr32/BUILD.gn @@ -179,10 +179,10 @@ source_set("efr32-attestation-credentials") { public_configs = [ ":attestation-credentials-config" ] } -source_set("efr32-factory-data-provider") { +source_set("silabs-factory-data-provider") { sources = [ - "EFR32DeviceDataProvider.cpp", - "EFR32DeviceDataProvider.h", + "${silabs_common_plat_dir}/SilabsDeviceDataProvider.cpp", + "${silabs_common_plat_dir}/SilabsDeviceDataProvider.h", ] public_deps = [ @@ -211,7 +211,7 @@ config("efr32-common-config") { defines = [ "OTA_PERIODIC_TIMEOUT=${ota_periodic_query_timeout_sec}" ] if (!disable_lcd) { - include_dirs = [ "display" ] + include_dirs = [ "${silabs_common_plat_dir}/display" ] defines += [ "DISPLAY_ENABLED" ] } @@ -221,7 +221,7 @@ config("efr32-common-config") { } if (chip_enable_ota_requestor) { - defines += [ "EFR32_OTA_ENABLED" ] + defines += [ "SILABS_OTA_ENABLED" ] } if (enable_heap_monitoring) { @@ -302,21 +302,21 @@ source_set("efr32-common") { } if (chip_enable_ota_requestor) { - sources += [ "OTAConfig.cpp" ] + sources += [ "${silabs_common_plat_dir}/OTAConfig.cpp" ] } if (!disable_lcd) { sources += [ - "display/demo-ui.c", - "display/lcd.cpp", + "${silabs_common_plat_dir}/display/demo-ui.c", + "${silabs_common_plat_dir}/display/lcd.cpp", ] - include_dirs += [ "display" ] + include_dirs += [ "${silabs_common_plat_dir}/display" ] public_deps += [ "${chip_root}/examples/common/QRCode" ] } if (enable_heap_monitoring) { - sources += [ "MemMonitoring.cpp" ] + sources += [ "${silabs_common_plat_dir}/MemMonitoring.cpp" ] } # OpenThread Settings @@ -356,7 +356,7 @@ source_set("efr32-common") { # Factory Data Provider if (use_efr32_factory_data_provider) { - public_deps += [ ":efr32-factory-data-provider" ] + public_deps += [ ":silabs-factory-data-provider" ] } if (chip_config_use_icd_subscription_callbacks) { diff --git a/examples/platform/silabs/efr32/BaseApplication.cpp b/examples/platform/silabs/efr32/BaseApplication.cpp index 4421ca4e313c44..bbb18fc005883a 100644 --- a/examples/platform/silabs/efr32/BaseApplication.cpp +++ b/examples/platform/silabs/efr32/BaseApplication.cpp @@ -37,7 +37,7 @@ #endif // QR_CODE_ENABLED #endif // DISPLAY_ENABLED -#include "EFR32DeviceDataProvider.h" +#include "SilabsDeviceDataProvider.h" #include #include #include @@ -221,7 +221,7 @@ CHIP_ERROR BaseApplication::Init(Identify * identifyObj) char qrCodeBuffer[chip::QRCodeBasicSetupPayloadGenerator::kMaxQRCodeBase38RepresentationLength + 1]; chip::MutableCharSpan QRCode(qrCodeBuffer); - if (EFR32::EFR32DeviceDataProvider::GetDeviceDataProvider().GetSetupPayload(QRCode) == CHIP_NO_ERROR) + if (Silabs::SilabsDeviceDataProvider::GetDeviceDataProvider().GetSetupPayload(QRCode) == CHIP_NO_ERROR) { // Print setup info on LCD if available #ifdef QR_CODE_ENABLED diff --git a/examples/platform/silabs/efr32/EFR32DeviceDataProvider.cpp b/examples/platform/silabs/efr32/EFR32DeviceDataProvider.cpp deleted file mode 100644 index 491fe1b117bbde..00000000000000 --- a/examples/platform/silabs/efr32/EFR32DeviceDataProvider.cpp +++ /dev/null @@ -1,352 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "EFR32DeviceDataProvider.h" -#include -#include -#include -#include -#include - -namespace chip { -namespace DeviceLayer { -namespace EFR32 { - -// using namespace chip::Credentials; -using namespace chip::DeviceLayer::Internal; - -CHIP_ERROR EFR32DeviceDataProvider::GetSetupDiscriminator(uint16_t & setupDiscriminator) -{ - CHIP_ERROR err; - uint32_t setupDiscriminator32; - - err = SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_SetupDiscriminator, setupDiscriminator32); -#if defined(CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR) && CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - setupDiscriminator32 = CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR; - err = CHIP_NO_ERROR; - } -#endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR) && CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR - - VerifyOrReturnLogError(setupDiscriminator32 <= kMaxDiscriminatorValue, CHIP_ERROR_INVALID_ARGUMENT); - setupDiscriminator = static_cast(setupDiscriminator32); - return CHIP_NO_ERROR; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) -{ - CHIP_ERROR err = SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_Spake2pIterationCount, iterationCount); - -#if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT) && CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - iterationCount = CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT; - err = CHIP_NO_ERROR; - } -#endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT) && CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT - return err; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) -{ - static constexpr size_t kSpake2pSalt_MaxBase64Len = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length) + 1; - - CHIP_ERROR err = CHIP_NO_ERROR; - char saltB64[kSpake2pSalt_MaxBase64Len] = { 0 }; - size_t saltB64Len = 0; - - err = SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_Spake2pSalt, saltB64, sizeof(saltB64), saltB64Len); - -#if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT) - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - saltB64Len = strlen(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT); - ReturnErrorCodeIf(saltB64Len > sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(saltB64, CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT, saltB64Len); - err = CHIP_NO_ERROR; - } -#endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT) - - ReturnErrorOnFailure(err); - - uint8_t saltByteArray[kSpake2pSalt_MaxBase64Len] = { 0 }; - size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, saltByteArray); - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - - memcpy(saltBuf.data(), saltByteArray, saltLen); - saltBuf.reduce_size(saltLen); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) -{ - static constexpr size_t kSpake2pSerializedVerifier_MaxBase64Len = - BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_VerifierSerialized_Length) + 1; - - CHIP_ERROR err = CHIP_NO_ERROR; - char verifierB64[kSpake2pSerializedVerifier_MaxBase64Len] = { 0 }; - size_t verifierB64Len = 0; - - err = SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_Spake2pVerifier, verifierB64, sizeof(verifierB64), - verifierB64Len); - -#if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER) - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - verifierB64Len = strlen(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER); - ReturnErrorCodeIf(verifierB64Len > sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(verifierB64, CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER, verifierB64Len); - err = CHIP_NO_ERROR; - } -#endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER) - - ReturnErrorOnFailure(err); - - verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - - memcpy(verifierBuf.data(), verifierB64, verifierLen); - verifierBuf.reduce_size(verifierLen); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetSetupPayload(MutableCharSpan & payloadBuf) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - uint8_t payloadBitSet[kTotalPayloadDataSizeInBytes] = { 0 }; - size_t bitSetLen = 0; - - err = SilabsConfig::ReadConfigValueBin(SilabsConfig::kConfigKey_SetupPayloadBitSet, payloadBitSet, kTotalPayloadDataSizeInBytes, - bitSetLen); - -#if defined(CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE) && CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - static constexpr uint8_t kTestSetupPayloadBitset[] = { 0x88, 0xFF, 0x2F, 0x00, 0x44, 0x00, 0xE0, 0x4B, 0x84, 0x68, 0x02 }; - bitSetLen = sizeof(kTestSetupPayloadBitset); - ReturnErrorCodeIf(bitSetLen > kTotalPayloadDataSizeInBytes, CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(payloadBitSet, kTestSetupPayloadBitset, bitSetLen); - err = CHIP_NO_ERROR; - } -#endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER) - - ReturnErrorOnFailure(err); - - size_t prefixLen = strlen(kQRCodePrefix); - - if (payloadBuf.size() < prefixLen + 1) - { - err = CHIP_ERROR_BUFFER_TOO_SMALL; - } - else - { - MutableCharSpan subSpan = payloadBuf.SubSpan(prefixLen, payloadBuf.size() - prefixLen); - memcpy(payloadBuf.data(), kQRCodePrefix, prefixLen); - err = base38Encode(MutableByteSpan(payloadBitSet), subSpan); - // Reduce output span size to be the size of written data - payloadBuf.reduce_size(subSpan.size() + prefixLen); - } - - return err; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetVendorName(char * buf, size_t bufSize) -{ - size_t vendorNameLen = 0; // without counting null-terminator - return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_VendorName, buf, bufSize, vendorNameLen); -} - -CHIP_ERROR EFR32DeviceDataProvider::GetVendorId(uint16_t & vendorId) -{ - ChipError err = CHIP_NO_ERROR; - uint32_t vendorId32 = 0; - - err = SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_VendorId, vendorId32); - -#if defined(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID) && CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - vendorId32 = CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID; - err = CHIP_NO_ERROR; - } -#endif // defined(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID) && CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID - - ReturnErrorOnFailure(err); - vendorId = static_cast(vendorId32); - return err; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetProductName(char * buf, size_t bufSize) -{ - size_t productNameLen = 0; // without counting null-terminator - return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_ProductName, buf, bufSize, productNameLen); -} - -CHIP_ERROR EFR32DeviceDataProvider::GetProductId(uint16_t & productId) -{ - ChipError err = CHIP_NO_ERROR; - uint32_t productId32 = 0; - - err = SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_ProductId, productId32); - -#if defined(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID) && CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - productId32 = CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID; - err = CHIP_NO_ERROR; - } -#endif // defined(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID) && CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID - ReturnErrorOnFailure(err); - - productId = static_cast(productId32); - return err; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) -{ - size_t hardwareVersionStringLen = 0; // without counting null-terminator - CHIP_ERROR err = - SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_HardwareVersionString, buf, bufSize, hardwareVersionStringLen); -#if defined(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING) - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - memcpy(buf, CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING, bufSize); - err = CHIP_NO_ERROR; - } -#endif // CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING - return err; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetHardwareVersion(uint16_t & hardwareVersion) -{ - CHIP_ERROR err; - uint32_t hardwareVersion32; - - err = SilabsConfig::ReadConfigValue(SilabsConfig::kConfigKey_HardwareVersion, hardwareVersion32); -#if defined(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION) - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - hardwareVersion32 = CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION; - err = CHIP_NO_ERROR; - } -#endif // defined(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION) - - hardwareVersion = static_cast(hardwareVersion32); - return err; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) -{ - ChipError err = CHIP_ERROR_WRONG_KEY_TYPE; -#if CHIP_ENABLE_ROTATING_DEVICE_ID - static_assert(ConfigurationManager::kRotatingDeviceIDUniqueIDLength >= ConfigurationManager::kMinRotatingDeviceIDUniqueIDLength, - "Length of unique ID for rotating device ID is smaller than minimum."); - - size_t uniqueIdLen = 0; - err = - SilabsConfig::ReadConfigValueBin(SilabsConfig::kConfigKey_UniqueId, uniqueIdSpan.data(), uniqueIdSpan.size(), uniqueIdLen); -#ifdef CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID - if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - constexpr uint8_t uniqueId[] = CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID; - - ReturnErrorCodeIf(sizeof(uniqueId) > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(uniqueIdSpan.data(), uniqueId, sizeof(uniqueId)); - uniqueIdLen = sizeof(uniqueId); - } -#endif // CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID - - ReturnErrorOnFailure(err); - uniqueIdSpan.reduce_size(uniqueIdLen); - -#endif // CHIP_ENABLE_ROTATING_DEVICE_ID - return err; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetSerialNumber(char * buf, size_t bufSize) -{ - size_t serialNumberLen = 0; // without counting null-terminator - return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_SerialNum, buf, bufSize, serialNumberLen); -} - -CHIP_ERROR EFR32DeviceDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) -{ - CHIP_ERROR err; - constexpr uint8_t kDateStringLength = 10; // YYYY-MM-DD - char dateStr[kDateStringLength + 1]; - size_t dateLen; - char * parseEnd; - - err = SilabsConfig::ReadConfigValueBin(SilabsConfig::kConfigKey_ManufacturingDate, reinterpret_cast(dateStr), - sizeof(dateStr), dateLen); - SuccessOrExit(err); - - VerifyOrExit(dateLen == kDateStringLength, err = CHIP_ERROR_INVALID_ARGUMENT); - - // Cast does not lose information, because we then check that we only parsed - // 4 digits, so our number can't be bigger than 9999. - year = static_cast(strtoul(dateStr, &parseEnd, 10)); - VerifyOrExit(parseEnd == dateStr + 4, err = CHIP_ERROR_INVALID_ARGUMENT); - - // Cast does not lose information, because we then check that we only parsed - // 2 digits, so our number can't be bigger than 99. - month = static_cast(strtoul(dateStr + 5, &parseEnd, 10)); - VerifyOrExit(parseEnd == dateStr + 7, err = CHIP_ERROR_INVALID_ARGUMENT); - - // Cast does not lose information, because we then check that we only parsed - // 2 digits, so our number can't be bigger than 99. - day = static_cast(strtoul(dateStr + 8, &parseEnd, 10)); - VerifyOrExit(parseEnd == dateStr + 10, err = CHIP_ERROR_INVALID_ARGUMENT); - -exit: - if (err != CHIP_NO_ERROR && err != CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - ChipLogError(DeviceLayer, "Invalid manufacturing date: %s", dateStr); - } - return err; -} - -CHIP_ERROR EFR32DeviceDataProvider::GetPartNumber(char * buf, size_t bufSize) -{ - size_t partNumberLen = 0; // without counting null-terminator - return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_PartNumber, buf, bufSize, partNumberLen); -} - -CHIP_ERROR EFR32DeviceDataProvider::GetProductURL(char * buf, size_t bufSize) -{ - size_t productUrlLen = 0; // without counting null-terminator - return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_ProductURL, buf, bufSize, productUrlLen); -} - -CHIP_ERROR EFR32DeviceDataProvider::GetProductLabel(char * buf, size_t bufSize) -{ - size_t productLabelLen = 0; // without counting null-terminator - return SilabsConfig::ReadConfigValueStr(SilabsConfig::KConfigKey_ProductLabel, buf, bufSize, productLabelLen); -} - -EFR32DeviceDataProvider & EFR32DeviceDataProvider::GetDeviceDataProvider() -{ - static EFR32DeviceDataProvider sDataProvider; - return sDataProvider; -} - -} // namespace EFR32 -} // namespace DeviceLayer -} // namespace chip diff --git a/examples/platform/silabs/efr32/MemMonitoring.cpp b/examples/platform/silabs/efr32/MemMonitoring.cpp deleted file mode 100644 index 9da075e4e79d42..00000000000000 --- a/examples/platform/silabs/efr32/MemMonitoring.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "MemMonitoring.h" - -#include "AppConfig.h" -#include "FreeRTOS.h" -#include - -#define BLE_STACK_TASK_NAME "Bluetooth stack" -#define BLE_LINK_TASK_NAME "Bluetooth linklayer" - -static StackType_t monitoringStack[MONITORING_STACK_SIZE_byte / sizeof(StackType_t)]; -static StaticTask_t monitoringTaskStruct; - -size_t nbAllocSuccess = 0; -size_t nbFreeSuccess = 0; -size_t largestBlockAllocated = 0; - -void MemMonitoring::startHeapMonitoring() -{ - xTaskCreateStatic(HeapMonitoring, "Monitoring", MONITORING_STACK_SIZE_byte / sizeof(StackType_t), NULL, 1, monitoringStack, - &monitoringTaskStruct); -} - -void MemMonitoring::HeapMonitoring(void * pvParameter) -{ - - UBaseType_t appTaskValue; - UBaseType_t bleEventTaskValue; - UBaseType_t bleTaskValue; - UBaseType_t linkLayerTaskValue; - UBaseType_t openThreadTaskValue; - UBaseType_t eventLoopTaskValue; - - TaskHandle_t eventLoopHandleStruct = xTaskGetHandle(CHIP_DEVICE_CONFIG_CHIP_TASK_NAME); - TaskHandle_t otTaskHandle = xTaskGetHandle(CHIP_DEVICE_CONFIG_THREAD_TASK_NAME); - TaskHandle_t appTaskHandle = xTaskGetHandle(APP_TASK_NAME); - TaskHandle_t bleStackTaskHandle = xTaskGetHandle(BLE_STACK_TASK_NAME); - TaskHandle_t bleLinkTaskHandle = xTaskGetHandle(BLE_LINK_TASK_NAME); - TaskHandle_t bleEventTaskHandle = xTaskGetHandle(CHIP_DEVICE_CONFIG_BLE_APP_TASK_NAME); - -#if CHIP_SYSTEM_CONFIG_USE_LWIP - UBaseType_t lwipTaskValue; - TaskHandle_t lwipHandle = xTaskGetHandle(TCPIP_THREAD_NAME); -#endif // CHIP_SYSTEM_CONFIG_USE_LWIP - - while (true) - { - appTaskValue = uxTaskGetStackHighWaterMark(appTaskHandle); - bleEventTaskValue = uxTaskGetStackHighWaterMark(bleEventTaskHandle); - bleTaskValue = uxTaskGetStackHighWaterMark(bleStackTaskHandle); - linkLayerTaskValue = uxTaskGetStackHighWaterMark(bleLinkTaskHandle); - openThreadTaskValue = uxTaskGetStackHighWaterMark(otTaskHandle); - eventLoopTaskValue = uxTaskGetStackHighWaterMark(eventLoopHandleStruct); -#if CHIP_SYSTEM_CONFIG_USE_LWIP - lwipTaskValue = uxTaskGetStackHighWaterMark(lwipHandle); -#endif // CHIP_SYSTEM_CONFIG_USE_LWIP - - SILABS_LOG("============================="); - SILABS_LOG(" "); - SILABS_LOG("Largest Block allocated 0x%x", largestBlockAllocated); - SILABS_LOG("Number Of Successful Alloc 0x%x", nbAllocSuccess); - SILABS_LOG("Number Of Successful Frees 0x%x", nbFreeSuccess); - SILABS_LOG(" "); - SILABS_LOG("App Task most bytes ever Free 0x%x", (appTaskValue * 4)); - SILABS_LOG("BLE Event most bytes ever Free 0x%x", (bleEventTaskValue * 4)); - SILABS_LOG("BLE Stack most bytes ever Free 0x%x", (bleTaskValue * 4)); - SILABS_LOG("Link Layer Task most bytes ever Free 0x%x", (linkLayerTaskValue * 4)); - SILABS_LOG("OpenThread Task most bytes ever Free 0x%x", (openThreadTaskValue * 4)); - SILABS_LOG("Event Loop Task most bytes ever Free 0x%x", (eventLoopTaskValue * 4)); -#if CHIP_SYSTEM_CONFIG_USE_LWIP - SILABS_LOG("LWIP Task most bytes ever Free 0x%x", (lwipTaskValue * 4)); -#endif // CHIP_SYSTEM_CONFIG_USE_LWIP - SILABS_LOG(" "); - SILABS_LOG("============================="); - vTaskDelay(pdMS_TO_TICKS(5000)); - } -} - -extern "C" void memMonitoringTrackAlloc(void * ptr, size_t size) -{ - if (ptr != NULL) - { - nbAllocSuccess++; - if (largestBlockAllocated < size) - { - largestBlockAllocated = size; - } - } -} - -extern "C" void memMonitoringTrackFree(void * ptr, size_t size) -{ - nbFreeSuccess++; -} diff --git a/examples/platform/silabs/efr32/OTAConfig.cpp b/examples/platform/silabs/efr32/OTAConfig.cpp deleted file mode 100644 index 91c84054220b9c..00000000000000 --- a/examples/platform/silabs/efr32/OTAConfig.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "OTAConfig.h" - -#include "application_properties.h" -#include - -// Header used for building the image GBL file -#define APP_PROPERTIES_VERSION 1 -#define APP_PROPERTIES_ID \ - { \ - 0 \ - } - -__attribute__((used)) ApplicationProperties_t sl_app_properties = { - /// @brief Magic value indicating that this is an ApplicationProperties_t - /// Must equal @ref APPLICATION_PROPERTIES_MAGIC - .magic = APPLICATION_PROPERTIES_MAGIC, - - /// Version number of this struct - .structVersion = APPLICATION_PROPERTIES_VERSION, - - /// Type of signature this application is signed with - .signatureType = APPLICATION_SIGNATURE_NONE, - - /// Location of the signature. Typically a pointer to the end of application - .signatureLocation = 0, - - /// Information about the application - .app = { - - /// Bitfield representing type of application - /// e.g. @ref APPLICATION_TYPE_BLUETOOTH_APP - .type = APPLICATION_TYPE_THREAD, - - /// Version number for this application - .version = APP_PROPERTIES_VERSION, - - /// Capabilities of this application - .capabilities = 0, - - /// Unique ID (e.g. UUID/GUID) for the product this application is built for - .productId = APP_PROPERTIES_ID, - }, - - /// Pointer to information about the certificate - .cert = NULL, - - /// Pointer to Long Token Data Section - .longTokenSectionAddress = NULL, -}; - -// Global OTA objects -chip::DefaultOTARequestor gRequestorCore; -chip::DefaultOTARequestorStorage gRequestorStorage; -chip::DeviceLayer::DefaultOTARequestorDriver gRequestorUser; -chip::BDXDownloader gDownloader; -chip::OTAImageProcessorImpl gImageProcessor; - -void OTAConfig::Init() -{ - // Initialize and interconnect the Requestor and Image Processor objects -- START - SetRequestorInstance(&gRequestorCore); - - gRequestorStorage.Init(chip::Server::GetInstance().GetPersistentStorage()); - gRequestorCore.Init(chip::Server::GetInstance(), gRequestorStorage, gRequestorUser, gDownloader); - - // Periodic query timeout must be set prior to requestor being initialized - gRequestorUser.SetPeriodicQueryTimeout(OTA_PERIODIC_TIMEOUT); - gRequestorUser.Init(&gRequestorCore, &gImageProcessor); - - gImageProcessor.SetOTAImageFile("test.txt"); - gImageProcessor.SetOTADownloader(&gDownloader); - - // Connect the Downloader and Image Processor objects - gDownloader.SetImageProcessorDelegate(&gImageProcessor); - // Initialize and interconnect the Requestor and Image Processor objects -- END -} diff --git a/examples/platform/silabs/efr32/display/demo-ui.h b/examples/platform/silabs/efr32/display/demo-ui.h deleted file mode 100644 index 6197a4e73c71ef..00000000000000 --- a/examples/platform/silabs/efr32/display/demo-ui.h +++ /dev/null @@ -1,139 +0,0 @@ -/***************************************************************************/ /** - * @file - * @brief User Interface for demo. - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. - *www.silabs.com - ******************************************************************************* - * - * The licensor of this software is Silicon - *Laboratories Inc. Your use of this software is - *governed by the terms of Silicon Labs Master - *Software License Agreement (MSLA) available at - * www.silabs.com/about-us/legal/master-software-license-agreement. - *This software is distributed to you in Source Code - *format and is governed by the sections of the MSLA - *applicable to Source Code. - * - ******************************************************************************/ - -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include "glib.h" -/**************************************************************************/ /** - * DEMO UI uses the underlying DMD interface and the - *GLIB and exposes several wrapper functions to - *application. These functions are used to display - * different bitmaps for the demo. - * - ******************************************************************************/ - -#define APP_NAME_MAX_LENGTH 20 - -/******************************************************************************* - ******************************** ENUMS ************************************ - ******************************************************************************/ - -typedef enum -{ - DEMO_UI_PROTOCOL1, - DEMO_UI_PROTOCOL2 -} demoUIProtocol; - -typedef enum -{ - DEMO_UI_LIGHT_OFF, - DEMO_UI_LIGHT_ON -} demoUILightState_t; - -typedef enum -{ - DEMO_UI_DIRECTION_PROT1, - DEMO_UI_DIRECTION_PROT2, - DEMO_UI_DIRECTION_SWITCH, - DEMO_UI_DIRECTION_INVALID -} demoUILightDirection_t; - -typedef enum -{ - DEMO_UI_NO_NETWORK, - DEMO_UI_SCANNING, - DEMO_UI_JOINING, - DEMO_UI_FORMING, - DEMO_UI_NETWORK_UP, - DEMO_UI_STATE_UNKNOWN -} demoUIZigBeeNetworkState_t; - -/******************************************************************************* - ****************************** PROTOTYPES ********************************* - ******************************************************************************/ - -/**************************************************************************/ /** - * @brief - * Initilize the GLIB and DMD interfaces. - * - * @param[in] void - * - * @return - * void - *****************************************************************************/ -void demoUIInit(GLIB_Context_t * context); - -/**************************************************************************/ /** - * @brief - * Update the display with Silicon Labs logo and - *application name. - * - * @param[in] name name of the current application. - * - * @return - * void - *****************************************************************************/ -void demoUIDisplayHeader(char * name); - -/**************************************************************************/ /** - * @brief - * Update the display with App image. Bool state only - *for now. - * - * @param[in] on status of App - * - * @return - * void - *****************************************************************************/ -void demoUIDisplayApp(bool on); - -/**************************************************************************/ /** - * @brief - * Update the display to show if the bluetooth is - *connected to the mobile device. - * - * @param[in] bool, true if the Light is connected to - *mobile device, false otherwise. - * - * @return - * void - *****************************************************************************/ -void demoUIDisplayProtocol(demoUIProtocol protocol, bool isConnected); - -/**************************************************************************/ /** - * @brief - * Clear the Lcd screen and display the main screen. - * - * @param[in] name - application name - * @param[in] showPROT1 - show protocol 1 related icon. - * @param[in] showPROT2 - show protocol 2 related icon. - * - * @return - * void - *****************************************************************************/ -void demoUIClearMainScreen(uint8_t * name); - -#ifdef __cplusplus -} -#endif diff --git a/examples/platform/silabs/efr32/display/lcd.h b/examples/platform/silabs/efr32/display/lcd.h deleted file mode 100644 index d375b7a133c9aa..00000000000000 --- a/examples/platform/silabs/efr32/display/lcd.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "AppConfig.h" -#include "glib.h" -#ifdef QR_CODE_ENABLED -#include "qrcodegen.h" -#include -#endif // QR_CODE_ENABLED - -#include "demo-ui.h" - -#define MAX_STR_LEN 48 - -class SilabsLCD -{ - -public: - typedef void (*customUICB)(GLIB_Context_t * context); - CHIP_ERROR Init(uint8_t * name = nullptr, bool initialState = false); - void * Context(); - int Clear(void); - int DrawPixel(void * pContext, int32_t x, int32_t y); - int Update(void); - void WriteDemoUI(bool state); - void SetCustomUI(customUICB cb); - -#ifdef QR_CODE_ENABLED - void SetQRCode(uint8_t * str, uint32_t size); - void ShowQRCode(bool show, bool forceRefresh = false); - void ToggleQRCode(void); -#endif - -private: - typedef struct demoState - { - bool mainState = false; - bool protocol1 = false; /* data */ - } DemoState_t; - - void WriteQRCode(); - void WriteDemoUI(); -#ifdef QR_CODE_ENABLED - void LCDFillRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h); - char mQRCodeBuffer[chip::QRCodeBasicSetupPayloadGenerator::kMaxQRCodeBase38RepresentationLength + 1]; - bool mShowQRCode = true; -#endif - GLIB_Context_t glibContext; - -#ifdef SL_DEMO_NAME - uint8_t mName[] = SL_DEMO_NAME -#else - uint8_t mName[APP_NAME_MAX_LENGTH + 1]; -#endif - customUICB customUI = nullptr; - DemoState_t dState; -}; diff --git a/examples/platform/silabs/efr32/matter_config.cpp b/examples/platform/silabs/efr32/matter_config.cpp index b530d5aa934f38..14118d071e892b 100644 --- a/examples/platform/silabs/efr32/matter_config.cpp +++ b/examples/platform/silabs/efr32/matter_config.cpp @@ -53,11 +53,11 @@ using namespace ::chip::DeviceLayer; static chip::DeviceLayer::Internal::Efr32PsaOperationalKeystore gOperationalKeystore; #endif -#include "EFR32DeviceDataProvider.h" +#include "SilabsDeviceDataProvider.h" #include #ifdef CHIP_CONFIG_USE_ICD_SUBSCRIPTION_CALLBACKS -ICDSubscriptionCallback EFR32MatterConfig::mICDSubscriptionHandler; +ICDSubscriptionCallback SilabsMatterConfig::mICDSubscriptionHandler; #endif // CHIP_CONFIG_USE_ICD_SUBSCRIPTION_CALLBACKS #if CHIP_ENABLE_OPENTHREAD @@ -87,10 +87,10 @@ void UnlockOpenThreadTask(void) } // ================================================================================ -// EFR32MatterConfig Methods +// SilabsMatterConfig Methods // ================================================================================ -CHIP_ERROR EFR32MatterConfig::InitOpenThread(void) +CHIP_ERROR SilabsMatterConfig::InitOpenThread(void) { SILABS_LOG("Initializing OpenThread stack"); ReturnErrorOnFailure(ThreadStackMgr().InitThreadStack()); @@ -110,14 +110,14 @@ CHIP_ERROR EFR32MatterConfig::InitOpenThread(void) } #endif // CHIP_ENABLE_OPENTHREAD -#if EFR32_OTA_ENABLED -void EFR32MatterConfig::InitOTARequestorHandler(System::Layer * systemLayer, void * appState) +#if SILABS_OTA_ENABLED +void SilabsMatterConfig::InitOTARequestorHandler(System::Layer * systemLayer, void * appState) { OTAConfig::Init(); } #endif -void EFR32MatterConfig::ConnectivityEventCallback(const ChipDeviceEvent * event, intptr_t arg) +void SilabsMatterConfig::ConnectivityEventCallback(const ChipDeviceEvent * event, intptr_t arg) { // Initialize OTA only when Thread or WiFi connectivity is established if (((event->Type == DeviceEventType::kThreadConnectivityChange) && @@ -125,7 +125,7 @@ void EFR32MatterConfig::ConnectivityEventCallback(const ChipDeviceEvent * event, ((event->Type == DeviceEventType::kInternetConnectivityChange) && (event->InternetConnectivityChange.IPv6 == kConnectivity_Established))) { -#if EFR32_OTA_ENABLED +#if SILABS_OTA_ENABLED SILABS_LOG("Scheduling OTA Requestor initialization") chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(OTAConfig::kInitOTARequestorDelaySec), InitOTARequestorHandler, nullptr); @@ -133,7 +133,7 @@ void EFR32MatterConfig::ConnectivityEventCallback(const ChipDeviceEvent * event, } } -CHIP_ERROR EFR32MatterConfig::InitMatter(const char * appName) +CHIP_ERROR SilabsMatterConfig::InitMatter(const char * appName) { CHIP_ERROR err; @@ -159,8 +159,8 @@ CHIP_ERROR EFR32MatterConfig::InitMatter(const char * appName) ReturnErrorOnFailure(chip::Platform::MemoryInit()); ReturnErrorOnFailure(PlatformMgr().InitChipStack()); - SetDeviceInstanceInfoProvider(&EFR32::EFR32DeviceDataProvider::GetDeviceDataProvider()); - SetCommissionableDataProvider(&EFR32::EFR32DeviceDataProvider::GetDeviceDataProvider()); + SetDeviceInstanceInfoProvider(&Silabs::SilabsDeviceDataProvider::GetDeviceDataProvider()); + SetCommissionableDataProvider(&Silabs::SilabsDeviceDataProvider::GetDeviceDataProvider()); chip::DeviceLayer::ConnectivityMgr().SetBLEDeviceName(appName); @@ -223,7 +223,7 @@ CHIP_ERROR EFR32MatterConfig::InitMatter(const char * appName) } #ifdef SL_WIFI -void EFR32MatterConfig::InitWiFi(void) +void SilabsMatterConfig::InitWiFi(void) { #ifdef WF200_WIFI // Start wfx bus communication task. diff --git a/examples/platform/silabs/efr32/spi_multiplex.c b/examples/platform/silabs/efr32/spi_multiplex.c index 137c3973aa846e..6b8d6539d760c5 100644 --- a/examples/platform/silabs/efr32/spi_multiplex.c +++ b/examples/platform/silabs/efr32/spi_multiplex.c @@ -38,6 +38,11 @@ *****************************************************************************/ void spi_drv_reinit(uint32_t baudrate) { + if (USART_BaudrateGet(USART0) == baudrate) + { + // USART synced to baudrate already + return; + } // USART is used in MG24 + WF200 combination USART_InitSync_TypeDef usartInit = USART_INITSYNC_DEFAULT; usartInit.msbf = true; @@ -50,29 +55,6 @@ void spi_drv_reinit(uint32_t baudrate) USART_InitSync(USART0, &usartInit); } -/**************************************************************************** - * @fn void set_spi_baudrate() - * @brief - * Setting the appropriate SPI baudrate - * @param[in] None - * @return returns void - *****************************************************************************/ -void set_spi_baudrate(peripheraltype_t pr_type) -{ - if (pr_type == LCD) - { - spi_drv_reinit(LCD_BIT_RATE); - } - else if (pr_type == EXP_HDR) - { - spi_drv_reinit(EXP_HDR_BIT_RATE); - } - else if (pr_type == EXT_SPIFLASH) - { - spi_drv_reinit(SPI_FLASH_BIT_RATE); - } -} - /**************************************************************************** * @fn void spiflash_cs_assert() * @brief @@ -110,14 +92,10 @@ void pre_bootloader_spi_transfer(void) { return; } - /* - * CS for Expansion header controlled within GSDK, - * however we need to ensure CS for Expansion header is High/disabled before use of EXT SPI Flash - */ - sl_wfx_host_spi_cs_deassert(); /* * Assert CS pin for EXT SPI Flash */ + spi_drv_reinit(SL_BIT_RATE_SPI_FLASH); spiflash_cs_assert(); } @@ -150,11 +128,7 @@ void pre_lcd_spi_transfer(void) { return; } - if (pr_type != LCD) - { - pr_type = LCD; - set_spi_baudrate(pr_type); - } + spi_drv_reinit(SL_BIT_RATE_LCD); /*LCD CS is handled as part of LCD gsdk*/ } @@ -208,7 +182,6 @@ void post_uart_transfer(void) return; } GPIO_PinModeSet(gpioPortA, 8, gpioModeInputPull, 1); - set_spi_baudrate(EXP_HDR); xSemaphoreGive(spi_sem_sync_hdl); sl_wfx_host_enable_platform_interrupt(); sl_wfx_enable_irq(); diff --git a/examples/platform/silabs/efr32/spi_multiplex.h b/examples/platform/silabs/efr32/spi_multiplex.h index 865e93ff4d8b36..29835962a4dd85 100644 --- a/examples/platform/silabs/efr32/spi_multiplex.h +++ b/examples/platform/silabs/efr32/spi_multiplex.h @@ -25,23 +25,26 @@ extern "C" { #include "sl_mx25_flash_shutdown_usart_config.h" #include "sl_spidrv_exp_config.h" #include "sl_wfx_host_api.h" +#include "spidrv.h" -#define LCD_BIT_RATE 1100000 -#define EXP_HDR_BIT_RATE 16000000 -#define SPI_FLASH_BIT_RATE 16000000 - -typedef enum PERIPHERAL_TYPE -{ - EXP_HDR = 0, - LCD, - EXT_SPIFLASH, -} peripheraltype_t; +#define SL_BIT_RATE_LCD 1100000 +#define SL_BIT_RATE_EXP_HDR 16000000 +#define SL_BIT_RATE_SPI_FLASH 16000000 +#define SL_BIT_RATE_UART_CONSOLE 16000000 extern SemaphoreHandle_t spi_sem_sync_hdl; -extern peripheraltype_t pr_type; + +#ifdef RS911X_WIFI +extern SPIDRV_Handle_t sl_spidrv_eusart_exp_handle; +#define SL_SPIDRV_HANDLE sl_spidrv_eusart_exp_handle +#endif + +#ifdef WF200_WIFI +extern SPIDRV_Handle_t sl_spidrv_exp_handle; +#define SL_SPIDRV_HANDLE sl_spidrv_exp_handle +#endif void spi_drv_reinit(uint32_t); -void set_spi_baudrate(peripheraltype_t); void spiflash_cs_assert(void); void spiflash_cs_deassert(void); diff --git a/examples/platform/silabs/efr32/wf200/efr_spi.c b/examples/platform/silabs/efr32/wf200/efr_spi.c index 7422ec686f0b9d..927b9a5fb892fa 100644 --- a/examples/platform/silabs/efr32/wf200/efr_spi.c +++ b/examples/platform/silabs/efr32/wf200/efr_spi.c @@ -49,13 +49,11 @@ #include "sl_power_manager.h" #endif -#if defined(EFR32MG24) +#if SL_WIFI #include "spi_multiplex.h" StaticSemaphore_t spi_sem_peripharal; SemaphoreHandle_t spi_sem_sync_hdl; -peripheraltype_t pr_type = EXP_HDR; #endif -extern SPIDRV_Handle_t sl_spidrv_exp_handle; #define USART SL_WFX_HOST_PINOUT_SPI_PERIPHERAL @@ -90,8 +88,8 @@ sl_status_t sl_wfx_host_init_bus(void) spi_enabled = true; /* Assign allocated DMA channel */ - tx_dma_channel = sl_spidrv_exp_handle->txDMACh; - rx_dma_channel = sl_spidrv_exp_handle->rxDMACh; + tx_dma_channel = SL_SPIDRV_HANDLE->txDMACh; + rx_dma_channel = SL_SPIDRV_HANDLE->rxDMACh; /* * Route EUSART1 MOSI, MISO, and SCLK to the specified pins. CS is @@ -116,7 +114,7 @@ sl_status_t sl_wfx_host_init_bus(void) #if defined(EFR32MG24) spi_sem_sync_hdl = xSemaphoreCreateBinaryStatic(&spi_sem_peripharal); xSemaphoreGive(spi_sem_sync_hdl); -#endif +#endif /* EFR32MG24 */ return SL_STATUS_OK; } @@ -130,6 +128,7 @@ sl_status_t sl_wfx_host_init_bus(void) sl_status_t sl_wfx_host_deinit_bus(void) { vSemaphoreDelete(spi_sem); + vSemaphoreDelete(spi_sem_sync_hdl); // Stop DMAs. DMADRV_StopTransfer(rx_dma_channel); DMADRV_StopTransfer(tx_dma_channel); @@ -149,6 +148,12 @@ sl_status_t sl_wfx_host_deinit_bus(void) *****************************************************************************/ sl_status_t sl_wfx_host_spi_cs_assert() { + configASSERT(spi_sem_sync_hdl); + if (xSemaphoreTake(spi_sem_sync_hdl, portMAX_DELAY) != pdTRUE) + { + return SL_STATUS_TIMEOUT; + } + spi_drv_reinit(SL_BIT_RATE_EXP_HDR); GPIO_PinOutClear(SL_SPIDRV_EXP_CS_PORT, SL_SPIDRV_EXP_CS_PIN); return SL_STATUS_OK; } @@ -163,6 +168,7 @@ sl_status_t sl_wfx_host_spi_cs_assert() sl_status_t sl_wfx_host_spi_cs_deassert() { GPIO_PinOutSet(SL_SPIDRV_EXP_CS_PORT, SL_SPIDRV_EXP_CS_PIN); + xSemaphoreGive(spi_sem_sync_hdl); return SL_STATUS_OK; } @@ -258,19 +264,6 @@ void transmitDMA(uint8_t * buffer, uint16_t buffer_length) sl_status_t sl_wfx_host_spi_transfer_no_cs_assert(sl_wfx_host_bus_transfer_type_t type, uint8_t * header, uint16_t header_length, uint8_t * buffer, uint16_t buffer_length) { - sl_status_t result = SL_STATUS_FAIL; -#if defined(EFR32MG24) - if (pr_type != EXP_HDR) - { - pr_type = EXP_HDR; - set_spi_baudrate(pr_type); - } - if (xSemaphoreTake(spi_sem_sync_hdl, portMAX_DELAY) != pdTRUE) - { - return SL_STATUS_TIMEOUT; - } - sl_wfx_host_spi_cs_assert(); -#endif const bool is_read = (type == SL_WFX_BUS_READ); while (!(MY_USART->STATUS & USART_STATUS_TXBL)) @@ -298,34 +291,29 @@ sl_status_t sl_wfx_host_spi_transfer_no_cs_assert(sl_wfx_host_bus_transfer_type_ if (buffer_length > 0) { MY_USART->CMD = USART_CMD_CLEARRX | USART_CMD_CLEARTX; - if (xSemaphoreTake(spi_sem, portMAX_DELAY) == pdTRUE) + // Reset the semaphore + configASSERT(spi_sem); + if (xSemaphoreTake(spi_sem, portMAX_DELAY) != pdTRUE) { - if (is_read) - { - receiveDMA(buffer, buffer_length); - result = SL_STATUS_OK; - } - else - { - transmitDMA(buffer, buffer_length); - result = SL_STATUS_OK; - } + return SL_STATUS_TIMEOUT; + } - if (xSemaphoreTake(spi_sem, portMAX_DELAY) == pdTRUE) - { - xSemaphoreGive(spi_sem); - } + if (is_read) + { + receiveDMA(buffer, buffer_length); } else { - result = SL_STATUS_TIMEOUT; + transmitDMA(buffer, buffer_length); + } + // wait for dma_complete by using the same spi_semaphore + if (xSemaphoreTake(spi_sem, portMAX_DELAY) != pdTRUE) + { + return SL_STATUS_TIMEOUT; } + xSemaphoreGive(spi_sem); } -#if defined(EFR32MG24) - sl_wfx_host_spi_cs_deassert(); - xSemaphoreGive(spi_sem_sync_hdl); -#endif - return result; + return SL_STATUS_OK; } /**************************************************************************** diff --git a/examples/platform/silabs/efr32/matter_config.h b/examples/platform/silabs/matter_config.h similarity index 98% rename from examples/platform/silabs/efr32/matter_config.h rename to examples/platform/silabs/matter_config.h index e4acdb107bad1f..4983abac4189b1 100644 --- a/examples/platform/silabs/efr32/matter_config.h +++ b/examples/platform/silabs/matter_config.h @@ -26,7 +26,7 @@ #include "ICDSubscriptionCallback.h" #endif // CHIP_CONFIG_USE_ICD_SUBSCRIPTION_CALLBACKS -class EFR32MatterConfig +class SilabsMatterConfig { public: static CHIP_ERROR InitMatter(const char * appName); diff --git a/examples/platform/telink/common/include/AppConfigCommon.h b/examples/platform/telink/common/include/AppConfigCommon.h new file mode 100755 index 00000000000000..6af3da6bb213cc --- /dev/null +++ b/examples/platform/telink/common/include/AppConfigCommon.h @@ -0,0 +1,34 @@ +/* + * + * Copyright (c) 2022-2023 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 + +// 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 +#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) +#define SYSTEM_STATE_LED 7 +#if APP_USE_IDENTIFY_PWM +#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) +#endif diff --git a/examples/ota-requestor-app/telink/include/AppEvent.h b/examples/platform/telink/common/include/AppEventCommon.h similarity index 84% rename from examples/ota-requestor-app/telink/include/AppEvent.h rename to examples/platform/telink/common/include/AppEventCommon.h index 72554b4bb54b5a..0110cd3c840e63 100644 --- a/examples/ota-requestor-app/telink/include/AppEvent.h +++ b/examples/platform/telink/common/include/AppEventCommon.h @@ -35,7 +35,10 @@ struct AppEvent kEventType_IdentifyStart, kEventType_IdentifyStop, kEventType_Lighting, + kEventType_Thermostat, kEventType_Install, + kEventType_Contact, + kEventType_Start, }; uint16_t Type; @@ -56,6 +59,15 @@ struct AppEvent int32_t Actor; } LightingEvent; struct + { + uint8_t Action; + } ContactEvent; + struct + { + uint8_t Action; + int32_t Actor; + } StartEvent; + struct { LEDWidget * LedWidget; } UpdateLedStateEvent; diff --git a/examples/platform/telink/common/include/AppTaskCommon.h b/examples/platform/telink/common/include/AppTaskCommon.h new file mode 100644 index 00000000000000..01e02087687e08 --- /dev/null +++ b/examples/platform/telink/common/include/AppTaskCommon.h @@ -0,0 +1,113 @@ +/* + * + * Copyright (c) 2022-2023 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "AppConfig.h" +#include "AppEventCommon.h" + +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED +#include "LEDWidget.h" +#endif + +#if APP_USE_IDENTIFY_PWM +#include "PWMDevice.h" +#endif + +#include +#include +#include + +#include + +#if CONFIG_CHIP_FACTORY_DATA +#include +#endif + +#include + +#include + +using namespace ::chip; +using namespace ::chip::app; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; + +namespace { +constexpr EndpointId kExampleEndpointId = 1; +constexpr uint8_t kDefaultMinLevel = 0; +constexpr uint8_t kDefaultMaxLevel = 254; +constexpr uint8_t kButtonPushEvent = 1; +constexpr uint8_t kButtonReleaseEvent = 0; +} // namespace + +class AppTaskCommon +{ +public: + CHIP_ERROR StartApp(); + void PostEvent(AppEvent * event); + + static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); + +protected: + CHIP_ERROR InitCommonParts(void); + + void DispatchEvent(AppEvent * event); + void GetEvent(AppEvent * aEvent); + + void InitButtons(void); + + static void FactoryResetTimerTimeoutCallback(k_timer * timer); + static void FactoryResetTimerEventHandler(AppEvent * aEvent); + static void FactoryResetButtonEventHandler(void); + static void FactoryResetHandler(AppEvent * aEvent); + + static void StartBleAdvButtonEventHandler(void); + static void StartBleAdvHandler(AppEvent * aEvent); + +#if APP_USE_THREAD_START_BUTTON + static void StartThreadButtonEventHandler(void); + static void StartThreadHandler(AppEvent * aEvent); +#endif + +#if APP_USE_EXAMPLE_START_BUTTON + static void ExampleActionButtonEventHandler(void); + + void SetExampleButtonCallbacks(EventHandler aAction_CB); + EventHandler ExampleActionEventHandler; +#endif + + static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + +#if APP_USE_IDENTIFY_PWM + PWMDevice mPwmIdentifyLed; + + static void ActionIdentifyStateUpdateHandler(k_timer * timer); + static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); +#endif + +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED + static void UpdateLedStateEventHandler(AppEvent * aEvent); + static void LEDStateUpdateHandler(LEDWidget * ledWidget); + static void UpdateStatusLED(void); +#endif + +#if CONFIG_CHIP_FACTORY_DATA + chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; +#endif +}; diff --git a/examples/platform/telink/common/src/AppTaskCommon.cpp b/examples/platform/telink/common/src/AppTaskCommon.cpp new file mode 100644 index 00000000000000..37e8bf36d4846a --- /dev/null +++ b/examples/platform/telink/common/src/AppTaskCommon.cpp @@ -0,0 +1,583 @@ +/* + * + * Copyright (c) 2022-2023 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 "AppTaskCommon.h" +#include "AppTask.h" + +#include "ButtonManager.h" + +#include "ThreadUtil.h" + +#include +#include +#include +#include +#include + +#if CONFIG_CHIP_OTA_REQUESTOR +#include "OTAUtil.h" +#endif + +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); + +namespace { +constexpr int kFactoryResetCalcTimeout = 3000; +constexpr int kFactoryResetTriggerCntr = 3; +constexpr int kAppEventQueueSize = 10; + +#if APP_USE_IDENTIFY_PWM +constexpr uint32_t kIdentifyBlinkRateMs = 200; +constexpr uint32_t kIdentifyOkayOnRateMs = 50; +constexpr uint32_t kIdentifyOkayOffRateMs = 950; +constexpr uint32_t kIdentifyFinishOnRateMs = 950; +constexpr uint32_t kIdentifyFinishOffRateMs = 50; +constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; +constexpr uint32_t kIdentifyBreatheRateMs = 1000; + +const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; +#endif + +#if APP_SET_NETWORK_COMM_ENDPOINT_SEC +constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; +#endif + +K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); + +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED +LEDWidget sStatusLED; +#endif + +Button sFactoryResetButton; +Button sBleAdvStartButton; +#if APP_USE_EXAMPLE_START_BUTTON +Button sExampleActionButton; +#endif +#if APP_USE_THREAD_START_BUTTON +Button sThreadStartButton; +#endif + +k_timer sFactoryResetTimer; +uint8_t sFactoryResetCntr = 0; + +bool sIsThreadProvisioned = false; +bool sIsThreadEnabled = false; +bool sIsThreadAttached = false; +bool sHaveBLEConnections = false; + +#if APP_SET_DEVICE_INFO_PROVIDER +chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; +#endif + +#if APP_USE_IDENTIFY_PWM +void OnIdentifyTriggerEffect(Identify * identify) +{ + AppTaskCommon::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); +} + +Identify sIdentify = { + kExampleEndpointId, + [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStart"); }, + [](Identify *) { ChipLogProgress(Zcl, "OnIdentifyStop"); }, + EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, + OnIdentifyTriggerEffect, +}; +#endif + +#if CONFIG_CHIP_FACTORY_DATA +// NOTE! This key is for test/certification only and should not be available in production devices! +uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, + 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; +#endif +} // namespace + +class AppFabricTableDelegate : public FabricTable::Delegate +{ + void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) + { + if (chip::Server::GetInstance().GetFabricTable().FabricCount() == 0) + { + chip::Server::GetInstance().ScheduleFactoryReset(); + } + } +}; + +#if CONFIG_CHIP_LIB_SHELL +#include +#include + +static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) +{ + ARG_UNUSED(argc); + ARG_UNUSED(argv); + + shell_print(shell, "Performing board reboot..."); + sys_reboot(); +} + +SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), + SHELL_SUBCMD_SET_END); +SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); +#endif // CONFIG_CHIP_LIB_SHELL + +CHIP_ERROR AppTaskCommon::StartApp(void) +{ + CHIP_ERROR err = GetAppTask().Init(); + + if (err != CHIP_NO_ERROR) + { + LOG_ERR("AppTask Init fail"); + return err; + } + + AppEvent event = {}; + + while (true) + { + GetEvent(&event); + DispatchEvent(&event); + } +} + +CHIP_ERROR AppTaskCommon::InitCommonParts(void) +{ + CHIP_ERROR err; + LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + // Initialize status LED +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED + LEDWidget::InitGpio(LEDS_PORT); + LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); + sStatusLED.Init(SYSTEM_STATE_LED); + + UpdateStatusLED(); +#endif + + InitButtons(); + + // Initialize function button timer + k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); + k_timer_user_data_set(&sFactoryResetTimer, this); + +#if APP_USE_IDENTIFY_PWM + // Initialize PWM Identify led + err = GetAppTask().mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("Green IDENTIFY PWM Device Init fail"); + return err; + } + + GetAppTask().mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); +#endif + + // 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("mFactoryDataProvider.GetEnableKey() failed. Could not delegate a test event trigger"); + memset(sTestEventTriggerEnableKey, 0, sizeof(sTestEventTriggerEnableKey)); + } +#else + SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif + + // Init ZCL Data Model and start server + static CommonCaseDeviceServerInitParams initParams; + (void) initParams.InitializeStaticResourcesBeforeServerInit(); + ReturnErrorOnFailure(chip::Server::GetInstance().Init(initParams)); + +#if APP_SET_DEVICE_INFO_PROVIDER + gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); + chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); +#endif + +#if CONFIG_CHIP_OTA_REQUESTOR + InitBasicOTARequestor(); +#endif + + ConfigurationMgr().LogDeviceConfig(); + PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); + +#if APP_SET_NETWORK_COMM_ENDPOINT_SEC + // We only have network commissioning on endpoint 0. + // Set up a valid Network Commissioning cluster on endpoint 0 is done in + // src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.cpp + emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false); +#endif + + // 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); + + err = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("AppFabricTableDelegate fail"); + return err; + } + + return CHIP_NO_ERROR; +} + +void AppTaskCommon::InitButtons(void) +{ +#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE + sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); + sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); +#if APP_USE_THREAD_START_BUTTON + sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); +#endif +#if APP_USE_EXAMPLE_START_BUTTON + if (ExampleActionEventHandler) + { + sExampleActionButton.Configure(BUTTON_PORT, BUTTON_PIN_2, ExampleActionButtonEventHandler); + } +#endif +#else + sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); + sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); +#if APP_USE_THREAD_START_BUTTON + sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, StartThreadButtonEventHandler); +#endif +#if APP_USE_EXAMPLE_START_BUTTON + if (ExampleActionEventHandler) + { + sExampleActionButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_1, ExampleActionButtonEventHandler); + } +#endif +#endif + + ButtonManagerInst().AddButton(sFactoryResetButton); + ButtonManagerInst().AddButton(sBleAdvStartButton); +#if APP_USE_THREAD_START_BUTTON + ButtonManagerInst().AddButton(sThreadStartButton); +#endif +#if APP_USE_EXAMPLE_START_BUTTON + if (ExampleActionEventHandler) + { + ButtonManagerInst().AddButton(sExampleActionButton); + } +#endif +} + +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED +void AppTaskCommon::UpdateLedStateEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type == AppEvent::kEventType_UpdateLedState) + { + aEvent->UpdateLedStateEvent.LedWidget->UpdateState(); + } +} + +void AppTaskCommon::LEDStateUpdateHandler(LEDWidget * ledWidget) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateLedStateEventHandler; + event.UpdateLedStateEvent.LedWidget = ledWidget; + GetAppTask().PostEvent(&event); +} + +void AppTaskCommon::UpdateStatusLED() +{ + if (sIsThreadProvisioned && sIsThreadEnabled) + { + if (sIsThreadAttached) + { + sStatusLED.Blink(950, 50); + } + else + { + sStatusLED.Blink(100, 100); + } + } + else + { + sStatusLED.Blink(50, 950); + } +} +#endif + +#if APP_USE_IDENTIFY_PWM +void AppTaskCommon::ActionIdentifyStateUpdateHandler(k_timer * timer) +{ + AppEvent event; + event.Type = AppEvent::kEventType_UpdateLedState; + event.Handler = UpdateIdentifyStateEventHandler; + GetAppTask().PostEvent(&event); +} + +void AppTaskCommon::UpdateIdentifyStateEventHandler(AppEvent * aEvent) +{ + GetAppTask().mPwmIdentifyLed.UpdateAction(); +} + +void AppTaskCommon::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) +{ + AppEvent event; + event.Type = AppEvent::kEventType_IdentifyStart; + + switch (aEffect) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); + event.Handler = [](AppEvent *) { + GetAppTask().mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); + event.Handler = [](AppEvent *) { + GetAppTask().mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); + event.Handler = [](AppEvent *) { + GetAppTask().mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); + event.Handler = [](AppEvent *) { + GetAppTask().mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); + event.Handler = [](AppEvent *) { + GetAppTask().mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); + }; + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); + event.Handler = [](AppEvent *) { GetAppTask().mPwmIdentifyLed.StopAction(); }; + event.Type = AppEvent::kEventType_IdentifyStop; + break; + default: + ChipLogProgress(Zcl, "No identifier effect"); + return; + } + + GetAppTask().PostEvent(&event); +} +#endif + +void AppTaskCommon::StartBleAdvButtonEventHandler(void) +{ + AppEvent event; + + event.Type = AppEvent::kEventType_Button; + event.ButtonEvent.Action = kButtonPushEvent; + event.Handler = StartBleAdvHandler; + GetAppTask().PostEvent(&event); +} + +void AppTaskCommon::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 AppTaskCommon::FactoryResetButtonEventHandler(void) +{ + AppEvent event; + + event.Type = AppEvent::kEventType_Button; + event.ButtonEvent.Action = kButtonPushEvent; + event.Handler = FactoryResetHandler; + GetAppTask().PostEvent(&event); +} + +void AppTaskCommon::FactoryResetHandler(AppEvent * aEvent) +{ + if (sFactoryResetCntr == 0) + { + k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); + } + + sFactoryResetCntr++; + LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); + + if (sFactoryResetCntr == kFactoryResetTriggerCntr) + { + k_timer_stop(&sFactoryResetTimer); + sFactoryResetCntr = 0; + + chip::Server::GetInstance().ScheduleFactoryReset(); + } +} + +void AppTaskCommon::FactoryResetTimerTimeoutCallback(k_timer * timer) +{ + if (!timer) + { + return; + } + + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.Handler = FactoryResetTimerEventHandler; + GetAppTask().PostEvent(&event); +} + +void AppTaskCommon::FactoryResetTimerEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type != AppEvent::kEventType_Timer) + { + return; + } + + sFactoryResetCntr = 0; + LOG_INF("Factory Reset Trigger Counter is cleared"); +} + +#if APP_USE_THREAD_START_BUTTON +void AppTaskCommon::StartThreadButtonEventHandler(void) +{ + AppEvent event; + + event.Type = AppEvent::kEventType_Button; + event.ButtonEvent.Action = kButtonPushEvent; + event.Handler = StartThreadHandler; + GetAppTask().PostEvent(&event); +} + +void AppTaskCommon::StartThreadHandler(AppEvent * aEvent) +{ + LOG_INF("StartThreadHandler"); + if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) + { + // Switch context from BLE to Thread + Internal::BLEManagerImpl sInstance; + sInstance.SwitchToIeee802154(); + StartDefaultThreadNetwork(); + } + else + { + LOG_INF("Device already commissioned"); + } +} +#endif + +#if APP_USE_EXAMPLE_START_BUTTON +void AppTaskCommon::ExampleActionButtonEventHandler(void) +{ + AppEvent event; + + if (!GetAppTask().ExampleActionEventHandler) + { + return; + } + + event.Type = AppEvent::kEventType_Button; + event.ButtonEvent.Action = kButtonPushEvent; + event.Handler = GetAppTask().ExampleActionEventHandler; + GetAppTask().PostEvent(&event); +} + +void AppTaskCommon::SetExampleButtonCallbacks(EventHandler aAction_CB) +{ + ExampleActionEventHandler = aAction_CB; +} +#endif + +void AppTaskCommon::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) +{ + switch (event->Type) + { + case DeviceEventType::kCHIPoBLEAdvertisingChange: + sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED + UpdateStatusLED(); +#endif + break; + case DeviceEventType::kThreadStateChange: + sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); + sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); + sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED + UpdateStatusLED(); +#endif + break; + case DeviceEventType::kThreadConnectivityChange: +#if CONFIG_CHIP_OTA_REQUESTOR + if (event->ThreadConnectivityChange.Result == kConnectivity_Established) + { + InitBasicOTARequestor(); + } +#endif + break; + default: + break; + } +} + +void AppTaskCommon::PostEvent(AppEvent * aEvent) +{ + if (!aEvent) + return; + if (k_msgq_put(&sAppEventQueue, aEvent, K_NO_WAIT) != 0) + { + LOG_INF("PostEvent fail"); + } +} + +void AppTaskCommon::DispatchEvent(AppEvent * aEvent) +{ + if (!aEvent) + return; + if (aEvent->Handler) + { + aEvent->Handler(aEvent); + } + else + { + LOG_INF("Dropping event without handler"); + } +} + +void AppTaskCommon::GetEvent(AppEvent * aEvent) +{ + k_msgq_get(&sAppEventQueue, aEvent, K_FOREVER); +} diff --git a/examples/lighting-app/telink/src/main.cpp b/examples/platform/telink/common/src/mainCommon.cpp similarity index 100% rename from examples/lighting-app/telink/src/main.cpp rename to examples/platform/telink/common/src/mainCommon.cpp diff --git a/examples/platform/telink/pw_sys_io/sys_io_telink.cc b/examples/platform/telink/pw_sys_io/sys_io_telink.cc index 37af653075fdc6..ff40aeadd6e583 100644 --- a/examples/platform/telink/pw_sys_io/sys_io_telink.cc +++ b/examples/platform/telink/pw_sys_io/sys_io_telink.cc @@ -20,7 +20,7 @@ #include "pw_sys_io/sys_io.h" #include "zephyr/console/console.h" #include -#include +#include #ifdef CONFIG_USB #include diff --git a/examples/platform/telink/util/include/LEDWidget.h b/examples/platform/telink/util/include/LEDWidget.h index b1e25d4f91a703..de15216a1a8174 100644 --- a/examples/platform/telink/util/include/LEDWidget.h +++ b/examples/platform/telink/util/include/LEDWidget.h @@ -19,7 +19,7 @@ #include #include -#include +#include class LEDWidget { diff --git a/examples/platform/telink/util/src/ButtonManager.cpp b/examples/platform/telink/util/src/ButtonManager.cpp index 4c964ec1b60de4..bdfa0b812a1ad4 100644 --- a/examples/platform/telink/util/src/ButtonManager.cpp +++ b/examples/platform/telink/util/src/ButtonManager.cpp @@ -16,13 +16,11 @@ * limitations under the License. */ -#include #include #include #include #include #include -#include LOG_MODULE_REGISTER(ButtonManager); @@ -37,7 +35,10 @@ void button_pressed(const struct device * dev, struct gpio_callback * cb, uint32 void Button::Configure(const struct device * port, gpio_pin_t outPin, gpio_pin_t inPin, void (*callback)(void)) { - __ASSERT(device_is_ready(port), "%s is not ready\n", port->name); + if (!device_is_ready(port)) + { + LOG_ERR("%s is not ready\n", port->name); + } mPort = port; mOutPin = outPin; @@ -207,7 +208,10 @@ void Button::PollIRQ() void Button::Configure(const struct device * port, gpio_pin_t inPin, void (*callback)(void)) { - __ASSERT(device_is_ready(port), "%s is not ready\n", port->name); + if (!device_is_ready(port)) + { + LOG_ERR("%s is not ready\n", port->name); + } mPort = port; mInPin = inPin; diff --git a/examples/platform/telink/util/src/LEDWidget.cpp b/examples/platform/telink/util/src/LEDWidget.cpp index cefb8bbc1cb2a0..3e63c5e9e9d429 100644 --- a/examples/platform/telink/util/src/LEDWidget.cpp +++ b/examples/platform/telink/util/src/LEDWidget.cpp @@ -18,7 +18,10 @@ #include "LEDWidget.h" -#include +#include +#include + +LOG_MODULE_REGISTER(LEDWidget); const struct device * LEDWidget::mPort = NULL; static LEDWidget::LEDWidgetStateUpdateHandler sStateUpdateCallback; @@ -26,7 +29,10 @@ static LEDWidget::LEDWidgetStateUpdateHandler sStateUpdateCallback; void LEDWidget::InitGpio(const device * port) { mPort = port; - __ASSERT(device_is_ready(mPort), "%s is not ready\n", mPort->name); + if (!device_is_ready(mPort)) + { + LOG_ERR("%s is not ready\n", mPort->name); + } } void LEDWidget::SetStateUpdateCallback(LEDWidgetStateUpdateHandler stateUpdateCb) @@ -43,7 +49,10 @@ void LEDWidget::Init(gpio_pin_t 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); + if (ret < 0) + { + LOG_ERR("GPIO pin %d configure - fail. Status%d\n", mGPIONum, ret); + } k_timer_init(&mLedTimer, &LEDWidget::LedStateTimerHandler, nullptr); k_timer_user_data_set(&mLedTimer, this); @@ -91,7 +100,10 @@ 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); + if (ret < 0) + { + LOG_ERR("GPIO pin %d set -fail. Status: %d\n", mGPIONum, ret); + } } void LEDWidget::UpdateState() diff --git a/examples/platform/telink/util/src/PWMDevice.cpp b/examples/platform/telink/util/src/PWMDevice.cpp index c5e5e6a2374dc5..3bdc8509cb0afa 100644 --- a/examples/platform/telink/util/src/PWMDevice.cpp +++ b/examples/platform/telink/util/src/PWMDevice.cpp @@ -22,8 +22,8 @@ #include #include +#include #include -#include LOG_MODULE_DECLARE(app); diff --git a/examples/platform/telink/util/src/PigweedLogger.cpp b/examples/platform/telink/util/src/PigweedLogger.cpp index 82b2d9f11fd9e2..b1562ae7ee02fd 100644 --- a/examples/platform/telink/util/src/PigweedLogger.cpp +++ b/examples/platform/telink/util/src/PigweedLogger.cpp @@ -24,11 +24,11 @@ * needs to use HDLC/UART for another purpose like the RPC server. */ +#include #include #include #include #include -#include #include #include diff --git a/examples/platform/telink/util/src/ThreadUtil.cpp b/examples/platform/telink/util/src/ThreadUtil.cpp index dad09fe3e945eb..b8c13d54a11edd 100644 --- a/examples/platform/telink/util/src/ThreadUtil.cpp +++ b/examples/platform/telink/util/src/ThreadUtil.cpp @@ -23,7 +23,7 @@ #include #include -#include +#include #include diff --git a/examples/pump-app/telink/CMakeLists.txt b/examples/pump-app/telink/CMakeLists.txt index c5478b64704930..03f3012008517b 100755 --- a/examples/pump-app/telink/CMakeLists.txt +++ b/examples/pump-app/telink/CMakeLists.txt @@ -59,6 +59,7 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/pump-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) @@ -68,8 +69,9 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp - src/main.cpp src/PumpManager.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/pump-app/telink/include/AppConfig.h b/examples/pump-app/telink/include/AppConfig.h old mode 100755 new mode 100644 index 9d54306cc0bb40..a661fd8c3f25e6 --- a/examples/pump-app/telink/include/AppConfig.h +++ b/examples/pump-app/telink/include/AppConfig.h @@ -20,18 +20,14 @@ // ---- Pump Example App Config ---- -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#define APP_USE_EXAMPLE_START_BUTTON 1 +#define APP_USE_THREAD_START_BUTTON 1 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 0 +#define APP_USE_IDENTIFY_PWM 1 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 +#include "AppConfigCommon.h" -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 #define PUMP_STATE_LED 6 -#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) // Time it takes in ms for the simulated pump to move from one state to another. #define PUMP_START_PERIOS_MS 2000 diff --git a/examples/pump-app/telink/include/AppEvent.h b/examples/pump-app/telink/include/AppEvent.h deleted file mode 100644 index 3d9b6a28f56689..00000000000000 --- a/examples/pump-app/telink/include/AppEvent.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * - * Copyright (c) 2023 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_IdentifyStart, - kEventType_IdentifyStop, - kEventType_Lighting, - kEventType_Install, - kEventType_Start, - }; - - uint16_t Type; - - union - { - struct - { - uint8_t Action; - } ButtonEvent; - struct - { - void * Context; - } TimerEvent; - struct - { - uint8_t Action; - int32_t Actor; - } StartEvent; - struct - { - LEDWidget * LedWidget; - } UpdateLedStateEvent; - }; - - EventHandler Handler; -}; diff --git a/examples/pump-app/telink/include/AppTask.h b/examples/pump-app/telink/include/AppTask.h index a0ccc23a79dfcb..5d4537b38f54a5 100644 --- a/examples/pump-app/telink/include/AppTask.h +++ b/examples/pump-app/telink/include/AppTask.h @@ -18,75 +18,28 @@ #pragma once -#include "AppEvent.h" +#include "AppTaskCommon.h" #include "PumpManager.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.h" -#include - -#if CONFIG_CHIP_FACTORY_DATA -#include -#endif - -struct k_timer; -struct Identify; - -class AppTask +class AppTask : public AppTaskCommon { public: - CHIP_ERROR StartApp(); + void UpdateClusterState(); static void PostStartActionRequest(int32_t actor, PumpManager::Action_t action); - void PostEvent(AppEvent * event); - void UpdateClusterState(); - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); private: friend AppTask & GetAppTask(void); + friend class AppTaskCommon; CHIP_ERROR Init(void); - static void ActionIdentifyStateUpdateHandler(k_timer * timer); - static void ActionInitiated(PumpManager::Action_t action, int32_t actor); static void ActionCompleted(PumpManager::Action_t action, int32_t actor); - void DispatchEvent(AppEvent * event); - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - static void StartActionButtonEventHandler(void); - 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 StartActionEventHandler(AppEvent * aEvent); - static void StartBleAdvHandler(AppEvent * aEvent); - static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); - - static void LockActionEventHandler(AppEvent * event); - - static void InitButtons(void); static AppTask sAppTask; - PWMDevice mPwmIdentifyLed; - -#if CONFIG_CHIP_FACTORY_DATA - chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; -#endif }; inline AppTask & GetAppTask(void) diff --git a/examples/pump-app/telink/include/PumpManager.h b/examples/pump-app/telink/include/PumpManager.h index 986e2605e9fa15..230e858144712b 100644 --- a/examples/pump-app/telink/include/PumpManager.h +++ b/examples/pump-app/telink/include/PumpManager.h @@ -22,7 +22,7 @@ #include -#include "AppEvent.h" +#include "AppEventCommon.h" struct k_timer; @@ -86,9 +86,9 @@ class PumpManager void StartTimer(uint32_t aTimeoutMs); static void TimerEventHandler(k_timer * timer); - static void AutoRestartTimerEventHandler(const AppEvent & aEvent); + static void AutoRestartTimerEventHandler(AppEvent * aEvent); - static void PumpStartTimerEventHandler(const AppEvent & aEvent); + static void PumpStartTimerEventHandler(AppEvent * aEvent); static PumpManager sPump; }; diff --git a/examples/pump-app/telink/prj.conf b/examples/pump-app/telink/prj.conf index 6bd026d01cc298..de5cf119a6a831 100755 --- a/examples/pump-app/telink/prj.conf +++ b/examples/pump-app/telink/prj.conf @@ -26,9 +26,7 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=y -CONFIG_OPENTHREAD_FTD=n -CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 +CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=y CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings @@ -63,13 +61,5 @@ CONFIG_CHIP_FACTORY_DATA=n CONFIG_CHIP_FACTORY_DATA_BUILD=n CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management -CONFIG_PM=n -CONFIG_PM_DEVICE=n -CONFIG_CHIP_ENABLE_PM_DURING_BLE=n +CONFIG_PM=y diff --git a/examples/pump-app/telink/src/AppTask.cpp b/examples/pump-app/telink/src/AppTask.cpp index 7d7080d82fc721..30aeaf3828badb 100644 --- a/examples/pump-app/telink/src/AppTask.cpp +++ b/examples/pump-app/telink/src/AppTask.cpp @@ -17,487 +17,48 @@ */ #include "AppTask.h" - -#include "AppConfig.h" -#include "ButtonManager.h" #include "PumpManager.h" -#include "ThreadUtil.h" - -#include #include -#include -#include -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include - -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; - namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kPccClusterEndpoint = 1; -constexpr EndpointId kOnOffClusterEndpoint = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; -constexpr uint32_t kIdentifyBlinkRateMs = 200; -constexpr uint32_t kIdentifyOkayOnRateMs = 50; -constexpr uint32_t kIdentifyOkayOffRateMs = 950; -constexpr uint32_t kIdentifyFinishOnRateMs = 950; -constexpr uint32_t kIdentifyFinishOffRateMs = 50; -constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; -constexpr uint32_t kIdentifyBreatheRateMs = 1000; - -const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; - -#if CONFIG_CHIP_FACTORY_DATA -// NOTE! This key is for test/certification only and should not be available in production devices! -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; -#endif - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; +constexpr EndpointId kPccClusterEndpoint = 1; +constexpr EndpointId kOnOffClusterEndpoint = 1; #if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; LEDWidget sPumpStateLED; #endif - -Button sFactoryResetButton; -Button sPumpButton; -Button sThreadStartButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - -void OnIdentifyTriggerEffect(Identify * identify) -{ - AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); -} - -Identify sIdentify = { - kOnOffClusterEndpoint, - [](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(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); +#if APP_USE_EXAMPLE_START_BUTTON + SetExampleButtonCallbacks(StartActionEventHandler); +#endif + InitCommonParts(); - // Initialize status LED #if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); - sPumpStateLED.Init(PUMP_STATE_LED); sPumpStateLED.Set(!PumpMgr().IsStopped()); #endif - InitButtons(); - - // Initialize function button timer - k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); - k_timer_user_data_set(&sFactoryResetTimer, this); - - // Initialize PWM Identify led - CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("Green IDENTIFY PWM Device Init fail"); - return err; - } - - sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); - PumpMgr().Init(); PumpMgr().SetCallbacks(ActionInitiated, ActionCompleted); - // 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("mFactoryDataProvider.GetEnableKey() failed. Could not delegate a test event trigger"); - memset(sTestEventTriggerEnableKey, 0, sizeof(sTestEventTriggerEnableKey)); - } -#else - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); -#endif - - static CommonCaseDeviceServerInitParams initParams; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - 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); - - err = ConnectivityMgr().SetBLEDeviceName("Telink Pump"); + CHIP_ERROR err = ConnectivityMgr().SetBLEDeviceName("Telink Pump"); 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; } -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) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&event); - } -} - -void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) -{ - AppEvent event; - event.Type = AppEvent::kEventType_IdentifyStart; - - switch (aEffect) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); - event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; - event.Type = AppEvent::kEventType_IdentifyStop; - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - return; - } - - sAppTask.PostEvent(&event); -} - -void AppTask::StartActionButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartActionEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartActionEventHandler(AppEvent * aEvent) -{ - PumpManager::Action_t action = PumpManager::INVALID_ACTION; - int32_t actor = 0; - - if (aEvent->Type == AppEvent::kEventType_Start) - { - action = static_cast(aEvent->StartEvent.Action); - actor = aEvent->StartEvent.Actor; - } - else if (aEvent->Type == AppEvent::kEventType_Button) - { - action = PumpMgr().IsStopped() ? PumpManager::START_ACTION : PumpManager::STOP_ACTION; - actor = static_cast(AppEvent::kEventType_Button); - } - - if (action != PumpManager::INVALID_ACTION && !PumpMgr().InitiateAction(actor, action)) - LOG_INF("Action is already in progress or active."); -} - -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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -void AppTask::StartThreadButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartThreadHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartThreadHandler(AppEvent * aEvent) -{ - LOG_INF("StartThreadHandler"); - if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) - { - // Switch context from BLE to Thread - Internal::BLEManagerImpl sInstance; - sInstance.SwitchToIeee802154(); - StartDefaultThreadNetwork(); - } - else - { - LOG_INF("Device already commissioned"); - } -} - -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadConnectivityChange: -#if CONFIG_CHIP_OTA_REQUESTOR - if (event->ThreadConnectivityChange.Result == kConnectivity_Established) - { - InitBasicOTARequestor(); - } -#endif - break; - default: - break; - } -} - -void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_UpdateLedState; - event.Handler = UpdateIdentifyStateEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) -{ - sAppTask.mPwmIdentifyLed.UpdateAction(); -} - void AppTask::ActionInitiated(PumpManager::Action_t action, int32_t actor) { // If the action has been initiated by the pump, update the pump trait @@ -511,7 +72,9 @@ void AppTask::ActionInitiated(PumpManager::Action_t action, int32_t actor) LOG_INF("Pump Stop Action has been initiated"); } +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED sPumpStateLED.Blink(50, 50); +#endif } void AppTask::ActionCompleted(PumpManager::Action_t action, int32_t actor) @@ -522,12 +85,16 @@ void AppTask::ActionCompleted(PumpManager::Action_t action, int32_t actor) if (action == PumpManager::START_ACTION) { LOG_INF("Pump Start Action has been completed"); +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED sPumpStateLED.Set(true); +#endif } else if (action == PumpManager::STOP_ACTION) { LOG_INF("Pump Stop Action has been completed"); +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED sPumpStateLED.Set(false); +#endif } if (actor == static_cast(AppEvent::kEventType_Button)) @@ -546,108 +113,54 @@ void AppTask::PostStartActionRequest(int32_t actor, PumpManager::Action_t action sAppTask.PostEvent(&event); } -void AppTask::PostEvent(AppEvent * aEvent) +void AppTask::StartActionEventHandler(AppEvent * aEvent) { - if (k_msgq_put(&sAppEventQueue, aEvent, K_NO_WAIT) != 0) - { - LOG_INF("PostEvent fail"); - } -} + PumpManager::Action_t action = PumpManager::INVALID_ACTION; + int32_t actor = 0; -void AppTask::DispatchEvent(AppEvent * aEvent) -{ - if (aEvent->Handler) + if (aEvent->Type == AppEvent::kEventType_Start) { - aEvent->Handler(aEvent); + action = static_cast(aEvent->StartEvent.Action); + actor = aEvent->StartEvent.Actor; } - else + else if (aEvent->Type == AppEvent::kEventType_Button) { - LOG_INF("Dropping event without handler"); + action = PumpMgr().IsStopped() ? PumpManager::START_ACTION : PumpManager::STOP_ACTION; + actor = static_cast(AppEvent::kEventType_Button); } + + if (action != PumpManager::INVALID_ACTION && !PumpMgr().InitiateAction(actor, action)) + LOG_INF("Action is already in progress or active."); } void AppTask::UpdateClusterState() { - EmberStatus status; - - ChipLogProgress(NotSpecified, "UpdateClusterState"); - // Write the new values - bool onOffState = !PumpMgr().IsStopped(); - status = Clusters::OnOff::Attributes::OnOff::Set(kOnOffClusterEndpoint, onOffState); + EmberStatus status = Clusters::OnOff::Attributes::OnOff::Set(kOnOffClusterEndpoint, onOffState); if (status != EMBER_ZCL_STATUS_SUCCESS) { - ChipLogError(NotSpecified, "ERR: Updating On/Off state %x", status); + LOG_ERR("ERR: Updating On/Off state %x", status); } - int16_t maxPressure = PumpMgr().GetMaxPressure(); - - uint16_t maxSpeed = PumpMgr().GetMaxSpeed(); - - uint16_t maxFlow = PumpMgr().GetMaxFlow(); - - int16_t minConstPress = PumpMgr().GetMinConstPressure(); - - int16_t maxConstPress = PumpMgr().GetMaxConstPressure(); - - int16_t minCompPress = PumpMgr().GetMinCompPressure(); - - int16_t maxCompPress = PumpMgr().GetMaxCompPressure(); - + int16_t maxPressure = PumpMgr().GetMaxPressure(); + uint16_t maxSpeed = PumpMgr().GetMaxSpeed(); + uint16_t maxFlow = PumpMgr().GetMaxFlow(); + int16_t minConstPress = PumpMgr().GetMinConstPressure(); + int16_t maxConstPress = PumpMgr().GetMaxConstPressure(); + int16_t minCompPress = PumpMgr().GetMinCompPressure(); + int16_t maxCompPress = PumpMgr().GetMaxCompPressure(); uint16_t minConstSpeed = PumpMgr().GetMinConstSpeed(); - uint16_t maxConstSpeed = PumpMgr().GetMaxConstSpeed(); - - uint16_t minConstFlow = PumpMgr().GetMinConstFlow(); - - uint16_t maxConstFlow = PumpMgr().GetMaxConstFlow(); - - int16_t minConstTemp = PumpMgr().GetMinConstTemp(); - - int16_t maxConstTemp = PumpMgr().GetMaxConstTemp(); -} - -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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sPumpButton.Configure(BUTTON_PORT, BUTTON_PIN_2, StartActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sPumpButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_1, StartActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); -#endif - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sPumpButton); - ButtonManagerInst().AddButton(sThreadStartButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); + uint16_t minConstFlow = PumpMgr().GetMinConstFlow(); + uint16_t maxConstFlow = PumpMgr().GetMaxConstFlow(); + int16_t minConstTemp = PumpMgr().GetMinConstTemp(); + int16_t maxConstTemp = PumpMgr().GetMaxConstTemp(); + + LOG_INF("UpdateClusterState:\n maxPressure = %d,\t maxSpeed = %d,\t maxFlow = %d\n minConstPress = %d,\t " + "maxConstPress = %d\n minCompPress = %d,\t maxCompPress = %d\n minConstSpeed = %d,\t maxConstSpeed = %d\n" + "minConstFlow = %d,\t maxConstFlow = %d\n minConstTemp = %d,\t maxConstTemp = %d", + maxPressure, maxSpeed, maxFlow, minConstPress, maxConstPress, minCompPress, maxCompPress, minConstSpeed, maxConstSpeed, + minConstFlow, maxConstFlow, minConstTemp, maxConstTemp); } diff --git a/examples/pump-app/telink/src/PumpManager.cpp b/examples/pump-app/telink/src/PumpManager.cpp index 3e8654a1d8efa5..04d2a8a0763fa2 100644 --- a/examples/pump-app/telink/src/PumpManager.cpp +++ b/examples/pump-app/telink/src/PumpManager.cpp @@ -135,9 +135,9 @@ void PumpManager::TimerEventHandler(k_timer * timer) GetAppTask().PostEvent(&event); } -void PumpManager::AutoRestartTimerEventHandler(const AppEvent & aEvent) +void PumpManager::AutoRestartTimerEventHandler(AppEvent * aEvent) { - PumpManager * pump = static_cast(aEvent.TimerEvent.Context); + PumpManager * pump = static_cast(aEvent->TimerEvent.Context); int32_t actor = 0; // Make sure auto start timer is still armed. @@ -151,11 +151,11 @@ void PumpManager::AutoRestartTimerEventHandler(const AppEvent & aEvent) pump->InitiateAction(actor, START_ACTION); } -void PumpManager::PumpStartTimerEventHandler(const AppEvent & aEvent) +void PumpManager::PumpStartTimerEventHandler(AppEvent * aEvent) { Action_t actionCompleted = INVALID_ACTION; - PumpManager * pump = static_cast(aEvent.TimerEvent.Context); + PumpManager * pump = static_cast(aEvent->TimerEvent.Context); if (pump->mState == kState_StartInitiated) { diff --git a/examples/pump-app/telink/src/main.cpp b/examples/pump-app/telink/src/main.cpp deleted file mode 100644 index 71aa52f9d91901..00000000000000 --- a/examples/pump-app/telink/src/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright (c) 2023 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, CONFIG_CHIP_APP_LOG_LEVEL); - -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/pump-controller-app/telink/CMakeLists.txt b/examples/pump-controller-app/telink/CMakeLists.txt index 56721841de599f..d5eeb88ee6d202 100755 --- a/examples/pump-controller-app/telink/CMakeLists.txt +++ b/examples/pump-controller-app/telink/CMakeLists.txt @@ -59,6 +59,7 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/pump-controller-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) @@ -68,8 +69,9 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp - src/main.cpp src/PumpManager.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/pump-controller-app/telink/include/AppConfig.h b/examples/pump-controller-app/telink/include/AppConfig.h old mode 100755 new mode 100644 index 70ee2c5ca0f425..5dd793da63e67e --- a/examples/pump-controller-app/telink/include/AppConfig.h +++ b/examples/pump-controller-app/telink/include/AppConfig.h @@ -20,18 +20,14 @@ // ---- Pump Controller Example App Config ---- -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#define APP_USE_EXAMPLE_START_BUTTON 1 +#define APP_USE_THREAD_START_BUTTON 1 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 0 +#define APP_USE_IDENTIFY_PWM 1 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 +#include "AppConfigCommon.h" -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 #define PUMP_STATE_LED 6 -#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) // Time it takes in ms for the simulated pump to move from one state to another. #define PUMP_START_PERIOS_MS 2000 diff --git a/examples/pump-controller-app/telink/include/AppEvent.h b/examples/pump-controller-app/telink/include/AppEvent.h deleted file mode 100644 index 3d9b6a28f56689..00000000000000 --- a/examples/pump-controller-app/telink/include/AppEvent.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * - * Copyright (c) 2023 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_IdentifyStart, - kEventType_IdentifyStop, - kEventType_Lighting, - kEventType_Install, - kEventType_Start, - }; - - uint16_t Type; - - union - { - struct - { - uint8_t Action; - } ButtonEvent; - struct - { - void * Context; - } TimerEvent; - struct - { - uint8_t Action; - int32_t Actor; - } StartEvent; - struct - { - LEDWidget * LedWidget; - } UpdateLedStateEvent; - }; - - EventHandler Handler; -}; diff --git a/examples/pump-controller-app/telink/include/AppTask.h b/examples/pump-controller-app/telink/include/AppTask.h index a0ccc23a79dfcb..5d4537b38f54a5 100644 --- a/examples/pump-controller-app/telink/include/AppTask.h +++ b/examples/pump-controller-app/telink/include/AppTask.h @@ -18,75 +18,28 @@ #pragma once -#include "AppEvent.h" +#include "AppTaskCommon.h" #include "PumpManager.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.h" -#include - -#if CONFIG_CHIP_FACTORY_DATA -#include -#endif - -struct k_timer; -struct Identify; - -class AppTask +class AppTask : public AppTaskCommon { public: - CHIP_ERROR StartApp(); + void UpdateClusterState(); static void PostStartActionRequest(int32_t actor, PumpManager::Action_t action); - void PostEvent(AppEvent * event); - void UpdateClusterState(); - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); private: friend AppTask & GetAppTask(void); + friend class AppTaskCommon; CHIP_ERROR Init(void); - static void ActionIdentifyStateUpdateHandler(k_timer * timer); - static void ActionInitiated(PumpManager::Action_t action, int32_t actor); static void ActionCompleted(PumpManager::Action_t action, int32_t actor); - void DispatchEvent(AppEvent * event); - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - static void StartActionButtonEventHandler(void); - 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 StartActionEventHandler(AppEvent * aEvent); - static void StartBleAdvHandler(AppEvent * aEvent); - static void UpdateIdentifyStateEventHandler(AppEvent * aEvent); - - static void LockActionEventHandler(AppEvent * event); - - static void InitButtons(void); static AppTask sAppTask; - PWMDevice mPwmIdentifyLed; - -#if CONFIG_CHIP_FACTORY_DATA - chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; -#endif }; inline AppTask & GetAppTask(void) diff --git a/examples/pump-controller-app/telink/include/PumpManager.h b/examples/pump-controller-app/telink/include/PumpManager.h index 11c7b0886bd7b3..715bc45066274a 100644 --- a/examples/pump-controller-app/telink/include/PumpManager.h +++ b/examples/pump-controller-app/telink/include/PumpManager.h @@ -22,7 +22,7 @@ #include -#include "AppEvent.h" +#include "AppEventCommon.h" struct k_timer; @@ -72,9 +72,9 @@ class PumpManager void StartTimer(uint32_t aTimeoutMs); static void TimerEventHandler(k_timer * timer); - static void AutoRestartTimerEventHandler(const AppEvent & aEvent); + static void AutoRestartTimerEventHandler(AppEvent * aEvent); - static void PumpStartTimerEventHandler(const AppEvent & aEvent); + static void PumpStartTimerEventHandler(AppEvent * aEvent); static PumpManager sPump; }; diff --git a/examples/pump-controller-app/telink/prj.conf b/examples/pump-controller-app/telink/prj.conf index 07b9cd80e6bee4..66074d03470303 100755 --- a/examples/pump-controller-app/telink/prj.conf +++ b/examples/pump-controller-app/telink/prj.conf @@ -26,9 +26,7 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=y -CONFIG_OPENTHREAD_FTD=n -CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 +CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=y CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings @@ -63,13 +61,5 @@ CONFIG_CHIP_FACTORY_DATA=n CONFIG_CHIP_FACTORY_DATA_BUILD=n CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management -CONFIG_PM=n -CONFIG_PM_DEVICE=n -CONFIG_CHIP_ENABLE_PM_DURING_BLE=n +CONFIG_PM=y diff --git a/examples/pump-controller-app/telink/src/AppTask.cpp b/examples/pump-controller-app/telink/src/AppTask.cpp index 80dd632d2038f8..13bb753fe0d759 100644 --- a/examples/pump-controller-app/telink/src/AppTask.cpp +++ b/examples/pump-controller-app/telink/src/AppTask.cpp @@ -17,297 +17,46 @@ */ #include "AppTask.h" - -#include "AppConfig.h" -#include "ButtonManager.h" #include "PumpManager.h" -#include "ThreadUtil.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include - -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL - LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; - namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kPccClusterEndpoint = 1; -constexpr EndpointId kOnOffClusterEndpoint = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; -constexpr uint32_t kIdentifyBlinkRateMs = 200; -constexpr uint32_t kIdentifyOkayOnRateMs = 50; -constexpr uint32_t kIdentifyOkayOffRateMs = 950; -constexpr uint32_t kIdentifyFinishOnRateMs = 950; -constexpr uint32_t kIdentifyFinishOffRateMs = 50; -constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; -constexpr uint32_t kIdentifyBreatheRateMs = 1000; - -const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; - -#if CONFIG_CHIP_FACTORY_DATA -// NOTE! This key is for test/certification only and should not be available in production devices! -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; -#endif - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; +constexpr EndpointId kPccClusterEndpoint = 1; +constexpr EndpointId kOnOffClusterEndpoint = 1; #if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; LEDWidget sPumpStateLED; #endif - -Button sFactoryResetButton; -Button sPumpButton; -Button sThreadStartButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - -void OnIdentifyTriggerEffect(Identify * identify) -{ - AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); -} - -Identify sIdentify = { - kOnOffClusterEndpoint, - [](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(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); +#if APP_USE_EXAMPLE_START_BUTTON + SetExampleButtonCallbacks(StartActionEventHandler); +#endif + InitCommonParts(); - // Initialize status LED #if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); - sPumpStateLED.Init(PUMP_STATE_LED); sPumpStateLED.Set(!PumpMgr().IsStopped()); #endif - InitButtons(); - - // Initialize function button timer - k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); - k_timer_user_data_set(&sFactoryResetTimer, this); - - // Initialize PWM Identify led - CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("Green IDENTIFY PWM Device Init fail"); - return err; - } - - sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); - PumpMgr().Init(); PumpMgr().SetCallbacks(ActionInitiated, ActionCompleted); - // 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("mFactoryDataProvider.GetEnableKey() failed. Could not delegate a test event trigger"); - memset(sTestEventTriggerEnableKey, 0, sizeof(sTestEventTriggerEnableKey)); - } -#else - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); -#endif - - static CommonCaseDeviceServerInitParams initParams; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - 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); - - err = ConnectivityMgr().SetBLEDeviceName("Telink Pump Controller"); + CHIP_ERROR err = ConnectivityMgr().SetBLEDeviceName("Telink Pump Controller"); 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; } -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) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&event); - } -} - -void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) -{ - AppEvent event; - event.Type = AppEvent::kEventType_IdentifyStart; - - switch (aEffect) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); - event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; - event.Type = AppEvent::kEventType_IdentifyStop; - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - return; - } - - sAppTask.PostEvent(&event); -} - -void AppTask::StartActionButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartActionEventHandler; - sAppTask.PostEvent(&event); -} - void AppTask::StartActionEventHandler(AppEvent * aEvent) { PumpManager::Action_t action = PumpManager::INVALID_ACTION; @@ -328,176 +77,6 @@ void AppTask::StartActionEventHandler(AppEvent * aEvent) LOG_INF("Action is already in progress or active."); } -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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -void AppTask::StartThreadButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartThreadHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartThreadHandler(AppEvent * aEvent) -{ - LOG_INF("StartThreadHandler"); - if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) - { - // Switch context from BLE to Thread - Internal::BLEManagerImpl sInstance; - sInstance.SwitchToIeee802154(); - StartDefaultThreadNetwork(); - } - else - { - LOG_INF("Device already commissioned"); - } -} - -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadConnectivityChange: -#if CONFIG_CHIP_OTA_REQUESTOR - if (event->ThreadConnectivityChange.Result == kConnectivity_Established) - { - InitBasicOTARequestor(); - } -#endif - break; - default: - break; - } -} - -void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_UpdateLedState; - event.Handler = UpdateIdentifyStateEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) -{ - sAppTask.mPwmIdentifyLed.UpdateAction(); -} - void AppTask::ActionInitiated(PumpManager::Action_t action, int32_t actor) { // If the action has been initiated by the pump, update the pump trait @@ -511,7 +90,9 @@ void AppTask::ActionInitiated(PumpManager::Action_t action, int32_t actor) LOG_INF("Pump Stop Action has been initiated"); } +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED sPumpStateLED.Blink(50, 50); +#endif } void AppTask::ActionCompleted(PumpManager::Action_t action, int32_t actor) @@ -522,12 +103,16 @@ void AppTask::ActionCompleted(PumpManager::Action_t action, int32_t actor) if (action == PumpManager::START_ACTION) { LOG_INF("Pump Start Action has been completed"); +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED sPumpStateLED.Set(true); +#endif } else if (action == PumpManager::STOP_ACTION) { LOG_INF("Pump Stop Action has been completed"); +#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED sPumpStateLED.Set(false); +#endif } if (actor == static_cast(AppEvent::kEventType_Button)) @@ -546,67 +131,4 @@ void AppTask::PostStartActionRequest(int32_t actor, PumpManager::Action_t action sAppTask.PostEvent(&event); } -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 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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sPumpButton.Configure(BUTTON_PORT, BUTTON_PIN_2, StartActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sPumpButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_1, StartActionButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, BUTTON_PIN_2, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, BUTTON_PIN_2, StartBleAdvButtonEventHandler); -#endif - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sPumpButton); - ButtonManagerInst().AddButton(sThreadStartButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} diff --git a/examples/pump-controller-app/telink/src/PumpManager.cpp b/examples/pump-controller-app/telink/src/PumpManager.cpp index 18b7e655cabaf7..1c2a6ee693d607 100644 --- a/examples/pump-controller-app/telink/src/PumpManager.cpp +++ b/examples/pump-controller-app/telink/src/PumpManager.cpp @@ -135,9 +135,9 @@ void PumpManager::TimerEventHandler(k_timer * timer) GetAppTask().PostEvent(&event); } -void PumpManager::AutoRestartTimerEventHandler(const AppEvent & aEvent) +void PumpManager::AutoRestartTimerEventHandler(AppEvent * aEvent) { - PumpManager * pump = static_cast(aEvent.TimerEvent.Context); + PumpManager * pump = static_cast(aEvent->TimerEvent.Context); int32_t actor = 0; // Make sure auto start timer is still armed. @@ -151,11 +151,11 @@ void PumpManager::AutoRestartTimerEventHandler(const AppEvent & aEvent) pump->InitiateAction(actor, START_ACTION); } -void PumpManager::PumpStartTimerEventHandler(const AppEvent & aEvent) +void PumpManager::PumpStartTimerEventHandler(AppEvent * aEvent) { Action_t actionCompleted = INVALID_ACTION; - PumpManager * pump = static_cast(aEvent.TimerEvent.Context); + PumpManager * pump = static_cast(aEvent->TimerEvent.Context); if (pump->mState == kState_StartInitiated) { diff --git a/examples/pump-controller-app/telink/src/main.cpp b/examples/pump-controller-app/telink/src/main.cpp deleted file mode 100644 index 71aa52f9d91901..00000000000000 --- a/examples/pump-controller-app/telink/src/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright (c) 2023 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, CONFIG_CHIP_APP_LOG_LEVEL); - -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/temperature-measurement-app/telink/CMakeLists.txt b/examples/temperature-measurement-app/telink/CMakeLists.txt index 04233bf515e522..022eef1d319bce 100644 --- a/examples/temperature-measurement-app/telink/CMakeLists.txt +++ b/examples/temperature-measurement-app/telink/CMakeLists.txt @@ -59,6 +59,7 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/temperature-measurement-app + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include ) @@ -70,7 +71,8 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp src/SensorManager.cpp - src/main.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/temperature-measurement-app/telink/include/AppConfig.h b/examples/temperature-measurement-app/telink/include/AppConfig.h index f3daa577c44063..c2955144027fb2 100644 --- a/examples/temperature-measurement-app/telink/include/AppConfig.h +++ b/examples/temperature-measurement-app/telink/include/AppConfig.h @@ -20,14 +20,10 @@ // ---- Temperature measurement Example App Config ---- -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#define APP_USE_EXAMPLE_START_BUTTON 0 +#define APP_USE_THREAD_START_BUTTON 1 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 0 +#define APP_USE_IDENTIFY_PWM 0 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 - -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 +#include "AppConfigCommon.h" diff --git a/examples/temperature-measurement-app/telink/include/AppTask.h b/examples/temperature-measurement-app/telink/include/AppTask.h index b67d2ee6f1944a..f681fa37fa2378 100644 --- a/examples/temperature-measurement-app/telink/include/AppTask.h +++ b/examples/temperature-measurement-app/telink/include/AppTask.h @@ -18,65 +18,20 @@ #pragma once -#include "AppConfig.h" -#include "AppEvent.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.h" -#include +#include "AppTaskCommon.h" -#if CONFIG_CHIP_FACTORY_DATA -#include -#endif - -#include - -struct k_timer; - -class AppTask +class AppTask : public AppTaskCommon { -public: - CHIP_ERROR StartApp(void); - - void SetInitiateAction(PWMDevice::Action_t aAction, int32_t aActor, uint8_t * value); - void PostEvent(AppEvent * aEvent); - private: friend AppTask & GetAppTask(void); - CHIP_ERROR Init(void); - - void DispatchEvent(AppEvent * event); + friend class AppTaskCommon; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - static void FactoryResetButtonEventHandler(void); - static void StartThreadButtonEventHandler(void); - static void StartBleAdvButtonEventHandler(void); - - static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + CHIP_ERROR Init(void); static void TemperatureMeasurementTimerTimeoutCallback(k_timer * timer); static void TemperatureMeasurementTimerEventHandler(AppEvent * aEvent); - 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 InitButtons(void); - - static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); - static AppTask sAppTask; - -#if CONFIG_CHIP_FACTORY_DATA - chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; -#endif }; inline AppTask & GetAppTask(void) diff --git a/examples/temperature-measurement-app/telink/include/SensorManager.h b/examples/temperature-measurement-app/telink/include/SensorManager.h index b7059808601010..df1ffcf9378657 100644 --- a/examples/temperature-measurement-app/telink/include/SensorManager.h +++ b/examples/temperature-measurement-app/telink/include/SensorManager.h @@ -21,7 +21,7 @@ #include #include -#include "AppEvent.h" +#include "AppEventCommon.h" #include #include diff --git a/examples/temperature-measurement-app/telink/prj.conf b/examples/temperature-measurement-app/telink/prj.conf index 3c35726ec586cf..3f1a6e5bbc4e0d 100644 --- a/examples/temperature-measurement-app/telink/prj.conf +++ b/examples/temperature-measurement-app/telink/prj.conf @@ -26,9 +26,7 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=y -CONFIG_OPENTHREAD_FTD=n -CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 +CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=y CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings @@ -64,16 +62,8 @@ CONFIG_CHIP_FACTORY_DATA_BUILD=n CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management -CONFIG_PM=n -CONFIG_PM_DEVICE=n -CONFIG_CHIP_ENABLE_PM_DURING_BLE=n +CONFIG_PM=y # Custom RF power values CONFIG_B91_BLE_CTRL_RF_POWER_P9P11DBM=y diff --git a/examples/temperature-measurement-app/telink/src/AppTask.cpp b/examples/temperature-measurement-app/telink/src/AppTask.cpp index 9d84f94fa98d9b..38d99ed3b190ab 100644 --- a/examples/temperature-measurement-app/telink/src/AppTask.cpp +++ b/examples/temperature-measurement-app/telink/src/AppTask.cpp @@ -17,172 +17,26 @@ */ #include "AppTask.h" - -#include "AppConfig.h" -#include "AppEvent.h" -#include "ButtonManager.h" #include "SensorManager.h" -#include "ThreadUtil.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include - -#include - -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL - LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; - namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kEndpointId = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; - -#if CONFIG_CHIP_FACTORY_DATA -// NOTE! This key is for test/certification only and should not be available in production devices! -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; -#endif - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; - k_timer sTemperatureMeasurementTimer; constexpr uint16_t kSensorTimerPeriodMs = 5000; // 5s timer period - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; -#endif - -Button sFactoryResetButton; -Button sThreadStartButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - } // 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(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); - - // Initialize LEDs -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); -#endif - - InitButtons(); - - // Initialize function button timer - k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); - k_timer_user_data_set(&sFactoryResetTimer, this); + InitCommonParts(); // Initialize temperature measurement timer k_timer_init(&sTemperatureMeasurementTimer, &AppTask::TemperatureMeasurementTimerTimeoutCallback, nullptr); k_timer_user_data_set(&sTemperatureMeasurementTimer, this); k_timer_start(&sTemperatureMeasurementTimer, K_MSEC(kSensorTimerPeriodMs), K_NO_WAIT); - // 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; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - 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); - // Init Temperature Sensor CHIP_ERROR err = SensorMgr().Init(); if (err != CHIP_NO_ERROR) @@ -192,8 +46,8 @@ CHIP_ERROR AppTask::Init(void) } PlatformMgr().LockChipStack(); - app::Clusters::TemperatureMeasurement::Attributes::MinMeasuredValue::Set(kEndpointId, SensorMgr().GetMinMeasuredValue()); - app::Clusters::TemperatureMeasurement::Attributes::MaxMeasuredValue::Set(kEndpointId, SensorMgr().GetMaxMeasuredValue()); + app::Clusters::TemperatureMeasurement::Attributes::MinMeasuredValue::Set(kExampleEndpointId, SensorMgr().GetMinMeasuredValue()); + app::Clusters::TemperatureMeasurement::Attributes::MaxMeasuredValue::Set(kExampleEndpointId, SensorMgr().GetMaxMeasuredValue()); PlatformMgr().UnlockChipStack(); err = ConnectivityMgr().SetBLEDeviceName("TelinkTerm"); @@ -203,212 +57,9 @@ CHIP_ERROR AppTask::Init(void) 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; } -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) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -void AppTask::StartThreadButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartThreadHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartThreadHandler(AppEvent * aEvent) -{ - LOG_INF("StartThreadHandler"); - if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) - { - // Switch context from BLE to Thread - Internal::BLEManagerImpl sInstance; - sInstance.SwitchToIeee802154(); - StartDefaultThreadNetwork(); - } - else - { - LOG_INF("Device already commissioned"); - } -} - -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - 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::TemperatureMeasurementTimerTimeoutCallback(k_timer * timer) { if (!timer) @@ -430,7 +81,7 @@ void AppTask::TemperatureMeasurementTimerEventHandler(AppEvent * aEvent) } PlatformMgr().LockChipStack(); - app::Clusters::TemperatureMeasurement::Attributes::MeasuredValue::Set(kEndpointId, SensorMgr().GetMeasuredValue()); + app::Clusters::TemperatureMeasurement::Attributes::MeasuredValue::Set(kExampleEndpointId, SensorMgr().GetMeasuredValue()); PlatformMgr().UnlockChipStack(); LOG_INF("Current temperature is (%d*0.01)°C", SensorMgr().GetMeasuredValue()); @@ -438,44 +89,3 @@ void AppTask::TemperatureMeasurementTimerEventHandler(AppEvent * aEvent) // Start next timer to handle temp sensor. k_timer_start(&sTemperatureMeasurementTimer, K_MSEC(kSensorTimerPeriodMs), K_NO_WAIT); } - -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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - 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); -#endif - - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sThreadStartButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} diff --git a/examples/temperature-measurement-app/telink/src/SensorManager.cpp b/examples/temperature-measurement-app/telink/src/SensorManager.cpp index b108c59fab83a1..8ab8a42d9cc276 100644 --- a/examples/temperature-measurement-app/telink/src/SensorManager.cpp +++ b/examples/temperature-measurement-app/telink/src/SensorManager.cpp @@ -18,7 +18,6 @@ #include "SensorManager.h" #include "AppConfig.h" -#include "AppEvent.h" #include "AppTask.h" #define TEMPERATURE_SIMULATION_IS_USED diff --git a/examples/temperature-measurement-app/telink/src/main.cpp b/examples/temperature-measurement-app/telink/src/main.cpp deleted file mode 100644 index 71aa52f9d91901..00000000000000 --- a/examples/temperature-measurement-app/telink/src/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright (c) 2023 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, CONFIG_CHIP_APP_LOG_LEVEL); - -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/thermostat/silabs/efr32/src/main.cpp b/examples/thermostat/silabs/efr32/src/main.cpp index 5cfef676d77c8a..0af7a99a6a8dd9 100644 --- a/examples/thermostat/silabs/efr32/src/main.cpp +++ b/examples/thermostat/silabs/efr32/src/main.cpp @@ -50,7 +50,7 @@ static chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; int main(void) { init_efrPlatform(); - if (EFR32MatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) + if (SilabsMatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) appError(CHIP_ERROR_INTERNAL); gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage()); diff --git a/examples/thermostat/telink/CMakeLists.txt b/examples/thermostat/telink/CMakeLists.txt index e42891919e8b59..63744747849bfe 100755 --- a/examples/thermostat/telink/CMakeLists.txt +++ b/examples/thermostat/telink/CMakeLists.txt @@ -59,6 +59,7 @@ target_include_directories(app PRIVATE include ${GEN_DIR}/app-common ${GEN_DIR}/thermostat + ${TELINK_COMMON}/common/include ${TELINK_COMMON}/util/include ${TELINK_COMMON}/app/include) @@ -70,8 +71,9 @@ target_sources(app PRIVATE src/AppTask.cpp src/SensorManager.cpp src/TemperatureManager.cpp - src/main.cpp src/ZclCallbacks.cpp + ${TELINK_COMMON}/common/src/mainCommon.cpp + ${TELINK_COMMON}/common/src/AppTaskCommon.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp diff --git a/examples/thermostat/telink/include/AppConfig.h b/examples/thermostat/telink/include/AppConfig.h old mode 100755 new mode 100644 index 4e023cca312073..4b74db57e3091d --- a/examples/thermostat/telink/include/AppConfig.h +++ b/examples/thermostat/telink/include/AppConfig.h @@ -20,15 +20,10 @@ // ---- Thermostat Example App Config ---- -// Buttons config -#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) +#define APP_USE_EXAMPLE_START_BUTTON 0 +#define APP_USE_THREAD_START_BUTTON 1 +#define APP_SET_DEVICE_INFO_PROVIDER 1 +#define APP_SET_NETWORK_COMM_ENDPOINT_SEC 0 +#define APP_USE_IDENTIFY_PWM 1 // APP_USE_IDENTIFY_PWM must be defined before including "AppConfigCommon.h" -#define BUTTON_PIN_1 2 -#define BUTTON_PIN_3 3 -#define BUTTON_PIN_4 1 -#define BUTTON_PIN_2 0 - -// LEDs config -#define LEDS_PORT DEVICE_DT_GET(DT_NODELABEL(gpiob)) -#define SYSTEM_STATE_LED 7 -#define LIGHTING_PWM_SPEC_IDENTIFY_GREEN PWM_DT_SPEC_GET(DT_ALIAS(pwm_led3)) +#include "AppConfigCommon.h" diff --git a/examples/thermostat/telink/include/AppEvent.h b/examples/thermostat/telink/include/AppEvent.h deleted file mode 100755 index 3d5d5bc78d5883..00000000000000 --- a/examples/thermostat/telink/include/AppEvent.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -struct AppEvent; -typedef void (*EventHandler)(AppEvent *); - -class LEDWidget; - -struct AppEvent -{ - enum AppEventTypes - { - kEventType_Button = 0, - kEventType_Timer, - kEventType_UpdateLedState, - kEventType_IdentifyStart, - kEventType_IdentifyStop, - kEventType_Thermostat, - kEventType_Install, - }; - - uint16_t Type; - - union - { - struct - { - uint8_t Action; - } ButtonEvent; - struct - { - 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 facc5e7fb63d2e..8babf015ba4817 100755 --- a/examples/thermostat/telink/include/AppTask.h +++ b/examples/thermostat/telink/include/AppTask.h @@ -18,75 +18,23 @@ #pragma once -#include "AppEvent.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.h" +#include "AppTaskCommon.h" #include "SensorManager.h" #include "TemperatureManager.h" -#include - -#include - -#if CONFIG_CHIP_FACTORY_DATA -#include -#endif - -#include - -struct k_timer; -struct Identify; - -class AppTask +class AppTask : public AppTaskCommon { public: - CHIP_ERROR StartApp(void); - - void PostEvent(AppEvent * event); - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); - void UpdateClusterState(void); void UpdateThermoStatUI(void); private: friend AppTask & GetAppTask(void); - CHIP_ERROR Init(void); - - static void ActionIdentifyStateUpdateHandler(k_timer * timer); + friend class AppTaskCommon; - void DispatchEvent(AppEvent * event); - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - static void UpdateLedStateEventHandler(AppEvent * aEvent); - static void LEDStateUpdateHandler(LEDWidget * ledWidget); - static void UpdateStatusLED(); -#endif - 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 UpdateIdentifyStateEventHandler(AppEvent * aEvent); - - static void InitButtons(void); - - static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + CHIP_ERROR Init(void); static AppTask sAppTask; - PWMDevice mPwmIdentifyLed; - -#if CONFIG_CHIP_FACTORY_DATA - chip::DeviceLayer::FactoryDataProvider mFactoryDataProvider; -#endif }; inline AppTask & GetAppTask(void) diff --git a/examples/thermostat/telink/include/SensorManager.h b/examples/thermostat/telink/include/SensorManager.h index 828b3ef01d6120..2d2cdb9dd44fc6 100644 --- a/examples/thermostat/telink/include/SensorManager.h +++ b/examples/thermostat/telink/include/SensorManager.h @@ -21,7 +21,7 @@ #include #include -#include "AppEvent.h" +#include "AppEventCommon.h" #include #include diff --git a/examples/thermostat/telink/include/TemperatureManager.h b/examples/thermostat/telink/include/TemperatureManager.h index c55f064f8b8ecb..976e01ab86c523 100644 --- a/examples/thermostat/telink/include/TemperatureManager.h +++ b/examples/thermostat/telink/include/TemperatureManager.h @@ -21,7 +21,7 @@ #include #include -#include "AppEvent.h" +#include "AppEventCommon.h" #include diff --git a/examples/thermostat/telink/prj.conf b/examples/thermostat/telink/prj.conf index f2994ffd67ed78..827b3e7cbd32ff 100755 --- a/examples/thermostat/telink/prj.conf +++ b/examples/thermostat/telink/prj.conf @@ -26,9 +26,7 @@ CONFIG_PWM=y # OpenThread configs CONFIG_OPENTHREAD_MTD=y -CONFIG_OPENTHREAD_FTD=n -CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=n -CONFIG_CHIP_SED_IDLE_INTERVAL=200 +CONFIG_CHIP_ENABLE_SLEEPY_END_DEVICE_SUPPORT=y CONFIG_CHIP_THREAD_SSED=n # Default OpenThread network settings @@ -64,13 +62,5 @@ CONFIG_CHIP_FACTORY_DATA_BUILD=n CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE=n -# Enable Button IRQ mode. The poling mode is used by default. -CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE=n - -# Disable Status LED. -CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED=y - # Enable Power Management -CONFIG_PM=n -CONFIG_PM_DEVICE=n -CONFIG_CHIP_ENABLE_PM_DURING_BLE=n +CONFIG_PM=y diff --git a/examples/thermostat/telink/src/AppTask.cpp b/examples/thermostat/telink/src/AppTask.cpp index d7ab453dffce17..11b082e36b6e3e 100644 --- a/examples/thermostat/telink/src/AppTask.cpp +++ b/examples/thermostat/telink/src/AppTask.cpp @@ -18,194 +18,15 @@ #include "AppTask.h" -#include "AppConfig.h" -#include "AppEvent.h" -#include "ButtonManager.h" - -#include "ThreadUtil.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#if CONFIG_CHIP_OTA_REQUESTOR -#include "OTAUtil.h" -#endif - -#include -#include - -#include - -#if CONFIG_CHIP_LIB_SHELL -#include -#include - -static int cmd_telink_reboot(const struct shell * shell, size_t argc, char ** argv) -{ - ARG_UNUSED(argc); - ARG_UNUSED(argv); - - shell_print(shell, "Performing board reboot..."); - sys_reboot(); -} - -SHELL_STATIC_SUBCMD_SET_CREATE(sub_telink, SHELL_CMD(reboot, NULL, "Reboot board command", cmd_telink_reboot), - SHELL_SUBCMD_SET_END); -SHELL_CMD_REGISTER(telink, &sub_telink, "Telink commands", NULL); -#endif // CONFIG_CHIP_LIB_SHELL - LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); -using namespace ::chip; -using namespace ::chip::app; -using namespace ::chip::Credentials; -using namespace ::chip::DeviceLayer; - -namespace { -constexpr int kFactoryResetCalcTimeout = 3000; -constexpr int kFactoryResetTriggerCntr = 3; -constexpr int kAppEventQueueSize = 10; -constexpr uint8_t kButtonPushEvent = 1; -constexpr uint8_t kButtonReleaseEvent = 0; -constexpr EndpointId kEndpointId = 1; -constexpr uint8_t kDefaultMinLevel = 0; -constexpr uint8_t kDefaultMaxLevel = 254; -constexpr uint32_t kIdentifyBlinkRateMs = 200; -constexpr uint32_t kIdentifyOkayOnRateMs = 50; -constexpr uint32_t kIdentifyOkayOffRateMs = 950; -constexpr uint32_t kIdentifyFinishOnRateMs = 950; -constexpr uint32_t kIdentifyFinishOffRateMs = 50; -constexpr uint32_t kIdentifyChannelChangeRateMs = 1000; -constexpr uint32_t kIdentifyBreatheRateMs = 1000; - -const struct pwm_dt_spec sPwmIdentifySpecGreenLed = LIGHTING_PWM_SPEC_IDENTIFY_GREEN; - -#if CONFIG_CHIP_FACTORY_DATA -// NOTE! This key is for test/certification only and should not be available in production devices! -uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; -#endif - -K_MSGQ_DEFINE(sAppEventQueue, sizeof(AppEvent), kAppEventQueueSize, alignof(AppEvent)); -k_timer sFactoryResetTimer; -uint8_t sFactoryResetCntr = 0; - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -LEDWidget sStatusLED; -#endif - -Button sFactoryResetButton; -Button sThreadStartButton; -Button sBleAdvStartButton; - -bool sIsThreadProvisioned = false; -bool sIsThreadEnabled = false; -bool sIsThreadAttached = false; -bool sHaveBLEConnections = false; - -chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; - -void OnIdentifyTriggerEffect(Identify * identify) -{ - AppTask::IdentifyEffectHandler(identify->mCurrentEffectIdentifier); -} - -Identify sIdentify = { - kEndpointId, - [](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(void) { - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); - - // Initialize LEDs -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - LEDWidget::InitGpio(LEDS_PORT); - LEDWidget::SetStateUpdateCallback(LEDStateUpdateHandler); - sStatusLED.Init(SYSTEM_STATE_LED); - - UpdateStatusLED(); -#endif - - InitButtons(); - - // Initialize function button timer - k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr); - k_timer_user_data_set(&sFactoryResetTimer, this); - - // Initialize PWM Identify led - CHIP_ERROR err = sAppTask.mPwmIdentifyLed.Init(&sPwmIdentifySpecGreenLed, kDefaultMinLevel, kDefaultMaxLevel, kDefaultMaxLevel); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("Green IDENTIFY PWM Device Init fail"); - return err; - } - - sAppTask.mPwmIdentifyLed.SetCallbacks(nullptr, nullptr, ActionIdentifyStateUpdateHandler); - - // 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; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - 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)); + InitCommonParts(); - // 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); - - err = SensorMgr().Init(); + CHIP_ERROR err = SensorMgr().Init(); if (err != CHIP_NO_ERROR) { LOG_ERR("SensorMgr Init fail"); @@ -225,320 +46,13 @@ CHIP_ERROR AppTask::Init(void) 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; } -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) - { - k_msgq_get(&sAppEventQueue, &event, K_FOREVER); - DispatchEvent(&event); - } -} - -void AppTask::IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect) -{ - AppEvent event; - event.Type = AppEvent::kEventType_IdentifyStart; - - switch (aEffect) - { - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyBlinkRateMs, kIdentifyBlinkRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBreatheAction(PWMDevice::kBreatheType_Both, kIdentifyBreatheRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyOkayOnRateMs, kIdentifyOkayOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyChannelChangeRateMs, kIdentifyChannelChangeRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT"); - event.Handler = [](AppEvent *) { - sAppTask.mPwmIdentifyLed.InitiateBlinkAction(kIdentifyFinishOnRateMs, kIdentifyFinishOffRateMs); - }; - break; - case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT: - ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT"); - event.Handler = [](AppEvent *) { sAppTask.mPwmIdentifyLed.StopAction(); }; - event.Type = AppEvent::kEventType_IdentifyStop; - break; - default: - ChipLogProgress(Zcl, "No identifier effect"); - return; - } - - sAppTask.PostEvent(&event); -} - void AppTask::UpdateThermoStatUI(void) { LOG_INF("Thermostat Status - M:%d T:%d'C H:%d'C C:%d'C", TempMgr().GetMode(), TempMgr().GetCurrentTemp(), TempMgr().GetHeatingSetPoint(), TempMgr().GetCoolingSetPoint()); } -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 (sFactoryResetCntr == 0) - { - k_timer_start(&sFactoryResetTimer, K_MSEC(kFactoryResetCalcTimeout), K_NO_WAIT); - } - - sFactoryResetCntr++; - LOG_INF("Factory Reset Trigger Counter: %d/%d", sFactoryResetCntr, kFactoryResetTriggerCntr); - - if (sFactoryResetCntr == kFactoryResetTriggerCntr) - { - k_timer_stop(&sFactoryResetTimer); - sFactoryResetCntr = 0; - - chip::Server::GetInstance().ScheduleFactoryReset(); - } -} - -void AppTask::StartThreadButtonEventHandler(void) -{ - AppEvent event; - - event.Type = AppEvent::kEventType_Button; - event.ButtonEvent.Action = kButtonPushEvent; - event.Handler = StartThreadHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::StartThreadHandler(AppEvent * aEvent) -{ - LOG_INF("StartThreadHandler"); - if (!chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned()) - { - // Switch context from BLE to Thread - Internal::BLEManagerImpl sInstance; - sInstance.SwitchToIeee802154(); - StartDefaultThreadNetwork(); - } - else - { - LOG_INF("Device already commissioned"); - } -} - -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"); - } -} - -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -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); - } -} -#endif - -void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t /* arg */) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLEAdvertisingChange: - sHaveBLEConnections = ConnectivityMgr().NumBLEConnections() != 0; -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadStateChange: - sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); - sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); - sIsThreadAttached = ConnectivityMgr().IsThreadAttached(); -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED - UpdateStatusLED(); -#endif - break; - case DeviceEventType::kThreadConnectivityChange: -#if CONFIG_CHIP_OTA_REQUESTOR - if (event->ThreadConnectivityChange.Result == kConnectivity_Established) - { - InitBasicOTARequestor(); - } -#endif - break; - default: - break; - } -} - -void AppTask::ActionIdentifyStateUpdateHandler(k_timer * timer) -{ - AppEvent event; - event.Type = AppEvent::kEventType_UpdateLedState; - event.Handler = UpdateIdentifyStateEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::UpdateIdentifyStateEventHandler(AppEvent * aEvent) -{ - sAppTask.mPwmIdentifyLed.UpdateAction(); -} - -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 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; - } - - sFactoryResetCntr = 0; - LOG_INF("Factory Reset Trigger Counter is cleared"); -} - -void AppTask::InitButtons(void) -{ -#if CONFIG_CHIP_BUTTON_MANAGER_IRQ_MODE - sFactoryResetButton.Configure(BUTTON_PORT, BUTTON_PIN_1, FactoryResetButtonEventHandler); - sThreadStartButton.Configure(BUTTON_PORT, BUTTON_PIN_3, StartThreadButtonEventHandler); - sBleAdvStartButton.Configure(BUTTON_PORT, BUTTON_PIN_4, StartBleAdvButtonEventHandler); -#else - 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); -#endif - - ButtonManagerInst().AddButton(sFactoryResetButton); - ButtonManagerInst().AddButton(sThreadStartButton); - ButtonManagerInst().AddButton(sBleAdvStartButton); -} diff --git a/examples/thermostat/telink/src/SensorManager.cpp b/examples/thermostat/telink/src/SensorManager.cpp index 0dac8019360967..534a519b049cf4 100644 --- a/examples/thermostat/telink/src/SensorManager.cpp +++ b/examples/thermostat/telink/src/SensorManager.cpp @@ -18,7 +18,6 @@ #include "SensorManager.h" #include "AppConfig.h" -#include "AppEvent.h" #include "AppTask.h" LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); diff --git a/examples/thermostat/telink/src/TemperatureManager.cpp b/examples/thermostat/telink/src/TemperatureManager.cpp index b0e7929cf490f5..ca8b0eb4d98cb4 100644 --- a/examples/thermostat/telink/src/TemperatureManager.cpp +++ b/examples/thermostat/telink/src/TemperatureManager.cpp @@ -18,7 +18,6 @@ #include "TemperatureManager.h" #include "AppConfig.h" -#include "AppEvent.h" #include "AppTask.h" #include diff --git a/examples/thermostat/telink/src/main.cpp b/examples/thermostat/telink/src/main.cpp deleted file mode 100755 index 9dd145f55ba0c9..00000000000000 --- a/examples/thermostat/telink/src/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "AppTask.h" - -#include -#include - -#include - -LOG_MODULE_REGISTER(app, CONFIG_CHIP_APP_LOG_LEVEL); - -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/window-app/nrfconnect/CMakeLists.txt b/examples/window-app/nrfconnect/CMakeLists.txt index 92b43dc05fc779..21bb4caeb6194b 100644 --- a/examples/window-app/nrfconnect/CMakeLists.txt +++ b/examples/window-app/nrfconnect/CMakeLists.txt @@ -73,3 +73,7 @@ endif() if(CONFIG_MCUMGR_SMP_BT) target_sources(app PRIVATE ${NRFCONNECT_COMMON}/util/DFUOverSMP.cpp) endif() + +if(CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING) + target_sources(app PRIVATE ${NRFCONNECT_COMMON}/util/ICDUtil.cpp) +endif() diff --git a/examples/window-app/nrfconnect/main/AppTask.cpp b/examples/window-app/nrfconnect/main/AppTask.cpp index deb0cffb5e1a44..b0b3886a0a802f 100644 --- a/examples/window-app/nrfconnect/main/AppTask.cpp +++ b/examples/window-app/nrfconnect/main/AppTask.cpp @@ -35,6 +35,10 @@ #include "OTAUtil.h" #endif +#ifdef CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING +#include +#endif + #include #include #include @@ -191,6 +195,10 @@ CHIP_ERROR AppTask::Init() ConfigurationMgr().LogDeviceConfig(); PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); +#ifdef CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING + chip::app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(&GetICDUtil()); +#endif + // 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 diff --git a/examples/window-app/nrfconnect/main/include/AppTask.h b/examples/window-app/nrfconnect/main/include/AppTask.h index 9fbed1b2efba3b..4d134a791fa8fd 100644 --- a/examples/window-app/nrfconnect/main/include/AppTask.h +++ b/examples/window-app/nrfconnect/main/include/AppTask.h @@ -30,6 +30,10 @@ #include "DFUOverSMP.h" #endif +#ifdef CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING +#include "ICDUtil.h" +#endif + struct k_timer; struct Identify; diff --git a/examples/window-app/nrfconnect/prj.conf b/examples/window-app/nrfconnect/prj.conf index 3dc711bce86098..0f941b5aa1e6e8 100644 --- a/examples/window-app/nrfconnect/prj.conf +++ b/examples/window-app/nrfconnect/prj.conf @@ -36,6 +36,9 @@ CONFIG_CHIP_THREAD_SSED=y CONFIG_CHIP_SED_IDLE_INTERVAL=500 CONFIG_CHIP_SED_ACTIVE_INTERVAL=500 +# Enable ICD subscription platform specific handling +CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING=y + # Bluetooth Low Energy configuration CONFIG_BT_DEVICE_NAME="MatterWinCov" diff --git a/examples/window-app/nrfconnect/prj_no_dfu.conf b/examples/window-app/nrfconnect/prj_no_dfu.conf index d2da9b1a184eaa..b6caf7b75454e1 100644 --- a/examples/window-app/nrfconnect/prj_no_dfu.conf +++ b/examples/window-app/nrfconnect/prj_no_dfu.conf @@ -41,6 +41,9 @@ CONFIG_CHIP_THREAD_SSED=y CONFIG_CHIP_SED_IDLE_INTERVAL=500 CONFIG_CHIP_SED_ACTIVE_INTERVAL=500 +# Enable ICD subscription platform specific handling +CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING=y + # Bluetooth Low Energy configuration CONFIG_BT_DEVICE_NAME="MatterWinCov" diff --git a/examples/window-app/nrfconnect/prj_release.conf b/examples/window-app/nrfconnect/prj_release.conf index 336eb9ea95169f..bcf59cd9e35879 100644 --- a/examples/window-app/nrfconnect/prj_release.conf +++ b/examples/window-app/nrfconnect/prj_release.conf @@ -41,6 +41,9 @@ CONFIG_CHIP_THREAD_SSED=y CONFIG_CHIP_SED_IDLE_INTERVAL=500 CONFIG_CHIP_SED_ACTIVE_INTERVAL=500 +# Enable ICD subscription platform specific handling +CONFIG_CHIP_ICD_SUBSCRIPTION_HANDLING=y + # Bluetooth Low Energy configuration CONFIG_BT_DEVICE_NAME="MatterWinCov" diff --git a/examples/window-app/silabs/SiWx917/include/WindowAppImpl.h b/examples/window-app/silabs/SiWx917/include/WindowAppImpl.h index efaf194618b3a9..0acb38a4b1de22 100644 --- a/examples/window-app/silabs/SiWx917/include/WindowAppImpl.h +++ b/examples/window-app/silabs/SiWx917/include/WindowAppImpl.h @@ -44,6 +44,7 @@ class WindowAppImpl : public WindowApp { public: static WindowAppImpl sInstance; + bool mWindowAppInit = false; WindowAppImpl(); CHIP_ERROR Init() override; diff --git a/examples/window-app/silabs/SiWx917/src/WindowAppImpl.cpp b/examples/window-app/silabs/SiWx917/src/WindowAppImpl.cpp index 4cb033e349a366..108fd77f9f8e37 100644 --- a/examples/window-app/silabs/SiWx917/src/WindowAppImpl.cpp +++ b/examples/window-app/silabs/SiWx917/src/WindowAppImpl.cpp @@ -27,7 +27,7 @@ #ifdef QR_CODE_ENABLED #include #else -#include "SiWx917DeviceDataProvider.h" +#include "SilabsDeviceDataProvider.h" #include #include #endif // QR_CODE_ENABLED @@ -217,7 +217,7 @@ CHIP_ERROR WindowAppImpl::Init() char qrCodeBuffer[chip::QRCodeBasicSetupPayloadGenerator::kMaxQRCodeBase38RepresentationLength + 1]; chip::MutableCharSpan QRCode(qrCodeBuffer); - if (SIWx917::SIWx917DeviceDataProvider::GetDeviceDataProvider().GetSetupPayload(QRCode) == CHIP_NO_ERROR) + if (Silabs::SilabsDeviceDataProvider::GetDeviceDataProvider().GetSetupPayload(QRCode) == CHIP_NO_ERROR) { PrintQrCodeURL(QRCode); } @@ -227,6 +227,8 @@ CHIP_ERROR WindowAppImpl::Init() } #endif // QR_CODE_ENABLED + mWindowAppInit = true; + return CHIP_NO_ERROR; } @@ -531,14 +533,30 @@ WindowAppImpl::Button::Button(WindowApp::Button::Id id, const char * name) : Win void WindowAppImpl::OnButtonChange(uint8_t Btn, uint8_t btnAction) { WindowApp::Button * btn = static_cast