diff --git a/examples/temperature-measurement-app/telink/CMakeLists.txt b/examples/temperature-measurement-app/telink/CMakeLists.txt index d8dd3a478a3b85..04b3803882cc95 100644 --- a/examples/temperature-measurement-app/telink/CMakeLists.txt +++ b/examples/temperature-measurement-app/telink/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) 2022 Project CHIP Authors +# Copyright (c) 2023 Project CHIP Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -39,7 +39,8 @@ target_include_directories(app PRIVATE ${GEN_DIR}/app-common ${GEN_DIR}/temperature-measurement-app ${TELINK_COMMON}/util/include - ${TELINK_COMMON}/app/include) + ${TELINK_COMMON}/app/include + ) add_definitions( "-DCHIP_ADDRESS_RESOLVE_IMPL_INCLUDE_HEADER=" @@ -47,8 +48,8 @@ add_definitions( target_sources(app PRIVATE src/AppTask.cpp - src/main.cpp src/SensorManager.cpp + src/main.cpp ${TELINK_COMMON}/util/src/LEDWidget.cpp ${TELINK_COMMON}/util/src/ButtonManager.cpp ${TELINK_COMMON}/util/src/ThreadUtil.cpp @@ -63,157 +64,3 @@ chip_configure_data_model(app if(CONFIG_CHIP_OTA_REQUESTOR) target_sources(app PRIVATE ${TELINK_COMMON}/util/src/OTAUtil.cpp) endif() - -# Fix for unused swap parameter in: zephyr/include/zephyr/arch/riscv/irq.h:70 -add_compile_options(-Wno-error=unused-parameter) - -if (CONFIG_CHIP_PW_RPC) - -# Make all targets created below depend on zephyr_interface to inherit MCU-related compilation flags -link_libraries($) - -set(PIGWEED_ROOT "${CHIP_ROOT}/third_party/pigweed/repo") -include(${PIGWEED_ROOT}/pw_build/pigweed.cmake) -include(${PIGWEED_ROOT}/pw_protobuf_compiler/proto.cmake) - -include($ENV{PW_ROOT}/pw_assert/backend.cmake) -include($ENV{PW_ROOT}/pw_log/backend.cmake) -include($ENV{PW_ROOT}/pw_sys_io/backend.cmake) - -pw_set_module_config(pw_rpc_CONFIG pw_rpc.disable_global_mutex_config) -pw_set_backend(pw_log pw_log_basic) -pw_set_backend(pw_assert.check pw_assert_log.check_backend) -pw_set_backend(pw_assert.assert pw_assert.assert_compatibility_backend) -pw_set_backend(pw_sys_io pw_sys_io.telink) - -set(dir_pw_third_party_nanopb "${CHIP_ROOT}/third_party/nanopb/repo" CACHE STRING "" FORCE) - -add_subdirectory(third_party/connectedhomeip/third_party/pigweed/repo) -add_subdirectory(third_party/connectedhomeip/third_party/nanopb/repo) -add_subdirectory(third_party/connectedhomeip/examples/platform/telink/pw_sys_io) - -pw_proto_library(attributes_service - SOURCES - ${CHIP_ROOT}/examples/common/pigweed/protos/attributes_service.proto - INPUTS - ${CHIP_ROOT}/examples/common/pigweed/protos/attributes_service.options - PREFIX - attributes_service - STRIP_PREFIX - ${CHIP_ROOT}/examples/common/pigweed/protos - DEPS - pw_protobuf.common_proto -) - -pw_proto_library(button_service - SOURCES - ${CHIP_ROOT}/examples/common/pigweed/protos/button_service.proto - PREFIX - button_service - STRIP_PREFIX - ${CHIP_ROOT}/examples/common/pigweed/protos - DEPS - pw_protobuf.common_proto -) - -pw_proto_library(descriptor_service - SOURCES - ${CHIP_ROOT}/examples/common/pigweed/protos/descriptor_service.proto - PREFIX - descriptor_service - STRIP_PREFIX - ${CHIP_ROOT}/examples/common/pigweed/protos - DEPS - pw_protobuf.common_proto -) - -pw_proto_library(device_service - SOURCES - ${CHIP_ROOT}/examples/common/pigweed/protos/device_service.proto - INPUTS - ${CHIP_ROOT}/examples/common/pigweed/protos/device_service.options - PREFIX - device_service - STRIP_PREFIX - ${CHIP_ROOT}/examples/common/pigweed/protos - DEPS - pw_protobuf.common_proto -) - -pw_proto_library(lighting_service - SOURCES - ${CHIP_ROOT}/examples/common/pigweed/protos/lighting_service.proto - STRIP_PREFIX - ${CHIP_ROOT}/examples/common/pigweed/protos - PREFIX - lighting_service - DEPS - pw_protobuf.common_proto -) - -pw_proto_library(ot_cli_service - SOURCES - ${CHIP_ROOT}/examples/common/pigweed/protos/ot_cli_service.proto - INPUTS - ${CHIP_ROOT}/examples/common/pigweed/protos/ot_cli_service.options - STRIP_PREFIX - ${CHIP_ROOT}/examples/common/pigweed/protos - PREFIX - ot_cli_service - DEPS - pw_protobuf.common_proto -) - -pw_proto_library(thread_service - SOURCES - ${CHIP_ROOT}/examples/common/pigweed/protos/thread_service.proto - INPUTS - ${CHIP_ROOT}/examples/common/pigweed/protos/thread_service.options - STRIP_PREFIX - ${CHIP_ROOT}/examples/common/pigweed/protos - PREFIX - thread_service - DEPS - pw_protobuf.common_proto -) - -target_sources(app PRIVATE - ../../common/pigweed/RpcService.cpp - ../../common/pigweed/telink/PigweedLoggerMutex.cpp - ${TELINK_COMMON}/Rpc.cpp - ${TELINK_COMMON}/util/src/PigweedLogger.cpp -) - -target_include_directories(app PRIVATE - ${PIGWEED_ROOT}/pw_sys_io/public - ${CHIP_ROOT}/src/lib/support - ${CHIP_ROOT}/src/system - ${TELINK_COMMON} - ../../common - ../../common/pigweed - ../../common/pigweed/telink) - -target_compile_options(app PRIVATE - "-DPW_RPC_ATTRIBUTE_SERVICE=1" - "-DPW_RPC_BUTTON_SERVICE=1" - "-DPW_RPC_DESCRIPTOR_SERVICE=1" - "-DPW_RPC_DEVICE_SERVICE=1" - "-DPW_RPC_LIGHTING_SERVICE=1" - "-DPW_RPC_THREAD_SERVICE=1") - -target_link_libraries(app PRIVATE - attributes_service.nanopb_rpc - button_service.nanopb_rpc - descriptor_service.nanopb_rpc - device_service.nanopb_rpc - lighting_service.nanopb_rpc - thread_service.nanopb_rpc - pw_checksum - pw_hdlc - pw_hdlc.pw_rpc - pw_log - pw_rpc.server - pw_sys_io -) - -endif(CONFIG_CHIP_PW_RPC) diff --git a/examples/temperature-measurement-app/telink/README.md b/examples/temperature-measurement-app/telink/README.md index 1815f307a4e3ed..34c8f257ef6763 100644 --- a/examples/temperature-measurement-app/telink/README.md +++ b/examples/temperature-measurement-app/telink/README.md @@ -1,188 +1,178 @@ -# Matter Telink Temperature Measurement Example Application - -The Telink Temperature Measurement Example demonstrates getting simulated data from temperature sensor. -In further releases the real sensor handling will be implemented along. It uses buttons to test changing the device -states and LEDs to show the state of these changes. You can use this example as -a reference for creating your own application. - -![Telink B91 EVK](http://wiki.telink-semi.cn/wiki/assets/Hardware/B91_Generic_Starter_Kit_Hardware_Guide/connection_chart.png) - -## Build and flash - -1. Pull docker image from repository: - - ```bash - $ docker pull connectedhomeip/chip-build-telink:latest - ``` - -1. Run docker container: - - ```bash - $ docker run -it --rm -v ${CHIP_BASE}:/root/chip -v /dev/bus/usb:/dev/bus/usb --device-cgroup-rule "c 189:* rmw" connectedhomeip/chip-build-telink:latest - ``` - - here `${CHIP_BASE}` is directory which contains CHIP repo files **!!!Pay - attention that OUTPUT_DIR should contains ABSOLUTE path to output dir** - -1. Activate the build environment: - - ```bash - $ source ./scripts/activate.sh - ``` - -1. In the example dir run: - - ```bash - $ west build - ``` - -1. Flash binary: - - ``` - $ west flash --erase - ``` - -## Usage - -### UART - -To get output from device, connect UART to following pins: - -| Name | Pin | -| :--: | :---------------------------- | -| RX | PB3 (pin 17 of J34 connector) | -| TX | PB2 (pin 16 of J34 connector) | -| GND | GND | - -### Buttons - -The following buttons are available on **tlsr9518adk80d** board: - -| Name | Function | Description | -| :------- | :--------------------- | :----------------------------------------------------------------------------------------------------- | -| Button 1 | Factory reset | Perform factory reset to forget currently commissioned Thread network and back to uncommissioned state | -| Button 3 | Thread start | Commission thread with static credentials and enables the Thread on device | -| Button 4 | Open commission window | The button is opening commissioning window to perform commissioning over BLE | - -### LEDs - -#### Indicate current state of Thread network - -**Red** LED indicates current state of Thread network. It is able to be in -following states: - -| State | Description | -| :-------------------------- | :--------------------------------------------------------------------------- | -| Blinks with short pulses | Device is not commissioned to Thread, Thread is disabled | -| Blinks with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | -| Blinks with wide pulses | Device commissioned and joined to thread network as CHILD | - -#### Indicate identify of device - -**Green** LED used to identify the device. The LED starts blinking when the -Identify command of the Identify cluster is received. The command's argument can -be used to specify the the effect. It is able to be in following effects: - -| Effect | Description | -| :------------------------------ | :------------------------------------------------------------------- | -| Blinks (200 ms on/200 ms off) | Blink (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK) | -| Breathe (during 1000 ms) | Breathe (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE) | -| Blinks (50 ms on/950 ms off) | Okay (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY) | -| Blinks (1000 ms on/1000 ms off) | Channel Change (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE) | -| Blinks (950 ms on/50 ms off) | Finish (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT) | -| LED off | Stop (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT) | - -### CHIP tool commands - -1. Build - [chip-tool cli](https://github.com/project-chip/connectedhomeip/blob/master/examples/chip-tool/README.md) - -2. Pair with device - - ``` - ${CHIP_TOOL_DIR}/chip-tool pairing ble-thread ${NODE_ID} hex:${DATASET} ${PIN_CODE} ${DISCRIMINATOR} - ``` - - Example: - - ``` - ./chip-tool pairing ble-thread 1234 hex:0e080000000000010000000300000f35060004001fffe0020811111111222222220708fd61f77bd3df233e051000112233445566778899aabbccddeeff030e4f70656e54687265616444656d6f010212340410445f2b5ca6f2a93a55ce570a70efeecb0c0402a0fff8 20202021 3840 - ``` - -### OTA with Linux OTA Provider - -OTA feature enabled by default only for ota-requestor-app example. To enable OTA -feature for another Telink example: - -- set CONFIG_CHIP_OTA_REQUESTOR=y in corresponding "prj.conf" configuration - file. - -After build application with enabled OTA feature, use next binary files: - -- zephyr.bin - main binary to flash PCB (Use 2MB PCB). -- zephyr-ota.bin - binary for OTA Provider - -All binaries has the same SW version. To test OTA “zephyr-ota.bin” should have -higher SW version than base SW. Set CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=2 in -corresponding “prj.conf” configuration file. - -Usage of OTA: - -- Build the [Linux OTA Provider](../../ota-provider-app/linux) - - ``` - ./scripts/examples/gn_build_example.sh examples/ota-provider-app/linux out/ota-provider-app chip_config_network_layer_ble=false - ``` - -- Run the Linux OTA Provider with OTA image. - - ``` - ./chip-ota-provider-app -f zephyr-ota.bin - ``` - -- Provision the Linux OTA Provider using chip-tool - - ``` - ./chip-tool pairing onnetwork ${OTA_PROVIDER_NODE_ID} 20202021 - ``` - - here: - - - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider - -- Configure the ACL of the ota-provider-app to allow access - - ``` - ./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null}, {"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": null, "targets": null}]' ${OTA_PROVIDER_NODE_ID} 0 - ``` - - here: - - - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider - -- Use the chip-tool to announce the ota-provider-app to start the OTA process - - ``` - ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 - ``` - - here: - - - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider - - \${DEVICE_NODE_ID} is the node id of paired device - -Once the transfer is complete, OTA requestor sends ApplyUpdateRequest command to -OTA provider for applying the image. Device will restart on successful -application of OTA image. - -### Building with Pigweed RPCs - -The RPCs in `lighting-common/lighting_service/lighting_service.proto` can be -used to control various functionalities of the lighting app from a USB-connected -host computer. To build the example with the RPC server, run the following -command with _build-target_ replaced with the build target name of the Nordic -Semiconductor's kit you own: - - ``` - $ west build -b tlsr9518adk80d -- -DOVERLAY_CONFIG=rpc.overlay - ``` +# Matter Telink Temperature Measurement Example Application + +The Telink Temperature Measurement Example demonstrates getting simulated data +from temperature sensor. In further releases the real sensor handling will be +implemented along. It uses buttons to test changing the device states and LEDs +to show the state of these changes. You can use this example as a reference for +creating your own application. + +![Telink B91 EVK](http://wiki.telink-semi.cn/wiki/assets/Hardware/B91_Generic_Starter_Kit_Hardware_Guide/connection_chart.png) + +## Build and flash + +1. Pull docker image from repository: + + ```bash + $ docker pull connectedhomeip/chip-build-telink:latest + ``` + +1. Run docker container: + + ```bash + $ docker run -it --rm -v ${CHIP_BASE}:/root/chip -v /dev/bus/usb:/dev/bus/usb --device-cgroup-rule "c 189:* rmw" connectedhomeip/chip-build-telink:latest + ``` + + here `${CHIP_BASE}` is directory which contains CHIP repo files **!!!Pay + attention that OUTPUT_DIR should contains ABSOLUTE path to output dir** + +1. Activate the build environment: + + ```bash + $ source ./scripts/activate.sh + ``` + +1. In the example dir run: + + ```bash + $ west build + ``` + +1. Flash binary: + + ``` + $ west flash --erase + ``` + +## Usage + +### UART + +To get output from device, connect UART to following pins: + +| Name | Pin | +| :--: | :---------------------------- | +| RX | PB3 (pin 17 of J34 connector) | +| TX | PB2 (pin 16 of J34 connector) | +| GND | GND | + +### Buttons + +The following buttons are available on **tlsr9518adk80d** board: + +| Name | Function | Description | +| :------- | :--------------------- | :----------------------------------------------------------------------------------------------------- | +| Button 1 | Factory reset | Perform factory reset to forget currently commissioned Thread network and back to uncommissioned state | +| Button 2 | NA | NA | +| Button 3 | Thread start | Commission thread with static credentials and enables the Thread on device | +| Button 4 | Open commission window | The button is opening commissioning window to perform commissioning over BLE | + +### LEDs + +#### Indicate current state of Thread network + +**Red** LED indicates current state of Thread network. It is able to be in +following states: + +| State | Description | +| :-------------------------- | :--------------------------------------------------------------------------- | +| Blinks with short pulses | Device is not commissioned to Thread, Thread is disabled | +| Blinks with frequent pulses | Device is commissioned, Thread enabled. Device trying to JOIN thread network | +| Blinks with wide pulses | Device commissioned and joined to thread network as CHILD | + +#### Indicate identify of device + +**Green** LED used to identify the device. The LED starts blinking when the +Identify command of the Identify cluster is received. The command's argument can +be used to specify the the effect. It is able to be in following effects: + +| Effect | Description | +| :------------------------------ | :------------------------------------------------------------------- | +| Blinks (200 ms on/200 ms off) | Blink (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK) | +| Breathe (during 1000 ms) | Breathe (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE) | +| Blinks (50 ms on/950 ms off) | Okay (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY) | +| Blinks (1000 ms on/1000 ms off) | Channel Change (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE) | +| Blinks (950 ms on/50 ms off) | Finish (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT) | +| LED off | Stop (EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT) | + +### CHIP tool commands + +1. Build + [chip-tool cli](https://github.com/project-chip/connectedhomeip/blob/master/examples/chip-tool/README.md) + +2. Pair with device + + ``` + ${CHIP_TOOL_DIR}/chip-tool pairing ble-thread ${NODE_ID} hex:${DATASET} ${PIN_CODE} ${DISCRIMINATOR} + ``` + + Example: + + ``` + ./chip-tool pairing ble-thread 1234 hex:0e080000000000010000000300000f35060004001fffe0020811111111222222220708fd61f77bd3df233e051000112233445566778899aabbccddeeff030e4f70656e54687265616444656d6f010212340410445f2b5ca6f2a93a55ce570a70efeecb0c0402a0fff8 20202021 3840 + ``` + +### OTA with Linux OTA Provider + +OTA feature enabled by default only for ota-requestor-app example. To enable OTA +feature for another Telink example: + +- set CONFIG_CHIP_OTA_REQUESTOR=y in corresponding "prj.conf" configuration + file. + +After build application with enabled OTA feature, use next binary files: + +- zephyr.bin - main binary to flash PCB (Use 2MB PCB). +- zephyr-ota.bin - binary for OTA Provider + +All binaries has the same SW version. To test OTA “zephyr-ota.bin” should have +higher SW version than base SW. Set CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=2 in +corresponding “prj.conf” configuration file. + +Usage of OTA: + +- Build the [Linux OTA Provider](../../ota-provider-app/linux) + + ``` + ./scripts/examples/gn_build_example.sh examples/ota-provider-app/linux out/ota-provider-app chip_config_network_layer_ble=false + ``` + +- Run the Linux OTA Provider with OTA image. + + ``` + ./chip-ota-provider-app -f zephyr-ota.bin + ``` + +- Provision the Linux OTA Provider using chip-tool + + ``` + ./chip-tool pairing onnetwork ${OTA_PROVIDER_NODE_ID} 20202021 + ``` + + here: + + - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider + +- Configure the ACL of the ota-provider-app to allow access + + ``` + ./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null}, {"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": null, "targets": null}]' ${OTA_PROVIDER_NODE_ID} 0 + ``` + + here: + + - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider + +- Use the chip-tool to announce the ota-provider-app to start the OTA process + + ``` + ./chip-tool otasoftwareupdaterequestor announce-ota-provider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0 + ``` + + here: + + - \${OTA_PROVIDER_NODE_ID} is the node id of Linux OTA Provider + - \${DEVICE_NODE_ID} is the node id of paired device + +Once the transfer is complete, OTA requestor sends ApplyUpdateRequest command to +OTA provider for applying the image. Device will restart on successful +application of OTA image. diff --git a/examples/temperature-measurement-app/telink/include/AppConfig.h b/examples/temperature-measurement-app/telink/include/AppConfig.h index eb9104b9867a7c..ff2a9f20f56162 100644 --- a/examples/temperature-measurement-app/telink/include/AppConfig.h +++ b/examples/temperature-measurement-app/telink/include/AppConfig.h @@ -1,35 +1,35 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -// ---- Lighting Example App Config ---- - -// 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)) +/* + * + * 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 + +// ---- Temperature measurement Example App Config ---- + +// Buttons config +#define BUTTON_PORT DEVICE_DT_GET(DT_NODELABEL(gpioc)) + +#define BUTTON_PIN_1 2 +#define BUTTON_PIN_3 3 +#define BUTTON_PIN_4 1 +#define BUTTON_PIN_2 0 + +// LEDs config +#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)) diff --git a/examples/temperature-measurement-app/telink/include/AppEvent.h b/examples/temperature-measurement-app/telink/include/AppEvent.h index 72554b4bb54b5a..7e543274d55da1 100644 --- a/examples/temperature-measurement-app/telink/include/AppEvent.h +++ b/examples/temperature-measurement-app/telink/include/AppEvent.h @@ -1,65 +1,59 @@ -/* - * - * 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; -}; +/* + * + * 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_Install, + }; + + uint16_t Type; + + union + { + struct + { + uint8_t Action; + } ButtonEvent; + struct + { + void * Context; + } TimerEvent; + struct + { + LEDWidget * LedWidget; + } UpdateLedStateEvent; + }; + + EventHandler Handler; +}; diff --git a/examples/temperature-measurement-app/telink/include/AppTask.h b/examples/temperature-measurement-app/telink/include/AppTask.h index 0fd79f8aa3c72d..404d1d993dbe03 100644 --- a/examples/temperature-measurement-app/telink/include/AppTask.h +++ b/examples/temperature-measurement-app/telink/include/AppTask.h @@ -1,100 +1,93 @@ -/* - * - * 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 "AppEvent.h" -#if CONFIG_CHIP_ENABLE_APPLICATION_STATUS_LED -#include "LEDWidget.h" -#endif -#include "PWMDevice.h" -#include - -#if CONFIG_CHIP_FACTORY_DATA -#include -#endif - -#ifdef CONFIG_CHIP_PW_RPC -#include "Rpc.h" -#endif - -#include - -struct k_timer; -struct Identify; - -class AppTask -{ -public: - CHIP_ERROR StartApp(void); - - void SetInitiateAction(PWMDevice::Action_t aAction, int32_t aActor, uint8_t * value); - void PostEvent(AppEvent * aEvent); - - static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); - -private: -#ifdef CONFIG_CHIP_PW_RPC - friend class chip::rpc::TelinkButton; -#endif - friend AppTask & GetAppTask(void); - 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 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 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) -{ - return AppTask::sAppTask; -} +/* + * + * 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 "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 + +struct k_timer; +struct Identify; + +class AppTask +{ +public: + CHIP_ERROR StartApp(void); + + void SetInitiateAction(PWMDevice::Action_t aAction, int32_t aActor, uint8_t * value); + void PostEvent(AppEvent * aEvent); + + static void IdentifyEffectHandler(EmberAfIdentifyEffectIdentifier aEffect); + +private: + friend AppTask & GetAppTask(void); + 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 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 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) +{ + return AppTask::sAppTask; +} diff --git a/examples/temperature-measurement-app/telink/include/CHIPProjectConfig.h b/examples/temperature-measurement-app/telink/include/CHIPProjectConfig.h index 76d4372a80703f..3d2b44f67583e0 100644 --- a/examples/temperature-measurement-app/telink/include/CHIPProjectConfig.h +++ b/examples/temperature-measurement-app/telink/include/CHIPProjectConfig.h @@ -1,44 +1,39 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Example project configuration file for CHIP. - * - * This is a place to put application or project-specific overrides - * to the default configuration values for general CHIP features. - * - */ - -#pragma once - -// Use a default pairing code if one hasn't been provisioned in flash. -#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 -#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 - -// Switching from Thread child to router may cause a few second packet stall. -// Until this is improved in OpenThread we need to increase the retransmission -// interval to survive the stall. -#define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL (1000_ms32) - -/** - * CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE - * - * Reduce packet buffer pool size to 8 (default 15) to reduce ram consumption - */ -#define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 8 +/* + * + * 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 + +// Use a default pairing code if one hasn't been provisioned in flash. +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 + +/** + * CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE + * + * Reduce packet buffer pool size to 8 (default 15) to reduce ram consumption + */ +#define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 8 diff --git a/examples/temperature-measurement-app/telink/include/SensorManager.h b/examples/temperature-measurement-app/telink/include/SensorManager.h index 147f89b9ab6b05..361ed30abbe5b1 100644 --- a/examples/temperature-measurement-app/telink/include/SensorManager.h +++ b/examples/temperature-measurement-app/telink/include/SensorManager.h @@ -1,54 +1,54 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include - -#include "AppEvent.h" - -#include -#include - -class SensorManager -{ -public: - CHIP_ERROR Init(); - - int16_t GetMeasuredValue(); - int16_t GetMinMeasuredValue(); - int16_t GetMaxMeasuredValue(); - -private: - friend SensorManager & SensorMgr(); - - // Reads new generated sensor value, stores it, and updates local temperature attribute - static int16_t SensorEventHandler(); - - int16_t mMeasuredTempCelsius; - int16_t mMinMeasuredTempCelsius = -40; - int16_t mMaxMeasuredTempCelsius = 120; - - static SensorManager sSensorManager; -}; - -inline SensorManager & SensorMgr() -{ - return SensorManager::sSensorManager; -} +/* + * + * 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 + +#include "AppEvent.h" + +#include +#include + +class SensorManager +{ +public: + CHIP_ERROR Init(); + + int16_t GetMeasuredValue(); + int16_t GetMinMeasuredValue(); + int16_t GetMaxMeasuredValue(); + +private: + friend SensorManager & SensorMgr(); + + // Reads new generated sensor value, stores it, and updates local temperature attribute + static int16_t SensorEventHandler(); + + int16_t mMeasuredTempCelsius; + int16_t mMinMeasuredTempCelsius = -40; + int16_t mMaxMeasuredTempCelsius = 120; + + static SensorManager sSensorManager; +}; + +inline SensorManager & SensorMgr() +{ + return SensorManager::sSensorManager; +} diff --git a/examples/temperature-measurement-app/telink/prj.conf b/examples/temperature-measurement-app/telink/prj.conf index 75f3ba448974d6..735d5639020702 100644 --- a/examples/temperature-measurement-app/telink/prj.conf +++ b/examples/temperature-measurement-app/telink/prj.conf @@ -1,79 +1,79 @@ -# -# Copyright (c) 2021-2023 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# This sample uses sample-defaults.conf to set options common for all -# samples. This file should contain only options specific for this sample -# or overrides of default values. - -# enable GPIO -CONFIG_GPIO=y - -# enable PWM -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 -CONFIG_OPENTHREAD_PANID=4660 -CONFIG_OPENTHREAD_CHANNEL=15 -CONFIG_OPENTHREAD_NETWORK_NAME="OpenThreadDemo" -CONFIG_OPENTHREAD_XPANID="11:11:11:11:22:22:22:22" - -# Disable Matter OTA DFU -CONFIG_CHIP_OTA_REQUESTOR=n - -# CHIP configuration -CONFIG_CHIP_PROJECT_CONFIG="include/CHIPProjectConfig.h" -CONFIG_CHIP_OPENTHREAD_CONFIG="../../platform/telink/project_include/OpenThreadConfig.h" - -CONFIG_CHIP_DEVICE_VENDOR_ID=65521 -# 32781 == 0x800D (example temperature-measurement-app) -CONFIG_CHIP_DEVICE_PRODUCT_ID=32781 -CONFIG_CHIP_DEVICE_TYPE=65535 - -CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=1 -CONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING="2023" - -# Enable CHIP pairing automatically on application start. -CONFIG_CHIP_ENABLE_PAIRING_AUTOSTART=y - -# CHIP shell -CONFIG_CHIP_LIB_SHELL=n - -# Disable factory data support. -CONFIG_CHIP_FACTORY_DATA=n -CONFIG_CHIP_FACTORY_DATA_BUILD=n -CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n -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 -CONFIG_IEEE802154_B91_CUSTOM_RF_POWER=9 +# +# Copyright (c) 2023 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This sample uses sample-defaults.conf to set options common for all +# samples. This file should contain only options specific for this sample +# or overrides of default values. + +# enable GPIO +CONFIG_GPIO=y + +# enable PWM +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 +CONFIG_OPENTHREAD_PANID=4660 +CONFIG_OPENTHREAD_CHANNEL=15 +CONFIG_OPENTHREAD_NETWORK_NAME="OpenThreadDemo" +CONFIG_OPENTHREAD_XPANID="11:11:11:11:22:22:22:22" + +# Disable Matter OTA DFU +CONFIG_CHIP_OTA_REQUESTOR=n + +# CHIP configuration +CONFIG_CHIP_PROJECT_CONFIG="include/CHIPProjectConfig.h" +CONFIG_CHIP_OPENTHREAD_CONFIG="../../platform/telink/project_include/OpenThreadConfig.h" + +CONFIG_CHIP_DEVICE_VENDOR_ID=65521 +# 32781 == 0x800D (example temperature-measurement-app) +CONFIG_CHIP_DEVICE_PRODUCT_ID=32781 +CONFIG_CHIP_DEVICE_TYPE=65535 + +CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=1 +CONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING="2023" + +# Enable CHIP pairing automatically on application start. +CONFIG_CHIP_ENABLE_PAIRING_AUTOSTART=y + +# CHIP shell +CONFIG_CHIP_LIB_SHELL=n + +# Disable factory data support. +CONFIG_CHIP_FACTORY_DATA=n +CONFIG_CHIP_FACTORY_DATA_BUILD=n +CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=n +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 +CONFIG_IEEE802154_B91_CUSTOM_RF_POWER=9 diff --git a/examples/temperature-measurement-app/telink/rpc.overlay b/examples/temperature-measurement-app/telink/rpc.overlay deleted file mode 100644 index a97621181efc75..00000000000000 --- a/examples/temperature-measurement-app/telink/rpc.overlay +++ /dev/null @@ -1,47 +0,0 @@ -# -# Copyright (c) 2020 Project CHIP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# This file should be used as a configuration overlay to build Pigweed RPCs to -# lighting-app. - -# Enable Pigweed RPC -CONFIG_CHIP_PW_RPC=y - -# Add support for C++17 to build Pigweed components -CONFIG_STD_CPP14=n -CONFIG_STD_CPP17=y - -# Add support for Zephyr console component to use it for Pigweed console purposes -CONFIG_CONSOLE_SUBSYS=y -CONFIG_CONSOLE_GETCHAR=y -CONFIG_CONSOLE_PUTCHAR_BUFSIZE=256 - -# Disable features which may interfere with Pigweed HDLC transport -CONFIG_SHELL=n -CONFIG_OPENTHREAD_SHELL=n -CONFIG_BOOT_BANNER=n - -# Configure Zephyr logger with defaults backends disabled as the app provides its own, -# based on Pigweed HDLC. -CONFIG_LOG=y -CONFIG_LOG_MODE_MINIMAL=n -CONFIG_LOG_MODE_IMMEDIATE=y -CONFIG_LOG_BACKEND_UART=n -CONFIG_LOG_BACKEND_RTT=n -CONFIG_LOG_OUTPUT=y - -# Increase zephyr tty rx buffer -CONFIG_CONSOLE_GETCHAR_BUFSIZE=128 diff --git a/examples/temperature-measurement-app/telink/src/AppTask.cpp b/examples/temperature-measurement-app/telink/src/AppTask.cpp index a2e30d0745cfef..b877759db5f268 100644 --- a/examples/temperature-measurement-app/telink/src/AppTask.cpp +++ b/examples/temperature-measurement-app/telink/src/AppTask.cpp @@ -1,577 +1,577 @@ -/* - * - * 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 "AppConfig.h" -#include "AppEvent.h" -#include "ButtonManager.h" -#include "SensorManager.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 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; - -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; - -// 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 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 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; - } - - 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)); - - // 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 - err = SensorMgr().Init(); - if (err != CHIP_NO_ERROR) - { - LOG_ERR("SensorMgr Init fail"); - return err; - } - - PlatformMgr().LockChipStack(); - app::Clusters::TemperatureMeasurement::Attributes::MinMeasuredValue::Set(kEndpointId, SensorMgr().GetMinMeasuredValue()); - app::Clusters::TemperatureMeasurement::Attributes::MaxMeasuredValue::Set(kEndpointId, SensorMgr().GetMaxMeasuredValue()); - PlatformMgr().UnlockChipStack(); - - err = ConnectivityMgr().SetBLEDeviceName("TelinkTemperature"); - 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::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) - { - return; - } - - AppEvent event; - event.Type = AppEvent::kEventType_Timer; - event.Handler = TemperatureMeasurementTimerEventHandler; - sAppTask.PostEvent(&event); -} - -void AppTask::TemperatureMeasurementTimerEventHandler(AppEvent * aEvent) -{ - if (aEvent->Type != AppEvent::kEventType_Timer) - { - return; - } - - PlatformMgr().LockChipStack(); - app::Clusters::TemperatureMeasurement::Attributes::MeasuredValue::Set(kEndpointId, SensorMgr().GetMeasuredValue()); - PlatformMgr().UnlockChipStack(); - - LOG_INF("Current temperature is (%d*0.01)°C", SensorMgr().GetMeasuredValue()); - - // 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); -} +/* + * + * 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 "AppConfig.h" +#include "AppEvent.h" +#include "ButtonManager.h" +#include "SensorManager.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 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; + +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; + +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 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 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; + } + + 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)); + + // 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 + err = SensorMgr().Init(); + if (err != CHIP_NO_ERROR) + { + LOG_ERR("SensorMgr Init fail"); + return err; + } + + PlatformMgr().LockChipStack(); + app::Clusters::TemperatureMeasurement::Attributes::MinMeasuredValue::Set(kEndpointId, SensorMgr().GetMinMeasuredValue()); + app::Clusters::TemperatureMeasurement::Attributes::MaxMeasuredValue::Set(kEndpointId, SensorMgr().GetMaxMeasuredValue()); + PlatformMgr().UnlockChipStack(); + + err = ConnectivityMgr().SetBLEDeviceName("TelinkTerm"); + 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::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) + { + return; + } + + AppEvent event; + event.Type = AppEvent::kEventType_Timer; + event.Handler = TemperatureMeasurementTimerEventHandler; + sAppTask.PostEvent(&event); +} + +void AppTask::TemperatureMeasurementTimerEventHandler(AppEvent * aEvent) +{ + if (aEvent->Type != AppEvent::kEventType_Timer) + { + return; + } + + PlatformMgr().LockChipStack(); + app::Clusters::TemperatureMeasurement::Attributes::MeasuredValue::Set(kEndpointId, SensorMgr().GetMeasuredValue()); + PlatformMgr().UnlockChipStack(); + + LOG_INF("Current temperature is (%d*0.01)°C", SensorMgr().GetMeasuredValue()); + + // 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 fd17d5902a4226..58e2442bf61402 100644 --- a/examples/temperature-measurement-app/telink/src/SensorManager.cpp +++ b/examples/temperature-measurement-app/telink/src/SensorManager.cpp @@ -1,98 +1,93 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "SensorManager.h" -#include "AppConfig.h" -#include "AppEvent.h" -#include "AppTask.h" - -#ifdef SENSOR_IS_USED -// Provide REAL sensor implementation -// #include "SomeTemperatureSensor.h" -#else -#define TEMPERATURE_SIMULATION_IS_USED -#endif - -LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); - -using namespace chip; -using namespace ::chip::DeviceLayer; - -constexpr float kMinTemperatureDelta = 0.5; // 0.5 degree Celsius -constexpr uint16_t kSimulatedReadingFrequency = 5; // Change Simulated number -static float mSimulatedTemp[] = { 23.01, 24.02, 28.03, 25.50, 22.05, 21.25, 21.07, 26.08, 18.09, 27.11 }; - -k_timer sSensorTimer; - -SensorManager SensorManager::sSensorManager; - -CHIP_ERROR SensorManager::Init() -{ - // TODO: Initialize temp sensor - return CHIP_NO_ERROR; -} - -int16_t SensorManager::SensorEventHandler() -{ - float temperature = 0.0; - static float lastTemperature = 0.0; - -#ifdef TEMPERATURE_SIMULATION_IS_USED - static uint8_t nbOfRepetition = 0; - static uint8_t simulatedIndex = 0; - if (simulatedIndex >= sizeof(mSimulatedTemp) - 1) - { - simulatedIndex = 0; - } - temperature = mSimulatedTemp[simulatedIndex]; - - nbOfRepetition++; - - if (nbOfRepetition >= kSimulatedReadingFrequency) - { - simulatedIndex++; - nbOfRepetition = 0; - } - - if ((temperature >= (lastTemperature + kMinTemperatureDelta)) || temperature <= (lastTemperature - kMinTemperatureDelta)) - { - lastTemperature = temperature; - // Per spec Application Clusters 2.3.4.1. : MeasuredValue = 100 x temperature [°C] - sSensorManager.mMeasuredTempCelsius = (int16_t) 100 * temperature; - } -#else - // TODO: provide REAL sensor implementation - // sSensorManager.mMeasuredTempCelsius = (int16_t) 100 * GetRealSensorTemperature(); -#endif // TEMPERATURE_SIMULATION_IS_USED - return sSensorManager.mMeasuredTempCelsius; -} - -int16_t SensorManager::GetMeasuredValue() -{ - return SensorEventHandler(); -} - -int16_t SensorManager::GetMinMeasuredValue() -{ - return mMinMeasuredTempCelsius; -} - -int16_t SensorManager::GetMaxMeasuredValue() -{ - return mMaxMeasuredTempCelsius; -} \ No newline at end of file +/* + * + * 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 "SensorManager.h" +#include "AppConfig.h" +#include "AppEvent.h" +#include "AppTask.h" + +#define TEMPERATURE_SIMULATION_IS_USED + +LOG_MODULE_DECLARE(app, CONFIG_CHIP_APP_LOG_LEVEL); + +using namespace chip; +using namespace ::chip::DeviceLayer; + +constexpr float kMinTemperatureDelta = 0.5; // 0.5 degree Celsius +constexpr uint16_t kSimulatedReadingFrequency = 5; // Change Simulated number +static float mSimulatedTemp[] = { 23.01, 24.02, 28.03, 25.50, 22.05, 21.25, 21.07, 26.08, 18.09, 27.11 }; + +k_timer sSensorTimer; + +SensorManager SensorManager::sSensorManager; + +CHIP_ERROR SensorManager::Init() +{ + // TODO: Initialize temp sensor + return CHIP_NO_ERROR; +} + +int16_t SensorManager::SensorEventHandler() +{ + float temperature = 0.0; + static float lastTemperature = 0.0; + +#ifdef TEMPERATURE_SIMULATION_IS_USED + static uint8_t nbOfRepetition = 0; + static uint8_t simulatedIndex = 0; + if (simulatedIndex >= sizeof(mSimulatedTemp) - 1) + { + simulatedIndex = 0; + } + temperature = mSimulatedTemp[simulatedIndex]; + + nbOfRepetition++; + + if (nbOfRepetition >= kSimulatedReadingFrequency) + { + simulatedIndex++; + nbOfRepetition = 0; + } + + if ((temperature >= (lastTemperature + kMinTemperatureDelta)) || temperature <= (lastTemperature - kMinTemperatureDelta)) + { + lastTemperature = temperature; + // Per spec Application Clusters 2.3.4.1. : MeasuredValue = 100 x temperature [°C] + sSensorManager.mMeasuredTempCelsius = (int16_t) 100 * temperature; + } +#else + // TODO: provide REAL sensor implementation + sSensorManager.mMeasuredTempCelsius = (int16_t) 100 * GetRealSensorTemperature(); +#endif // TEMPERATURE_SIMULATION_IS_USED + return sSensorManager.mMeasuredTempCelsius; +} + +int16_t SensorManager::GetMeasuredValue() +{ + return SensorEventHandler(); +} + +int16_t SensorManager::GetMinMeasuredValue() +{ + return mMinMeasuredTempCelsius; +} + +int16_t SensorManager::GetMaxMeasuredValue() +{ + return mMaxMeasuredTempCelsius; +} diff --git a/examples/temperature-measurement-app/telink/src/main.cpp b/examples/temperature-measurement-app/telink/src/main.cpp index 12abb1de76ec74..2332c034156dc2 100644 --- a/examples/temperature-measurement-app/telink/src/main.cpp +++ b/examples/temperature-measurement-app/telink/src/main.cpp @@ -1,90 +1,82 @@ -/* - * - * Copyright (c) 2021-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 - -#ifdef CONFIG_CHIP_PW_RPC -#include "Rpc.h" -#endif - -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; - -#ifdef CONFIG_CHIP_PW_RPC - rpc::Init(); -#endif - - 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; -} +/* + * + * 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/temperature-measurement-common/temperature-measurement.matter b/examples/temperature-measurement-app/temperature-measurement-common/temperature-measurement.matter index 3d809d4214df2a..0c35b3e02edab6 100644 --- a/examples/temperature-measurement-app/temperature-measurement-common/temperature-measurement.matter +++ b/examples/temperature-measurement-app/temperature-measurement-common/temperature-measurement.matter @@ -6,6 +6,84 @@ struct LabelStruct { char_string<16> value = 1; } +client cluster Identify = 3 { + enum IdentifyEffectIdentifier : ENUM8 { + kBlink = 0; + kBreathe = 1; + kOkay = 2; + kChannelChange = 11; + kFinishEffect = 254; + kStopEffect = 255; + } + + enum IdentifyEffectVariant : ENUM8 { + kDefault = 0; + } + + enum IdentifyIdentifyType : ENUM8 { + kNone = 0; + kVisibleLight = 1; + kVisibleLED = 2; + kAudibleBeep = 3; + kDisplay = 4; + kActuator = 5; + } + + attribute int16u identifyTime = 0; + readonly attribute enum8 identifyType = 1; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct IdentifyRequest { + INT16U identifyTime = 0; + } + + command access(invoke: manage) Identify(IdentifyRequest): DefaultSuccess = 0; +} + +server cluster Identify = 3 { + enum IdentifyEffectIdentifier : ENUM8 { + kBlink = 0; + kBreathe = 1; + kOkay = 2; + kChannelChange = 11; + kFinishEffect = 254; + kStopEffect = 255; + } + + enum IdentifyEffectVariant : ENUM8 { + kDefault = 0; + } + + enum IdentifyIdentifyType : ENUM8 { + kNone = 0; + kVisibleLight = 1; + kVisibleLED = 2; + kAudibleBeep = 3; + kDisplay = 4; + kActuator = 5; + } + + attribute int16u identifyTime = 0; + readonly attribute enum8 identifyType = 1; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct IdentifyRequest { + INT16U identifyTime = 0; + } + + command access(invoke: manage) Identify(IdentifyRequest): DefaultSuccess = 0; +} + server cluster Descriptor = 29 { struct DeviceTypeStruct { devtype_id deviceType = 0; @@ -929,6 +1007,12 @@ server cluster TemperatureMeasurement = 1026 { endpoint 0 { device type rootdevice = 22, version 1; + server cluster Identify { + ram attribute identifyTime; + ram attribute featureMap; + ram attribute clusterRevision default = 4; + } + server cluster Descriptor { callback attribute deviceTypeList; callback attribute serverList; @@ -1126,6 +1210,14 @@ endpoint 0 { } endpoint 1 { device type tempsensor = 770, version 1; + binding cluster Identify; + + server cluster Identify { + ram attribute identifyTime; + ram attribute identifyType; + ram attribute featureMap; + ram attribute clusterRevision default = 4; + } server cluster Descriptor { callback attribute deviceTypeList; diff --git a/examples/temperature-measurement-app/temperature-measurement-common/temperature-measurement.zap b/examples/temperature-measurement-app/temperature-measurement-common/temperature-measurement.zap index e71bcc2ca12287..4b11f6bb2f68c2 100644 --- a/examples/temperature-measurement-app/temperature-measurement-common/temperature-measurement.zap +++ b/examples/temperature-measurement-app/temperature-measurement-common/temperature-measurement.zap @@ -52,7 +52,7 @@ "mfgCode": null, "source": "client", "incoming": 1, - "outgoing": 0 + "outgoing": 1 } ], "attributes": [ @@ -80,7 +80,7 @@ "mfgCode": null, "define": "IDENTIFY_CLUSTER", "side": "server", - "enabled": 0, + "enabled": 1, "attributes": [ { "name": "IdentifyTime", @@ -98,6 +98,22 @@ "maxInterval": 65344, "reportableChange": 0 }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, { "name": "ClusterRevision", "code": 65533, @@ -3325,7 +3341,7 @@ "mfgCode": null, "define": "IDENTIFY_CLUSTER", "side": "client", - "enabled": 0, + "enabled": 1, "commands": [ { "name": "Identify", @@ -3361,7 +3377,7 @@ "mfgCode": null, "define": "IDENTIFY_CLUSTER", "side": "server", - "enabled": 0, + "enabled": 1, "attributes": [ { "name": "IdentifyTime", @@ -3379,6 +3395,38 @@ "maxInterval": 65344, "reportableChange": 0 }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "enum8", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, { "name": "ClusterRevision", "code": 65533,