From 0112731f01f4ad6c63b22e0aee98da0a60f0c88d Mon Sep 17 00:00:00 2001 From: "jun.luo" Date: Tue, 14 Dec 2021 09:38:56 +0800 Subject: [PATCH 01/20] Add beken base code into Matter SDK Change-Id: I414568f9ba813e8fb28efe4a097fda8e8d52a822 --- config/beken/.gn | 28 + config/beken/BUILD.gn | 26 + config/beken/args.gni | 36 + config/beken/build | 1 + config/beken/build_overrides | 1 + config/beken/mbedtls/BUILD.gn | 22 + config/beken/third_party/connectedhomeip | 1 + config/beken/toolchain/BUILD.gn | 35 + .../beken/main/CHIPDeviceManager.cpp | 168 +++ .../beken/main/DeviceCallbacks.cpp | 161 +++ examples/lighting-app/beken/main/DsoHack.cpp | 20 + .../lighting-app/beken/main/chipinterface.cpp | 284 ++++ .../beken/main/include/CHIPDeviceManager.h | 124 ++ .../beken/main/include/DeviceCallbacks.h | 44 + src/app/server/Server.cpp | 2 +- src/lib/support/UnitTestUtils.cpp | 4 +- src/platform/BUILD.gn | 8 + src/platform/Beken/BLEManagerImpl.cpp | 1171 +++++++++++++++++ src/platform/Beken/BLEManagerImpl.h | 234 ++++ src/platform/Beken/BUILD.gn | 58 + src/platform/Beken/BekenConfig.cpp | 322 +++++ src/platform/Beken/BekenConfig.h | 115 ++ src/platform/Beken/BlePlatformConfig.h | 39 + src/platform/Beken/CHIPDevicePlatformConfig.h | 73 + src/platform/Beken/CHIPDevicePlatformEvent.h | 84 ++ src/platform/Beken/CHIPMem-Platform.cpp | 143 ++ src/platform/Beken/CHIPPlatformConfig.h | 114 ++ .../Beken/ConfigurationManagerImpl.cpp | 249 ++++ src/platform/Beken/ConfigurationManagerImpl.h | 79 ++ .../Beken/ConnectivityManagerImpl.cpp | 670 ++++++++++ src/platform/Beken/ConnectivityManagerImpl.h | 213 +++ .../DeviceNetworkProvisioningDelegateImpl.cpp | 43 + .../DeviceNetworkProvisioningDelegateImpl.h | 44 + .../Beken/DiagnosticDataProviderImpl.cpp | 350 +++++ .../Beken/DiagnosticDataProviderImpl.h | 69 + src/platform/Beken/InetPlatformConfig.h | 47 + .../Beken/KeyValueStoreManagerImpl.cpp | 115 ++ src/platform/Beken/KeyValueStoreManagerImpl.h | 77 ++ src/platform/Beken/Logging.cpp | 68 + src/platform/Beken/LwIPCoreLock.cpp | 60 + src/platform/Beken/PlatformManagerImpl.cpp | 96 ++ src/platform/Beken/PlatformManagerImpl.h | 93 ++ src/platform/Beken/ServiceProvisioning.cpp | 47 + src/platform/Beken/ServiceProvisioning.h | 26 + .../Beken/SoftwareUpdateManagerImpl.h | 89 ++ src/platform/Beken/SystemPlatformConfig.h | 65 + src/platform/Beken/args.gni | 25 + src/platform/device.gni | 16 +- 48 files changed, 5854 insertions(+), 5 deletions(-) create mode 100644 config/beken/.gn create mode 100644 config/beken/BUILD.gn create mode 100755 config/beken/args.gni create mode 120000 config/beken/build create mode 120000 config/beken/build_overrides create mode 100644 config/beken/mbedtls/BUILD.gn create mode 120000 config/beken/third_party/connectedhomeip create mode 100755 config/beken/toolchain/BUILD.gn create mode 100644 examples/lighting-app/beken/main/CHIPDeviceManager.cpp create mode 100644 examples/lighting-app/beken/main/DeviceCallbacks.cpp create mode 100644 examples/lighting-app/beken/main/DsoHack.cpp create mode 100644 examples/lighting-app/beken/main/chipinterface.cpp create mode 100644 examples/lighting-app/beken/main/include/CHIPDeviceManager.h create mode 100644 examples/lighting-app/beken/main/include/DeviceCallbacks.h create mode 100755 src/platform/Beken/BLEManagerImpl.cpp create mode 100755 src/platform/Beken/BLEManagerImpl.h create mode 100755 src/platform/Beken/BUILD.gn create mode 100644 src/platform/Beken/BekenConfig.cpp create mode 100755 src/platform/Beken/BekenConfig.h create mode 100644 src/platform/Beken/BlePlatformConfig.h create mode 100755 src/platform/Beken/CHIPDevicePlatformConfig.h create mode 100644 src/platform/Beken/CHIPDevicePlatformEvent.h create mode 100644 src/platform/Beken/CHIPMem-Platform.cpp create mode 100644 src/platform/Beken/CHIPPlatformConfig.h create mode 100644 src/platform/Beken/ConfigurationManagerImpl.cpp create mode 100644 src/platform/Beken/ConfigurationManagerImpl.h create mode 100644 src/platform/Beken/ConnectivityManagerImpl.cpp create mode 100644 src/platform/Beken/ConnectivityManagerImpl.h create mode 100644 src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp create mode 100644 src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.h create mode 100644 src/platform/Beken/DiagnosticDataProviderImpl.cpp create mode 100644 src/platform/Beken/DiagnosticDataProviderImpl.h create mode 100755 src/platform/Beken/InetPlatformConfig.h create mode 100755 src/platform/Beken/KeyValueStoreManagerImpl.cpp create mode 100755 src/platform/Beken/KeyValueStoreManagerImpl.h create mode 100644 src/platform/Beken/Logging.cpp create mode 100644 src/platform/Beken/LwIPCoreLock.cpp create mode 100644 src/platform/Beken/PlatformManagerImpl.cpp create mode 100644 src/platform/Beken/PlatformManagerImpl.h create mode 100755 src/platform/Beken/ServiceProvisioning.cpp create mode 100644 src/platform/Beken/ServiceProvisioning.h create mode 100755 src/platform/Beken/SoftwareUpdateManagerImpl.h create mode 100755 src/platform/Beken/SystemPlatformConfig.h create mode 100755 src/platform/Beken/args.gni diff --git a/config/beken/.gn b/config/beken/.gn new file mode 100644 index 00000000000000..3d48789e30ab3d --- /dev/null +++ b/config/beken/.gn @@ -0,0 +1,28 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "arm" + target_os = "freertos" + + import("//args.gni") +} diff --git a/config/beken/BUILD.gn b/config/beken/BUILD.gn new file mode 100644 index 00000000000000..96ae17d002e087 --- /dev/null +++ b/config/beken/BUILD.gn @@ -0,0 +1,26 @@ +# 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. + +# Options from standalone-chip.mk that differ from configure defaults. These +# options are used from examples/. + +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") + +#import("${chip_root}/build/chip/tests.gni") + +group("beken") { + deps = [ "${chip_root}/src/lib" ] + +} diff --git a/config/beken/args.gni b/config/beken/args.gni new file mode 100755 index 00000000000000..67ac560c7d4e8a --- /dev/null +++ b/config/beken/args.gni @@ -0,0 +1,36 @@ +# 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. + +# Options from standalone-chip.mk that differ from configure defaults. These +# options are used from examples/. + +chip_device_platform = "beken" + +chip_project_config_include = "" +chip_system_project_config_include = "" +chip_ble_project_config_include = "" + +mbedtls_target = "//mbedtls:mbedtls" +lwip_platform = "external" + +chip_build_tests = false + +chip_inet_config_enable_tcp_endpoint = true +chip_inet_config_enable_udp_endpoint = true + +chip_bypass_rendezvous = false +chip_config_network_layer_ble = true +chip_config_memory_management = "platform" + +custom_toolchain = "//third_party/connectedhomeip/config/beken/toolchain:beken" diff --git a/config/beken/build b/config/beken/build new file mode 120000 index 00000000000000..d56ed62ae4d1ff --- /dev/null +++ b/config/beken/build @@ -0,0 +1 @@ +third_party/connectedhomeip/build \ No newline at end of file diff --git a/config/beken/build_overrides b/config/beken/build_overrides new file mode 120000 index 00000000000000..aea3e8d3b72a17 --- /dev/null +++ b/config/beken/build_overrides @@ -0,0 +1 @@ +../../examples/build_overrides \ No newline at end of file diff --git a/config/beken/mbedtls/BUILD.gn b/config/beken/mbedtls/BUILD.gn new file mode 100644 index 00000000000000..f33d684b620bfe --- /dev/null +++ b/config/beken/mbedtls/BUILD.gn @@ -0,0 +1,22 @@ +# 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. + +# Options from standalone-chip.mk that differ from configure defaults. These +# options are used from examples/. + +import("//build_overrides/chip.gni") + +# Ameba has its own mbedtls, so nothing to do, just provide a target +group("mbedtls") { +} diff --git a/config/beken/third_party/connectedhomeip b/config/beken/third_party/connectedhomeip new file mode 120000 index 00000000000000..a8a4f8c2127bf7 --- /dev/null +++ b/config/beken/third_party/connectedhomeip @@ -0,0 +1 @@ +../../.. \ No newline at end of file diff --git a/config/beken/toolchain/BUILD.gn b/config/beken/toolchain/BUILD.gn new file mode 100755 index 00000000000000..9851a08e102c17 --- /dev/null +++ b/config/beken/toolchain/BUILD.gn @@ -0,0 +1,35 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +#import("${build_root}/toolchain/arm_gcc/arm_toolchain.gni") +import("${build_root}/toolchain/gcc_toolchain.gni") +declare_args() { + beken_ar = "" + beken_cc = "" + beken_cxx = "" +} + +gcc_toolchain("beken") { + ar = beken_ar + cc = beken_cc + cxx = beken_cxx + + toolchain_args = { + current_os = "freertos" + is_clang = false + import("${chip_root}/src/platform/Beken/args.gni") + } +} diff --git a/examples/lighting-app/beken/main/CHIPDeviceManager.cpp b/examples/lighting-app/beken/main/CHIPDeviceManager.cpp new file mode 100644 index 00000000000000..4004eb03c35406 --- /dev/null +++ b/examples/lighting-app/beken/main/CHIPDeviceManager.cpp @@ -0,0 +1,168 @@ +/* + * + * 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. + */ + +/** + * @file + * This file implements the CHIP Device Interface that is used by + * applications to interact with the CHIP stack + * + */ + +#include + +#include "CHIPDeviceManager.h" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace ::chip; + +namespace chip { + +namespace DeviceManager { + +using namespace ::chip::DeviceLayer; + +void CHIPDeviceManager::CommonDeviceEventHandler(const ChipDeviceEvent * event, intptr_t arg) +{ + CHIPDeviceManagerCallbacks * cb = reinterpret_cast(arg); + if (cb != nullptr) + { + cb->DeviceEventCallback(event, reinterpret_cast(cb)); + } +} + +CHIP_ERROR CHIPDeviceManager::Init(CHIPDeviceManagerCallbacks * cb) +{ + CHIP_ERROR err; + mCB = cb; + + err = PlatformMgr().InitChipStack(); + SuccessOrExit(err); + + if (CONFIG_NETWORK_LAYER_BLE) + { + ConnectivityMgr().SetBLEAdvertisingEnabled(true); + } + + err = Platform::MemoryInit(); + SuccessOrExit(err); + + PlatformMgr().AddEventHandler(CHIPDeviceManager::CommonDeviceEventHandler, reinterpret_cast(cb)); + + // // Start a task to run the CHIP Device event loop. + err = PlatformMgr().StartEventLoopTask(); + if (err != CHIP_NO_ERROR) + { + printf("StartEventLoopTask() - ERROR!\r\n"); + } + else + { + printf("StartEventLoopTask() - OK\r\n"); + } + +exit: + return err; +} +} // namespace DeviceManager +} // namespace chip + +void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t mask, uint8_t type, + uint16_t size, uint8_t * value) +{ + chip::DeviceManager::CHIPDeviceManagerCallbacks * cb = + chip::DeviceManager::CHIPDeviceManager::GetInstance().GetCHIPDeviceManagerCallbacks(); + + EndpointId endpointId = attributePath.mEndpointId; + ClusterId clusterId = attributePath.mClusterId; + AttributeId attributeId = attributePath.mAttributeId; + + if (clusterId == ZCL_ON_OFF_CLUSTER_ID) + { + if (attributeId != ZCL_ON_OFF_ATTRIBUTE_ID) + { + ChipLogProgress(Zcl, "Unknown attribute ID: %" PRIx32, attributeId); + return; + } + } + else if (clusterId == ZCL_LEVEL_CONTROL_CLUSTER_ID) + { + if (attributeId != ZCL_CURRENT_LEVEL_ATTRIBUTE_ID) + { + ChipLogProgress(Zcl, "Unknown attribute ID: %" PRIx32, attributeId); + return; + } + if (size == 1) + { + // ChipLogProgress(Zcl, "New level: %u ", *value); + } + else + { + ChipLogError(Zcl, "wrong length for level: %d\n", size); + } + } + else if (clusterId == ZCL_COLOR_CONTROL_CLUSTER_ID) + { + uint8_t hue, saturation; + + if ((attributeId != ZCL_COLOR_CONTROL_CURRENT_HUE_ATTRIBUTE_ID) && + (attributeId != ZCL_COLOR_CONTROL_CURRENT_SATURATION_ATTRIBUTE_ID)) + { + ChipLogProgress(Zcl, "Unknown attribute ID: %" PRIx32, attributeId); + return; + } + + if (attributeId == ZCL_COLOR_CONTROL_CURRENT_HUE_ATTRIBUTE_ID) + { + hue = *value; + emberAfReadServerAttribute(endpointId, ZCL_COLOR_CONTROL_CLUSTER_ID, ZCL_COLOR_CONTROL_CURRENT_SATURATION_ATTRIBUTE_ID, + &saturation, sizeof(uint8_t)); + } + if (attributeId == ZCL_COLOR_CONTROL_CURRENT_SATURATION_ATTRIBUTE_ID) + { + saturation = *value; + emberAfReadServerAttribute(endpointId, ZCL_COLOR_CONTROL_CLUSTER_ID, ZCL_COLOR_CONTROL_CURRENT_HUE_ATTRIBUTE_ID, &hue, + sizeof(uint8_t)); + } + ChipLogProgress(Zcl, "New hue: %d, New saturation: %d ", hue, saturation); + } + else if (clusterId == ZCL_IDENTIFY_CLUSTER_ID) + { + if (attributeId == ZCL_IDENTIFY_TIME_ATTRIBUTE_ID) + { + if (cb != nullptr) + { + cb->PostAttributeChangeCallback(endpointId, clusterId, attributeId, mask, type, size, value); + } + ChipLogProgress(Zcl, "ZCL_IDENTIFY_TIME_ATTRIBUTE_ID value: %u ", *value); + } + } + else + { + // ChipLogProgress(Zcl, "Unknown cluster ID: %" PRIx32, clusterId); + return; + } +} diff --git a/examples/lighting-app/beken/main/DeviceCallbacks.cpp b/examples/lighting-app/beken/main/DeviceCallbacks.cpp new file mode 100644 index 00000000000000..aad851257c59e8 --- /dev/null +++ b/examples/lighting-app/beken/main/DeviceCallbacks.cpp @@ -0,0 +1,161 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.cpp + * + * Implements all the callbacks to the application from the CHIP Stack + * + **/ +#include "DeviceCallbacks.h" + +#include "CHIPDeviceManager.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const char * TAG = "app-devicecallbacks"; + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::System; +using namespace ::chip::DeviceLayer; +using namespace ::chip::DeviceManager; +using namespace ::chip::Logging; + +uint32_t identifyTimerCount; +constexpr uint32_t kIdentifyTimerDelayMS = 250; + +void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg) +{ + ChipLogProgress(Zcl, "DeviceEventCallback, event->Type:%d \r\n", event->Type); + switch (event->Type) + { + case DeviceEventType::kInternetConnectivityChange: + OnInternetConnectivityChange(event); + break; + + case DeviceEventType::kSessionEstablished: + OnSessionEstablished(event); + break; + case DeviceEventType::kInterfaceIpAddressChanged: + ChipLogProgress(Zcl, "IP(%s) changed event", (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned)? "IPv4": "IPv6"); + if ((event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV4_Assigned) || + (event->InterfaceIpAddressChanged.Type == InterfaceIpChangeType::kIpV6_Assigned)) + { + // MDNS server restart on any ip assignment: if link local ipv6 is configured, that + // will not trigger a 'internet connectivity change' as there is no internet + // connectivity. MDNS still wants to refresh its listening interfaces to include the + // newly selected address. + chip::app::DnssdServer::Instance().StartServer(); + } + break; + case DeviceEventType::kCHIPoBLEConnectionEstablished: + ChipLogProgress(Zcl, "CHIPoBLE connection established"); + break; + case DeviceEventType::kCHIPoBLEConnectionClosed: + ChipLogProgress(Zcl, "CHIPoBLE disconnected"); + break; + case DeviceEventType::kCommissioningComplete: + ChipLogProgress(Zcl, "Commissioning complete"); + break; + } +} + +void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event) +{ + if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established) + { + ChipLogProgress(Zcl, "Server ready at:%d", CHIP_PORT); + //chip::app::DnssdServer::Instance().StartServer(); + } + else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost) + { + ChipLogProgress(Zcl, "Lost IPv4 connectivity..."); + } + if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established) + { + ChipLogProgress(Zcl, "IPv6 Server ready..."); + chip::app::DnssdServer::Instance().StartServer(); + } + else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost) + { + ChipLogProgress(Zcl, "Lost IPv6 connectivity..."); + } +} + +void DeviceCallbacks::OnSessionEstablished(const ChipDeviceEvent * event) +{ + if (event->SessionEstablished.IsCommissioner) + { + ChipLogProgress(Zcl, "Commissioner detected!"); + } +} + +void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t mask, + uint8_t type, uint16_t size, uint8_t * value) +{ + switch (clusterId) + { + case ZCL_IDENTIFY_CLUSTER_ID: + OnIdentifyPostAttributeChangeCallback(endpointId, attributeId, value); + break; + + default: + ChipLogProgress(Zcl, "Unknown cluster ID: " ChipLogFormatMEI, ChipLogValueMEI(clusterId)); + break; + } +} + +void IdentifyTimerHandler(Layer * systemLayer, void * appState) +{ + // statusLED1.Animate(); + + if (identifyTimerCount) + { + systemLayer->StartTimer(Clock::Milliseconds32(kIdentifyTimerDelayMS), IdentifyTimerHandler, appState); + // Decrement the timer count. + identifyTimerCount--; + } +} + +void DeviceCallbacks::OnIdentifyPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) +{ + VerifyOrExit(attributeId == ZCL_IDENTIFY_TIME_ATTRIBUTE_ID, + ChipLogError(DeviceLayer, "[%s] Unhandled Attribute ID: '0x%04x", TAG, attributeId)); + VerifyOrExit(endpointId == 1, ChipLogError(DeviceLayer, "[%s] Unexpected EndPoint ID: `0x%02x'", TAG, endpointId)); + + // timerCount represents the number of callback executions before we stop the timer. + // value is expressed in seconds and the timer is fired every 250ms, so just multiply value by 4. + // Also, we want timerCount to be odd number, so the ligth state ends in the same state it starts. + identifyTimerCount = (*value) * 4; + + DeviceLayer::SystemLayer().CancelTimer(IdentifyTimerHandler, this); + DeviceLayer::SystemLayer().StartTimer(Clock::Milliseconds32(kIdentifyTimerDelayMS), IdentifyTimerHandler, this); + +exit: + return; +} diff --git a/examples/lighting-app/beken/main/DsoHack.cpp b/examples/lighting-app/beken/main/DsoHack.cpp new file mode 100644 index 00000000000000..2378086f551b8a --- /dev/null +++ b/examples/lighting-app/beken/main/DsoHack.cpp @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// This hack is needed because Beken SDK is not linking against libstdc++ correctly. +extern "C" { +void * __dso_handle = 0; +} diff --git a/examples/lighting-app/beken/main/chipinterface.cpp b/examples/lighting-app/beken/main/chipinterface.cpp new file mode 100644 index 00000000000000..6570769fb8f4ce --- /dev/null +++ b/examples/lighting-app/beken/main/chipinterface.cpp @@ -0,0 +1,284 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "CHIPDeviceManager.h" +#include "DeviceCallbacks.h" +#include "Server.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceManager; +using namespace ::chip::DeviceLayer; + +#define QRCODE_BASE_URL "https://dhrishi.github.io/connectedhomeip/qrcode.html" +#define EXAMPLE_VENDOR_TAG_IP 1 + +static DeviceCallbacks EchoCallbacks; + +// need to check CONFIG_RENDEZVOUS_MODE +bool isRendezvousBLE() +{ + RendezvousInformationFlags flags = RendezvousInformationFlags(CONFIG_RENDEZVOUS_MODE); + return flags.Has(RendezvousInformationFlag::kBLE); +} + +std::string createSetupPayload() +{ + CHIP_ERROR err = CHIP_NO_ERROR; + std::string result; + + uint16_t discriminator; + err = ConfigurationMgr().GetSetupDiscriminator(discriminator); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(Zcl, "Couldn't get discriminator: %s\r\n", ErrorStr(err)); + return result; + } + ChipLogProgress(Zcl, "Setup discriminator: %u (0x%x)\r\n", discriminator, discriminator); + + uint32_t setupPINCode; + err = ConfigurationMgr().GetSetupPinCode(setupPINCode); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(Zcl, "Couldn't get setupPINCode: %s\r\n", ErrorStr(err)); + return result; + } + ChipLogProgress(Zcl, "Setup PIN code: %u (0x%x)\r\n", setupPINCode, setupPINCode); + + uint16_t vendorId; + err = ConfigurationMgr().GetVendorId(vendorId); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(Zcl, "Couldn't get vendorId: %s\r\n", ErrorStr(err)); + return result; + } + + uint16_t productId; + err = ConfigurationMgr().GetProductId(productId); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(Zcl, "Couldn't get productId: %s\r\n", ErrorStr(err)); + return result; + } + ChipLogProgress(Zcl, "Setup VendorId: %u (0x%x)\r\n", vendorId, vendorId); + ChipLogProgress(Zcl, "Setup ProductId: %u (0x%x)\r\n", productId, productId); + SetupPayload payload; + payload.version = 0; + payload.discriminator = discriminator; + payload.setUpPINCode = setupPINCode; + payload.rendezvousInformation = RendezvousInformationFlags(CONFIG_RENDEZVOUS_MODE); + payload.vendorID = vendorId; + payload.productID = productId; + + if (isRendezvousBLE()) + { + QRCodeSetupPayloadGenerator generator(payload); + err = generator.payloadBase38Representation(result); + } + + ManualSetupPayloadGenerator generator(payload); + std::string outCode; + + if (generator.payloadDecimalStringRepresentation(outCode) == CHIP_NO_ERROR) + { + ChipLogProgress(Zcl, "Short Manual(decimal) setup code: %s\r\n", outCode.c_str()); + } + else + { + ChipLogProgress(Zcl, "Failed to get decimal setup code\r\n"); + } + + payload.commissioningFlow = CommissioningFlow::kCustom; + generator = ManualSetupPayloadGenerator(payload); + + if (generator.payloadDecimalStringRepresentation(outCode) == CHIP_NO_ERROR) + { + // intentional extra space here to align the log with the short code + ChipLogProgress(Zcl, "Long Manual(decimal) setup code: %s\r\n", outCode.c_str()); + } + else + { + ChipLogProgress(Zcl, "Failed to get decimal setup code\r\n"); + } + + + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(Zcl, "Couldn't get payload string %\r\n" CHIP_ERROR_FORMAT, err.Format()); + } + return result; +}; + +void OnIdentifyStart(Identify *) +{ + ChipLogProgress(Zcl, "OnIdentifyStart"); +} + +void OnIdentifyStop(Identify *) +{ + ChipLogProgress(Zcl, "OnIdentifyStop"); +} + +void OnTriggerEffect(Identify * identify) +{ + switch (identify->mCurrentEffectIdentifier) + { + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY"); + break; + case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE: + ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE"); + break; + default: + ChipLogProgress(Zcl, "No identifier effect"); + return; + } +} + +static Identify gIdentify1 = { + chip::EndpointId{ 1 }, OnIdentifyStart, OnIdentifyStop, EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, OnTriggerEffect, +}; + +//Warkaround for ld error:undefined reference to '__sync_synchronize' +//refer to https://stackoverflow.com/questions/64658430/gnu-arm-embedded-toolchain-undefined-reference-to-sync-synchronize +extern "C" void __sync_synchronize() {} + +extern "C" unsigned int __atomic_fetch_add_4(volatile void * ptr, unsigned int val, int memorder) +{ + return (*(unsigned int*)ptr + val); +} + +extern "C" bool __atomic_compare_exchange_4(volatile void* pulDestination, void* ulComparand, unsigned int desired, bool weak, int success_memorder, int failure_memorder) +{ + bool ulReturnValue; + if( *(unsigned int*)pulDestination == *(unsigned int*)ulComparand ) + { + *(unsigned int*)pulDestination = desired; + ulReturnValue = true; + } + else + { + *(unsigned int*)ulComparand = *(unsigned int*)pulDestination; + ulReturnValue = false; + } + return ulReturnValue; +} + +extern "C" unsigned int __atomic_fetch_sub_4(volatile void * ptr, unsigned int val, int memorder) +{ + return (*(unsigned int*)ptr + val); +} +extern "C" bool __atomic_compare_exchange_1(volatile void* pulDestination, void* ulComparand, unsigned char desired, bool weak, int success_memorder, int failure_memorder) +{ + bool ulReturnValue; + if( *(unsigned char*)pulDestination == *(unsigned char*)ulComparand ) + { + *(unsigned char*)pulDestination = desired; + ulReturnValue = true; + } + else + { + *(unsigned char*)ulComparand = *(unsigned char*)pulDestination; + ulReturnValue = false; + } + return ulReturnValue; +} + +extern "C" unsigned int __atomic_fetch_and_4(volatile void *pulDestination, unsigned int ulValue, int memorder) +{ + unsigned int ulCurrent; + + ulCurrent = *(unsigned int*)pulDestination; + *(unsigned int*)pulDestination &= ulValue; + return ulCurrent; +} + +extern "C" bool __sync_bool_compare_and_swap_4(volatile void* ptr, unsigned int oldval, unsigned int newval) +{ + if(*(unsigned int*)ptr == oldval) + { + *(unsigned int*)ptr = newval; + return true; + } + else + { + return false; + } +} +/* stub for __libc_init_array */ +extern "C" void _fini(void) { } +extern "C" void _init(void) {;} + +extern "C" void ChipTest(void) +{ + ChipLogProgress(Zcl, "ChipTest"); + CHIP_ERROR err = CHIP_NO_ERROR; + //initPref(); + + CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); + err = deviceMgr.Init(&EchoCallbacks); //start the CHIP task + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(Zcl, "DeviceManagerInit() - ERROR!"); + } + else + { + ChipLogProgress(Zcl, "DeviceManagerInit() - OK"); + } + chip::Server::GetInstance().Init(); + // Initialize device attestation config + SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); + + std::string qrCodeText = createSetupPayload(); + + ChipLogProgress(Zcl, "QR CODE Text: '%s'\r\n", qrCodeText.c_str()); + + { + std::vector qrCode(3 * qrCodeText.size() + 1); + err = EncodeQRCodeToUrl(qrCodeText.c_str(), qrCodeText.size(), qrCode.data(), qrCode.max_size()); + if (err == CHIP_NO_ERROR) + { + ChipLogProgress(DeviceLayer, "Copy/paste the below URL in a browser to see the QR CODE:\t"); + ChipLogProgress(DeviceLayer, "%s?data=%s \r\n",QRCODE_BASE_URL, qrCode.data()); + } + } + while (true) + vTaskDelay(pdMS_TO_TICKS(50)); +} + +bool lowPowerClusterSleep() +{ + return true; +} diff --git a/examples/lighting-app/beken/main/include/CHIPDeviceManager.h b/examples/lighting-app/beken/main/include/CHIPDeviceManager.h new file mode 100644 index 00000000000000..d7b7d41f6513b6 --- /dev/null +++ b/examples/lighting-app/beken/main/include/CHIPDeviceManager.h @@ -0,0 +1,124 @@ +/* + * + * 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. + */ + +/** + * @file + * This file contains definitions for the CHIP DeviceManager Interface + * + * This object will co-ordinate multiple activities such as + * initialisation, rendezvous, session mgmt and other such + * activities within the CHIP stack. This is a singleton object. + */ + +#pragma once + +#include +#include +#include + +#include + +#include +#include + +#include + +namespace chip { +namespace DeviceManager { + +/** + * @brief + * This class provides a skeleton for all the callback functions. The functions will be + * called by other objects within the CHIP stack for specific events. + * Applications interested in receiving specific callbacks can specialize this class and handle + * these events in their implementation of this class. + */ +class CHIPDeviceManagerCallbacks +{ +public: + /** + * @brief + * Called when CHIP Device events (PublicEventTypes) are triggered. + * + * @param event ChipDeviceEvent that occurred + * @param arg arguments specific to the event, if any + */ + virtual void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg) {} + + /** + * @brief + * Called after an attribute has been changed + * + * @param endpoint endpoint id + * @param clusterID cluster id + * @param attributeId attribute id that was changed + * @param mask mask of the attribute + * @param manufacturerCode manufacturer code + * @param type attribute type + * @param size size of the attribute + * @param value pointer to the new value + */ + virtual void PostAttributeChangeCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t mask, uint8_t type, uint16_t size, uint8_t * value) + {} + virtual ~CHIPDeviceManagerCallbacks() {} +}; + +/** + * @brief + * A common class that drives other components of the CHIP stack + */ +class DLL_EXPORT CHIPDeviceManager +{ +public: + CHIPDeviceManager(const CHIPDeviceManager &) = delete; + CHIPDeviceManager(const CHIPDeviceManager &&) = delete; + CHIPDeviceManager & operator=(const CHIPDeviceManager &) = delete; + + static CHIPDeviceManager & GetInstance() + { + static CHIPDeviceManager instance; + return instance; + } + + /** + * @brief + * Initialise CHIPDeviceManager + * + * @param cb Application's instance of the CHIPDeviceManagerCallbacks for consuming events + */ + CHIP_ERROR Init(CHIPDeviceManagerCallbacks * cb); + + /** + * @brief + * Fetch a pointer to the registered CHIPDeviceManagerCallbacks object. + * + */ + CHIPDeviceManagerCallbacks * GetCHIPDeviceManagerCallbacks() { return mCB; } + + /** + * Use internally for registration of the ChipDeviceEvents + */ + static void CommonDeviceEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + +private: + CHIPDeviceManagerCallbacks * mCB = nullptr; + CHIPDeviceManager() {} +}; + +} // namespace DeviceManager +} // namespace chip diff --git a/examples/lighting-app/beken/main/include/DeviceCallbacks.h b/examples/lighting-app/beken/main/include/DeviceCallbacks.h new file mode 100644 index 00000000000000..f7a2c0b52b1624 --- /dev/null +++ b/examples/lighting-app/beken/main/include/DeviceCallbacks.h @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file DeviceCallbacks.h + * + * Implementations for the DeviceManager callbacks for this application + * + **/ + +#pragma once + +#include "CHIPDeviceManager.h" +#include +#include +#include + +class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks +{ +public: + virtual void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, + uint8_t mask, uint8_t type, uint16_t size, uint8_t * value) override; + +private: + void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); + void OnSessionEstablished(const chip::DeviceLayer::ChipDeviceEvent * event); + void OnIdentifyPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); +}; diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index f292d1b99b63fc..45f5c19fec2623 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -240,7 +240,7 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams) // TODO @bzbarsky-apple @cecille Move to examples // ESP32 and Mbed OS examples have a custom logic for enabling DNS-SD #if !CHIP_DEVICE_LAYER_TARGET_ESP32 && !CHIP_DEVICE_LAYER_TARGET_MBED && \ - (!CHIP_DEVICE_LAYER_TARGET_AMEBA || !CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE) + (!CHIP_DEVICE_LAYER_TARGET_AMEBA || !CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE) && !CHIP_DEVICE_LAYER_TARGET_BEKEN // StartServer only enables commissioning mode if device has not been commissioned app::DnssdServer::Instance().StartServer(); #endif diff --git a/src/lib/support/UnitTestUtils.cpp b/src/lib/support/UnitTestUtils.cpp index c63bd5be015596..eba5c56665c27c 100644 --- a/src/lib/support/UnitTestUtils.cpp +++ b/src/lib/support/UnitTestUtils.cpp @@ -19,7 +19,7 @@ // Platform specific includes for test_utils #include -#if CHIP_DEVICE_LAYER_TARGET_EFR32 || CHIP_DEVICE_LAYER_TARGET_AMEBA +#if CHIP_DEVICE_LAYER_TARGET_EFR32 || CHIP_DEVICE_LAYER_TARGET_AMEBA || CHIP_DEVICE_LAYER_TARGET_BEKEN #include #include #else @@ -30,7 +30,7 @@ namespace chip { namespace test_utils { -#if CHIP_DEVICE_LAYER_TARGET_EFR32 || CHIP_DEVICE_LAYER_TARGET_AMEBA +#if CHIP_DEVICE_LAYER_TARGET_EFR32 || CHIP_DEVICE_LAYER_TARGET_AMEBA || CHIP_DEVICE_LAYER_TARGET_BEKEN namespace { diff --git a/src/platform/BUILD.gn b/src/platform/BUILD.gn index ce0b3bc89c518c..8554f1276eaf8b 100644 --- a/src/platform/BUILD.gn +++ b/src/platform/BUILD.gn @@ -248,6 +248,12 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { ] defines -= [ "CHIP_DEVICE_CONFIG_ENABLE_WPA=${chip_device_config_enable_wpa}" ] + } else if (chip_device_platform == "beken") { + defines += [ + "CHIP_DEVICE_LAYER_TARGET_BEKEN=1", + "CHIP_DEVICE_LAYER_TARGET=Beken", + "CHIP_DEVICE_CONFIG_ENABLE_WIFI=${chip_enable_wifi}", + ] } } } else if (chip_device_platform == "none") { @@ -399,6 +405,8 @@ if (chip_device_platform != "none") { _platform_target = "fake" } else if (chip_device_platform == "cyw30739") { _platform_target = "CYW30739" + } else if (chip_device_platform == "beken") { + _platform_target = "Beken" } else { assert(false, "Unknown chip_device_platform: ${chip_device_platform}") } diff --git a/src/platform/Beken/BLEManagerImpl.cpp b/src/platform/Beken/BLEManagerImpl.cpp new file mode 100755 index 00000000000000..f84be5aeb2cf32 --- /dev/null +++ b/src/platform/Beken/BLEManagerImpl.cpp @@ -0,0 +1,1171 @@ +/* + * + * Copyright (c) 2020-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 + * Provides an implementation of the BLEManager singleton object + * for the Beken platforms. + */ + +/* this file behaves like a config.h, comes first */ +#include +#include + +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#include + +#include "stdio.h" +#include "timers.h" + +// BK7231n BLE related header files +#include "ble_api_5_x.h" +#include "ble_api.h" +#include "app_ble.h" +#include "app_sdp.h" +#include "app_ble_init.h" +#include "ble_ui.h" +#include "rtos_pub.h" +#include "timers.h" + +/******************************************************************************* + * Local data types + *******************************************************************************/ +using namespace ::chip; +using namespace ::chip::Ble; + +namespace chip { +namespace DeviceLayer { +namespace Internal { + +namespace { + +/******************************************************************************* + * Macros & Constants definitions + *******************************************************************************/ +#ifndef MAX_ADV_DATA_LEN +#define MAX_ADV_DATA_LEN 31 +#endif +#define CHIP_ADV_DATA_TYPE_FLAGS 0x01 +#define CHIP_ADV_DATA_FLAGS 0x06 + +/* advertising configuration */ +#define CHIP_ADV_SHORT_UUID_LEN (2) + +/* FreeRTOS sw timer */ +TimerHandle_t bleFastAdvTimer; + +enum +{ + DriveBLEExtPerfEvt_DISCONNECT = 0, +}; + +const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, + 0x9D, 0x11 } }; +const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, + 0x9D, 0x12 } }; +static const uint8_t _svc_uuid[16] = {0xF6,0xFF,0,0,0x0,0x0,0,0,0,0,0x0,0x0,0,0,0,0}; + +#define UUID_CHIPoBLECharact_RX { 0x11, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18 } +//#define UUID_CHIPoBLECharact_RX { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x11 } +#define ChipUUID_CHIPoBLECharact_TX { 0x12, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18 } +//#define ChipUUID_CHIPoBLECharact_TX { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x12 } + +#define BEKEN_ATT_DECL_PRIMARY_SERVICE_128 {0x00,0x28,0,0,0,0,0,0,0,0,0,0,0,0,0,0} +#define BEKEN_ATT_DECL_CHARACTERISTIC_128 {0x03,0x28,0,0,0,0,0,0,0,0,0,0,0,0,0,0} +#define BEKEN_ATT_DESC_CLIENT_CHAR_CFG_128 {0x02,0x29,0,0,0,0,0,0,0,0,0,0,0,0,0,0} + +enum +{ + SVR_FFF6_IDX_SVC = 0, + SVR_FFF6_RX_DECL = 1, + SVR_FFF6_RX_VALUE = 2, + SVR_FFF6_TX_DECL = 3, + SVR_FFF6_TX_VALUE = 4, + SVR_FFF6_TX_CFG = 5, + SVR_FFF6_MAX = 6, +}; + +bk_attm_desc_t svr_fff6_att_db[SVR_FFF6_MAX] = +{ + // Service Declaration + [SVR_FFF6_IDX_SVC] = {BEKEN_ATT_DECL_PRIMARY_SERVICE_128, BK_PERM_SET(RD, ENABLE), 0, 2}, + + // Level Characteristic Declaration + [SVR_FFF6_RX_DECL] = {BEKEN_ATT_DECL_CHARACTERISTIC_128, BK_PERM_SET(RD, ENABLE), 0, 0}, + // Level Characteristic Value BK_PERM_RIGHT_ENABLE WRITE_REQ_POS RI_POS UUID_LEN_POS BK_PERM_RIGHT_UUID_128 + [SVR_FFF6_RX_VALUE] = {UUID_CHIPoBLECharact_RX, BK_PERM_SET(WRITE_REQ, ENABLE), BK_PERM_SET(RI, ENABLE)|BK_PERM_SET(UUID_LEN, UUID_128), 512}, + + ///RD_POS NTF_POS + [SVR_FFF6_TX_DECL] = {BEKEN_ATT_DECL_CHARACTERISTIC_128, BK_PERM_SET(RD, ENABLE) | BK_PERM_SET(NTF, ENABLE), 0, 0}, + //// UUID_LEN_POS BK_PERM_RIGHT_UUID_128 RD_POS + [SVR_FFF6_TX_VALUE] = {ChipUUID_CHIPoBLECharact_TX, BK_PERM_SET(RD, ENABLE) | BK_PERM_SET(NTF, ENABLE), BK_PERM_SET(RI, ENABLE) | BK_PERM_SET(UUID_LEN, UUID_128), 512}, + [SVR_FFF6_TX_CFG] = {BEKEN_ATT_DESC_CLIENT_CHAR_CFG_128, BK_PERM_SET(RD, ENABLE) | BK_PERM_SET(WRITE_REQ, ENABLE), 0, 2}, +}; + + +///const static uint8_t svr_fff6_att_db_item = SVR_FFF6_MAX; +} // namespace + +BLEManagerImpl BLEManagerImpl::sInstance; + +int BLEManagerImpl::beken_ble_init(void) +{ + int status; + + struct bk_ble_db_cfg ble_db_cfg; + + ble_db_cfg.att_db = svr_fff6_att_db; + ble_db_cfg.att_db_nb = SVR_FFF6_MAX; + ble_db_cfg.prf_task_id = 0; + ble_db_cfg.start_hdl = 0; + ble_db_cfg.svc_perm = BK_PERM_SET(SVC_UUID_LEN, UUID_16); + memcpy(&(ble_db_cfg.uuid[0]), &_svc_uuid[0], 16); + + status = bk_ble_create_db(&ble_db_cfg); + if(status != ERR_SUCCESS){ + return -1; + } + return 0; +} + + +CHIP_ERROR BLEManagerImpl::_Init() +{ + CHIP_ERROR err; + + // Initialize the CHIP BleLayer. + err = BleLayer::Init(this, this, &DeviceLayer::SystemLayer()); + SuccessOrExit(err); + + mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; + memset(mBleConnections, 0, sizeof(mBleConnections)); + // Check if BLE stack is initialized + VerifyOrExit(!mFlags.Has(Flags::kAMEBABLEStackInitialized), err = CHIP_ERROR_INCORRECT_STATE); + ble_set_notice_cb(ble_event_notice); + + // Set related flags + mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); + mFlags.Set(Flags::kAMEBABLEStackInitialized); + mFlags.Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? true : false); + mFlags.Set(Flags::kFastAdvertisingEnabled); + mFlags.Set(Flags::kSlowAdvertisingEnabled); + if(!mFlags.Has(Flags::kBEKENBLEAdvTimer)){ + uint32_t bleAdvTimeoutMs = CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME; + bleFastAdvTimer = xTimerCreate("", + ( bleAdvTimeoutMs / 2 ), + pdFALSE, + NULL, + ble_adv_timer_timeout_handle ); + mFlags.Set(Flags::kBEKENBLEAdvTimer); + } + + PlatformMgr().ScheduleWork(DriveBLEState, 0); + +exit: + return err; +} + +void BLEManagerImpl::HandleTXCharRead(void* param) +{ + CHIPoBLEConState * conState; + read_req_t *r_req = (read_req_t *)param; + if(param == NULL){ + ChipLogError(DeviceLayer, "HandleTXCharRead failed: %p",param); + } + r_req->length = 0; +} + +void BLEManagerImpl::HandleTXCharCCCDRead(void * param) +{ + CHIPoBLEConState * conState; + read_req_t *r_req = (read_req_t *)param; + conState = GetConnectionState(r_req->conn_idx); + + if(param == NULL) { + ChipLogError(DeviceLayer, "HandleTXCharCCCDRead failed"); + return; + } + + if (conState != NULL) { + r_req->value[0] = conState->subscribed ? 1 : 0; + r_req->value[1] = 0; + r_req->length = 2; + } + else { + ChipLogError(DeviceLayer, "conState failed: %p",conState); + r_req->length = 0; + } +} + +void BLEManagerImpl::HandleTXCharCCCDWrite(int conn_id, int notificationsEnabled, int indicationsEnabled) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + // If the client has requested to enabled indications/notifications + if (indicationsEnabled || notificationsEnabled) + { + // If indications are not already enabled for the connection... + if (!IsSubscribed(conn_id)) + { + // Record that indications have been enabled for this connection. + err = SetSubscribed(conn_id); + VerifyOrExit(err != CHIP_ERROR_NO_MEMORY, err = CHIP_NO_ERROR); + SuccessOrExit(err); + } + } + else + { + // If indications had previously been enabled for this connection, record that they are no longer enabled. + UnsetSubscribed(conn_id); + } + + // Post an event to the Chip queue to process either a CHIPoBLE Subscribe or Unsubscribe based on + // whether the client is enabling or disabling indications. + { + ChipDeviceEvent event; + event.Type = (indicationsEnabled || notificationsEnabled) ? DeviceEventType::kCHIPoBLESubscribe + : DeviceEventType::kCHIPoBLEUnsubscribe; + event.CHIPoBLESubscribe.ConId = conn_id; + PlatformMgr().PostEventOrDie(&event); + } + + ChipLogProgress(DeviceLayer, "CHIPoBLE %s received", + (indicationsEnabled || notificationsEnabled) ? "subscribe" : "unsubscribe"); + +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "HandleTXCharCCCDWrite() failed: %s", ErrorStr(err)); + } + + return; +} + +CHIP_ERROR BLEManagerImpl::HandleTXComplete(int conn_id) +{ + // Post an event to the Chip queue to process the indicate confirmation. + ChipDeviceEvent event; + event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm; + event.CHIPoBLEIndicateConfirm.ConId = conn_id; + PlatformMgr().PostEventOrDie(&event); + return CHIP_NO_ERROR; +} + +uint16_t BLEManagerImpl::_NumConnections(void) +{ + uint16_t numCons = 0; + + for (uint8_t i = 0; i < kMaxConnections; i++) + { + if (mBleConnections[i].allocated == 1) + { + numCons += 1; + } + } + + return numCons; +} + +CHIP_ERROR BLEManagerImpl::HandleGAPConnect(uint16_t conn_id) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + // Track the number of active GAP connections. + mNumGAPCons++; + err = SetSubscribed(conn_id); + VerifyOrExit(err != CHIP_ERROR_NO_MEMORY, err = CHIP_NO_ERROR); + SuccessOrExit(err); + +exit: + return err; +} + +CHIP_ERROR BLEManagerImpl::HandleGAPDisconnect(uint16_t conn_id, uint16_t disc_cause) +{ + // Update the number of GAP connections. + if (mNumGAPCons > 0) + { + mNumGAPCons--; + } + + if (RemoveConnection(conn_id)) + { + CHIP_ERROR disconReason; + switch (disc_cause) + { + case 0x13: + case 0x08: + disconReason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; + break; + case 0x16: + disconReason = BLE_ERROR_APP_CLOSED_CONNECTION; + break; + default: + disconReason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT; + break; + } + HandleConnectionError(conn_id, disconReason); + } + + // Force a reconfiguration of advertising in case we switched to non-connectable mode when + // the BLE connection was established. + mFlags.Set(Flags::kAdvertisingRefreshNeeded); + return CHIP_NO_ERROR; +} + +bool BLEManagerImpl::RemoveConnection(uint8_t connectionHandle) +{ + CHIPoBLEConState * bleConnState = GetConnectionState(connectionHandle); + bool status = false; + + if (bleConnState != NULL) + { + bleConnState->Reset(); + memset(bleConnState, 0, sizeof(CHIPoBLEConState)); + status = true; + } + return status; +} + +BLEManagerImpl::CHIPoBLEConState * BLEManagerImpl::GetConnectionState(uint8_t connectionHandle, bool allocate) +{ + uint8_t freeIndex = kMaxConnections; + + for (uint8_t i = 0; i < kMaxConnections; i++) + { + if (mBleConnections[i].allocated == 1) + { + if (mBleConnections[i].conn_idx == connectionHandle) + { + return &mBleConnections[i]; + } + } + + else if (i < freeIndex) + { + freeIndex = i; + } + } + + if (allocate) + { + if (freeIndex < kMaxConnections) + { + mBleConnections[freeIndex].Set(connectionHandle); + return &mBleConnections[freeIndex]; + } + + ChipLogError(DeviceLayer, "Failed to allocate CHIPoBLEConState"); + } + + return NULL; +} + +CHIP_ERROR BLEManagerImpl::_SetCHIPoBLEServiceMode(CHIPoBLEServiceMode val) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + VerifyOrExit(val != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); + + if (val != mServiceMode) + { + mServiceMode = val; + PlatformMgr().ScheduleWork(DriveBLEState, 0); + } + +exit: + return err; +} + +CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); + + if (mFlags.Has(Flags::kAdvertisingEnabled) != val) + { + mFlags.Set(Flags::kAdvertisingEnabled, val); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + } + +exit: + return err; +} + +CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode) +{ + switch (mode) + { + case BLEAdvertisingMode::kFastAdvertising: + mFlags.Set(Flags::kFastAdvertisingEnabled, true); + break; + case BLEAdvertisingMode::kSlowAdvertising: + mFlags.Set(Flags::kFastAdvertisingEnabled, false); + break; + default: + return CHIP_ERROR_INVALID_ARGUMENT; + } + mFlags.Set(Flags::kAdvertisingRefreshNeeded); + + PlatformMgr().ScheduleWork(DriveBLEState, 0); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) +{ + if (strlen(mDeviceName) >= bufSize) + { + return CHIP_ERROR_BUFFER_TOO_SMALL; + } + strcpy(buf, mDeviceName); + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); + + if (deviceName != NULL && deviceName[0] != 0) + { + VerifyOrExit(strlen(deviceName) >= kMaxDeviceNameLength, err = CHIP_ERROR_INVALID_ARGUMENT); + strcpy(mDeviceName, deviceName); + mFlags.Set(Flags::kDeviceNameSet); + ChipLogProgress(DeviceLayer, "Setting device name to : \"%s\"", deviceName); + } + else + { + mDeviceName[0] = 0; + mFlags.Clear(Flags::kDeviceNameSet); + } + +exit: + return err; +} + +void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) +{ + switch (event->Type) + { + // Platform specific events + case DeviceEventType::kCHIPoBLESubscribe: + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + { + ChipDeviceEvent connEstEvent; + connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; + PlatformMgr().PostEventOrDie(&connEstEvent); + } + break; + + case DeviceEventType::kCHIPoBLEUnsubscribe: { + ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEUnsubscribe"); + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + } + break; + + case DeviceEventType::kCHIPoBLEWriteReceived: { + ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEWriteReceived"); + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); + } + break; + + case DeviceEventType::kCHIPoBLEConnectionError: { + ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEConnectionError"); + HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason); + } + break; + + case DeviceEventType::kCHIPoBLEIndicateConfirm: { + ChipLogProgress(DeviceLayer, "_OnPlatformEvent kCHIPoBLEIndicateConfirm"); + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + } + break; + + case DeviceEventType::kFabricMembershipChange: + case DeviceEventType::kServiceProvisioningChange: + case DeviceEventType::kAccountPairingChange: + case DeviceEventType::kWiFiConnectivityChange: + +// If CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED is enabled, when there is a change to the device's provisioning state and device +// is now fully provisioned, the CHIPoBLE advertising will be disabled. +#if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED + if (ConfigurationMgr().IsFullyProvisioned()) + { + mFlags.Clear(Flags::kAdvertisingEnabled); + ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); + } +#endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED + ChipLogProgress(DeviceLayer, "Updating advertising data"); + StartAdvertising(); + break; + + default: + ChipLogProgress(DeviceLayer, "_OnPlatformEvent default: event->Type = %d", event->Type); + break; + } +} + +bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) +{ + ChipLogProgress(DeviceLayer, "BLEManagerImpl::SubscribeCharacteristic() not supported"); + return false; +} + +bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) +{ + ChipLogProgress(DeviceLayer, "BLEManagerImpl::UnsubscribeCharacteristic() not supported"); + return false; +} + +bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) +{ + CHIP_ERROR err; + ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (con %u)", conId); + uint32_t delay_time = 20; + int ret; + + do{ + ret = bk_ble_disconnect(conId, beken_ble_cmd_cb); + if(ERR_SUCCESS == ret){ + break; + } + rtos_delay_milliseconds(10); + delay_time--; + }while(delay_time); + // Beken Ble close function + err = MapBLEError(ret); + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "bk_ble_disconnect() failed: %s", ErrorStr(err)); + } + + return false; +} + +uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const +{ + CHIPoBLEConState * conState = const_cast(this)->GetConnectionState(conId); + return (conState != NULL) ? conState->mtu : 0; +} + +bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, + PacketBufferHandle pBuf) +{ + ChipLogError(DeviceLayer, "BLEManagerImpl::SendWriteRequest() not supported"); + return false; +} + +bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, + PacketBufferHandle pBuf) +{ + ChipLogError(DeviceLayer, "BLEManagerImpl::SendReadRequest() not supported"); + return false; +} + +bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, + const ChipBleUUID * svcId, const ChipBleUUID * charId) +{ + ChipLogError(DeviceLayer, "BLEManagerImpl::SendReadResponse() not supported"); + return false; +} + +void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) +{ + // Nothing to do +} + +extern "C" ble_err_t bk_ble_send_ntf_value(uint32_t len, uint8_t *buf, uint16_t prf_id, uint16_t att_idx); + +bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, + PacketBufferHandle data) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + int ret; + + VerifyOrExit(IsSubscribed(conId), err = CHIP_ERROR_INVALID_ARGUMENT); + ret = bk_ble_send_ntf_value(/*conId,*/data->DataLength(),data->Start(), 0, SVR_FFF6_TX_VALUE); + err = MapBLEError(ret); +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %s", ErrorStr(err)); + return false; + } + + return true; +} + +/******************************************************************************* + * Private functions + *******************************************************************************/ + +CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + // If the device name is not specified, generate a CHIP-standard name based on the bottom digits of the Chip device id. + uint16_t discriminator; + SuccessOrExit(err = ConfigurationMgr().GetSetupDiscriminator(discriminator)); + + if (!mFlags.Has(Flags::kDeviceNameSet)) + { + snprintf(mDeviceName, sizeof(mDeviceName), "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, discriminator); + mDeviceName[kMaxDeviceNameLength] = 0; + } + + // Configure the BLE device name. + sInstance.mFlags.Set(Flags::kDeviceNameDefSet); + ble_appm_set_dev_name(kMaxDeviceNameLength, (uint8_t*)mDeviceName); + +exit: + return err; +} + +CHIP_ERROR BLEManagerImpl::StartAdvertising(void) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + ChipLogProgress(DeviceLayer, "StartAdvertising..."); + if((!mFlags.Has(Flags::kDeviceNameSet)) && (!mFlags.Has(Flags::kDeviceNameDefSet))){ + err = sInstance.ConfigureAdvertisingData(); + SuccessOrExit(err); + } + // Post a CHIPoBLEAdvertisingChange(Stopped) event. + if (mFlags.Has(Flags::kBEKENBLEADVStop)) + { + bk_ble_delete_advertising(adv_actv_idx, beken_ble_cmd_cb); + mFlags.Clear(Flags::kBEKENBLEADVStop); + ChipDeviceEvent advChange; + advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; + advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Stopped; + PlatformMgr().PostEventOrDie(&advChange); + goto exit; + } + else if(!mFlags.Has(Flags::kBEKENBLEADVCreate)) + { + uint16_t adv_int_min; + uint16_t adv_int_max; + + if (mFlags.Has(Flags::kFastAdvertisingEnabled)) + { + adv_int_min = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN; + adv_int_max = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX; + mFlags.Set(Flags::kAdvertisingIsFastADV); + } + else + { + adv_int_min = CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MIN; + adv_int_max = CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX; + mFlags.Clear(Flags::kAdvertisingIsFastADV); + } + adv_actv_idx = app_ble_get_idle_actv_idx_handle(); + if(BLE_ACTIVITY_MAX <= adv_actv_idx){ + ChipLogError(DeviceLayer, "adv act-idx:%d error", adv_actv_idx); + return MapBLEError(-1); + } + bk_ble_create_advertising(adv_actv_idx, 7, adv_int_min, adv_int_max, beken_ble_cmd_cb); + sInstance.mFlags.Clear(Flags::kAdvertisingRefreshNeeded); + goto exit; + } + else if(!mFlags.Has(Flags::kBEKENBLEADVSetData)){ + ChipBLEDeviceIdentificationInfo deviceIdInfo; + uint8_t advData[MAX_ADV_DATA_LEN] = { 0 }; + uint8_t index = 0; + /**************** Prepare advertising data *******************************************/ + memset(advData, 0, sizeof(advData)); + advData[index++] = 0x02; // length + advData[index++] = CHIP_ADV_DATA_TYPE_FLAGS; // AD type : flags + advData[index++] = CHIP_ADV_DATA_FLAGS; // AD value + advData[index++] = static_cast(sizeof(deviceIdInfo) + CHIP_ADV_SHORT_UUID_LEN + 1);; // length + advData[index++] = 0x16; // AD type: (Service Data - 16-bit UUID) + advData[index++] = static_cast(_svc_uuid[0] & 0xFF); // AD value + advData[index++] = static_cast(_svc_uuid[1] & 0xFF); // AD value + err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(deviceIdInfo); + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "GetBLEDeviceIdentificationInfo(): %s", ErrorStr(err)); + ExitNow(); + } + + VerifyOrExit(index + sizeof(deviceIdInfo) <= sizeof(advData), err = CHIP_ERROR_OUTBOUND_MESSAGE_TOO_BIG); + memcpy(&advData[index], &deviceIdInfo, sizeof(deviceIdInfo)); + index = static_cast(index + sizeof(deviceIdInfo)); + bk_ble_set_adv_data(adv_actv_idx, advData, index, beken_ble_cmd_cb); + goto exit; + } + else if(!mFlags.Has(Flags::kBEKENBLEADVSetRsp)) { + ///uint8_t advData[MAX_ADV_DATA_LEN] = { 0 }; + ///bk_ble_set_scan_rsp_data(adv_actv_idx, advData, 0xF, beken_ble_cmd_cb); + sInstance.mFlags.Set(Flags::kBEKENBLEADVSetRsp); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + goto exit; + } + else if(!mFlags.Has(Flags::kBEKENBLEADVStarted)){ + bk_ble_start_advertising(adv_actv_idx, 0, beken_ble_cmd_cb); + goto exit; + } + + if (mFlags.Has(Flags::kBEKENBLEADVStarted)) + { + ChipDeviceEvent advChange; + advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; + advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Started; + PlatformMgr().PostEventOrDie(&advChange); + } + +exit: + return err; +} + +CHIP_ERROR BLEManagerImpl::StopAdvertising(void) +{ + // Change flag status to the 'not Advertising state' + if ((mFlags.Has(Flags::kBEKENBLEADVStarted)) && (!mFlags.Has(Flags::kBEKENBLEADVStop))) + { + mFlags.Set(Flags::kBEKENBLEADVStop); + bk_ble_stop_advertising(adv_actv_idx, beken_ble_cmd_cb); + ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopping"); + goto exit; + } + + // Post a CHIPoBLEAdvertisingChange(Stopped) event. + if (mFlags.Has(Flags::kBEKENBLEADVStop)) + { + bk_ble_delete_advertising(adv_actv_idx, beken_ble_cmd_cb); + mFlags.Clear(Flags::kBEKENBLEADVStop); + ChipDeviceEvent advChange; + advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; + advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Stopped; + PlatformMgr().PostEventOrDie(&advChange); + } +exit: + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLEManagerImpl::MapBLEError(int bleErr) +{ + switch (bleErr) + { + case ERR_SUCCESS: + return CHIP_NO_ERROR; + default: + return CHIP_ERROR_INCORRECT_STATE; + } +} + +void BLEManagerImpl::DriveBLEState(void) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + // Check if BLE stack is initialized + VerifyOrExit(mFlags.Has(Flags::kAMEBABLEStackInitialized), /* */); + if(mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled){ + if(!mFlags.Has(Flags::kBekenBLESGATTSReady)){ + beken_ble_init(); + goto exit; + } + } + +// If CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED is enabled and the device is fully provisioned, the CHIPoBLE +// advertising will be disabled. +#if CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED + if (ConfigurationMgr().IsFullyProvisioned()) + { + mFlags.Clear(Flags::kAdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingRefreshNeeded); + ChipLogProgress(DeviceLayer, "CHIPoBLE advertising disabled because device is fully provisioned"); + } +#endif // CHIP_DEVICE_CONFIG_CHIPOBLE_DISABLE_ADVERTISING_WHEN_PROVISIONED + + if((!mFlags.Has(Flags::kFastAdvertisingEnabled)) && (!mFlags.Has(Flags::kSlowAdvertisingEnabled))){ + mFlags.Clear(Flags::kAdvertisingEnabled); + mFlags.Clear(Flags::kAdvertisingRefreshNeeded); + } + + if(mFlags.Has(Flags::kAdvertisingRefreshNeeded)){ + if(mFlags.Has(Flags::kBEKENBLEADVStarted)){ + err = StopAdvertising(); + SuccessOrExit(err); + goto exit; + }else if(mFlags.Has(Flags::kBEKENBLEADVStarted)){ + bk_ble_delete_advertising(adv_actv_idx, beken_ble_cmd_cb); + goto exit; + } + } + + // Start advertising if needed... + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled + && ((mFlags.Has(Flags::kAdvertisingEnabled)) || (mFlags.Has(Flags::kAdvertisingRefreshNeeded)))) + { + // Start/re-start advertising if not already started, or if there is a pending change + // to the advertising configuration. + if (!mFlags.Has(Flags::kBEKENBLEADVStarted)) + { + err = StartAdvertising(); + SuccessOrExit(err); + } + else{ + mFlags.Clear(Flags::kAdvertisingRefreshNeeded); + } + } + // Otherwise, stop advertising if it is enabled. + else if ((mFlags.Has(Flags::kBEKENBLEADVStarted)) || (mFlags.Has(Flags::kBEKENBLEADVStop))) + { + err = StopAdvertising(); + SuccessOrExit(err); + ChipLogProgress(DeviceLayer, "Stopped Advertising"); + } + +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); + mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; + } +} + +void BLEManagerImpl::DriveBLEState(intptr_t arg) +{ + sInstance.DriveBLEState(); +} + +void BLEManagerImpl::DriveBLEExtPerf(intptr_t arg) +{ + int arg_int = static_cast(arg); + int event = arg_int & 0xFFU; + switch(event){ + case DriveBLEExtPerfEvt_DISCONNECT: + { + uint8_t conn_indx = (arg_int >> 8) & 0xFFU; + sInstance.CloseConnection(conn_indx); + } + break; + default: + break; + } +} + +/******************************************************************************* + * FreeRTOS Task Management Functions + *******************************************************************************/ +void BLEManagerImpl::ble_adv_timer_timeout_handle(TimerHandle_t xTimer) +{ + if (sInstance.mFlags.Has(Flags::kFastAdvertisingEnabled)) + { + ChipLogDetail(DeviceLayer, "bleAdv Timeout : Stop Fast advertisement"); + + sInstance.mFlags.Clear(Flags::kFastAdvertisingEnabled); + // Stop advertising, change interval and restart it; + sInstance.StopAdvertising(); + } + else if (sInstance._IsAdvertisingEnabled()) + { + // Advertisement time expired. Stop advertising + ChipLogDetail(DeviceLayer, "bleAdv Timeout : Stop slow advertisement"); + sInstance.mFlags.Clear(Flags::kSlowAdvertisingEnabled); + sInstance.StopAdvertising(); + } +} + +void BLEManagerImpl::CancelBleAdvTimeoutTimer(void) +{ + if (xTimerIsTimerActive(bleFastAdvTimer)) { + if (xTimerStop(bleFastAdvTimer, 0) == pdFAIL) + { + ChipLogError(DeviceLayer, "Failed to stop BledAdv timeout timer"); + sInstance.mFlags.Clear(Flags::kBEKENBLEAdvTimerRun); + } + } +} + +void BLEManagerImpl::StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs) +{ + CancelBleAdvTimeoutTimer(); + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(bleFastAdvTimer, aTimeoutInMs / portTICK_PERIOD_MS, 100) != pdPASS) + { + ChipLogError(DeviceLayer, "Failed to start BledAdv timeout timer"); + }else{ + xTimerStart( bleFastAdvTimer, BEKEN_WAIT_FOREVER ); + sInstance.mFlags.Set(Flags::kBEKENBLEAdvTimerRun); + } +} + +CHIP_ERROR BLEManagerImpl::SetSubscribed(uint16_t conId) +{ + CHIPoBLEConState * bleConnState = GetConnectionState(conId, false); + + if(bleConnState != NULL){ + bleConnState->subscribed = 1; + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_NO_MEMORY; +} + +bool BLEManagerImpl::UnsetSubscribed(uint16_t conId) +{ + CHIPoBLEConState * bleConnState = GetConnectionState(conId, false); + + if(bleConnState != NULL){ + bleConnState->subscribed = 0; + return true; + } + + return false; +} + +bool BLEManagerImpl::IsSubscribed(uint16_t conId) +{ + CHIPoBLEConState * bleConnState = GetConnectionState(conId, false); + + if(bleConnState != NULL){ + if(bleConnState->subscribed){ + return true; + } + } + return false; +} + +void BLEManagerImpl::HandleRXCharWrite(uint8_t * p_value, uint16_t len, uint8_t conn_id) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + PacketBufferHandle buf = System::PacketBufferHandle::New(len, 0); + memcpy(buf->Start(), p_value, len); + buf->SetDataLength(len); + + // Post an event to the Chip queue to deliver the data into the Chip stack. + { + ChipDeviceEvent event; + event.Type = DeviceEventType::kCHIPoBLEWriteReceived; + event.CHIPoBLEWriteReceived.ConId = (uint16_t) conn_id; + event.CHIPoBLEWriteReceived.Data = std::move(buf).UnsafeRelease(); + PlatformMgr().PostEventOrDie(&event); + } + + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "HandleRXCharWrite() failed: %s", ErrorStr(err)); + } +} + +void BLEManagerImpl::HandleTXCharConfirm(CHIPoBLEConState * conState, int status) +{ + // If the confirmation was successful... + if (status == 0) + { + // Post an event to the Chip queue to process the indicate confirmation. + ChipDeviceEvent event; + event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm; + event.CHIPoBLEIndicateConfirm.ConId = conState->conn_idx; + PlatformMgr().PostEventOrDie(&event); + } + else + { + ChipDeviceEvent event; + event.Type = DeviceEventType::kCHIPoBLEConnectionError; + event.CHIPoBLEConnectionError.ConId = conState->conn_idx; + event.CHIPoBLEConnectionError.Reason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT; + PlatformMgr().PostEventOrDie(&event); + } +} + +void BLEManagerImpl::beken_ble_cmd_cb(ble_cmd_t cmd, ble_cmd_param_t *param) +{ + ChipLogProgress(DeviceLayer,"cmd:%d idx:%d status:%d\r\n", cmd, param->cmd_idx, param->status); + switch(cmd){ + case BLE_CREATE_ADV: + sInstance.mFlags.Set(Flags::kBEKENBLEADVCreate); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + break; + case BLE_SET_ADV_DATA: + sInstance.mFlags.Set(Flags::kBEKENBLEADVSetData); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + break; + case BLE_SET_RSP_DATA: + sInstance.mFlags.Set(Flags::kBEKENBLEADVSetRsp); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + break; + case BLE_START_ADV: + { + uint32_t bleAdvTimeoutMs; + sInstance.mFlags.Set(Flags::kBEKENBLEADVStarted); + if (sInstance.mFlags.Has(Flags::kAdvertisingIsFastADV)){ + bleAdvTimeoutMs = CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME; + }else{ + bleAdvTimeoutMs = CHIP_DEVICE_CONFIG_BLE_ADVERTISING_TIMEOUT; + } + StartBleAdvTimeoutTimer(bleAdvTimeoutMs); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + } + break; + case BLE_STOP_ADV: + sInstance.mFlags.Clear(Flags::kBEKENBLEADVStarted); + ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped"); + CancelBleAdvTimeoutTimer(); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + break; + case BLE_DELETE_ADV: + sInstance.mFlags.Clear(Flags::kBEKENBLEADVCreate); + sInstance.mFlags.Clear(Flags::kBEKENBLEADVSetData); + sInstance.mFlags.Clear(Flags::kBEKENBLEADVSetRsp); + sInstance.mFlags.Clear(Flags::kBEKENBLEADVStarted); + sInstance.adv_actv_idx = kUnusedIndex; + PlatformMgr().ScheduleWork(DriveBLEState, 0); + break; + case BLE_CONN_DIS_CONN: + break; + default: + break; + } +} + +void BLEManagerImpl::ble_event_notice(ble_notice_t notice, void *param) +{ + ///BLEManagerImpl * blemgr = static_cast(param); + switch (notice) + { + case BLE_5_STACK_OK: + { + ChipLogProgress(DeviceLayer, "ble stack ok"); + sInstance.mFlags.Set(Flags::kAMEBABLEStackInitialized); + } + break; + case BLE_5_WRITE_EVENT: + { + write_req_t *w_req = (write_req_t *)param; + ChipLogProgress(DeviceLayer, "write_cb:conn_idx:%d, prf_id:%d, add_id:%d, len:%d, data[0]:%02x\r\n", + w_req->conn_idx, w_req->prf_id, w_req->att_idx, w_req->len, w_req->value[0]); + if (w_req->att_idx == SVR_FFF6_TX_VALUE) + { + sInstance.HandleRXCharWrite((uint8_t*)&w_req->value[0],w_req->len,w_req->conn_idx); + } + else if (w_req->att_idx == SVR_FFF6_TX_CFG) + { + int notificationsEnabled = w_req->value[0] | (w_req->value[0] << 8); + sInstance.HandleTXCharCCCDWrite(w_req->conn_idx, notificationsEnabled); + } + else if (w_req->att_idx == SVR_FFF6_RX_VALUE) + { + sInstance.HandleRXCharWrite((uint8_t*)&w_req->value[0],w_req->len,w_req->conn_idx); + } + break; + } + case BLE_5_READ_EVENT: + { + read_req_t *r_req = (read_req_t *)param; + ChipLogProgress(DeviceLayer, "read_cb:conn_idx:%d, prf_id:%d, add_id:%d\r\n", + r_req->conn_idx, r_req->prf_id, r_req->att_idx); + if (r_req->att_idx == SVR_FFF6_RX_VALUE) + { + sInstance.HandleTXCharRead(param); + } + if (r_req->att_idx == SVR_FFF6_TX_CFG) + { + sInstance.HandleTXCharCCCDRead(param); + } + break; + } + case BLE_5_TX_DONE: + { + ChipLogProgress(DeviceLayer, "BLE_5_TX_DONE"); + tx_done_rsp_t* txd_rsp = (tx_done_rsp_t*)param; + if(txd_rsp) { + CHIPoBLEConState * conState = sInstance.GetConnectionState(txd_rsp->conn_idx,false); + if (conState != NULL) + { + sInstance.HandleTXCharConfirm(conState, txd_rsp->status); + } + } + } + break; + case BLE_5_MTU_CHANGE: + { + mtu_change_t *m_ind = (mtu_change_t *)param; + ChipLogProgress(DeviceLayer, "m_ind:conn_idx:%d, mtu_size:%d\r\n", m_ind->conn_idx, m_ind->mtu_size); + CHIPoBLEConState * conState = sInstance.GetConnectionState(m_ind->conn_idx); + if (conState != NULL) + { + conState->mtu = (m_ind->mtu_size >= (1 << 10)) ? ((1 << 10)-1) : m_ind->mtu_size; + } + break; + } + case BLE_5_CONNECT_EVENT: + { + conn_ind_t *c_ind = (conn_ind_t *)param; + ChipLogProgress(DeviceLayer, "BLE GATT connection established (con %u)", c_ind->conn_idx); + ChipLogProgress(DeviceLayer, "c_ind:conn_idx:%d, addr_type:%d, peer_addr:%02x:%02x:%02x:%02x:%02x:%02x\r\n", + c_ind->conn_idx, c_ind->peer_addr_type, c_ind->peer_addr[0], c_ind->peer_addr[1], + c_ind->peer_addr[2], c_ind->peer_addr[3], c_ind->peer_addr[4], c_ind->peer_addr[5]); + sInstance.mFlags.Clear(Flags::kBEKENBLEADVStarted); + CHIPoBLEConState * bleConnState = sInstance.GetConnectionState(c_ind->conn_idx, true); + if (bleConnState == NULL) { + ChipLogError(DeviceLayer, "BLE_5_CONNECT_EVENT failed"); + int ext_evt = DriveBLEExtPerfEvt_DISCONNECT | (c_ind->conn_idx << 8); + PlatformMgr().ScheduleWork(DriveBLEExtPerf, ext_evt); + } + break; + } + case BLE_5_DISCONNECT_EVENT: + { + discon_ind_t *d_ind = (discon_ind_t *)param; + ChipLogProgress(DeviceLayer, "d_ind:conn_idx:%d,reason:%d\r\n", d_ind->conn_idx,d_ind->reason); + sInstance.HandleGAPDisconnect(d_ind->conn_idx,d_ind->reason); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + break; + } + case BLE_5_ATT_INFO_REQ: + { + att_info_req_t *a_ind = (att_info_req_t *)param; + ChipLogProgress(DeviceLayer, "a_ind:conn_idx:%d\r\n", a_ind->conn_idx); + if(SVR_FFF6_RX_VALUE == a_ind->att_idx){ + a_ind->length = 512; + a_ind->status = ERR_SUCCESS; + }else if(SVR_FFF6_TX_CFG == a_ind->att_idx){ + a_ind->length = 2; + a_ind->status = ERR_SUCCESS; + } + break; + } + case BLE_5_CREATE_DB: + { + create_db_t *cd_ind = (create_db_t *)param; + ChipLogProgress(DeviceLayer, "cd_ind:prf_id:%d, status:%d\r\n", cd_ind->prf_id, cd_ind->status); + sInstance.mFlags.Set(Flags::kBekenBLESGATTSReady); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + break; + } + default: + { + ChipLogProgress(DeviceLayer, "Unhandled event:%x",notice); + } + break; + } +} + + +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip +#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/Beken/BLEManagerImpl.h b/src/platform/Beken/BLEManagerImpl.h new file mode 100755 index 00000000000000..c00c51ce69dd86 --- /dev/null +++ b/src/platform/Beken/BLEManagerImpl.h @@ -0,0 +1,234 @@ +/* + * + * Copyright (c) 2020-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 + +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#include "FreeRTOS.h" +#include "event_groups.h" + +#include "ble_api_5_x.h" +#include "rtos_pub.h" +#include "timers.h" + +namespace chip { +namespace DeviceLayer { +namespace Internal { + +using namespace chip::Ble; + +/** + * Concrete implementation of the BLEManager singleton object for the Ameba platforms. + */ +class BLEManagerImpl final : public BLEManager, + private BleLayer, + private BlePlatformDelegate, + private BleApplicationDelegate +{ + // Allow the BLEManager interface class to delegate method calls to + // the implementation methods provided by this class. + friend BLEManager; + +private: + // ===== Members that implement the BLEManager internal interface. + + CHIP_ERROR _Init(void); + CHIP_ERROR _Shutdown() { return CHIP_NO_ERROR; } + CHIPoBLEServiceMode _GetCHIPoBLEServiceMode(void); + CHIP_ERROR _SetCHIPoBLEServiceMode(CHIPoBLEServiceMode val); + bool _IsAdvertisingEnabled(void); + CHIP_ERROR _SetAdvertisingEnabled(bool val); + bool _IsAdvertising(void); + CHIP_ERROR _SetAdvertisingMode(BLEAdvertisingMode mode); + CHIP_ERROR _GetDeviceName(char * buf, size_t bufSize); + CHIP_ERROR _SetDeviceName(const char * deviceName); + uint16_t _NumConnections(void); + void _OnPlatformEvent(const ChipDeviceEvent * event); + BleLayer * _GetBleLayer(void); + + // ===== Members that implement virtual methods on BlePlatformDelegate. + + bool SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, + const Ble::ChipBleUUID * charId) override; + bool UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, + const Ble::ChipBleUUID * charId) override; + bool CloseConnection(BLE_CONNECTION_OBJECT conId) override; + uint16_t GetMTU(BLE_CONNECTION_OBJECT conId) const override; + bool SendIndication(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, + System::PacketBufferHandle pBuf) override; + bool SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, + System::PacketBufferHandle pBuf) override; + bool SendReadRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, + System::PacketBufferHandle pBuf) override; + bool SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const Ble::ChipBleUUID * svcId, + const Ble::ChipBleUUID * charId) override; + + // ===== Members that implement virtual methods on BleApplicationDelegate. + + void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) override; + + // ===== Members for internal use by the following friends. + + friend BLEManager & BLEMgr(void); + friend BLEManagerImpl & BLEMgrImpl(void); + + static BLEManagerImpl sInstance; + + // ===== Private members reserved for use by this class only. + enum class Flags : uint32_t + { + kAdvertisingEnabled = 0x0001, + kAdvertisingRefreshNeeded = 0x0002, + kFastAdvertisingEnabled = 0x0004, + kSlowAdvertisingEnabled = 0x0008, + kAdvertisingIsFastADV = 0x0010, + kAMEBABLEStackInitialized = 0x0020, + kDeviceNameSet = 0x0040, + kDeviceNameDefSet = 0x0080, + + kBekenBLESGATTSReady = 0x00100, + kBEKENBLEADVCreate = 0x00200, + kBEKENBLEADVSetData = 0x00400, + kBEKENBLEADVSetRsp = 0x00800, + kBEKENBLEADVStarted = 0x01000, + kBEKENBLEADVStop = 0x02000, + kBEKENBLEADVDelet = 0x04000, + kBEKENBLEAdvTimer = 0x08000, + kBEKENBLEAdvTimerRun = 0x10000, + }; + + BitFlags mFlags; + + enum + { + kMaxConnections = BLE_LAYER_NUM_BLE_ENDPOINTS, + kMaxDeviceNameLength = 16, + kUnusedIndex = 0xFF, + }; + + struct CHIPoBLEConState + { + uint8_t conn_idx; + uint16_t mtu : 16; + uint16_t allocated : 1; + uint16_t subscribed : 1; + uint16_t unused : 6; + void Set(uint16_t conId) + { + conn_idx = conId; + mtu = 0; + allocated = 1; + subscribed = 0; + unused = 0; + } + void Reset() + { + conn_idx = kUnusedIndex; + mtu = 0; + allocated = 0; + subscribed = 0; + unused = 0; + } + }; + CHIPoBLEConState mBleConnections[kMaxConnections]; + + CHIPoBLEServiceMode mServiceMode; + + uint16_t mNumGAPCons; + uint16_t mTXCharCCCDAttrHandle; + char mDeviceName[kMaxDeviceNameLength + 1]; + CHIP_ERROR MapBLEError(int bleErr); + + void DriveBLEState(void); + CHIP_ERROR StartAdvertising(void); + CHIP_ERROR StopAdvertising(void); + CHIP_ERROR ConfigureAdvertisingData(void); + + void HandleRXCharWrite(uint8_t *, uint16_t, uint8_t); + void HandleTXCharRead(void * param); + void HandleTXCharCCCDRead(void * param); + void HandleTXCharCCCDWrite(int, int, int ind = 0); + void HandleTXCharConfirm(CHIPoBLEConState * conState, int status); + CHIP_ERROR HandleTXComplete(int); + CHIP_ERROR HandleGAPConnect(uint16_t); + CHIP_ERROR HandleGAPDisconnect(uint16_t, uint16_t); + CHIP_ERROR SetSubscribed(uint16_t conId); + bool UnsetSubscribed(uint16_t conId); + bool IsSubscribed(uint16_t conId); + + bool RemoveConnection(uint8_t connectionHandle); + + uint8_t adv_actv_idx; + BLEManagerImpl::CHIPoBLEConState * GetConnectionState(uint8_t connectionHandle, bool allocate = false); + static void ble_event_notice(ble_notice_t notice, void *param); + static void beken_ble_cmd_cb(ble_cmd_t cmd, ble_cmd_param_t *param); + static void DriveBLEState(intptr_t arg); + static void DriveBLEExtPerf(intptr_t arg); + static int beken_ble_init(void); + static void ble_adv_timer_timeout_handle(TimerHandle_t xTimer); + static void CancelBleAdvTimeoutTimer(void); + static void StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs); +}; + +/** + * Returns a reference to the public interface of the BLEManager singleton object. + * + * Internal components should use this to access features of the BLEManager object + * that are common to all platforms. + */ +inline BLEManager & BLEMgr(void) +{ + return BLEManagerImpl::sInstance; +} + +/** + * Returns the platform-specific implementation of the BLEManager singleton object. + * + * Internal components can use this to gain access to features of the BLEManager + * that are specific to the platforms. + */ +inline BLEManagerImpl & BLEMgrImpl(void) +{ + return BLEManagerImpl::sInstance; +} + +inline BleLayer * BLEManagerImpl::_GetBleLayer() +{ + return this; +} + +inline BLEManager::CHIPoBLEServiceMode BLEManagerImpl::_GetCHIPoBLEServiceMode(void) +{ + return mServiceMode; +} + +inline bool BLEManagerImpl::_IsAdvertisingEnabled(void) +{ + return mFlags.Has(Flags::kAdvertisingEnabled); +} + +inline bool BLEManagerImpl::_IsAdvertising(void) +{ + return mFlags.Has(Flags::kBEKENBLEADVStarted); +} + +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip + +#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/Beken/BUILD.gn b/src/platform/Beken/BUILD.gn new file mode 100755 index 00000000000000..0217f5b3ea4211 --- /dev/null +++ b/src/platform/Beken/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") + +import("${chip_root}/src/platform/device.gni") + +assert(chip_device_platform == "beken") + +static_library("Beken") { + sources = [ + "../FreeRTOS/SystemTimeSupport.cpp", + "../SingletonConfigurationManager.cpp", + "BekenConfig.cpp", + "BekenConfig.h", + "BLEManagerImpl.cpp", + "BLEManagerImpl.h", + "CHIPDevicePlatformConfig.h", + "CHIPDevicePlatformEvent.h", + "ConfigurationManagerImpl.cpp", + "ConfigurationManagerImpl.h", + "ConnectivityManagerImpl.cpp", + "ConnectivityManagerImpl.h", + "DeviceNetworkProvisioningDelegateImpl.cpp", + "DeviceNetworkProvisioningDelegateImpl.h", + "DiagnosticDataProviderImpl.cpp", + "DiagnosticDataProviderImpl.h", + "KeyValueStoreManagerImpl.cpp", + "KeyValueStoreManagerImpl.h", + "Logging.cpp", + "LwIPCoreLock.cpp", + "PlatformManagerImpl.cpp", + "PlatformManagerImpl.h", + "ServiceProvisioning.cpp", + "ServiceProvisioning.h", + "SoftwareUpdateManagerImpl.h", + "SystemPlatformConfig.h", + "CHIPMem-Platform.cpp", + ] + + deps = [ "${chip_root}/src/lib/dnssd:platform_header" ] + + public_deps = [ + "${chip_root}/src/crypto", + "${chip_root}/src/platform:platform_base", + ] +} diff --git a/src/platform/Beken/BekenConfig.cpp b/src/platform/Beken/BekenConfig.cpp new file mode 100644 index 00000000000000..a900c77f2ac099 --- /dev/null +++ b/src/platform/Beken/BekenConfig.cpp @@ -0,0 +1,322 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* this file behaves like a config.h, comes first */ +#include + +#include +#include +#include +#include +#include +#include + +#include "error.h" +#include "flash_namespace_value.h" //api for flash interface + +enum +{ + kPrefsTypeBoolean = 1, + kPrefsTypeInteger = 2, + kPrefsTypeString = 3, + kPrefsTypeBuffer = 4, + kPrefsTypeBinary = 5 +}; + +namespace chip { +namespace DeviceLayer { +namespace Internal { + +// *** CAUTION ***: Changing the names or namespaces of these values will *break* existing devices. + +// NVS namespaces used to store device configuration information. +const char BekenConfig::kConfigNamespace_ChipFactory[] = "chip-factory"; +const char BekenConfig::kConfigNamespace_ChipConfig[] = "chip-config"; +const char BekenConfig::kConfigNamespace_ChipCounters[] = "chip-counters"; + +// Keys stored in the chip-factory namespace +const BekenConfig::Key BekenConfig::kConfigKey_SerialNum = { kConfigNamespace_ChipFactory, "serial-num" }; +const BekenConfig::Key BekenConfig::kConfigKey_MfrDeviceId = { kConfigNamespace_ChipFactory, "device-id" }; +const BekenConfig::Key BekenConfig::kConfigKey_MfrDeviceCert = { kConfigNamespace_ChipFactory, "device-cert" }; +const BekenConfig::Key BekenConfig::kConfigKey_MfrDeviceICACerts = { kConfigNamespace_ChipFactory, "device-ca-certs" }; +const BekenConfig::Key BekenConfig::kConfigKey_MfrDevicePrivateKey = { kConfigNamespace_ChipFactory, "device-key" }; +const BekenConfig::Key BekenConfig::kConfigKey_HardwareVersion = { kConfigNamespace_ChipFactory, "hardware-ver" }; +const BekenConfig::Key BekenConfig::kConfigKey_ManufacturingDate = { kConfigNamespace_ChipFactory, "mfg-date" }; +const BekenConfig::Key BekenConfig::kConfigKey_SetupPinCode = { kConfigNamespace_ChipFactory, "pin-code" }; +const BekenConfig::Key BekenConfig::kConfigKey_SetupDiscriminator = { kConfigNamespace_ChipFactory, "discriminator" }; + +// Keys stored in the chip-config namespace +const BekenConfig::Key BekenConfig::kConfigKey_FabricId = { kConfigNamespace_ChipConfig, "fabric-id" }; +const BekenConfig::Key BekenConfig::kConfigKey_ServiceConfig = { kConfigNamespace_ChipConfig, "service-config" }; +const BekenConfig::Key BekenConfig::kConfigKey_PairedAccountId = { kConfigNamespace_ChipConfig, "account-id" }; +const BekenConfig::Key BekenConfig::kConfigKey_ServiceId = { kConfigNamespace_ChipConfig, "service-id" }; +const BekenConfig::Key BekenConfig::kConfigKey_GroupKeyIndex = { kConfigNamespace_ChipConfig, "group-key-index" }; +const BekenConfig::Key BekenConfig::kConfigKey_LastUsedEpochKeyId = { kConfigNamespace_ChipConfig, "last-ek-id" }; +const BekenConfig::Key BekenConfig::kConfigKey_FailSafeArmed = { kConfigNamespace_ChipConfig, "fail-safe-armed" }; +const BekenConfig::Key BekenConfig::kConfigKey_WiFiStationSecType = { kConfigNamespace_ChipConfig, "sta-sec-type" }; +const BekenConfig::Key BekenConfig::kConfigKey_OperationalDeviceId = { kConfigNamespace_ChipConfig, "op-device-id" }; +const BekenConfig::Key BekenConfig::kConfigKey_OperationalDeviceCert = { kConfigNamespace_ChipConfig, "op-device-cert" }; +const BekenConfig::Key BekenConfig::kConfigKey_OperationalDeviceICACerts = { kConfigNamespace_ChipConfig, "op-device-ca-certs" }; +const BekenConfig::Key BekenConfig::kConfigKey_OperationalDevicePrivateKey = { kConfigNamespace_ChipConfig, "op-device-key" }; +const BekenConfig::Key BekenConfig::kConfigKey_RegulatoryLocation = { kConfigNamespace_ChipConfig, "regulatory-location" }; +const BekenConfig::Key BekenConfig::kConfigKey_CountryCode = { kConfigNamespace_ChipConfig, "country-code" }; +const BekenConfig::Key BekenConfig::kConfigKey_ActiveLocale = { kConfigNamespace_ChipConfig, "active-locale" }; +const BekenConfig::Key BekenConfig::kConfigKey_Breadcrumb = { kConfigNamespace_ChipConfig, "breadcrumb" }; +const BekenConfig::Key BekenConfig::kConfigKey_HourFormat = { kConfigNamespace_ChipConfig, "hour-format" }; +const BekenConfig::Key BekenConfig::kConfigKey_CalendarType = { kConfigNamespace_ChipConfig, "calendar-type" }; + +// Keys stored in the Chip-counters namespace +const BekenConfig::Key BekenConfig::kCounterKey_RebootCount = { kConfigNamespace_ChipCounters, "reboot-count" }; +const BekenConfig::Key BekenConfig::kCounterKey_UpTime = { kConfigNamespace_ChipCounters, "up-time" }; +const BekenConfig::Key BekenConfig::kCounterKey_TotalOperationalHours = { kConfigNamespace_ChipCounters, "total-hours" }; +const BekenConfig::Key BekenConfig::kCounterKey_BootReason = { kConfigNamespace_ChipCounters, "boot-reason" }; + +CHIP_ERROR BekenConfig::ReadConfigValue(Key key, bool & val) +{ + uint32_t success = 0; + uint32_t out_length = 0; + uint8_t intval = 0; + success = bk_read_data( key.Namespace, key.Name, (char *)&intval,1,&out_length); + + if (kNoErr !=success) + ChipLogProgress(DeviceLayer, "bk_read_data: %s %s failed\n", (char *)key.Namespace, (char *)key.Name); + + val = (intval != 0); + if (kNoErr == success) + return CHIP_NO_ERROR; + else + return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; + +} + +CHIP_ERROR BekenConfig::ReadConfigValue(Key key, uint32_t & val) +{ + uint32_t success = 0; + uint32_t out_length = 0; + uint32_t temp_data = 0; + + success = bk_read_data( key.Namespace, key.Name,(char *)&temp_data,sizeof(uint32_t),&out_length); + + if (kNoErr !=success) + ChipLogProgress(DeviceLayer, "bk_read_data: %s %s failed\n", (char *)key.Namespace, (char *)key.Name); + val = temp_data; + + if (kNoErr == success) + return CHIP_NO_ERROR; + else + return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; +} + +CHIP_ERROR BekenConfig::ReadConfigValue(Key key, uint64_t & val) +{ + uint32_t success = 0; + uint32_t out_length = 0; + uint64_t temp_data = 0; + + success = bk_read_data( key.Namespace, key.Name,(char *)&temp_data,sizeof(uint64_t),&out_length); + + if (kNoErr !=success) + ChipLogProgress(DeviceLayer, "bk_read_data: %s %s failed\n", (char *)key.Namespace, (char *)key.Name); + val = temp_data; + + if (kNoErr == success) + return CHIP_NO_ERROR; + else + return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; + +} + +CHIP_ERROR BekenConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) +{ + uint32_t success = 0; + uint32_t out_length = 0; + + success = bk_read_data( key.Namespace, key.Name,buf,bufSize,&out_length); + outLen = out_length; + + if (kNoErr !=success) + ChipLogProgress(DeviceLayer, "bk_read_data: %s %s failed\n", (char *)key.Namespace, (char *)key.Name); + + if (kNoErr == success) + { + return CHIP_NO_ERROR; + } + else + { + outLen = 0; + return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; + } +} + +CHIP_ERROR BekenConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) +{ + uint32_t success = 0; + uint32_t out_length = 0; + + success = bk_read_data( key.Namespace, key.Name,(char *)buf,bufSize,&out_length); + outLen = out_length; + + if (kNoErr !=success) + ChipLogProgress(DeviceLayer, "bk_read_data: %s %s failed\n", (char *)key.Namespace, (char *)key.Name); + + if (kNoErr == success) + { + return CHIP_NO_ERROR; + } + else + { + outLen = 0; + return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; + } + +} + +CHIP_ERROR BekenConfig::WriteConfigValue(Key key, bool val) +{ + uint32_t success = 0; + uint8_t value = 0; + + if (val == 1) + { + value = 1; + } + else + { + value = 0; + } + + success = bk_write_data( key.Namespace,key.Name, (char*)&value,1); + if (kNoErr != success) + ChipLogError(DeviceLayer, "bk_write_data: %s %s %s failed\n", (char *)key.Namespace, (char *)key.Name, value ? "true" : "false"); + + return CHIP_NO_ERROR; + +} + +CHIP_ERROR BekenConfig::WriteConfigValue(Key key, uint32_t val) +{ + uint32_t success = 0; + + success = bk_write_data( key.Namespace,key.Name, (char *)&val,sizeof(val)); + if (kNoErr != success) + ChipLogError(DeviceLayer, "bk_write_data: %s %s = %lu(0x%lx) failed\n", (char *)key.Namespace, (char *)key.Name, val, val); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR BekenConfig::WriteConfigValue(Key key, uint64_t val) +{ + uint32_t success = 0; + + success = bk_write_data( key.Namespace,key.Name,(char *)&val,sizeof(val)); + if (kNoErr != success) + ChipLogError(DeviceLayer, "bk_write_data: %s %s = %llu(0x%llx) failed\n", (char *)key.Namespace, (char *)key.Name, val, val); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR BekenConfig::WriteConfigValueStr(Key key, const char * str) +{ + uint32_t success = 0; + + success = bk_write_data( key.Namespace,key.Name, (char *)str,strlen(str)); + if (kNoErr != success) + ChipLogError(DeviceLayer, "bk_write_data: %s %s %s failed\n", (char *)key.Namespace, (char *)key.Name, (char *)str); + + return CHIP_NO_ERROR; + +} + +CHIP_ERROR BekenConfig::WriteConfigValueStr(Key key, const char * str, size_t strLen) +{ + uint32_t success = 0; + strLen = (strLen > strlen(str)) ? strlen(str) : strLen; + + success = bk_write_data( key.Namespace,key.Name, (char *)str,strLen); + if (kNoErr != success) + ChipLogError(DeviceLayer, "bk_write_data: %s %s %s failed\n", (char *)key.Namespace, (char *)key.Name, (char *)str); + + return CHIP_NO_ERROR; + +} + +CHIP_ERROR BekenConfig::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) +{ + uint32_t success = 0; + + success = bk_write_data( key.Namespace,key.Name,(char *)data, dataLen); + if (kNoErr != success) + ChipLogError(DeviceLayer, "bk_write_data: %s %s failed \r\n", key.Namespace, key.Name); + + return CHIP_NO_ERROR; + +} + +CHIP_ERROR BekenConfig::ClearConfigValue(Key key) +{ + uint32_t success = 0; + + success = bk_clean_data(key.Namespace, key.Name); + if (kNoErr != success) + ChipLogProgress(DeviceLayer, "%s : %s %s failed\n", __FUNCTION__, key.Namespace, key.Name); + return CHIP_NO_ERROR; +} + +bool BekenConfig::ConfigValueExists(Key key) +{ + if (kNoErr == bk_ensure_name_data(key.Namespace, key.Name)) + { + return 1; + } + else + { + return 0; + } +} + +CHIP_ERROR BekenConfig::EnsureNamespace(const char * ns) +{ + uint32_t success = 0; + + success = bk_ensure_namespace(ns); + if (kNoErr != success) + { + ChipLogError(DeviceLayer, "dct_register_module failed\n"); + } + return CHIP_NO_ERROR; + +} + +CHIP_ERROR BekenConfig::ClearNamespace(const char * ns) +{ + uint32_t success = 0; + + success = bK_clear_namespace(ns); + if (success != 0) + { + ChipLogError(DeviceLayer, "ClearNamespace failed\n"); + } + return CHIP_NO_ERROR; + +} + +void BekenConfig::RunConfigUnitTest() {} + +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/BekenConfig.h b/src/platform/Beken/BekenConfig.h new file mode 100755 index 00000000000000..342ac69195c174 --- /dev/null +++ b/src/platform/Beken/BekenConfig.h @@ -0,0 +1,115 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include +namespace chip { +namespace DeviceLayer { +namespace Internal { + +class BekenConfig +{ +public: + struct Key; + + // Maximum length of an NVS key name. + static constexpr size_t kMaxConfigKeyNameLength = 15; + + // NVS namespaces used to store device configuration information. + static const char kConfigNamespace_ChipFactory[]; + static const char kConfigNamespace_ChipConfig[]; + static const char kConfigNamespace_ChipCounters[]; + + // Key definitions for well-known keys. + static const Key kConfigKey_SerialNum; + static const Key kConfigKey_MfrDeviceId; + static const Key kConfigKey_MfrDeviceCert; + static const Key kConfigKey_MfrDeviceICACerts; + static const Key kConfigKey_MfrDevicePrivateKey; + static const Key kConfigKey_HardwareVersion; + static const Key kConfigKey_ManufacturingDate; + static const Key kConfigKey_SetupPinCode; + static const Key kConfigKey_FabricId; + static const Key kConfigKey_ServiceConfig; + static const Key kConfigKey_PairedAccountId; + static const Key kConfigKey_ServiceId; + static const Key kConfigKey_FabricSecret; + static const Key kConfigKey_GroupKeyIndex; + static const Key kConfigKey_LastUsedEpochKeyId; + static const Key kConfigKey_FailSafeArmed; + static const Key kConfigKey_WiFiStationSecType; + static const Key kConfigKey_OperationalDeviceId; + static const Key kConfigKey_OperationalDeviceCert; + static const Key kConfigKey_OperationalDeviceICACerts; + static const Key kConfigKey_OperationalDevicePrivateKey; + static const Key kConfigKey_SetupDiscriminator; + static const Key kConfigKey_RegulatoryLocation; + static const Key kConfigKey_CountryCode; + static const Key kConfigKey_ActiveLocale; + static const Key kConfigKey_Breadcrumb; + static const Key kConfigKey_HourFormat; + static const Key kConfigKey_CalendarType; + + // Counter keys + static const Key kCounterKey_RebootCount; + static const Key kCounterKey_UpTime; + static const Key kCounterKey_TotalOperationalHours; + static const Key kCounterKey_BootReason; + + static const char kGroupKeyNamePrefix[]; + + // Config value accessors. + static CHIP_ERROR ReadConfigValue(Key key, bool & val); + static CHIP_ERROR ReadConfigValue(Key key, uint32_t & val); + static CHIP_ERROR ReadConfigValue(Key key, uint64_t & val); + static CHIP_ERROR ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen); + static CHIP_ERROR ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen); + static CHIP_ERROR WriteConfigValue(Key key, bool val); + static CHIP_ERROR WriteConfigValue(Key key, uint32_t val); + static CHIP_ERROR WriteConfigValue(Key key, uint64_t val); + static CHIP_ERROR WriteConfigValueStr(Key key, const char * str); + static CHIP_ERROR WriteConfigValueStr(Key key, const char * str, size_t strLen); + static CHIP_ERROR WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen); + static CHIP_ERROR ClearConfigValue(Key key); + static bool ConfigValueExists(Key key); + + static CHIP_ERROR EnsureNamespace(const char * ns); + static CHIP_ERROR ClearNamespace(const char * ns); + + static void RunConfigUnitTest(void); +}; + +struct BekenConfig::Key +{ + const char * Namespace; + const char * Name; + + bool operator==(const Key & other) const; +}; + +inline bool BekenConfig::Key::operator==(const Key & other) const +{ + return strcmp(Namespace, other.Namespace) == 0 && strcmp(Name, other.Name) == 0; +} + +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/BlePlatformConfig.h b/src/platform/Beken/BlePlatformConfig.h new file mode 100644 index 00000000000000..30446cbca23c74 --- /dev/null +++ b/src/platform/Beken/BlePlatformConfig.h @@ -0,0 +1,39 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Platform-specific configuration overrides for the CHIP BLE + * Layer on Beken platform. + * + */ + +#pragma once + +// ==================== Platform Adaptations ==================== + +#define BLE_CONNECTION_OBJECT uint16_t +#define BLE_CONNECTION_UNINITIALIZED (0xFFFF) +#define BLE_MAX_RECEIVE_WINDOW_SIZE 5 + +#define BLE_CONFIG_ERROR_MIN 6000000 +#define BLE_CONFIG_ERROR_MAX 6000999 + +// ========== Platform-specific Configuration Overrides ========= + +/* none so far */ diff --git a/src/platform/Beken/CHIPDevicePlatformConfig.h b/src/platform/Beken/CHIPDevicePlatformConfig.h new file mode 100755 index 00000000000000..cc0996df75f511 --- /dev/null +++ b/src/platform/Beken/CHIPDevicePlatformConfig.h @@ -0,0 +1,73 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Platform-specific configuration overrides for the chip Device Layer + * on Beken platform. + */ + +#pragma once + +// ==================== Platform Adaptations ==================== +#define CHIP_CONFIG_ERROR_CLASS 1 + +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 0 +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 + +#if CHIP_ENABLE_OPENTHREAD +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD 1 +#endif + +#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 + +#define CHIP_DEVICE_CONFIG_ENABLE_CHIP_TIME_SERVICE_TIME_SYNC 0 + +// ========== Platform-specific Configuration ========= + +// These are configuration options that are unique to the platform. +// These can be overridden by the application as needed. + +// ... + +// ========== Platform-specific Configuration Overrides ========= + +#ifndef CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE +#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE 8192 +#endif // CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE + +#ifndef CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE +#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE 4096 +#endif // CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE + +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_TELEMETRY 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY_FULL 0 +#define CHIP_DEVICE_CONFIG_LOG_PROVISIONING_HASH 0 + +#define CHIP_DEVICE_LAYER_NONE 0 + +// 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 + +#define CONFIG_RENDEZVOUS_MODE 6 +#define CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY 2 + +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 +#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DISCOVERY 1 diff --git a/src/platform/Beken/CHIPDevicePlatformEvent.h b/src/platform/Beken/CHIPDevicePlatformEvent.h new file mode 100644 index 00000000000000..a996c7b01000c7 --- /dev/null +++ b/src/platform/Beken/CHIPDevicePlatformEvent.h @@ -0,0 +1,84 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Defines platform-specific event types and data for the chip + * Device Layer on Beken platforms. + */ + +#pragma once + +#include + +namespace chip { +namespace DeviceLayer { +namespace DeviceEventType { + +/** + * Enumerates platform-specific event types that are visible to the application. + */ +enum PublicPlatformSpecificEventTypes +{ + /* None currently defined */ +}; + +/** + * Enumerates platform-specific event types that are internal to the chip Device Layer. + */ +enum InternalPlatformSpecificEventTypes +{ + kQorvoBLEConnected = kRange_InternalPlatformSpecific, + kQorvoBLEDisconnected, + kCHIPoBLECCCWriteEvent, + kCHIPoBLERXCharWriteEvent, + kCHIPoBLETXCharWriteEvent, + kRtkWiFiStationConnectedEvent, +}; + +} // namespace DeviceEventType + +/** + * Represents platform-specific event information. + */ +struct ChipDevicePlatformEvent final +{ + // TODO - add platform specific definition extension + union + { + struct + { + uint8_t dummy; + } QorvoBLEConnected; + struct + { + uint8_t dummy; + } CHIPoBLECCCWriteEvent; + struct + { + uint8_t dummy; + } CHIPoBLERXCharWriteEvent; + struct + { + uint8_t dummy; + } CHIPoBLETXCharWriteEvent; + }; +}; + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/CHIPMem-Platform.cpp b/src/platform/Beken/CHIPMem-Platform.cpp new file mode 100644 index 00000000000000..1ef99a7abcbe0d --- /dev/null +++ b/src/platform/Beken/CHIPMem-Platform.cpp @@ -0,0 +1,143 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Nest Labs, Inc. + * + * 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. + */ + +/* + * + * Copyright (c) 2020-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 + * This file implements heap memory allocation APIs for CHIP. These functions are platform + * specific and might be C Standard Library heap functions re-direction in most of cases. + * + */ + +//#include +#include +#include "projdefs.h" +#include "portable.h" +#include + + +#include +#include +#include +#include + +#if CHIP_CONFIG_MEMORY_MGMT_PLATFORM + +namespace chip { +namespace Platform { + +#define VERIFY_INITIALIZED() VerifyInitialized(__func__) + +static std::atomic_int memoryInitialized{ 0 }; + +static void VerifyInitialized(const char * func) +{ +#if 0 + if (!memoryInitialized) + { + fprintf(stderr, "ABORT: chip::Platform::%s() called before chip::Platform::MemoryInit()\n", func); + abort(); + } +#endif +} + +CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize) +{ +#ifndef NDEBUG + if (memoryInitialized++ > 0) + { + fprintf(stderr, "ABORT: chip::Platform::MemoryInit() called twice.\n"); + abort(); + } +#endif + return CHIP_NO_ERROR; +} + +void MemoryAllocatorShutdown() +{ +#ifndef NDEBUG + if (--memoryInitialized < 0) + { + fprintf(stderr, "ABORT: chip::Platform::MemoryShutdown() called twice.\n"); + abort(); + } +#endif +} + +void * MemoryAlloc(size_t size) +{ + void * ptr; + VERIFY_INITIALIZED(); + ptr = pvPortMalloc(size); + return ptr; +} + +void * MemoryAlloc(size_t size, bool isLongTermAlloc) +{ + void * ptr; + VERIFY_INITIALIZED(); + ptr = pvPortMalloc(size); + return ptr; +} + +void * MemoryCalloc(size_t num, size_t size) +{ + VERIFY_INITIALIZED(); + void * ptr = pvPortCalloc(num, size); + return ptr; +} + +void * MemoryRealloc(void * p, size_t size) +{ + VERIFY_INITIALIZED(); + p = pvPortRealloc(p, size); + return p; +} + +void MemoryFree(void * p) +{ + VERIFY_INITIALIZED(); + vPortFree(p); +} + +bool MemoryInternalCheckPointer(const void * p, size_t min_size) +{ + return (p != nullptr); +} + +} // namespace Platform +} // namespace chip + +#endif // CHIP_CONFIG_MEMORY_MGMT_PLATFORM diff --git a/src/platform/Beken/CHIPPlatformConfig.h b/src/platform/Beken/CHIPPlatformConfig.h new file mode 100644 index 00000000000000..0778cb7ccc2b93 --- /dev/null +++ b/src/platform/Beken/CHIPPlatformConfig.h @@ -0,0 +1,114 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Platform-specific configuration overrides for CHIP on + * Beken platforms. + */ + +#pragma once + +// ==================== General Platform Adaptations ==================== + +#define CHIP_CONFIG_ERROR_TYPE uint32_t +#define CHIP_CONFIG_ERROR_FORMAT PRId32 +#define CHIP_CONFIG_NO_ERROR 0 +#define CHIP_CONFIG_ERROR_MIN 4000000 +#define CHIP_CONFIG_ERROR_MAX 4000999 + +#define ASN1_CONFIG_ERROR_TYPE uint32_t +#define ASN1_CONFIG_NO_ERROR 0 +#define ASN1_CONFIG_ERROR_MIN 5000000 +#define ASN1_CONFIG_ERROR_MAX 5000999 + +#define CHIP_CONFIG_TIME_ENABLE_CLIENT 1 +#define CHIP_CONFIG_TIME_ENABLE_SERVER 0 + +#define ChipDie() abort() + +// ==================== Security Adaptations ==================== + +#define CHIP_CONFIG_USE_OPENSSL_ECC 0 +#define CHIP_CONFIG_USE_MICRO_ECC 0 + +#define CHIP_CONFIG_HASH_IMPLEMENTATION_OPENSSL 0 +#define CHIP_CONFIG_HASH_IMPLEMENTATION_MINCRYPT 1 + +#define CHIP_CONFIG_AES_IMPLEMENTATION_OPENSSL 0 +#define CHIP_CONFIG_AES_IMPLEMENTATION_AESNI 0 +#define CHIP_CONFIG_AES_IMPLEMENTATION_MBEDTLS 0 +#define CHIP_CONFIG_AES_IMPLEMENTATION_PLATFORM 1 + +#define CHIP_CONFIG_RNG_IMPLEMENTATION_OPENSSL 0 +#define CHIP_CONFIG_RNG_IMPLEMENTATION_CHIPDRBG 1 +#define CHIP_CONFIG_RNG_IMPLEMENTATION_PLATFORM 0 + +#define CHIP_CONFIG_ENABLE_PASE_INITIATOR 0 +#define CHIP_CONFIG_ENABLE_PASE_RESPONDER 1 +#define CHIP_CONFIG_ENABLE_CASE_INITIATOR 1 + +#define CHIP_CONFIG_SUPPORT_PASE_CONFIG0 0 +#define CHIP_CONFIG_SUPPORT_PASE_CONFIG1 0 +#define CHIP_CONFIG_SUPPORT_PASE_CONFIG2 0 +#define CHIP_CONFIG_SUPPORT_PASE_CONFIG3 0 +#define CHIP_CONFIG_SUPPORT_PASE_CONFIG4 1 + +#define CHIP_CONFIG_ENABLE_KEY_EXPORT_INITIATOR 0 + +#define CHIP_CONFIG_ENABLE_PROVISIONING_BUNDLE_SUPPORT 0 + +// ==================== General Configuration Overrides ==================== + +#ifndef CHIP_CONFIG_MAX_PEER_NODES +#define CHIP_CONFIG_MAX_PEER_NODES 16 +#endif // CHIP_CONFIG_MAX_PEER_NODES + +#ifndef CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS +#define CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS 16 +#endif // CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS + +#ifndef CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS +#define CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS 8 +#endif // CHIP_CONFIG_MAX_EXCHANGE_CONTEXTS + +#ifndef CHIP_CONFIG_WRMP_TIMER_DEFAULT_PERIOD +#define CHIP_CONFIG_WRMP_TIMER_DEFAULT_PERIOD 50 +#endif // CHIP_CONFIG_WRMP_TIMER_DEFAULT_PERIOD + +#ifndef CHIP_LOG_FILTERING +#define CHIP_LOG_FILTERING 0 +#endif // CHIP_LOG_FILTERING + +#ifndef CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS +#define CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS 1 +#endif // CHIP_CONFIG_BDX_MAX_NUM_TRANSFERS + +// ==================== Security Configuration Overrides ==================== + +#ifndef CHIP_CONFIG_MAX_APPLICATION_GROUPS +#define CHIP_CONFIG_MAX_APPLICATION_GROUPS 4 +#endif // CHIP_CONFIG_MAX_APPLICATION_GROUPS + +#ifndef CHIP_CONFIG_DEBUG_CERT_VALIDATION +#define CHIP_CONFIG_DEBUG_CERT_VALIDATION 0 +#endif // CHIP_CONFIG_DEBUG_CERT_VALIDATION + +#ifndef CHIP_CONFIG_ENABLE_CASE_RESPONDER +#define CHIP_CONFIG_ENABLE_CASE_RESPONDER 1 +#endif // CHIP_CONFIG_ENABLE_CASE_RESPONDER diff --git a/src/platform/Beken/ConfigurationManagerImpl.cpp b/src/platform/Beken/ConfigurationManagerImpl.cpp new file mode 100644 index 00000000000000..6126bc795fdf67 --- /dev/null +++ b/src/platform/Beken/ConfigurationManagerImpl.cpp @@ -0,0 +1,249 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Provides the implementation of the Device Layer ConfigurationManager object + * for the Beken. + */ +/* this file behaves like a config.h, comes first */ +#include + +#include +#include +#include +#include +#include +#include + +#include "wlan_ui_pub.h" + +namespace chip { +namespace DeviceLayer { + +using namespace chip::DeviceLayer::Internal; + +ConfigurationManagerImpl & ConfigurationManagerImpl::GetDefaultInstance() +{ + static ConfigurationManagerImpl sInstance; + return sInstance; +} + +CHIP_ERROR ConfigurationManagerImpl::Init() +{ + CHIP_ERROR err; + uint32_t rebootCount; + bool failSafeArmed; + + ChipLogProgress(DeviceLayer, "ConfigurationManagerImpl::Init"); + // Force initialization of NVS namespaces if they doesn't already exist. + err = BekenConfig::EnsureNamespace(BekenConfig::kConfigNamespace_ChipFactory); + SuccessOrExit(err); + err = BekenConfig::EnsureNamespace(BekenConfig::kConfigNamespace_ChipConfig); + SuccessOrExit(err); + err = BekenConfig::EnsureNamespace(BekenConfig::kConfigNamespace_ChipCounters); + SuccessOrExit(err); + + if (BekenConfig::ConfigValueExists(BekenConfig::kCounterKey_RebootCount)) + { + err = GetRebootCount(rebootCount); + SuccessOrExit(err); + + err = StoreRebootCount(rebootCount + 1); + SuccessOrExit(err); + } + else + { + // The first boot after factory reset of the Node. + err = StoreRebootCount(1); + SuccessOrExit(err); + } + + if (!BekenConfig::ConfigValueExists(BekenConfig::kCounterKey_TotalOperationalHours)) + { + err = StoreTotalOperationalHours(0); + SuccessOrExit(err); + } + + if (!BekenConfig::ConfigValueExists(BekenConfig::kCounterKey_BootReason)) + { + err = StoreBootReason(DiagnosticDataProvider::BootReasonType::Unspecified); + SuccessOrExit(err); + } + + // Initialize the generic implementation base class. + err = Internal::GenericConfigurationManagerImpl::Init(); + SuccessOrExit(err); + + // If the fail-safe was armed when the device last shutdown, initiate a factory reset. + if (GetFailSafeArmed(failSafeArmed) == CHIP_NO_ERROR && failSafeArmed) + { + ChipLogProgress(DeviceLayer, "Detected fail-safe armed on reboot; initiating factory reset"); + InitiateFactoryReset(); + } + err = CHIP_NO_ERROR; + +exit: + return err; +} + +CHIP_ERROR ConfigurationManagerImpl::GetRebootCount(uint32_t & rebootCount) +{ + return ReadConfigValue(BekenConfig::kCounterKey_RebootCount, rebootCount); +} + +CHIP_ERROR ConfigurationManagerImpl::StoreRebootCount(uint32_t rebootCount) +{ + return WriteConfigValue(BekenConfig::kCounterKey_RebootCount, rebootCount); +} + +CHIP_ERROR ConfigurationManagerImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) +{ + return ReadConfigValue(BekenConfig::kCounterKey_TotalOperationalHours, totalOperationalHours); +} + +CHIP_ERROR ConfigurationManagerImpl::StoreTotalOperationalHours(uint32_t totalOperationalHours) +{ + return WriteConfigValue(BekenConfig::kCounterKey_TotalOperationalHours, totalOperationalHours); +} + +CHIP_ERROR ConfigurationManagerImpl::GetBootReason(uint32_t & bootReason) +{ + return ReadConfigValue(BekenConfig::kCounterKey_BootReason, bootReason); +} + +CHIP_ERROR ConfigurationManagerImpl::StoreBootReason(uint32_t bootReason) +{ + return WriteConfigValue(BekenConfig::kCounterKey_BootReason, bootReason); +} + +CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * buf) +{ + bk_wifi_get_station_mac_address((char*)buf); + return CHIP_NO_ERROR; +} + +bool ConfigurationManagerImpl::CanFactoryReset() +{ + // TODO: query the application to determine if factory reset is allowed. + return true; +} + +void ConfigurationManagerImpl::InitiateFactoryReset() +{ + PlatformMgr().ScheduleWork(DoFactoryReset); +} + +CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) +{ + BekenConfig::Key configKey{ BekenConfig::kConfigNamespace_ChipCounters, key }; + + CHIP_ERROR err = ReadConfigValue(configKey, value); + if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) + { + err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; + } + return err; +} + +CHIP_ERROR ConfigurationManagerImpl::WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) +{ + BekenConfig::Key configKey{ BekenConfig::kConfigNamespace_ChipCounters, key }; + return WriteConfigValue(configKey, value); +} + +CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, bool & val) +{ + return BekenConfig::ReadConfigValue(key, val); +} + +CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint32_t & val) +{ + return BekenConfig::ReadConfigValue(key, val); +} + +CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint64_t & val) +{ + return BekenConfig::ReadConfigValue(key, val); +} + +CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) +{ + return BekenConfig::ReadConfigValueStr(key, buf, bufSize, outLen); +} + +CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) +{ + return BekenConfig::ReadConfigValueBin(key, buf, bufSize, outLen); +} + +CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, bool val) +{ + return BekenConfig::WriteConfigValue(key, val); +} + +CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint32_t val) +{ + return BekenConfig::WriteConfigValue(key, val); +} + +CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint64_t val) +{ + return BekenConfig::WriteConfigValue(key, val); +} + +CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str) +{ + return BekenConfig::WriteConfigValueStr(key, str); +} + +CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str, size_t strLen) +{ + return BekenConfig::WriteConfigValueStr(key, str, strLen); +} + +CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) +{ + return BekenConfig::WriteConfigValueBin(key, data, dataLen); +} + +void ConfigurationManagerImpl::RunConfigUnitTest(void) +{ + BekenConfig::RunConfigUnitTest(); +} + +void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) +{ + CHIP_ERROR err; + + ChipLogProgress(DeviceLayer, "Performing factory reset"); + + // Erase all values in the chip-config NVS namespace. + err = BekenConfig::ClearNamespace(BekenConfig::kConfigNamespace_ChipConfig); + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "ClearNamespace(ChipConfig) failed: %s", chip::ErrorStr(err)); + } + + // Restart the system. + ChipLogProgress(DeviceLayer, "System restarting"); + bk_reboot(); +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/ConfigurationManagerImpl.h b/src/platform/Beken/ConfigurationManagerImpl.h new file mode 100644 index 00000000000000..2513975179e010 --- /dev/null +++ b/src/platform/Beken/ConfigurationManagerImpl.h @@ -0,0 +1,79 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Provides an implementation of the ConfigurationManager object + * for the Beken platform. + */ +#pragma once + +#include +#include +#include + +namespace chip { +namespace DeviceLayer { +/** + * Concrete implementation of the ConfigurationManager singleton object for the Beken platform. + */ +class ConfigurationManagerImpl: public Internal::GenericConfigurationManagerImpl +{ +public: + // This returns an instance of this class. + static ConfigurationManagerImpl & GetDefaultInstance(); + +private: + // ===== Members that implement the ConfigurationManager public interface. + + CHIP_ERROR Init(void) ; + CHIP_ERROR GetPrimaryWiFiMACAddress(uint8_t * buf) ; + bool CanFactoryReset(void) ; + void InitiateFactoryReset(void) ; + CHIP_ERROR ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) ; + CHIP_ERROR WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) ; + CHIP_ERROR GetRebootCount(uint32_t & rebootCount) ; + CHIP_ERROR StoreRebootCount(uint32_t rebootCount) ; + CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours) ; + CHIP_ERROR StoreTotalOperationalHours(uint32_t totalOperationalHours) ; + CHIP_ERROR GetBootReason(uint32_t & bootReason) ; + CHIP_ERROR StoreBootReason(uint32_t bootReason) ; + + // NOTE: Other public interface methods are implemented by GenericConfigurationManagerImpl<>. + + // ===== Members that implement the GenericConfigurationManagerImpl protected interface. + CHIP_ERROR ReadConfigValue(Key key, bool & val) ; + CHIP_ERROR ReadConfigValue(Key key, uint32_t & val) ; + CHIP_ERROR ReadConfigValue(Key key, uint64_t & val) ; + CHIP_ERROR ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) ; + CHIP_ERROR ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) ; + CHIP_ERROR WriteConfigValue(Key key, bool val) ; + CHIP_ERROR WriteConfigValue(Key key, uint32_t val) ; + CHIP_ERROR WriteConfigValue(Key key, uint64_t val) ; + CHIP_ERROR WriteConfigValueStr(Key key, const char * str) ; + CHIP_ERROR WriteConfigValueStr(Key key, const char * str, size_t strLen) ; + CHIP_ERROR WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) ; + void RunConfigUnitTest(void) ; + + // ===== Private members reserved for use by this class only. + + static void DoFactoryReset(intptr_t arg); +}; + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/ConnectivityManagerImpl.cpp b/src/platform/Beken/ConnectivityManagerImpl.cpp new file mode 100644 index 00000000000000..0ec2466280259e --- /dev/null +++ b/src/platform/Beken/ConnectivityManagerImpl.cpp @@ -0,0 +1,670 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* this file behaves like a config.h, comes first */ +#include + +#include + +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#include +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +#include +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include +#endif + +#include +#include +#include + +#include +#include +#include +#include + +#include "wlan_ui_pub.h" + +using namespace ::chip; +using namespace ::chip::Inet; +using namespace ::chip::TLV; +using namespace ::chip::DeviceLayer::Internal; + +namespace chip { +namespace DeviceLayer { + +ConnectivityManagerImpl ConnectivityManagerImpl::sInstance; + +// ==================== ConnectivityManager Platform Internal Methods ==================== + +CHIP_ERROR ConnectivityManagerImpl::_Init() +{ +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + mLastStationConnectFailTime = System::Clock::kZero; + mLastAPDemandTime = System::Clock::kZero; + mWiFiStationMode = kWiFiStationMode_Disabled; + mWiFiStationState = kWiFiStationState_NotConnected; + mWiFiAPMode = kWiFiAPMode_Disabled; + mWiFiAPState = kWiFiAPState_NotActive; + mWiFiStationReconnectInterval = System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_WIFI_STATION_RECONNECT_INTERVAL); + mWiFiAPIdleTimeout = System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_WIFI_AP_IDLE_TIMEOUT); + mFlags.SetRaw(0); + + // Ensure that station mode is enabled. + //wifi_on(RTW_MODE_STA); + + // Ensure that station mode is enabled in the WiFi layer. + //wifi_set_mode(RTW_MODE_STA); + ; + + // If there is no persistent station provision... + if (!IsWiFiStationProvisioned()) + { + // If the code has been compiled with a default WiFi station provision, configure that now. +#if !defined(CONFIG_DEFAULT_WIFI_SSID) + printf("%s %d pls define CONFIG_DEFAULT_WIFI_SSID\r\n", __func__, __LINE__); +#else + if (CONFIG_DEFAULT_WIFI_SSID[0] != 0) + { + ChipLogProgress(DeviceLayer, "Setting default WiFi station configuration (SSID: %s)", CONFIG_DEFAULT_WIFI_SSID); + + // Set a default station configuration. + rtw_wifi_setting_t wifiConfig; + + // Set the wifi configuration + memset(&wifiConfig, 0, sizeof(wifiConfig)); + memcpy(wifiConfig.ssid, CONFIG_DEFAULT_WIFI_SSID, strlen(CONFIG_DEFAULT_WIFI_SSID) + 1); + memcpy(wifiConfig.password, CONFIG_DEFAULT_WIFI_PASSWORD, strlen(CONFIG_DEFAULT_WIFI_PASSWORD) + 1); + wifiConfig.mode = RTW_MODE_STA; + + // Configure the WiFi interface. + int err = CHIP_SetWiFiConfig(&wifiConfig); + if (err != 0) + { + ChipLogError(DeviceLayer, "_Init _SetWiFiConfig() failed: %d", err); + } + + // Enable WiFi station mode. + ReturnErrorOnFailure(SetWiFiStationMode(kWiFiStationMode_Enabled)); + } + + // Otherwise, ensure WiFi station mode is disabled. + else + { + ReturnErrorOnFailure(SetWiFiStationMode(kWiFiStationMode_Disabled)); + } +#endif + } + + // Force AP mode off for now. + + // Queue work items to bootstrap the AP and station state machines once the Chip event loop is running. + ReturnErrorOnFailure(DeviceLayer::SystemLayer().ScheduleWork(DriveStationState, NULL)); + ReturnErrorOnFailure(DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL)); + +#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI + + return CHIP_NO_ERROR; +} + +void ConnectivityManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) +{ + // Forward the event to the generic base classes as needed. +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD + GenericConnectivityManagerImpl_Thread::_OnPlatformEvent(event); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + if (event->Type == DeviceEventType::kRtkWiFiStationConnectedEvent) + { + ChipLogProgress(DeviceLayer, "WIFI_EVENT_STA_CONNECTED"); + if (mWiFiStationState == kWiFiStationState_Connecting) + { + ChangeWiFiStationState(kWiFiStationState_Connecting_Succeeded); + } + DriveStationState(); + } +#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI +} + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +ConnectivityManager::WiFiStationMode ConnectivityManagerImpl::_GetWiFiStationMode(void) +{ +#if 0 + if (mWiFiStationMode != kWiFiStationMode_ApplicationControlled) + { + mWiFiStationMode = (wifi_mode == RTW_MODE_STA) ? kWiFiStationMode_Enabled : kWiFiStationMode_Disabled; + } +#endif + //TODO should enabled + return kWiFiStationMode_Enabled; +} + +bool ConnectivityManagerImpl::_IsWiFiStationEnabled(void) +{ + return GetWiFiStationMode() == kWiFiStationMode_Enabled; +} + +CHIP_ERROR ConnectivityManagerImpl::_SetWiFiStationMode(WiFiStationMode val) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + VerifyOrExit(val != kWiFiStationMode_NotSupported, err = CHIP_ERROR_INVALID_ARGUMENT); + + if(mWiFiStationMode == kWiFiStationMode_Disabled && val == kWiFiStationMode_Enabled) + { + bk_wlan_status_register_cb(ConnectivityManagerImpl().wlan_status_cb); + ChangeWiFiStationState(kWiFiStationState_Connecting); + } + + if (val != kWiFiStationMode_ApplicationControlled) + { + DeviceLayer::SystemLayer().ScheduleWork(DriveStationState, NULL); + } + + if (mWiFiStationMode != val) + { + ChipLogProgress(DeviceLayer, "WiFi station mode change: %s -> %s", WiFiStationModeToStr(mWiFiStationMode), + WiFiStationModeToStr(val)); + } + + mWiFiStationMode = val; + +exit: + return err; +} + +bool ConnectivityManagerImpl::_IsWiFiStationProvisioned(void) +{ + wlan_sta_config_t config; + + memset(&config, 0, sizeof(config)); + config.field = WLAN_STA_FIELD_SSID; + if(0 != wlan_sta_get_config(&config)) + { + ChipLogError(DeviceLayer, "wlan_sta_get_config failed!"); + return false; + } + return (config.u.ssid.ssid[0] != 0) ? true : false; +} + +void ConnectivityManagerImpl::_ClearWiFiStationProvision(void) +{ + // TBD +} + +CHIP_ERROR ConnectivityManagerImpl::_SetWiFiAPMode(WiFiAPMode val) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + VerifyOrExit(val != kWiFiAPMode_NotSupported, err = CHIP_ERROR_INVALID_ARGUMENT); + + if (mWiFiAPMode != val) + { + ChipLogProgress(DeviceLayer, "WiFi AP mode change: %s -> %s", WiFiAPModeToStr(mWiFiAPMode), WiFiAPModeToStr(val)); + } + + mWiFiAPMode = val; + + DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL); + +exit: + return err; +} + +void ConnectivityManagerImpl::_DemandStartWiFiAP(void) +{ + if (mWiFiAPMode == kWiFiAPMode_OnDemand || mWiFiAPMode == kWiFiAPMode_OnDemand_NoStationProvision) + { + mLastAPDemandTime = System::SystemClock().GetMonotonicTimestamp(); + DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL); + } +} + +void ConnectivityManagerImpl::_StopOnDemandWiFiAP(void) +{ + if (mWiFiAPMode == kWiFiAPMode_OnDemand || mWiFiAPMode == kWiFiAPMode_OnDemand_NoStationProvision) + { + mLastAPDemandTime = System::Clock::kZero; + DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL); + } +} + +void ConnectivityManagerImpl::_MaintainOnDemandWiFiAP(void) +{ + if (mWiFiAPMode == kWiFiAPMode_OnDemand || mWiFiAPMode == kWiFiAPMode_OnDemand_NoStationProvision) + { + if (mWiFiAPState == kWiFiAPState_Activating || mWiFiAPState == kWiFiAPState_Active) + { + mLastAPDemandTime = System::SystemClock().GetMonotonicTimestamp(); + } + } +} + +void ConnectivityManagerImpl::_SetWiFiAPIdleTimeout(System::Clock::Timeout val) +{ + mWiFiAPIdleTimeout = val; + DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL); +} + +CHIP_ERROR ConnectivityManagerImpl::_GetAndLogWifiStatsCounters(void) +{ + return CHIP_NO_ERROR; +} + +void ConnectivityManagerImpl::_OnWiFiScanDone() +{ + // Schedule a call to DriveStationState method in case a station connect attempt was + // deferred because the scan was in progress. + DeviceLayer::SystemLayer().ScheduleWork(DriveStationState, NULL); +} + +void ConnectivityManagerImpl::_OnWiFiStationProvisionChange() +{ + // Schedule a call to the DriveStationState method to adjust the station state as needed. + DeviceLayer::SystemLayer().ScheduleWork(DriveStationState, NULL); +} + +// ==================== ConnectivityManager Private Methods ==================== +void ConnectivityManagerImpl::WiFiStationConnectedHandler() +{ + ChipDeviceEvent event; + memset(&event, 0, sizeof(event)); + event.Type = DeviceEventType::kRtkWiFiStationConnectedEvent; + PlatformMgr().PostEventOrDie(&event); +} + +static bool stationConnected = false; +void ConnectivityManagerImpl::wlan_status_cb(void *ctxt) +{ + int notice_event = *(unsigned int*)ctxt; + + switch(notice_event){ + case RW_EVT_STA_GOT_IP: + stationConnected = true; + WiFiStationConnectedHandler(); + ChipLogProgress(DeviceLayer, "RW_EVT_STA_GOT_IP"); + break; + case RW_EVT_STA_CONNECTED: + ChipLogProgress(DeviceLayer, "RW_EVT_STA_CONNECTED"); + break; + case RW_EVT_STA_DISCONNECTED: + stationConnected = false; + ChipLogProgress(DeviceLayer, "RW_EVT_STA_DISCONNECTED"); + break; + default: + ChipLogProgress(DeviceLayer, "unSupported wifi status:%d", notice_event); + break; + } +} + +void ConnectivityManagerImpl::DriveStationState() +{ + int ret; + + GetWiFiStationMode(); + + // If the station interface is NOT under application control... + if (mWiFiStationMode != kWiFiStationMode_ApplicationControlled) + { + // Ensure that the WiFi layer is started. + //wifi_on(RTW_MODE_STA); + + // Ensure that station mode is enabled in the WiFi layer. + //wifi_set_mode(RTW_MODE_STA); + ; + } +#if 0 + wlan_sta_states_t state; + ret = wlan_sta_state(&state); + if(ret != 0) + { + ChipLogError(DeviceLayer, "Get wlan sta state faield!"); + return; + } + + // Determine if the WiFi layer thinks the station interface is currently connected. + stationConnected = (state == WLAN_STA_STATE_CONNECTED) ? true : false; +#endif + ChipLogProgress(DeviceLayer, "wifi station state:%d, mWiFiStationState:%d", stationConnected, mWiFiStationState); + // If the station interface is currently connected ... + if (stationConnected) + { + // Advance the station state to Connected if it was previously NotConnected or + // a previously initiated connect attempt succeeded. + if (mWiFiStationState == kWiFiStationState_NotConnected || mWiFiStationState == kWiFiStationState_Connecting_Succeeded) + { + ChangeWiFiStationState(kWiFiStationState_Connected); + ChipLogProgress(DeviceLayer, "WiFi station interface connected"); + mLastStationConnectFailTime = System::Clock::kZero; + OnStationConnected(); + IpConnectedEventNotify(); + } + + // If the WiFi station interface is no longer enabled, or no longer provisioned, + // disconnect the station from the AP, unless the WiFi station mode is currently + // under application control. + if (mWiFiStationMode != kWiFiStationMode_ApplicationControlled && + (mWiFiStationMode != kWiFiStationMode_Enabled || !IsWiFiStationProvisioned())) + { + ChipLogProgress(DeviceLayer, "Disconnecting WiFi station interface"); + if(0 != wlan_sta_disconnect()) + { + ChipLogError(DeviceLayer, "wifi_disconnect() failed!"); + return; + } + + ChangeWiFiStationState(kWiFiStationState_Disconnecting); + } + } + + // Otherwise the station interface is NOT connected to an AP, so... + else + { + System::Clock::Timestamp now = System::SystemClock().GetMonotonicTimestamp(); + + // Advance the station state to NotConnected if it was previously Connected or Disconnecting, + // or if a previous initiated connect attempt failed. + if (mWiFiStationState == kWiFiStationState_Connected || mWiFiStationState == kWiFiStationState_Disconnecting || + mWiFiStationState == kWiFiStationState_Connecting_Failed) + { + WiFiStationState prevState = mWiFiStationState; + ChangeWiFiStationState(kWiFiStationState_NotConnected); + if (prevState != kWiFiStationState_Connecting_Failed) + { + ChipLogProgress(DeviceLayer, "WiFi station interface disconnected"); + mLastStationConnectFailTime = System::Clock::kZero; + OnStationDisconnected(); + } + else + { + mLastStationConnectFailTime = now; + } + } + // If the WiFi station interface is now enabled and provisioned (and by implication, + // not presently under application control), AND the system is not in the process of + // scanning, then... + ChipLogProgress(DeviceLayer, "mWiFiStationMode:%d, IsWiFiStationProvisioned:%d", mWiFiStationMode, IsWiFiStationProvisioned()); + if (mWiFiStationMode == kWiFiStationMode_Enabled && IsWiFiStationProvisioned() && + mWiFiStationState != kWiFiStationState_Connecting) + { + // Initiate a connection to the AP if we haven't done so before, or if enough + // time has passed since the last attempt. + if (mLastStationConnectFailTime == System::Clock::kZero || + now >= mLastStationConnectFailTime + mWiFiStationReconnectInterval) + { + ChipLogProgress(DeviceLayer, "Attempting to connect WiFi station interface"); + bk_wlan_status_register_cb(ConnectivityManagerImpl().wlan_status_cb); + if(0 != wlan_sta_connect(0))//assume not support fast connect + { + ChipLogError(DeviceLayer, "wlan_sta_connect() failed!"); + return; + } + ChangeWiFiStationState(kWiFiStationState_Connecting); + } + + // Otherwise arrange another connection attempt at a suitable point in the future. + else + { + System::Clock::Timeout timeToNextConnect = (mLastStationConnectFailTime + mWiFiStationReconnectInterval) - now; + + ChipLogProgress(DeviceLayer, "Next WiFi station reconnect in %" PRIu32 " ms", + System::Clock::Milliseconds32(timeToNextConnect).count()); + + ReturnOnFailure(DeviceLayer::SystemLayer().StartTimer(timeToNextConnect, DriveStationState, nullptr)); + } + } + } + ChipLogProgress(DeviceLayer, "Done driving station state, nothing else to do..."); + // Kick-off any pending network scan that might have been deferred due to the activity + // of the WiFi station. +} + +void ConnectivityManagerImpl::OnStationConnected() +{ + // Alert other components of the new state. + ChipDeviceEvent event; + event.Type = DeviceEventType::kWiFiConnectivityChange; + event.WiFiConnectivityChange.Result = kConnectivity_Established; + PlatformMgr().PostEventOrDie(&event); + + UpdateInternetConnectivityState(); +} + +void ConnectivityManagerImpl::OnStationDisconnected() +{ + // Alert other components of the new state. + ChipDeviceEvent event; + event.Type = DeviceEventType::kWiFiConnectivityChange; + event.WiFiConnectivityChange.Result = kConnectivity_Lost; + PlatformMgr().PostEventOrDie(&event); + + UpdateInternetConnectivityState(); +} + +void ConnectivityManagerImpl::ChangeWiFiStationState(WiFiStationState newState) +{ + if (mWiFiStationState != newState) + { + ChipLogProgress(DeviceLayer, "WiFi station state change: %s -> %s", WiFiStationStateToStr(mWiFiStationState), + WiFiStationStateToStr(newState)); + mWiFiStationState = newState; + } +} + +void ConnectivityManagerImpl::DriveStationState(::chip::System::Layer * aLayer, void * aAppState) +{ + sInstance.DriveStationState(); +} + +void ConnectivityManagerImpl::DriveAPState() +{ + ChipLogProgress(DeviceLayer, "WiFi ConnectivityManagerImpl::DriveAPState, do nothing!"); + CHIP_ERROR err = CHIP_NO_ERROR; +} + +CHIP_ERROR ConnectivityManagerImpl::ConfigureWiFiAP() +{ + return CHIP_NO_ERROR; +} + +void ConnectivityManagerImpl::ChangeWiFiAPState(WiFiAPState newState) +{ + if (mWiFiAPState != newState) + { + ChipLogProgress(DeviceLayer, "WiFi AP state change: %s -> %s", WiFiAPStateToStr(mWiFiAPState), WiFiAPStateToStr(newState)); + mWiFiAPState = newState; + } +} + +void ConnectivityManagerImpl::DriveAPState(::chip::System::Layer * aLayer, void * aAppState) +{ + sInstance.DriveAPState(); +} + +void ConnectivityManagerImpl::UpdateInternetConnectivityState(void) +{ + bool haveIPv4Conn = false; + bool haveIPv6Conn = false; + const bool hadIPv4Conn = mFlags.Has(ConnectivityFlags::kHaveIPv4InternetConnectivity); + const bool hadIPv6Conn = mFlags.Has(ConnectivityFlags::kHaveIPv6InternetConnectivity); + IPAddress addr; + + // If the WiFi station is currently in the connected state... + if (mWiFiStationState == kWiFiStationState_Connected) + { + // Get the LwIP netif for the WiFi station interface. + struct netif * netif = netif_list; + + // If the WiFi station interface is up... + if (netif != NULL && netif_is_up(netif) && netif_is_link_up(netif)) + { + // Check if a DNS server is currently configured. If so... + ip_addr_t dnsServerAddr = *dns_getserver(0); + if (!ip_addr_isany_val(dnsServerAddr)) + { + // If the station interface has been assigned an IPv4 address, and has + // an IPv4 gateway, then presume that the device has IPv4 Internet + // connectivity. + if (!ip4_addr_isany_val(*netif_ip4_addr(netif)) && !ip4_addr_isany_val(*netif_ip4_gw(netif))) + { + haveIPv4Conn = true; + //char addrStr[INET_ADDRSTRLEN]; + //ip4addr_ntoa_r((const ip4_addr_t *) LwIP_GetIP(&xnetif[0]), addrStr, sizeof(addrStr)); + //IPAddress::FromString(addrStr, addr); + } + + // Search among the IPv6 addresses assigned to the interface for a Global Unicast + // address (2000::/3) that is in the valid state. If such an address is found... + for (uint8_t i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) + { + if (ip6_addr_isglobal(netif_ip6_addr(netif, i)) && ip6_addr_isvalid(netif_ip6_addr_state(netif, i))) + { + // Determine if there is a default IPv6 router that is currently reachable + // via the station interface. If so, presume for now that the device has + // IPv6 connectivity. + struct netif * found_if = nd6_find_route(IP6_ADDR_ANY6); + if (found_if && netif->num == found_if->num) + { + haveIPv6Conn = true; + } + } + } + } + } + } + + // If the internet connectivity state has changed... + if (haveIPv4Conn != hadIPv4Conn || haveIPv6Conn != hadIPv6Conn) + { + // Update the current state. + mFlags.Set(ConnectivityFlags::kHaveIPv4InternetConnectivity, haveIPv4Conn) + .Set(ConnectivityFlags::kHaveIPv6InternetConnectivity, haveIPv6Conn); + + // Alert other components of the state change. + ChipDeviceEvent event; + event.Type = DeviceEventType::kInternetConnectivityChange; + event.InternetConnectivityChange.IPv4 = GetConnectivityChange(hadIPv4Conn, haveIPv4Conn); + event.InternetConnectivityChange.IPv6 = GetConnectivityChange(hadIPv6Conn, haveIPv6Conn); + //addr.ToString(event.InternetConnectivityChange.address); + PlatformMgr().PostEventOrDie(&event); + + if (haveIPv4Conn != hadIPv4Conn) + { + ChipLogProgress(DeviceLayer, "%s Internet connectivity %s", "IPv4", (haveIPv4Conn) ? "ESTABLISHED" : "LOST"); + } + + if (haveIPv6Conn != hadIPv6Conn) + { + ChipLogProgress(DeviceLayer, "%s Internet connectivity %s", "IPv6", (haveIPv6Conn) ? "ESTABLISHED" : "LOST"); + } + } +} + +void ConnectivityManagerImpl::OnStationIPv4AddressAvailable(void) +{ +#if 0 + uint8_t * ip = LwIP_GetIP(&xnetif[0]); + uint8_t * gw = LwIP_GetGW(&xnetif[0]); + uint8_t * msk = LwIP_GetMASK(&xnetif[0]); +#if CHIP_PROGRESS_LOGGING + { + ChipLogProgress(DeviceLayer, "\n\r\tIP => %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); + ChipLogProgress(DeviceLayer, "\n\r\tGW => %d.%d.%d.%d\n\r", gw[0], gw[1], gw[2], gw[3]); + ChipLogProgress(DeviceLayer, "\n\r\tmsk => %d.%d.%d.%d\n\r", msk[0], msk[1], msk[2], msk[3]); + } +#endif // CHIP_PROGRESS_LOGGING +#endif + + UpdateInternetConnectivityState(); + ChipLogProgress(DeviceLayer, "IPv4 address available on WiFi station interface"); + ChipDeviceEvent event; + event.Type = DeviceEventType::kInterfaceIpAddressChanged; + event.InterfaceIpAddressChanged.Type = InterfaceIpChangeType::kIpV4_Assigned; + PlatformMgr().PostEventOrDie(&event); +} + +void ConnectivityManagerImpl::OnStationIPv4AddressLost(void) +{ + ChipLogProgress(DeviceLayer, "IPv4 address lost on WiFi station interface"); + + UpdateInternetConnectivityState(); + + ChipDeviceEvent event; + event.Type = DeviceEventType::kInterfaceIpAddressChanged; + event.InterfaceIpAddressChanged.Type = InterfaceIpChangeType::kIpV4_Lost; + PlatformMgr().PostEventOrDie(&event); +} + +void ConnectivityManagerImpl::OnIPv6AddressAvailable(void) +{ +#if 0 +#if LWIP_VERSION_MAJOR >= 2 && LWIP_VERSION_MINOR >= 1 +#if LWIP_IPV6 + uint8_t * ipv6_0 = LwIP_GetIPv6_linklocal(&xnetif[0]); + uint8_t * ipv6_1 = LwIP_GetIPv6_global(&xnetif[0]); +#endif +#endif +#if CHIP_PROGRESS_LOGGING + { +#if LWIP_VERSION_MAJOR >= 2 && LWIP_VERSION_MINOR >= 1 +#if LWIP_IPV6 + ChipLogProgress(DeviceLayer, + "\n\r\tLink-local IPV6 => %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", + ipv6_0[0], ipv6_0[1], ipv6_0[2], ipv6_0[3], ipv6_0[4], ipv6_0[5], ipv6_0[6], ipv6_0[7], ipv6_0[8], + ipv6_0[9], ipv6_0[10], ipv6_0[11], ipv6_0[12], ipv6_0[13], ipv6_0[14], ipv6_0[15]); + ChipLogProgress(DeviceLayer, + "\n\r\tIPV6 => %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", + ipv6_1[0], ipv6_1[1], ipv6_1[2], ipv6_1[3], ipv6_1[4], ipv6_1[5], ipv6_1[6], ipv6_1[7], ipv6_1[8], + ipv6_1[9], ipv6_1[10], ipv6_1[11], ipv6_1[12], ipv6_1[13], ipv6_1[14], ipv6_1[15]); +#endif +#endif + } +#endif // CHIP_PROGRESS_LOGGING +#endif + + UpdateInternetConnectivityState(); + ChipLogProgress(DeviceLayer, "IPv6 address available on WiFi station interface"); + ChipDeviceEvent event; + event.Type = DeviceEventType::kInterfaceIpAddressChanged; + event.InterfaceIpAddressChanged.Type = InterfaceIpChangeType::kIpV6_Assigned; + PlatformMgr().PostEventOrDie(&event); +} + +void ConnectivityManagerImpl::IpConnectedEventNotify() +{ + const bool hadIPv4Conn = mFlags.Has(ConnectivityFlags::kHaveIPv4InternetConnectivity); + const bool hadIPv6Conn = mFlags.Has(ConnectivityFlags::kHaveIPv6InternetConnectivity); + + if(hadIPv4Conn) + { + sInstance.OnStationIPv4AddressAvailable(); + } + if(hadIPv6Conn) + { + sInstance.OnIPv6AddressAvailable(); + } +} + +#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/ConnectivityManagerImpl.h b/src/platform/Beken/ConnectivityManagerImpl.h new file mode 100644 index 00000000000000..e611b8aaded326 --- /dev/null +++ b/src/platform/Beken/ConnectivityManagerImpl.h @@ -0,0 +1,213 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include +#include + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include +#else +#include +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +#include +#else +#include +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#include +#else +#include +#endif + +#include + +//#include + +namespace chip { + +namespace Inet { +class IPAddress; +} // namespace Inet + +namespace DeviceLayer { + +class PlatformManagerImpl; + +class ConnectivityManagerImpl final : public ConnectivityManager, + public Internal::GenericConnectivityManagerImpl, +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + public Internal::GenericConnectivityManagerImpl_WiFi, +#else + public Internal::GenericConnectivityManagerImpl_NoWiFi, +#endif +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + public Internal::GenericConnectivityManagerImpl_BLE, +#else + public Internal::GenericConnectivityManagerImpl_NoBLE, +#endif +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD + public Internal::GenericConnectivityManagerImpl_Thread +#else + public Internal::GenericConnectivityManagerImpl_NoThread +#endif +{ + // Allow the ConnectivityManager interface class to delegate method calls to + // the implementation methods provided by this class. + friend class ConnectivityManager; +private: + CHIP_ERROR _Init(void); + void _OnPlatformEvent(const ChipDeviceEvent * event); + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + using Flags = GenericConnectivityManagerImpl_WiFi::ConnectivityFlags; + // ===== Members that implement the ConnectivityManager abstract interface. + + WiFiStationMode _GetWiFiStationMode(void); + CHIP_ERROR _SetWiFiStationMode(WiFiStationMode val); + bool _IsWiFiStationEnabled(void); + bool _IsWiFiStationApplicationControlled(void); + bool _IsWiFiStationConnected(void); + System::Clock::Timeout _GetWiFiStationReconnectInterval(void); + CHIP_ERROR _SetWiFiStationReconnectInterval(System::Clock::Timeout val); + bool _IsWiFiStationProvisioned(void); + void _ClearWiFiStationProvision(void); + WiFiAPMode _GetWiFiAPMode(void); + CHIP_ERROR _SetWiFiAPMode(WiFiAPMode val); + bool _IsWiFiAPActive(void); + bool _IsWiFiAPApplicationControlled(void); + void _DemandStartWiFiAP(void); + void _StopOnDemandWiFiAP(void); + void _MaintainOnDemandWiFiAP(void); + System::Clock::Timeout _GetWiFiAPIdleTimeout(void); + void _SetWiFiAPIdleTimeout(System::Clock::Timeout val); + CHIP_ERROR _GetAndLogWifiStatsCounters(void); + bool _CanStartWiFiScan(); + void _OnWiFiScanDone(); + void _OnWiFiStationProvisionChange(); + + // ===== Private members reserved for use by this class only. + + System::Clock::Timestamp mLastStationConnectFailTime; + System::Clock::Timestamp mLastAPDemandTime; + WiFiStationMode mWiFiStationMode; + WiFiStationState mWiFiStationState; + WiFiAPMode mWiFiAPMode; + WiFiAPState mWiFiAPState; + System::Clock::Timeout mWiFiStationReconnectInterval; + System::Clock::Timeout mWiFiAPIdleTimeout; + BitFlags mFlags; + + void DriveStationState(void); + void OnStationConnected(void); + void OnStationDisconnected(void); + void ChangeWiFiStationState(WiFiStationState newState); + static void DriveStationState(::chip::System::Layer * aLayer, void * aAppState); + + void DriveAPState(void); + CHIP_ERROR ConfigureWiFiAP(void); + void ChangeWiFiAPState(WiFiAPState newState); + static void DriveAPState(::chip::System::Layer * aLayer, void * aAppState); + + void UpdateInternetConnectivityState(void); + void OnStationIPv4AddressAvailable(void); + void OnStationIPv4AddressLost(void); + void OnIPv6AddressAvailable(void); + +#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI + + // ===== Members for internal use by the following friends. + + friend ConnectivityManager & ConnectivityMgr(void); + friend ConnectivityManagerImpl & ConnectivityMgrImpl(void); + + static ConnectivityManagerImpl sInstance; + static void WiFiStationConnectedHandler(); + static void wlan_status_cb(void *ctxt); + void IpConnectedEventNotify(void); +}; + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +inline bool ConnectivityManagerImpl::_IsWiFiStationApplicationControlled(void) +{ + return mWiFiStationMode == kWiFiStationMode_ApplicationControlled; +} + +inline bool ConnectivityManagerImpl::_IsWiFiStationConnected(void) +{ + return mWiFiStationState == kWiFiStationState_Connected; +} + +inline bool ConnectivityManagerImpl::_IsWiFiAPApplicationControlled(void) +{ + return mWiFiAPMode == kWiFiAPMode_ApplicationControlled; +} + +inline System::Clock::Timeout ConnectivityManagerImpl::_GetWiFiStationReconnectInterval(void) +{ + return mWiFiStationReconnectInterval; +} + +inline ConnectivityManager::WiFiAPMode ConnectivityManagerImpl::_GetWiFiAPMode(void) +{ + return mWiFiAPMode; +} + +inline bool ConnectivityManagerImpl::_IsWiFiAPActive(void) +{ + return mWiFiAPState == kWiFiAPState_Active; +} + +inline System::Clock::Timeout ConnectivityManagerImpl::_GetWiFiAPIdleTimeout(void) +{ + return mWiFiAPIdleTimeout; +} + +inline bool ConnectivityManagerImpl::_CanStartWiFiScan() +{ + return mWiFiStationState != kWiFiStationState_Connecting; +} +#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI + +/** + * Returns the public interface of the ConnectivityManager singleton object. + * + * Chip applications should use this to access features of the ConnectivityManager object + * that are common to all platforms. + */ +inline ConnectivityManager & ConnectivityMgr(void) +{ + return ConnectivityManagerImpl::sInstance; +} + +/** + * Returns the platform-specific implementation of the ConnectivityManager singleton object. + * + * Chip applications can use this to gain access to features of the ConnectivityManager + * that are specific to the Beken platform. + */ +inline ConnectivityManagerImpl & ConnectivityMgrImpl(void) +{ + return ConnectivityManagerImpl::sInstance; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp b/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp new file mode 100644 index 00000000000000..19d63924a2eaa2 --- /dev/null +++ b/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp @@ -0,0 +1,43 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "DeviceNetworkProvisioningDelegateImpl.h" +#include "ServiceProvisioning.h" + +namespace chip { +namespace DeviceLayer { + +CHIP_ERROR DeviceNetworkProvisioningDelegateImpl::_ProvisionWiFiNetwork(const char * ssid, const char * key) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + ChipLogProgress(NetworkProvisioning, "BekenNetworkProvisioningDelegate: SSID: %s", ssid); + err = SetWiFiStationProvisioning(ssid, key); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NetworkProvisioning, "Failed to connect to WiFi network: %s", chip::ErrorStr(err)); + } + + return err; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.h b/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.h new file mode 100644 index 00000000000000..2492fba40c367a --- /dev/null +++ b/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.h @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +namespace chip { +namespace DeviceLayer { + +namespace Internal { + +template +class GenericDeviceNetworkProvisioningDelegateImpl; + +} // namespace Internal + +class DeviceNetworkProvisioningDelegateImpl final + : public Internal::GenericDeviceNetworkProvisioningDelegateImpl +{ +private: + friend class GenericDeviceNetworkProvisioningDelegateImpl; + + CHIP_ERROR _ProvisionWiFiNetwork(const char * ssid, const char * passwd); + CHIP_ERROR _ProvisionThreadNetwork(ByteSpan threadData) { return CHIP_ERROR_NOT_IMPLEMENTED; } +}; + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.cpp b/src/platform/Beken/DiagnosticDataProviderImpl.cpp new file mode 100644 index 00000000000000..15a0036bbf4c9a --- /dev/null +++ b/src/platform/Beken/DiagnosticDataProviderImpl.cpp @@ -0,0 +1,350 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Provides an implementation of the DiagnosticDataProvider object + * for Beken platform. + */ + +#include + +#include +#include +#include + +namespace chip { +namespace DeviceLayer { + +DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() +{ + static DiagnosticDataProviderImpl sInstance; + return sInstance; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) +{ + currentHeapFree = xPortGetFreeHeapSize(); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) +{ + //currentHeapUsed = xPortGetTotalHeapSize() - xPortGetFreeHeapSize(); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) +{ + // currentHeapHighWatermark = xPortGetTotalHeapSize() - xPortGetMinimumEverFreeHeapSize(); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetRebootCount(uint16_t & rebootCount) +{ + uint32_t count = 0; + + CHIP_ERROR err = ConfigurationMgr().GetRebootCount(count); + + if (err == CHIP_NO_ERROR) + { + VerifyOrReturnError(count <= UINT16_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); + rebootCount = static_cast(count); + } + + return err; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetUpTime(uint64_t & upTime) +{ + System::Clock::Timestamp currentTime = System::SystemClock().GetMonotonicTimestamp(); + System::Clock::Timestamp startTime = PlatformMgrImpl().GetStartTime(); + + if (currentTime >= startTime) + { + upTime = std::chrono::duration_cast(currentTime - startTime).count(); + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_INVALID_TIME; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) +{ + uint64_t upTime = 0; + + if (GetUpTime(upTime) == CHIP_NO_ERROR) + { + uint32_t totalHours = 0; + if (ConfigurationMgr().GetTotalOperationalHours(totalHours) == CHIP_NO_ERROR) + { + VerifyOrReturnError(upTime / 3600 <= UINT32_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); + totalOperationalHours = totalHours + static_cast(upTime / 3600); + return CHIP_NO_ERROR; + } + } + + return CHIP_ERROR_INVALID_TIME; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(uint8_t & bootReason) +{ + uint32_t reason = 0; + + CHIP_ERROR err = ConfigurationMgr().GetBootReason(reason); + + if (err == CHIP_NO_ERROR) + { + VerifyOrReturnError(reason <= UINT8_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); + bootReason = static_cast(reason); + } + + return err; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** netifpp) +{ +#if 0 + CHIP_ERROR err = CHIP_ERROR_READ_FAILED; + NetworkInterface * head = NULL; + struct ifaddrs * ifaddr = nullptr; + + if (xnetif == NULL) + { + ChipLogError(DeviceLayer, "Failed to get network interfaces"); + } + else + { + for (struct netif * ifa = xnetif; ifa != NULL; ifa = ifa->next) + { + NetworkInterface * ifp = new NetworkInterface(); + + strncpy(ifp->Name, ifa->name, Inet::InterfaceId::kMaxIfNameLength); + ifp->Name[Inet::InterfaceId::kMaxIfNameLength - 1] = '\0'; + + ifp->name = CharSpan(ifp->Name, strlen(ifp->Name)); + ifp->fabricConnected = true; + if ((ifa->flags) & NETIF_FLAG_ETHERNET) + ifp->type = EMBER_ZCL_INTERFACE_TYPE_ETHERNET; + else + ifp->type = EMBER_ZCL_INTERFACE_TYPE_WI_FI; + ifp->offPremiseServicesReachableIPv4 = false; + ifp->offPremiseServicesReachableIPv6 = false; + + memcpy(ifp->MacAddress, ifa->hwaddr, sizeof(ifa->hwaddr)); + + if (0) + { + ChipLogError(DeviceLayer, "Failed to get network hardware address"); + } + else + { + // Set 48-bit IEEE MAC Address + ifp->hardwareAddress = ByteSpan(ifp->MacAddress, 6); + } + + ifp->Next = head; + head = ifp; + } + } + + *netifpp = head; +#endif + return CHIP_NO_ERROR; +} + +void DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * netifp) +{ + while (netifp) + { + NetworkInterface * del = netifp; + netifp = netifp->Next; + delete del; + } +} + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(ByteSpan & BssId) +{ +#if 0 + CHIP_ERROR err = CHIP_ERROR_READ_FAILED; + static uint8_t ameba_bssid[6]; + + if (wifi_get_ap_bssid(ameba_bssid) == 0) + { + err = CHIP_NO_ERROR; + ChipLogProgress(DeviceLayer, "%02x,%02x,%02x,%02x,%02x,%02x\n", ameba_bssid[0], ameba_bssid[1], ameba_bssid[2], + ameba_bssid[3], ameba_bssid[4], ameba_bssid[5]); + } + + BssId = ameba_bssid; +#endif + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion) +{ + // Support 802.11a/n Wi-Fi in AmebaD chipset + wifiVersion = EMBER_ZCL_WI_FI_VERSION_TYPE_802__11N; + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(uint8_t & securityType) +{ +#if 0 + unsigned int _auth_type; + unsigned short _security = 0; + rtw_wifi_setting_t setting; + +#ifdef CONFIG_PLATFORM_8721D + if (wext_get_enc_ext("wlan0", &_security, &setting.key_idx, setting.password) < 0) + { + securityType = 0; + } + else + { + switch (_security) + { + case IW_ENCODE_ALG_NONE: + setting.security_type = EMBER_ZCL_SECURITY_TYPE_NONE; + break; + case IW_ENCODE_ALG_WEP: + setting.security_type = EMBER_ZCL_SECURITY_TYPE_WEP; + break; + case IW_ENCODE_ALG_TKIP: + setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA; + break; + case IW_ENCODE_ALG_CCMP: + setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA2; + break; + default: + setting.security_type = EMBER_ZCL_SECURITY_TYPE_UNSPECIFIED; + break; + } + securityType = setting.security_type; + } +#else + wext_get_enc_ext("wlan0", &_security, &setting.key_idx, setting.password); + if (wext_get_auth_type("wlan0", &_auth_type) < 0) + { + securityType = 0; + } + else + { + switch (_security) + { + case IW_ENCODE_ALG_NONE: + setting.security_type = EMBER_ZCL_SECURITY_TYPE_NONE; + break; + case IW_ENCODE_ALG_WEP: + setting.security_type = EMBER_ZCL_SECURITY_TYPE_WEP; + break; + case IW_ENCODE_ALG_TKIP: + if (_auth_type == WPA_SECURITY) + setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA; + else if (_auth_type == WPA2_SECURITY) + setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA2; + break; + case IW_ENCODE_ALG_CCMP: + if (_auth_type == WPA_SECURITY) + setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA; + else if (_auth_type == WPA2_SECURITY) + setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA2; + else if (_auth_type == WPA3_SECURITY) + setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA3; + break; + default: + setting.security_type = EMBER_ZCL_SECURITY_TYPE_UNSPECIFIED; + break; + } + securityType = setting.security_type; + } +#endif +#endif + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) +{ +#if 0 + unsigned char channel; + + if (wext_get_channel("wlan0", &channel) < 0) + channelNumber = 0; + else + channelNumber = (uint16_t) channel; +#endif + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi) +{ +#if 0 + int _rssi = 0; + if (wifi_get_rssi(&_rssi) < 0) + rssi = 0; + else + rssi = _rssi; +#endif + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconLostCount(uint32_t & beaconLostCount) +{ + beaconLostCount = 0; + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiCurrentMaxRate(uint64_t & currentMaxRate) +{ + currentMaxRate = 0; + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastRxCount(uint32_t & packetMulticastRxCount) +{ + packetMulticastRxCount = 0; + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastTxCount(uint32_t & packetMulticastTxCount) +{ + packetMulticastTxCount = 0; + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastRxCount(uint32_t & packetUnicastRxCount) +{ + packetUnicastRxCount = 0; + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastTxCount(uint32_t & packetUnicastTxCount) +{ + packetUnicastTxCount = 0; + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiOverrunCount(uint64_t & overrunCount) +{ + overrunCount = 0; + return CHIP_NO_ERROR; +} +#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.h b/src/platform/Beken/DiagnosticDataProviderImpl.h new file mode 100644 index 00000000000000..9190c1a3bdc9e8 --- /dev/null +++ b/src/platform/Beken/DiagnosticDataProviderImpl.h @@ -0,0 +1,69 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Provides an implementation of the DiagnosticDataProvider object. + */ + +#pragma once + +#include + +namespace chip { +namespace DeviceLayer { + +/** + * Concrete implementation of the PlatformManager singleton object for Linux platforms. + */ +class DiagnosticDataProviderImpl : public DiagnosticDataProvider +{ +public: + static DiagnosticDataProviderImpl & GetDefaultInstance(); + + // ===== Methods that implement the PlatformManager abstract interface. + + CHIP_ERROR GetCurrentHeapFree(uint64_t & currentHeapFree) override; + CHIP_ERROR GetCurrentHeapUsed(uint64_t & currentHeapUsed) override; + CHIP_ERROR GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) override; + + CHIP_ERROR GetRebootCount(uint16_t & rebootCount) override; + CHIP_ERROR GetUpTime(uint64_t & upTime) override; + CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours) override; + CHIP_ERROR GetBootReason(uint8_t & bootReason) override; + + CHIP_ERROR GetNetworkInterfaces(NetworkInterface ** netifpp) override; + void ReleaseNetworkInterfaces(NetworkInterface * netifp) override; + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + CHIP_ERROR GetWiFiBssId(ByteSpan & BssId) override; + CHIP_ERROR GetWiFiSecurityType(uint8_t & securityType) override; + CHIP_ERROR GetWiFiVersion(uint8_t & wifiVersion) override; + CHIP_ERROR GetWiFiChannelNumber(uint16_t & channelNumber) override; + CHIP_ERROR GetWiFiRssi(int8_t & rssi) override; + CHIP_ERROR GetWiFiBeaconLostCount(uint32_t & beaconLostCount) override; + CHIP_ERROR GetWiFiPacketMulticastRxCount(uint32_t & packetMulticastRxCount) override; + CHIP_ERROR GetWiFiPacketMulticastTxCount(uint32_t & packetMulticastTxCount) override; + CHIP_ERROR GetWiFiPacketUnicastRxCount(uint32_t & packetUnicastRxCount) override; + CHIP_ERROR GetWiFiPacketUnicastTxCount(uint32_t & packetUnicastTxCount) override; + CHIP_ERROR GetWiFiCurrentMaxRate(uint64_t & currentMaxRate) override; + CHIP_ERROR GetWiFiOverrunCount(uint64_t & overrunCount) override; +#endif +}; + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/InetPlatformConfig.h b/src/platform/Beken/InetPlatformConfig.h new file mode 100755 index 00000000000000..ef21415a816950 --- /dev/null +++ b/src/platform/Beken/InetPlatformConfig.h @@ -0,0 +1,47 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Platform-specific configuration overrides for the CHIP Inet + * Layer on the Beken platform. + * + */ + +#pragma once + +// ==================== Platform Adaptations ==================== + +#define INET_CONFIG_ERROR_TYPE int32_t +#define INET_CONFIG_NO_ERROR 0 +#define INET_CONFIG_ERROR_MIN 1000000 +#define INET_CONFIG_ERROR_MAX 1000999 + +// ==================== General Configuration Overrides ==================== + +// NOTE: Values that are mapped to CONFIG_ #defines are settable via the Kconfig mechanism. + +#ifndef INET_CONFIG_NUM_TCP_ENDPOINTS +#define INET_CONFIG_NUM_TCP_ENDPOINTS 10 +#endif // INET_CONFIG_NUM_TCP_ENDPOINTS + +#ifndef INET_CONFIG_NUM_UDP_ENDPOINTS +#define INET_CONFIG_NUM_UDP_ENDPOINTS 10 +#endif // INET_CONFIG_NUM_UDP_ENDPOINTS + +#define INET_CONFIG_ENABLE_IPV4 1 diff --git a/src/platform/Beken/KeyValueStoreManagerImpl.cpp b/src/platform/Beken/KeyValueStoreManagerImpl.cpp new file mode 100755 index 00000000000000..3eb2401d44df54 --- /dev/null +++ b/src/platform/Beken/KeyValueStoreManagerImpl.cpp @@ -0,0 +1,115 @@ +/* + * + * 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 + * Platform-specific key value storage implementation for Beken + */ +/* this file behaves like a config.h, comes first */ +#include +#include +#include "error.h" +#include "flash_namespace_value.h" + +namespace chip { +namespace DeviceLayer { +namespace PersistedStorage { + +KeyValueStoreManagerImpl KeyValueStoreManagerImpl::sInstance; + +CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t value_size, size_t * read_bytes_size, + size_t offset_bytes) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + int32_t ret = -1; + + if ((!value) || (!read_bytes_size)) + { + return (err = CHIP_ERROR_INVALID_ARGUMENT); + } + + if (offset_bytes > 0) + { + // Offset and partial reads are not supported in nvs, for now just return NOT_IMPLEMENTED. Support can be added in the + // future if this is needed. + return (err = CHIP_ERROR_NOT_IMPLEMENTED); + } + + ret = bk_read_data( key,key,(char *) value,value_size,(uint32_t *)read_bytes_size); + + if (ret == kNoErr) + { + err = CHIP_NO_ERROR; + if (read_bytes_size) + { + *read_bytes_size = value_size; + } + } + else + { + err = CHIP_ERROR_INTERNAL; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, size_t value_size) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + uint32_t ret = 0; + + if (!value) + { + return (err = CHIP_ERROR_INVALID_ARGUMENT); + } + + ret = bk_write_data( key,key, (char *)value,value_size); + if (ret == kNoErr) + { + err = CHIP_NO_ERROR; + } + else + { + err = CHIP_ERROR_INTERNAL; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) +{ + uint32_t ret = 0; + CHIP_ERROR err = CHIP_NO_ERROR; + + ret = bk_clean_data ( key,key); + + if (kNoErr == ret) + { + err = CHIP_NO_ERROR; + } + else + { + err = CHIP_ERROR_INTERNAL; + } + + return err; +} + +} // namespace PersistedStorage +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/KeyValueStoreManagerImpl.h b/src/platform/Beken/KeyValueStoreManagerImpl.h new file mode 100755 index 00000000000000..e86c244d71a369 --- /dev/null +++ b/src/platform/Beken/KeyValueStoreManagerImpl.h @@ -0,0 +1,77 @@ +/* + * + * 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 + * Platform-specific key value storage implementation for Beken + */ +/* this file behaves like a config.h, comes first */ + +#pragma once + +namespace chip { +namespace DeviceLayer { +namespace PersistedStorage { + +class KeyValueStoreManagerImpl final : public KeyValueStoreManager +{ + // Allow the KeyValueStoreManager interface class to delegate method calls to + // the implementation methods provided by this class. + friend class KeyValueStoreManager; + +public: + // NOTE: Currently this platform does not support partial and offset reads + // these will return CHIP_ERROR_NOT_IMPLEMENTED. + CHIP_ERROR _Get(const char * key, void * value, size_t value_size, size_t * read_bytes_size = nullptr, size_t offset = 0); + + CHIP_ERROR _Delete(const char * key); + + CHIP_ERROR _Put(const char * key, const void * value, size_t value_size); + +private: + // ===== Members for internal use by the following friends. + friend KeyValueStoreManager & KeyValueStoreMgr(); + friend KeyValueStoreManagerImpl & KeyValueStoreMgrImpl(); + + static KeyValueStoreManagerImpl sInstance; +}; + +/** + * Returns the public interface of the KeyValueStoreManager singleton object. + * + * Chip applications should use this to access features of the KeyValueStoreManager object + * that are common to all platforms. + */ +inline KeyValueStoreManager & KeyValueStoreMgr(void) +{ + return KeyValueStoreManagerImpl::sInstance; +} + +/** + * Returns the platform-specific implementation of the KeyValueStoreManager singleton object. + * + * Chip applications can use this to gain access to features of the KeyValueStoreManager. + */ +inline KeyValueStoreManagerImpl & KeyValueStoreMgrImpl(void) +{ + return KeyValueStoreManagerImpl::sInstance; +} + +} // namespace PersistedStorage +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/Logging.cpp b/src/platform/Beken/Logging.cpp new file mode 100644 index 00000000000000..243584dd08f2a6 --- /dev/null +++ b/src/platform/Beken/Logging.cpp @@ -0,0 +1,68 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Provides implementations for the CHIP logging functions + * on the Beken platform. + */ +/* this file behaves like a config.h, comes first */ +#include + +#include +#include + +#include +extern "C" void bk_printf(const char *fmt, ...); + +#ifdef LOG_LOCAL_LEVEL +#undef LOG_LOCAL_LEVEL +#endif + +namespace chip { +namespace Logging { +namespace Platform { + +void LogV(const char * module, uint8_t category, const char * msg, va_list v) +{ + char tag[11]; + + snprintf(tag, sizeof(tag), "chip[%s]", module); + tag[sizeof(tag) - 1] = 0; + + char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; + vsnprintf(formattedMsg, sizeof(formattedMsg), msg, v); + + switch (category) + { + case kLogCategory_Error: + bk_printf("%s %s\r\n", tag, formattedMsg); + break; + case kLogCategory_Progress: + default: + bk_printf("%s %s\r\n", tag, formattedMsg); + break; + case kLogCategory_Detail: + bk_printf("%s %s\r\n", tag, formattedMsg); + break; + } +} + +} // namespace Platform +} // namespace Logging +} // namespace chip diff --git a/src/platform/Beken/LwIPCoreLock.cpp b/src/platform/Beken/LwIPCoreLock.cpp new file mode 100644 index 00000000000000..7629ca3a4cf5ff --- /dev/null +++ b/src/platform/Beken/LwIPCoreLock.cpp @@ -0,0 +1,60 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* this file behaves like a config.h, comes first */ +#include + +#include + +namespace { + +SemaphoreHandle_t LwIPCoreLock; + +} + +namespace chip { +namespace DeviceLayer { +namespace Internal { + +CHIP_ERROR InitLwIPCoreLock(void) +{ + if (LwIPCoreLock == NULL) + { + LwIPCoreLock = xSemaphoreCreateMutex(); + if (LwIPCoreLock == NULL) + { + ChipLogError(DeviceLayer, "Failed to create LwIP core lock"); + return CHIP_ERROR_NO_MEMORY; + } + } + + return CHIP_NO_ERROR; +} + +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip + +extern "C" void lock_lwip_core() +{ + xSemaphoreTake(LwIPCoreLock, portMAX_DELAY); +} + +extern "C" void unlock_lwip_core() +{ + xSemaphoreGive(LwIPCoreLock); +} diff --git a/src/platform/Beken/PlatformManagerImpl.cpp b/src/platform/Beken/PlatformManagerImpl.cpp new file mode 100644 index 00000000000000..77fbb00e2e6905 --- /dev/null +++ b/src/platform/Beken/PlatformManagerImpl.cpp @@ -0,0 +1,96 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Provides an implementation of the PlatformManager object + * for the Beken platform. + */ +/* this file behaves like a config.h, comes first */ +#include + +#include +#include +#include +#include + +namespace chip { +namespace DeviceLayer { +namespace Internal { +CHIP_ERROR InitLwIPCoreLock(void); +} + +PlatformManagerImpl PlatformManagerImpl::sInstance; + +extern "C" int mbedtls_hardware_poll(void *data, unsigned char *output, size_t len, size_t *olen); + +CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) +{ + + CHIP_ERROR err; + + SetConfigurationMgr(&ConfigurationManagerImpl::GetDefaultInstance()); + SetDiagnosticDataProvider(&DiagnosticDataProviderImpl::GetDefaultInstance()); + + // Make sure the LwIP core lock has been initialized + err = Internal::InitLwIPCoreLock(); + + SuccessOrExit(err); + + mStartTime = System::SystemClock().GetMonotonicTimestamp(); + + // TODO Wi-Fi Initialzation currently done through the example app needs to be moved into here. + // for now we will let this happen that way and assume all is OK + chip::Crypto::add_entropy_source(mbedtls_hardware_poll, NULL, 32); + + // Call _InitChipStack() on the generic implementation base class + // to finish the initialization process. + err = Internal::GenericPlatformManagerImpl_FreeRTOS::_InitChipStack(); + SuccessOrExit(err); + +exit: + return err; +} + +CHIP_ERROR PlatformManagerImpl::_Shutdown() +{ + uint64_t upTime = 0; + + if (GetDiagnosticDataProvider().GetUpTime(upTime) == CHIP_NO_ERROR) + { + uint32_t totalOperationalHours = 0; + + if (ConfigurationMgr().GetTotalOperationalHours(totalOperationalHours) == CHIP_NO_ERROR) + { + ConfigurationMgr().StoreTotalOperationalHours(totalOperationalHours + static_cast(upTime / 3600)); + } + else + { + ChipLogError(DeviceLayer, "Failed to get total operational hours of the Node"); + } + } + else + { + ChipLogError(DeviceLayer, "Failed to get current uptime since the Node’s last reboot"); + } + + return Internal::GenericPlatformManagerImpl_FreeRTOS::_Shutdown(); +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/PlatformManagerImpl.h b/src/platform/Beken/PlatformManagerImpl.h new file mode 100644 index 00000000000000..5d085612f3437a --- /dev/null +++ b/src/platform/Beken/PlatformManagerImpl.h @@ -0,0 +1,93 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Provides an implementation of the PlatformManager object + * for the Beken platform. + */ + +#pragma once + +#include + +namespace chip { +namespace DeviceLayer { + +/** + * Concrete implementation of the PlatformManager singleton object for the Beken platform. + */ +class PlatformManagerImpl final : public PlatformManager, public Internal::GenericPlatformManagerImpl_FreeRTOS +{ + // Allow the PlatformManager interface class to delegate method calls to + // the implementation methods provided by this class. + friend PlatformManager; + + // Allow the generic implementation base class to call helper methods on + // this class. +#ifndef DOXYGEN_SHOULD_SKIP_THIS + friend Internal::GenericPlatformManagerImpl_FreeRTOS; +#endif + +public: + // ===== Platform-specific members that may be accessed directly by the application. + + System::Clock::Timestamp GetStartTime() { return mStartTime; } + +private: + // ===== Methods that implement the PlatformManager abstract interface. + + CHIP_ERROR _InitChipStack(void); + CHIP_ERROR _Shutdown(); + + // ===== Members for internal use by the following friends. + + friend PlatformManager & PlatformMgr(void); + friend PlatformManagerImpl & PlatformMgrImpl(void); + + System::Clock::Timestamp mStartTime = System::Clock::kZero; + + static PlatformManagerImpl sInstance; + + using Internal::GenericPlatformManagerImpl_FreeRTOS::PostEventFromISR; +}; + +/** + * Returns the public interface of the PlatformManager singleton object. + * + * Chip applications should use this to access features of the PlatformManager object + * that are common to all platforms. + */ +inline PlatformManager & PlatformMgr(void) +{ + return PlatformManagerImpl::sInstance; +} + +/** + * Returns the platform-specific implementation of the PlatformManager singleton object. + * + * Chip applications can use this to gain access to features of the PlatformManager + * that are specific to the Beken platform. + */ +inline PlatformManagerImpl & PlatformMgrImpl(void) +{ + return PlatformManagerImpl::sInstance; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/ServiceProvisioning.cpp b/src/platform/Beken/ServiceProvisioning.cpp new file mode 100755 index 00000000000000..a0610c3b9acd69 --- /dev/null +++ b/src/platform/Beken/ServiceProvisioning.cpp @@ -0,0 +1,47 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "ServiceProvisioning.h" + +#include "include.h" +#include "str_pub.h" +#include "mem_pub.h" +#include "wlan_ui_pub.h" + +using namespace ::chip::DeviceLayer; + +CHIP_ERROR SetWiFiStationProvisioning(const char * ssid, const char * key) +{ + ConnectivityMgr().SetWiFiStationMode(ConnectivityManager::kWiFiStationMode_Disabled); + network_InitTypeDef_st network_cfg; + + memset(&network_cfg, 0, sizeof(network_InitTypeDef_st)); + + network_cfg.wifi_mode = BK_STATION; + strcpy(network_cfg.wifi_ssid, ssid); + strcpy(network_cfg.wifi_key, key); + network_cfg.dhcp_mode = DHCP_CLIENT; + bk_wlan_start(&network_cfg); + ConnectivityMgr().SetWiFiStationMode(ConnectivityManager::kWiFiStationMode_Enabled); + + return CHIP_NO_ERROR; +} diff --git a/src/platform/Beken/ServiceProvisioning.h b/src/platform/Beken/ServiceProvisioning.h new file mode 100644 index 00000000000000..7ac2a8375addae --- /dev/null +++ b/src/platform/Beken/ServiceProvisioning.h @@ -0,0 +1,26 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _SERVICE_PROVISIONING_H +#define _SERVICE_PROVISIONING_H + +#include + +CHIP_ERROR SetWiFiStationProvisioning(const char * ssid, const char * key); + +#endif // _SERVICE_PROVISIONING_H diff --git a/src/platform/Beken/SoftwareUpdateManagerImpl.h b/src/platform/Beken/SoftwareUpdateManagerImpl.h new file mode 100755 index 00000000000000..df934dc323345b --- /dev/null +++ b/src/platform/Beken/SoftwareUpdateManagerImpl.h @@ -0,0 +1,89 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Google LLC. + * 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 + +#if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER + +#include +#include + +namespace chip { +namespace DeviceLayer { + +/** + * Concrete implementation of the SoftwareUpdateManager singleton object for the + * Beken platform. + */ +class SoftwareUpdateManagerImpl final : public SoftwareUpdateManager, + public Internal::GenericSoftwareUpdateManagerImpl, + public Internal::GenericSoftwareUpdateManagerImpl_BDX +{ + // Allow the SoftwareUpdateManager interface class to delegate method calls to + // the implementation methods provided by this class. + friend class SoftwareUpdateManager; + + // Allow the GenericSoftwareUpdateManagerImpl base class to access helper methods + // and types defined on this class. + friend class Internal::GenericSoftwareUpdateManagerImpl; + + // Allow the GenericSoftwareUpdateManagerImpl_BDX base class to access helper methods + // and types defined on this class. + friend class Internal::GenericSoftwareUpdateManagerImpl_BDX; + +public: + // ===== Members for internal use by the following friends. + + friend ::chip::DeviceLayer::SoftwareUpdateManager & SoftwareUpdateMgr(void); + friend SoftwareUpdateManagerImpl & SoftwareUpdateMgrImpl(void); + + static SoftwareUpdateManagerImpl sInstance; + +private: + // ===== Members that implement the SoftwareUpdateManager abstract interface. + + CHIP_ERROR _Init(void); +}; + +/** + * Returns a reference to the public interface of the SoftwareUpdateManager singleton object. + * + * Internal components should use this to access features of the SoftwareUpdateManager object + * that are common to all platforms. + */ +inline SoftwareUpdateManager & SoftwareUpdateMgr(void) +{ + return SoftwareUpdateManagerImpl::sInstance; +} + +/** + * Returns the platform-specific implementation of the SoftwareUpdateManager singleton object. + * + * Internal components can use this to gain access to features of the SoftwareUpdateManager + * that are specific to the Beken platform. + */ +inline SoftwareUpdateManagerImpl & SoftwareUpdateMgrImpl(void) +{ + return SoftwareUpdateManagerImpl::sInstance; +} + +} // namespace DeviceLayer +} // namespace chip + +#endif // CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER diff --git a/src/platform/Beken/SystemPlatformConfig.h b/src/platform/Beken/SystemPlatformConfig.h new file mode 100755 index 00000000000000..944fa44b059a0b --- /dev/null +++ b/src/platform/Beken/SystemPlatformConfig.h @@ -0,0 +1,65 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Platform-specific configuration overrides for the CHIP System + * Layer on the Beken platform. + * + */ + +#pragma once + +#include + +namespace chip { +namespace DeviceLayer { +struct ChipDeviceEvent; +} // namespace DeviceLayer +} // namespace chip + +// ==================== Platform Adaptations ==================== +#define CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_EVENT_FUNCTIONS 1 +#define CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME 1 +#define CHIP_SYSTEM_CONFIG_EVENT_OBJECT_TYPE const struct ::chip::DeviceLayer::ChipDeviceEvent * + +#define CHIP_SYSTEM_CONFIG_ERROR_TYPE uint32_t +#define CHIP_SYSTEM_CONFIG_NO_ERROR 0 +#define CHIP_SYSTEM_CONFIG_ERROR_MIN 7000000 +#define CHIP_SYSTEM_CONFIG_ERROR_MAX 7000999 +#define _CHIP_SYSTEM_CONFIG_ERROR(e) (CHIP_SYSTEM_CONFIG_ERROR_MIN + (e)) +#define CHIP_SYSTEM_LWIP_ERROR_MIN 3000000 +#define CHIP_SYSTEM_LWIP_ERROR_MAX 3000128 + +// ==================== General Configuration Overrides ==================== + +// NOTE: Values that are mapped to CONFIG_ #defines are settable via the Kconfig mechanism. + +#ifndef CHIP_SYSTEM_CONFIG_NUM_TIMERS +#define CHIP_SYSTEM_CONFIG_NUM_TIMERS 16 +#endif // CHIP_SYSTEM_CONFIG_NUM_TIMERS + +#define CHIP_SYSTEM_CONFIG_USE_ZEPHYR_NET_IF 0 +#define CHIP_SYSTEM_CONFIG_USE_BSD_IFADDRS 0 +#define CHIP_SYSTEM_CONFIG_USE_ZEPHYR_SOCKET_EXTENSIONS00 +#define CHIP_SYSTEM_CONFIG_USE_LWIP 1 +#define CHIP_SYSTEM_CONFIG_USE_SOCKETS 0 +#define CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK 0 +#define CHIP_SYSTEM_CONFIG_POSIX_LOCKING 0 +#define CHIP_SYSTEM_CONFIG_FREERTOS_LOCKING 1 +#define CHIP_CONFIG_MDNS_CACHE_SIZE 4 diff --git a/src/platform/Beken/args.gni b/src/platform/Beken/args.gni new file mode 100755 index 00000000000000..9bdd727ee0e8fe --- /dev/null +++ b/src/platform/Beken/args.gni @@ -0,0 +1,25 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") + +chip_device_platform = "beken" + +lwip_platform = "external" +mbedtls_target = "//mbedtls:mbedtls" + +chip_build_tests = false +chip_inet_config_enable_tun_endpoint = false +chip_inet_config_enable_tcp_endpoint = true +chip_inet_config_enable_udp_endpoint = true diff --git a/src/platform/device.gni b/src/platform/device.gni index 6ac5b17f02202a..566a4c415878c1 100755 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -58,7 +58,7 @@ declare_args() { chip_device_platform == "linux" || chip_device_platform == "esp32" || chip_device_platform == "mbed" || chip_device_platform == "tizen" || chip_device_platform == "android" || chip_device_platform == "ameba" || - chip_device_platform == "webos" || chip_device_platform == "bl602" + chip_device_platform == "webos" || chip_device_platform == "bl602" || chip_device_platform == "beken" # Enable ble support. if (chip_device_platform == "fake") { @@ -76,7 +76,11 @@ declare_args() { # Select DNS-SD implementation if (chip_device_platform == "linux" || chip_device_platform == "esp32" || chip_device_platform == "mbed" || chip_device_platform == "p6" || +<<<<<<< HEAD chip_device_platform == "ameba" || chip_device_platform == "webos") { +======= + chip_device_platform == "ameba"|| chip_device_platform == "beken") { +>>>>>>> Add beken base code into Matter SDK chip_mdns = "minimal" } else if (chip_device_platform == "darwin" || chip_device_platform == "cc13x2_26x2" || current_os == "android" || @@ -121,8 +125,13 @@ if (chip_device_platform == "cc13x2_26x2") { _chip_device_layer = "bouffalolab/BL602" } else if (chip_device_platform == "cyw30739") { _chip_device_layer = "CYW30739" +<<<<<<< HEAD } else if (chip_device_platform == "webos") { _chip_device_layer = "webos" +======= +} else if (chip_device_platform == "beken") { + _chip_device_layer = "Beken" +>>>>>>> Add beken base code into Matter SDK } if (chip_device_platform != "external") { @@ -164,7 +173,6 @@ if (_chip_device_layer != "none" && chip_device_platform != "external") { chip_system_platform_config_include = "" } - assert( (current_os != "freertos" && chip_device_platform == "none") || chip_device_platform == "fake" || @@ -177,5 +185,9 @@ assert( chip_device_platform == "telink" || chip_device_platform == "mbed" || chip_device_platform == "p6" || chip_device_platform == "android" || chip_device_platform == "ameba" || chip_device_platform == "cyw30739" || +<<<<<<< HEAD chip_device_platform == "webos" || chip_device_platform == "bl602", +======= + chip_device_platform == "beken", +>>>>>>> Add beken base code into Matter SDK "Please select a valid value for chip_device_platform") From d01d6a0e3d831e6f55d4fced06935c293975cc4e Mon Sep 17 00:00:00 2001 From: "jun.luo" Date: Thu, 27 Jan 2022 11:30:16 +0800 Subject: [PATCH 02/20] Support rotate-id Can check the field with nRF and chip-tool discover Change-Id: I65487f95c430f653a80ea1b5aff60efb6528dfbe --- config/beken/args.gni | 2 + src/platform/Beken/BLEManagerImpl.cpp | 77 ++++++++++++++++++++++++--- src/platform/Beken/BLEManagerImpl.h | 4 ++ src/platform/Beken/BUILD.gn | 5 +- 4 files changed, 79 insertions(+), 9 deletions(-) diff --git a/config/beken/args.gni b/config/beken/args.gni index 67ac560c7d4e8a..c60fc0c25e1088 100755 --- a/config/beken/args.gni +++ b/config/beken/args.gni @@ -32,5 +32,7 @@ chip_inet_config_enable_udp_endpoint = true chip_bypass_rendezvous = false chip_config_network_layer_ble = true chip_config_memory_management = "platform" +chip_enable_additional_data_advertising = true +chip_enable_rotating_device_id = true custom_toolchain = "//third_party/connectedhomeip/config/beken/toolchain:beken" diff --git a/src/platform/Beken/BLEManagerImpl.cpp b/src/platform/Beken/BLEManagerImpl.cpp index f84be5aeb2cf32..8166c0f5f25519 100755 --- a/src/platform/Beken/BLEManagerImpl.cpp +++ b/src/platform/Beken/BLEManagerImpl.cpp @@ -28,6 +28,9 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING +#include +#endif #include "stdio.h" #include "timers.h" @@ -84,20 +87,25 @@ static const uint8_t _svc_uuid[16] = {0xF6,0xFF,0,0,0x0,0x0,0,0,0,0,0x0,0x0,0,0, //#define UUID_CHIPoBLECharact_RX { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x11 } #define ChipUUID_CHIPoBLECharact_TX { 0x12, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18 } //#define ChipUUID_CHIPoBLECharact_TX { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x12 } - +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING +#define UUID_CHIPoBLEChar_C3 { 0x04, 0x8F, 0x21, 0x83, 0x8A, 0x74, 0x7D, 0xB8, 0xF2, 0x45, 0x72, 0x87, 0x38, 0x02, 0x63, 0x64 } +#endif #define BEKEN_ATT_DECL_PRIMARY_SERVICE_128 {0x00,0x28,0,0,0,0,0,0,0,0,0,0,0,0,0,0} #define BEKEN_ATT_DECL_CHARACTERISTIC_128 {0x03,0x28,0,0,0,0,0,0,0,0,0,0,0,0,0,0} #define BEKEN_ATT_DESC_CLIENT_CHAR_CFG_128 {0x02,0x29,0,0,0,0,0,0,0,0,0,0,0,0,0,0} enum { - SVR_FFF6_IDX_SVC = 0, - SVR_FFF6_RX_DECL = 1, - SVR_FFF6_RX_VALUE = 2, - SVR_FFF6_TX_DECL = 3, - SVR_FFF6_TX_VALUE = 4, - SVR_FFF6_TX_CFG = 5, - SVR_FFF6_MAX = 6, + SVR_FFF6_IDX_SVC, + SVR_FFF6_RX_DECL , + SVR_FFF6_RX_VALUE, + SVR_FFF6_TX_DECL, + SVR_FFF6_TX_VALUE, +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + SVR_FFF6_C3_VALUE, +#endif + SVR_FFF6_TX_CFG, + SVR_FFF6_MAX, }; bk_attm_desc_t svr_fff6_att_db[SVR_FFF6_MAX] = @@ -114,6 +122,9 @@ bk_attm_desc_t svr_fff6_att_db[SVR_FFF6_MAX] = [SVR_FFF6_TX_DECL] = {BEKEN_ATT_DECL_CHARACTERISTIC_128, BK_PERM_SET(RD, ENABLE) | BK_PERM_SET(NTF, ENABLE), 0, 0}, //// UUID_LEN_POS BK_PERM_RIGHT_UUID_128 RD_POS [SVR_FFF6_TX_VALUE] = {ChipUUID_CHIPoBLECharact_TX, BK_PERM_SET(RD, ENABLE) | BK_PERM_SET(NTF, ENABLE), BK_PERM_SET(RI, ENABLE) | BK_PERM_SET(UUID_LEN, UUID_128), 512}, +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + [SVR_FFF6_C3_VALUE] = {UUID_CHIPoBLEChar_C3, BK_PERM_SET(RD, ENABLE), BK_PERM_SET(RI, ENABLE) | BK_PERM_SET(UUID_LEN, UUID_128), 512}, +#endif [SVR_FFF6_TX_CFG] = {BEKEN_ATT_DESC_CLIENT_CHAR_CFG_128, BK_PERM_SET(RD, ENABLE) | BK_PERM_SET(WRITE_REQ, ENABLE), 0, 2}, }; @@ -706,7 +717,11 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising(void) ExitNow(); } +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + deviceIdInfo.SetAdditionalDataFlag(true); +#endif VerifyOrExit(index + sizeof(deviceIdInfo) <= sizeof(advData), err = CHIP_ERROR_OUTBOUND_MESSAGE_TOO_BIG); + memcpy(&advData[index], &deviceIdInfo, sizeof(deviceIdInfo)); index = static_cast(index + sizeof(deviceIdInfo)); bk_ble_set_adv_data(adv_actv_idx, advData, index, beken_ble_cmd_cb); @@ -1041,6 +1056,45 @@ void BLEManagerImpl::beken_ble_cmd_cb(ble_cmd_t cmd, ble_cmd_param_t *param) } } +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING +void BLEManagerImpl::HandleC3CharRead(void * param) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + chip::System::PacketBufferHandle bufferHandle; + read_req_t *r_req = (read_req_t *)param; + + char serialNumber[ConfigurationManager::kMaxSerialNumberLength + 1]; + uint16_t lifetimeCounter = 0; + BitFlags additionalDataFields; + +#if CHIP_ENABLE_ROTATING_DEVICE_ID + err = ConfigurationMgr().GetSerialNumber(serialNumber, sizeof(serialNumber)); + SuccessOrExit(err); + err = ConfigurationMgr().GetLifetimeCounter(lifetimeCounter); + SuccessOrExit(err); + + additionalDataFields.Set(AdditionalDataFields::RotatingDeviceId); +#endif /* CHIP_ENABLE_ROTATING_DEVICE_ID */ + + err = AdditionalDataPayloadGenerator().generateAdditionalDataPayload(lifetimeCounter, serialNumber, strlen(serialNumber), + bufferHandle, additionalDataFields); + SuccessOrExit(err); + if(r_req->value == NULL) + { + ChipLogError(DeviceLayer, "param->value == NULL"); + return; + } + memcpy(r_req->value, bufferHandle->Start(), bufferHandle->DataLength()); + r_req->length = bufferHandle->DataLength(); +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "Failed to generate TLV encoded Additional Data"); + } + return; +} +#endif + void BLEManagerImpl::ble_event_notice(ble_notice_t notice, void *param) { ///BLEManagerImpl * blemgr = static_cast(param); @@ -1085,6 +1139,13 @@ void BLEManagerImpl::ble_event_notice(ble_notice_t notice, void *param) { sInstance.HandleTXCharCCCDRead(param); } +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + if (r_req->att_idx == SVR_FFF6_C3_VALUE) + { + ChipLogProgress(DeviceLayer, "SVR_FFF6_OPT_VALUE!!!!\r\n"); + sInstance.HandleTXCharRead((void*)param); + } +#endif break; } case BLE_5_TX_DONE: diff --git a/src/platform/Beken/BLEManagerImpl.h b/src/platform/Beken/BLEManagerImpl.h index c00c51ce69dd86..b12a38477ac2d4 100755 --- a/src/platform/Beken/BLEManagerImpl.h +++ b/src/platform/Beken/BLEManagerImpl.h @@ -183,6 +183,10 @@ class BLEManagerImpl final : public BLEManager, static void ble_adv_timer_timeout_handle(TimerHandle_t xTimer); static void CancelBleAdvTimeoutTimer(void); static void StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs); +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + void HandleC3CharRead(void * param); +#endif + }; /** diff --git a/src/platform/Beken/BUILD.gn b/src/platform/Beken/BUILD.gn index 0217f5b3ea4211..5e237b63f410d8 100755 --- a/src/platform/Beken/BUILD.gn +++ b/src/platform/Beken/BUILD.gn @@ -49,7 +49,10 @@ static_library("Beken") { "CHIPMem-Platform.cpp", ] - deps = [ "${chip_root}/src/lib/dnssd:platform_header" ] + deps = [ + "${chip_root}/src/lib/dnssd:platform_header", + "${chip_root}/src/setup_payload", + ] public_deps = [ "${chip_root}/src/crypto", From 0418518b7fb2308717a09a7a6345cc7290967ec0 Mon Sep 17 00:00:00 2001 From: "fuxing.guo" Date: Fri, 28 Jan 2022 17:36:25 +0800 Subject: [PATCH 03/20] When the device bring up,auto connect to WIFI that the device has connected on the last time.` Change-Id: I8591ca1a2a98a9decda2d15bb5a926300dc86358 --- .../Beken/ConnectivityManagerImpl.cpp | 88 +++++++++++++++---- .../DeviceNetworkProvisioningDelegateImpl.cpp | 2 +- .../Beken/KeyValueStoreManagerImpl.cpp | 25 +++--- 3 files changed, 86 insertions(+), 29 deletions(-) diff --git a/src/platform/Beken/ConnectivityManagerImpl.cpp b/src/platform/Beken/ConnectivityManagerImpl.cpp index 0ec2466280259e..85d8509f8ca1c7 100644 --- a/src/platform/Beken/ConnectivityManagerImpl.cpp +++ b/src/platform/Beken/ConnectivityManagerImpl.cpp @@ -42,6 +42,10 @@ #include #include "wlan_ui_pub.h" +#include "flash_namespace_value.h" + +#define BEKEN_WIFI_INFO "BekenWiFi" +static uint32_t dwWifiExit = 0; using namespace ::chip; using namespace ::chip::Inet; @@ -74,6 +78,19 @@ CHIP_ERROR ConnectivityManagerImpl::_Init() // Ensure that station mode is enabled in the WiFi layer. //wifi_set_mode(RTW_MODE_STA); ; + ssid_key_save_t fci = {{0}}; + CHIP_ERROR err = CHIP_NO_ERROR; + + err = PersistedStorage::KeyValueStoreMgr().Get(BEKEN_WIFI_INFO, &fci,sizeof(ssid_key_save_t)); + if(err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer,"%s %d KeyValueGet failed\r\n",__FUNCTION__,__LINE__); + } + else if(fci.ucssid[0] != 0) + { + dwWifiExit = 1; + ChipLogProgress(DeviceLayer,"Station get ssid: %s %s \r\n",fci.ucssid,fci.ucKey); + } // If there is no persistent station provision... if (!IsWiFiStationProvisioned()) @@ -135,7 +152,7 @@ void ConnectivityManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) #if CHIP_DEVICE_CONFIG_ENABLE_WIFI if (event->Type == DeviceEventType::kRtkWiFiStationConnectedEvent) { - ChipLogProgress(DeviceLayer, "WIFI_EVENT_STA_CONNECTED"); + ChipLogProgress(DeviceLayer, "_OnPlatformEvent WIFI_EVENT_STA_CONNECTED"); if (mWiFiStationState == kWiFiStationState_Connecting) { ChangeWiFiStationState(kWiFiStationState_Connecting_Succeeded); @@ -154,6 +171,11 @@ ConnectivityManager::WiFiStationMode ConnectivityManagerImpl::_GetWiFiStationMod mWiFiStationMode = (wifi_mode == RTW_MODE_STA) ? kWiFiStationMode_Enabled : kWiFiStationMode_Disabled; } #endif + if(dwWifiExit) + { + mWiFiStationMode = kWiFiStationMode_Enabled; + } + //TODO should enabled return kWiFiStationMode_Enabled; } @@ -195,15 +217,26 @@ CHIP_ERROR ConnectivityManagerImpl::_SetWiFiStationMode(WiFiStationMode val) bool ConnectivityManagerImpl::_IsWiFiStationProvisioned(void) { wlan_sta_config_t config; + bool rtn = false; - memset(&config, 0, sizeof(config)); - config.field = WLAN_STA_FIELD_SSID; - if(0 != wlan_sta_get_config(&config)) + if(dwWifiExit) { - ChipLogError(DeviceLayer, "wlan_sta_get_config failed!"); - return false; + rtn = true ; } - return (config.u.ssid.ssid[0] != 0) ? true : false; + else + { + memset(&config, 0, sizeof(config)); + config.field = WLAN_STA_FIELD_SSID; + if(0 != wlan_sta_get_config(&config)) + { + ChipLogError(DeviceLayer, "wlan_sta_get_config failed!"); + return false; + } + + rtn = (config.u.ssid.ssid[0] != 0) ? true : false; + } + + return rtn; } void ConnectivityManagerImpl::_ClearWiFiStationProvision(void) @@ -296,11 +329,19 @@ static bool stationConnected = false; void ConnectivityManagerImpl::wlan_status_cb(void *ctxt) { int notice_event = *(unsigned int*)ctxt; + ssid_key_save_t wpa_save = {{0}}; switch(notice_event){ case RW_EVT_STA_GOT_IP: stationConnected = true; WiFiStationConnectedHandler(); + + if (wpa_ssid_key_get(&wpa_save)) + { + ChipLogError(DeviceLayer, "wpa_ssid_key_get fail"); + return ; + } + PersistedStorage::KeyValueStoreMgr().Put(BEKEN_WIFI_INFO, (const void *)&wpa_save, sizeof(ssid_key_save_t)); ChipLogProgress(DeviceLayer, "RW_EVT_STA_GOT_IP"); break; case RW_EVT_STA_CONNECTED: @@ -319,9 +360,7 @@ void ConnectivityManagerImpl::wlan_status_cb(void *ctxt) void ConnectivityManagerImpl::DriveStationState() { int ret; - GetWiFiStationMode(); - // If the station interface is NOT under application control... if (mWiFiStationMode != kWiFiStationMode_ApplicationControlled) { @@ -403,7 +442,7 @@ void ConnectivityManagerImpl::DriveStationState() // not presently under application control), AND the system is not in the process of // scanning, then... ChipLogProgress(DeviceLayer, "mWiFiStationMode:%d, IsWiFiStationProvisioned:%d", mWiFiStationMode, IsWiFiStationProvisioned()); - if (mWiFiStationMode == kWiFiStationMode_Enabled && IsWiFiStationProvisioned() && + if (mWiFiStationMode == kWiFiStationMode_Enabled && IsWiFiStationProvisioned() && mWiFiStationState != kWiFiStationState_Connecting) { // Initiate a connection to the AP if we haven't done so before, or if enough @@ -411,13 +450,28 @@ void ConnectivityManagerImpl::DriveStationState() if (mLastStationConnectFailTime == System::Clock::kZero || now >= mLastStationConnectFailTime + mWiFiStationReconnectInterval) { - ChipLogProgress(DeviceLayer, "Attempting to connect WiFi station interface"); - bk_wlan_status_register_cb(ConnectivityManagerImpl().wlan_status_cb); - if(0 != wlan_sta_connect(0))//assume not support fast connect - { - ChipLogError(DeviceLayer, "wlan_sta_connect() failed!"); - return; - } + ChipLogProgress(DeviceLayer,"Attempting to connect WiFi station interface \r\n"); + ssid_key_save_t fci = {{0}}; + network_InitTypeDef_st network_cfg; + + PersistedStorage::KeyValueStoreMgr().Get(BEKEN_WIFI_INFO, &fci,sizeof(ssid_key_save_t)); + bk_wlan_status_register_cb(ConnectivityManagerImpl().wlan_status_cb); + + memset(&network_cfg, 0, sizeof(network_InitTypeDef_st)); + network_cfg.wifi_mode = BK_STATION; + strcpy(network_cfg.wifi_ssid, (char *)fci.ucssid); + + strcpy(network_cfg.wifi_key, (char *)fci.ucKey); + network_cfg.dhcp_mode = DHCP_CLIENT; + + bk_wlan_start(&network_cfg); + #if 0 + if(0 != wlan_sta_connect(0))//assume not support fast connect + { + ChipLogError(DeviceLayer, "wlan_sta_connect() failed!"); + return; + } + #endif ChangeWiFiStationState(kWiFiStationState_Connecting); } diff --git a/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp b/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp index 19d63924a2eaa2..7c3a4d73c3968b 100644 --- a/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp +++ b/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp @@ -28,7 +28,7 @@ namespace DeviceLayer { CHIP_ERROR DeviceNetworkProvisioningDelegateImpl::_ProvisionWiFiNetwork(const char * ssid, const char * key) { CHIP_ERROR err = CHIP_NO_ERROR; - + ChipLogProgress(NetworkProvisioning, "BekenNetworkProvisioningDelegate: SSID: %s", ssid); err = SetWiFiStationProvisioning(ssid, key); if (err != CHIP_NO_ERROR) diff --git a/src/platform/Beken/KeyValueStoreManagerImpl.cpp b/src/platform/Beken/KeyValueStoreManagerImpl.cpp index 3eb2401d44df54..aadd73ac31dcce 100755 --- a/src/platform/Beken/KeyValueStoreManagerImpl.cpp +++ b/src/platform/Beken/KeyValueStoreManagerImpl.cpp @@ -37,20 +37,23 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t { CHIP_ERROR err = CHIP_NO_ERROR; int32_t ret = -1; - - if ((!value) || (!read_bytes_size)) + uint32_t dwTeReadBytes = 0; + + if ((!value) || offset_bytes > 0) { + // Offset and partial reads are not supported in nvs, for now just return NOT_IMPLEMENTED. Support can be added in the + // future if this is needed. return (err = CHIP_ERROR_INVALID_ARGUMENT); } - if (offset_bytes > 0) + if(read_bytes_size == NULL) { - // Offset and partial reads are not supported in nvs, for now just return NOT_IMPLEMENTED. Support can be added in the - // future if this is needed. - return (err = CHIP_ERROR_NOT_IMPLEMENTED); + ret = bk_read_data( key,key,(char *) value,value_size,&dwTeReadBytes); + } + else + { + ret = bk_read_data( key,key,(char *) value,value_size,(uint32_t *)read_bytes_size); } - - ret = bk_read_data( key,key,(char *) value,value_size,(uint32_t *)read_bytes_size); if (ret == kNoErr) { @@ -65,7 +68,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t err = CHIP_ERROR_INTERNAL; } - return CHIP_NO_ERROR; + return err; } CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, size_t value_size) @@ -77,8 +80,8 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, { return (err = CHIP_ERROR_INVALID_ARGUMENT); } - ret = bk_write_data( key,key, (char *)value,value_size); + if (ret == kNoErr) { err = CHIP_NO_ERROR; @@ -88,7 +91,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, err = CHIP_ERROR_INTERNAL; } - return CHIP_NO_ERROR; + return err; } CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) From d7e1f2f346e84f45aa53bc55a7f0bdad1a97d6df Mon Sep 17 00:00:00 2001 From: "yongjia.fang" Date: Thu, 17 Feb 2022 10:34:30 +0800 Subject: [PATCH 04/20] network commission refactor --- .../lighting-app/beken/main/chipinterface.cpp | 8 + .../network-commissioning-old.cpp | 295 ++++++++++++++++++ src/platform/Beken/BUILD.gn | 5 +- src/platform/Beken/BekenConfig.cpp | 9 +- src/platform/Beken/BekenConfig.h | 7 +- .../Beken/ConnectivityManagerImpl.cpp | 2 + .../DeviceNetworkProvisioningDelegateImpl.cpp | 43 --- .../DeviceNetworkProvisioningDelegateImpl.h | 44 --- .../Beken/KeyValueStoreManagerImpl.cpp | 28 +- src/platform/Beken/KeyValueStoreManagerImpl.h | 4 + .../Beken/NetworkCommissioningDriver.h | 101 ++++++ .../Beken/NetworkCommissioningWiFiDriver.cpp | 294 +++++++++++++++++ src/platform/Beken/ServiceProvisioning.cpp | 47 --- src/platform/Beken/ServiceProvisioning.h | 26 -- 14 files changed, 736 insertions(+), 177 deletions(-) create mode 100644 src/app/clusters/network-commissioning-old/network-commissioning-old.cpp mode change 100644 => 100755 src/platform/Beken/ConnectivityManagerImpl.cpp delete mode 100644 src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp delete mode 100644 src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.h create mode 100755 src/platform/Beken/NetworkCommissioningDriver.h create mode 100755 src/platform/Beken/NetworkCommissioningWiFiDriver.cpp delete mode 100755 src/platform/Beken/ServiceProvisioning.cpp delete mode 100644 src/platform/Beken/ServiceProvisioning.h diff --git a/examples/lighting-app/beken/main/chipinterface.cpp b/examples/lighting-app/beken/main/chipinterface.cpp index 6570769fb8f4ce..1e2d1aab3d0ea0 100644 --- a/examples/lighting-app/beken/main/chipinterface.cpp +++ b/examples/lighting-app/beken/main/chipinterface.cpp @@ -25,9 +25,11 @@ #include #include +#include #include #include #include +#include #include #include @@ -41,6 +43,11 @@ using namespace ::chip::DeviceLayer; static DeviceCallbacks EchoCallbacks; +namespace { +app::Clusters::NetworkCommissioning::Instance + sWiFiNetworkCommissioningInstance(0 /* Endpoint Id */, &(NetworkCommissioning::BekenWiFiDriver::GetInstance())); +} // namespace + // need to check CONFIG_RENDEZVOUS_MODE bool isRendezvousBLE() { @@ -260,6 +267,7 @@ extern "C" void ChipTest(void) chip::Server::GetInstance().Init(); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); + sWiFiNetworkCommissioningInstance.Init(); std::string qrCodeText = createSetupPayload(); diff --git a/src/app/clusters/network-commissioning-old/network-commissioning-old.cpp b/src/app/clusters/network-commissioning-old/network-commissioning-old.cpp new file mode 100644 index 00000000000000..3b9323fc9e155f --- /dev/null +++ b/src/app/clusters/network-commissioning-old/network-commissioning-old.cpp @@ -0,0 +1,295 @@ + + +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "network-commissioning.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +#include +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD + +// Include DeviceNetworkProvisioningDelegateImpl for WiFi provisioning. +// TODO: Enable wifi network should be done by ConnectivityManager. (Or other platform neutral interfaces) +#if defined(CHIP_DEVICE_LAYER_TARGET) +//#define DEVICENETWORKPROVISIONING_HEADER +//#include DEVICENETWORKPROVISIONING_HEADER +#endif + +// TODO: Configuration should move to build-time configuration +#ifndef CHIP_CLUSTER_NETWORK_COMMISSIONING_MAX_NETWORKS +#define CHIP_CLUSTER_NETWORK_COMMISSIONING_MAX_NETWORKS 4 +#endif // CHIP_CLUSTER_NETWORK_COMMISSIONING_MAX_NETWORKS + +using namespace chip; +using namespace chip::app; + +namespace chip { +namespace app { +namespace Clusters { +namespace NetworkCommissioning { + +constexpr uint8_t kMaxNetworkIDLen = 32; +constexpr uint8_t kMaxThreadDatasetLen = 254; // As defined in Thread spec. +constexpr uint8_t kMaxWiFiSSIDLen = 32; +constexpr uint8_t kMaxWiFiCredentialsLen = 64; +constexpr uint8_t kMaxNetworks = CHIP_CLUSTER_NETWORK_COMMISSIONING_MAX_NETWORKS; + +enum class NetworkType : uint8_t +{ + kUndefined = 0, + kWiFi = 1, + kThread = 2, + kEthernet = 3, +}; + +struct ThreadNetworkInfo +{ + uint8_t mDataset[kMaxThreadDatasetLen]; + uint8_t mDatasetLen; +}; + +struct WiFiNetworkInfo +{ + uint8_t mSSID[kMaxWiFiSSIDLen + 1]; + uint8_t mSSIDLen; + uint8_t mCredentials[kMaxWiFiCredentialsLen]; + uint8_t mCredentialsLen; +}; + +struct NetworkInfo +{ + uint8_t mNetworkID[kMaxNetworkIDLen]; + uint8_t mNetworkIDLen; + uint8_t mEnabled; + NetworkType mNetworkType; + union NetworkData + { +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD + Thread::OperationalDataset mThread; +#endif +#if defined(CHIP_DEVICE_LAYER_TARGET) + WiFiNetworkInfo mWiFi; +#endif + } mData; +}; + +namespace { +// The internal network info containing credentials. Need to find some better place to save these info. +NetworkInfo sNetworks[kMaxNetworks]; +} // namespace + +void OnAddOrUpdateThreadNetworkCommandCallbackInternal(app::CommandHandler * apCommandHandler, + const app::ConcreteCommandPath & commandPath, ByteSpan operationalDataset, + uint64_t breadcrumb, uint32_t timeoutMs) +{ + Commands::NetworkConfigResponse::Type response; +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD + NetworkCommissioningStatus err = NetworkCommissioningStatus::kBoundsExceeded; + + for (size_t i = 0; i < kMaxNetworks; i++) + { + if (sNetworks[i].mNetworkType == NetworkType::kUndefined) + { + Thread::OperationalDataset & dataset = sNetworks[i].mData.mThread; + CHIP_ERROR error = dataset.Init(operationalDataset); + + if (error != CHIP_NO_ERROR) + { + ChipLogDetail(Zcl, "Failed to parse Thread operational dataset: %s", ErrorStr(error)); + err = NetworkCommissioningStatus::kUnknownError; + break; + } + + uint8_t extendedPanId[Thread::kSizeExtendedPanId]; + + static_assert(sizeof(sNetworks[i].mNetworkID) >= sizeof(extendedPanId), + "Network ID must be larger than Thread extended PAN ID!"); + SuccessOrExit(dataset.GetExtendedPanId(extendedPanId)); + memcpy(sNetworks[i].mNetworkID, extendedPanId, sizeof(extendedPanId)); + sNetworks[i].mNetworkIDLen = sizeof(extendedPanId); + + sNetworks[i].mNetworkType = NetworkType::kThread; + sNetworks[i].mEnabled = false; + + err = NetworkCommissioningStatus::kSuccess; + break; + } + } + +exit: + // TODO: We should encode response command here. + + ChipLogDetail(Zcl, "AddOrUpdateThreadNetwork: %u", to_underlying(err)); + response.networkingStatus = err; +#else + // The target does not supports ThreadNetwork. We should not add AddOrUpdateThreadNetwork command in that case then the upper + // layer will return "Command not found" error. + response.networkingStatus = NetworkCommissioningStatus::kUnknownError; +#endif + apCommandHandler->AddResponseData(commandPath, response); +} + +void OnAddOrUpdateWiFiNetworkCommandCallbackInternal(app::CommandHandler * apCommandHandler, + const app::ConcreteCommandPath & commandPath, ByteSpan ssid, + ByteSpan credentials, uint64_t breadcrumb, uint32_t timeoutMs) +{ + Commands::NetworkConfigResponse::Type response; +#if defined(CHIP_DEVICE_LAYER_TARGET) + NetworkCommissioningStatus err = NetworkCommissioningStatus::kBoundsExceeded; + + for (size_t i = 0; i < kMaxNetworks; i++) + { + if (sNetworks[i].mNetworkType == NetworkType::kUndefined) + { + VerifyOrExit(ssid.size() <= sizeof(sNetworks[i].mData.mWiFi.mSSID), err = NetworkCommissioningStatus::kOutOfRange); + memcpy(sNetworks[i].mData.mWiFi.mSSID, ssid.data(), ssid.size()); + + using WiFiSSIDLenType = decltype(sNetworks[i].mData.mWiFi.mSSIDLen); + VerifyOrExit(CanCastTo(ssid.size()), err = NetworkCommissioningStatus::kOutOfRange); + sNetworks[i].mData.mWiFi.mSSIDLen = static_cast(ssid.size()); + + VerifyOrExit(credentials.size() <= sizeof(sNetworks[i].mData.mWiFi.mCredentials), + err = NetworkCommissioningStatus::kOutOfRange); + memcpy(sNetworks[i].mData.mWiFi.mCredentials, credentials.data(), credentials.size()); + + using WiFiCredentialsLenType = decltype(sNetworks[i].mData.mWiFi.mCredentialsLen); + VerifyOrExit(CanCastTo(ssid.size()), err = NetworkCommissioningStatus::kOutOfRange); + sNetworks[i].mData.mWiFi.mCredentialsLen = static_cast(credentials.size()); + + VerifyOrExit(ssid.size() <= sizeof(sNetworks[i].mNetworkID), err = NetworkCommissioningStatus::kOutOfRange); + memcpy(sNetworks[i].mNetworkID, sNetworks[i].mData.mWiFi.mSSID, ssid.size()); + + using NetworkIDLenType = decltype(sNetworks[i].mNetworkIDLen); + VerifyOrExit(CanCastTo(ssid.size()), err = NetworkCommissioningStatus::kOutOfRange); + sNetworks[i].mNetworkIDLen = static_cast(ssid.size()); + + sNetworks[i].mNetworkType = NetworkType::kWiFi; + sNetworks[i].mEnabled = false; + + err = NetworkCommissioningStatus::kSuccess; + break; + } + } + + VerifyOrExit(err == NetworkCommissioningStatus::kSuccess, ); + + ChipLogDetail(Zcl, "WiFi provisioning data: SSID: %.*s", static_cast(ssid.size()), ssid.data()); +exit: + // TODO: We should encode response command here. + + ChipLogDetail(Zcl, "AddOrUpdateWiFiNetwork: %u", to_underlying(err)); + response.networkingStatus = err; +#else + // The target does not supports WiFiNetwork. + // return "Command not found" error. + response.networkingStatus = NetworkCommissioningStatus::kUnknownError; +#endif + apCommandHandler->AddResponseData(commandPath, response); +} + +namespace { +CHIP_ERROR DoConnectNetwork(NetworkInfo * network) +{ + switch (network->mNetworkType) + { + case NetworkType::kThread: +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +// TODO: On linux, we are using Reset() instead of Detach() to disable thread network, which is not expected. +// Upstream issue: https://github.com/openthread/ot-br-posix/issues/755 +#if !CHIP_DEVICE_LAYER_TARGET_LINUX + ReturnErrorOnFailure(DeviceLayer::ThreadStackMgr().SetThreadEnabled(false)); +#endif + ReturnErrorOnFailure(DeviceLayer::ThreadStackMgr().SetThreadProvision(network->mData.mThread.AsByteSpan())); + ReturnErrorOnFailure(DeviceLayer::ThreadStackMgr().SetThreadEnabled(true)); +#else + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +#endif + break; + case NetworkType::kWiFi: +#if defined(CHIP_DEVICE_LAYER_TARGET) + { + // TODO: Currently, DeviceNetworkProvisioningDelegateImpl assumes that ssid and credentials are null terminated strings, + // which is not correct, this should be changed once we have better method for commissioning wifi networks. + //DeviceLayer::DeviceNetworkProvisioningDelegateImpl deviceDelegate; + //ReturnErrorOnFailure(deviceDelegate.ProvisionWiFi(reinterpret_cast(network->mData.mWiFi.mSSID), + //reinterpret_cast(network->mData.mWiFi.mCredentials))); + break; + } +#else + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +#endif + break; + case NetworkType::kEthernet: + case NetworkType::kUndefined: + default: + return CHIP_ERROR_NOT_IMPLEMENTED; + } + network->mEnabled = true; + return CHIP_NO_ERROR; +} +} // namespace + +void OnConnectNetworkCommandCallbackInternal(app::CommandHandler * apCommandHandler, const app::ConcreteCommandPath & commandPath, + ByteSpan networkID, uint64_t breadcrumb, uint32_t timeoutMs) +{ + Commands::ConnectNetworkResponse::Type response; + size_t networkSeq; + NetworkCommissioningStatus err = NetworkCommissioningStatus::kNetworkIDNotFound; + + for (networkSeq = 0; networkSeq < kMaxNetworks; networkSeq++) + { + if (sNetworks[networkSeq].mNetworkIDLen == networkID.size() && + sNetworks[networkSeq].mNetworkType != NetworkType::kUndefined && + memcmp(sNetworks[networkSeq].mNetworkID, networkID.data(), networkID.size()) == 0) + { + // TODO: Currently, we cannot figure out the detailed error from network provisioning on DeviceLayer, we should + // implement this in device layer. + VerifyOrExit(DoConnectNetwork(&sNetworks[networkSeq]) == CHIP_NO_ERROR, + err = NetworkCommissioningStatus::kUnknownError); + ExitNow(err = NetworkCommissioningStatus::kSuccess); + } + } + // TODO: We should encode response command here. +exit: + if (err == NetworkCommissioningStatus::kSuccess) + { + DeviceLayer::DeviceControlServer::DeviceControlSvr().ConnectNetworkForOperational(networkID); + } + response.networkingStatus = err; + apCommandHandler->AddResponseData(commandPath, response); +} + +} // namespace NetworkCommissioning +} // namespace Clusters +} // namespace app +} // namespace chip diff --git a/src/platform/Beken/BUILD.gn b/src/platform/Beken/BUILD.gn index 5e237b63f410d8..7367fd1d26a177 100755 --- a/src/platform/Beken/BUILD.gn +++ b/src/platform/Beken/BUILD.gn @@ -32,8 +32,6 @@ static_library("Beken") { "ConfigurationManagerImpl.h", "ConnectivityManagerImpl.cpp", "ConnectivityManagerImpl.h", - "DeviceNetworkProvisioningDelegateImpl.cpp", - "DeviceNetworkProvisioningDelegateImpl.h", "DiagnosticDataProviderImpl.cpp", "DiagnosticDataProviderImpl.h", "KeyValueStoreManagerImpl.cpp", @@ -42,10 +40,9 @@ static_library("Beken") { "LwIPCoreLock.cpp", "PlatformManagerImpl.cpp", "PlatformManagerImpl.h", - "ServiceProvisioning.cpp", - "ServiceProvisioning.h", "SoftwareUpdateManagerImpl.h", "SystemPlatformConfig.h", + "NetworkCommissioningWiFiDriver.cpp", "CHIPMem-Platform.cpp", ] diff --git a/src/platform/Beken/BekenConfig.cpp b/src/platform/Beken/BekenConfig.cpp index a900c77f2ac099..8015ee3696d499 100644 --- a/src/platform/Beken/BekenConfig.cpp +++ b/src/platform/Beken/BekenConfig.cpp @@ -1,6 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2020-2022 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -59,6 +59,10 @@ const BekenConfig::Key BekenConfig::kConfigKey_HardwareVersion = { kConfigNa const BekenConfig::Key BekenConfig::kConfigKey_ManufacturingDate = { kConfigNamespace_ChipFactory, "mfg-date" }; const BekenConfig::Key BekenConfig::kConfigKey_SetupPinCode = { kConfigNamespace_ChipFactory, "pin-code" }; const BekenConfig::Key BekenConfig::kConfigKey_SetupDiscriminator = { kConfigNamespace_ChipFactory, "discriminator" }; +const BekenConfig::Key BekenConfig::kConfigKey_Spake2pIterationCount = { kConfigNamespace_ChipFactory, "iteration-count" }; +const BekenConfig::Key BekenConfig::kConfigKey_Spake2pSalt = { kConfigNamespace_ChipFactory, "salt" }; +const BekenConfig::Key BekenConfig::kConfigKey_Spake2pVerifier = { kConfigNamespace_ChipFactory, "verifier" }; +const BekenConfig::Key BekenConfig::kConfigKey_UniqueId = { kConfigNamespace_ChipFactory, "uniqueId" }; // Keys stored in the chip-config namespace const BekenConfig::Key BekenConfig::kConfigKey_FabricId = { kConfigNamespace_ChipConfig, "fabric-id" }; @@ -75,10 +79,7 @@ const BekenConfig::Key BekenConfig::kConfigKey_OperationalDeviceICACerts = { k const BekenConfig::Key BekenConfig::kConfigKey_OperationalDevicePrivateKey = { kConfigNamespace_ChipConfig, "op-device-key" }; const BekenConfig::Key BekenConfig::kConfigKey_RegulatoryLocation = { kConfigNamespace_ChipConfig, "regulatory-location" }; const BekenConfig::Key BekenConfig::kConfigKey_CountryCode = { kConfigNamespace_ChipConfig, "country-code" }; -const BekenConfig::Key BekenConfig::kConfigKey_ActiveLocale = { kConfigNamespace_ChipConfig, "active-locale" }; const BekenConfig::Key BekenConfig::kConfigKey_Breadcrumb = { kConfigNamespace_ChipConfig, "breadcrumb" }; -const BekenConfig::Key BekenConfig::kConfigKey_HourFormat = { kConfigNamespace_ChipConfig, "hour-format" }; -const BekenConfig::Key BekenConfig::kConfigKey_CalendarType = { kConfigNamespace_ChipConfig, "calendar-type" }; // Keys stored in the Chip-counters namespace const BekenConfig::Key BekenConfig::kCounterKey_RebootCount = { kConfigNamespace_ChipCounters, "reboot-count" }; diff --git a/src/platform/Beken/BekenConfig.h b/src/platform/Beken/BekenConfig.h index 342ac69195c174..bc9317a858df32 100755 --- a/src/platform/Beken/BekenConfig.h +++ b/src/platform/Beken/BekenConfig.h @@ -63,12 +63,13 @@ class BekenConfig static const Key kConfigKey_SetupDiscriminator; static const Key kConfigKey_RegulatoryLocation; static const Key kConfigKey_CountryCode; - static const Key kConfigKey_ActiveLocale; static const Key kConfigKey_Breadcrumb; - static const Key kConfigKey_HourFormat; - static const Key kConfigKey_CalendarType; + static const Key kConfigKey_Spake2pIterationCount; + static const Key kConfigKey_Spake2pSalt; + static const Key kConfigKey_Spake2pVerifier; // Counter keys + static const Key kConfigKey_UniqueId; static const Key kCounterKey_RebootCount; static const Key kCounterKey_UpTime; static const Key kCounterKey_TotalOperationalHours; diff --git a/src/platform/Beken/ConnectivityManagerImpl.cpp b/src/platform/Beken/ConnectivityManagerImpl.cpp old mode 100644 new mode 100755 index 85d8509f8ca1c7..1445912a71eca4 --- a/src/platform/Beken/ConnectivityManagerImpl.cpp +++ b/src/platform/Beken/ConnectivityManagerImpl.cpp @@ -43,6 +43,7 @@ #include "wlan_ui_pub.h" #include "flash_namespace_value.h" +#include "NetworkCommissioningDriver.h" #define BEKEN_WIFI_INFO "BekenWiFi" static uint32_t dwWifiExit = 0; @@ -346,6 +347,7 @@ void ConnectivityManagerImpl::wlan_status_cb(void *ctxt) break; case RW_EVT_STA_CONNECTED: ChipLogProgress(DeviceLayer, "RW_EVT_STA_CONNECTED"); + NetworkCommissioning::BekenWiFiDriver::GetInstance().OnConnectWiFiNetwork(); break; case RW_EVT_STA_DISCONNECTED: stationConnected = false; diff --git a/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp b/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp deleted file mode 100644 index 7c3a4d73c3968b..00000000000000 --- a/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "DeviceNetworkProvisioningDelegateImpl.h" -#include "ServiceProvisioning.h" - -namespace chip { -namespace DeviceLayer { - -CHIP_ERROR DeviceNetworkProvisioningDelegateImpl::_ProvisionWiFiNetwork(const char * ssid, const char * key) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - ChipLogProgress(NetworkProvisioning, "BekenNetworkProvisioningDelegate: SSID: %s", ssid); - err = SetWiFiStationProvisioning(ssid, key); - if (err != CHIP_NO_ERROR) - { - ChipLogError(NetworkProvisioning, "Failed to connect to WiFi network: %s", chip::ErrorStr(err)); - } - - return err; -} - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.h b/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.h deleted file mode 100644 index 2492fba40c367a..00000000000000 --- a/src/platform/Beken/DeviceNetworkProvisioningDelegateImpl.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -namespace chip { -namespace DeviceLayer { - -namespace Internal { - -template -class GenericDeviceNetworkProvisioningDelegateImpl; - -} // namespace Internal - -class DeviceNetworkProvisioningDelegateImpl final - : public Internal::GenericDeviceNetworkProvisioningDelegateImpl -{ -private: - friend class GenericDeviceNetworkProvisioningDelegateImpl; - - CHIP_ERROR _ProvisionWiFiNetwork(const char * ssid, const char * passwd); - CHIP_ERROR _ProvisionThreadNetwork(ByteSpan threadData) { return CHIP_ERROR_NOT_IMPLEMENTED; } -}; - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/Beken/KeyValueStoreManagerImpl.cpp b/src/platform/Beken/KeyValueStoreManagerImpl.cpp index aadd73ac31dcce..cef17544bf61fb 100755 --- a/src/platform/Beken/KeyValueStoreManagerImpl.cpp +++ b/src/platform/Beken/KeyValueStoreManagerImpl.cpp @@ -45,14 +45,14 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t // future if this is needed. return (err = CHIP_ERROR_INVALID_ARGUMENT); } - + if(read_bytes_size == NULL) { - ret = bk_read_data( key,key,(char *) value,value_size,&dwTeReadBytes); + ret = bk_read_data(GetKVNameSpaceName(key), key, (char *) value, value_size, &dwTeReadBytes); } else { - ret = bk_read_data( key,key,(char *) value,value_size,(uint32_t *)read_bytes_size); + ret = bk_read_data(GetKVNameSpaceName(key), key, (char *) value, value_size, (uint32_t *)read_bytes_size); } if (ret == kNoErr) @@ -75,12 +75,13 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, { CHIP_ERROR err = CHIP_NO_ERROR; uint32_t ret = 0; - + bk_printf("put key:%s \r\n", key); if (!value) { return (err = CHIP_ERROR_INVALID_ARGUMENT); } - ret = bk_write_data( key,key, (char *)value,value_size); + + ret = bk_write_data(GetKVNameSpaceName(key), key, (char *)value, value_size); if (ret == kNoErr) { @@ -99,7 +100,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) uint32_t ret = 0; CHIP_ERROR err = CHIP_NO_ERROR; - ret = bk_clean_data ( key,key); + ret = bk_clean_data (GetKVNameSpaceName(key), key); if (kNoErr == ret) { @@ -113,6 +114,21 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) return err; } +const char* KeyValueStoreManagerImpl::GetKVNameSpaceName(const char *key) +{ + int idx = 0; + const char* BekenkeyValueNameSpace[] = {"BEKEN0", "BEKEN1", "BEKEN2", "BEKEN3", "BEKEN4"};//Put all key-value date into this namespace + if (key != NULL) + { + int i, len = strlen(key); + int sum = 0; + for (i = 0; i < len; i += 2) + sum += key[i]; + idx = sum % (sizeof(BekenkeyValueNameSpace)/sizeof(BekenkeyValueNameSpace[0])); + } + return BekenkeyValueNameSpace[idx]; +} + } // namespace PersistedStorage } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/Beken/KeyValueStoreManagerImpl.h b/src/platform/Beken/KeyValueStoreManagerImpl.h index e86c244d71a369..8e63c79baa929c 100755 --- a/src/platform/Beken/KeyValueStoreManagerImpl.h +++ b/src/platform/Beken/KeyValueStoreManagerImpl.h @@ -24,6 +24,9 @@ #pragma once +#include + + namespace chip { namespace DeviceLayer { namespace PersistedStorage { @@ -49,6 +52,7 @@ class KeyValueStoreManagerImpl final : public KeyValueStoreManager friend KeyValueStoreManagerImpl & KeyValueStoreMgrImpl(); static KeyValueStoreManagerImpl sInstance; + const char* GetKVNameSpaceName(const char * key); }; /** diff --git a/src/platform/Beken/NetworkCommissioningDriver.h b/src/platform/Beken/NetworkCommissioningDriver.h new file mode 100755 index 00000000000000..2219e8c33b36ae --- /dev/null +++ b/src/platform/Beken/NetworkCommissioningDriver.h @@ -0,0 +1,101 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include + +namespace chip { +namespace DeviceLayer { +namespace NetworkCommissioning { + +namespace { +constexpr uint8_t kMaxWiFiNetworks = 1; +constexpr uint8_t kWiFiScanNetworksTimeOutSeconds = 10; +constexpr uint8_t kWiFiConnectNetworkTimeoutSeconds = 20; +} // namespace + +class BekenWiFiDriver final : public WiFiDriver +{ +public: + class WiFiNetworkIterator final : public NetworkIterator + { + public: + WiFiNetworkIterator(BekenWiFiDriver * aDriver) : mDriver(aDriver) {} + size_t Count() override; + bool Next(Network & item) override; + void Release() override { delete this; } + ~WiFiNetworkIterator() = default; + + private: + BekenWiFiDriver * mDriver; + bool mExhausted = false; + }; + + struct WiFiNetwork + { + char ssid[DeviceLayer::Internal::kMaxWiFiSSIDLength]; + uint8_t ssidLen = 0; + char credentials[DeviceLayer::Internal::kMaxWiFiKeyLength]; + uint8_t credentialsLen = 0; + }; + + + + // BaseDriver + NetworkIterator * GetNetworks() override { return new WiFiNetworkIterator(this); } + CHIP_ERROR Init() override; + CHIP_ERROR Shutdown() override; + + // WirelessDriver + uint8_t GetMaxNetworks() override { return kMaxWiFiNetworks; } + uint8_t GetScanNetworkTimeoutSeconds() override { return kWiFiScanNetworksTimeOutSeconds; } + uint8_t GetConnectNetworkTimeoutSeconds() override { return kWiFiConnectNetworkTimeoutSeconds; } + + CHIP_ERROR CommitConfiguration() override; + CHIP_ERROR RevertConfiguration() override; + + Status RemoveNetwork(ByteSpan networkId) override; + Status ReorderNetwork(ByteSpan networkId, uint8_t index) override; + void ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) override; + + // WiFiDriver + Status AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials) override; + void ScanNetworks(ByteSpan ssid, ScanCallback * callback) override; + + CHIP_ERROR ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, const char * key, uint8_t keyLen); + void OnConnectWiFiNetwork(); + void OnScanWiFiNetworkDone(); + static BekenWiFiDriver & GetInstance() + { + static BekenWiFiDriver instance; + return instance; + } + +private: + bool NetworkMatch(const WiFiNetwork & network, ByteSpan networkId); + CHIP_ERROR StartScanWiFiNetworks(ByteSpan ssid); + + WiFiNetworkIterator mWiFiIterator = WiFiNetworkIterator(this); + WiFiNetwork mSavedNetwork; + WiFiNetwork mStagingNetwork; + ScanCallback * mpScanCallback; + ConnectCallback * mpConnectCallback; +}; + +} // namespace NetworkCommissioning +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp b/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp new file mode 100755 index 00000000000000..c0a420d72ca518 --- /dev/null +++ b/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp @@ -0,0 +1,294 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include +#include + +#include "wlan_ui_pub.h" + +using namespace ::chip; +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +namespace chip { +namespace DeviceLayer { +namespace NetworkCommissioning { + +namespace { +constexpr char kWiFiSSIDKeyName[] = "wifi-ssid"; +constexpr char kWiFiCredentialsKeyName[] = "wifi-pass"; +static uint8_t WiFiSSIDStr[DeviceLayer::Internal::kMaxWiFiSSIDLength]; +} // namespace + +CHIP_ERROR BekenWiFiDriver::Init() +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::Init\r\n"); + CHIP_ERROR err; + size_t ssidLen = 0; + size_t credentialsLen = 0; + + err = PersistedStorage::KeyValueStoreMgr().Get(kWiFiCredentialsKeyName, mSavedNetwork.credentials, + sizeof(mSavedNetwork.credentials), &credentialsLen); + if (err == CHIP_ERROR_NOT_FOUND) + { + return CHIP_NO_ERROR; + } + + err = PersistedStorage::KeyValueStoreMgr().Get(kWiFiSSIDKeyName, mSavedNetwork.ssid, sizeof(mSavedNetwork.ssid), &ssidLen); + if (err == CHIP_ERROR_NOT_FOUND) + { + return CHIP_NO_ERROR; + } + mSavedNetwork.credentialsLen = credentialsLen; + mSavedNetwork.ssidLen = ssidLen; + + mStagingNetwork = mSavedNetwork; + mpScanCallback = nullptr; + mpConnectCallback = nullptr; + return err; +} + +CHIP_ERROR BekenWiFiDriver::Shutdown() +{ + return CHIP_NO_ERROR; +} + +CHIP_ERROR BekenWiFiDriver::CommitConfiguration() +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::CommitConfiguration\r\n"); + ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Put(kWiFiSSIDKeyName, mStagingNetwork.ssid, mStagingNetwork.ssidLen)); + ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Put(kWiFiCredentialsKeyName, mStagingNetwork.credentials, + mStagingNetwork.credentialsLen)); + mSavedNetwork = mStagingNetwork; + return CHIP_NO_ERROR; +} + +CHIP_ERROR BekenWiFiDriver::RevertConfiguration() +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::RevertConfiguration\r\n"); + mStagingNetwork = mSavedNetwork; + return CHIP_NO_ERROR; +} + +bool BekenWiFiDriver::NetworkMatch(const WiFiNetwork & network, ByteSpan networkId) +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::NetworkMatch\r\n"); + return networkId.size() == network.ssidLen && memcmp(networkId.data(), network.ssid, network.ssidLen) == 0; +} + +Status BekenWiFiDriver::AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials) +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::AddOrUpdateNetwork\r\n"); + VerifyOrReturnError(mStagingNetwork.ssidLen == 0 || NetworkMatch(mStagingNetwork, ssid), Status::kBoundsExceeded); + VerifyOrReturnError(credentials.size() <= sizeof(mStagingNetwork.credentials), Status::kOutOfRange); + VerifyOrReturnError(ssid.size() <= sizeof(mStagingNetwork.ssid), Status::kOutOfRange); + + memcpy(mStagingNetwork.credentials, credentials.data(), credentials.size()); + mStagingNetwork.credentialsLen = static_cast(credentials.size()); + + memcpy(mStagingNetwork.ssid, ssid.data(), ssid.size()); + mStagingNetwork.ssidLen = static_cast(ssid.size()); + + return Status::kSuccess; +} + +Status BekenWiFiDriver::RemoveNetwork(ByteSpan networkId) +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::RemoveNetwork\r\n"); + VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); + + // Use empty ssid for representing invalid network + mStagingNetwork.ssidLen = 0; + return Status::kSuccess; +} + +Status BekenWiFiDriver::ReorderNetwork(ByteSpan networkId, uint8_t index) +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::ReorderNetwork\r\n"); + // Only one network is supported now + VerifyOrReturnError(index == 0, Status::kOutOfRange); + VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); + return Status::kSuccess; +} + +CHIP_ERROR BekenWiFiDriver::ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, const char * key, uint8_t keyLen) +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::ConnectWiFiNetwork....ssid:%s", ssid); + ReturnErrorOnFailure(ConnectivityMgr().SetWiFiStationMode(ConnectivityManager::kWiFiStationMode_Disabled)); + + network_InitTypeDef_st network_cfg; + + memset(&network_cfg, 0, sizeof(network_InitTypeDef_st)); + + network_cfg.wifi_mode = BK_STATION; + memcpy(network_cfg.wifi_ssid, ssid, ssidLen); + memcpy(network_cfg.wifi_key, key, keyLen); + network_cfg.dhcp_mode = DHCP_CLIENT; + bk_wlan_start(&network_cfg); + + return ConnectivityMgr().SetWiFiStationMode(ConnectivityManager::kWiFiStationMode_Enabled); +} + +void BekenWiFiDriver::OnConnectWiFiNetwork() +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::OnConnectWiFiNetwork\r\n"); + if (mpConnectCallback) + { + mpConnectCallback->OnResult(Status::kSuccess, CharSpan(), 0); + mpConnectCallback = nullptr; + } +} + +void BekenWiFiDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + Status networkingStatus = Status::kSuccess; + + VerifyOrExit(NetworkMatch(mStagingNetwork, networkId), networkingStatus = Status::kNetworkIDNotFound); + VerifyOrExit(mpConnectCallback == nullptr, networkingStatus = Status::kUnknownError); + ChipLogProgress(NetworkProvisioning, "Beken NetworkCommissioningDelegate: SSID: %s", networkId.data()); + + err = ConnectWiFiNetwork(reinterpret_cast(mStagingNetwork.ssid), mStagingNetwork.ssidLen, + reinterpret_cast(mStagingNetwork.credentials), mStagingNetwork.credentialsLen); + mpConnectCallback = callback; +exit: + if (err != CHIP_NO_ERROR) + { + networkingStatus = Status::kUnknownError; + } + if (networkingStatus != Status::kSuccess) + { + ChipLogError(NetworkProvisioning, "Failed to connect to WiFi network:%s", chip::ErrorStr(err)); + mpConnectCallback = nullptr; + callback->OnResult(networkingStatus, CharSpan(), 0); + } +} + +CHIP_ERROR BekenWiFiDriver::StartScanWiFiNetworks(ByteSpan ssid) +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::StartScanWiFiNetworks\r\n"); + CHIP_ERROR err = CHIP_NO_ERROR; + if (ssid.data())//directed scanning + { + uint8_t **ssid_array; + uint8_t * oob_ssid; + memcpy(oob_ssid,ssid.data(),ssid.size()); + ssid_array = &oob_ssid; + ChipLogProgress(NetworkProvisioning, "StartScanWiFiNetworks... ssid:%s\r\n", ssid.data()); + bk_wlan_start_assign_scan(ssid_array, 1); + } + else//non-directed scanning + { + bk_wlan_start_scan(); + } + + return CHIP_NO_ERROR; +} + +void BekenWiFiDriver::OnScanWiFiNetworkDone() +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::OnScanWiFiNetworkDone\r\n"); + char scan_rst_ap_num = 0; + scan_rst_ap_num = bk_wlan_get_scan_ap_result_numbers(); + if(scan_rst_ap_num == 0) + { + os_printf("NULL AP\r\n"); + return; + } + sta_scan_res *scan_rst_table = ( sta_scan_res *)pvPortMalloc(sizeof(sta_scan_res) * scan_rst_ap_num); + if(scan_rst_table == NULL) + { + os_printf("scan_rst_table malloc failed!\r\n"); + return; + } + bk_wlan_get_scan_ap_result(scan_rst_table, scan_rst_ap_num); + +} + +void BekenWiFiDriver::ScanNetworks(ByteSpan ssid, WiFiDriver::ScanCallback * callback) +{ + if (callback != nullptr) + { + mpScanCallback = callback; + if (StartScanWiFiNetworks(ssid) != CHIP_NO_ERROR) + { + mpScanCallback = nullptr; + callback->OnFinished(Status::kUnknownError, CharSpan(), nullptr); + } + } +} + +CHIP_ERROR GetConnectedNetwork(Network & network) +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver GetConnectedNetwork\r\n"); +#ifdef FANG + wifi_ap_record_t ap_info; + esp_err_t err; + err = esp_wifi_sta_get_ap_info(&ap_info); + if (err != ESP_OK) + { + return chip::DeviceLayer::Internal::ESP32Utils::MapError(err); + } + uint8_t length = strnlen(reinterpret_cast(ap_info.ssid), DeviceLayer::Internal::kMaxWiFiSSIDLength); + if (length > sizeof(network.networkID)) + { + return CHIP_ERROR_INTERNAL; + } + memcpy(network.networkID, ap_info.ssid, length); + network.networkIDLen = length; +#endif + return CHIP_NO_ERROR; +} + +size_t BekenWiFiDriver::WiFiNetworkIterator::Count() +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::WiFiNetworkIterator::Count\r\n"); + return mDriver->mStagingNetwork.ssidLen == 0 ? 0 : 1; +} + +bool BekenWiFiDriver::WiFiNetworkIterator::Next(Network & item) +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::WiFiNetworkIterator::Next\r\n"); + if (mExhausted || mDriver->mStagingNetwork.ssidLen == 0) + { + return false; + } + memcpy(item.networkID, mDriver->mStagingNetwork.ssid, mDriver->mStagingNetwork.ssidLen); + item.networkIDLen = mDriver->mStagingNetwork.ssidLen; + item.connected = false; + mExhausted = true; + + Network connectedNetwork; + CHIP_ERROR err = GetConnectedNetwork(connectedNetwork); + if (err == CHIP_NO_ERROR) + { + if (connectedNetwork.networkIDLen == item.networkIDLen && + memcmp(connectedNetwork.networkID, item.networkID, item.networkIDLen) == 0) + { + item.connected = true; + } + } + return true; +} + +} // namespace NetworkCommissioning +} // namespace DeviceLayer +} // namespace chip +#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI diff --git a/src/platform/Beken/ServiceProvisioning.cpp b/src/platform/Beken/ServiceProvisioning.cpp deleted file mode 100755 index a0610c3b9acd69..00000000000000 --- a/src/platform/Beken/ServiceProvisioning.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "ServiceProvisioning.h" - -#include "include.h" -#include "str_pub.h" -#include "mem_pub.h" -#include "wlan_ui_pub.h" - -using namespace ::chip::DeviceLayer; - -CHIP_ERROR SetWiFiStationProvisioning(const char * ssid, const char * key) -{ - ConnectivityMgr().SetWiFiStationMode(ConnectivityManager::kWiFiStationMode_Disabled); - network_InitTypeDef_st network_cfg; - - memset(&network_cfg, 0, sizeof(network_InitTypeDef_st)); - - network_cfg.wifi_mode = BK_STATION; - strcpy(network_cfg.wifi_ssid, ssid); - strcpy(network_cfg.wifi_key, key); - network_cfg.dhcp_mode = DHCP_CLIENT; - bk_wlan_start(&network_cfg); - ConnectivityMgr().SetWiFiStationMode(ConnectivityManager::kWiFiStationMode_Enabled); - - return CHIP_NO_ERROR; -} diff --git a/src/platform/Beken/ServiceProvisioning.h b/src/platform/Beken/ServiceProvisioning.h deleted file mode 100644 index 7ac2a8375addae..00000000000000 --- a/src/platform/Beken/ServiceProvisioning.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _SERVICE_PROVISIONING_H -#define _SERVICE_PROVISIONING_H - -#include - -CHIP_ERROR SetWiFiStationProvisioning(const char * ssid, const char * key); - -#endif // _SERVICE_PROVISIONING_H From b353e83132b3f41caadd2321a1706fce299d5d82 Mon Sep 17 00:00:00 2001 From: "jun.luo" Date: Tue, 22 Feb 2022 13:48:55 +0800 Subject: [PATCH 05/20] Fix the SoftwareDiagnostics attributes implementation --- src/platform/Beken/DiagnosticDataProviderImpl.cpp | 5 +++-- src/platform/Beken/NetworkCommissioningWiFiDriver.cpp | 1 - 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.cpp b/src/platform/Beken/DiagnosticDataProviderImpl.cpp index 15a0036bbf4c9a..0054ba07cdf0a5 100644 --- a/src/platform/Beken/DiagnosticDataProviderImpl.cpp +++ b/src/platform/Beken/DiagnosticDataProviderImpl.cpp @@ -44,13 +44,14 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeap CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) { - //currentHeapUsed = xPortGetTotalHeapSize() - xPortGetFreeHeapSize(); + currentHeapUsed = prvHeapGetTotalSize() - xPortGetFreeHeapSize(); + ChipLogProgress(DeviceLayer, "beken-GetCurrentHeapUsed\n"); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) { - // currentHeapHighWatermark = xPortGetTotalHeapSize() - xPortGetMinimumEverFreeHeapSize(); + currentHeapHighWatermark = prvHeapGetTotalSize() - xPortGetMinimumEverFreeHeapSize(); return CHIP_NO_ERROR; } diff --git a/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp b/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp index c0a420d72ca518..2bd1260d063557 100755 --- a/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp +++ b/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp @@ -163,7 +163,6 @@ void BekenWiFiDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callb VerifyOrExit(NetworkMatch(mStagingNetwork, networkId), networkingStatus = Status::kNetworkIDNotFound); VerifyOrExit(mpConnectCallback == nullptr, networkingStatus = Status::kUnknownError); - ChipLogProgress(NetworkProvisioning, "Beken NetworkCommissioningDelegate: SSID: %s", networkId.data()); err = ConnectWiFiNetwork(reinterpret_cast(mStagingNetwork.ssid), mStagingNetwork.ssidLen, reinterpret_cast(mStagingNetwork.credentials), mStagingNetwork.credentialsLen); From 5de404cd81b1201bc169839a2fc1a94dfe88b965 Mon Sep 17 00:00:00 2001 From: "jun.luo" Date: Wed, 23 Feb 2022 19:23:46 +0800 Subject: [PATCH 06/20] 1. Add SystemTimer support 2. Fix TC-WIFIDIAG-WiFiDiagnostics cases --- src/platform/Beken/BUILD.gn | 2 +- .../Beken/DiagnosticDataProviderImpl.cpp | 197 ++++++------------ src/platform/Beken/Logging.cpp | 1 + src/platform/Beken/PlatformManagerImpl.cpp | 3 + src/platform/Beken/SystemTimeSupport.cpp | 81 +++++++ 5 files changed, 155 insertions(+), 129 deletions(-) create mode 100644 src/platform/Beken/SystemTimeSupport.cpp diff --git a/src/platform/Beken/BUILD.gn b/src/platform/Beken/BUILD.gn index 7367fd1d26a177..fabee4f07cde52 100755 --- a/src/platform/Beken/BUILD.gn +++ b/src/platform/Beken/BUILD.gn @@ -20,7 +20,7 @@ assert(chip_device_platform == "beken") static_library("Beken") { sources = [ - "../FreeRTOS/SystemTimeSupport.cpp", + "SystemTimeSupport.cpp", "../SingletonConfigurationManager.cpp", "BekenConfig.cpp", "BekenConfig.h", diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.cpp b/src/platform/Beken/DiagnosticDataProviderImpl.cpp index 0054ba07cdf0a5..2da1e3b1cca277 100644 --- a/src/platform/Beken/DiagnosticDataProviderImpl.cpp +++ b/src/platform/Beken/DiagnosticDataProviderImpl.cpp @@ -27,6 +27,9 @@ #include #include +#include "wlan_ui_pub.h" +#include "net.h" + namespace chip { namespace DeviceLayer { @@ -45,7 +48,6 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeap CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) { currentHeapUsed = prvHeapGetTotalSize() - xPortGetFreeHeapSize(); - ChipLogProgress(DeviceLayer, "beken-GetCurrentHeapUsed\n"); return CHIP_NO_ERROR; } @@ -119,52 +121,26 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(uint8_t & bootReason) CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** netifpp) { -#if 0 - CHIP_ERROR err = CHIP_ERROR_READ_FAILED; - NetworkInterface * head = NULL; - struct ifaddrs * ifaddr = nullptr; + NetworkInterface * ifp = new NetworkInterface(); + struct netif *netif; - if (xnetif == NULL) + netif = ( struct netif*)net_get_sta_handle();//assume only on station mode + if(netif == NULL || ifp == NULL) { - ChipLogError(DeviceLayer, "Failed to get network interfaces"); - } - else - { - for (struct netif * ifa = xnetif; ifa != NULL; ifa = ifa->next) - { - NetworkInterface * ifp = new NetworkInterface(); - - strncpy(ifp->Name, ifa->name, Inet::InterfaceId::kMaxIfNameLength); - ifp->Name[Inet::InterfaceId::kMaxIfNameLength - 1] = '\0'; - - ifp->name = CharSpan(ifp->Name, strlen(ifp->Name)); - ifp->fabricConnected = true; - if ((ifa->flags) & NETIF_FLAG_ETHERNET) - ifp->type = EMBER_ZCL_INTERFACE_TYPE_ETHERNET; - else - ifp->type = EMBER_ZCL_INTERFACE_TYPE_WI_FI; - ifp->offPremiseServicesReachableIPv4 = false; - ifp->offPremiseServicesReachableIPv6 = false; - - memcpy(ifp->MacAddress, ifa->hwaddr, sizeof(ifa->hwaddr)); - - if (0) - { - ChipLogError(DeviceLayer, "Failed to get network hardware address"); - } - else - { - // Set 48-bit IEEE MAC Address - ifp->hardwareAddress = ByteSpan(ifp->MacAddress, 6); - } - - ifp->Next = head; - head = ifp; - } + ChipLogError(DeviceLayer, "Can't get the netif instance"); + *netifpp = NULL; + return CHIP_ERROR_INTERNAL; } - *netifpp = head; -#endif + strncpy(ifp->Name, netif->hostname, Inet::InterfaceId::kMaxIfNameLength); + ifp->Name[Inet::InterfaceId::kMaxIfNameLength - 1] = '\0'; + ifp->name = CharSpan::fromCharString(ifp->Name); + ifp->fabricConnected = true; + ifp->type = EMBER_ZCL_INTERFACE_TYPE_WI_FI; + ifp->offPremiseServicesReachableIPv4.SetNonNull(false); + ifp->offPremiseServicesReachableIPv6.SetNonNull(false); + memcpy(ifp->MacAddress, netif->hwaddr, sizeof(netif->hwaddr)); + *netifpp = ifp; return CHIP_NO_ERROR; } @@ -181,126 +157,91 @@ void DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * net #if CHIP_DEVICE_CONFIG_ENABLE_WIFI CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(ByteSpan & BssId) { -#if 0 - CHIP_ERROR err = CHIP_ERROR_READ_FAILED; - static uint8_t ameba_bssid[6]; + LinkStatusTypeDef linkStatus; - if (wifi_get_ap_bssid(ameba_bssid) == 0) + memset(&linkStatus, 0x0, sizeof(LinkStatusTypeDef)); + if (0 == bk_wlan_get_link_status(&linkStatus)) { - err = CHIP_NO_ERROR; - ChipLogProgress(DeviceLayer, "%02x,%02x,%02x,%02x,%02x,%02x\n", ameba_bssid[0], ameba_bssid[1], ameba_bssid[2], - ameba_bssid[3], ameba_bssid[4], ameba_bssid[5]); + BssId = ByteSpan(linkStatus.bssid, 6); + } + else + { + ChipLogError(DeviceLayer, "GetWiFiBssId Not Supported"); + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } - - BssId = ameba_bssid; -#endif return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion) { - // Support 802.11a/n Wi-Fi in AmebaD chipset + // Support 802.11a/n Wi-Fi in Beken chipset wifiVersion = EMBER_ZCL_WI_FI_VERSION_TYPE_802__11N; return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(uint8_t & securityType) { -#if 0 - unsigned int _auth_type; - unsigned short _security = 0; - rtw_wifi_setting_t setting; - -#ifdef CONFIG_PLATFORM_8721D - if (wext_get_enc_ext("wlan0", &_security, &setting.key_idx, setting.password) < 0) + int cipher_type; + cipher_type = bk_sta_cipher_type(); + switch(cipher_type) { - securityType = 0; - } - else - { - switch (_security) - { - case IW_ENCODE_ALG_NONE: - setting.security_type = EMBER_ZCL_SECURITY_TYPE_NONE; - break; - case IW_ENCODE_ALG_WEP: - setting.security_type = EMBER_ZCL_SECURITY_TYPE_WEP; - break; - case IW_ENCODE_ALG_TKIP: - setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA; - break; - case IW_ENCODE_ALG_CCMP: - setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA2; - break; - default: - setting.security_type = EMBER_ZCL_SECURITY_TYPE_UNSPECIFIED; + case BK_SECURITY_TYPE_NONE: + securityType = EMBER_ZCL_SECURITY_TYPE_NONE; break; - } - securityType = setting.security_type; - } -#else - wext_get_enc_ext("wlan0", &_security, &setting.key_idx, setting.password); - if (wext_get_auth_type("wlan0", &_auth_type) < 0) - { - securityType = 0; - } - else - { - switch (_security) - { - case IW_ENCODE_ALG_NONE: - setting.security_type = EMBER_ZCL_SECURITY_TYPE_NONE; + case BK_SECURITY_TYPE_WEP : + securityType = EMBER_ZCL_SECURITY_TYPE_WEP; break; - case IW_ENCODE_ALG_WEP: - setting.security_type = EMBER_ZCL_SECURITY_TYPE_WEP; + case BK_SECURITY_TYPE_WPA_TKIP: + case BK_SECURITY_TYPE_WPA_AES: + securityType = EMBER_ZCL_SECURITY_TYPE_WPA; break; - case IW_ENCODE_ALG_TKIP: - if (_auth_type == WPA_SECURITY) - setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA; - else if (_auth_type == WPA2_SECURITY) - setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA2; + case BK_SECURITY_TYPE_WPA2_AES: + case BK_SECURITY_TYPE_WPA2_TKIP: + case BK_SECURITY_TYPE_WPA2_MIXED: + securityType = EMBER_ZCL_SECURITY_TYPE_WPA2; break; - case IW_ENCODE_ALG_CCMP: - if (_auth_type == WPA_SECURITY) - setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA; - else if (_auth_type == WPA2_SECURITY) - setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA2; - else if (_auth_type == WPA3_SECURITY) - setting.security_type = EMBER_ZCL_SECURITY_TYPE_WPA3; + case BK_SECURITY_TYPE_WPA3_SAE: + case BK_SECURITY_TYPE_WPA3_WPA2_MIXED: + securityType = EMBER_ZCL_SECURITY_TYPE_WPA3; break; + case BK_SECURITY_TYPE_AUTO: default: - setting.security_type = EMBER_ZCL_SECURITY_TYPE_UNSPECIFIED; - break; - } - securityType = setting.security_type; + securityType = EMBER_ZCL_SECURITY_TYPE_UNSPECIFIED; } -#endif -#endif return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) { -#if 0 - unsigned char channel; + LinkStatusTypeDef linkStatus; - if (wext_get_channel("wlan0", &channel) < 0) - channelNumber = 0; + memset(&linkStatus, 0x0, sizeof(LinkStatusTypeDef)); + if(0 == bk_wlan_get_link_status(&linkStatus)) + { + channelNumber = linkStatus.channel; + } else - channelNumber = (uint16_t) channel; -#endif + { + ChipLogError(DeviceLayer, "GetWiFiChannelNumber Not Supported"); + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; + } return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi) { -#if 0 - int _rssi = 0; - if (wifi_get_rssi(&_rssi) < 0) - rssi = 0; + LinkStatusTypeDef linkStatus; + + memset(&linkStatus, 0x0, sizeof(LinkStatusTypeDef)); + if(0 == bk_wlan_get_link_status(&linkStatus)) + { + rssi = linkStatus.wifi_strength; + } else - rssi = _rssi; -#endif + { + ChipLogError(DeviceLayer, "GetWiFiRssi Not Supported"); + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; + } return CHIP_NO_ERROR; } diff --git a/src/platform/Beken/Logging.cpp b/src/platform/Beken/Logging.cpp index 243584dd08f2a6..109998ccc0b095 100644 --- a/src/platform/Beken/Logging.cpp +++ b/src/platform/Beken/Logging.cpp @@ -58,6 +58,7 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) bk_printf("%s %s\r\n", tag, formattedMsg); break; case kLogCategory_Detail: + case kLogCategory_Automation: bk_printf("%s %s\r\n", tag, formattedMsg); break; } diff --git a/src/platform/Beken/PlatformManagerImpl.cpp b/src/platform/Beken/PlatformManagerImpl.cpp index 77fbb00e2e6905..f843c485882e67 100644 --- a/src/platform/Beken/PlatformManagerImpl.cpp +++ b/src/platform/Beken/PlatformManagerImpl.cpp @@ -26,6 +26,7 @@ #include #include +#include #include #include @@ -62,6 +63,8 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) // to finish the initialization process. err = Internal::GenericPlatformManagerImpl_FreeRTOS::_InitChipStack(); SuccessOrExit(err); + err = System::Clock::InitClock_RealTime(); + SuccessOrExit(err); exit: return err; diff --git a/src/platform/Beken/SystemTimeSupport.cpp b/src/platform/Beken/SystemTimeSupport.cpp new file mode 100644 index 00000000000000..9c73735c959565 --- /dev/null +++ b/src/platform/Beken/SystemTimeSupport.cpp @@ -0,0 +1,81 @@ + +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Provides implementations of the CHIP System Layer platform + * time/clock functions that are suitable for use on the Ameba platform. + */ +/* this file behaves like a config.h, comes first */ +#include + +#include "FreeRTOS.h" + +namespace chip { +namespace System { +namespace Clock { + +namespace Internal { +ClockImpl gClockImpl; +} // namespace Internal + +Clock::Milliseconds64 baseTime; + +Microseconds64 ClockImpl::GetMonotonicMicroseconds64(void) +{ + return (Clock::Microseconds64(xTaskGetTickCount()) * kMicrosecondsPerMillisecond); +} + +Milliseconds64 ClockImpl::GetMonotonicMilliseconds64(void) +{ + return (Clock::Milliseconds64(xTaskGetTickCount())); +} + +CHIP_ERROR ClockImpl::GetClock_RealTime(Clock::Microseconds64 & curTime) +{ + curTime = GetMonotonicMicroseconds64(); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR ClockImpl::GetClock_RealTimeMS(Clock::Milliseconds64 & curTime) +{ + curTime = baseTime + GetMonotonicMilliseconds64(); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR ClockImpl::SetClock_RealTime(Clock::Microseconds64 aNewCurTime) +{ + baseTime = Clock::Milliseconds64(aNewCurTime.count() / kMicrosecondsPerMillisecond); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR InitClock_RealTime() +{ + baseTime = Clock::Milliseconds64((static_cast(CHIP_SYSTEM_CONFIG_VALID_REAL_TIME_THRESHOLD) * kMicrosecondsPerMillisecond)); + + return CHIP_NO_ERROR; +} + + +} // namespace Clock +} // namespace System +} // namespace chip From bd865db792b24a22e937563b6a553c80c80eb7be Mon Sep 17 00:00:00 2001 From: "jun.luo" Date: Thu, 24 Feb 2022 14:40:15 +0800 Subject: [PATCH 07/20] Fix TC-WIFIDIAG-3.1,command:reset-counts --- src/platform/Beken/DiagnosticDataProviderImpl.cpp | 6 ++++++ src/platform/Beken/DiagnosticDataProviderImpl.h | 1 + 2 files changed, 7 insertions(+) diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.cpp b/src/platform/Beken/DiagnosticDataProviderImpl.cpp index 2da1e3b1cca277..6dde91026d8e98 100644 --- a/src/platform/Beken/DiagnosticDataProviderImpl.cpp +++ b/src/platform/Beken/DiagnosticDataProviderImpl.cpp @@ -286,6 +286,12 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiOverrunCount(uint64_t & overrunCou overrunCount = 0; return CHIP_NO_ERROR; } + +CHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts() +{ + return CHIP_NO_ERROR; +} + #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI } // namespace DeviceLayer diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.h b/src/platform/Beken/DiagnosticDataProviderImpl.h index 9190c1a3bdc9e8..155b657560c4aa 100644 --- a/src/platform/Beken/DiagnosticDataProviderImpl.h +++ b/src/platform/Beken/DiagnosticDataProviderImpl.h @@ -62,6 +62,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider CHIP_ERROR GetWiFiPacketUnicastTxCount(uint32_t & packetUnicastTxCount) override; CHIP_ERROR GetWiFiCurrentMaxRate(uint64_t & currentMaxRate) override; CHIP_ERROR GetWiFiOverrunCount(uint64_t & overrunCount) override; + CHIP_ERROR ResetWiFiNetworkDiagnosticsCounts() override; #endif }; From 3a8ace1f154a6443a2ea793f5b8107855d3f60bf Mon Sep 17 00:00:00 2001 From: "jun.luo" Date: Thu, 24 Feb 2022 18:30:32 +0800 Subject: [PATCH 08/20] Correct the system timer as the frequency is 500HZ --- src/platform/Beken/SystemTimeSupport.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/platform/Beken/SystemTimeSupport.cpp b/src/platform/Beken/SystemTimeSupport.cpp index 9c73735c959565..ac44bc9e95b4e9 100644 --- a/src/platform/Beken/SystemTimeSupport.cpp +++ b/src/platform/Beken/SystemTimeSupport.cpp @@ -39,12 +39,12 @@ Clock::Milliseconds64 baseTime; Microseconds64 ClockImpl::GetMonotonicMicroseconds64(void) { - return (Clock::Microseconds64(xTaskGetTickCount()) * kMicrosecondsPerMillisecond); + return (Clock::Microseconds64(xTaskGetTickCount() << 1) * kMicrosecondsPerMillisecond); } Milliseconds64 ClockImpl::GetMonotonicMilliseconds64(void) { - return (Clock::Milliseconds64(xTaskGetTickCount())); + return (Clock::Milliseconds64(xTaskGetTickCount() << 1)); } CHIP_ERROR ClockImpl::GetClock_RealTime(Clock::Microseconds64 & curTime) From 19ea8579dfdf8204d42f0f3f935f5559449b0387 Mon Sep 17 00:00:00 2001 From: "yongjia.fang" Date: Wed, 23 Feb 2022 19:13:09 +0800 Subject: [PATCH 09/20] syn payload config&git interfaces --- .../lighting-app/beken/main/chipinterface.cpp | 104 +----------------- 1 file changed, 3 insertions(+), 101 deletions(-) mode change 100644 => 100755 examples/lighting-app/beken/main/chipinterface.cpp diff --git a/examples/lighting-app/beken/main/chipinterface.cpp b/examples/lighting-app/beken/main/chipinterface.cpp old mode 100644 new mode 100755 index 1e2d1aab3d0ea0..f97505c68916a9 --- a/examples/lighting-app/beken/main/chipinterface.cpp +++ b/examples/lighting-app/beken/main/chipinterface.cpp @@ -38,8 +38,8 @@ using namespace ::chip::Credentials; using namespace ::chip::DeviceManager; using namespace ::chip::DeviceLayer; -#define QRCODE_BASE_URL "https://dhrishi.github.io/connectedhomeip/qrcode.html" -#define EXAMPLE_VENDOR_TAG_IP 1 +//#define QRCODE_BASE_URL "https://dhrishi.github.io/connectedhomeip/qrcode.html" +//#define EXAMPLE_VENDOR_TAG_IP 1 static DeviceCallbacks EchoCallbacks; @@ -55,93 +55,6 @@ bool isRendezvousBLE() return flags.Has(RendezvousInformationFlag::kBLE); } -std::string createSetupPayload() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - std::string result; - - uint16_t discriminator; - err = ConfigurationMgr().GetSetupDiscriminator(discriminator); - if (err != CHIP_NO_ERROR) - { - ChipLogProgress(Zcl, "Couldn't get discriminator: %s\r\n", ErrorStr(err)); - return result; - } - ChipLogProgress(Zcl, "Setup discriminator: %u (0x%x)\r\n", discriminator, discriminator); - - uint32_t setupPINCode; - err = ConfigurationMgr().GetSetupPinCode(setupPINCode); - if (err != CHIP_NO_ERROR) - { - ChipLogProgress(Zcl, "Couldn't get setupPINCode: %s\r\n", ErrorStr(err)); - return result; - } - ChipLogProgress(Zcl, "Setup PIN code: %u (0x%x)\r\n", setupPINCode, setupPINCode); - - uint16_t vendorId; - err = ConfigurationMgr().GetVendorId(vendorId); - if (err != CHIP_NO_ERROR) - { - ChipLogProgress(Zcl, "Couldn't get vendorId: %s\r\n", ErrorStr(err)); - return result; - } - - uint16_t productId; - err = ConfigurationMgr().GetProductId(productId); - if (err != CHIP_NO_ERROR) - { - ChipLogProgress(Zcl, "Couldn't get productId: %s\r\n", ErrorStr(err)); - return result; - } - ChipLogProgress(Zcl, "Setup VendorId: %u (0x%x)\r\n", vendorId, vendorId); - ChipLogProgress(Zcl, "Setup ProductId: %u (0x%x)\r\n", productId, productId); - SetupPayload payload; - payload.version = 0; - payload.discriminator = discriminator; - payload.setUpPINCode = setupPINCode; - payload.rendezvousInformation = RendezvousInformationFlags(CONFIG_RENDEZVOUS_MODE); - payload.vendorID = vendorId; - payload.productID = productId; - - if (isRendezvousBLE()) - { - QRCodeSetupPayloadGenerator generator(payload); - err = generator.payloadBase38Representation(result); - } - - ManualSetupPayloadGenerator generator(payload); - std::string outCode; - - if (generator.payloadDecimalStringRepresentation(outCode) == CHIP_NO_ERROR) - { - ChipLogProgress(Zcl, "Short Manual(decimal) setup code: %s\r\n", outCode.c_str()); - } - else - { - ChipLogProgress(Zcl, "Failed to get decimal setup code\r\n"); - } - - payload.commissioningFlow = CommissioningFlow::kCustom; - generator = ManualSetupPayloadGenerator(payload); - - if (generator.payloadDecimalStringRepresentation(outCode) == CHIP_NO_ERROR) - { - // intentional extra space here to align the log with the short code - ChipLogProgress(Zcl, "Long Manual(decimal) setup code: %s\r\n", outCode.c_str()); - } - else - { - ChipLogProgress(Zcl, "Failed to get decimal setup code\r\n"); - } - - - if (err != CHIP_NO_ERROR) - { - ChipLogProgress(Zcl, "Couldn't get payload string %\r\n" CHIP_ERROR_FORMAT, err.Format()); - } - return result; -}; - void OnIdentifyStart(Identify *) { ChipLogProgress(Zcl, "OnIdentifyStart"); @@ -269,19 +182,8 @@ extern "C" void ChipTest(void) SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); sWiFiNetworkCommissioningInstance.Init(); - std::string qrCodeText = createSetupPayload(); - - ChipLogProgress(Zcl, "QR CODE Text: '%s'\r\n", qrCodeText.c_str()); + PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); - { - std::vector qrCode(3 * qrCodeText.size() + 1); - err = EncodeQRCodeToUrl(qrCodeText.c_str(), qrCodeText.size(), qrCode.data(), qrCode.max_size()); - if (err == CHIP_NO_ERROR) - { - ChipLogProgress(DeviceLayer, "Copy/paste the below URL in a browser to see the QR CODE:\t"); - ChipLogProgress(DeviceLayer, "%s?data=%s \r\n",QRCODE_BASE_URL, qrCode.data()); - } - } while (true) vTaskDelay(pdMS_TO_TICKS(50)); } From 1a91502a80cf2ce765ac27336ba827da93f2c60b Mon Sep 17 00:00:00 2001 From: "fuxing.guo" Date: Fri, 25 Feb 2022 13:52:41 +0800 Subject: [PATCH 10/20] Add the OTA function to device. Change-Id: I824bc4ea2491886a597e9525cb33d2e1ce6d6f2d --- .../beken/main/DeviceCallbacks.cpp | 24 ++ .../lighting-app/beken/main/chipinterface.cpp | 149 +++++++++ .../beken/main/include/DeviceCallbacks.h | 3 +- src/platform/Beken/BUILD.gn | 2 + src/platform/Beken/OTAImageProcessorImpl.cpp | 316 ++++++++++++++++++ src/platform/Beken/OTAImageProcessorImpl.h | 70 ++++ src/platform/Beken/SystemTimeSupport.h | 29 ++ src/platform/device.gni | 2 +- 8 files changed, 593 insertions(+), 2 deletions(-) create mode 100755 src/platform/Beken/OTAImageProcessorImpl.cpp create mode 100755 src/platform/Beken/OTAImageProcessorImpl.h create mode 100755 src/platform/Beken/SystemTimeSupport.h diff --git a/examples/lighting-app/beken/main/DeviceCallbacks.cpp b/examples/lighting-app/beken/main/DeviceCallbacks.cpp index aad851257c59e8..aba23e9ba735a6 100644 --- a/examples/lighting-app/beken/main/DeviceCallbacks.cpp +++ b/examples/lighting-app/beken/main/DeviceCallbacks.cpp @@ -120,6 +120,10 @@ void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, Cluster { switch (clusterId) { + case ZCL_ON_OFF_CLUSTER_ID: + OnOnOffPostAttributeChangeCallback(endpointId, attributeId, value); + break; + case ZCL_IDENTIFY_CLUSTER_ID: OnIdentifyPostAttributeChangeCallback(endpointId, attributeId, value); break; @@ -130,6 +134,20 @@ void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, Cluster } } +void DeviceCallbacks::OnOnOffPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value) +{ + VerifyOrExit(attributeId == ZCL_ON_OFF_ATTRIBUTE_ID, + ChipLogError(DeviceLayer, TAG, "Unhandled Attribute ID: '0x%04x", attributeId)); + VerifyOrExit(endpointId == 1 || endpointId == 2, + ChipLogError(DeviceLayer, TAG, "Unexpected EndPoint ID: `0x%02x'", endpointId)); + + // At this point we can assume that value points to a bool value. + //statusLED1.Set(*value); + +exit: + return; +} + void IdentifyTimerHandler(Layer * systemLayer, void * appState) { // statusLED1.Animate(); @@ -159,3 +177,9 @@ void DeviceCallbacks::OnIdentifyPostAttributeChangeCallback(EndpointId endpointI exit: return; } + +bool emberAfBasicClusterMfgSpecificPingCallback(chip::app::CommandHandler * commandObj) +{ + emberAfSendDefaultResponse(emberAfCurrentCommand(), EMBER_ZCL_STATUS_SUCCESS); + return true; +} \ No newline at end of file diff --git a/examples/lighting-app/beken/main/chipinterface.cpp b/examples/lighting-app/beken/main/chipinterface.cpp index f97505c68916a9..e37c23b168b7e7 100755 --- a/examples/lighting-app/beken/main/chipinterface.cpp +++ b/examples/lighting-app/beken/main/chipinterface.cpp @@ -33,15 +33,51 @@ #include #include +//#if CONFIG_ENABLE_OTA_REQUESTOR +#include "app/clusters/ota-requestor/BDXDownloader.h" +#include "app/clusters/ota-requestor/OTARequestor.h" +#include "platform/Beken/OTAImageProcessorImpl.h" +#include "platform/GenericOTARequestorDriver.h" +//#endif + +using chip::OTAImageProcessorImpl; +using chip::BDXDownloader; +using chip::ByteSpan; +using chip::EndpointId; +using chip::FabricIndex; +using chip::GetRequestorInstance; +using chip::NodeId; +using chip::OnDeviceConnected; +using chip::OnDeviceConnectionFailure; +using chip::OTADownloader; +using chip::OTAImageProcessorParams; +using chip::OTARequestor; +using chip::PeerId; +using chip::Server; +using chip::VendorId; +using chip::Callback::Callback; +using chip::System::Layer; +using chip::Transport::PeerAddress; +using namespace chip::Messaging; +using namespace chip::app::Clusters::OtaSoftwareUpdateProvider::Commands; + + using namespace ::chip; using namespace ::chip::Credentials; using namespace ::chip::DeviceManager; using namespace ::chip::DeviceLayer; +using namespace ::chip::System; //#define QRCODE_BASE_URL "https://dhrishi.github.io/connectedhomeip/qrcode.html" //#define EXAMPLE_VENDOR_TAG_IP 1 static DeviceCallbacks EchoCallbacks; +//#if CONFIG_ENABLE_OTA_REQUESTOR +OTARequestor gRequestorCore; +GenericOTARequestorDriver gRequestorUser; +BDXDownloader gDownloader; +OTAImageProcessorImpl gImageProcessor; +//#endif namespace { app::Clusters::NetworkCommissioning::Instance @@ -55,6 +91,113 @@ bool isRendezvousBLE() return flags.Has(RendezvousInformationFlag::kBLE); } +//#if CONFIG_ENABLE_OTA_REQUESTOR +extern "C" void QueryImageCmdHandler(uint32_t nodeId, uint32_t fabricId) +{ + ChipLogProgress(DeviceLayer, "Calling QueryImageCmdHandler"); + // In this mode Provider node ID and fabric idx must be supplied explicitly from ATS$ cmd + gRequestorCore.TestModeSetProviderParameters(nodeId, fabricId, chip::kRootEndpointId); + + static_cast(GetRequestorInstance())->TriggerImmediateQuery(); +} + +extern "C" void ApplyUpdateCmdHandler() +{ + ChipLogProgress(DeviceLayer, "Calling ApplyUpdateCmdHandler"); + + static_cast(GetRequestorInstance())->ApplyUpdate(); +} +/********************************************************************* + * Funtion Name:BkQueryImageCmdHandler + * + * Funtion Discription:trigger ota requestor queries image from ota provider + * + * + * Date:2022-02-22 + *******************************************************************/ +extern "C" void BkQueryImageCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv ) +{ + uint32_t dwLoop = 0; + uint32_t nodeId = 0; + uint32_t fabricId = 0; + + char cmd0 = 0; + char cmd1 = 0; + + for(dwLoop = 0; dwLoop < argc; dwLoop++) + { + ChipLogProgress(DeviceLayer, "QueryImageArgument %d = %s\r\n", dwLoop + 1, argv[dwLoop]); + } + + if(argc == 3) + { + cmd0 = argv[1][0] - 0x30; + cmd1 = argv[1][1] - 0x30; + nodeId = (uint32_t)(cmd0 * 10 + cmd1); + + cmd0 = argv[2][0] - 0x30; + cmd1 = argv[2][1] - 0x30; + fabricId = (uint32_t)(cmd0 * 10 + cmd1); + ChipLogProgress(DeviceLayer, "nodeId %lu,fabricId %lu\r\n", nodeId,fabricId); + } + else + { + ChipLogProgress(DeviceLayer,"cmd param error "); + return ; + } + + QueryImageCmdHandler( nodeId, fabricId); + ChipLogProgress(DeviceLayer,"QueryImageCmdHandler begin"); + + return ; +} + +/********************************************************************* + * Funtion Name:BkApplyUpdateCmdHandler + * + * Funtion Discription:trigger ota requestor queries image from ota provider + * + * + * Date:2022-02-22 + *******************************************************************/ +extern "C" void BkApplyUpdateCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv ) +{ + ApplyUpdateCmdHandler(); + ChipLogProgress(DeviceLayer,"ApplyUpdateCmdHandler send requst"); + + return ; +} + + +static void InitOTARequestor(void) +{ + // Initialize and interconnect the Requestor and Image Processor objects -- START + SetRequestorInstance(&gRequestorCore); + + // Set server instance used for session establishment + /* - Set server instance used to get access to the system resources necessary to open CASE sessions and drive + * - BDX transfers + * - Set the OTA requestor driver instance used to communicate download progress and errors + * - Set the BDX downloader instance used for initiating BDX downloads + */ + gRequestorCore.Init(&(chip::Server::GetInstance()), &gRequestorUser, &gDownloader); + + // WARNING: this is probably not realistic to know such details of the image or to even have an OTADownloader instantiated at + // the beginning of program execution. We're using hardcoded values here for now since this is a reference application. + // TODO: instatiate and initialize these values when QueryImageResponse tells us an image is available + // TODO: add API for OTARequestor to pass QueryImageResponse info to the application to use for OTADownloader init + OTAImageProcessorParams ipParams; + gImageProcessor.SetOTAImageProcessorParams(ipParams); + gImageProcessor.SetOTADownloader(&gDownloader); + + // Connect the Downloader and Image Processor objects + gDownloader.SetImageProcessorDelegate(&gImageProcessor); + gRequestorUser.Init(&gRequestorCore, &gImageProcessor); + + // Initialize and interconnect the Requestor and Image Processor objects -- END +} +//#endif // CONFIG_ENABLE_OTA_REQUESTOR + void OnIdentifyStart(Identify *) { ChipLogProgress(Zcl, "OnIdentifyStart"); @@ -184,8 +327,14 @@ extern "C" void ChipTest(void) PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); +//#if CONFIG_ENABLE_OTA_REQUESTOR + InitOTARequestor(); +//#endif while (true) vTaskDelay(pdMS_TO_TICKS(50)); +exit: + ChipLogProgress(SoftwareUpdate, "Exited"); + return; } bool lowPowerClusterSleep() diff --git a/examples/lighting-app/beken/main/include/DeviceCallbacks.h b/examples/lighting-app/beken/main/include/DeviceCallbacks.h index f7a2c0b52b1624..10ac917c02890a 100644 --- a/examples/lighting-app/beken/main/include/DeviceCallbacks.h +++ b/examples/lighting-app/beken/main/include/DeviceCallbacks.h @@ -33,12 +33,13 @@ class DeviceCallbacks : public chip::DeviceManager::CHIPDeviceManagerCallbacks { public: - virtual void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg); + void DeviceEventCallback(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg) override; void PostAttributeChangeCallback(chip::EndpointId endpointId, chip::ClusterId clusterId, chip::AttributeId attributeId, uint8_t mask, uint8_t type, uint16_t size, uint8_t * value) override; private: void OnInternetConnectivityChange(const chip::DeviceLayer::ChipDeviceEvent * event); void OnSessionEstablished(const chip::DeviceLayer::ChipDeviceEvent * event); + void OnOnOffPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); void OnIdentifyPostAttributeChangeCallback(chip::EndpointId endpointId, chip::AttributeId attributeId, uint8_t * value); }; diff --git a/src/platform/Beken/BUILD.gn b/src/platform/Beken/BUILD.gn index fabee4f07cde52..808eb1c5b9e669 100755 --- a/src/platform/Beken/BUILD.gn +++ b/src/platform/Beken/BUILD.gn @@ -38,6 +38,8 @@ static_library("Beken") { "KeyValueStoreManagerImpl.h", "Logging.cpp", "LwIPCoreLock.cpp", + "OTAImageProcessorImpl.cpp", + "OTAImageProcessorImpl.h", "PlatformManagerImpl.cpp", "PlatformManagerImpl.h", "SoftwareUpdateManagerImpl.h", diff --git a/src/platform/Beken/OTAImageProcessorImpl.cpp b/src/platform/Beken/OTAImageProcessorImpl.cpp new file mode 100755 index 00000000000000..3b178b581a8423 --- /dev/null +++ b/src/platform/Beken/OTAImageProcessorImpl.cpp @@ -0,0 +1,316 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include "wlan_ui_pub.h" +#include "BkDriverFlash.h" +#include "flash_namespace_value.h" + + +namespace chip { + +const char ucFinishFlag[] = {0xF0,0x5D,0x4A,0x8C};//Flag that OTA update has finished +CHIP_ERROR OTAImageProcessorImpl::PrepareDownload() +{ + ChipLogProgress(SoftwareUpdate, "Prepare download"); + + DeviceLayer::PlatformMgr().ScheduleWork(HandlePrepareDownload, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::Finalize() +{ + ChipLogProgress(SoftwareUpdate, "Finalize"); + + DeviceLayer::PlatformMgr().ScheduleWork(HandleFinalize, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::Apply() +{ + ChipLogProgress(SoftwareUpdate, "Apply"); + + DeviceLayer::PlatformMgr().ScheduleWork(HandleApply, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::Abort() +{ + ChipLogProgress(SoftwareUpdate, "Abort"); + + DeviceLayer::PlatformMgr().ScheduleWork(HandleAbort, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block) +{ + ChipLogProgress(SoftwareUpdate, "Process Block"); + + if ((block.data() == nullptr) || block.empty()) + { + return CHIP_ERROR_INVALID_ARGUMENT; + } + CHIP_ERROR err = SetBlock(block); + if (err != CHIP_NO_ERROR) + { + ChipLogError(SoftwareUpdate, "Cannot set block data: %" CHIP_ERROR_FORMAT, err.Format()); + return err; + } + + DeviceLayer::PlatformMgr().ScheduleWork(HandleProcessBlock, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + if (imageProcessor == nullptr) + { + ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + return; + } + else if (imageProcessor->mDownloader == nullptr) + { + ChipLogError(SoftwareUpdate, "mDownloader is null"); + return; + } + + // Get OTA update partition + ChipLogProgress(SoftwareUpdate, "%s [%d] OTA address space will be upgraded",__FUNCTION__,__LINE__); + + imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR); +} + +void OTAImageProcessorImpl::HandleFinalize(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + bk_logic_partition_t *partition_info = NULL; + UINT32 dwFlagAddrOffset = 0; + if (imageProcessor == nullptr) + { + ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + return; + } + + partition_info = bk_flash_get_info(BK_PARTITION_OTA); + BK_CHECK_POINTER_NULL_TO_VOID(partition_info); + dwFlagAddrOffset = partition_info->partition_length - (sizeof(ucFinishFlag) - 1); + + bk_write_ota_data_to_flash((char *)ucFinishFlag,dwFlagAddrOffset,(sizeof(ucFinishFlag) - 1)); + + // need to add Verify checksum code in the future + #if 0 + if (imageProcessor == nullptr) + { + ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + return; + } + esp_err_t err = esp_ota_end(imageProcessor->mOTAUpdateHandle); + if (err != ESP_OK) + { + if (err == ESP_ERR_OTA_VALIDATE_FAILED) + { + ESP_LOGE(TAG, "Image validation failed, image is corrupted"); + } + else + { + ESP_LOGE(TAG, "esp_ota_end failed (%s)!", esp_err_to_name(err)); + } + return; + } + #endif + imageProcessor->ReleaseBlock(); + + ChipLogProgress(SoftwareUpdate, "OTA image downloaded and written to flash"); +} + +void OTAImageProcessorImpl::HandleAbort(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + if (imageProcessor == nullptr) + { + ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + return; + } + + // Abort OTA procedure + + imageProcessor->ReleaseBlock(); +} + +void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + + ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] ",__FUNCTION__,__LINE__); + if (imageProcessor == nullptr) + { + ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + return; + } + else if (imageProcessor->mDownloader == nullptr) + { + ChipLogError(SoftwareUpdate, "mDownloader is null"); + return; + } + ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] ",__FUNCTION__,__LINE__); + + if (!imageProcessor->readHeader) // First block received, process header + { + ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] ",__FUNCTION__,__LINE__); + ota_data_struct_t * tempBuf = (ota_data_struct_t *) malloc(sizeof(ota_data_struct_t)); + + if(NULL == tempBuf) + { + ChipLogError(SoftwareUpdate, "%s [%d] malloc failed ",__FUNCTION__,__LINE__); + } + memset((char *)tempBuf,0,sizeof(ota_data_struct_t)); + memcpy((char *)&(imageProcessor->pOtaTgtHdr), imageProcessor->mBlock.data(), sizeof(ota_data_struct_t)); + + imageProcessor->flash_data_offset = 0; + + bk_read_ota_data_in_flash( (char *)tempBuf,imageProcessor->flash_data_offset,sizeof(ota_data_struct_t)); + ChipLogProgress(SoftwareUpdate, "tempBuf version %s,date is %ld ",tempBuf->version,tempBuf->timestamp); + ChipLogProgress(SoftwareUpdate, "imageProcessor version %s,date is 0x%lx ",imageProcessor->pOtaTgtHdr.version,imageProcessor->pOtaTgtHdr.timestamp); + + bk_logic_partition_t *partition_info = NULL; + UINT32 dwFlagAddrOffset = 0; + char ucflag[(sizeof(ucFinishFlag) - 1)] = {0}; + + partition_info = bk_flash_get_info(BK_PARTITION_OTA); + BK_CHECK_POINTER_NULL_TO_VOID(partition_info); + + dwFlagAddrOffset = partition_info->partition_length - (sizeof(ucFinishFlag) - 1); + bk_read_ota_data_in_flash( (char *)ucflag,dwFlagAddrOffset,(sizeof(ucFinishFlag) - 1)); + ChipLogProgress(SoftwareUpdate, "Block size is %d ,ucFinishFlag size len is %d",imageProcessor->mBlock.size(),sizeof(ucFinishFlag)); + + if ((0 == memcmp(ucflag,ucFinishFlag,(sizeof(ucFinishFlag) - 1))) && + (0 == memcmp(tempBuf->version,imageProcessor->pOtaTgtHdr.version,sizeof(imageProcessor->pOtaTgtHdr.version)))) + { + free(tempBuf); + tempBuf = NULL; + ChipLogError(SoftwareUpdate, "The version is is the same as the previous version"); + return; + } + + imageProcessor->readHeader = true; + ChipLogProgress(SoftwareUpdate, "flash_data_offset is 0x%lx",imageProcessor->flash_data_offset); + ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] ",__FUNCTION__,__LINE__); + + // Erase update partition + ChipLogProgress(SoftwareUpdate, "Erasing target partition..."); + bk_erase_ota_data_in_flash(); + ChipLogProgress(SoftwareUpdate, "Erasing target partition..."); + if(0 != bk_write_ota_data_to_flash((char *) imageProcessor->mBlock.data(),imageProcessor->flash_data_offset,imageProcessor->mBlock.size())) + { + free(tempBuf); + tempBuf = NULL; + ChipLogError(SoftwareUpdate, "bk_write_ota_data_to_flash failed %s [%d] ",__FUNCTION__,__LINE__); + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); + return; + } + ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] ",__FUNCTION__,__LINE__); + imageProcessor->flash_data_offset += imageProcessor->mBlock.size();//count next write flash address + + free(tempBuf); + tempBuf = NULL; + } + else // received subsequent blocks + { + ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] 0x%lx %d",__FUNCTION__,__LINE__,imageProcessor->flash_data_offset,imageProcessor->mBlock.size()); + if(0 != bk_write_ota_data_to_flash( (char *)imageProcessor->mBlock.data(),imageProcessor->flash_data_offset,imageProcessor->mBlock.size())) + { + ChipLogError(SoftwareUpdate, "bk_write_ota_data_to_flash failed %s [%d] ",__FUNCTION__,__LINE__); + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); + return; + } + imageProcessor->flash_data_offset += imageProcessor->mBlock.size();//count next write flash address + + imageProcessor->size += imageProcessor->mBlock.size(); + } + + imageProcessor->mParams.downloadedBytes += imageProcessor->mBlock.size(); + ChipLogError(SoftwareUpdate, "BBBB %s [%d],downloadedBytes is %lld FetchNextData",__FUNCTION__,__LINE__,imageProcessor->mParams.downloadedBytes); + imageProcessor->mDownloader->FetchNextData(); +} + +void OTAImageProcessorImpl::HandleApply(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + ChipLogError(SoftwareUpdate, "Update completly,will reboot %s [%d] ",__FUNCTION__,__LINE__); + + // Reboot + bk_reboot(); +} + +CHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block) +{ + if ((block.data() == nullptr) || block.empty()) + { + return CHIP_NO_ERROR; + } + + if (mBlock.size() < block.size()) + { + if (!mBlock.empty()) + { + ReleaseBlock(); + } + uint8_t * mBlock_ptr = static_cast(chip::Platform::MemoryAlloc(block.size())); + if (mBlock_ptr == nullptr) + { + return CHIP_ERROR_NO_MEMORY; + } + mBlock = MutableByteSpan(mBlock_ptr, block.size()); + } + + // Allocate memory for block data if it has not been done yet + if (mBlock.empty()) + { + mBlock = MutableByteSpan(static_cast(chip::Platform::MemoryAlloc(block.size())), block.size()); + if (mBlock.data() == nullptr) + { + return CHIP_ERROR_NO_MEMORY; + } + } + + // Store the actual block data + CHIP_ERROR err = CopySpanToMutableSpan(block, mBlock); + if (err != CHIP_NO_ERROR) + { + ChipLogError(SoftwareUpdate, "Cannot copy block data: %" CHIP_ERROR_FORMAT, err.Format()); + return err; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::ReleaseBlock() +{ + if (mBlock.data() != nullptr) + { + chip::Platform::MemoryFree(mBlock.data()); + } + + mBlock = MutableByteSpan(); + return CHIP_NO_ERROR; +} +} // namespace chip diff --git a/src/platform/Beken/OTAImageProcessorImpl.h b/src/platform/Beken/OTAImageProcessorImpl.h new file mode 100755 index 00000000000000..7522ebc40c4df8 --- /dev/null +++ b/src/platform/Beken/OTAImageProcessorImpl.h @@ -0,0 +1,70 @@ +/* + * + * 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 + +#include +#include +//#include +#include +#include +#include "flash_namespace_value.h" + + +namespace chip { + +class OTAImageProcessorImpl : public OTAImageProcessorInterface +{ +public: + //////////// OTAImageProcessorInterface Implementation /////////////// + CHIP_ERROR PrepareDownload() override; + CHIP_ERROR Finalize() override; + CHIP_ERROR Apply() override; + CHIP_ERROR Abort() override; + CHIP_ERROR ProcessBlock(ByteSpan & block) override; + void SetOTADownloader(OTADownloader * downloader) { mDownloader = downloader; } + +private: + //////////// Actual handlers for the OTAImageProcessorInterface /////////////// + static void HandlePrepareDownload(intptr_t context); + static void HandleFinalize(intptr_t context); + static void HandleAbort(intptr_t context); + static void HandleProcessBlock(intptr_t context); + static void HandleApply(intptr_t context); + + /** + * Called to allocate memory for mBlock if necessary and set it to block + */ + CHIP_ERROR SetBlock(ByteSpan & block); + + /** + * Called to release allocated memory for mBlock + */ + CHIP_ERROR ReleaseBlock(); + + MutableByteSpan mBlock; + OTADownloader * mDownloader; + + bool readHeader = false; + ota_data_struct_t pOtaTgtHdr = {0}; + uint32_t flash_data_offset = 0; + uint32_t size = 0; +}; + +} // namespace chip + diff --git a/src/platform/Beken/SystemTimeSupport.h b/src/platform/Beken/SystemTimeSupport.h new file mode 100755 index 00000000000000..89eb960eea07b9 --- /dev/null +++ b/src/platform/Beken/SystemTimeSupport.h @@ -0,0 +1,29 @@ + +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +namespace chip { +namespace System { +namespace Clock { + +CHIP_ERROR InitClock_RealTime(); + +} // namespace Clock +} // namespace System +} // namespace chip diff --git a/src/platform/device.gni b/src/platform/device.gni index 566a4c415878c1..0524b1cf36c45a 100755 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -71,7 +71,7 @@ declare_args() { chip_enable_nfc = false # Enable OTA requestor support - chip_enable_ota_requestor = false + chip_enable_ota_requestor = true # Select DNS-SD implementation if (chip_device_platform == "linux" || chip_device_platform == "esp32" || From 6976db8f8c4a583e9e3459b75f026215ad64b91b Mon Sep 17 00:00:00 2001 From: "fuxing.guo" Date: Mon, 28 Feb 2022 15:10:52 +0800 Subject: [PATCH 11/20] Optimize the code. Change-Id: I101a84a13d44a9f3eb721228db1b097fd1a7bd12 --- .../lighting-app/beken/main/chipinterface.cpp | 5 --- src/platform/Beken/OTAImageProcessorImpl.cpp | 45 ++++--------------- 2 files changed, 9 insertions(+), 41 deletions(-) diff --git a/examples/lighting-app/beken/main/chipinterface.cpp b/examples/lighting-app/beken/main/chipinterface.cpp index e37c23b168b7e7..2430f935dd7e32 100755 --- a/examples/lighting-app/beken/main/chipinterface.cpp +++ b/examples/lighting-app/beken/main/chipinterface.cpp @@ -52,8 +52,6 @@ using chip::OnDeviceConnectionFailure; using chip::OTADownloader; using chip::OTAImageProcessorParams; using chip::OTARequestor; -using chip::PeerId; -using chip::Server; using chip::VendorId; using chip::Callback::Callback; using chip::System::Layer; @@ -68,8 +66,6 @@ using namespace ::chip::DeviceManager; using namespace ::chip::DeviceLayer; using namespace ::chip::System; -//#define QRCODE_BASE_URL "https://dhrishi.github.io/connectedhomeip/qrcode.html" -//#define EXAMPLE_VENDOR_TAG_IP 1 static DeviceCallbacks EchoCallbacks; //#if CONFIG_ENABLE_OTA_REQUESTOR @@ -168,7 +164,6 @@ extern "C" void BkApplyUpdateCmdHandler(char *pcWriteBuffer, int xWriteBufferLen return ; } - static void InitOTARequestor(void) { // Initialize and interconnect the Requestor and Image Processor objects -- START diff --git a/src/platform/Beken/OTAImageProcessorImpl.cpp b/src/platform/Beken/OTAImageProcessorImpl.cpp index 3b178b581a8423..36d564f9b3ab8f 100755 --- a/src/platform/Beken/OTAImageProcessorImpl.cpp +++ b/src/platform/Beken/OTAImageProcessorImpl.cpp @@ -23,6 +23,7 @@ #include "wlan_ui_pub.h" #include "BkDriverFlash.h" #include "flash_namespace_value.h" +#include "mem_pub.h" namespace chip { @@ -93,7 +94,6 @@ void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context) return; } - // Get OTA update partition ChipLogProgress(SoftwareUpdate, "%s [%d] OTA address space will be upgraded",__FUNCTION__,__LINE__); imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR); @@ -116,27 +116,6 @@ void OTAImageProcessorImpl::HandleFinalize(intptr_t context) bk_write_ota_data_to_flash((char *)ucFinishFlag,dwFlagAddrOffset,(sizeof(ucFinishFlag) - 1)); - // need to add Verify checksum code in the future - #if 0 - if (imageProcessor == nullptr) - { - ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); - return; - } - esp_err_t err = esp_ota_end(imageProcessor->mOTAUpdateHandle); - if (err != ESP_OK) - { - if (err == ESP_ERR_OTA_VALIDATE_FAILED) - { - ESP_LOGE(TAG, "Image validation failed, image is corrupted"); - } - else - { - ESP_LOGE(TAG, "esp_ota_end failed (%s)!", esp_err_to_name(err)); - } - return; - } - #endif imageProcessor->ReleaseBlock(); ChipLogProgress(SoftwareUpdate, "OTA image downloaded and written to flash"); @@ -160,7 +139,6 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) { auto * imageProcessor = reinterpret_cast(context); - ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] ",__FUNCTION__,__LINE__); if (imageProcessor == nullptr) { ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); @@ -171,24 +149,23 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) ChipLogError(SoftwareUpdate, "mDownloader is null"); return; } - ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] ",__FUNCTION__,__LINE__); if (!imageProcessor->readHeader) // First block received, process header { - ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] ",__FUNCTION__,__LINE__); - ota_data_struct_t * tempBuf = (ota_data_struct_t *) malloc(sizeof(ota_data_struct_t)); + ota_data_struct_t * tempBuf = (ota_data_struct_t *) os_malloc(sizeof(ota_data_struct_t)); if(NULL == tempBuf) { ChipLogError(SoftwareUpdate, "%s [%d] malloc failed ",__FUNCTION__,__LINE__); } - memset((char *)tempBuf,0,sizeof(ota_data_struct_t)); - memcpy((char *)&(imageProcessor->pOtaTgtHdr), imageProcessor->mBlock.data(), sizeof(ota_data_struct_t)); + os_memset((char *)tempBuf,0,sizeof(ota_data_struct_t)); + os_memcpy((char *)&(imageProcessor->pOtaTgtHdr), imageProcessor->mBlock.data(), sizeof(ota_data_struct_t)); imageProcessor->flash_data_offset = 0; bk_read_ota_data_in_flash( (char *)tempBuf,imageProcessor->flash_data_offset,sizeof(ota_data_struct_t)); - ChipLogProgress(SoftwareUpdate, "tempBuf version %s,date is %ld ",tempBuf->version,tempBuf->timestamp); + ChipLogProgress(SoftwareUpdate, "Download version %s,date is %ld ",tempBuf->version,tempBuf->timestamp); + ChipLogProgress(SoftwareUpdate, "Download size_raw %ld,size_package is %ld ",tempBuf->size_raw,tempBuf->size_package); ChipLogProgress(SoftwareUpdate, "imageProcessor version %s,date is 0x%lx ",imageProcessor->pOtaTgtHdr.version,imageProcessor->pOtaTgtHdr.timestamp); bk_logic_partition_t *partition_info = NULL; @@ -205,7 +182,7 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) if ((0 == memcmp(ucflag,ucFinishFlag,(sizeof(ucFinishFlag) - 1))) && (0 == memcmp(tempBuf->version,imageProcessor->pOtaTgtHdr.version,sizeof(imageProcessor->pOtaTgtHdr.version)))) { - free(tempBuf); + os_free(tempBuf); tempBuf = NULL; ChipLogError(SoftwareUpdate, "The version is is the same as the previous version"); return; @@ -213,7 +190,6 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) imageProcessor->readHeader = true; ChipLogProgress(SoftwareUpdate, "flash_data_offset is 0x%lx",imageProcessor->flash_data_offset); - ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] ",__FUNCTION__,__LINE__); // Erase update partition ChipLogProgress(SoftwareUpdate, "Erasing target partition..."); @@ -221,21 +197,19 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) ChipLogProgress(SoftwareUpdate, "Erasing target partition..."); if(0 != bk_write_ota_data_to_flash((char *) imageProcessor->mBlock.data(),imageProcessor->flash_data_offset,imageProcessor->mBlock.size())) { - free(tempBuf); + os_free(tempBuf); tempBuf = NULL; ChipLogError(SoftwareUpdate, "bk_write_ota_data_to_flash failed %s [%d] ",__FUNCTION__,__LINE__); imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); return; } - ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] ",__FUNCTION__,__LINE__); imageProcessor->flash_data_offset += imageProcessor->mBlock.size();//count next write flash address - free(tempBuf); + os_free(tempBuf); tempBuf = NULL; } else // received subsequent blocks { - ChipLogError(SoftwareUpdate, "BBBBRRRRWWWW %s [%d] 0x%lx %d",__FUNCTION__,__LINE__,imageProcessor->flash_data_offset,imageProcessor->mBlock.size()); if(0 != bk_write_ota_data_to_flash( (char *)imageProcessor->mBlock.data(),imageProcessor->flash_data_offset,imageProcessor->mBlock.size())) { ChipLogError(SoftwareUpdate, "bk_write_ota_data_to_flash failed %s [%d] ",__FUNCTION__,__LINE__); @@ -248,7 +222,6 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) } imageProcessor->mParams.downloadedBytes += imageProcessor->mBlock.size(); - ChipLogError(SoftwareUpdate, "BBBB %s [%d],downloadedBytes is %lld FetchNextData",__FUNCTION__,__LINE__,imageProcessor->mParams.downloadedBytes); imageProcessor->mDownloader->FetchNextData(); } From 3880dbcf04174b20198c0a5e89ef062da13a3b28 Mon Sep 17 00:00:00 2001 From: "jun.luo" Date: Thu, 3 Mar 2022 10:39:59 +0800 Subject: [PATCH 12/20] sync with TE8/rc3 --- config/beken/args.gni | 1 + .../beken/main/CHIPDeviceManager.cpp | 4 +- .../lighting-app/beken/main/chipinterface.cpp | 38 +++++++++---------- .../Beken/DiagnosticDataProviderImpl.cpp | 1 - src/platform/device.gni | 2 +- 5 files changed, 22 insertions(+), 24 deletions(-) diff --git a/config/beken/args.gni b/config/beken/args.gni index c60fc0c25e1088..c62b92ac11e375 100755 --- a/config/beken/args.gni +++ b/config/beken/args.gni @@ -34,5 +34,6 @@ chip_config_network_layer_ble = true chip_config_memory_management = "platform" chip_enable_additional_data_advertising = true chip_enable_rotating_device_id = true +chip_enable_ota_requestor = true custom_toolchain = "//third_party/connectedhomeip/config/beken/toolchain:beken" diff --git a/examples/lighting-app/beken/main/CHIPDeviceManager.cpp b/examples/lighting-app/beken/main/CHIPDeviceManager.cpp index 4004eb03c35406..525c645927c4a5 100644 --- a/examples/lighting-app/beken/main/CHIPDeviceManager.cpp +++ b/examples/lighting-app/beken/main/CHIPDeviceManager.cpp @@ -77,11 +77,11 @@ CHIP_ERROR CHIPDeviceManager::Init(CHIPDeviceManagerCallbacks * cb) err = PlatformMgr().StartEventLoopTask(); if (err != CHIP_NO_ERROR) { - printf("StartEventLoopTask() - ERROR!\r\n"); + ChipLogProgress(Zcl, "StartEventLoopTask() - ERROR!\r\n"); } else { - printf("StartEventLoopTask() - OK\r\n"); + ChipLogProgress(Zcl, "StartEventLoopTask() - OK\r\n"); } exit: diff --git a/examples/lighting-app/beken/main/chipinterface.cpp b/examples/lighting-app/beken/main/chipinterface.cpp index 2430f935dd7e32..84a7dd6dedf710 100755 --- a/examples/lighting-app/beken/main/chipinterface.cpp +++ b/examples/lighting-app/beken/main/chipinterface.cpp @@ -66,16 +66,14 @@ using namespace ::chip::DeviceManager; using namespace ::chip::DeviceLayer; using namespace ::chip::System; +namespace { static DeviceCallbacks EchoCallbacks; -//#if CONFIG_ENABLE_OTA_REQUESTOR OTARequestor gRequestorCore; GenericOTARequestorDriver gRequestorUser; BDXDownloader gDownloader; OTAImageProcessorImpl gImageProcessor; -//#endif -namespace { app::Clusters::NetworkCommissioning::Instance sWiFiNetworkCommissioningInstance(0 /* Endpoint Id */, &(NetworkCommissioning::BekenWiFiDriver::GetInstance())); } // namespace @@ -88,12 +86,9 @@ bool isRendezvousBLE() } //#if CONFIG_ENABLE_OTA_REQUESTOR -extern "C" void QueryImageCmdHandler(uint32_t nodeId, uint32_t fabricId) +extern "C" void QueryImageCmdHandler() { ChipLogProgress(DeviceLayer, "Calling QueryImageCmdHandler"); - // In this mode Provider node ID and fabric idx must be supplied explicitly from ATS$ cmd - gRequestorCore.TestModeSetProviderParameters(nodeId, fabricId, chip::kRootEndpointId); - static_cast(GetRequestorInstance())->TriggerImmediateQuery(); } @@ -113,6 +108,7 @@ extern "C" void ApplyUpdateCmdHandler() *******************************************************************/ extern "C" void BkQueryImageCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv ) { +#if 0 uint32_t dwLoop = 0; uint32_t nodeId = 0; uint32_t fabricId = 0; @@ -141,8 +137,8 @@ extern "C" void BkQueryImageCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, ChipLogProgress(DeviceLayer,"cmd param error "); return ; } - - QueryImageCmdHandler( nodeId, fabricId); +#endif + QueryImageCmdHandler(); ChipLogProgress(DeviceLayer,"QueryImageCmdHandler begin"); return ; @@ -299,6 +295,17 @@ extern "C" bool __sync_bool_compare_and_swap_4(volatile void* ptr, unsigned int extern "C" void _fini(void) { } extern "C" void _init(void) {;} +static void InitServer(intptr_t context) +{ + // Init ZCL Data Model and CHIP App Server + chip::Server::GetInstance().Init(); + + // Initialize device attestation config + SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); + sWiFiNetworkCommissioningInstance.Init(); + PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); +} + extern "C" void ChipTest(void) { ChipLogProgress(Zcl, "ChipTest"); @@ -315,19 +322,10 @@ extern "C" void ChipTest(void) { ChipLogProgress(Zcl, "DeviceManagerInit() - OK"); } - chip::Server::GetInstance().Init(); - // Initialize device attestation config - SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); - sWiFiNetworkCommissioningInstance.Init(); - - PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); - -//#if CONFIG_ENABLE_OTA_REQUESTOR + chip::DeviceLayer::PlatformMgr().ScheduleWork(InitServer, reinterpret_cast(nullptr)); InitOTARequestor(); -//#endif while (true) - vTaskDelay(pdMS_TO_TICKS(50)); -exit: + vTaskDelay(pdMS_TO_TICKS(50)); //Just server the application event handler ChipLogProgress(SoftwareUpdate, "Exited"); return; } diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.cpp b/src/platform/Beken/DiagnosticDataProviderImpl.cpp index 6dde91026d8e98..cf4527d8643e2b 100644 --- a/src/platform/Beken/DiagnosticDataProviderImpl.cpp +++ b/src/platform/Beken/DiagnosticDataProviderImpl.cpp @@ -135,7 +135,6 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** strncpy(ifp->Name, netif->hostname, Inet::InterfaceId::kMaxIfNameLength); ifp->Name[Inet::InterfaceId::kMaxIfNameLength - 1] = '\0'; ifp->name = CharSpan::fromCharString(ifp->Name); - ifp->fabricConnected = true; ifp->type = EMBER_ZCL_INTERFACE_TYPE_WI_FI; ifp->offPremiseServicesReachableIPv4.SetNonNull(false); ifp->offPremiseServicesReachableIPv6.SetNonNull(false); diff --git a/src/platform/device.gni b/src/platform/device.gni index 0524b1cf36c45a..566a4c415878c1 100755 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -71,7 +71,7 @@ declare_args() { chip_enable_nfc = false # Enable OTA requestor support - chip_enable_ota_requestor = true + chip_enable_ota_requestor = false # Select DNS-SD implementation if (chip_device_platform == "linux" || chip_device_platform == "esp32" || From abf15841fb4856f0231169d5bac4c57be23d61c8 Mon Sep 17 00:00:00 2001 From: "fuxing.guo" Date: Tue, 12 Apr 2022 16:40:11 +0800 Subject: [PATCH 13/20] When the Beken driver malloc spaces from MEM_HEAP TYPE,the device would be corruption on commissioning.This modifcation will resovle the problem. Change-Id: I8b37a4ea3a90e08d34a7cb6f37e56b76238d57d8 --- .../lighting-app/beken/main/chipinterface.cpp | 52 ++++++++++++++++++- src/inet/UDPEndPointImplLwIP.cpp | 6 ++- src/system/SystemPacketBuffer.cpp | 18 ++++++- 3 files changed, 73 insertions(+), 3 deletions(-) diff --git a/examples/lighting-app/beken/main/chipinterface.cpp b/examples/lighting-app/beken/main/chipinterface.cpp index 84a7dd6dedf710..7980354c2b0c3c 100755 --- a/examples/lighting-app/beken/main/chipinterface.cpp +++ b/examples/lighting-app/beken/main/chipinterface.cpp @@ -98,6 +98,14 @@ extern "C" void ApplyUpdateCmdHandler() static_cast(GetRequestorInstance())->ApplyUpdate(); } + +extern "C" void NotifyUpdateAppliedHandler(uint32_t version) +{ + ChipLogProgress(DeviceLayer, "NotifyUpdateApplied"); + + static_cast(GetRequestorInstance())->NotifyUpdateApplied(version); +} + /********************************************************************* * Funtion Name:BkQueryImageCmdHandler * @@ -155,7 +163,48 @@ extern "C" void BkQueryImageCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, extern "C" void BkApplyUpdateCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv ) { ApplyUpdateCmdHandler(); - ChipLogProgress(DeviceLayer,"ApplyUpdateCmdHandler send requst"); + ChipLogProgress(DeviceLayer,"ApplyUpdateCmdHandler send request"); + + return ; +} + +/********************************************************************* + * Funtion Name:BkNotifyUpdateApplied + * + * Funtion Discription:trigger ota requestor notify update applied to ota provider + * + * + * Date:2022-03-10 + *******************************************************************/ +extern "C" void BkNotifyUpdateApplied(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv ) +{ + uint32_t dwLoop = 0; + uint32_t version = 0; + + char cmd0 = 0; + char cmd1 = 0; + + for(dwLoop = 0; dwLoop < argc; dwLoop++) + { + ChipLogProgress(DeviceLayer, "NotifyUpdateApplied %d = %s\r\n", dwLoop + 1, argv[dwLoop]); + } + + if(argc == 2) + { + cmd0 = argv[1][0] - 0x30; + cmd1 = argv[1][1] - 0x30; + version = (uint32_t)(cmd0 * 10 + cmd1); + + ChipLogProgress(DeviceLayer, "version %lu \r\n", version); + } + else + { + ChipLogProgress(DeviceLayer,"cmd param error "); + return ; + } + + NotifyUpdateAppliedHandler( version); + ChipLogProgress(DeviceLayer,"NotifyUpdateApplied send request"); return ; } @@ -164,6 +213,7 @@ static void InitOTARequestor(void) { // Initialize and interconnect the Requestor and Image Processor objects -- START SetRequestorInstance(&gRequestorCore); + ChipLogProgress(DeviceLayer,"InitOTARequestor gRequestorCore init"); // Set server instance used for session establishment /* - Set server instance used to get access to the system resources necessary to open CASE sessions and drive diff --git a/src/inet/UDPEndPointImplLwIP.cpp b/src/inet/UDPEndPointImplLwIP.cpp index b3ce8a24705eb1..3b0845ac66ab66 100644 --- a/src/inet/UDPEndPointImplLwIP.cpp +++ b/src/inet/UDPEndPointImplLwIP.cpp @@ -471,7 +471,11 @@ struct netif * UDPEndPointImplLwIP::FindNetifFromInterfaceId(InterfaceId aInterf IPPacketInfo * UDPEndPointImplLwIP::GetPacketInfo(const System::PacketBufferHandle & aBuffer) { - if (!aBuffer->EnsureReservedSize(sizeof(IPPacketInfo) + 3)) + //The original Matter codes + //if (!aBuffer->EnsureReservedSize(sizeof(IPPacketInfo) + 3)) + + //Modify by Beken CorPoration + if (!aBuffer->EnsureReservedSize(sizeof(IPPacketInfo))) { return nullptr; } diff --git a/src/system/SystemPacketBuffer.cpp b/src/system/SystemPacketBuffer.cpp index 3f6c136bcb152b..6d8ac7dd1433f7 100644 --- a/src/system/SystemPacketBuffer.cpp +++ b/src/system/SystemPacketBuffer.cpp @@ -387,11 +387,27 @@ CHIP_ERROR PacketBuffer::Read(uint8_t * aDestination, size_t aReadLength) const bool PacketBuffer::EnsureReservedSize(uint16_t aReservedSize) { const uint16_t kCurrentReservedSize = this->ReservedSize(); + uint32_t dwReturn = 0; + uint32_t dwAllocsize = 0; + if (aReservedSize <= kCurrentReservedSize) return true; + //The original Matter codes + //if ((aReservedSize + this->len) > this->AllocSize()) + + /*============= Modify by Beken Corporation============*/ + /*========================START========================*/ + dwReturn = pbuf_length_get (this, &dwAllocsize); + ChipLogError(chipSystemLayer, "The pbuf type is wrong"); - if ((aReservedSize + this->len) > this->AllocSize()) + if ((aReservedSize + this->len) > dwAllocsize) + { + ChipLogError(chipSystemLayer, "The pbuf space is not adequte"); return false; + } + /*============= Modify by Beken Corporation============*/ + /*========================END========================*/ + // Cast is safe because aReservedSize > kCurrentReservedSize. const uint16_t kMoveLength = static_cast(aReservedSize - kCurrentReservedSize); From 2b848cf2bacb93168cdd470519f31e58b9e3e1bc Mon Sep 17 00:00:00 2001 From: "yongjia.fang" Date: Wed, 20 Apr 2022 17:14:48 +0800 Subject: [PATCH 14/20] Add networkcommission interface:ScanNetworks & GetConnectedNetwork --- .../Beken/NetworkCommissioningDriver.h | 34 ++++++++ .../Beken/NetworkCommissioningWiFiDriver.cpp | 79 ++++++++++--------- 2 files changed, 77 insertions(+), 36 deletions(-) diff --git a/src/platform/Beken/NetworkCommissioningDriver.h b/src/platform/Beken/NetworkCommissioningDriver.h index 2219e8c33b36ae..0bf39b9fcb97e1 100755 --- a/src/platform/Beken/NetworkCommissioningDriver.h +++ b/src/platform/Beken/NetworkCommissioningDriver.h @@ -17,6 +17,9 @@ #pragma once #include +#include "wlan_ui_pub.h" + +#define NC_SECURITYCONVERT(security) ((security < 3) ? security : (security == 3) ? 2 : (security < 7) ? 3 : 4 ) namespace chip { namespace DeviceLayer { @@ -28,6 +31,37 @@ constexpr uint8_t kWiFiScanNetworksTimeOutSeconds = 10; constexpr uint8_t kWiFiConnectNetworkTimeoutSeconds = 20; } // namespace +class BKScanResponseIterator : public Iterator +{ +public: + BKScanResponseIterator(const size_t size, const ScanResult_adv * scanResults) : mSize(size), mpScanResults(scanResults) {} + size_t Count() override { return mSize; } + bool Next(WiFiScanResponse & item) override + { + if (mIternum >= mSize) + { + return false; + } + uint8_t ssidlenth = strlen(mpScanResults->ApList[mIternum].ssid); + item.security = NC_SECURITYCONVERT(mpScanResults->ApList[mIternum].security); + item.ssidLen = ssidlenth; + item.channel = mpScanResults->ApList[mIternum].channel; + item.wiFiBand = chip::DeviceLayer::NetworkCommissioning::WiFiBand::k2g4; + item.rssi = mpScanResults->ApList[mIternum].ApPower; + memcpy(item.ssid, mpScanResults->ApList[mIternum].ssid, ssidlenth); + memcpy(item.bssid, mpScanResults->ApList[mIternum].bssid, 6); + + mIternum++; + return true; + } + void Release() override {} + +private: + const size_t mSize; + const ScanResult_adv * mpScanResults; + size_t mIternum = 0; +}; + class BekenWiFiDriver final : public WiFiDriver { public: diff --git a/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp b/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp index 2bd1260d063557..480757dec91962 100755 --- a/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp +++ b/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp @@ -37,6 +37,8 @@ constexpr char kWiFiCredentialsKeyName[] = "wifi-pass"; static uint8_t WiFiSSIDStr[DeviceLayer::Internal::kMaxWiFiSSIDLength]; } // namespace + + CHIP_ERROR BekenWiFiDriver::Init() { ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::Init\r\n"); @@ -148,8 +150,8 @@ CHIP_ERROR BekenWiFiDriver::ConnectWiFiNetwork(const char * ssid, uint8_t ssidLe void BekenWiFiDriver::OnConnectWiFiNetwork() { - ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::OnConnectWiFiNetwork\r\n"); - if (mpConnectCallback) + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::OnConnectWiFiNetwork\r\n"); + if (mpConnectCallback) { mpConnectCallback->OnResult(Status::kSuccess, CharSpan(), 0); mpConnectCallback = nullptr; @@ -158,6 +160,7 @@ void BekenWiFiDriver::OnConnectWiFiNetwork() void BekenWiFiDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) { + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::ConnectNetwork\r\n"); CHIP_ERROR err = CHIP_NO_ERROR; Status networkingStatus = Status::kSuccess; @@ -187,45 +190,60 @@ CHIP_ERROR BekenWiFiDriver::StartScanWiFiNetworks(ByteSpan ssid) if (ssid.data())//directed scanning { uint8_t **ssid_array; - uint8_t * oob_ssid; - memcpy(oob_ssid,ssid.data(),ssid.size()); - ssid_array = &oob_ssid; - ChipLogProgress(NetworkProvisioning, "StartScanWiFiNetworks... ssid:%s\r\n", ssid.data()); - bk_wlan_start_assign_scan(ssid_array, 1); + uint8_t *oob_ssid = (uint8_t*)malloc(ssid.size()*sizeof(uint8_t)); + memcpy(oob_ssid,ssid.data(),ssid.size()); + ChipLogProgress(NetworkProvisioning, "directed scanning... ssid:%s ; %d \r\n",oob_ssid,ssid.size()); + ssid_array = &oob_ssid; + bk_wlan_start_assign_scan(ssid_array, 1); } else//non-directed scanning { + ChipLogProgress(NetworkProvisioning, "non-directed scanning...\r\n" ); bk_wlan_start_scan(); } - return CHIP_NO_ERROR; } void BekenWiFiDriver::OnScanWiFiNetworkDone() { ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::OnScanWiFiNetworkDone\r\n"); - char scan_rst_ap_num = 0; - scan_rst_ap_num = bk_wlan_get_scan_ap_result_numbers(); + ScanResult_adv apList; + int scan_rst_ap_num = 0; + if (wlan_sta_scan_result(&apList) == 0) { + scan_rst_ap_num = apList.ApNum; + ChipLogProgress(NetworkProvisioning,"Got ap count: %d\r\n", apList.ApNum); + } if(scan_rst_ap_num == 0) { os_printf("NULL AP\r\n"); + GetInstance().mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), nullptr); + GetInstance().mpScanCallback = nullptr; return; } - sta_scan_res *scan_rst_table = ( sta_scan_res *)pvPortMalloc(sizeof(sta_scan_res) * scan_rst_ap_num); - if(scan_rst_table == NULL) + BKScanResponseIterator iter(scan_rst_ap_num, &apList); + if (GetInstance().mpScanCallback) { - os_printf("scan_rst_table malloc failed!\r\n"); - return; + GetInstance().mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), &iter); + GetInstance().mpScanCallback = nullptr; + } + else + { + ChipLogProgress(NetworkProvisioning, "can't find the ScanCallback function\r\n"); } - bk_wlan_get_scan_ap_result(scan_rst_table, scan_rst_ap_num); - +} + +void scan_ap_cb(void *ctxt, uint8_t param) +{ + NetworkCommissioning::BekenWiFiDriver::GetInstance().OnScanWiFiNetworkDone(); } void BekenWiFiDriver::ScanNetworks(ByteSpan ssid, WiFiDriver::ScanCallback * callback) { + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::ScanNetworks\r\n"); if (callback != nullptr) { mpScanCallback = callback; + bk_wlan_scan_ap_reg_cb(scan_ap_cb); if (StartScanWiFiNetworks(ssid) != CHIP_NO_ERROR) { mpScanCallback = nullptr; @@ -236,29 +254,19 @@ void BekenWiFiDriver::ScanNetworks(ByteSpan ssid, WiFiDriver::ScanCallback * cal CHIP_ERROR GetConnectedNetwork(Network & network) { - ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver GetConnectedNetwork\r\n"); -#ifdef FANG - wifi_ap_record_t ap_info; - esp_err_t err; - err = esp_wifi_sta_get_ap_info(&ap_info); - if (err != ESP_OK) - { - return chip::DeviceLayer::Internal::ESP32Utils::MapError(err); - } - uint8_t length = strnlen(reinterpret_cast(ap_info.ssid), DeviceLayer::Internal::kMaxWiFiSSIDLength); - if (length > sizeof(network.networkID)) - { - return CHIP_ERROR_INTERNAL; - } - memcpy(network.networkID, ap_info.ssid, length); - network.networkIDLen = length; -#endif + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::GetConnectedNetwork\r\n"); + LinkStatusTypeDef wifi_setting={0}; + bk_wlan_get_link_status(&wifi_setting); + uint8_t length = strnlen(reinterpret_cast(wifi_setting.ssid), DeviceLayer::Internal::kMaxWiFiSSIDLength); + memcpy(network.networkID, wifi_setting.ssid, length); + ChipLogProgress(NetworkProvisioning, "networkID:[%s][%d]\r\n",network.networkID,length); + network.networkIDLen = sizeof(network.networkID); return CHIP_NO_ERROR; } size_t BekenWiFiDriver::WiFiNetworkIterator::Count() { - ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::WiFiNetworkIterator::Count\r\n"); + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::WiFiNetworkIterator::Count\r\n"); return mDriver->mStagingNetwork.ssidLen == 0 ? 0 : 1; } @@ -273,8 +281,7 @@ bool BekenWiFiDriver::WiFiNetworkIterator::Next(Network & item) item.networkIDLen = mDriver->mStagingNetwork.ssidLen; item.connected = false; mExhausted = true; - - Network connectedNetwork; + Network connectedNetwork={0}; CHIP_ERROR err = GetConnectedNetwork(connectedNetwork); if (err == CHIP_NO_ERROR) { From d77202d0d7fa6b50f81e9a5c763eb3c2787adc9c Mon Sep 17 00:00:00 2001 From: "fuxing.guo" Date: Tue, 26 Apr 2022 16:31:32 +0800 Subject: [PATCH 15/20] Resolve the problem that device print 'watchdog triggered'. This problem is caused by different threads operation on variable in same time. Change-Id: I35b8619cbe136862ba80aef9148f00724413bad5 --- src/lib/core/ReferenceCounted.h | 69 +++++++++++++++++-- src/platform/Beken/CHIPDevicePlatformConfig.h | 2 +- 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/src/lib/core/ReferenceCounted.h b/src/lib/core/ReferenceCounted.h index 2d59af288c842c..c98fc4bbd819d3 100644 --- a/src/lib/core/ReferenceCounted.h +++ b/src/lib/core/ReferenceCounted.h @@ -29,6 +29,8 @@ #include #include +#include "FreeRTOS.h" +#include "semphr.h" namespace chip { @@ -49,12 +51,41 @@ class ReferenceCounted public: using count_type = uint32_t; + //=============Add by Beken Corporation Start====================// + ReferenceCounted() + { + mRefCountMutex = xSemaphoreCreateMutex(); + + if (mRefCountMutex == NULL) + { + os_printf("Failed to create CHIP mRefCountMutex \r\n"); + } + } + + ~ReferenceCounted() + { + vSemaphoreDelete(mRefCountMutex); + } + + void LockMrefcountChipStack() + { + xSemaphoreTake(mRefCountMutex, portMAX_DELAY); + } + + void UnlockMrefcountChipStack() + { + xSemaphoreGive(mRefCountMutex); + } + //=============Add by Beken Corporation End====================// + /** Adds one to the usage count of this class */ + Subclass * Retain() { - VerifyOrDie(!kInitRefCount || mRefCount > 0); - VerifyOrDie(mRefCount < std::numeric_limits::max()); - ++mRefCount; + VerifyOrDie(!kInitRefCount || GetReferenceCount() > 0);//Modified by Beken Corporation + VerifyOrDie(GetReferenceCount() < std::numeric_limits::max()); + //++mRefCount; + IncrementReferenceCount();//Modified by Beken Corporation return static_cast(this); } @@ -62,19 +93,43 @@ class ReferenceCounted /** Release usage of this class */ void Release() { - VerifyOrDie(mRefCount != 0); - - if (--mRefCount == 0) + VerifyOrDie(GetReferenceCount() != 0); + //if (--mRefCount == 0) + if (DecrementReferenceCount() == 0)//Modified by Beken Corporation { Deletor::Release(static_cast(this)); } } /** Get the current reference counter value */ - count_type GetReferenceCount() const { return mRefCount; } + //Modified by Beken Corporation + count_type GetReferenceCount() { + count_type RefCount; + LockMrefcountChipStack(); + RefCount = mRefCount; + UnlockMrefcountChipStack(); + return RefCount; + } + //=============Add by Beken Corporation Start====================// + void IncrementReferenceCount() + { + LockMrefcountChipStack(); + ++mRefCount; + UnlockMrefcountChipStack(); + } + + count_type DecrementReferenceCount() + { + LockMrefcountChipStack(); + --mRefCount; + UnlockMrefcountChipStack(); + return mRefCount; + } + //=============Add by Beken Corporation End====================// private: count_type mRefCount = kInitRefCount; + SemaphoreHandle_t mRefCountMutex;//Add by Beken Corporation Start }; } // namespace chip diff --git a/src/platform/Beken/CHIPDevicePlatformConfig.h b/src/platform/Beken/CHIPDevicePlatformConfig.h index cc0996df75f511..e0089311c91fa1 100755 --- a/src/platform/Beken/CHIPDevicePlatformConfig.h +++ b/src/platform/Beken/CHIPDevicePlatformConfig.h @@ -67,7 +67,7 @@ #define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 #define CONFIG_RENDEZVOUS_MODE 6 -#define CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY 2 +#define CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY 1 #define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 #define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DISCOVERY 1 From 623951ecdf4eb19a121a3ae7b88ae34425d5daee Mon Sep 17 00:00:00 2001 From: "jun.luo" Date: Mon, 9 May 2022 11:31:58 +0800 Subject: [PATCH 16/20] Sync with TE9 --- config/beken/BUILD.gn | 3 + config/beken/args.gni | 1 - .../lighting-app/beken/main/chipinterface.cpp | 57 +++++++++----- src/platform/Beken/BLEManagerImpl.cpp | 21 ++++-- src/platform/Beken/BUILD.gn | 4 +- .../Beken/ConfigurationManagerImpl.cpp | 11 +-- .../Beken/ConnectivityManagerImpl.cpp | 6 +- .../Beken/DiagnosticDataProviderImpl.cpp | 4 +- .../Beken/DiagnosticDataProviderImpl.h | 2 +- .../Beken/KeyValueStoreManagerImpl.cpp | 17 +---- .../Beken/NetworkCommissioningDriver.h | 18 +++-- .../Beken/NetworkCommissioningWiFiDriver.cpp | 75 ++++++++++++++----- src/platform/Beken/OTAImageProcessorImpl.cpp | 1 + src/platform/Beken/PlatformManagerImpl.cpp | 2 +- src/platform/device.gni | 14 +--- 15 files changed, 144 insertions(+), 92 deletions(-) diff --git a/config/beken/BUILD.gn b/config/beken/BUILD.gn index 96ae17d002e087..d497e377fcd0f8 100644 --- a/config/beken/BUILD.gn +++ b/config/beken/BUILD.gn @@ -24,3 +24,6 @@ group("beken") { deps = [ "${chip_root}/src/lib" ] } +group("default") { + deps = [ ":beken" ] +} diff --git a/config/beken/args.gni b/config/beken/args.gni index c62b92ac11e375..b3ee09f91afa28 100755 --- a/config/beken/args.gni +++ b/config/beken/args.gni @@ -29,7 +29,6 @@ chip_build_tests = false chip_inet_config_enable_tcp_endpoint = true chip_inet_config_enable_udp_endpoint = true -chip_bypass_rendezvous = false chip_config_network_layer_ble = true chip_config_memory_management = "platform" chip_enable_additional_data_advertising = true diff --git a/examples/lighting-app/beken/main/chipinterface.cpp b/examples/lighting-app/beken/main/chipinterface.cpp index 7980354c2b0c3c..fda92e01373337 100755 --- a/examples/lighting-app/beken/main/chipinterface.cpp +++ b/examples/lighting-app/beken/main/chipinterface.cpp @@ -34,13 +34,15 @@ #include //#if CONFIG_ENABLE_OTA_REQUESTOR -#include "app/clusters/ota-requestor/BDXDownloader.h" -#include "app/clusters/ota-requestor/OTARequestor.h" -#include "platform/Beken/OTAImageProcessorImpl.h" -#include "platform/GenericOTARequestorDriver.h" +#include "app/clusters/ota-requestor/DefaultOTARequestorStorage.h" +#include +#include +#include +#include +#include //#endif -using chip::OTAImageProcessorImpl; +//using chip::OTAImageProcessorImpl; using chip::BDXDownloader; using chip::ByteSpan; using chip::EndpointId; @@ -50,8 +52,8 @@ using chip::NodeId; using chip::OnDeviceConnected; using chip::OnDeviceConnectionFailure; using chip::OTADownloader; -using chip::OTAImageProcessorParams; -using chip::OTARequestor; +//using chip::OTAImageProcessorParams; +//using chip::OTARequestor; using chip::VendorId; using chip::Callback::Callback; using chip::System::Layer; @@ -69,10 +71,10 @@ using namespace ::chip::System; namespace { static DeviceCallbacks EchoCallbacks; -OTARequestor gRequestorCore; -GenericOTARequestorDriver gRequestorUser; +//OTARequestor gRequestorCore; +//GenericOTARequestorDriver gRequestorUser; BDXDownloader gDownloader; -OTAImageProcessorImpl gImageProcessor; +//OTAImageProcessorImpl gImageProcessor; app::Clusters::NetworkCommissioning::Instance sWiFiNetworkCommissioningInstance(0 /* Endpoint Id */, &(NetworkCommissioning::BekenWiFiDriver::GetInstance())); @@ -89,21 +91,21 @@ bool isRendezvousBLE() extern "C" void QueryImageCmdHandler() { ChipLogProgress(DeviceLayer, "Calling QueryImageCmdHandler"); - static_cast(GetRequestorInstance())->TriggerImmediateQuery(); + //static_cast(GetRequestorInstance())->TriggerImmediateQuery(); } extern "C" void ApplyUpdateCmdHandler() { ChipLogProgress(DeviceLayer, "Calling ApplyUpdateCmdHandler"); - static_cast(GetRequestorInstance())->ApplyUpdate(); + //static_cast(GetRequestorInstance())->ApplyUpdate(); } extern "C" void NotifyUpdateAppliedHandler(uint32_t version) { ChipLogProgress(DeviceLayer, "NotifyUpdateApplied"); - static_cast(GetRequestorInstance())->NotifyUpdateApplied(version); + //static_cast(GetRequestorInstance())->NotifyUpdateApplied(version); } /********************************************************************* @@ -145,9 +147,10 @@ extern "C" void BkQueryImageCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, ChipLogProgress(DeviceLayer,"cmd param error "); return ; } -#endif + QueryImageCmdHandler(); ChipLogProgress(DeviceLayer,"QueryImageCmdHandler begin"); +#endif return ; } @@ -162,7 +165,7 @@ extern "C" void BkQueryImageCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, *******************************************************************/ extern "C" void BkApplyUpdateCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv ) { - ApplyUpdateCmdHandler(); + //ApplyUpdateCmdHandler(); ChipLogProgress(DeviceLayer,"ApplyUpdateCmdHandler send request"); return ; @@ -178,6 +181,7 @@ extern "C" void BkApplyUpdateCmdHandler(char *pcWriteBuffer, int xWriteBufferLen *******************************************************************/ extern "C" void BkNotifyUpdateApplied(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv ) { +#if 0 uint32_t dwLoop = 0; uint32_t version = 0; @@ -205,12 +209,13 @@ extern "C" void BkNotifyUpdateApplied(char *pcWriteBuffer, int xWriteBufferLen, NotifyUpdateAppliedHandler( version); ChipLogProgress(DeviceLayer,"NotifyUpdateApplied send request"); - +#endif return ; } static void InitOTARequestor(void) { +#if 0 // Initialize and interconnect the Requestor and Image Processor objects -- START SetRequestorInstance(&gRequestorCore); ChipLogProgress(DeviceLayer,"InitOTARequestor gRequestorCore init"); @@ -234,7 +239,7 @@ static void InitOTARequestor(void) // Connect the Downloader and Image Processor objects gDownloader.SetImageProcessorDelegate(&gImageProcessor); gRequestorUser.Init(&gRequestorCore, &gImageProcessor); - +#endif // Initialize and interconnect the Requestor and Image Processor objects -- END } //#endif // CONFIG_ENABLE_OTA_REQUESTOR @@ -341,6 +346,20 @@ extern "C" bool __sync_bool_compare_and_swap_4(volatile void* ptr, unsigned int return false; } } + +extern "C" bool __sync_bool_compare_and_swap_1(volatile void* ptr, unsigned char oldval, unsigned char newval) +{ + if (*(unsigned char*)ptr == oldval) + { + *(unsigned char*)ptr = newval; + return true; + } + else + { + return false; + } +} + /* stub for __libc_init_array */ extern "C" void _fini(void) { } extern "C" void _init(void) {;} @@ -348,7 +367,9 @@ extern "C" void _init(void) {;} static void InitServer(intptr_t context) { // Init ZCL Data Model and CHIP App Server - chip::Server::GetInstance().Init(); + static chip::CommonCaseDeviceServerInitParams initParams; + (void) initParams.InitializeStaticResourcesBeforeServerInit(); + chip::Server::GetInstance().Init(initParams); // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/src/platform/Beken/BLEManagerImpl.cpp b/src/platform/Beken/BLEManagerImpl.cpp index 8166c0f5f25519..7b305930a1253d 100755 --- a/src/platform/Beken/BLEManagerImpl.cpp +++ b/src/platform/Beken/BLEManagerImpl.cpp @@ -25,6 +25,8 @@ /* this file behaves like a config.h, comes first */ #include #include +#include + #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include @@ -635,7 +637,7 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) // If the device name is not specified, generate a CHIP-standard name based on the bottom digits of the Chip device id. uint16_t discriminator; - SuccessOrExit(err = ConfigurationMgr().GetSetupDiscriminator(discriminator)); + SuccessOrExit(err = GetCommissionableDataProvider()->GetSetupDiscriminator(discriminator)); if (!mFlags.Has(Flags::kDeviceNameSet)) { @@ -1063,20 +1065,23 @@ void BLEManagerImpl::HandleC3CharRead(void * param) chip::System::PacketBufferHandle bufferHandle; read_req_t *r_req = (read_req_t *)param; - char serialNumber[ConfigurationManager::kMaxSerialNumberLength + 1]; - uint16_t lifetimeCounter = 0; + AdditionalDataPayloadGeneratorParams additionalDataPayloadParams; BitFlags additionalDataFields; -#if CHIP_ENABLE_ROTATING_DEVICE_ID - err = ConfigurationMgr().GetSerialNumber(serialNumber, sizeof(serialNumber)); + +#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) + uint8_t rotatingDeviceIdUniqueId[ConfigurationManager::kRotatingDeviceIDUniqueIDLength] = {}; + MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId); + + err = ConfigurationMgr().GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan); SuccessOrExit(err); - err = ConfigurationMgr().GetLifetimeCounter(lifetimeCounter); + err = ConfigurationMgr().GetLifetimeCounter(additionalDataPayloadParams.rotatingDeviceIdLifetimeCounter); SuccessOrExit(err); - + additionalDataPayloadParams.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan; additionalDataFields.Set(AdditionalDataFields::RotatingDeviceId); #endif /* CHIP_ENABLE_ROTATING_DEVICE_ID */ - err = AdditionalDataPayloadGenerator().generateAdditionalDataPayload(lifetimeCounter, serialNumber, strlen(serialNumber), + err = AdditionalDataPayloadGenerator().generateAdditionalDataPayload(additionalDataPayloadParams, bufferHandle, additionalDataFields); SuccessOrExit(err); if(r_req->value == NULL) diff --git a/src/platform/Beken/BUILD.gn b/src/platform/Beken/BUILD.gn index 808eb1c5b9e669..80bbe31a5a06bc 100755 --- a/src/platform/Beken/BUILD.gn +++ b/src/platform/Beken/BUILD.gn @@ -38,8 +38,8 @@ static_library("Beken") { "KeyValueStoreManagerImpl.h", "Logging.cpp", "LwIPCoreLock.cpp", - "OTAImageProcessorImpl.cpp", - "OTAImageProcessorImpl.h", + #"OTAImageProcessorImpl.cpp", + #"OTAImageProcessorImpl.h", "PlatformManagerImpl.cpp", "PlatformManagerImpl.h", "SoftwareUpdateManagerImpl.h", diff --git a/src/platform/Beken/ConfigurationManagerImpl.cpp b/src/platform/Beken/ConfigurationManagerImpl.cpp index 6126bc795fdf67..74ba241e4f66b9 100644 --- a/src/platform/Beken/ConfigurationManagerImpl.cpp +++ b/src/platform/Beken/ConfigurationManagerImpl.cpp @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include #include @@ -48,7 +48,6 @@ CHIP_ERROR ConfigurationManagerImpl::Init() { CHIP_ERROR err; uint32_t rebootCount; - bool failSafeArmed; ChipLogProgress(DeviceLayer, "ConfigurationManagerImpl::Init"); // Force initialization of NVS namespaces if they doesn't already exist. @@ -82,7 +81,7 @@ CHIP_ERROR ConfigurationManagerImpl::Init() if (!BekenConfig::ConfigValueExists(BekenConfig::kCounterKey_BootReason)) { - err = StoreBootReason(DiagnosticDataProvider::BootReasonType::Unspecified); + err = StoreBootReason(to_underlying(BootReasonType::kUnspecified)); SuccessOrExit(err); } @@ -90,12 +89,6 @@ CHIP_ERROR ConfigurationManagerImpl::Init() err = Internal::GenericConfigurationManagerImpl::Init(); SuccessOrExit(err); - // If the fail-safe was armed when the device last shutdown, initiate a factory reset. - if (GetFailSafeArmed(failSafeArmed) == CHIP_NO_ERROR && failSafeArmed) - { - ChipLogProgress(DeviceLayer, "Detected fail-safe armed on reboot; initiating factory reset"); - InitiateFactoryReset(); - } err = CHIP_NO_ERROR; exit: diff --git a/src/platform/Beken/ConnectivityManagerImpl.cpp b/src/platform/Beken/ConnectivityManagerImpl.cpp index 1445912a71eca4..20f4fd49586c78 100755 --- a/src/platform/Beken/ConnectivityManagerImpl.cpp +++ b/src/platform/Beken/ConnectivityManagerImpl.cpp @@ -21,15 +21,15 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include +#include #endif #if CHIP_DEVICE_CONFIG_ENABLE_WIFI -#include +#include #endif #include diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.cpp b/src/platform/Beken/DiagnosticDataProviderImpl.cpp index cf4527d8643e2b..2dfd13e9fc9f64 100644 --- a/src/platform/Beken/DiagnosticDataProviderImpl.cpp +++ b/src/platform/Beken/DiagnosticDataProviderImpl.cpp @@ -104,7 +104,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetTotalOperationalHours(uint32_t & total return CHIP_ERROR_INVALID_TIME; } -CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(uint8_t & bootReason) +CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason) { uint32_t reason = 0; @@ -113,7 +113,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(uint8_t & bootReason) if (err == CHIP_NO_ERROR) { VerifyOrReturnError(reason <= UINT8_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); - bootReason = static_cast(reason); + bootReason = static_cast(reason); } return err; diff --git a/src/platform/Beken/DiagnosticDataProviderImpl.h b/src/platform/Beken/DiagnosticDataProviderImpl.h index 155b657560c4aa..c599b109645a7c 100644 --- a/src/platform/Beken/DiagnosticDataProviderImpl.h +++ b/src/platform/Beken/DiagnosticDataProviderImpl.h @@ -44,7 +44,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider CHIP_ERROR GetRebootCount(uint16_t & rebootCount) override; CHIP_ERROR GetUpTime(uint64_t & upTime) override; CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours) override; - CHIP_ERROR GetBootReason(uint8_t & bootReason) override; + CHIP_ERROR GetBootReason(BootReasonType & bootReason) override; CHIP_ERROR GetNetworkInterfaces(NetworkInterface ** netifpp) override; void ReleaseNetworkInterfaces(NetworkInterface * netifp) override; diff --git a/src/platform/Beken/KeyValueStoreManagerImpl.cpp b/src/platform/Beken/KeyValueStoreManagerImpl.cpp index cef17544bf61fb..bb387b3f2a6ae8 100755 --- a/src/platform/Beken/KeyValueStoreManagerImpl.cpp +++ b/src/platform/Beken/KeyValueStoreManagerImpl.cpp @@ -65,7 +65,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t } else { - err = CHIP_ERROR_INTERNAL; + err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; } return err; @@ -99,19 +99,10 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) { uint32_t ret = 0; CHIP_ERROR err = CHIP_NO_ERROR; - - ret = bk_clean_data (GetKVNameSpaceName(key), key); - - if (kNoErr == ret) - { - err = CHIP_NO_ERROR; - } - else - { - err = CHIP_ERROR_INTERNAL; - } - return err; + bk_clean_data (GetKVNameSpaceName(key), key); + + return CHIP_NO_ERROR; } const char* KeyValueStoreManagerImpl::GetKVNameSpaceName(const char *key) diff --git a/src/platform/Beken/NetworkCommissioningDriver.h b/src/platform/Beken/NetworkCommissioningDriver.h index 0bf39b9fcb97e1..3b9fd415f875b0 100755 --- a/src/platform/Beken/NetworkCommissioningDriver.h +++ b/src/platform/Beken/NetworkCommissioningDriver.h @@ -43,7 +43,7 @@ class BKScanResponseIterator : public Iterator return false; } uint8_t ssidlenth = strlen(mpScanResults->ApList[mIternum].ssid); - item.security = NC_SECURITYCONVERT(mpScanResults->ApList[mIternum].security); + item.security.SetRaw(NC_SECURITYCONVERT(mpScanResults->ApList[mIternum].security)); item.ssidLen = ssidlenth; item.channel = mpScanResults->ApList[mIternum].channel; item.wiFiBand = chip::DeviceLayer::NetworkCommissioning::WiFiBand::k2g4; @@ -91,7 +91,7 @@ class BekenWiFiDriver final : public WiFiDriver // BaseDriver NetworkIterator * GetNetworks() override { return new WiFiNetworkIterator(this); } - CHIP_ERROR Init() override; + CHIP_ERROR Init(NetworkStatusChangeCallback * networkStatusChangeCallback) override; CHIP_ERROR Shutdown() override; // WirelessDriver @@ -102,17 +102,23 @@ class BekenWiFiDriver final : public WiFiDriver CHIP_ERROR CommitConfiguration() override; CHIP_ERROR RevertConfiguration() override; - Status RemoveNetwork(ByteSpan networkId) override; - Status ReorderNetwork(ByteSpan networkId, uint8_t index) override; + Status RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) override; + Status ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) override; void ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) override; // WiFiDriver - Status AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials) override; + Status AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials, MutableCharSpan & outDebugText, + uint8_t & outNetworkIndex) override; void ScanNetworks(ByteSpan ssid, ScanCallback * callback) override; CHIP_ERROR ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, const char * key, uint8_t keyLen); void OnConnectWiFiNetwork(); void OnScanWiFiNetworkDone(); + void OnNetworkStatusChange(); + + CHIP_ERROR SetLastDisconnectReason(const ChipDeviceEvent * event); + int32_t GetLastDisconnectReason(); + static BekenWiFiDriver & GetInstance() { static BekenWiFiDriver instance; @@ -128,6 +134,8 @@ class BekenWiFiDriver final : public WiFiDriver WiFiNetwork mStagingNetwork; ScanCallback * mpScanCallback; ConnectCallback * mpConnectCallback; + NetworkStatusChangeCallback * mpStatusChangeCallback = nullptr; + int32_t mLastDisconnectedReason; }; } // namespace NetworkCommissioning diff --git a/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp b/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp index 480757dec91962..c5a6118595f7c1 100755 --- a/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp +++ b/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp @@ -34,12 +34,12 @@ namespace NetworkCommissioning { namespace { constexpr char kWiFiSSIDKeyName[] = "wifi-ssid"; constexpr char kWiFiCredentialsKeyName[] = "wifi-pass"; -static uint8_t WiFiSSIDStr[DeviceLayer::Internal::kMaxWiFiSSIDLength]; + } // namespace -CHIP_ERROR BekenWiFiDriver::Init() +CHIP_ERROR BekenWiFiDriver::Init(NetworkStatusChangeCallback * networkStatusChangeCallback) { ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::Init\r\n"); CHIP_ERROR err; @@ -64,11 +64,13 @@ CHIP_ERROR BekenWiFiDriver::Init() mStagingNetwork = mSavedNetwork; mpScanCallback = nullptr; mpConnectCallback = nullptr; + mpStatusChangeCallback = networkStatusChangeCallback; return err; } CHIP_ERROR BekenWiFiDriver::Shutdown() { + mpStatusChangeCallback = nullptr; return CHIP_NO_ERROR; } @@ -95,9 +97,13 @@ bool BekenWiFiDriver::NetworkMatch(const WiFiNetwork & network, ByteSpan network return networkId.size() == network.ssidLen && memcmp(networkId.data(), network.ssid, network.ssidLen) == 0; } -Status BekenWiFiDriver::AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials) +Status BekenWiFiDriver::AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials, MutableCharSpan & outDebugText, + uint8_t & outNetworkIndex) { ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::AddOrUpdateNetwork\r\n"); + + outDebugText.reduce_size(0); + outNetworkIndex = 0; VerifyOrReturnError(mStagingNetwork.ssidLen == 0 || NetworkMatch(mStagingNetwork, ssid), Status::kBoundsExceeded); VerifyOrReturnError(credentials.size() <= sizeof(mStagingNetwork.credentials), Status::kOutOfRange); VerifyOrReturnError(ssid.size() <= sizeof(mStagingNetwork.ssid), Status::kOutOfRange); @@ -111,9 +117,12 @@ Status BekenWiFiDriver::AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials) return Status::kSuccess; } -Status BekenWiFiDriver::RemoveNetwork(ByteSpan networkId) +Status BekenWiFiDriver::RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) { ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::RemoveNetwork\r\n"); + + outDebugText.reduce_size(0); + outNetworkIndex = 0; VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); // Use empty ssid for representing invalid network @@ -121,10 +130,11 @@ Status BekenWiFiDriver::RemoveNetwork(ByteSpan networkId) return Status::kSuccess; } -Status BekenWiFiDriver::ReorderNetwork(ByteSpan networkId, uint8_t index) +Status BekenWiFiDriver::ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) { ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::ReorderNetwork\r\n"); // Only one network is supported now + outDebugText.reduce_size(0); VerifyOrReturnError(index == 0, Status::kOutOfRange); VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); return Status::kSuccess; @@ -183,6 +193,49 @@ void BekenWiFiDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callb } } +CHIP_ERROR GetConnectedNetwork(Network & network) +{ + ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::GetConnectedNetwork\r\n"); + LinkStatusTypeDef wifi_setting={0}; + bk_wlan_get_link_status(&wifi_setting); + uint8_t length = strnlen(reinterpret_cast(wifi_setting.ssid), DeviceLayer::Internal::kMaxWiFiSSIDLength); + memcpy(network.networkID, wifi_setting.ssid, length); + ChipLogProgress(NetworkProvisioning, "networkID:[%s][%d]\r\n",network.networkID,length); + network.networkIDLen = sizeof(network.networkID); + return CHIP_NO_ERROR; +} + +void BekenWiFiDriver::OnNetworkStatusChange() +{ + Network configuredNetwork = {0}; + + VerifyOrReturn(mpStatusChangeCallback != nullptr); + GetConnectedNetwork(configuredNetwork); + + if (configuredNetwork.networkID[0]) + { + mpStatusChangeCallback->OnNetworkingStatusChange( + Status::kSuccess, MakeOptional(ByteSpan(configuredNetwork.networkID, configuredNetwork.networkIDLen)), NullOptional); + return; + } + mpStatusChangeCallback->OnNetworkingStatusChange( + Status::kUnknownError, MakeOptional(ByteSpan(configuredNetwork.networkID, configuredNetwork.networkIDLen)), + MakeOptional(GetLastDisconnectReason())); +} + +CHIP_ERROR BekenWiFiDriver::SetLastDisconnectReason(const ChipDeviceEvent * event) +{ + //VerifyOrReturnError(event->Type == DeviceEventType::kRtkWiFiStationDisconnectedEvent, CHIP_ERROR_INVALID_ARGUMENT); + //mLastDisconnectedReason = wifi_get_last_error(); + //TODO + return CHIP_NO_ERROR; +} + +int32_t BekenWiFiDriver::GetLastDisconnectReason() +{ + return mLastDisconnectedReason; +} + CHIP_ERROR BekenWiFiDriver::StartScanWiFiNetworks(ByteSpan ssid) { ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::StartScanWiFiNetworks\r\n"); @@ -252,18 +305,6 @@ void BekenWiFiDriver::ScanNetworks(ByteSpan ssid, WiFiDriver::ScanCallback * cal } } -CHIP_ERROR GetConnectedNetwork(Network & network) -{ - ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::GetConnectedNetwork\r\n"); - LinkStatusTypeDef wifi_setting={0}; - bk_wlan_get_link_status(&wifi_setting); - uint8_t length = strnlen(reinterpret_cast(wifi_setting.ssid), DeviceLayer::Internal::kMaxWiFiSSIDLength); - memcpy(network.networkID, wifi_setting.ssid, length); - ChipLogProgress(NetworkProvisioning, "networkID:[%s][%d]\r\n",network.networkID,length); - network.networkIDLen = sizeof(network.networkID); - return CHIP_NO_ERROR; -} - size_t BekenWiFiDriver::WiFiNetworkIterator::Count() { ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::WiFiNetworkIterator::Count\r\n"); diff --git a/src/platform/Beken/OTAImageProcessorImpl.cpp b/src/platform/Beken/OTAImageProcessorImpl.cpp index 36d564f9b3ab8f..e6452baa9faa24 100755 --- a/src/platform/Beken/OTAImageProcessorImpl.cpp +++ b/src/platform/Beken/OTAImageProcessorImpl.cpp @@ -17,6 +17,7 @@ */ #include +#include #include #include diff --git a/src/platform/Beken/PlatformManagerImpl.cpp b/src/platform/Beken/PlatformManagerImpl.cpp index f843c485882e67..174bb68cfef186 100644 --- a/src/platform/Beken/PlatformManagerImpl.cpp +++ b/src/platform/Beken/PlatformManagerImpl.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/device.gni b/src/platform/device.gni index 566a4c415878c1..c701a2078ac7e9 100755 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -76,11 +76,7 @@ declare_args() { # Select DNS-SD implementation if (chip_device_platform == "linux" || chip_device_platform == "esp32" || chip_device_platform == "mbed" || chip_device_platform == "p6" || -<<<<<<< HEAD - chip_device_platform == "ameba" || chip_device_platform == "webos") { -======= - chip_device_platform == "ameba"|| chip_device_platform == "beken") { ->>>>>>> Add beken base code into Matter SDK + chip_device_platform == "ameba" || chip_device_platform == "webos" || chip_device_platform == "beken") { chip_mdns = "minimal" } else if (chip_device_platform == "darwin" || chip_device_platform == "cc13x2_26x2" || current_os == "android" || @@ -125,13 +121,10 @@ if (chip_device_platform == "cc13x2_26x2") { _chip_device_layer = "bouffalolab/BL602" } else if (chip_device_platform == "cyw30739") { _chip_device_layer = "CYW30739" -<<<<<<< HEAD } else if (chip_device_platform == "webos") { _chip_device_layer = "webos" -======= } else if (chip_device_platform == "beken") { _chip_device_layer = "Beken" ->>>>>>> Add beken base code into Matter SDK } if (chip_device_platform != "external") { @@ -185,9 +178,6 @@ assert( chip_device_platform == "telink" || chip_device_platform == "mbed" || chip_device_platform == "p6" || chip_device_platform == "android" || chip_device_platform == "ameba" || chip_device_platform == "cyw30739" || -<<<<<<< HEAD - chip_device_platform == "webos" || chip_device_platform == "bl602", -======= + chip_device_platform == "webos" || chip_device_platform == "bl602" || chip_device_platform == "beken", ->>>>>>> Add beken base code into Matter SDK "Please select a valid value for chip_device_platform") From df88c002296f59ce242e28f34898fdcc64123133 Mon Sep 17 00:00:00 2001 From: "fuxing.guo" Date: Tue, 17 May 2022 10:20:53 +0800 Subject: [PATCH 17/20] Synchronize OTA to TE9. Change-Id: I0c336e83cd1886912e65b2c556ed6eb19f3df5dd --- .../lighting-app/beken/main/chipinterface.cpp | 85 ++++++------- src/platform/Beken/BUILD.gn | 4 +- src/platform/Beken/OTAImageProcessorImpl.cpp | 113 ++++++++++++++---- src/platform/Beken/OTAImageProcessorImpl.h | 9 +- 4 files changed, 139 insertions(+), 72 deletions(-) diff --git a/examples/lighting-app/beken/main/chipinterface.cpp b/examples/lighting-app/beken/main/chipinterface.cpp index fda92e01373337..ce82a1980bae58 100755 --- a/examples/lighting-app/beken/main/chipinterface.cpp +++ b/examples/lighting-app/beken/main/chipinterface.cpp @@ -34,9 +34,14 @@ #include //#if CONFIG_ENABLE_OTA_REQUESTOR +#include +#include +#include +#include #include "app/clusters/ota-requestor/DefaultOTARequestorStorage.h" #include #include +#include #include #include #include @@ -45,6 +50,7 @@ //using chip::OTAImageProcessorImpl; using chip::BDXDownloader; using chip::ByteSpan; +using chip::DefaultOTARequestor; using chip::EndpointId; using chip::FabricIndex; using chip::GetRequestorInstance; @@ -52,8 +58,8 @@ using chip::NodeId; using chip::OnDeviceConnected; using chip::OnDeviceConnectionFailure; using chip::OTADownloader; -//using chip::OTAImageProcessorParams; -//using chip::OTARequestor; +using chip::PeerId; +using chip::Server; using chip::VendorId; using chip::Callback::Callback; using chip::System::Layer; @@ -61,25 +67,29 @@ using chip::Transport::PeerAddress; using namespace chip::Messaging; using namespace chip::app::Clusters::OtaSoftwareUpdateProvider::Commands; - using namespace ::chip; using namespace ::chip::Credentials; using namespace ::chip::DeviceManager; using namespace ::chip::DeviceLayer; -using namespace ::chip::System; -namespace { -static DeviceCallbacks EchoCallbacks; -//OTARequestor gRequestorCore; -//GenericOTARequestorDriver gRequestorUser; -BDXDownloader gDownloader; -//OTAImageProcessorImpl gImageProcessor; +namespace { + constexpr EndpointId kNetworkCommissioningEndpointMain = 0; + constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE; app::Clusters::NetworkCommissioning::Instance - sWiFiNetworkCommissioningInstance(0 /* Endpoint Id */, &(NetworkCommissioning::BekenWiFiDriver::GetInstance())); + sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointMain /* Endpoint Id */, &(NetworkCommissioning::BekenWiFiDriver::GetInstance())); } // namespace +static DeviceCallbacks EchoCallbacks; +DefaultOTARequestor gRequestorCore; +DefaultOTARequestorStorage gRequestorStorage; +ExtendedOTARequestorDriver gRequestorUser; +BDXDownloader gDownloader; +OTAImageProcessorImpl gImageProcessor; +chip::ota::DefaultOTARequestorUserConsent gUserConsentProvider; +static chip::ota::UserConsentState gUserConsentState = chip::ota::UserConsentState::kGranted; + // need to check CONFIG_RENDEZVOUS_MODE bool isRendezvousBLE() { @@ -91,21 +101,19 @@ bool isRendezvousBLE() extern "C" void QueryImageCmdHandler() { ChipLogProgress(DeviceLayer, "Calling QueryImageCmdHandler"); - //static_cast(GetRequestorInstance())->TriggerImmediateQuery(); + PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->TriggerImmediateQuery(); }); } extern "C" void ApplyUpdateCmdHandler() { ChipLogProgress(DeviceLayer, "Calling ApplyUpdateCmdHandler"); - - //static_cast(GetRequestorInstance())->ApplyUpdate(); + PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->ApplyUpdate(); }); } extern "C" void NotifyUpdateAppliedHandler(uint32_t version) { ChipLogProgress(DeviceLayer, "NotifyUpdateApplied"); - - //static_cast(GetRequestorInstance())->NotifyUpdateApplied(version); + PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->NotifyUpdateApplied(); }); } /********************************************************************* @@ -118,7 +126,6 @@ extern "C" void NotifyUpdateAppliedHandler(uint32_t version) *******************************************************************/ extern "C" void BkQueryImageCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv ) { -#if 0 uint32_t dwLoop = 0; uint32_t nodeId = 0; uint32_t fabricId = 0; @@ -150,7 +157,6 @@ extern "C" void BkQueryImageCmdHandler(char *pcWriteBuffer, int xWriteBufferLen, QueryImageCmdHandler(); ChipLogProgress(DeviceLayer,"QueryImageCmdHandler begin"); -#endif return ; } @@ -181,7 +187,6 @@ extern "C" void BkApplyUpdateCmdHandler(char *pcWriteBuffer, int xWriteBufferLen *******************************************************************/ extern "C" void BkNotifyUpdateApplied(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv ) { -#if 0 uint32_t dwLoop = 0; uint32_t version = 0; @@ -209,37 +214,32 @@ extern "C" void BkNotifyUpdateApplied(char *pcWriteBuffer, int xWriteBufferLen, NotifyUpdateAppliedHandler( version); ChipLogProgress(DeviceLayer,"NotifyUpdateApplied send request"); -#endif + return ; } static void InitOTARequestor(void) { -#if 0 // Initialize and interconnect the Requestor and Image Processor objects -- START SetRequestorInstance(&gRequestorCore); - ChipLogProgress(DeviceLayer,"InitOTARequestor gRequestorCore init"); + + gRequestorStorage.Init(Server::GetInstance().GetPersistentStorage()); // Set server instance used for session establishment - /* - Set server instance used to get access to the system resources necessary to open CASE sessions and drive - * - BDX transfers - * - Set the OTA requestor driver instance used to communicate download progress and errors - * - Set the BDX downloader instance used for initiating BDX downloads - */ - gRequestorCore.Init(&(chip::Server::GetInstance()), &gRequestorUser, &gDownloader); - - // WARNING: this is probably not realistic to know such details of the image or to even have an OTADownloader instantiated at - // the beginning of program execution. We're using hardcoded values here for now since this is a reference application. - // TODO: instatiate and initialize these values when QueryImageResponse tells us an image is available - // TODO: add API for OTARequestor to pass QueryImageResponse info to the application to use for OTADownloader init - OTAImageProcessorParams ipParams; - gImageProcessor.SetOTAImageProcessorParams(ipParams); + gRequestorCore.Init(Server::GetInstance(), gRequestorStorage, gRequestorUser, gDownloader); + gImageProcessor.SetOTADownloader(&gDownloader); // Connect the Downloader and Image Processor objects gDownloader.SetImageProcessorDelegate(&gImageProcessor); gRequestorUser.Init(&gRequestorCore, &gImageProcessor); -#endif + + if (gUserConsentState != chip::ota::UserConsentState::kUnknown) + { + gUserConsentProvider.SetUserConsentState(gUserConsentState); + gRequestorUser.SetUserConsentDelegate(&gUserConsentProvider); + } + // Initialize and interconnect the Requestor and Image Processor objects -- END } //#endif // CONFIG_ENABLE_OTA_REQUESTOR @@ -374,27 +374,29 @@ static void InitServer(intptr_t context) // Initialize device attestation config SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); sWiFiNetworkCommissioningInstance.Init(); + InitOTARequestor(); PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); } extern "C" void ChipTest(void) { - ChipLogProgress(Zcl, "ChipTest"); + ChipLogProgress(DeviceLayer, "Lighting App Demo!"); CHIP_ERROR err = CHIP_NO_ERROR; + //initPref(); CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance(); err = deviceMgr.Init(&EchoCallbacks); //start the CHIP task if (err != CHIP_NO_ERROR) { - ChipLogProgress(Zcl, "DeviceManagerInit() - ERROR!"); + ChipLogError(DeviceLayer, "DeviceManagerInit() - ERROR!\r\n"); } else { - ChipLogProgress(Zcl, "DeviceManagerInit() - OK"); + ChipLogProgress(DeviceLayer, "DeviceManagerInit() - OK\r\n"); } - chip::DeviceLayer::PlatformMgr().ScheduleWork(InitServer, reinterpret_cast(nullptr)); - InitOTARequestor(); + chip::DeviceLayer::PlatformMgr().ScheduleWork(InitServer, 0); + while (true) vTaskDelay(pdMS_TO_TICKS(50)); //Just server the application event handler ChipLogProgress(SoftwareUpdate, "Exited"); @@ -405,3 +407,4 @@ bool lowPowerClusterSleep() { return true; } + diff --git a/src/platform/Beken/BUILD.gn b/src/platform/Beken/BUILD.gn index 80bbe31a5a06bc..808eb1c5b9e669 100755 --- a/src/platform/Beken/BUILD.gn +++ b/src/platform/Beken/BUILD.gn @@ -38,8 +38,8 @@ static_library("Beken") { "KeyValueStoreManagerImpl.h", "Logging.cpp", "LwIPCoreLock.cpp", - #"OTAImageProcessorImpl.cpp", - #"OTAImageProcessorImpl.h", + "OTAImageProcessorImpl.cpp", + "OTAImageProcessorImpl.h", "PlatformManagerImpl.cpp", "PlatformManagerImpl.h", "SoftwareUpdateManagerImpl.h", diff --git a/src/platform/Beken/OTAImageProcessorImpl.cpp b/src/platform/Beken/OTAImageProcessorImpl.cpp index e6452baa9faa24..8705ed9a5d2bc6 100755 --- a/src/platform/Beken/OTAImageProcessorImpl.cpp +++ b/src/platform/Beken/OTAImageProcessorImpl.cpp @@ -26,9 +26,18 @@ #include "flash_namespace_value.h" #include "mem_pub.h" +using namespace chip::System; +using namespace ::chip::DeviceLayer::Internal; namespace chip { +namespace { +void HandleRestart(Layer * systemLayer, void * appState) +{ + bk_reboot(); +} +} // namespace + const char ucFinishFlag[] = {0xF0,0x5D,0x4A,0x8C};//Flag that OTA update has finished CHIP_ERROR OTAImageProcessorImpl::PrepareDownload() { @@ -62,6 +71,38 @@ CHIP_ERROR OTAImageProcessorImpl::Abort() return CHIP_NO_ERROR; } +bool OTAImageProcessorImpl::IsFirstImageRun() +{ + OTARequestorInterface * requestor = chip::GetRequestorInstance(); + if (requestor == nullptr) + { + return false; + } + + return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying; +} + +CHIP_ERROR OTAImageProcessorImpl::ConfirmCurrentImage() +{ + OTARequestorInterface * requestor = chip::GetRequestorInstance(); + if (requestor == nullptr) + { + return CHIP_ERROR_INTERNAL; + } + + uint32_t currentVersion; + uint32_t targetVersion = requestor->GetTargetVersion(); + ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(currentVersion)); + if (currentVersion != targetVersion) + { + ChipLogError(SoftwareUpdate, "Current software version = %" PRIu32 ", expected software version = %" PRIu32, currentVersion, + targetVersion); + return CHIP_ERROR_INCORRECT_STATE; + } + + return CHIP_NO_ERROR; +} + CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block) { ChipLogProgress(SoftwareUpdate, "Process Block"); @@ -96,7 +137,7 @@ void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context) } ChipLogProgress(SoftwareUpdate, "%s [%d] OTA address space will be upgraded",__FUNCTION__,__LINE__); - + imageProcessor->mHeaderParser.Init();//Initialize the status of OTA parse imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR); } @@ -151,6 +192,16 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) return; } + ByteSpan block = ByteSpan(imageProcessor->mBlock.data(), imageProcessor->mBlock.size()); + + CHIP_ERROR error = imageProcessor->ProcessHeader(block); + if (error != CHIP_NO_ERROR) + { + ChipLogError(SoftwareUpdate,"Failed to process OTA image header"); + imageProcessor->mDownloader->EndDownload(error); + return; + } + if (!imageProcessor->readHeader) // First block received, process header { ota_data_struct_t * tempBuf = (ota_data_struct_t *) os_malloc(sizeof(ota_data_struct_t)); @@ -160,7 +211,7 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) ChipLogError(SoftwareUpdate, "%s [%d] malloc failed ",__FUNCTION__,__LINE__); } os_memset((char *)tempBuf,0,sizeof(ota_data_struct_t)); - os_memcpy((char *)&(imageProcessor->pOtaTgtHdr), imageProcessor->mBlock.data(), sizeof(ota_data_struct_t)); + os_memcpy((char *)&(imageProcessor->pOtaTgtHdr), block.data(), sizeof(ota_data_struct_t)); imageProcessor->flash_data_offset = 0; @@ -178,7 +229,7 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) dwFlagAddrOffset = partition_info->partition_length - (sizeof(ucFinishFlag) - 1); bk_read_ota_data_in_flash( (char *)ucflag,dwFlagAddrOffset,(sizeof(ucFinishFlag) - 1)); - ChipLogProgress(SoftwareUpdate, "Block size is %d ,ucFinishFlag size len is %d",imageProcessor->mBlock.size(),sizeof(ucFinishFlag)); + ChipLogProgress(SoftwareUpdate, "Block size is %d ,ucFinishFlag size len is %d",block.size(),sizeof(ucFinishFlag)); if ((0 == memcmp(ucflag,ucFinishFlag,(sizeof(ucFinishFlag) - 1))) && (0 == memcmp(tempBuf->version,imageProcessor->pOtaTgtHdr.version,sizeof(imageProcessor->pOtaTgtHdr.version)))) @@ -196,7 +247,8 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) ChipLogProgress(SoftwareUpdate, "Erasing target partition..."); bk_erase_ota_data_in_flash(); ChipLogProgress(SoftwareUpdate, "Erasing target partition..."); - if(0 != bk_write_ota_data_to_flash((char *) imageProcessor->mBlock.data(),imageProcessor->flash_data_offset,imageProcessor->mBlock.size())) + + if(0 != bk_write_ota_data_to_flash((char *) block.data(),imageProcessor->flash_data_offset,block.size())) { os_free(tempBuf); tempBuf = NULL; @@ -204,25 +256,27 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); return; } - imageProcessor->flash_data_offset += imageProcessor->mBlock.size();//count next write flash address + + imageProcessor->flash_data_offset += block.size();//count next write flash address os_free(tempBuf); tempBuf = NULL; } else // received subsequent blocks { - if(0 != bk_write_ota_data_to_flash( (char *)imageProcessor->mBlock.data(),imageProcessor->flash_data_offset,imageProcessor->mBlock.size())) + if(0 != bk_write_ota_data_to_flash( (char *)block.data(),imageProcessor->flash_data_offset,block.size())) { ChipLogError(SoftwareUpdate, "bk_write_ota_data_to_flash failed %s [%d] ",__FUNCTION__,__LINE__); imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); return; } - imageProcessor->flash_data_offset += imageProcessor->mBlock.size();//count next write flash address + + imageProcessor->flash_data_offset += block.size();//count next write flash address - imageProcessor->size += imageProcessor->mBlock.size(); + imageProcessor->size += block.size(); } - imageProcessor->mParams.downloadedBytes += imageProcessor->mBlock.size(); + imageProcessor->mParams.downloadedBytes += block.size(); imageProcessor->mDownloader->FetchNextData(); } @@ -231,17 +285,17 @@ void OTAImageProcessorImpl::HandleApply(intptr_t context) auto * imageProcessor = reinterpret_cast(context); ChipLogError(SoftwareUpdate, "Update completly,will reboot %s [%d] ",__FUNCTION__,__LINE__); - // Reboot - bk_reboot(); + // HandleApply is called after delayed action time seconds are elapsed, so it would be safe to schedule the restart + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Milliseconds32(2 * 1000), HandleRestart, nullptr); } CHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block) { - if ((block.data() == nullptr) || block.empty()) + if (!IsSpanUsable(block)) { + ReleaseBlock(); return CHIP_NO_ERROR; } - if (mBlock.size() < block.size()) { if (!mBlock.empty()) @@ -255,25 +309,13 @@ CHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block) } mBlock = MutableByteSpan(mBlock_ptr, block.size()); } - - // Allocate memory for block data if it has not been done yet - if (mBlock.empty()) - { - mBlock = MutableByteSpan(static_cast(chip::Platform::MemoryAlloc(block.size())), block.size()); - if (mBlock.data() == nullptr) - { - return CHIP_ERROR_NO_MEMORY; - } - } - - // Store the actual block data CHIP_ERROR err = CopySpanToMutableSpan(block, mBlock); if (err != CHIP_NO_ERROR) { ChipLogError(SoftwareUpdate, "Cannot copy block data: %" CHIP_ERROR_FORMAT, err.Format()); return err; } - + return CHIP_NO_ERROR; } @@ -287,4 +329,23 @@ CHIP_ERROR OTAImageProcessorImpl::ReleaseBlock() mBlock = MutableByteSpan(); return CHIP_NO_ERROR; } + +CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) +{ + if (mHeaderParser.IsInitialized()) + { + OTAImageHeader header; + CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); + + // Needs more data to decode the header + ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + ReturnErrorOnFailure(error); + + mParams.totalFileBytes = header.mPayloadSize; + mHeaderParser.Clear(); + } + + return CHIP_NO_ERROR; +} + } // namespace chip diff --git a/src/platform/Beken/OTAImageProcessorImpl.h b/src/platform/Beken/OTAImageProcessorImpl.h index 7522ebc40c4df8..fd238107d9e91e 100755 --- a/src/platform/Beken/OTAImageProcessorImpl.h +++ b/src/platform/Beken/OTAImageProcessorImpl.h @@ -18,9 +18,9 @@ #pragma once -#include +#include #include -//#include +#include #include #include #include "flash_namespace_value.h" @@ -37,6 +37,8 @@ class OTAImageProcessorImpl : public OTAImageProcessorInterface CHIP_ERROR Apply() override; CHIP_ERROR Abort() override; CHIP_ERROR ProcessBlock(ByteSpan & block) override; + bool IsFirstImageRun() override; + CHIP_ERROR ConfirmCurrentImage() override; void SetOTADownloader(OTADownloader * downloader) { mDownloader = downloader; } private: @@ -56,10 +58,11 @@ class OTAImageProcessorImpl : public OTAImageProcessorInterface * Called to release allocated memory for mBlock */ CHIP_ERROR ReleaseBlock(); + CHIP_ERROR ProcessHeader(ByteSpan & block); MutableByteSpan mBlock; OTADownloader * mDownloader; - + OTAImageHeaderParser mHeaderParser; bool readHeader = false; ota_data_struct_t pOtaTgtHdr = {0}; uint32_t flash_data_offset = 0; From 22c4a9861665cbc851ab4c0387d420354d26e6d1 Mon Sep 17 00:00:00 2001 From: "jun.luo" Date: Tue, 17 May 2022 16:08:28 +0800 Subject: [PATCH 18/20] KV interface implementation is incorrect. KeyValueStoreManagerImpl::_Get did NOT return the real lenght of read data. BTW, i enable CHIP_CONFIG_VERBOSE_VERIFY_OR_DIE, thus we can detect CHIP trhead going to die easily --- src/platform/Beken/CHIPPlatformConfig.h | 3 +++ src/platform/Beken/KeyValueStoreManagerImpl.cpp | 8 +------- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/platform/Beken/CHIPPlatformConfig.h b/src/platform/Beken/CHIPPlatformConfig.h index 0778cb7ccc2b93..488140649e03f1 100644 --- a/src/platform/Beken/CHIPPlatformConfig.h +++ b/src/platform/Beken/CHIPPlatformConfig.h @@ -112,3 +112,6 @@ #ifndef CHIP_CONFIG_ENABLE_CASE_RESPONDER #define CHIP_CONFIG_ENABLE_CASE_RESPONDER 1 #endif // CHIP_CONFIG_ENABLE_CASE_RESPONDER + +#define CHIP_CONFIG_VERBOSE_VERIFY_OR_DIE 1 + diff --git a/src/platform/Beken/KeyValueStoreManagerImpl.cpp b/src/platform/Beken/KeyValueStoreManagerImpl.cpp index bb387b3f2a6ae8..a8cde782fa4631 100755 --- a/src/platform/Beken/KeyValueStoreManagerImpl.cpp +++ b/src/platform/Beken/KeyValueStoreManagerImpl.cpp @@ -38,14 +38,13 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t CHIP_ERROR err = CHIP_NO_ERROR; int32_t ret = -1; uint32_t dwTeReadBytes = 0; - + if ((!value) || offset_bytes > 0) { // Offset and partial reads are not supported in nvs, for now just return NOT_IMPLEMENTED. Support can be added in the // future if this is needed. return (err = CHIP_ERROR_INVALID_ARGUMENT); } - if(read_bytes_size == NULL) { ret = bk_read_data(GetKVNameSpaceName(key), key, (char *) value, value_size, &dwTeReadBytes); @@ -54,14 +53,9 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t { ret = bk_read_data(GetKVNameSpaceName(key), key, (char *) value, value_size, (uint32_t *)read_bytes_size); } - if (ret == kNoErr) { err = CHIP_NO_ERROR; - if (read_bytes_size) - { - *read_bytes_size = value_size; - } } else { From 793cdfdaefc4d4b3d5cef7360a8ddc96d87c5db6 Mon Sep 17 00:00:00 2001 From: "fuxing.guo" Date: Thu, 19 May 2022 15:00:50 +0800 Subject: [PATCH 19/20] Implement DeviceInfoProvider on beken platform. Change-Id: I62961c1ecd72bf0f12eda67b2fdf61d37997f0da --- src/platform/Beken/BUILD.gn | 2 + src/platform/Beken/DeviceInfoProviderImpl.cpp | 364 ++++++++++++++++++ src/platform/Beken/DeviceInfoProviderImpl.h | 108 ++++++ src/platform/Beken/PlatformManagerImpl.cpp | 2 + 4 files changed, 476 insertions(+) create mode 100755 src/platform/Beken/DeviceInfoProviderImpl.cpp create mode 100755 src/platform/Beken/DeviceInfoProviderImpl.h diff --git a/src/platform/Beken/BUILD.gn b/src/platform/Beken/BUILD.gn index 808eb1c5b9e669..42a7a9f9ecaebd 100755 --- a/src/platform/Beken/BUILD.gn +++ b/src/platform/Beken/BUILD.gn @@ -32,6 +32,8 @@ static_library("Beken") { "ConfigurationManagerImpl.h", "ConnectivityManagerImpl.cpp", "ConnectivityManagerImpl.h", + "DeviceInfoProviderImpl.cpp", + "DeviceInfoProviderImpl.h", "DiagnosticDataProviderImpl.cpp", "DiagnosticDataProviderImpl.h", "KeyValueStoreManagerImpl.cpp", diff --git a/src/platform/Beken/DeviceInfoProviderImpl.cpp b/src/platform/Beken/DeviceInfoProviderImpl.cpp new file mode 100755 index 00000000000000..015e2c9e488a75 --- /dev/null +++ b/src/platform/Beken/DeviceInfoProviderImpl.cpp @@ -0,0 +1,364 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace chip { +namespace DeviceLayer { + +namespace { +constexpr TLV::Tag kLabelNameTag = TLV::ContextTag(0); +constexpr TLV::Tag kLabelValueTag = TLV::ContextTag(1); +} // anonymous namespace + +DeviceInfoProviderImpl & DeviceInfoProviderImpl::GetDefaultInstance() +{ + static DeviceInfoProviderImpl sInstance; + return sInstance; +} + +DeviceInfoProvider::FixedLabelIterator * DeviceInfoProviderImpl::IterateFixedLabel(EndpointId endpoint) +{ + return new FixedLabelIteratorImpl(endpoint); +} + +DeviceInfoProviderImpl::FixedLabelIteratorImpl::FixedLabelIteratorImpl(EndpointId endpoint) : mEndpoint(endpoint) +{ + mIndex = 0; +} + +size_t DeviceInfoProviderImpl::FixedLabelIteratorImpl::Count() +{ + // In Beken Simulation, return the size of the hardcoded labelList on all endpoints. + return 4; +} + +bool DeviceInfoProviderImpl::FixedLabelIteratorImpl::Next(FixedLabelType & output) +{ + bool retval = true; + + // In Beken Simulation, use the following hardcoded labelList on all endpoints. + CHIP_ERROR err = CHIP_NO_ERROR; + + const char * labelPtr = nullptr; + const char * valuePtr = nullptr; + + VerifyOrReturnError(mIndex < 4, false); + + ChipLogProgress(DeviceLayer, "Get the fixed label with index:%d at endpoint:%d", mIndex, mEndpoint); + + switch (mIndex) + { + case 0: + labelPtr = "room"; + valuePtr = "bedroom 2"; + break; + case 1: + labelPtr = "orientation"; + valuePtr = "North"; + break; + case 2: + labelPtr = "floor"; + valuePtr = "2"; + break; + case 3: + labelPtr = "direction"; + valuePtr = "up"; + break; + default: + err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; + break; + } + + if (err == CHIP_NO_ERROR) + { + VerifyOrReturnError(std::strlen(labelPtr) <= kMaxLabelNameLength, false); + VerifyOrReturnError(std::strlen(valuePtr) <= kMaxLabelValueLength, false); + + Platform::CopyString(mFixedLabelNameBuf, kMaxLabelNameLength + 1, labelPtr); + Platform::CopyString(mFixedLabelValueBuf, kMaxLabelValueLength + 1, valuePtr); + + output.label = CharSpan::fromCharString(mFixedLabelNameBuf); + output.value = CharSpan::fromCharString(mFixedLabelValueBuf); + + mIndex++; + + retval = true; + } + else + { + retval = false; + } + + return retval; +} + +CHIP_ERROR DeviceInfoProviderImpl::SetUserLabelLength(EndpointId endpoint, size_t val) +{ + DefaultStorageKeyAllocator keyAlloc; + + return mStorage->SyncSetKeyValue(keyAlloc.UserLabelLengthKey(endpoint), &val, static_cast(sizeof(val))); +} + +CHIP_ERROR DeviceInfoProviderImpl::GetUserLabelLength(EndpointId endpoint, size_t & val) +{ + DefaultStorageKeyAllocator keyAlloc; + uint16_t len = static_cast(sizeof(val)); + + return mStorage->SyncGetKeyValue(keyAlloc.UserLabelLengthKey(endpoint), &val, len); +} + +CHIP_ERROR DeviceInfoProviderImpl::SetUserLabelAt(EndpointId endpoint, size_t index, const UserLabelType & userLabel) +{ + DefaultStorageKeyAllocator keyAlloc; + uint8_t buf[UserLabelTLVMaxSize()]; + TLV::TLVWriter writer; + writer.Init(buf); + + TLV::TLVType outerType; + ReturnErrorOnFailure(writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerType)); + ReturnErrorOnFailure(writer.PutString(kLabelNameTag, userLabel.label)); + ReturnErrorOnFailure(writer.PutString(kLabelValueTag, userLabel.value)); + ReturnErrorOnFailure(writer.EndContainer(outerType)); + + return mStorage->SyncSetKeyValue(keyAlloc.UserLabelIndexKey(endpoint, index), buf, + static_cast(writer.GetLengthWritten())); +} + +DeviceInfoProvider::UserLabelIterator * DeviceInfoProviderImpl::IterateUserLabel(EndpointId endpoint) +{ + return new UserLabelIteratorImpl(*this, endpoint); +} + +DeviceInfoProviderImpl::UserLabelIteratorImpl::UserLabelIteratorImpl(DeviceInfoProviderImpl & provider, EndpointId endpoint) : + mProvider(provider), mEndpoint(endpoint) +{ + size_t total = 0; + + ReturnOnFailure(mProvider.GetUserLabelLength(mEndpoint, total)); + mTotal = total; + mIndex = 0; +} + +bool DeviceInfoProviderImpl::UserLabelIteratorImpl::Next(UserLabelType & output) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + VerifyOrReturnError(mIndex < mTotal, false); + + DefaultStorageKeyAllocator keyAlloc; + uint8_t buf[UserLabelTLVMaxSize()]; + uint16_t len = static_cast(UserLabelTLVMaxSize()); + + err = mProvider.mStorage->SyncGetKeyValue(keyAlloc.UserLabelIndexKey(mEndpoint, mIndex), buf, len); + VerifyOrReturnError(err == CHIP_NO_ERROR, false); + + TLV::ContiguousBufferTLVReader reader; + reader.Init(buf); + err = reader.Next(TLV::kTLVType_Structure, TLV::AnonymousTag()); + VerifyOrReturnError(err == CHIP_NO_ERROR, false); + + TLV::TLVType containerType; + VerifyOrReturnError(reader.EnterContainer(containerType) == CHIP_NO_ERROR, false); + + chip::CharSpan label; + chip::CharSpan value; + + VerifyOrReturnError(reader.Next(kLabelNameTag) == CHIP_NO_ERROR, false); + VerifyOrReturnError(reader.Get(label) == CHIP_NO_ERROR, false); + + VerifyOrReturnError(reader.Next(kLabelValueTag) == CHIP_NO_ERROR, false); + VerifyOrReturnError(reader.Get(value) == CHIP_NO_ERROR, false); + + VerifyOrReturnError(reader.VerifyEndOfContainer() == CHIP_NO_ERROR, false); + VerifyOrReturnError(reader.ExitContainer(containerType) == CHIP_NO_ERROR, false); + + Platform::CopyString(mUserLabelNameBuf, label); + Platform::CopyString(mUserLabelValueBuf, value); + + output.label = CharSpan::fromCharString(mUserLabelNameBuf); + output.value = CharSpan::fromCharString(mUserLabelValueBuf); + + mIndex++; + + return true; +} + +DeviceInfoProvider::SupportedLocalesIterator * DeviceInfoProviderImpl::IterateSupportedLocales() +{ + return new SupportedLocalesIteratorImpl(); +} + +size_t DeviceInfoProviderImpl::SupportedLocalesIteratorImpl::Count() +{ + // In Beken Simulation, return the size of the hardcoded list of Strings that are valid values for the ActiveLocale. + // {("en-US"), ("de-DE"), ("fr-FR"), ("en-GB"), ("es-ES"), ("zh-CN"), ("it-IT"), ("ja-JP")} + + return 8; +} + +bool DeviceInfoProviderImpl::SupportedLocalesIteratorImpl::Next(CharSpan & output) +{ + bool retval = true; + + // In Beken simulation, return following hardcoded list of Strings that are valid values for the ActiveLocale. + CHIP_ERROR err = CHIP_NO_ERROR; + + const char * activeLocalePtr = nullptr; + + VerifyOrReturnError(mIndex < 8, false); + + switch (mIndex) + { + case 0: + activeLocalePtr = "en-US"; + break; + case 1: + activeLocalePtr = "de-DE"; + break; + case 2: + activeLocalePtr = "fr-FR"; + break; + case 3: + activeLocalePtr = "en-GB"; + break; + case 4: + activeLocalePtr = "es-ES"; + break; + case 5: + activeLocalePtr = "zh-CN"; + break; + case 6: + activeLocalePtr = "it-IT"; + break; + case 7: + activeLocalePtr = "ja-JP"; + break; + default: + err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; + break; + } + + if (err == CHIP_NO_ERROR) + { + VerifyOrReturnError(std::strlen(activeLocalePtr) <= kMaxActiveLocaleLength, false); + + Platform::CopyString(mActiveLocaleBuf, kMaxActiveLocaleLength + 1, activeLocalePtr); + + output = CharSpan::fromCharString(mActiveLocaleBuf); + + mIndex++; + + retval = true; + } + else + { + retval = false; + } + + return retval; +} + +DeviceInfoProvider::SupportedCalendarTypesIterator * DeviceInfoProviderImpl::IterateSupportedCalendarTypes() +{ + return new SupportedCalendarTypesIteratorImpl(); +} + +size_t DeviceInfoProviderImpl::SupportedCalendarTypesIteratorImpl::Count() +{ + // In Beken Simulation, return the size of the hardcoded list of Strings that are valid values for the Calendar Types. + // {("kBuddhist"), ("kChinese"), ("kCoptic"), ("kEthiopian"), ("kGregorian"), ("kHebrew"), ("kIndian"), ("kJapanese"), + // ("kKorean"), ("kPersian"), ("kTaiwanese"), ("kIslamic")} + + return 12; +} + +bool DeviceInfoProviderImpl::SupportedCalendarTypesIteratorImpl::Next(CalendarType & output) +{ + bool retval = true; + + // In Beken Simulation, return following hardcoded list of Strings that are valid values for the Calendar Types. + CHIP_ERROR err = CHIP_NO_ERROR; + + VerifyOrReturnError(mIndex < 12, false); + + switch (mIndex) + { + case 0: + output = app::Clusters::TimeFormatLocalization::CalendarType::kBuddhist; + break; + case 1: + output = app::Clusters::TimeFormatLocalization::CalendarType::kChinese; + break; + case 2: + output = app::Clusters::TimeFormatLocalization::CalendarType::kCoptic; + break; + case 3: + output = app::Clusters::TimeFormatLocalization::CalendarType::kEthiopian; + break; + case 4: + output = app::Clusters::TimeFormatLocalization::CalendarType::kGregorian; + break; + case 5: + output = app::Clusters::TimeFormatLocalization::CalendarType::kHebrew; + break; + case 6: + output = app::Clusters::TimeFormatLocalization::CalendarType::kIndian; + break; + case 7: + output = app::Clusters::TimeFormatLocalization::CalendarType::kJapanese; + break; + case 8: + output = app::Clusters::TimeFormatLocalization::CalendarType::kKorean; + break; + case 9: + output = app::Clusters::TimeFormatLocalization::CalendarType::kPersian; + break; + case 10: + output = app::Clusters::TimeFormatLocalization::CalendarType::kTaiwanese; + break; + case 11: + output = app::Clusters::TimeFormatLocalization::CalendarType::kIslamic; + break; + default: + err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; + break; + } + + if (err == CHIP_NO_ERROR) + { + mIndex++; + retval = true; + } + else + { + retval = false; + } + + return retval; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/Beken/DeviceInfoProviderImpl.h b/src/platform/Beken/DeviceInfoProviderImpl.h new file mode 100755 index 00000000000000..24956ac319b84f --- /dev/null +++ b/src/platform/Beken/DeviceInfoProviderImpl.h @@ -0,0 +1,108 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include +#include +#include + +namespace chip { +namespace DeviceLayer { + +class DeviceInfoProviderImpl : public DeviceInfoProvider +{ +public: + DeviceInfoProviderImpl() = default; + ~DeviceInfoProviderImpl() override {} + + // Iterators + FixedLabelIterator * IterateFixedLabel(EndpointId endpoint) override; + UserLabelIterator * IterateUserLabel(EndpointId endpoint) override; + SupportedLocalesIterator * IterateSupportedLocales() override; + SupportedCalendarTypesIterator * IterateSupportedCalendarTypes() override; + + static DeviceInfoProviderImpl & GetDefaultInstance(); + +protected: + class FixedLabelIteratorImpl : public FixedLabelIterator + { + public: + FixedLabelIteratorImpl(EndpointId endpoint); + size_t Count() override; + bool Next(FixedLabelType & output) override; + void Release() override { delete this; } + + private: + EndpointId mEndpoint = 0; + size_t mIndex = 0; + char mFixedLabelNameBuf[kMaxLabelNameLength + 1]; + char mFixedLabelValueBuf[kMaxLabelValueLength + 1]; + }; + + class UserLabelIteratorImpl : public UserLabelIterator + { + public: + UserLabelIteratorImpl(DeviceInfoProviderImpl & provider, EndpointId endpoint); + size_t Count() override { return mTotal; } + bool Next(UserLabelType & output) override; + void Release() override { delete this; } + + private: + DeviceInfoProviderImpl & mProvider; + EndpointId mEndpoint = 0; + size_t mIndex = 0; + size_t mTotal = 0; + char mUserLabelNameBuf[kMaxLabelNameLength + 1]; + char mUserLabelValueBuf[kMaxLabelValueLength + 1]; + }; + + class SupportedLocalesIteratorImpl : public SupportedLocalesIterator + { + public: + SupportedLocalesIteratorImpl() = default; + size_t Count() override; + bool Next(CharSpan & output) override; + void Release() override { delete this; } + + private: + size_t mIndex = 0; + char mActiveLocaleBuf[kMaxActiveLocaleLength + 1]; + }; + + class SupportedCalendarTypesIteratorImpl : public SupportedCalendarTypesIterator + { + public: + SupportedCalendarTypesIteratorImpl() = default; + size_t Count() override; + bool Next(CalendarType & output) override; + void Release() override { delete this; } + + private: + size_t mIndex = 0; + }; + + CHIP_ERROR SetUserLabelLength(EndpointId endpoint, size_t val) override; + CHIP_ERROR GetUserLabelLength(EndpointId endpoint, size_t & val) override; + CHIP_ERROR SetUserLabelAt(EndpointId endpoint, size_t index, const UserLabelType & userLabel) override; + +private: + static constexpr size_t UserLabelTLVMaxSize() { return TLV::EstimateStructOverhead(kMaxLabelNameLength, kMaxLabelValueLength); } +}; + +} // namespace DeviceLayer +} // namespace chip + diff --git a/src/platform/Beken/PlatformManagerImpl.cpp b/src/platform/Beken/PlatformManagerImpl.cpp index 174bb68cfef186..3ee7ee2a5de778 100644 --- a/src/platform/Beken/PlatformManagerImpl.cpp +++ b/src/platform/Beken/PlatformManagerImpl.cpp @@ -25,6 +25,7 @@ #include #include +#include #include #include #include @@ -47,6 +48,7 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) SetConfigurationMgr(&ConfigurationManagerImpl::GetDefaultInstance()); SetDiagnosticDataProvider(&DiagnosticDataProviderImpl::GetDefaultInstance()); + SetDeviceInfoProvider(&DeviceInfoProviderImpl::GetDefaultInstance()); // Make sure the LwIP core lock has been initialized err = Internal::InitLwIPCoreLock(); From b4d8ef5e471f6ae9555720285d6df41acfc21368 Mon Sep 17 00:00:00 2001 From: "yongjia.fang" Date: Wed, 25 May 2022 17:26:46 +0800 Subject: [PATCH 20/20] modify interface for new chiptool scan command --- .../Beken/NetworkCommissioningDriver.h | 2 +- .../Beken/NetworkCommissioningWiFiDriver.cpp | 29 +++++++++---------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/platform/Beken/NetworkCommissioningDriver.h b/src/platform/Beken/NetworkCommissioningDriver.h index 3b9fd415f875b0..c7aaebb3b7e79a 100755 --- a/src/platform/Beken/NetworkCommissioningDriver.h +++ b/src/platform/Beken/NetworkCommissioningDriver.h @@ -59,7 +59,7 @@ class BKScanResponseIterator : public Iterator private: const size_t mSize; const ScanResult_adv * mpScanResults; - size_t mIternum = 0; + size_t mIternum = 1; }; class BekenWiFiDriver final : public WiFiDriver diff --git a/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp b/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp index c5a6118595f7c1..4723686d1698d1 100755 --- a/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp +++ b/src/platform/Beken/NetworkCommissioningWiFiDriver.cpp @@ -260,29 +260,28 @@ CHIP_ERROR BekenWiFiDriver::StartScanWiFiNetworks(ByteSpan ssid) void BekenWiFiDriver::OnScanWiFiNetworkDone() { ChipLogProgress(NetworkProvisioning, "BekenWiFiDriver::OnScanWiFiNetworkDone\r\n"); - ScanResult_adv apList; - int scan_rst_ap_num = 0; - if (wlan_sta_scan_result(&apList) == 0) { - scan_rst_ap_num = apList.ApNum; - ChipLogProgress(NetworkProvisioning,"Got ap count: %d\r\n", apList.ApNum); - } - if(scan_rst_ap_num == 0) + if(!GetInstance().mpScanCallback) { - os_printf("NULL AP\r\n"); - GetInstance().mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), nullptr); - GetInstance().mpScanCallback = nullptr; + ChipLogProgress(NetworkProvisioning, "can't find the ScanCallback function\r\n"); return; } - BKScanResponseIterator iter(scan_rst_ap_num, &apList); - if (GetInstance().mpScanCallback) + ScanResult_adv apList; + int scan_rst_ap_num = 0; + wlan_sta_scan_result(&apList); + scan_rst_ap_num = apList.ApNum; + + if(scan_rst_ap_num < 2) { - GetInstance().mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), &iter); - GetInstance().mpScanCallback = nullptr; + ChipLogProgress(NetworkProvisioning,"NULL AP\r\n"); + GetInstance().mpScanCallback->OnFinished(Status::kNetworkNotFound, CharSpan(), nullptr); } else { - ChipLogProgress(NetworkProvisioning, "can't find the ScanCallback function\r\n"); + ChipLogProgress(NetworkProvisioning,"AP num = %d\r\n", scan_rst_ap_num); + BKScanResponseIterator iter(scan_rst_ap_num, &apList); + GetInstance().mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), &iter); } + GetInstance().mpScanCallback = nullptr; } void scan_ap_cb(void *ctxt, uint8_t param)