diff --git a/examples/lighting-app/bouffalolab/README.md b/examples/lighting-app/bouffalolab/README.md index db48724b5dd858..7e42d3bcc45b0a 100644 --- a/examples/lighting-app/bouffalolab/README.md +++ b/examples/lighting-app/bouffalolab/README.md @@ -305,7 +305,7 @@ ota-provider-app build and usage. - BLE commission BL602/BL702 lighting if not commissioned. - Start OTA software upgrade process ```shell - ./chip-tool otasoftwareupdaterequestor announce-ota-provider 1 0 0 0 0 + ./chip-tool otasoftwareupdaterequestor announce-otaprovider 1 0 0 0 0 ``` where `` is node id of BL602/BL702 lighting app. - After OTA software upgrade gets done, BL602/BL702 will get reboot diff --git a/examples/lighting-app/bouffalolab/bl702/args.gni b/examples/lighting-app/bouffalolab/bl702/args.gni index c76c3d0f267d17..8087dc1470f236 100644 --- a/examples/lighting-app/bouffalolab/bl702/args.gni +++ b/examples/lighting-app/bouffalolab/bl702/args.gni @@ -30,3 +30,8 @@ lwip_platform = "bl702" chip_enable_ota_requestor = true chip_detail_logging = false + +pw_build_LINK_DEPS = [ + "$dir_pw_assert:impl", + "$dir_pw_log:impl", +] diff --git a/examples/lighting-app/bouffalolab/common/AppTask.cpp b/examples/lighting-app/bouffalolab/common/AppTask.cpp index 100e8792a59e42..3e7171dd75aa18 100644 --- a/examples/lighting-app/bouffalolab/common/AppTask.cpp +++ b/examples/lighting-app/bouffalolab/common/AppTask.cpp @@ -40,9 +40,9 @@ #endif #if CHIP_ENABLE_OPENTHREAD -#include #include #include +#include #include #endif diff --git a/examples/platform/bouffalolab/common/plat/OTAConfig.cpp b/examples/platform/bouffalolab/common/plat/OTAConfig.cpp index ed5c6286178ef7..b6ca3b621cd747 100644 --- a/examples/platform/bouffalolab/common/plat/OTAConfig.cpp +++ b/examples/platform/bouffalolab/common/plat/OTAConfig.cpp @@ -19,6 +19,7 @@ #include "OTAConfig.h" #include +#include // Global OTA objects chip::DefaultOTARequestor gRequestorCore; chip::DefaultOTARequestorStorage gRequestorStorage; diff --git a/examples/platform/bouffalolab/common/plat/OTAConfig.h b/examples/platform/bouffalolab/common/plat/OTAConfig.h index 906b7f533709cc..24d8fb5c11109f 100644 --- a/examples/platform/bouffalolab/common/plat/OTAConfig.h +++ b/examples/platform/bouffalolab/common/plat/OTAConfig.h @@ -22,7 +22,6 @@ #include #include #include -#include class OTAConfig { diff --git a/examples/platform/bouffalolab/common/plat/platform.cpp b/examples/platform/bouffalolab/common/plat/platform.cpp index 0c6f1912d3bb80..dc2f2a02fbfc1f 100644 --- a/examples/platform/bouffalolab/common/plat/platform.cpp +++ b/examples/platform/bouffalolab/common/plat/platform.cpp @@ -30,7 +30,7 @@ #include #include #endif -#include +#include #if HEAP_MONITORING #include @@ -38,9 +38,9 @@ #endif #if CHIP_ENABLE_OPENTHREAD -#include #include #include +#include #include #endif diff --git a/examples/platform/silabs/syscalls_stubs.cpp b/examples/platform/silabs/syscalls_stubs.cpp index f6a845639c6e7c..685bd63f567bb5 100644 --- a/examples/platform/silabs/syscalls_stubs.cpp +++ b/examples/platform/silabs/syscalls_stubs.cpp @@ -174,7 +174,7 @@ int __attribute__((weak)) _read(int file, char * ptr, int len) { (void) file; #if SILABS_LOG_OUT_UART - return = uartConsoleRead(ptr, len); + return uartConsoleRead(ptr, len); #else (void) ptr; (void) len; diff --git a/integrations/cloudbuild/smoke-test.yaml b/integrations/cloudbuild/smoke-test.yaml index 1134778bda2714..e3f18bcc42bef5 100644 --- a/integrations/cloudbuild/smoke-test.yaml +++ b/integrations/cloudbuild/smoke-test.yaml @@ -7,7 +7,7 @@ steps: git config --global --add safe.directory "*" git submodule update --init --recursive id: Submodules - - name: "connectedhomeip/chip-build-vscode:0.7.3" + - name: "connectedhomeip/chip-build-vscode:0.7.16" env: - PW_ENVIRONMENT_ROOT=/pwenv args: diff --git a/scripts/tools/memory/platform/qpg.cfg b/scripts/tools/memory/platform/qpg.cfg index 97aea63fdfa051..ec6a7d374c81f7 100644 --- a/scripts/tools/memory/platform/qpg.cfg +++ b/scripts/tools/memory/platform/qpg.cfg @@ -35,10 +35,21 @@ 'sections': { 'FLASH': [ '.text', - '.rom', + '.flashjumptable', + '.datajumptable', + '.m_flashjumptable', + '.loaded_user_license', '.native_user_license', + '.extended_user_license', '.isr_vector', '.ARM.exidx', + # Bootloader + '.bootloader', + '.bl_user_license', + '.upgrade_image_user_license', + # NVM / Factory areas + '.gpNVM', + '.factory_data', ], 'RAM': [ '.data', @@ -49,17 +60,17 @@ '.ret_hw', '.ret_sw', '.unused_area', - '.pkey', - '.pufr', '.lower_ram_retain', '.lower_ram_retain_gpmicro_accessible', '.higher_ram_noretain', - '.gpNVM', + '.rom_m_bss', + '.rom_m_data', + '.lower_ram_retain_gpmicro_accessible_mrom', + ], + 'OTA': [ + 'OTA', + 'JTOTA', ] } }, - 'collect': { - # Strip these prefixes from compilation unit paths. - 'prefix': ['/mnt/c/Projects', '/mnt/c'] - }, } diff --git a/src/app/tests/suites/certification/PICS.yaml b/src/app/tests/suites/certification/PICS.yaml index ed767818f71afb..c361661a9a17cb 100644 --- a/src/app/tests/suites/certification/PICS.yaml +++ b/src/app/tests/suites/certification/PICS.yaml @@ -6915,7 +6915,7 @@ PICS: id: DGTHREAD.S.A0033 - label: - "Does the DUT(server) support the RxErrInvalidScrAddrCount attribute?" + "Does the DUT(server) support the RxErrInvalidSrcAddrCount attribute?" id: DGTHREAD.S.A0034 - label: "Does the DUT(server) support the RxErrSecCount attribute?" @@ -7255,7 +7255,7 @@ PICS: - label: "Does the DUT(client) have access privileges for the - RxErrInvalidScrAddrCount attribute implemented on the server?" + RxErrInvalidSrcAddrCount attribute implemented on the server?" id: DGTHREAD.C.A0034 - label: diff --git a/src/app/tests/suites/include/ConstraintsChecker.h b/src/app/tests/suites/include/ConstraintsChecker.h index be446fd3f42c28..eb52c3b6b6bba5 100644 --- a/src/app/tests/suites/include/ConstraintsChecker.h +++ b/src/app/tests/suites/include/ConstraintsChecker.h @@ -299,6 +299,17 @@ class ConstraintsChecker return CheckConstraintMinValue(itemName, current.Value(), static_cast(expected)); } + template + bool CheckConstraintMinValue(const char * itemName, const chip::app::DataModel::Nullable & current, + const chip::app::DataModel::Nullable & expected) + { + if (expected.IsNull()) + { + return true; + } + return CheckConstraintMinValue(itemName, current, expected.Value()); + } + template bool CheckConstraintMinValue(const char * itemName, const T & current, const chip::Optional & expected) { @@ -375,6 +386,17 @@ class ConstraintsChecker return CheckConstraintMaxValue(itemName, current.Value(), static_cast(expected)); } + template + bool CheckConstraintMaxValue(const char * itemName, const chip::app::DataModel::Nullable & current, + const chip::app::DataModel::Nullable & expected) + { + if (expected.IsNull()) + { + return true; + } + return CheckConstraintMaxValue(itemName, current, expected.Value()); + } + template bool CheckConstraintMaxValue(const char * itemName, const T & current, const chip::Optional & expected) { diff --git a/src/platform/BUILD.gn b/src/platform/BUILD.gn index 6473ed404beaf9..7f18adc631cb73 100644 --- a/src/platform/BUILD.gn +++ b/src/platform/BUILD.gn @@ -229,13 +229,13 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { } else if (chip_device_platform == "bl602") { defines += [ "CHIP_DEVICE_LAYER_TARGET_BL602=1", - "CHIP_DEVICE_LAYER_TARGET=bouffalolab/BL602", + "CHIP_DEVICE_LAYER_TARGET=bouffalolab/common", "CHIP_DEVICE_CONFIG_ENABLE_WIFI=${chip_enable_wifi}", ] } else if (chip_device_platform == "bl702") { defines += [ "CHIP_DEVICE_LAYER_TARGET_BL702=1", - "CHIP_DEVICE_LAYER_TARGET=bouffalolab/BL702", + "CHIP_DEVICE_LAYER_TARGET=bouffalolab/common", "CHIP_DEVICE_CONFIG_ENABLE_WIFI=${chip_enable_wifi}", ] } else if (chip_device_platform == "fake") { diff --git a/src/platform/bouffalolab/BL602/BL602Config.cpp b/src/platform/bouffalolab/BL602/BL602Config.cpp deleted file mode 100644 index 140b52d5fa0edd..00000000000000 --- a/src/platform/bouffalolab/BL602/BL602Config.cpp +++ /dev/null @@ -1,336 +0,0 @@ -/* - * - * Copyright (c) 2021-2022 Project CHIP Authors - * Copyright (c) 2019-2020 Google LLC. - * Copyright (c) 2019 Nest Labs, Inc. - * 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 - * Utilities for interacting with the the BL602 Easyflash module. - */ -/* this file behaves like a config.h, comes first */ -#include - -#include - -#include -#include -#include -#include -#include - -#include -#include - -// 3R: easyflash errno mapping to the CHIP errno - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -const BL602Config::Key BL602Config::kConfigKey_SerialNum = { "serial-num" }; -const BL602Config::Key BL602Config::kConfigKey_MfrDeviceId = { "device-id" }; -const BL602Config::Key BL602Config::kConfigKey_MfrDeviceCert = { "device-cert" }; -const BL602Config::Key BL602Config::kConfigKey_MfrDeviceICACerts = { "device-ca-certs" }; -const BL602Config::Key BL602Config::kConfigKey_MfrDevicePrivateKey = { "device-key" }; -const BL602Config::Key BL602Config::kConfigKey_HardwareVersion = { "hardware-ver" }; -const BL602Config::Key BL602Config::kConfigKey_ManufacturingDate = { "mfg-date" }; -const BL602Config::Key BL602Config::kConfigKey_SetupPinCode = { "pin-code" }; -const BL602Config::Key BL602Config::kConfigKey_SetupDiscriminator = { "discriminator" }; -const BL602Config::Key BL602Config::kConfigKey_Spake2pIterationCount = { "iteration-count" }; -const BL602Config::Key BL602Config::kConfigKey_Spake2pSalt = { "salt" }; -const BL602Config::Key BL602Config::kConfigKey_Spake2pVerifier = { "verifier" }; - -// Keys stored in the chip-config namespace -const BL602Config::Key BL602Config::kConfigKey_ServiceConfig = { "service-config" }; -const BL602Config::Key BL602Config::kConfigKey_PairedAccountId = { "account-id" }; -const BL602Config::Key BL602Config::kConfigKey_ServiceId = { "service-id" }; -const BL602Config::Key BL602Config::kConfigKey_LastUsedEpochKeyId = { "last-ek-id" }; -const BL602Config::Key BL602Config::kConfigKey_FailSafeArmed = { "fail-safe-armed" }; -const BL602Config::Key BL602Config::kConfigKey_WiFiStationSecType = { "sta-sec-type" }; -const BL602Config::Key BL602Config::kConfigKey_OperationalDeviceId = { "op-device-id" }; -const BL602Config::Key BL602Config::kConfigKey_OperationalDeviceCert = { "op-device-cert" }; -const BL602Config::Key BL602Config::kConfigKey_OperationalDeviceICACerts = { "op-device-ca-certs" }; -const BL602Config::Key BL602Config::kConfigKey_OperationalDevicePrivateKey = { "op-device-key" }; -const BL602Config::Key BL602Config::kConfigKey_RegulatoryLocation = { "regulatory-location" }; -const BL602Config::Key BL602Config::kConfigKey_CountryCode = { "country-code" }; -const BL602Config::Key BL602Config::kConfigKey_UniqueId = { "unique-id" }; - -const BL602Config::Key BL602Config::kCounterKey_RebootCount = { "reboot-count" }; -const BL602Config::Key BL602Config::kCounterKey_TotalOperationalHours = { "total-hours" }; - -CHIP_ERROR BL602Config::Init() -{ - return CHIP_NO_ERROR; -} - -CHIP_ERROR BL602Config::ReadConfigValue(Key key, bool & val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - size_t valLen = 0; - - ef_get_env_blob(key.name, &val, 1, &valLen); - if (0 == valLen) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR BL602Config::ReadConfigValue(Key key, uint32_t & val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - size_t valLen = 0; - - ef_get_env_blob(key.name, &val, sizeof(val), &valLen); - if (0 == valLen) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR BL602Config::ReadConfigValue(Key key, uint64_t & val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - size_t valLen = 0; - - ef_get_env_blob(key.name, &val, sizeof(val), &valLen); - if (0 == valLen) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR BL602Config::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - outLen = 0; - ef_get_env_blob(key.name, buf, bufSize, &outLen); - if (0 == outLen) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR BL602Config::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - ef_get_env_blob(key.name, buf, bufSize, &outLen); - if (0 == outLen) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValue(Key key, bool val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - EfErrCode ret = ef_set_env_blob(key.name, &val, sizeof(val)); - if (ret != EF_NO_ERR) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - SuccessOrExit(err); - - // ChipLogProgress(DeviceLayer, "Easyflash set: %s = %s", key.name, val ? "true" : "false"); -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValue(Key key, uint32_t val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - EfErrCode ret = ef_set_env_blob(key.name, &val, sizeof(val)); - if (ret != EF_NO_ERR) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - SuccessOrExit(err); - - // ChipLogProgress(DeviceLayer, "Easyflash set: %s = %" PRIu32 " (0x%" PRIX32 ")", key.name, val, val); - -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValue(Key key, uint64_t val) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - EfErrCode ret = ef_set_env_blob(key.name, &val, sizeof(val)); - if (ret != EF_NO_ERR) - { - log_error("WriteConfigValue() failed. key: %s, ret: %d\r\n", StringOrNullMarker(key.name), ret); - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - SuccessOrExit(err); - - // ChipLogProgress(DeviceLayer, "Easyflash set: %s = %" PRIu64 " (0x%" PRIX64 ")", key.name, val, val); - -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValueStr(Key key, const char * str) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - if (str != NULL) - { - EfErrCode ret = ef_set_env(key.name, str); - if (ret != EF_NO_ERR) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - SuccessOrExit(err); - - // ChipLogProgress(DeviceLayer, "Easyflash set: %s = \"%s\"", key.name, str); - } - else - { - err = ClearConfigValue(key); - SuccessOrExit(err); - } - -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValueStr(Key key, const char * str, size_t strLen) -{ - CHIP_ERROR err; - chip::Platform::ScopedMemoryBuffer strCopy; - - if (str != NULL) - { - strCopy.Calloc(strLen + 1); - VerifyOrExit(strCopy, err = CHIP_ERROR_NO_MEMORY); - Platform::CopyString(strCopy.Get(), strLen + 1, str); - } - err = BL602Config::WriteConfigValueStr(key, strCopy.Get()); - -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - if (data != NULL) - { - EfErrCode ret = ef_set_env_blob(key.name, data, dataLen); - if (ret != EF_NO_ERR) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - SuccessOrExit(err); - - // ChipLogProgress(DeviceLayer, "Easyflash set: /%s = (blob length %" PRId32 ")", key.name, (unsigned long )dataLen); - } - else - { - err = ClearConfigValue(key); - SuccessOrExit(err); - } - -exit: - return err; -} - -CHIP_ERROR BL602Config::WriteWifiInfo(const char * ssid, const char * passwd) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - -#if 0 - if (ssid != NULL && passwd != NULL) - { - EfErrCode ret = ef_set_env_blob(kBLConfigKey_wifissid, ssid, strlen(ssid)); - if (ret != EF_NO_ERR) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - ef_set_env_blob(kBLConfigKey_wifipassword, passwd, strlen(passwd)); - if (ret != EF_NO_ERR) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - SuccessOrExit(err); - - } - else - { - //err = ClearConfigValue(ssid); - //err = ClearConfigValue(passwd); - SuccessOrExit(err); - } - -exit: -#endif - - return err; -} - -CHIP_ERROR BL602Config::ClearConfigValue(Key key) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - EfErrCode ret = ef_del_env(key.name); - if (ret != EF_NO_ERR) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - SuccessOrExit(err); - - ChipLogProgress(DeviceLayer, "Easyflash erase: %s", StringOrNullMarker(key.name)); - -exit: - return err; -} - -bool BL602Config::ConfigValueExists(Key key) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - env_node_obj node; - bool result = ef_get_env_obj(key.name, &node); - if (!result) - { - err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - } - - return err == CHIP_NO_ERROR; -} - -void BL602Config::RunConfigUnitTest() {} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/BL602Config.h b/src/platform/bouffalolab/BL602/BL602Config.h deleted file mode 100644 index 11be4c9ebe3402..00000000000000 --- a/src/platform/bouffalolab/BL602/BL602Config.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019-2020 Google LLC. - * Copyright (c) 2019 Nest Labs, Inc. - * 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 - * Utilities for interacting with the the BL602 Easyflash module. - */ - -#pragma once - -#include - -#include - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -/** - * Provides functions and definitions for accessing device configuration information on the BL602 platform. - * - * This class is designed to be mixed-in to concrete implementation classes as a means to - * provide access to configuration information to generic base classes. - */ -class BL602Config -{ -public: - static constexpr const char * kBLConfigKey_wifissid = ("bl-wifi-ssid"); - static constexpr const char * kBLConfigKey_wifipassword = ("bl-wifi-psk"); - struct Key; - - // Maximum length of an easyflash key name - static constexpr size_t kMaxConfigKeyNameLength = 15; - - // Easyflash 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_ServiceConfig; - static const Key kConfigKey_PairedAccountId; - static const Key kConfigKey_ServiceId; - 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_UniqueId; - static const Key kConfigKey_Spake2pIterationCount; - static const Key kConfigKey_Spake2pSalt; - static const Key kConfigKey_Spake2pVerifier; - - static const Key kCounterKey_RebootCount; - static const Key kCounterKey_TotalOperationalHours; - - static CHIP_ERROR Init(void); - - // 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 ReadConfigValueBin(const char * 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 WriteWifiInfo(const char * ssid, const char * passwd); - static CHIP_ERROR ReadWiFiInfo(const char * ssid, uint32_t ssid_size, const char * passwd, uint32_t passwd_size); - static bool isWiFiInfoSaved(void); - - static CHIP_ERROR ClearConfigValue(Key key); - static bool ConfigValueExists(Key key); - - // // NVS Namespace helper functions. - // static CHIP_ERROR EnsureNamespace(const char * ns); - // static CHIP_ERROR ClearNamespace(const char * ns); - - static void RunConfigUnitTest(void); -}; - -struct BL602Config::Key -{ - // const char * Namespace; - const char * name; - - bool operator==(const Key & other) const; -}; - -inline bool BL602Config::Key::operator==(const Key & other) const -{ - return strcmp(name, other.name) == 0; -} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/BUILD.gn b/src/platform/bouffalolab/BL602/BUILD.gn index 64846e02898547..0f414afb036db6 100644 --- a/src/platform/bouffalolab/BL602/BUILD.gn +++ b/src/platform/bouffalolab/BL602/BUILD.gn @@ -1,4 +1,5 @@ -# Copyright (c) 2021 Project CHIP Authors +# Copyright (c) 2022 Project CHIP Authors +# All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,7 +14,6 @@ # limitations under the License. import("//build_overrides/chip.gni") -import("//build_overrides/pigweed.gni") import("${chip_root}/src/platform/device.gni") @@ -21,50 +21,45 @@ assert(chip_device_platform == "bl602") static_library("BL602") { sources = [ - "../../FreeRTOS/SystemTimeSupport.cpp", - "../../SingletonConfigurationManager.cpp", - "BL602Config.cpp", - "BL602Config.h", - "BLEManagerImpl.cpp", - "BLEManagerImpl.h", - "BlePlatformConfig.h", - "CHIPDevicePlatformConfig.h", - "CHIPDevicePlatformEvent.h", - "CHIPMem-Platform.cpp", - "CHIPPlatformConfig.h", "ConfigurationManagerImpl.cpp", - "ConfigurationManagerImpl.h", "ConnectivityManagerImpl.cpp", - "ConnectivityManagerImpl.h", "DiagnosticDataProviderImpl.cpp", - "DiagnosticDataProviderImpl.h", - "InetPlatformConfig.h", - "Logging.cpp", "NetworkCommissioningDriver.cpp", - "OTAImageProcessorImpl.cpp", "PlatformManagerImpl.cpp", - "PlatformManagerImpl.h", - "SystemPlatformConfig.h", "wifi_mgmr_portable.c", - "wifi_mgmr_portable.h", - ] - - deps = [ - "${chip_root}/src/lib/dnssd:platform_header", - "${chip_root}/src/setup_payload", - ] - - public_deps = [ "${chip_root}/src/platform:platform_base" ] - - sources += [ - "KeyValueStoreManagerImpl.cpp", - "KeyValueStoreManagerImpl.h", ] - sources += [ + common_sources = [ "${chip_root}/src/credentials/CHIPCert.h", "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", + "../../FreeRTOS/SystemTimeSupport.cpp", + "../../SingletonConfigurationManager.cpp", + "../common/BLConfig.cpp", + "../common/ConfigurationManagerImpl.cpp", + "../common/ConnectivityManagerImpl.cpp", + "../common/DiagnosticDataProviderImpl.cpp", "../common/FactoryDataProvider.cpp", "../common/FactoryDataProvider.h", + "../common/KeyValueStoreManagerImpl.cpp", + "../common/Logging.cpp", + "../common/PlatformManagerImpl.cpp", ] + + if (chip_enable_ota_requestor) { + sources += [ + "../common/OTAImageProcessorImpl.cpp", + "../common/OTAImageProcessorImpl.h", + ] + } + + if (chip_enable_ble) { + sources += [ + "../common/BLEManagerImpl.cpp", + "../common/BLEManagerImpl.h", + ] + } + sources += common_sources + + deps = [ "${chip_root}/src/lib/dnssd:platform_header" ] + public_deps = [ "${chip_root}/src/platform:platform_base" ] } diff --git a/src/platform/bouffalolab/BL602/BlePlatformConfig.h b/src/platform/bouffalolab/BL602/BlePlatformConfig.h deleted file mode 100644 index f445cabca58a59..00000000000000 --- a/src/platform/bouffalolab/BL602/BlePlatformConfig.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * - * 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 - * Platform-specific configuration overrides for the CHIP BLE - * Layer on the BL602 platform. - * - */ - -#pragma once - -// ==================== Platform Adaptations ==================== - -struct bt_conn; -#define BLE_CONNECTION_OBJECT bt_conn * -#define BLE_CONNECTION_UNINITIALIZED nullptr -#define BLE_MAX_RECEIVE_WINDOW_SIZE 5 - -// ========== Platform-specific Configuration Overrides ========= - -/* none so far */ diff --git a/src/platform/bouffalolab/BL602/CHIPDevicePlatformConfig.h b/src/platform/bouffalolab/BL602/CHIPDevicePlatformConfig.h deleted file mode 100644 index 7e6b56f57e3fed..00000000000000 --- a/src/platform/bouffalolab/BL602/CHIPDevicePlatformConfig.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * - * 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. - */ - -/** - * @file - * Platform-specific configuration overrides for the Chip Device Layer - * on BL602 platforms using the BouffaloLab SDK. - */ - -#pragma once - -// ==================== Platform Adaptations ==================== - -#define CHIP_DEVICE_CONFIG_BL602_EASYFLASH_ERROR_MIN 22000000 -#define CHIP_DEVICE_CONFIG_BL602_BLE_ERROR_MIN 23000000 - -#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 -#define CHIP_DEVICE_CONFIG_ENABLE_MDNS 1 -#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 -#endif - -//#define CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE 1 - -#define CHIP_DEVICE_CONFIG_PERSISTED_STORAGE_CRIT_EIDC_KEY 2 -#define CHIP_DEVICE_CONFIG_PERSISTED_STORAGE_PROD_EIDC_KEY 3 -#define CHIP_DEVICE_CONFIG_PERSISTED_STORAGE_INFO_EIDC_KEY 4 -#define CHIP_DEVICE_CONFIG_PERSISTED_STORAGE_DEBUG_EIDC_KEY 5 - -// ========== Platform-specific Configuration ========= - -// These are configuration options that are unique to the BL602 platform. -// These can be overridden by the application as needed. - -// -------------- BL602 EasyFlash Storage Configuration ------------- - -/** - * @def CHIP_DEVICE_CONFIG_EASYFLASH_MAX_NUM_OBJECTS - * - * @brief - * Configures the size of the easyflash cache and should be set >= the - * maximum number of Chip Config objects, e.g... - * Factory configs[5], System configs[23], Counter configs[32] + margin[4] = 64. - * - */ -#ifndef CHIP_DEVICE_CONFIG_EASYFLASH_MAX_NUM_OBJECTS -#define CHIP_DEVICE_CONFIG_EASYFLASH_MAX_NUM_OBJECTS 64 -#endif // CHIP_DEVICE_CONFIG_EASYFLASH_MAX_NUM_OBJECTS - -/** - * @def CHIP_DEVICE_CONFIG_EASYFLASH_MAX_OBJECT_SIZE - * - * @brief - * This determines the max size for any Chip easyflash object - * (e.g. for Config 'string' or 'binary' types). - */ -#ifndef CHIP_DEVICE_CONFIG_EASYFLASH_MAX_OBJECT_SIZE -#define CHIP_DEVICE_CONFIG_EASYFLASH_MAX_OBJECT_SIZE 1000 -#endif // CHIP_DEVICE_CONFIG_EASYFLASH_MAX_OBJECT_SIZE - -/** - * @def CHIP_DEVICE_CONFIG_EASYFLASH_NUM_FLASH_PAGES_FOR_STORAGE - * - * @brief - * This determines the Flash size used for easyflash data storage:- - * (assuming 2k Flash page size) => Total Flash size for easyflash: 8 * 2k = 16k - * The total size should allow sufficient margin for wear-levelling and - * repacking. - */ -#ifndef CHIP_DEVICE_CONFIG_EASYFLASH_NUM_FLASH_PAGES_FOR_STORAGE -#define CHIP_DEVICE_CONFIG_EASYFLASH_NUM_FLASH_PAGES_FOR_STORAGE 8 -#endif // CHIP_DEVICE_CONFIG_EASYFLASH_NUM_FLASH_PAGES_FOR_STORAGE - -// ========== Platform-specific Configuration Overrides ========= - -#ifndef CHIP_DEVICE_CONFIG_BLE_LL_TASK_PRIORITY -#define CHIP_DEVICE_CONFIG_BLE_LL_TASK_PRIORITY (configTIMER_TASK_PRIORITY - 1) -#endif // CHIP_DEVICE_CONFIG_BLE_LL_TASK_PRIORITY - -#ifndef CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY -#define CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY (CHIP_DEVICE_CONFIG_BLE_LL_TASK_PRIORITY - 1) -#endif // CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY - -#ifndef CHIP_DEVICE_CONFIG_BLE_APP_TASK_PRIORITY -#define CHIP_DEVICE_CONFIG_BLE_APP_TASK_PRIORITY (CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY - 1) -#endif // CHIP_DEVICE_CONFIG_BLE_STACK_TASK_PRIORITY - -#ifndef CHIP_DEVICE_CONFIG_BLE_APP_TASK_STACK_SIZE -#define CHIP_DEVICE_CONFIG_BLE_APP_TASK_STACK_SIZE 1536 -#endif // CHIP_DEVICE_CONFIG_BLE_APP_TASK_STACK_SIZE - -#ifndef CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE -#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE (8 * 1024) -#endif // CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE - -#ifndef CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE -#if defined(BL602MG21) -#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE (2 * 1024) -#else -#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE (3 * 1024) -#endif -#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 - -#ifndef CHIP_DEVICE_CONFIG_BLE_APP_TASK_NAME -#define CHIP_DEVICE_CONFIG_BLE_APP_TASK_NAME "BLE_EVENT" -#endif // CHIP_DEVICE_CONFIG_BLE_APP_TASK_NAME - -#define CHIP_DEVICE_CONFIG_MAX_EVENT_QUEUE_SIZE 25 diff --git a/src/platform/bouffalolab/BL602/CHIPDevicePlatformEvent.h b/src/platform/bouffalolab/BL602/CHIPDevicePlatformEvent.h deleted file mode 100644 index 1342cc24ac2830..00000000000000 --- a/src/platform/bouffalolab/BL602/CHIPDevicePlatformEvent.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Defines platform-specific event types and data for the chip - * Device Layer on the BL602 platform. - */ - -#pragma once - -#include - -#include -#include - -namespace chip { -namespace DeviceLayer { - -namespace DeviceEventType { - -/** - * Enumerates Zephyr platform-specific event types that are visible to the application. - */ -enum PublicPlatformSpecificEventTypes -{ - /* None currently defined */ -}; - -/** - * Enumerates Zephyr platform-specific event types that are internal to the chip Device Layer. - */ -enum InternalPlatformSpecificEventTypes -{ - kPlatformZephyrEvent = kRange_InternalPlatformSpecific, - kPlatformZephyrBleConnected, - kPlatformZephyrBleDisconnected, - kPlatformZephyrBleCCCWrite, - kPlatformZephyrBleC1WriteEvent, - kPlatformZephyrBleC2IndDoneEvent, - kPlatformZephyrBleOutOfBuffersEvent, -}; - -} // namespace DeviceEventType - -struct BleConnEventType -{ - bt_conn * BtConn; - uint8_t HciResult; -}; - -struct BleCCCWriteEventType -{ - bt_conn * BtConn; - uint16_t Value; -}; - -struct BleC1WriteEventType -{ - bt_conn * BtConn; - ::chip::System::PacketBuffer * Data; -}; - -struct BleC2IndDoneEventType -{ - bt_conn * BtConn; - uint8_t Result; -}; - -/** - * Represents platform-specific event information for BL602 platforms. - */ -struct ChipDevicePlatformEvent final -{ - union - { - BleConnEventType BleConnEvent; - BleCCCWriteEventType BleCCCWriteEvent; - BleC1WriteEventType BleC1WriteEvent; - BleC2IndDoneEventType BleC2IndDoneEvent; - }; -}; - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp b/src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp deleted file mode 100644 index 3b9b274941bfb8..00000000000000 --- a/src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - * - * Copyright (c) 2021 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 -#include -#include - -#include -#include -#include -#include -#include - -extern "C" { -#include -}; - -#if CHIP_CONFIG_MEMORY_MGMT_PLATFORM - -extern "C" void memMonitoringTrackAlloc(void * ptr, size_t size); -extern "C" void memMonitoringTrackFree(void * ptr, size_t size); - -#ifndef trackAlloc -#define trackAlloc(pvAddress, uiSize) memMonitoringTrackAlloc(pvAddress, uiSize) -#endif -#ifndef trackFree -#define trackFree(pvAddress, uiSize) memMonitoringTrackFree(pvAddress, uiSize) -#endif - -namespace chip { -namespace Platform { - -#define VERIFY_INITIALIZED() VerifyInitialized(__func__) - -static std::atomic_int memoryInitialized{ 0 }; - -static void VerifyInitialized(const char * func) -{ - if (!memoryInitialized) - { - log_error("ABORT: chip::Platform::%s() called before chip::Platform::MemoryInit()\r\n", func); - abort(); - } -} - -CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize) -{ -#ifndef NDEBUG - if (memoryInitialized++ > 0) - { - log_error("ABORT: chip::Platform::MemoryInit() called twice.\r\n"); - abort(); - } -#endif - return CHIP_NO_ERROR; -} - -void MemoryAllocatorShutdown() -{ -#ifndef NDEBUG - if (--memoryInitialized < 0) - { - log_error("ABORT: chip::Platform::MemoryShutdown() called twice.\r\n"); - abort(); - } -#endif -} - -void * MemoryAlloc(size_t size) -{ - void * ptr; - VERIFY_INITIALIZED(); - ptr = pvPortMalloc(size); - trackAlloc(ptr, size); - return ptr; -} - -void * MemoryAlloc(size_t size, bool isLongTermAlloc) -{ - void * ptr; - VERIFY_INITIALIZED(); - ptr = pvPortMalloc(size); - trackAlloc(ptr, size); - return ptr; -} - -void * MemoryCalloc(size_t num, size_t size) -{ - void * ptr; - VERIFY_INITIALIZED(); - ptr = pvPortCalloc(num, size); - trackAlloc(ptr, size * num); - return ptr; -} - -void * MemoryRealloc(void * p, size_t size) -{ - VERIFY_INITIALIZED(); - return pvPortRealloc(p, size); -} - -void MemoryFree(void * p) -{ - VERIFY_INITIALIZED(); - trackFree(p, 0); - vPortFree(p); -} - -bool MemoryInternalCheckPointer(const void * p, size_t min_size) -{ - return (p != nullptr); -} - -} // namespace Platform -} // namespace chip - -extern "C" void memMonitoringTrackAlloc(void * ptr, size_t size) {} - -extern "C" void memMonitoringTrackFree(void * ptr, size_t size) {} - -#endif // CHIP_CONFIG_MEMORY_MGMT_PLATFORM diff --git a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp b/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp index 5c53153867fbe0..b112fe751a4358 100644 --- a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp @@ -1,7 +1,5 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Nest Labs, Inc. + * Copyright (c) 2022 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,213 +15,25 @@ * limitations under the License. */ -/** - * @file - * Provides the implementation of the Device Layer ConfigurationManager object - * for the BL602 platform. - */ -/* this file behaves like a config.h, comes first */ #include -#include -#include #include -#include + #include +#include +#include + +#include +#include + extern "C" { #include -#include -#include } namespace chip { namespace DeviceLayer { -using namespace ::chip::DeviceLayer::Internal; - -namespace { - -enum -{ - kChipProduct_Connect = 0x0016 -}; - -} // unnamed namespace - -/** Singleton instance of the ConfigurationManager implementation object for the BL602 platform. - */ -ConfigurationManagerImpl ConfigurationManagerImpl::sInstance; - -ConfigurationManagerImpl & ConfigurationManagerImpl::GetDefaultInstance() -{ - static ConfigurationManagerImpl sInstance; - return sInstance; -} - -CHIP_ERROR ConfigurationManagerImpl::Init() -{ - CHIP_ERROR err; - bool failSafeArmed; - uint32_t rebootCount; - - // Initialize the generic implementation base class. - err = Internal::GenericConfigurationManagerImpl::Init(); - SuccessOrExit(err); - - if (BL602Config::ConfigValueExists(BL602Config::kCounterKey_RebootCount)) - { - err = GetRebootCount(rebootCount); - SuccessOrExit(err); - } - else - { - rebootCount = 0; - } - - err = StoreRebootCount(rebootCount + 1); - SuccessOrExit(err); - - if (!BL602Config::ConfigValueExists(BL602Config::kCounterKey_TotalOperationalHours)) - { - err = StoreTotalOperationalHours(0); - 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; -} - -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::GetRebootCount(uint32_t & rebootCount) -{ - return BL602Config::ReadConfigValue(BL602Config::kCounterKey_RebootCount, rebootCount); -} - -CHIP_ERROR ConfigurationManagerImpl::StoreRebootCount(uint32_t rebootCount) -{ - return BL602Config::WriteConfigValue(BL602Config::kCounterKey_RebootCount, rebootCount); -} - -CHIP_ERROR ConfigurationManagerImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) -{ - return ReadConfigValue(BL602Config::kCounterKey_TotalOperationalHours, totalOperationalHours); -} - -CHIP_ERROR ConfigurationManagerImpl::StoreTotalOperationalHours(uint32_t totalOperationalHours) -{ - return WriteConfigValue(BL602Config::kCounterKey_TotalOperationalHours, totalOperationalHours); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) -{ - BL602Config::Key configKey{ 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) -{ - BL602Config::Key configKey{ key }; - return WriteConfigValue(configKey, value); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, bool & val) -{ - return BL602Config::ReadConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint32_t & val) -{ - return BL602Config::ReadConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint64_t & val) -{ - return BL602Config::ReadConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) -{ - return BL602Config::ReadConfigValueStr(key, buf, bufSize, outLen); -} - -CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) -{ - return BL602Config::ReadConfigValueBin(key, buf, bufSize, outLen); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, bool val) -{ - return BL602Config::WriteConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint32_t val) -{ - return BL602Config::WriteConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint64_t val) -{ - return BL602Config::WriteConfigValue(key, val); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str) -{ - return BL602Config::WriteConfigValueStr(key, str); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str, size_t strLen) -{ - return BL602Config::WriteConfigValueStr(key, str, strLen); -} - -CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) -{ - return BL602Config::WriteConfigValueBin(key, data, dataLen); -} - -void ConfigurationManagerImpl::RunConfigUnitTest(void) -{ - BL602Config::RunConfigUnitTest(); -} - -void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) -{ - ChipLogProgress(DeviceLayer, "Performing factory reset"); - ef_env_set_default(); - ChipLogProgress(DeviceLayer, "System restarting"); - hal_reboot(); -} - -ConfigurationManager & ConfigurationMgrImpl() -{ - return ConfigurationManagerImpl::GetDefaultInstance(); -} - CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * buf) { bl_efuse_read_mac(buf); diff --git a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h b/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h deleted file mode 100644 index 0183da4e3a007f..00000000000000 --- a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Nest Labs, Inc. - * 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 BL602 platform. - */ - -#pragma once - -#include -#include -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include -#else -#include -#endif - -#include - -namespace chip { -namespace DeviceLayer { - -/** - * Concrete implementation of the ConfigurationManager singleton object for the BL602 platform. - */ -class ConfigurationManagerImpl final : public Internal::GenericConfigurationManagerImpl, -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - public Internal::GenericConnectivityManagerImpl_BLE -#else - public Internal::GenericConnectivityManagerImpl_NoBLE -#endif -{ -public: - static ConfigurationManagerImpl & GetDefaultInstance(); - // Allow the ConfigurationManager interface class to delegate method calls to - // the implementation methods provided by this class. - friend class ConfigurationManager; - -private: - // ===== Members that implement the ConfigurationManager public interface. - - CHIP_ERROR Init(void) override; - CHIP_ERROR GetPrimaryWiFiMACAddress(uint8_t * buf) override; - bool CanFactoryReset(void) override; - void InitiateFactoryReset(void) override; - CHIP_ERROR ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) override; - CHIP_ERROR WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) override; - - CHIP_ERROR GetRebootCount(uint32_t & rebootCount) override; - CHIP_ERROR StoreRebootCount(uint32_t rebootCount) override; - CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours) override; - CHIP_ERROR StoreTotalOperationalHours(uint32_t totalOperationalHours) override; -#if 0 - CHIP_ERROR GetBootReason(uint32_t & bootReasons) override; - CHIP_ERROR StoreBootReason(uint32_t bootReasons) override; -#endif - - // NOTE: Other public interface methods are implemented by GenericConfigurationManagerImpl<>. - - // ===== Members for internal use by the following friends. - - CHIP_ERROR ReadConfigValue(Key key, bool & val) override; - CHIP_ERROR ReadConfigValue(Key key, uint32_t & val) override; - CHIP_ERROR ReadConfigValue(Key key, uint64_t & val) override; - CHIP_ERROR ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) override; - CHIP_ERROR ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) override; - CHIP_ERROR WriteConfigValue(Key key, bool val) override; - CHIP_ERROR WriteConfigValue(Key key, uint32_t val) override; - CHIP_ERROR WriteConfigValue(Key key, uint64_t val) override; - CHIP_ERROR WriteConfigValueStr(Key key, const char * str) override; - CHIP_ERROR WriteConfigValueStr(Key key, const char * str, size_t strLen) override; - CHIP_ERROR WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) override; - void RunConfigUnitTest(void) override; - - static ConfigurationManagerImpl sInstance; - - // ===== Private members reserved for use by this class only. - - static void DoFactoryReset(intptr_t arg); -}; - -/** - * Returns the platform-specific implementation of the ConfigurationManager object. - * - * Applications can use this to gain access to features of the ConfigurationManager - * that are specific to the selected platform. - */ -ConfigurationManager & ConfigurationMgrImpl(); - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp index 56e3ebf522a36b..9f209d14ebf133 100644 --- a/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp @@ -1,7 +1,6 @@ /* - * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Nest Labs, Inc. + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +14,7 @@ * 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 @@ -68,7 +67,6 @@ using namespace ::chip::DeviceLayer::Internal; namespace chip { namespace DeviceLayer { -ConnectivityManagerImpl ConnectivityManagerImpl::sInstance; ConnectivityManager::WiFiStationState ConnectivityManagerImpl::mWiFiStationState = ConnectivityManager::kWiFiStationState_NotConnected; @@ -103,34 +101,6 @@ CHIP_ERROR ConnectivityManagerImpl::_SetWiFiStationMode(WiFiStationMode val) return err; } -CHIP_ERROR ConnectivityManagerImpl::_Init() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - // Initialize the generic base classes that require it. -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD - GenericConnectivityManagerImpl_Thread::_Init(); -#endif - - SuccessOrExit(err); - - err = SetWiFiStationMode(kWiFiStationMode_Enabled); - NetworkCommissioning::BLWiFiDriver::GetInstance().ReConnectWiFiNetwork(); - - SuccessOrExit(err); - -exit: - return err; -} - -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 -} - bool ConnectivityManagerImpl::_IsWiFiStationEnabled(void) { return GetWiFiStationMode() == kWiFiStationMode_Enabled; diff --git a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp index 3597e599a4c587..b49fa9cbde9a5a 100644 --- a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp +++ b/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp @@ -1,6 +1,6 @@ /* - * - * Copyright (c) 2021-2022 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,133 +15,51 @@ * limitations under the License. */ -/** - * @file - * Provides an implementation of the DiagnosticDataProvider object - * for Bouffalolab BL602 platform. - */ - -#include - -#include -#include #include +#include +#include +#include #include extern "C" { +#include +#include + #include #include #include -#include -#include #include #include } -extern uint8_t _heap_size; - namespace chip { namespace DeviceLayer { -DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() -{ - static DiagnosticDataProviderImpl sInstance; - return sInstance; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) -{ - size_t freeHeapSize; - - freeHeapSize = xPortGetFreeHeapSize(); - currentHeapFree = static_cast(freeHeapSize); - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) -{ - currentHeapUsed = (uint32_t) &_heap_size - xPortGetFreeHeapSize(); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) -{ - currentHeapHighWatermark = (uint32_t) &_heap_size - 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(BootReasonType & bootReason) { - BL_RST_REASON_E BL_RST_REASON = bl_sys_rstinfo_get(); - - bootReason = BootReasonType::kUnspecified; + BL_RST_REASON_E bootCause = bl_sys_rstinfo_get(); - if (BL_RST_REASON == BL_RST_POWER_OFF) + if (bootCause == BL_RST_POWER_OFF) { bootReason = BootReasonType::kPowerOnReboot; } - else if (BL_RST_REASON == BL_RST_HARDWARE_WATCHDOG) + else if (bootCause == BL_RST_HARDWARE_WATCHDOG) { bootReason = BootReasonType::kHardwareWatchdogReset; } - else if (BL_RST_REASON == BL_RST_SOFTWARE_WATCHDOG) + else if (bootCause == BL_RST_SOFTWARE_WATCHDOG) { bootReason = BootReasonType::kSoftwareWatchdogReset; } - else if (BL_RST_REASON == BL_RST_SOFTWARE) + else if (bootCause == BL_RST_SOFTWARE) { bootReason = BootReasonType::kSoftwareReset; } + else + { + bootReason = BootReasonType::kUnspecified; + } return CHIP_NO_ERROR; } @@ -214,11 +132,6 @@ void DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * net } } -DiagnosticDataProvider & GetDiagnosticDataProviderImpl() -{ - return DiagnosticDataProviderImpl::GetDefaultInstance(); -} - CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(MutableByteSpan & BssId) { return CopySpanToMutableSpan(ByteSpan(wifiMgmr.wifi_mgmr_stat_info.bssid), BssId); @@ -376,5 +289,4 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconRxCount(uint32_t & beaconRxC } } // namespace DeviceLayer -wifi_diagnosis_info_t * info; } // namespace chip diff --git a/src/platform/bouffalolab/BL602/InetPlatformConfig.h b/src/platform/bouffalolab/BL602/InetPlatformConfig.h deleted file mode 100644 index 0c17f57a4c798a..00000000000000 --- a/src/platform/bouffalolab/BL602/InetPlatformConfig.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Google LLC. - * - * 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 BL602 platforms using the Bouffalolab SDK. - * - */ - -#pragma once - -#include - -// ==================== 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 - -#define INET_CONFIG_ENABLE_IPV4 1 - -// ========== Platform-specific Configuration Overrides ========= - -#ifndef INET_CONFIG_NUM_TCP_ENDPOINTS -#define INET_CONFIG_NUM_TCP_ENDPOINTS 4 -#endif // INET_CONFIG_NUM_TCP_ENDPOINTS - -#ifndef INET_CONFIG_NUM_UDP_ENDPOINTS -#define INET_CONFIG_NUM_UDP_ENDPOINTS 6 -#endif // INET_CONFIG_NUM_UDP_ENDPOINTS diff --git a/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp b/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp deleted file mode 100644 index dc7aee8708d0f5..00000000000000 --- a/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Platform-specific key value storage implementation for BL602 - */ -/* this file behaves like a config.h, comes first */ -#include - -#include - -#include - -#include -#include - -namespace chip { -namespace DeviceLayer { -namespace PersistedStorage { - -using namespace ::chip::DeviceLayer::Internal; - -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) const -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - // todo: need get value at offset for return - size_t outlen = 0; - BL602Config::Key ckey = { key }; - - err = BL602Config::ReadConfigValueBin(ckey, (uint8_t *) value, value_size, outlen); - if (CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND == err) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - SuccessOrExit(err); - - if (read_bytes_size) - { - *read_bytes_size = outlen; - } - -exit: - return err; -} - -CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, size_t value_size) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - BL602Config::Key ckey = { key }; - - err = BL602Config::WriteConfigValueBin(ckey, (uint8_t *) value, value_size); - if (CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND == err) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - return err; -} - -CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - BL602Config::Key ckey = { key }; - - err = BL602Config::ClearConfigValue(ckey); - - if (CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND == err) - { - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - } - - return err; -} - -// #if defined(CHIP_KVS_AVAILABLE) && CHIP_KVS_AVAILABLE - -// CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t value_size, size_t * read_bytes_size, -// size_t offset_bytes) const -// { -// assert(CHIP_KVS_AVAILABLE); -// auto status_and_size = mKvs.Get(key, pw::span(reinterpret_cast(value), value_size), offset_bytes); -// if (read_bytes_size) -// { -// *read_bytes_size = status_and_size.size(); -// } -// switch (status_and_size.status().code()) -// { -// case pw::OkStatus().code(): -// return CHIP_NO_ERROR; -// case pw::Status::NotFound().code(): -// return CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; -// case pw::Status::DataLoss().code(): -// return CHIP_ERROR_INTEGRITY_CHECK_FAILED; -// case pw::Status::ResourceExhausted().code(): -// return CHIP_ERROR_BUFFER_TOO_SMALL; -// case pw::Status::FailedPrecondition().code(): -// return CHIP_ERROR_WELL_UNINITIALIZED; -// case pw::Status::InvalidArgument().code(): -// return CHIP_ERROR_INVALID_ARGUMENT; -// default: -// break; -// } -// return CHIP_ERROR_INTERNAL; // Unexpected KVS status. -// } - -// CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, size_t value_size) -// { -// assert(CHIP_KVS_AVAILABLE); -// auto status = mKvs.Put(key, pw::span(reinterpret_cast(value), value_size)); -// switch (status.code()) -// { -// case pw::OkStatus().code(): -// return CHIP_NO_ERROR; -// case pw::Status::DataLoss().code(): -// return CHIP_ERROR_INTEGRITY_CHECK_FAILED; -// case pw::Status::ResourceExhausted().code(): -// case pw::Status::AlreadyExists().code(): -// return CHIP_ERROR_PERSISTED_STORAGE_FAILED; -// case pw::Status::FailedPrecondition().code(): -// return CHIP_ERROR_WELL_UNINITIALIZED; -// case pw::Status::InvalidArgument().code(): -// return CHIP_ERROR_INVALID_ARGUMENT; -// default: -// break; -// } -// return CHIP_ERROR_INTERNAL; // Unexpected KVS status. -// } - -// CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) -// { -// printf("KeyValueStoreManagerImpl::_Delete, key = %s\r\n", key); -// assert(CHIP_KVS_AVAILABLE); -// printf("KeyValueStoreManagerImpl::_Delete, key = %s\r\n", key); - -// auto status = mKvs.Delete(key); -// switch (status.code()) -// { -// case pw::OkStatus().code(): -// return CHIP_NO_ERROR; -// case pw::Status::NotFound().code(): -// return CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; -// case pw::Status::DataLoss().code(): -// return CHIP_ERROR_INTEGRITY_CHECK_FAILED; -// case pw::Status::ResourceExhausted().code(): -// return CHIP_ERROR_PERSISTED_STORAGE_FAILED; -// case pw::Status::FailedPrecondition().code(): -// return CHIP_ERROR_WELL_UNINITIALIZED; -// case pw::Status::InvalidArgument().code(): -// return CHIP_ERROR_INVALID_ARGUMENT; -// default: -// break; -// } -// return CHIP_ERROR_INTERNAL; // Unexpected KVS status. -// } - -// CHIP_ERROR KeyValueStoreManagerImpl::ErasePartition() -// { -// assert(CHIP_KVS_AVAILABLE); -// auto status = mKvsPartition.Erase(); -// switch (status.code()) -// { -// case pw::OkStatus().code(): -// return CHIP_NO_ERROR; -// case pw::Status::DeadlineExceeded().code(): -// return CHIP_ERROR_TIMEOUT; -// case pw::Status::PermissionDenied().code(): -// return CHIP_ERROR_ACCESS_DENIED; -// default: -// break; -// } -// return CHIP_ERROR_INTERNAL; // Unexpected KVS status. -// } -// #endif // defined(CHIP_KVS_AVAILABLE) && CHIP_KVS_AVAILABLE - -} // namespace PersistedStorage -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.h b/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.h deleted file mode 100644 index c7d495b347db42..00000000000000 --- a/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Platform-specific key value storage implementation for BL602. - * - */ - -#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: - CHIP_ERROR _Get(const char * key, void * value, size_t value_size, size_t * read_bytes_size = nullptr, size_t offset = 0) const; - - 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 - * that are specific to the ESP32 platform. - */ -inline KeyValueStoreManagerImpl & KeyValueStoreMgrImpl(void) -{ - return KeyValueStoreManagerImpl::sInstance; -} - -} // namespace PersistedStorage -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/Logging.cpp b/src/platform/bouffalolab/BL602/Logging.cpp deleted file mode 100644 index 33397bd520f409..00000000000000 --- a/src/platform/bouffalolab/BL602/Logging.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* See Project CHIP LICENSE file for licensing information. */ - -#include - -#include -#include - -#include -#include - -#ifdef PW_RPC_ENABLED -#include "PigweedLogger.h" -#endif - -namespace chip { -namespace Logging { -namespace Platform { - -void LogV(const char * module, uint8_t category, const char * msg, va_list v) -{ - char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; - -#ifndef PW_RPC_ENABLED - vsnprintf(formattedMsg, sizeof(formattedMsg), msg, v); - - switch (category) - { - case kLogCategory_Error: - log_error("[%s] %s\r\n", module, formattedMsg); - break; - case kLogCategory_Progress: - default: - log_info("[%s] %s\r\n", module, formattedMsg); - break; - case kLogCategory_Detail: - log_trace("[%s] %s\r\n", module, formattedMsg); - break; - } -#else - size_t prefixLen = 0; - - switch (category) - { - case kLogCategory_Error: - strcpy(formattedMsg, "[ERROR] "); - break; - case kLogCategory_Progress: - default: - strcpy(formattedMsg, "[INFO] "); - break; - case kLogCategory_Detail: - strcpy(formattedMsg, "[TRACE] "); - break; - } - - prefixLen = strlen(formattedMsg); - snprintf(formattedMsg + prefixLen, sizeof(formattedMsg) - prefixLen, "[%s] ", module); - prefixLen = strlen(formattedMsg); - vsnprintf(formattedMsg + prefixLen, sizeof(formattedMsg) - prefixLen, msg, v); - - PigweedLogger::putString(formattedMsg, strlen(formattedMsg)); - const char * newline = "\r\n"; - PigweedLogger::putString(newline, strlen(newline)); -#endif -} - -} // namespace Platform -} // namespace Logging -} // namespace chip diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp index f4ba42ff5adcc2..28f5a5f9a2892d 100644 --- a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp +++ b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp @@ -35,7 +35,7 @@ #define WIFI_STA_DISCONNECT_DELAY (pdMS_TO_TICKS(200)) using namespace ::chip; -//#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + namespace chip { namespace DeviceLayer { namespace NetworkCommissioning { @@ -425,4 +425,3 @@ bool BLWiFiDriver::WiFiNetworkIterator::Next(Network & item) } // namespace NetworkCommissioning } // namespace DeviceLayer } // namespace chip -//#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI diff --git a/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp index a8739d6adfbe9e..56761846061dc2 100644 --- a/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp @@ -1,7 +1,6 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Nest Labs, Inc. + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +15,12 @@ * limitations under the License. */ -/** - * @file - * Provides an implementation of the PlatformManager object - * for BL602 platforms using the Bouffalolab BL602 SDK. - */ -/* this file behaves like a config.h, comes first */ #include #include #include -#include #include +#include #include #include @@ -48,8 +41,6 @@ extern "C" { namespace chip { namespace DeviceLayer { -PlatformManagerImpl PlatformManagerImpl::sInstance; - static wifi_conf_t conf = { .country_code = "CN", }; @@ -237,7 +228,7 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) TaskHandle_t backup_eventLoopTask; // Initialize the configuration system. - err = Internal::BL602Config::Init(); + err = Internal::BLConfig::Init(); SuccessOrExit(err); // Initialize LwIP. @@ -269,30 +260,5 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) return err; } -void 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"); - } - - Internal::GenericPlatformManagerImpl_FreeRTOS::_Shutdown(); -} - } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL602/SystemPlatformConfig.h b/src/platform/bouffalolab/BL602/SystemPlatformConfig.h deleted file mode 100644 index cf6fbdc4be2240..00000000000000 --- a/src/platform/bouffalolab/BL602/SystemPlatformConfig.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Google LLC. - * - * 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 Bouffalolab BL602 Platforms. - * - */ - -#pragma once - -#include - -namespace chip { -namespace DeviceLayer { -struct ChipDeviceEvent; -} // namespace DeviceLayer -} // namespace chip - -// ==================== Platform Adaptations ==================== -#define CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME 1 -#define CHIP_SYSTEM_CONFIG_LWIP_EVENT_TYPE int -#define CHIP_SYSTEM_CONFIG_EVENT_OBJECT_TYPE const struct ::chip::DeviceLayer::ChipDeviceEvent * - -#define CHIP_SYSTEM_CONFIG_ERROR_TYPE int32_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 - -// ========== Platform-specific Configuration Overrides ========= diff --git a/src/platform/bouffalolab/BL602/args.gni b/src/platform/bouffalolab/BL602/args.gni index 0f32696fb1c914..9a4f156ce3ee8c 100644 --- a/src/platform/bouffalolab/BL602/args.gni +++ b/src/platform/bouffalolab/BL602/args.gni @@ -28,8 +28,6 @@ chip_inet_config_enable_ipv4 = true chip_enable_rotating_device_id = false -chip_config_memory_management = "platform" - chip_build_tests = false chip_inet_config_enable_dns_resolver = false chip_inet_config_enable_tun_endpoint = false diff --git a/src/platform/bouffalolab/BL702/BLEManagerImpl.cpp b/src/platform/bouffalolab/BL702/BLEManagerImpl.cpp deleted file mode 100644 index 2a90fdf646aaba..00000000000000 --- a/src/platform/bouffalolab/BL702/BLEManagerImpl.cpp +++ /dev/null @@ -1,834 +0,0 @@ -/* - * - * Copyright (c) 2020-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. - */ - -#define __ZEPHYR__ 1 -#include - -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - -#include "BLEManagerImpl.h" - -#include -#include -#include -#include -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -#include -#endif - -extern "C" { -#include -} - -#include -#include - -using namespace ::chip; -using namespace ::chip::Ble; -using namespace ::chip::System; - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -const bt_uuid_128 UUID128_CHIPoBLEChar_RX = - BT_UUID_INIT_128(0x11, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18); -const bt_uuid_128 UUID128_CHIPoBLEChar_TX = - BT_UUID_INIT_128(0x12, 0x9D, 0x9F, 0x42, 0x9C, 0x4F, 0x9F, 0x95, 0x59, 0x45, 0x3D, 0x26, 0xF5, 0x2E, 0xEE, 0x18); -bt_uuid_16 UUID16_CHIPoBLEService = BT_UUID_INIT_16(0xFFF6); - -const ChipBleUUID chipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; - -const ChipBleUUID chipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -const bt_uuid_128 UUID128_CHIPoBLEChar_C3 = - BT_UUID_INIT_128(0x04, 0x8F, 0x21, 0x83, 0x8A, 0x74, 0x7D, 0xB8, 0xF2, 0x45, 0x72, 0x87, 0x38, 0x02, 0x63, 0x64); -#endif - -_bt_gatt_ccc CHIPoBLEChar_TX_CCC = BT_GATT_CCC_INITIALIZER(nullptr, BLEManagerImpl::HandleTXCCCWrite, nullptr); - -struct bt_gatt_attr sChipoBleAttributes[] = { - BT_GATT_PRIMARY_SERVICE(&UUID16_CHIPoBLEService.uuid), - BT_GATT_CHARACTERISTIC(&UUID128_CHIPoBLEChar_RX.uuid, BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, nullptr, BLEManagerImpl::HandleRXWrite, nullptr), - BT_GATT_CHARACTERISTIC(&UUID128_CHIPoBLEChar_TX.uuid, BT_GATT_CHRC_INDICATE, BT_GATT_PERM_NONE, nullptr, nullptr, nullptr), - BT_GATT_CCC_MANAGED(&CHIPoBLEChar_TX_CCC, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE), -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - BT_GATT_CHARACTERISTIC(&UUID128_CHIPoBLEChar_C3.uuid, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, BLEManagerImpl::HandleC3Read, - nullptr, nullptr), -#endif -}; - -struct bt_gatt_service sChipoBleService = { - .attrs = sChipoBleAttributes, - .attr_count = sizeof(sChipoBleAttributes) / sizeof(sChipoBleAttributes[0]), -}; - -static const int kCHIPoBLE_CCC_AttributeIndex = 3; - -CHIP_ERROR InitRandomStaticAddress() -{ - // When the BT privacy feature is disabled, generate a random static address once per boot. - // This must be done before bt_enable() has been called. - bt_addr_le_t addr; - - int error = bt_addr_le_create_static(&addr); - if (error) - { - ChipLogError(DeviceLayer, "Failed to create BLE address: %d", error); - return System::MapErrorZephyr(error); - } - - error = bt_id_create(&addr, nullptr); - - if (error < 0) - { - ChipLogError(DeviceLayer, "Failed to create BLE identity: %d", error); - return System::MapErrorZephyr(error); - } - - ChipLogProgress(DeviceLayer, "BLE address: %02X:%02X:%02X:%02X:%02X:%02X", addr.a.val[5], addr.a.val[4], addr.a.val[3], - addr.a.val[2], addr.a.val[1], addr.a.val[0]); - return CHIP_NO_ERROR; -} - -BLEManagerImpl BLEManagerImpl::sInstance; - -CHIP_ERROR BLEManagerImpl::_Init() -{ - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; - mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); - mFlags.Set(Flags::kFastAdvertisingEnabled, true); - mGAPConns = 0; - - memset(mSubscribedConns, 0, sizeof(mSubscribedConns)); - - ReturnErrorOnFailure(InitRandomStaticAddress()); - - ble_controller_init(configMAX_PRIORITIES - 1); - hci_driver_init(); - bt_enable(NULL); - - memset(&mConnCallbacks, 0, sizeof(mConnCallbacks)); - mConnCallbacks.connected = HandleConnect; - mConnCallbacks.disconnected = HandleDisconnect; - - bt_conn_cb_register(&mConnCallbacks); - - // Initialize the CHIP BleLayer. - ReturnErrorOnFailure(BleLayer::Init(this, this, &DeviceLayer::SystemLayer())); - - PlatformMgr().ScheduleWork(DriveBLEState, 0); - - return CHIP_NO_ERROR; -} - -void BLEManagerImpl::DriveBLEState(intptr_t arg) -{ - BLEMgrImpl().DriveBLEState(); -} - -void BLEManagerImpl::DriveBLEState() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - // Perform any initialization actions that must occur after the CHIP task is running. - if (!mFlags.Has(Flags::kAsyncInitCompleted)) - { - mFlags.Set(Flags::kAsyncInitCompleted); - } - - // If the application has enabled CHIPoBLE and BLE advertising... - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && - mFlags.Has(Flags::kAdvertisingEnabled) -#if CHIP_DEVICE_CONFIG_CHIPOBLE_SINGLE_CONNECTION - // and no connections are active... - && (NumConnections() == 0) -#endif - ) - { - // Start/re-start advertising if not already advertising, or if the - // advertising state needs to be refreshed. - if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kAdvertisingRefreshNeeded)) - { - mFlags.Clear(Flags::kAdvertisingRefreshNeeded); - err = StartAdvertising(); - SuccessOrExit(err); - } - } - else - { - if (mFlags.Has(Flags::kAdvertising)) - { - err = StopAdvertising(); - SuccessOrExit(err); - } - - // If no connections are active unregister also CHIPoBLE GATT service - if (NumConnections() == 0 && mFlags.Has(Flags::kChipoBleGattServiceRegister)) - { - // Unregister CHIPoBLE service to not allow discovering it when pairing is disabled. - if (bt_gatt_service_unregister(&sChipoBleService) != 0) - { - ChipLogError(DeviceLayer, "Failed to unregister CHIPoBLE GATT service"); - } - else - { - mFlags.Clear(Flags::kChipoBleGattServiceRegister); - } - } - } - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; - } -} - -struct BLEManagerImpl::ServiceData -{ - uint8_t uuid[2]; - ChipBLEDeviceIdentificationInfo deviceIdInfo; -} __attribute__((packed)); - -CHIP_ERROR BLEManagerImpl::StartAdvertising(void) -{ - int err = 0; - const bool isAdvertisingRerun = mFlags.Has(Flags::kAdvertising); - - // At first run always select fast advertising, on the next attempt slow down interval. - const uint32_t intervalMin = mFlags.Has(Flags::kFastAdvertisingEnabled) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN - : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MIN; - const uint32_t intervalMax = mFlags.Has(Flags::kFastAdvertisingEnabled) ? CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX - : CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX; - - bt_le_adv_param advParams; - advParams.id = BT_ID_DEFAULT; - advParams.options = BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME; - advParams.interval_min = intervalMin; - advParams.interval_max = intervalMax; - - // Define advertising and, if BLE device name is set, scan response data - ServiceData serviceData; - const uint8_t advFlags = BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR; - const bt_data advertisingData[] = { BT_DATA(BT_DATA_FLAGS, &advFlags, sizeof(advFlags)), - BT_DATA(BT_DATA_SVC_DATA16, &serviceData, sizeof(serviceData)) }; - - const char * deviceName = bt_get_name(); - const uint8_t deviceNameSize = static_cast(strlen(deviceName)); - const bt_data scanResponseData[] = { BT_DATA(BT_DATA_NAME_COMPLETE, deviceName, deviceNameSize) }; - const bt_data * scanResponseDataPtr = deviceNameSize > 0 ? scanResponseData : nullptr; - const size_t scanResponseDataLen = deviceNameSize > 0 ? sizeof(scanResponseData) / sizeof(scanResponseData[0]) : 0u; - - // Register dynamically CHIPoBLE GATT service - if (!mFlags.Has(Flags::kChipoBleGattServiceRegister)) - { - err = bt_gatt_service_register(&sChipoBleService); - - if (err != 0) - ChipLogError(DeviceLayer, "Failed to register CHIPoBLE GATT service"); - - VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - - mFlags.Set(Flags::kChipoBleGattServiceRegister); - } - - // Initialize service data - static_assert(sizeof(serviceData) == 10, "Size of BLE advertisement data changed! Was that intentional?"); - chip::Encoding::LittleEndian::Put16(serviceData.uuid, UUID16_CHIPoBLEService.val); - ReturnErrorOnFailure(ConfigurationMgr().GetBLEDeviceIdentificationInfo(serviceData.deviceIdInfo)); - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - ReturnErrorOnFailure(PrepareC3CharData()); -#endif - - if (!isAdvertisingRerun) - { -#if CONFIG_BT_PRIVACY - static_assert(CHIP_DEVICE_CONFIG_DISCOVERY_TIMEOUT_SECS <= CONFIG_BT_RPA_TIMEOUT, - "BLE advertising timeout is too long relative to RPA timeout"); - // Generate new private BLE address - bt_le_oob bleOobInfo; - err = bt_le_oob_get_local(advParams.id, &bleOobInfo); - VerifyOrReturnError(err == 0, MapErrorZephyr(err)); -#endif // CONFIG_BT_PRIVACY - } - - // Restart advertising - err = bt_le_adv_stop(); - VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - - err = bt_le_adv_start(&advParams, advertisingData, sizeof(advertisingData) / sizeof(advertisingData[0]), scanResponseDataPtr, - scanResponseDataLen); - VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - - // Transition to the Advertising state... - if (!mFlags.Has(Flags::kAdvertising)) - { - ChipLogProgress(DeviceLayer, "CHIPoBLE advertising started"); - - mFlags.Set(Flags::kAdvertising); - - // Post a CHIPoBLEAdvertisingChange(Started) event. - { - ChipDeviceEvent advChange; - advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; - advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Started; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&advChange)); - } - - if (mFlags.Has(Flags::kFastAdvertisingEnabled)) - { - // Start timer to change advertising interval. - DeviceLayer::SystemLayer().StartTimer( - System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME), - HandleBLEAdvertisementIntervalChange, this); - } - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::StopAdvertising(void) -{ - int err = bt_le_adv_stop(); - VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - - // Transition to the not Advertising state... - if (mFlags.Has(Flags::kAdvertising)) - { - mFlags.Clear(Flags::kAdvertising); - mFlags.Set(Flags::kFastAdvertisingEnabled, true); - - ChipLogProgress(DeviceLayer, "CHIPoBLE advertising stopped"); - - // Post a CHIPoBLEAdvertisingChange(Stopped) event. - { - ChipDeviceEvent advChange; - advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; - advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Stopped; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&advChange)); - } - - // Cancel timer event changing CHIPoBLE advertisement interval - DeviceLayer::SystemLayer().CancelTimer(HandleBLEAdvertisementIntervalChange, this); - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) -{ - VerifyOrReturnError(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, - CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - - if (mFlags.Has(Flags::kAdvertisingEnabled) != val) - { - ChipLogDetail(DeviceLayer, "CHIPoBLE advertising set to %s", val ? "on" : "off"); - - mFlags.Set(Flags::kAdvertisingEnabled, val); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode) -{ - switch (mode) - { - 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) -{ - Platform::CopyString(buf, bufSize, bt_get_name()); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) -{ - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported) - { - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; - } - - ChipLogDetail(DeviceLayer, "Device name set to: %s", deviceName); - return MapErrorZephyr(bt_set_name(deviceName)); -} - -CHIP_ERROR BLEManagerImpl::HandleGAPConnect(const ChipDeviceEvent * event) -{ - const BleConnEventType * connEvent = &event->Platform.BleConnEvent; - - if (connEvent->HciResult == BT_HCI_ERR_SUCCESS) - { - ChipLogProgress(DeviceLayer, "BLE connection established (ConnId: 0x%02x)", bt_conn_index(connEvent->BtConn)); - mGAPConns++; - } - else - { - ChipLogError(DeviceLayer, "BLE connection failed (reason: 0x%02x)", connEvent->HciResult); - } - - ChipLogProgress(DeviceLayer, "Current number of connections: %u/%u", NumConnections(), CONFIG_BT_MAX_CONN); - - mFlags.Set(Flags::kAdvertisingRefreshNeeded); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - - bt_conn_unref(connEvent->BtConn); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::HandleGAPDisconnect(const ChipDeviceEvent * event) -{ - const BleConnEventType * connEvent = &event->Platform.BleConnEvent; - - ChipLogProgress(DeviceLayer, "BLE GAP connection terminated (reason 0x%02x)", connEvent->HciResult); - - mGAPConns--; - - // If indications were enabled for this connection, record that they are now disabled and - // notify the BLE Layer of a disconnect. - if (UnsetSubscribed(connEvent->BtConn)) - { - CHIP_ERROR disconReason; - switch (connEvent->HciResult) - { - case BT_HCI_ERR_REMOTE_USER_TERM_CONN: - // Do not treat proper connection termination as an error and exit. - VerifyOrExit(!ConfigurationMgr().IsFullyProvisioned(), ); - disconReason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; - break; - case BT_HCI_ERR_LOCALHOST_TERM_CONN: - disconReason = BLE_ERROR_APP_CLOSED_CONNECTION; - break; - default: - disconReason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT; - break; - } - HandleConnectionError(connEvent->BtConn, disconReason); - } - -exit: - // Unref bt_conn before scheduling DriveBLEState. - bt_conn_unref(connEvent->BtConn); - - ChipLogProgress(DeviceLayer, "Current number of connections: %u/%u", NumConnections(), CONFIG_BT_MAX_CONN); - - ChipDeviceEvent disconnectEvent; - disconnectEvent.Type = DeviceEventType::kCHIPoBLEConnectionClosed; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&disconnectEvent)); - - // Force a reconfiguration of advertising in case we switched to non-connectable mode when - // the BLE connection was established. - mFlags.Set(Flags::kAdvertisingRefreshNeeded); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::HandleTXCharCCCDWrite(const ChipDeviceEvent * event) -{ - const BleCCCWriteEventType * writeEvent = &event->Platform.BleCCCWriteEvent; - - ChipLogDetail(DeviceLayer, "ConnId: 0x%02x, New CCCD value: 0x%04x", bt_conn_index(writeEvent->BtConn), writeEvent->Value); - - // If the client has requested to enable indications and if it is not yet subscribed - if (writeEvent->Value == BT_GATT_CCC_INDICATE && SetSubscribed(writeEvent->BtConn)) - { - // Alert the BLE layer that CHIPoBLE "subscribe" has been received and increment the bt_conn reference counter. - HandleSubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); - - ChipLogProgress(DeviceLayer, "CHIPoBLE connection established (ConnId: 0x%02x, GATT MTU: %u)", - bt_conn_index(writeEvent->BtConn), GetMTU(writeEvent->BtConn)); - - // Post a CHIPoBLEConnectionEstablished event to the DeviceLayer and the application. - { - ChipDeviceEvent conEstEvent; - conEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; - ReturnErrorOnFailure(PlatformMgr().PostEvent(&conEstEvent)); - } - } - else - { - if (UnsetSubscribed(writeEvent->BtConn)) - { - HandleUnsubscribeReceived(writeEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); - } - } - - bt_conn_unref(writeEvent->BtConn); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::HandleRXCharWrite(const ChipDeviceEvent * event) -{ - const BleC1WriteEventType * c1WriteEvent = &event->Platform.BleC1WriteEvent; - - ChipLogDetail(DeviceLayer, "Write request received for CHIPoBLE RX characteristic (ConnId 0x%02x)", - bt_conn_index(c1WriteEvent->BtConn)); - - HandleWriteReceived(c1WriteEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_RX, - PacketBufferHandle::Adopt(c1WriteEvent->Data)); - bt_conn_unref(c1WriteEvent->BtConn); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::HandleTXCharComplete(const ChipDeviceEvent * event) -{ - const BleC2IndDoneEventType * c2IndDoneEvent = &event->Platform.BleC2IndDoneEvent; - - ChipLogDetail(DeviceLayer, "Indication for CHIPoBLE TX characteristic done (ConnId 0x%02x, result 0x%02x)", - bt_conn_index(c2IndDoneEvent->BtConn), c2IndDoneEvent->Result); - - // Signal the BLE Layer that the outstanding indication is complete. - HandleIndicationConfirmation(c2IndDoneEvent->BtConn, &CHIP_BLE_SVC_ID, &chipUUID_CHIPoBLEChar_TX); - bt_conn_unref(c2IndDoneEvent->BtConn); - - return CHIP_NO_ERROR; -} - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -CHIP_ERROR BLEManagerImpl::PrepareC3CharData() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - BitFlags additionalDataFields; - AdditionalDataPayloadGeneratorParams additionalDataPayloadParams; - -#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) - uint8_t rotatingDeviceIdUniqueId[ConfigurationManager::kRotatingDeviceIDUniqueIDLength] = {}; - MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId); - - err = DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan); - SuccessOrExit(err); - err = ConfigurationMgr().GetLifetimeCounter(additionalDataPayloadParams.rotatingDeviceIdLifetimeCounter); - SuccessOrExit(err); - additionalDataPayloadParams.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan; - additionalDataFields.Set(AdditionalDataFields::RotatingDeviceId); -#endif /* CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) */ - - err = AdditionalDataPayloadGenerator().generateAdditionalDataPayload(additionalDataPayloadParams, c3CharDataBufferHandle, - additionalDataFields); - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Failed to generate TLV encoded Additional Data (%s)", __func__); - } - - return err; -} -#endif - -void BLEManagerImpl::HandleBLEAdvertisementIntervalChange(System::Layer * layer, void * param) -{ - BLEMgr().SetAdvertisingMode(BLEAdvertisingMode::kSlowAdvertising); - ChipLogProgress(DeviceLayer, "CHIPoBLE advertising mode changed to slow"); -} - -void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - switch (event->Type) - { - case DeviceEventType::kPlatformZephyrBleConnected: - err = HandleGAPConnect(event); - break; - - case DeviceEventType::kPlatformZephyrBleDisconnected: - err = HandleGAPDisconnect(event); - break; - - case DeviceEventType::kPlatformZephyrBleCCCWrite: - err = HandleTXCharCCCDWrite(event); - break; - - case DeviceEventType::kPlatformZephyrBleC1WriteEvent: - err = HandleRXCharWrite(event); - break; - - case DeviceEventType::kPlatformZephyrBleC2IndDoneEvent: - err = HandleTXCharComplete(event); - break; - - default: - break; - } - - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %" CHIP_ERROR_FORMAT, err.Format()); - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; - PlatformMgr().ScheduleWork(DriveBLEState, 0); - } -} - -uint16_t BLEManagerImpl::_NumConnections(void) -{ - return mGAPConns; -} - -bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) -{ - ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (ConnId %02x)", bt_conn_index((bt_conn *) conId)); - return bt_conn_disconnect((bt_conn *) conId, BT_HCI_ERR_REMOTE_USER_TERM_CONN) == 0; -} - -uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const -{ - return bt_gatt_get_mtu((bt_conn *) conId); -} - -bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) -{ - ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); - return true; -} - -bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) -{ - ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); - return true; -} - -bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - int status = 0; - uint8_t index = bt_conn_index(conId); - bt_gatt_indicate_params * params = &mIndicateParams[index]; - - VerifyOrExit(IsSubscribed(conId) == true, err = CHIP_ERROR_INVALID_ARGUMENT); - - ChipLogDetail(DeviceLayer, "Sending indication for CHIPoBLE TX characteristic (ConnId %02x, len %u)", index, - pBuf->DataLength()); - - params->uuid = nullptr; - params->attr = &sChipoBleAttributes[kCHIPoBLE_CCC_AttributeIndex]; - params->func = HandleTXIndicated; - params->data = pBuf->Start(); - params->len = pBuf->DataLength(); - - status = bt_gatt_indicate(conId, params); - VerifyOrExit(status == 0, err = MapErrorZephyr(status)); - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %." CHIP_ERROR_FORMAT, err.Format()); - ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %d", status); - } - - return err == CHIP_NO_ERROR; -} - -bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf) -{ - ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); - return true; -} - -bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf) -{ - ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); - return true; -} - -bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, - const ChipBleUUID * svcId, const ChipBleUUID * charId) -{ - ChipLogError(DeviceLayer, "%s: NOT IMPLEMENTED", __PRETTY_FUNCTION__); - return true; -} - -void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) -{ - CloseConnection(conId); -} - -bool BLEManagerImpl::IsSubscribed(bt_conn * conn) -{ - return mSubscribedConns[bt_conn_index(conn)]; -} - -bool BLEManagerImpl::SetSubscribed(bt_conn * conn) -{ - uint8_t index = bt_conn_index(conn); - bool isSubscribed = mSubscribedConns[index]; - mSubscribedConns[index] = true; - - // If we were not subscribed previously, increment the reference counter of the connection. - if (!isSubscribed) - { - bt_conn_ref(conn); - } - - return !isSubscribed; -} - -bool BLEManagerImpl::UnsetSubscribed(bt_conn * conn) -{ - uint8_t index = bt_conn_index(conn); - bool isSubscribed = mSubscribedConns[index]; - mSubscribedConns[index] = false; - - // If we were subscribed previously, decrement the reference counter of the connection. - if (isSubscribed) - { - bt_conn_unref(conn); - } - - return isSubscribed; -} - -ssize_t BLEManagerImpl::HandleRXWrite(struct bt_conn * conId, const struct bt_gatt_attr * attr, const void * buf, uint16_t len, - uint16_t offset, uint8_t flags) -{ - ChipDeviceEvent event; - PacketBufferHandle packetBuf = PacketBufferHandle::NewWithData(buf, len); - - if (!packetBuf.IsNull()) - { - // Arrange to post a CHIPoBLERXWriteEvent event to the CHIP queue. - event.Type = DeviceEventType::kPlatformZephyrBleC1WriteEvent; - event.Platform.BleC1WriteEvent.BtConn = bt_conn_ref(conId); - event.Platform.BleC1WriteEvent.Data = std::move(packetBuf).UnsafeRelease(); - } - - // If we failed to allocate a buffer, post a kPlatformZephyrBleOutOfBuffersEvent event. - else - { - event.Type = DeviceEventType::kPlatformZephyrBleOutOfBuffersEvent; - } - - PlatformMgr().PostEventOrDie(&event); - - return len; -} - -bool BLEManagerImpl::HandleTXCCCWrite(struct bt_conn * conId, const struct bt_gatt_attr * attr, uint16_t value) -{ - ChipDeviceEvent event; - - if (value != BT_GATT_CCC_INDICATE && value != 0) - { - return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED); - } - - event.Type = DeviceEventType::kPlatformZephyrBleCCCWrite; - event.Platform.BleCCCWriteEvent.BtConn = bt_conn_ref(conId); - event.Platform.BleCCCWriteEvent.Value = value; - - PlatformMgr().PostEventOrDie(&event); - - return sizeof(value); -} - -void BLEManagerImpl::HandleTXIndicated(struct bt_conn * conId, IndicationAttrType, uint8_t err) -{ - ChipDeviceEvent event; - - event.Type = DeviceEventType::kPlatformZephyrBleC2IndDoneEvent; - event.Platform.BleC2IndDoneEvent.BtConn = bt_conn_ref(conId); - event.Platform.BleC2IndDoneEvent.Result = err; - - PlatformMgr().PostEventOrDie(&event); -} - -void BLEManagerImpl::HandleConnect(struct bt_conn * conId, uint8_t err) -{ - ChipDeviceEvent event; - - PlatformMgr().LockChipStack(); - - // Don't handle BLE connecting events when it is not related to CHIPoBLE - VerifyOrExit(sInstance.mFlags.Has(Flags::kChipoBleGattServiceRegister), ); - - event.Type = DeviceEventType::kPlatformZephyrBleConnected; - event.Platform.BleConnEvent.BtConn = bt_conn_ref(conId); - event.Platform.BleConnEvent.HciResult = err; - - PlatformMgr().PostEventOrDie(&event); - -exit: - PlatformMgr().UnlockChipStack(); -} - -void BLEManagerImpl::HandleDisconnect(struct bt_conn * conId, uint8_t reason) -{ - ChipDeviceEvent event; - - PlatformMgr().LockChipStack(); - - // Don't handle BLE disconnecting events when it is not related to CHIPoBLE - VerifyOrExit(sInstance.mFlags.Has(Flags::kChipoBleGattServiceRegister), ); - - event.Type = DeviceEventType::kPlatformZephyrBleDisconnected; - event.Platform.BleConnEvent.BtConn = bt_conn_ref(conId); - event.Platform.BleConnEvent.HciResult = reason; - - PlatformMgr().PostEventOrDie(&event); - -exit: - PlatformMgr().UnlockChipStack(); -} - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -ssize_t BLEManagerImpl::HandleC3Read(struct bt_conn * conId, const struct bt_gatt_attr * attr, void * buf, uint16_t len, - uint16_t offset) -{ - ChipLogDetail(DeviceLayer, "Read request received for CHIPoBLE C3 (ConnId 0x%02x)", bt_conn_index(conId)); - - if (sInstance.c3CharDataBufferHandle.IsNull()) - { - return 0; - } - - return bt_gatt_attr_read(conId, attr, buf, len, offset, sInstance.c3CharDataBufferHandle->Start(), - sInstance.c3CharDataBufferHandle->DataLength()); -} -#endif - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/bouffalolab/BL702/BLEManagerImpl.h b/src/platform/bouffalolab/BL702/BLEManagerImpl.h deleted file mode 100644 index 0f9ff7666a1c1e..00000000000000 --- a/src/platform/bouffalolab/BL702/BLEManagerImpl.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - -#include -#include -#include - -#include - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -using namespace chip::Ble; - -/** - * Concrete implementation of the BLEManager singleton object for the BL702 platform. - */ -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. - using IndicationAttrType = - std::conditional_t::value, - bt_gatt_indicate_params *, const bt_gatt_attr *>; - CHIP_ERROR _Init(void); - void _Shutdown() {} - 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 ChipBleUUID * svcId, const ChipBleUUID * charId); - bool UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId); - bool CloseConnection(BLE_CONNECTION_OBJECT conId); - uint16_t GetMTU(BLE_CONNECTION_OBJECT conId) const; - bool SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf); - bool SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf); - bool SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf); - bool SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const ChipBleUUID * svcId, - const ChipBleUUID * charId); - - // ===== Members that implement virtual methods on BleApplicationDelegate. - - void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId); - - // ===== Private members reserved for use by this class only. - - enum class Flags : uint8_t - { - kAsyncInitCompleted = 0x0001, /**< One-time asynchronous initialization actions have been performed. */ - kAdvertisingEnabled = 0x0002, /**< The application has enabled CHIPoBLE advertising. */ - kFastAdvertisingEnabled = 0x0004, /**< The application has enabled fast advertising. */ - kAdvertising = 0x0008, /**< The system is currently CHIPoBLE advertising. */ - kAdvertisingRefreshNeeded = - 0x0010, /**< The advertising state/configuration has changed, but the SoftDevice has yet to be updated. */ - kChipoBleGattServiceRegister = 0x0020, /**< The system has currently CHIPoBLE GATT service registered. */ - }; - - struct ServiceData; - - BitFlags mFlags; - uint16_t mGAPConns; - CHIPoBLEServiceMode mServiceMode; - bool mSubscribedConns[CONFIG_BT_MAX_CONN]; - bt_gatt_indicate_params mIndicateParams[CONFIG_BT_MAX_CONN]; - bt_conn_cb mConnCallbacks; -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - PacketBufferHandle c3CharDataBufferHandle; -#endif - - void DriveBLEState(void); - CHIP_ERROR ConfigureAdvertising(void); - CHIP_ERROR StartAdvertising(void); - CHIP_ERROR StopAdvertising(void); - CHIP_ERROR HandleGAPConnect(const ChipDeviceEvent * event); - CHIP_ERROR HandleGAPDisconnect(const ChipDeviceEvent * event); - CHIP_ERROR HandleRXCharWrite(const ChipDeviceEvent * event); - CHIP_ERROR HandleTXCharCCCDWrite(const ChipDeviceEvent * event); - CHIP_ERROR HandleTXCharComplete(const ChipDeviceEvent * event); -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - CHIP_ERROR PrepareC3CharData(); -#endif - bool IsSubscribed(bt_conn * conn); - bool SetSubscribed(bt_conn * conn); - bool UnsetSubscribed(bt_conn * conn); - uint32_t GetAdvertisingInterval(); - - static void DriveBLEState(intptr_t arg); - - // Below callbacks run from the system workqueue context and have a limited stack capacity. - static void HandleTXIndicated(bt_conn * conn, IndicationAttrType attr, uint8_t err); - static void HandleConnect(bt_conn * conn, uint8_t err); - static void HandleDisconnect(bt_conn * conn, uint8_t reason); - static void HandleBLEAdvertisementIntervalChange(System::Layer * layer, void * param); - - // ===== Members for internal use by the following friends. - - friend BLEManager & BLEMgr(void); - friend BLEManagerImpl & BLEMgrImpl(void); - - static BLEManagerImpl sInstance; - -public: - // Below callbacks are public in order to be visible from the global scope. - static ssize_t HandleRXWrite(bt_conn * conn, const bt_gatt_attr * attr, const void * buf, uint16_t len, uint16_t offset, - uint8_t flags); - static bool HandleTXCCCWrite(bt_conn * conn, const bt_gatt_attr * attr, uint16_t value); - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - static ssize_t HandleC3Read(struct bt_conn * conn, const struct bt_gatt_attr * attr, void * buf, uint16_t len, uint16_t offset); -#endif -}; - -/** - * 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 BL702 platform. - */ -inline BLEManagerImpl & BLEMgrImpl(void) -{ - return BLEManagerImpl::sInstance; -} - -inline BleLayer * BLEManagerImpl::_GetBleLayer() -{ - return this; -} - -inline bool BLEManagerImpl::_IsAdvertisingEnabled(void) -{ - return mFlags.Has(Flags::kAdvertisingEnabled); -} - -inline bool BLEManagerImpl::_IsAdvertising(void) -{ - return mFlags.Has(Flags::kAdvertising); -} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip - -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/bouffalolab/BL702/BUILD.gn b/src/platform/bouffalolab/BL702/BUILD.gn index ae941605978012..dd0279175bfd50 100644 --- a/src/platform/bouffalolab/BL702/BUILD.gn +++ b/src/platform/bouffalolab/BL702/BUILD.gn @@ -25,60 +25,53 @@ if (chip_enable_openthread) { static_library("BL702") { sources = [ - "../../FreeRTOS/SystemTimeSupport.cpp", - "../../SingletonConfigurationManager.cpp", - "CHIPDevicePlatformConfig.h", - "CHIPDevicePlatformEvent.h", - "CHIPmemory.cpp", - "ConfigurationManagerImpl.cpp", - "ConfigurationManagerImpl.h", - "ConnectivityManagerImpl.cpp", - "ConnectivityManagerImpl.h", "DiagnosticDataProviderImpl.cpp", - "DiagnosticDataProviderImpl.h", - "InetPlatformConfig.h", - "KeyValueStoreManagerImpl.cpp", - "KeyValueStoreManagerImpl.h", - "Logging.cpp", "PlatformManagerImpl.cpp", - "PlatformManagerImpl.h", - "SystemPlatformConfig.h", - "bl702Config.cpp", - "bl702Config.h", ] - deps = [] + common_sources = [ + "../../FreeRTOS/SystemTimeSupport.cpp", + "../../SingletonConfigurationManager.cpp", + "../common/BLConfig.cpp", + "../common/ConfigurationManagerImpl.cpp", + "../common/ConnectivityManagerImpl.cpp", + "../common/DiagnosticDataProviderImpl.cpp", + "../common/KeyValueStoreManagerImpl.cpp", + "../common/Logging.cpp", + "../common/PlatformManagerImpl.cpp", + + # "${chip_root}/src/credentials/CHIPCert.h", + # "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", - public_deps = [ - "${chip_root}/src/crypto", - "${chip_root}/src/platform:platform_base", + # "../common/FactoryDataProvider.cpp", + # "../common/FactoryDataProvider.h", ] if (chip_enable_ota_requestor) { sources += [ - "OTAImageProcessorImpl.cpp", - "OTAImageProcessorImpl.h", + "../common/OTAImageProcessorImpl.cpp", + "../common/OTAImageProcessorImpl.h", ] } if (chip_enable_ble) { sources += [ - "BLEManagerImpl.cpp", - "BLEManagerImpl.h", + "../common/BLEManagerImpl.cpp", + "../common/BLEManagerImpl.h", ] } + sources += common_sources if (chip_enable_openthread) { # needed for MTD/FTD import("//build_overrides/bouffalolab_iot_sdk.gni") import("${bouffalolab_iot_sdk_build_root}/bl702/bl_iot_sdk.gni") - public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl702:bl_iot_sdk" ] + deps = [ "${bouffalolab_iot_sdk_build_root}/bl702:bl_iot_sdk" ] sources += [ "../../OpenThread/OpenThreadUtils.cpp", "ThreadStackManagerImpl.cpp", - "ThreadStackManagerImpl.h", ] if (chip_mdns == "platform") { @@ -90,4 +83,6 @@ static_library("BL702") { deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] } } + + public_deps = [ "${chip_root}/src/platform:platform_base" ] } diff --git a/src/platform/bouffalolab/BL702/CHIPPlatformConfig.h b/src/platform/bouffalolab/BL702/CHIPPlatformConfig.h deleted file mode 100644 index b5815d686157b8..00000000000000 --- a/src/platform/bouffalolab/BL702/CHIPPlatformConfig.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -// ==================== General Platform Adaptations ==================== - -#define ChipDie() assert() - -#define CHIP_CONFIG_PERSISTED_STORAGE_KEY_TYPE uint16_t -#define CHIP_CONFIG_PERSISTED_STORAGE_ENC_MSG_CNTR_ID 1 -#define CHIP_CONFIG_PERSISTED_STORAGE_MAX_KEY_LENGTH 2 - -#define CHIP_CONFIG_LIFETIIME_PERSISTED_COUNTER_KEY 0x01 -#define CHIP_CONFIG_PERSISTED_STORAGE_KEY_GLOBAL_MESSAGE_COUNTER 0x2 - -// ==================== Security Adaptations ==================== - -// This platform uses mbedtls, but these defines don't seem to be used in source -#define CHIP_CONFIG_USE_OPENSSL_ECC 0 -#define CHIP_CONFIG_USE_MICRO_ECC 1 - -#define CHIP_CONFIG_HASH_IMPLEMENTATION_OPENSSL 0 -#define CHIP_CONFIG_HASH_IMPLEMENTATION_MINCRYPT 0 -#define CHIP_CONFIG_HASH_IMPLEMENTATION_MBEDTLS 1 -#define CHIP_CONFIG_HASH_IMPLEMENTATION_PLATFORM 0 - -//#define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(bl_sha_ctx_t) -#define CHIP_CONFIG_SHA256_CONTEXT_SIZE ((1 + 5 + 18 + 16 + 16) * sizeof(unsigned int)) - -#define CHIP_CONFIG_AES_IMPLEMENTATION_OPENSSL 0 -#define CHIP_CONFIG_AES_IMPLEMENTATION_AESNI 0 -#define CHIP_CONFIG_AES_IMPLEMENTATION_MBEDTLS 1 -#define CHIP_CONFIG_AES_IMPLEMENTATION_PLATFORM 0 - -#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 8 -#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_MAX_ACTIVE_CHANNELS -#define CHIP_CONFIG_MAX_ACTIVE_CHANNELS 8 -#endif // CHIP_CONFIG_MAX_ACTIVE_CHANNELS - -#ifndef CHIP_CONFIG_MAX_CHANNEL_HANDLES -#define CHIP_CONFIG_MAX_CHANNEL_HANDLES 16 -#endif // CHIP_CONFIG_MAX_CHANNEL_HANDLES - -#ifndef CHIP_CONFIG_RMP_TIMER_DEFAULT_PERIOD_SHIFT -#define CHIP_CONFIG_RMP_TIMER_DEFAULT_PERIOD_SHIFT 6 -#endif // CHIP_CONFIG_RMP_TIMER_DEFAULT_PERIOD_SHIFT - -#ifndef CHIP_LOG_FILTERING -#define CHIP_LOG_FILTERING 0 -#endif // CHIP_LOG_FILTERING - -#ifndef CHIP_CONFIG_MAX_INTERFACES -#define CHIP_CONFIG_MAX_INTERFACES 4 -#endif // CHIP_CONFIG_MAX_INTERFACES - -#ifndef CHIP_CONFIG_MAX_LOCAL_ADDR_UDP_ENDPOINTS -#define CHIP_CONFIG_MAX_LOCAL_ADDR_UDP_ENDPOINTS 4 -#endif // CHIP_CONFIG_MAX_LOCAL_ADDR_UDP_ENDPOINTS - -#ifndef CHIP_CONFIG_MAX_FABRICS -#define CHIP_CONFIG_MAX_FABRICS 5 -#endif - -// ==================== 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 - -#ifndef CHIP_CONFIG_FREERTOS_USE_STATIC_TASK -#define CHIP_CONFIG_FREERTOS_USE_STATIC_TASK 1 -#endif - -#ifndef CHIP_CONFIG_FREERTOS_USE_STATIC_QUEUE -#define CHIP_CONFIG_FREERTOS_USE_STATIC_QUEUE 1 -#endif diff --git a/src/platform/bouffalolab/BL702/CHIPmemory.cpp b/src/platform/bouffalolab/BL702/CHIPmemory.cpp deleted file mode 100644 index 5438016ad53d0f..00000000000000 --- a/src/platform/bouffalolab/BL702/CHIPmemory.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include - -#ifndef NDEBUG -#include -#include -#endif - -#if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC -#include -#include -#endif // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC - -#if CHIP_CONFIG_MEMORY_MGMT_PLATFORM - -#include "FreeRTOS.h" -#include "task.h" - -namespace chip { -namespace Platform { - -#ifdef NDEBUG - -#define VERIFY_INITIALIZED() -#define VERIFY_POINTER(p) - -#else - -#define VERIFY_INITIALIZED() VerifyInitialized(__func__) - -static std::atomic_int memoryInitialized{ 0 }; - -static void VerifyInitialized(const char * func) -{ - if (!memoryInitialized) - { - fprintf(stderr, "ABORT: chip::Platform::%s() called before chip::Platform::MemoryInit()\n", func); - abort(); - } -} - -#define VERIFY_POINTER(p) \ - do \ - if (((p) != nullptr) && (MemoryDebugCheckPointer((p)) == false)) \ - { \ - fprintf(stderr, "ABORT: chip::Platform::%s() found corruption on %p\n", __func__, (p)); \ - abort(); \ - } \ - while (0) - -#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 -#if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC - dmalloc_shutdown(); -#endif // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC -} - -void * MemoryAlloc(size_t size) -{ - VERIFY_INITIALIZED(); - - return malloc(size); -} - -void * MemoryCalloc(size_t num, size_t size) -{ - VERIFY_INITIALIZED(); - - return pvPortCallocPsram(num, size); -} - -void * MemoryRealloc(void * p, size_t size) -{ - VERIFY_INITIALIZED(); - VERIFY_POINTER(p); - - return realloc(p, size); -} - -void MemoryFree(void * p) -{ - VERIFY_INITIALIZED(); - VERIFY_POINTER(p); - - free(p); -} - -bool MemoryInternalCheckPointer(const void * p, size_t min_size) -{ -#if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC - return CanCastTo(min_size) && (p != nullptr) && - (dmalloc_verify_pnt(__FILE__, __LINE__, __func__, p, 1, static_cast(min_size)) == MALLOC_VERIFY_NOERROR); -#else // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC - return (p != nullptr); -#endif // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC -} - -} // namespace Platform -} // namespace chip - -#endif // CHIP_CONFIG_MEMORY_MGMT_MALLOC diff --git a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.h b/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.h deleted file mode 100644 index 06774161b8c3f2..00000000000000 --- a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include -#if INET_CONFIG_ENABLE_TCP_ENDPOINT -#include -#endif -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include -#else -#include -#endif -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include -#else -#include -#endif -#include - -namespace chip { -namespace DeviceLayer { - -/** - * Concrete implementation of the ConnectivityManager singleton object for the CC13X2_26X2 platforms. - */ -class ConnectivityManagerImpl final : public ConnectivityManager, - public Internal::GenericConnectivityManagerImpl, - public Internal::GenericConnectivityManagerImpl_UDP, -#if INET_CONFIG_ENABLE_TCP_ENDPOINT - public Internal::GenericConnectivityManagerImpl_TCP, -#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 - public Internal::GenericConnectivityManagerImpl_NoWiFi -{ - // Allow the ConnectivityManager interface class to delegate method calls to - // the implementation methods provided by this class. - friend class ConnectivityManager; - -#if CHIP_DEVICE_CONFIG_ENABLE_WIFI -public: - static WiFiStationState mWiFiStationState; - static void GetWiFiMacAddress(uint8_t *); -#endif - -private: - // ===== Members that implement the ConnectivityManager abstract interface. - -#if CHIP_DEVICE_CONFIG_ENABLE_WIFI - bool _IsWiFiStationConnected(void); - bool _IsWiFiStationEnabled(void); - ConnectivityManager::WiFiStationMode _GetWiFiStationMode(void); - - friend void DriveState(int arg); - void NetworkChanged(void); - bool _IsWiFiStationProvisioned(void); - void _ClearWiFiStationProvision(void); -#endif - - CHIP_ERROR _Init(void); - void _OnPlatformEvent(const ChipDeviceEvent * event); - - // ===== Members for internal use by the following friends. - - friend ConnectivityManager & ConnectivityMgr(void); - friend ConnectivityManagerImpl & ConnectivityMgrImpl(void); - - static ConnectivityManagerImpl sInstance; -}; - -/** - * 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 BL702 platform - */ -inline ConnectivityManagerImpl & ConnectivityMgrImpl(void) -{ - return ConnectivityManagerImpl::sInstance; -} - -#if CHIP_DEVICE_CONFIG_ENABLE_WIFI -inline bool ConnectivityManagerImpl::_IsWiFiStationConnected(void) -{ - return mWiFiStationState == kWiFiStationState_Connected; -} - -inline bool ConnectivityManagerImpl::_IsWiFiStationEnabled(void) -{ - return true; -} - -inline ConnectivityManager::WiFiStationMode ConnectivityManagerImpl::_GetWiFiStationMode(void) -{ - return kWiFiStationMode_Enabled; -} - -#endif - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp index acdf61e27caa26..62fe129c0a9685 100644 --- a/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp +++ b/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp @@ -15,229 +15,40 @@ * limitations under the License. */ -#include -#include - #include -#include - -#include - -#include - -using namespace ::chip::app::Clusters::GeneralDiagnostics; +#include +#include +extern "C" { +#include +} namespace chip { namespace DeviceLayer { -extern "C" size_t get_heap_size(void); -extern "C" size_t get_heap3_size(void); - -DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() -{ - static DiagnosticDataProviderImpl sInstance; - return sInstance; -} - -/* - * The following Heap stats are compiled values done by the FreeRTOS Heap5 implementation. - * It keeps track of the number of calls to allocate and free memory as well as the - * number of free bytes remaining, but says nothing about fragmentation. - */ -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) -{ - /** for BL706 with PSRAM, just get SRAM heap size which is more critical for firmware execution **/ - -#ifdef CFG_USE_PSRAM - size_t freeHeapSize = xPortGetFreeHeapSize() + xPortGetFreeHeapSizePsram(); -#else - size_t freeHeapSize = xPortGetFreeHeapSize(); -#endif - currentHeapFree = static_cast(freeHeapSize); - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) -{ - // Calculate the Heap used based on Total heap - Free heap - -#ifdef CFG_USE_PSRAM - int64_t heapUsed = (get_heap_size() + get_heap3_size() - xPortGetFreeHeapSize() - xPortGetFreeHeapSizePsram()); -#else - size_t freeHeapSize = xPortGetFreeHeapSize(); -#endif - - // Something went wrong, this should not happen - VerifyOrReturnError(heapUsed >= 0, CHIP_ERROR_INVALID_INTEGER_VALUE); - currentHeapUsed = static_cast(heapUsed); - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) -{ - // FreeRTOS records the lowest amount of available heap during runtime - // currentHeapHighWatermark wants the highest heap usage point so we calculate it here - -#ifdef CFG_USE_PSRAM - int64_t HighestHeapUsageRecorded = - (get_heap_size() + get_heap3_size() - xPortGetMinimumEverFreeHeapSize() - xPortGetMinimumEverFreeHeapSizePsram()); -#else - size_t freeHeapSize = xPortGetFreeHeapSize(); - int64_t HighestHeapUsageRecorded = (get_heap_size() - xPortGetMinimumEverFreeHeapSize()); -#endif - - // Something went wrong, this should not happen - VerifyOrReturnError(HighestHeapUsageRecorded >= 0, CHIP_ERROR_INVALID_INTEGER_VALUE); - currentHeapHighWatermark = static_cast(HighestHeapUsageRecorded); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetThreadMetrics(ThreadMetrics ** threadMetricsOut) +CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason) { - /* Obtain all available task information */ - TaskStatus_t * taskStatusArray; - ThreadMetrics * head = nullptr; - uint32_t arraySize, x, dummy; - - arraySize = uxTaskGetNumberOfTasks(); + BL_RST_REASON_E bootCause = bl_sys_rstinfo_get(); - taskStatusArray = static_cast(chip::Platform::MemoryCalloc(arraySize, sizeof(TaskStatus_t))); - - if (taskStatusArray != NULL) + if (BL_RST_POR == bootCause) { - /* Generate raw status information about each task. */ - arraySize = uxTaskGetSystemState(taskStatusArray, arraySize, &dummy); - /* For each populated position in the taskStatusArray array, - format the raw data as human readable ASCII data. */ - - for (x = 0; x < arraySize; x++) - { - ThreadMetrics * thread = new ThreadMetrics(); - if (thread) - { - Platform::CopyString(thread->NameBuf, taskStatusArray[x].pcTaskName); - thread->name.Emplace(CharSpan::fromCharString(thread->NameBuf)); - thread->id = taskStatusArray[x].xTaskNumber; - thread->stackFreeMinimum.Emplace(taskStatusArray[x].usStackHighWaterMark); - - /* Unsupported metrics */ - // thread->stackSize - // thread->stackFreeCurrent - - thread->Next = head; - head = thread; - } - } - - *threadMetricsOut = head; - /* The array is no longer needed, free the memory it consumes. */ - chip::Platform::MemoryFree(taskStatusArray); + bootReason = BootReasonType::kPowerOnReboot; } - - return CHIP_NO_ERROR; -} - -void DiagnosticDataProviderImpl::ReleaseThreadMetrics(ThreadMetrics * threadMetrics) -{ - while (threadMetrics) + else if (BL_RST_BOR == bootCause) { - ThreadMetrics * del = threadMetrics; - threadMetrics = threadMetrics->Next; - delete del; + bootReason = BootReasonType::kBrownOutReset; } -} - -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::GetBootReason(BootReasonType & bootReason) -{ - uint32_t reason = 0; - CHIP_ERROR err = ConfigurationMgr().GetBootReason(reason); - - if (err == CHIP_NO_ERROR) + else if (BL_RST_WDT == bootCause) { - VerifyOrReturnError(reason <= UINT8_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE); - bootReason = static_cast(reason); + bootReason = BootReasonType::kHardwareWatchdogReset; } - - 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) + else if (BL_RST_SOFTWARE == bootCause) { - upTime = std::chrono::duration_cast(currentTime - startTime).count(); - return CHIP_NO_ERROR; + bootReason = BootReasonType::kSoftwareReset; } - - return CHIP_ERROR_INVALID_TIME; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) -{ - uint64_t upTime = 0; - - if (GetUpTime(upTime) == CHIP_NO_ERROR) + else { - 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; - } + bootReason = BootReasonType::kUnspecified; } - - return CHIP_ERROR_INVALID_TIME; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetActiveHardwareFaults(GeneralFaults & hardwareFaults) -{ -#if CHIP_CONFIG_TEST - ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kRadio))); - ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kSensor))); - ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kPowerSource))); - ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kUserInterfaceFault))); -#endif - - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetActiveRadioFaults(GeneralFaults & radioFaults) -{ -#if CHIP_CONFIG_TEST - ReturnErrorOnFailure(radioFaults.add(EMBER_ZCL_RADIO_FAULT_ENUM_THREAD_FAULT)); - ReturnErrorOnFailure(radioFaults.add(EMBER_ZCL_RADIO_FAULT_ENUM_BLE_FAULT)); -#endif - - return CHIP_NO_ERROR; -} - -CHIP_ERROR DiagnosticDataProviderImpl::GetActiveNetworkFaults(GeneralFaults & networkFaults) -{ -#if CHIP_CONFIG_TEST - ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kHardwareFailure))); - ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kNetworkJammed))); - ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kConnectionFailed))); -#endif - return CHIP_NO_ERROR; } @@ -245,23 +56,18 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** { NetworkInterface * ifp = new NetworkInterface(); -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD - const char * threadNetworkName = otThreadGetNetworkName(ThreadStackMgrImpl().OTInstance()); ifp->name = Span(threadNetworkName, strlen(threadNetworkName)); ifp->isOperational = true; ifp->offPremiseServicesReachableIPv4.SetNull(); ifp->offPremiseServicesReachableIPv6.SetNull(); - ifp->type = InterfaceTypeEnum::EMBER_ZCL_INTERFACE_TYPE_ENUM_THREAD; + ifp->type = EMBER_ZCL_INTERFACE_TYPE_ENUM_THREAD; uint8_t macBuffer[ConfigurationManager::kPrimaryMACAddressLength]; ConfigurationMgr().GetPrimary802154MACAddress(macBuffer); ifp->hardwareAddress = ByteSpan(macBuffer, ConfigurationManager::kPrimaryMACAddressLength); -#else - /* TODO */ -#endif - *netifpp = ifp; + return CHIP_NO_ERROR; } @@ -275,10 +81,5 @@ void DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * net } } -DiagnosticDataProvider & GetDiagnosticDataProviderImpl() -{ - return DiagnosticDataProviderImpl::GetDefaultInstance(); -} - } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.h b/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.h deleted file mode 100644 index 6411b8e4cbd501..00000000000000 --- a/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -#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 GetThreadMetrics(ThreadMetrics ** threadMetricsOut) override; - void ReleaseThreadMetrics(ThreadMetrics * threadMetrics) override; - CHIP_ERROR GetRebootCount(uint16_t & rebootCount) override; - CHIP_ERROR GetBootReason(BootReasonType & bootReason) override; - CHIP_ERROR GetUpTime(uint64_t & upTime) override; - CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours) override; - CHIP_ERROR GetActiveHardwareFaults(GeneralFaults & hardwareFaults) override; - CHIP_ERROR GetActiveRadioFaults(GeneralFaults & radioFaults) override; - CHIP_ERROR GetActiveNetworkFaults(GeneralFaults & networkFaults) override; - CHIP_ERROR GetNetworkInterfaces(NetworkInterface ** netifpp) override; - void ReleaseNetworkInterfaces(NetworkInterface * netifp) override; -}; - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.cpp b/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.cpp deleted file mode 100644 index 1e49c74e4f9eb0..00000000000000 --- a/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.cpp +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "OTAImageProcessorImpl.h" -extern "C" { -#include -#include -} - -using namespace chip::System; - -namespace chip { - -CHIP_ERROR OTAImageProcessorImpl::PrepareDownload() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandlePrepareDownload, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::Finalize() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandleFinalize, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::Apply() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandleApply, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::Abort() -{ - DeviceLayer::PlatformMgr().ScheduleWork(HandleAbort, reinterpret_cast(this)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block) -{ - if ((nullptr == block.data()) || block.empty()) - { - return CHIP_ERROR_INVALID_ARGUMENT; - } - - // Store block data for HandleProcessBlock to access - CHIP_ERROR err = SetBlock(block); - if (err != CHIP_NO_ERROR) - { - ChipLogError(SoftwareUpdate, "Cannot set block data: %" CHIP_ERROR_FORMAT, err.Format()); - } - - 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; - } - - imageProcessor->mParams.downloadedBytes = 0; - imageProcessor->mParams.totalFileBytes = 0; - imageProcessor->mHeaderParser.Init(); - - imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR); -} - -void OTAImageProcessorImpl::HandleFinalize(intptr_t context) -{ - auto * imageProcessor = reinterpret_cast(context); - - if (imageProcessor == nullptr) - { - return; - } - - if (hosal_ota_check() < 0) - { - imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); - ChipLogProgress(SoftwareUpdate, "OTA image verification error"); - } - else - { - ChipLogProgress(SoftwareUpdate, "OTA image downloaded"); - } - - imageProcessor->ReleaseBlock(); -} - -void OTAImageProcessorImpl::HandleApply(intptr_t context) -{ - auto * imageProcessor = reinterpret_cast(context); - - if (imageProcessor == nullptr) - { - return; - } - - hosal_ota_apply(0); - DeviceLayer::SystemLayer().StartTimer( - System::Clock::Seconds32(OTA_AUTO_REBOOT_DELAY), - [](Layer *, void *) { - ChipLogProgress(SoftwareUpdate, "Rebooting..."); - hal_reboot(); - }, - nullptr); -} - -void OTAImageProcessorImpl::HandleAbort(intptr_t context) -{ - auto * imageProcessor = reinterpret_cast(context); - if (imageProcessor == nullptr) - { - return; - } - - hosal_ota_abort(); - - imageProcessor->ReleaseBlock(); -} - -void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) -{ - OTAImageHeader header; - CHIP_ERROR error; - 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; - } - - ByteSpan block = imageProcessor->mBlock; - if (imageProcessor->mHeaderParser.IsInitialized()) - { - - error = imageProcessor->mHeaderParser.AccumulateAndDecode(block, header); - if (CHIP_ERROR_BUFFER_TOO_SMALL == error) - { - return; - } - else if (CHIP_NO_ERROR != error) - { - ChipLogError(SoftwareUpdate, "Matter image header parser error %s", chip::ErrorStr(error)); - imageProcessor->mDownloader->EndDownload(CHIP_ERROR_INVALID_FILE_IDENTIFIER); - imageProcessor->mHeaderParser.Clear(); - return; - } - - ChipLogProgress(SoftwareUpdate, "Image Header software version: %ld payload size: %lu", header.mSoftwareVersion, - (long unsigned int) header.mPayloadSize); - imageProcessor->mParams.totalFileBytes = header.mPayloadSize; - imageProcessor->mHeaderParser.Clear(); - - if (hosal_ota_start(header.mPayloadSize) < 0) - { - imageProcessor->mDownloader->EndDownload(CHIP_ERROR_OPEN_FAILED); - return; - } - } - - if (imageProcessor->mParams.totalFileBytes) - { - if (hosal_ota_update(imageProcessor->mParams.totalFileBytes, imageProcessor->mParams.downloadedBytes, - (uint8_t *) block.data(), block.size()) < 0) - { - imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); - return; - } - imageProcessor->mParams.downloadedBytes += block.size(); - } - - imageProcessor->mDownloader->FetchNextData(); -} - -// Store block data for HandleProcessBlock to access -CHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block) -{ - if ((block.data() == nullptr) || block.empty()) - { - return CHIP_NO_ERROR; - } - - // Allocate memory for block data if we don't have enough already - if (mBlock.size() < block.size()) - { - ReleaseBlock(); - - 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/bouffalolab/BL702/OTAImageProcessorImpl.h b/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.h deleted file mode 100644 index 4bae9152f8f48c..00000000000000 --- a/src/platform/bouffalolab/BL702/OTAImageProcessorImpl.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include -#include - -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; - bool IsFirstImageRun() override { return false; } - CHIP_ERROR ConfirmCurrentImage() override { return CHIP_NO_ERROR; } - - 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 HandleApply(intptr_t context); - static void HandleAbort(intptr_t context); - static void HandleProcessBlock(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; - OTAImageHeaderParser mHeaderParser; -}; - -} // namespace chip diff --git a/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp index 3f7e1399fe722b..b195abce5fb3b9 100644 --- a/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp @@ -15,13 +15,12 @@ * limitations under the License. */ -/* this file behaves like a config.h, comes first */ #include #include #include #include -#include +#include #include #include @@ -57,7 +56,7 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) otRadio_opt_t opt; // Initialize the configuration system. - err = Internal::BL702Config::Init(); + err = Internal::BLConfig::Init(); SuccessOrExit(err); opt.byte = 0; @@ -88,6 +87,29 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) exit: return err; } +void 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"); + } + + Internal::GenericPlatformManagerImpl_FreeRTOS::_Shutdown(); +} } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/PlatformManagerImpl.h b/src/platform/bouffalolab/BL702/PlatformManagerImpl.h deleted file mode 100644 index 9dd8e14c87d293..00000000000000 --- a/src/platform/bouffalolab/BL702/PlatformManagerImpl.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2022 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -namespace chip { -namespace DeviceLayer { - -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 - -protected: - void _RunEventLoop(void); - -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); - - // ===== Members for internal use by the following friends. - friend PlatformManager & PlatformMgr(void); - friend PlatformManagerImpl & PlatformMgrImpl(void); - friend class Internal::BLEManagerImpl; - - static PlatformManagerImpl sInstance; - System::Clock::Timestamp mStartTime = System::Clock::kZero; - - using Internal::GenericPlatformManagerImpl_FreeRTOS::PostEventFromISR; - - // ===== Methods that implement the PlatformManager Implementation dedicated. - CHIP_ERROR PlatformInit(void); -}; - -/** - * 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 Baffalolab BL702 SoC. - */ -inline PlatformManagerImpl & PlatformMgrImpl(void) -{ - return PlatformManagerImpl::sInstance; -} - -inline void PlatformManagerImpl::_RunEventLoop(void) -{ - PlatformInit(); - Internal::GenericPlatformManagerImpl_FreeRTOS::_RunEventLoop(); -} - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/bouffalolab/BL702/args.gni b/src/platform/bouffalolab/BL702/args.gni index eca543ed30dc06..47a03c6f7bd268 100644 --- a/src/platform/bouffalolab/BL702/args.gni +++ b/src/platform/bouffalolab/BL702/args.gni @@ -29,8 +29,6 @@ chip_inet_config_enable_tcp_endpoint = false chip_build_tests = false -chip_config_memory_management = "platform" - openthread_external_mbedtls = mbedtls_target openthread_project_core_config_file = "bl702-openthread-core-bl-config.h" openthread_core_config_platform_check_file = @@ -39,8 +37,3 @@ openthread_project_include_dirs = [ "${chip_root}/src/platform/bouffalolab/BL702" ] openthread_external_platform = "${bouffalolab_iot_sdk_build_root}/bl702:bl_iot_sdk" - -pw_build_LINK_DEPS = [ - "$dir_pw_assert:impl", - "$dir_pw_log:impl", -] diff --git a/src/platform/bouffalolab/BL702/bl702Config.cpp b/src/platform/bouffalolab/common/BLConfig.cpp similarity index 58% rename from src/platform/bouffalolab/BL702/bl702Config.cpp rename to src/platform/bouffalolab/common/BLConfig.cpp index a036a9277afe66..b8144dd1c23025 100644 --- a/src/platform/bouffalolab/BL702/bl702Config.cpp +++ b/src/platform/bouffalolab/common/BLConfig.cpp @@ -17,7 +17,7 @@ #include -#include +#include #include #include @@ -31,13 +31,12 @@ namespace chip { namespace DeviceLayer { namespace Internal { -// // Prefix used for Easyflash keys that contain Chip group encryption keys. -CHIP_ERROR BL702Config::Init() +CHIP_ERROR BLConfig::Init() { return CHIP_NO_ERROR; } -CHIP_ERROR BL702Config::ReadConfigValue(const char * key, uint8_t * val, size_t size, size_t & readsize) +CHIP_ERROR BLConfig::ReadConfigValue(const char * key, uint8_t * val, size_t size, size_t & readsize) { env_node_obj node; @@ -71,25 +70,25 @@ CHIP_ERROR BL702Config::ReadConfigValue(const char * key, uint8_t * val, size_t return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } -CHIP_ERROR BL702Config::ReadConfigValue(const char * key, bool & val) +CHIP_ERROR BLConfig::ReadConfigValue(const char * key, bool & val) { size_t readlen = 0; return ReadConfigValue(key, (uint8_t *) &val, 1, readlen); } -CHIP_ERROR BL702Config::ReadConfigValue(const char * key, uint32_t & val) +CHIP_ERROR BLConfig::ReadConfigValue(const char * key, uint32_t & val) { size_t readlen = 0; return ReadConfigValue(key, (uint8_t *) &val, sizeof(val), readlen); } -CHIP_ERROR BL702Config::ReadConfigValue(const char * key, uint64_t & val) +CHIP_ERROR BLConfig::ReadConfigValue(const char * key, uint64_t & val) { size_t readlen = 0; return ReadConfigValue(key, (uint8_t *) &val, sizeof(val), readlen); } -CHIP_ERROR BL702Config::ReadConfigValueStr(const char * key, char * buf, size_t bufSize, size_t & outLen) +CHIP_ERROR BLConfig::ReadConfigValueStr(const char * key, char * buf, size_t bufSize, size_t & outLen) { size_t readlen = 0; if (CHIP_NO_ERROR == ReadConfigValue(key, (uint8_t *) buf, bufSize, readlen)) @@ -106,7 +105,7 @@ CHIP_ERROR BL702Config::ReadConfigValueStr(const char * key, char * buf, size_t return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } -CHIP_ERROR BL702Config::ReadConfigValueBin(const char * key, uint8_t * buf, size_t bufSize, size_t & outLen) +CHIP_ERROR BLConfig::ReadConfigValueBin(const char * key, uint8_t * buf, size_t bufSize, size_t & outLen) { size_t readlen = 0; if (CHIP_NO_ERROR == ReadConfigValue(key, (uint8_t *) buf, bufSize, readlen)) @@ -118,7 +117,7 @@ CHIP_ERROR BL702Config::ReadConfigValueBin(const char * key, uint8_t * buf, size return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } -CHIP_ERROR BL702Config::WriteConfigValue(const char * key, uint8_t * val, size_t size) +CHIP_ERROR BLConfig::WriteConfigValue(const char * key, uint8_t * val, size_t size) { EfErrCode ret = EF_NO_ERR; @@ -141,42 +140,42 @@ CHIP_ERROR BL702Config::WriteConfigValue(const char * key, uint8_t * val, size_t } } -CHIP_ERROR BL702Config::WriteConfigValue(const char * key, bool val) +CHIP_ERROR BLConfig::WriteConfigValue(const char * key, bool val) { return WriteConfigValue(key, (uint8_t *) &val, sizeof(val)); } -CHIP_ERROR BL702Config::WriteConfigValue(const char * key, uint32_t val) +CHIP_ERROR BLConfig::WriteConfigValue(const char * key, uint32_t val) { return WriteConfigValue(key, (uint8_t *) &val, sizeof(val)); } -CHIP_ERROR BL702Config::WriteConfigValue(const char * key, uint64_t val) +CHIP_ERROR BLConfig::WriteConfigValue(const char * key, uint64_t val) { return WriteConfigValue(key, (uint8_t *) &val, sizeof(val)); } -CHIP_ERROR BL702Config::WriteConfigValueStr(const char * key, const char * str) +CHIP_ERROR BLConfig::WriteConfigValueStr(const char * key, const char * str) { return WriteConfigValue(key, (uint8_t *) str, strlen(str) + 1); } -CHIP_ERROR BL702Config::WriteConfigValueStr(const char * key, const char * str, size_t strLen) +CHIP_ERROR BLConfig::WriteConfigValueStr(const char * key, const char * str, size_t strLen) { return WriteConfigValue(key, (uint8_t *) str, strLen); } -CHIP_ERROR BL702Config::WriteConfigValueBin(const char * key, const uint8_t * data, size_t dataLen) +CHIP_ERROR BLConfig::WriteConfigValueBin(const char * key, const uint8_t * data, size_t dataLen) { return WriteConfigValue(key, (uint8_t *) data, dataLen); } -CHIP_ERROR BL702Config::ClearConfigValue(const char * key) +CHIP_ERROR BLConfig::ClearConfigValue(const char * key) { return EF_NO_ERR == ef_del_env(key) ? CHIP_NO_ERROR : CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } -CHIP_ERROR BL702Config::FactoryResetConfig(void) +CHIP_ERROR BLConfig::FactoryResetConfig(void) { // Only reset config section information @@ -185,16 +184,16 @@ CHIP_ERROR BL702Config::FactoryResetConfig(void) return CHIP_NO_ERROR; } -void BL702Config::RunConfigUnitTest() {} +void BLConfig::RunConfigUnitTest() {} -bool BL702Config::ConfigValueExists(const char * key) +bool BLConfig::ConfigValueExists(const char * key) { env_node_obj node; return ef_get_env_obj(key, &node); } -CHIP_ERROR BL702Config::ReadKVS(const char * key, void * value, size_t value_size, size_t * read_bytes_size, size_t offset_bytes) +CHIP_ERROR BLConfig::ReadKVS(const char * key, void * value, size_t value_size, size_t * read_bytes_size, size_t offset_bytes) { size_t read_len = 0, datalen; env_node_obj node; @@ -247,7 +246,7 @@ CHIP_ERROR BL702Config::ReadKVS(const char * key, void * value, size_t value_siz return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } -CHIP_ERROR BL702Config::WriteKVS(const char * key, const void * value, size_t value_size) +CHIP_ERROR BLConfig::WriteKVS(const char * key, const void * value, size_t value_size) { EfErrCode ret = EF_NO_ERR; @@ -270,7 +269,7 @@ CHIP_ERROR BL702Config::WriteKVS(const char * key, const void * value, size_t va } } -CHIP_ERROR BL702Config::ClearKVS(const char * key) +CHIP_ERROR BLConfig::ClearKVS(const char * key) { ef_port_env_lock(); @@ -281,72 +280,6 @@ CHIP_ERROR BL702Config::ClearKVS(const char * key) return CHIP_NO_ERROR; } -CHIP_ERROR BL702Config::WriteWiFiInfo(const char * ssid, const char * passwd) -{ - char *pssid = (char *) ssid, *ppass = (char *) passwd; - - ef_port_env_lock(); - - if (EF_NO_ERR == ef_set_env_blob(kBLConfigKey_wifissid, pssid, strlen(pssid)) && - EF_NO_ERR == ef_set_env_blob(kBLConfigKey_wifipassword, ppass, strlen(ppass))) - { - - ef_port_env_unlock(); - - return CHIP_NO_ERROR; - } - - ef_port_env_unlock(); - - return CHIP_ERROR_PERSISTED_STORAGE_FAILED; -} - -CHIP_ERROR BL702Config::ReadWiFiInfo(const char * ssid, uint32_t ssid_size, const char * passwd, uint32_t passwd_size) -{ - size_t saved_value_len = 0; - char *pssid = (char *) ssid, *ppass = (char *) passwd; - - memset((void *) ssid, 0, ssid_size); - memset((void *) passwd, 0, passwd_size); - - ef_port_env_lock(); - - ef_get_env_blob(kBLConfigKey_wifissid, (void *) pssid, ssid_size, &saved_value_len); - if (saved_value_len != 0) - { - saved_value_len = 0; - ef_get_env_blob(kBLConfigKey_wifipassword, (void *) ppass, passwd_size, &saved_value_len); - } - - ef_port_env_unlock(); - - return saved_value_len ? CHIP_NO_ERROR : CHIP_ERROR_PERSISTED_STORAGE_FAILED; -} - -CHIP_ERROR BL702Config::ClearWiFiInfo(void) -{ - ef_port_env_lock(); - if (EF_NO_ERR == ef_del_env(kBLConfigKey_wifissid) && EF_NO_ERR == ef_del_env(kBLConfigKey_wifipassword)) - { - ef_port_env_unlock(); - - return CHIP_NO_ERROR; - } - ef_port_env_unlock(); - - return CHIP_ERROR_PERSISTED_STORAGE_FAILED; -} - -bool BL702Config::isWiFiInfoSaved() -{ - env_node_obj node; - - char tssid[64], tpasswd[64]; - ReadWiFiInfo(tssid, sizeof(tssid), tpasswd, sizeof(tpasswd)); - - return ef_get_env_obj(kBLConfigKey_wifissid, &node) && ef_get_env_obj(kBLConfigKey_wifipassword, &node); -} - } // namespace Internal } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/bl702Config.h b/src/platform/bouffalolab/common/BLConfig.h similarity index 93% rename from src/platform/bouffalolab/BL702/bl702Config.h rename to src/platform/bouffalolab/common/BLConfig.h index af40b430964a3c..3b533a08f5e142 100644 --- a/src/platform/bouffalolab/BL702/bl702Config.h +++ b/src/platform/bouffalolab/common/BLConfig.h @@ -25,14 +25,13 @@ namespace chip { namespace DeviceLayer { namespace Internal { -#define KCONFIG_SECT_PSV "PSV" /** - * Provides functions and definitions for accessing device configuration information on the BL702 platform. + * Provides functions and definitions for accessing device configuration information on the Bouffalo Lab platform. * * This class is designed to be mixed-in to concrete implementation classes as a means to * provide access to configuration information to generic base classes. */ -class BL702Config +class BLConfig { public: using Key = const char *; @@ -107,14 +106,6 @@ class BL702Config static CHIP_ERROR ReadKVS(const char * key, void * value, size_t value_size, size_t * read_bytes_size, size_t offset_bytes); static CHIP_ERROR WriteKVS(const char * key, const void * value, size_t value_size); static CHIP_ERROR ClearKVS(const char * key); - -#ifdef CFG_USE_PSRAM - static bool isPsramRegion(void * paddr); -#endif - static CHIP_ERROR WriteWiFiInfo(const char * ssid, const char * password); - static CHIP_ERROR ReadWiFiInfo(const char * ssid, uint32_t ssid_size, const char * passwd, uint32_t passwd_size); - static bool isWiFiInfoSaved(); - static CHIP_ERROR ClearWiFiInfo(void); }; } // namespace Internal diff --git a/src/platform/bouffalolab/BL602/BLEManagerImpl.cpp b/src/platform/bouffalolab/common/BLEManagerImpl.cpp similarity index 99% rename from src/platform/bouffalolab/BL602/BLEManagerImpl.cpp rename to src/platform/bouffalolab/common/BLEManagerImpl.cpp index 20d5bc9006d81d..ff26daf1167bd8 100644 --- a/src/platform/bouffalolab/BL602/BLEManagerImpl.cpp +++ b/src/platform/bouffalolab/common/BLEManagerImpl.cpp @@ -696,8 +696,6 @@ bool BLEManagerImpl::SetSubscribed(bt_conn * conn) bool isSubscribed = mSubscribedConns[index]; mSubscribedConns[index] = true; - ChipLogError(DeviceLayer, "BLEManagerImpl::SetSubscribed %u", index); - // If we were not subscribed previously, increment the reference counter of the connection. if (!isSubscribed) { diff --git a/src/platform/bouffalolab/BL602/BLEManagerImpl.h b/src/platform/bouffalolab/common/BLEManagerImpl.h similarity index 100% rename from src/platform/bouffalolab/BL602/BLEManagerImpl.h rename to src/platform/bouffalolab/common/BLEManagerImpl.h diff --git a/src/platform/bouffalolab/BL702/BlePlatformConfig.h b/src/platform/bouffalolab/common/BlePlatformConfig.h similarity index 100% rename from src/platform/bouffalolab/BL702/BlePlatformConfig.h rename to src/platform/bouffalolab/common/BlePlatformConfig.h diff --git a/src/platform/bouffalolab/BL702/CHIPDevicePlatformConfig.h b/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h similarity index 58% rename from src/platform/bouffalolab/BL702/CHIPDevicePlatformConfig.h rename to src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h index d71c8ff00ec895..698c9419620374 100644 --- a/src/platform/bouffalolab/BL702/CHIPDevicePlatformConfig.h +++ b/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h @@ -17,38 +17,29 @@ #pragma once -// ==================== Platform Adaptations ==================== - +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 1 +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 +#else #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 0 #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 - -// ========== Platform-specific Configuration ========= - -#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_ENABLE_TUNNEL_TELEMETRY 0 - -// ========== CHIP Platform Configuration ========= -#define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE (4 * 1024) -#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE (6 * 1024) -#define CHIP_DEVICE_CONFIG_MAX_EVENT_QUEUE_SIZE 15 +#endif #if CHIP_ENABLE_OPENTHREAD #define CHIP_DEVICE_CONFIG_ENABLE_THREAD 1 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 1 #define CHIP_DEVICE_CONFIG_ENABLE_THREAD_DNS_CLIENT 1 -#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 +#else +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_DNS_CLIENT 0 #endif -// Per 5.2.5.2. Commencement Section of CHIP spec, BLE advertisement is -// disabled for Locks and Barrier Access Devices. -#define CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART 0 -#define CHIP_DEVICE_CONFIG_ENABLE_PAIRING_AUTOSTART 1 +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 -#ifndef CHIP_DEVICE_CONFIG_ENABLE_DNSSD -#define CHIP_DEVICE_CONFIG_ENABLE_DNSSD 1 -#endif -#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DISCOVERY 1 +#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_PERSISTED_STORAGE_GLOBAL_EIDC_KEY 2 +#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE (8 * 1024) +#define CHIP_DEVICE_CONFIG_MAX_EVENT_QUEUE_SIZE 25 diff --git a/src/platform/bouffalolab/BL702/CHIPDevicePlatformEvent.h b/src/platform/bouffalolab/common/CHIPDevicePlatformEvent.h similarity index 88% rename from src/platform/bouffalolab/BL702/CHIPDevicePlatformEvent.h rename to src/platform/bouffalolab/common/CHIPDevicePlatformEvent.h index d14d1f7b9bb2ac..8746bebf82bfe8 100644 --- a/src/platform/bouffalolab/BL702/CHIPDevicePlatformEvent.h +++ b/src/platform/bouffalolab/common/CHIPDevicePlatformEvent.h @@ -17,9 +17,10 @@ #pragma once +#include + #include #include -#include namespace chip { namespace DeviceLayer { @@ -27,7 +28,7 @@ namespace DeviceLayer { namespace DeviceEventType { /** - * Enumerates BL702 platform-specific event types that are visible to the application. + * Enumerates Bouffalo Lab platforms event types that are visible to the application. */ enum PublicPlatformSpecificEventTypes { @@ -35,7 +36,7 @@ enum PublicPlatformSpecificEventTypes }; /** - * Enumerates BL702 platform-specific event types that are internal to the chip Device Layer. + * Enumerates Bouffalo Lab platforms event types that are internal to the chip Device Layer. */ enum InternalPlatformSpecificEventTypes { @@ -75,7 +76,7 @@ struct BleC2IndDoneEventType }; /** - * Represents platform-specific event information for the BL702 platform. + * Represents platform-specific event information for Bouffalo Lab platforms. */ struct ChipDevicePlatformEvent final { diff --git a/src/platform/bouffalolab/BL602/CHIPPlatformConfig.h b/src/platform/bouffalolab/common/CHIPPlatformConfig.h similarity index 81% rename from src/platform/bouffalolab/BL602/CHIPPlatformConfig.h rename to src/platform/bouffalolab/common/CHIPPlatformConfig.h index 44d3114c1fcc75..c3e39f3d2d22d9 100644 --- a/src/platform/bouffalolab/BL602/CHIPPlatformConfig.h +++ b/src/platform/bouffalolab/common/CHIPPlatformConfig.h @@ -1,7 +1,6 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Google LLC. + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,28 +15,11 @@ * limitations under the License. */ -/** - * @file - * Platform-specific configuration overrides for CHIP on - * Bouffalolab BL602 platforms. - */ - #pragma once #include // ==================== General Platform Adaptations ==================== - -#define CHIP_CONFIG_ERROR_TYPE int32_t -#define CHIP_CONFIG_NO_ERROR 0 -#define CHIP_CONFIG_ERROR_MIN 4000000 -#define CHIP_CONFIG_ERROR_MAX 4000999 - -#define ASN1_CONFIG_ERROR_TYPE int32_t -#define ASN1_CONFIG_NO_ERROR 0 -#define ASN1_CONFIG_ERROR_MIN 5000000 -#define ASN1_CONFIG_ERROR_MAX 5000999 - #define ChipDie() abort() #define CHIP_CONFIG_PERSISTED_STORAGE_KEY_TYPE const char * @@ -47,14 +29,8 @@ #define CHIP_CONFIG_LIFETIIME_PERSISTED_COUNTER_KEY 0x01 // ==================== 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_HASH_IMPLEMENTATION_MBEDTLS 0 -#define CHIP_CONFIG_HASH_IMPLEMENTATION_PLATFORM 0 +//#define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(bl_sha_ctx_t) +#define CHIP_CONFIG_SHA256_CONTEXT_SIZE ((1 + 5 + 18 + 16 + 16) * sizeof(unsigned int)) #define CHIP_CONFIG_AES_IMPLEMENTATION_OPENSSL 0 #define CHIP_CONFIG_AES_IMPLEMENTATION_AESNI 0 @@ -65,9 +41,6 @@ #define CHIP_CONFIG_RNG_IMPLEMENTATION_CHIPDRBG 1 #define CHIP_CONFIG_RNG_IMPLEMENTATION_PLATFORM 0 -//#define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(bl_sha_ctx_t) -#define CHIP_CONFIG_SHA256_CONTEXT_SIZE ((1 + 5 + 18 + 16 + 16) * sizeof(unsigned int)) - #define CHIP_CONFIG_ENABLE_PASE_INITIATOR 0 #define CHIP_CONFIG_ENABLE_PASE_RESPONDER 1 #define CHIP_CONFIG_ENABLE_CASE_INITIATOR 1 diff --git a/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.cpp b/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp similarity index 61% rename from src/platform/bouffalolab/BL702/ConfigurationManagerImpl.cpp rename to src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp index 00878976150d26..4618e7f72f7274 100644 --- a/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.cpp +++ b/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp @@ -35,9 +35,6 @@ namespace chip { namespace DeviceLayer { using namespace ::chip::DeviceLayer::Internal; - -/** Singleton instance of the ConfigurationManager implementation object. - */ ConfigurationManagerImpl & ConfigurationManagerImpl::GetDefaultInstance() { static ConfigurationManagerImpl sInstance; @@ -50,42 +47,25 @@ CHIP_ERROR ConfigurationManagerImpl::Init() bool failSafeArmed; uint32_t rebootCount = 0; - err = Internal::GenericConfigurationManagerImpl::Init(); + err = Internal::GenericConfigurationManagerImpl::Init(); + SuccessOrExit(err); - BL_RST_REASON_E bootCause = bl_sys_rstinfo_get(); - mBootReason = to_underlying(BootReasonType::kUnspecified); - if (BL_RST_POR == bootCause) - { - mBootReason = to_underlying(BootReasonType::kPowerOnReboot); - } - else if (BL_RST_BOR == bootCause) - { - mBootReason = to_underlying(BootReasonType::kBrownOutReset); - } - else if (BL_RST_WDT == bootCause) + if (BLConfig::ConfigValueExists(BLConfig::kCounterKey_RebootCount)) { - mBootReason = to_underlying(BootReasonType::kHardwareWatchdogReset); + err = GetRebootCount(rebootCount); + SuccessOrExit(err); } - // else if (BL_RST_HBN == bootCause) { - // mBootReason = BootReasonType::SoftwareReset; - // } - else if (BL_RST_SOFTWARE == bootCause) + else { - mBootReason = to_underlying(BootReasonType::kSoftwareReset); + rebootCount = 0; } + err = StoreRebootCount(rebootCount + 1); + SuccessOrExit(err); - if (BL_RST_HBN != bootCause) + if (!BLConfig::ConfigValueExists(BLConfig::kCounterKey_TotalOperationalHours)) { - if (CHIP_NO_ERROR == ReadConfigValue(BL702Config::kCounterKey_RebootCount, rebootCount)) - { - rebootCount += 1; - } - WriteConfigValue(BL702Config::kCounterKey_RebootCount, rebootCount + 1); - } - - if (!BL702Config::ConfigValueExists(BL702Config::kCounterKey_TotalOperationalHours)) - { - ReturnErrorOnFailure(StoreTotalOperationalHours(0)); + err = StoreTotalOperationalHours(0); + SuccessOrExit(err); } // If the fail-safe was armed when the device last shutdown, initiate a factory reset. @@ -96,6 +76,7 @@ CHIP_ERROR ConfigurationManagerImpl::Init() } err = CHIP_NO_ERROR; +exit: return err; } @@ -110,113 +91,102 @@ void ConfigurationManagerImpl::InitiateFactoryReset() PlatformMgr().ScheduleWork(DoFactoryReset); } -CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) -{ - char keyname[sizeof(KCONFIG_SECT_PSV) + 10]; - - sprintf(keyname, "%s_%x", KCONFIG_SECT_PSV, key); - - CHIP_ERROR err = ReadConfigValue(keyname, 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) -{ - char keyname[sizeof(KCONFIG_SECT_PSV) + 10]; - - sprintf(keyname, "%s_%d", KCONFIG_SECT_PSV, key); - - return WriteConfigValue(keyname, value); -} - CHIP_ERROR ConfigurationManagerImpl::GetRebootCount(uint32_t & rebootCount) { - return ReadConfigValue(BL702Config::kCounterKey_RebootCount, rebootCount); + return BLConfig::ReadConfigValue(BLConfig::kCounterKey_RebootCount, rebootCount); } CHIP_ERROR ConfigurationManagerImpl::StoreRebootCount(uint32_t rebootCount) { - return WriteConfigValue(BL702Config::kCounterKey_RebootCount, rebootCount); + return BLConfig::WriteConfigValue(BLConfig::kCounterKey_RebootCount, rebootCount); } CHIP_ERROR ConfigurationManagerImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours) { - return ReadConfigValue(BL702Config::kCounterKey_TotalOperationalHours, totalOperationalHours); + return ReadConfigValue(BLConfig::kCounterKey_TotalOperationalHours, totalOperationalHours); } CHIP_ERROR ConfigurationManagerImpl::StoreTotalOperationalHours(uint32_t totalOperationalHours) { - return WriteConfigValue(BL702Config::kCounterKey_TotalOperationalHours, totalOperationalHours); + return WriteConfigValue(BLConfig::kCounterKey_TotalOperationalHours, totalOperationalHours); } -CHIP_ERROR ConfigurationManagerImpl::GetBootReason(uint32_t & bootReason) +CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) { - bootReason = mBootReason; - return CHIP_NO_ERROR; + BLConfig::Key configKey{ 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) +{ + BLConfig::Key configKey{ key }; + return WriteConfigValue(configKey, value); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, bool & val) { - return BL702Config::ReadConfigValue(key, val); + return BLConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint32_t & val) { - return BL702Config::ReadConfigValue(key, val); + return BLConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValue(Key key, uint64_t & val) { - return BL702Config::ReadConfigValue(key, val); + return BLConfig::ReadConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { - return BL702Config::ReadConfigValueStr(key, buf, bufSize, outLen); + return BLConfig::ReadConfigValueStr(key, buf, bufSize, outLen); } CHIP_ERROR ConfigurationManagerImpl::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) { - return BL702Config::ReadConfigValueBin(key, buf, bufSize, outLen); + return BLConfig::ReadConfigValueBin(key, buf, bufSize, outLen); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, bool val) { - return BL702Config::WriteConfigValue(key, val); + return BLConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint32_t val) { - return BL702Config::WriteConfigValue(key, val); + return BLConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValue(Key key, uint64_t val) { - return BL702Config::WriteConfigValue(key, val); + return BLConfig::WriteConfigValue(key, val); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str) { - return BL702Config::WriteConfigValueStr(key, str); + return BLConfig::WriteConfigValueStr(key, str); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueStr(Key key, const char * str, size_t strLen) { - return BL702Config::WriteConfigValueStr(key, str, strLen); + return BLConfig::WriteConfigValueStr(key, str, strLen); } CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) { - return BL702Config::WriteConfigValueBin(key, data, dataLen); + return BLConfig::WriteConfigValueBin(key, data, dataLen); } void ConfigurationManagerImpl::RunConfigUnitTest(void) { - BL702Config::RunConfigUnitTest(); + BLConfig::RunConfigUnitTest(); } void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) @@ -225,7 +195,7 @@ void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) ChipLogProgress(DeviceLayer, "Performing factory reset"); - err = BL702Config::FactoryResetConfig(); + err = BLConfig::FactoryResetConfig(); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "FactoryResetConfig() failed: %s", ErrorStr(err)); @@ -240,6 +210,5 @@ ConfigurationManager & ConfigurationMgrImpl() { return ConfigurationManagerImpl::GetDefaultInstance(); } - } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.h b/src/platform/bouffalolab/common/ConfigurationManagerImpl.h similarity index 78% rename from src/platform/bouffalolab/BL702/ConfigurationManagerImpl.h rename to src/platform/bouffalolab/common/ConfigurationManagerImpl.h index db7668bf0f5eab..1d69d582185e75 100644 --- a/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.h +++ b/src/platform/bouffalolab/common/ConfigurationManagerImpl.h @@ -17,7 +17,8 @@ #pragma once -#include +#include + #include namespace chip { @@ -26,32 +27,26 @@ namespace DeviceLayer { /** * Concrete implementation of the ConfigurationManager singleton object for the bl702 platform. */ -class ConfigurationManagerImpl : public Internal::GenericConfigurationManagerImpl +class ConfigurationManagerImpl : public Internal::GenericConfigurationManagerImpl { public: - // This returns an instance of this class. static ConfigurationManagerImpl & GetDefaultInstance(); 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); private: - uint32_t mBootReason; - - // ===== Members that implement the ConfigurationManager public interface. + // ===== Members that implement the ConfigurationManager private interface. CHIP_ERROR Init(void) override; + bool CanFactoryReset(void) override; void InitiateFactoryReset(void) override; CHIP_ERROR ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) override; CHIP_ERROR WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) override; - // NOTE: Other public interface methods are implemented by GenericConfigurationManagerImpl<>. - - // ===== Members that implement the GenericConfigurationManagerImpl protected interface. CHIP_ERROR ReadConfigValue(Key key, bool & val) override; CHIP_ERROR ReadConfigValue(Key key, uint32_t & val) override; CHIP_ERROR ReadConfigValue(Key key, uint64_t & val) override; @@ -65,22 +60,12 @@ class ConfigurationManagerImpl : public Internal::GenericConfigurationManagerImp CHIP_ERROR WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) override; void RunConfigUnitTest(void) override; - // ===== Private members reserved for use by this class only. - - static void DoFactoryReset(intptr_t arg); - #if CHIP_DEVICE_CONFIG_ENABLE_WIFI CHIP_ERROR GetPrimaryWiFiMACAddress(uint8_t * buf) override; #endif -}; -#if CHIP_DEVICE_CONFIG_ENABLE_WIFI -inline CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * buf) -{ - ConnectivityManagerImpl::GetWiFiMacAddress(buf); - return CHIP_NO_ERROR; -} -#endif + static void DoFactoryReset(intptr_t arg); +}; } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp similarity index 83% rename from src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp rename to src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp index cf1585a44a0e53..f1a47e5a68de06 100644 --- a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp +++ b/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp @@ -28,6 +28,13 @@ #include #endif +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include +#ifdef BL602 +#include +#endif +#endif + #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include #endif @@ -54,6 +61,13 @@ CHIP_ERROR ConnectivityManagerImpl::_Init() GenericConnectivityManagerImpl_Thread::_Init(); #endif +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + CHIP_ERROR err = SetWiFiStationMode(kWiFiStationMode_Enabled); + NetworkCommissioning::BLWiFiDriver::GetInstance().ReConnectWiFiNetwork(); + + ReturnErrorOnFailure(err); +#endif + return CHIP_NO_ERROR; } diff --git a/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.h b/src/platform/bouffalolab/common/ConnectivityManagerImpl.h similarity index 88% rename from src/platform/bouffalolab/BL602/ConnectivityManagerImpl.h rename to src/platform/bouffalolab/common/ConnectivityManagerImpl.h index 3efacc02c75043..8c06c585fb806f 100644 --- a/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.h +++ b/src/platform/bouffalolab/common/ConnectivityManagerImpl.h @@ -1,7 +1,6 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors - * Copyright (c) 2019 Nest Labs, Inc. + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +23,11 @@ #if INET_CONFIG_ENABLE_TCP_ENDPOINT #include #endif +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI #include +#else +#include +#endif #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include #else @@ -36,23 +39,20 @@ #include #endif -namespace Inet { -class IPAddress; -} // namespace Inet - namespace chip { namespace DeviceLayer { -/** - * Concrete implementation of the ConnectivityManager singleton object for Bouffalolab BL602 platforms. - */ class ConnectivityManagerImpl final : public ConnectivityManager, public Internal::GenericConnectivityManagerImpl, public Internal::GenericConnectivityManagerImpl_UDP, #if INET_CONFIG_ENABLE_TCP_ENDPOINT public Internal::GenericConnectivityManagerImpl_TCP, #endif +#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 @@ -68,6 +68,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, // the implementation methods provided by this class. friend class ConnectivityManager; +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI public: static WiFiStationState mWiFiStationState; @@ -76,19 +77,22 @@ class ConnectivityManagerImpl final : public ConnectivityManager, void OnStationConnected(void); void ChangeWiFiStationState(WiFiStationState newState); void OnIPv6AddressAvailable(); +#endif private: // ===== Members that implement the ConnectivityManager abstract interface. - +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI bool _IsWiFiStationEnabled(void); - bool _IsWiFiStationProvisioned(void); + // bool _IsWiFiStationProvisioned(void); CHIP_ERROR _SetWiFiStationMode(WiFiStationMode val); + void GetWifiState(void); + WiFiStationState GetWiFiStationState(void); +#endif + void DriveStationState(void); static void DriveStationState(::chip::System::Layer * aLayer, void * aAppState); CHIP_ERROR _Init(void); void _OnPlatformEvent(const ChipDeviceEvent * event); - void GetWifiState(void); - WiFiStationState GetWiFiStationState(void); // ===== Members for internal use by the following friends. @@ -98,6 +102,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, static ConnectivityManagerImpl sInstance; }; +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI inline ConnectivityManager::WiFiStationState ConnectivityManagerImpl::GetWiFiStationState(void) { return mWiFiStationState; @@ -107,6 +112,7 @@ inline bool ConnectivityManagerImpl::_IsWiFiStationConnected(void) { return mWiFiStationState == kWiFiStationState_Connected; } +#endif /** * Returns the public interface of the ConnectivityManager singleton object. @@ -123,7 +129,7 @@ inline ConnectivityManager & ConnectivityMgr(void) * 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 ESP32 platform. + * that are specific to the Bouffalo Lab platform. */ inline ConnectivityManagerImpl & ConnectivityMgrImpl(void) { diff --git a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp new file mode 100644 index 00000000000000..6e11e6f91d261e --- /dev/null +++ b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include +#include + +#include + +namespace chip { +namespace DeviceLayer { + +extern "C" size_t get_heap_size(void); +#ifdef CFG_USE_PSRAM +extern "C" size_t get_heap3_size(void); +#endif + +DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() +{ + static DiagnosticDataProviderImpl sInstance; + return sInstance; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) +{ +#ifdef CFG_USE_PSRAM + size_t freeHeapSize = xPortGetFreeHeapSize() + xPortGetFreeHeapSizePsram(); +#else + size_t freeHeapSize = xPortGetFreeHeapSize(); +#endif + + currentHeapFree = static_cast(freeHeapSize); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) +{ +#ifdef CFG_USE_PSRAM + currentHeapUsed = (get_heap_size() + get_heap3_size() - xPortGetFreeHeapSize() - xPortGetFreeHeapSizePsram()); +#else + currentHeapUsed = (get_heap_size() - xPortGetFreeHeapSize()); +#endif + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) +{ +#ifdef CFG_USE_PSRAM + currentHeapHighWatermark = + get_heap_size() + get_heap3_size() - xPortGetMinimumEverFreeHeapSize() - xPortGetMinimumEverFreeHeapSizePsram(); +#else + currentHeapHighWatermark = get_heap_size() - xPortGetMinimumEverFreeHeapSize(); +#endif + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetThreadMetrics(ThreadMetrics ** threadMetricsOut) +{ + /* Obtain all available task information */ + TaskStatus_t * taskStatusArray; + ThreadMetrics * head = nullptr; + uint32_t arraySize, x, dummy; + + arraySize = uxTaskGetNumberOfTasks(); + + taskStatusArray = static_cast(chip::Platform::MemoryCalloc(arraySize, sizeof(TaskStatus_t))); + + if (taskStatusArray != NULL) + { + /* Generate raw status information about each task. */ + arraySize = uxTaskGetSystemState(taskStatusArray, arraySize, &dummy); + /* For each populated position in the taskStatusArray array, + format the raw data as human readable ASCII data. */ + + for (x = 0; x < arraySize; x++) + { + ThreadMetrics * thread = new ThreadMetrics(); + if (thread) + { + Platform::CopyString(thread->NameBuf, taskStatusArray[x].pcTaskName); + thread->name.Emplace(CharSpan::fromCharString(thread->NameBuf)); + thread->id = taskStatusArray[x].xTaskNumber; + thread->stackFreeMinimum.Emplace(taskStatusArray[x].usStackHighWaterMark); + + /* Unsupported metrics */ + // thread->stackSize + // thread->stackFreeCurrent + + thread->Next = head; + head = thread; + } + } + + *threadMetricsOut = head; + /* The array is no longer needed, free the memory it consumes. */ + chip::Platform::MemoryFree(taskStatusArray); + } + + return CHIP_NO_ERROR; +} + +void DiagnosticDataProviderImpl::ReleaseThreadMetrics(ThreadMetrics * threadMetrics) +{ + while (threadMetrics) + { + ThreadMetrics * del = threadMetrics; + threadMetrics = threadMetrics->Next; + delete del; + } +} + +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::GetActiveHardwareFaults(GeneralFaults & hardwareFaults) +{ +#if CHIP_CONFIG_TEST + ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kRadio))); + ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kSensor))); + ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kPowerSource))); + ReturnErrorOnFailure(hardwareFaults.add(to_underlying(HardwareFaultEnum::kUserInterfaceFault))); +#endif + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetActiveRadioFaults(GeneralFaults & radioFaults) +{ +#if CHIP_CONFIG_TEST + ReturnErrorOnFailure(radioFaults.add(EMBER_ZCL_RADIO_FAULT_ENUM_THREAD_FAULT)); + ReturnErrorOnFailure(radioFaults.add(EMBER_ZCL_RADIO_FAULT_ENUM_BLE_FAULT)); +#endif + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetActiveNetworkFaults(GeneralFaults & networkFaults) +{ +#if CHIP_CONFIG_TEST + ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kHardwareFailure))); + ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kNetworkJammed))); + ReturnErrorOnFailure(networkFaults.add(to_underlying(NetworkFaultEnum::kConnectionFailed))); +#endif + + return CHIP_NO_ERROR; +} + +DiagnosticDataProvider & GetDiagnosticDataProviderImpl() +{ + return DiagnosticDataProviderImpl::GetDefaultInstance(); +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.h b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h similarity index 85% rename from src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.h rename to src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h index f8a1688d1c3870..8001afb0544cb3 100644 --- a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.h +++ b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h @@ -1,5 +1,4 @@ /* - * * Copyright (c) 2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,11 +14,6 @@ * limitations under the License. */ -/** - * @file - * Provides an implementation of the DiagnosticDataProvider object. - */ - #pragma once #include @@ -42,14 +36,18 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider CHIP_ERROR GetCurrentHeapFree(uint64_t & currentHeapFree) override; CHIP_ERROR GetCurrentHeapUsed(uint64_t & currentHeapUsed) override; CHIP_ERROR GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) override; - + CHIP_ERROR GetThreadMetrics(ThreadMetrics ** threadMetricsOut) override; + void ReleaseThreadMetrics(ThreadMetrics * threadMetrics) override; CHIP_ERROR GetRebootCount(uint16_t & rebootCount) override; + CHIP_ERROR GetBootReason(BootReasonType & bootReason) override; CHIP_ERROR GetUpTime(uint64_t & upTime) override; CHIP_ERROR GetTotalOperationalHours(uint32_t & totalOperationalHours) override; - CHIP_ERROR GetBootReason(BootReasonType & bootReason) override; - + CHIP_ERROR GetActiveHardwareFaults(GeneralFaults & hardwareFaults) override; + CHIP_ERROR GetActiveRadioFaults(GeneralFaults & radioFaults) override; + CHIP_ERROR GetActiveNetworkFaults(GeneralFaults & networkFaults) override; CHIP_ERROR GetNetworkInterfaces(NetworkInterface ** netifpp) override; void ReleaseNetworkInterfaces(NetworkInterface * netifp) override; +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI CHIP_ERROR GetWiFiBssId(MutableByteSpan & BssId) override; CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) override; CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) override; @@ -64,15 +62,8 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider CHIP_ERROR GetWiFiCurrentMaxRate(uint64_t & currentMaxRate) override; CHIP_ERROR GetWiFiOverrunCount(uint64_t & overrunCount) override; CHIP_ERROR ResetWiFiNetworkDiagnosticsCounts() override; +#endif }; -/** - * Returns the platform-specific implementation of the DiagnosticDataProvider singleton object. - * - * Applications can use this to gain access to features of the DiagnosticDataProvider - * that are specific to the selected platform. - */ -DiagnosticDataProvider & GetDiagnosticDataProviderImpl(); - } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/InetPlatformConfig.h b/src/platform/bouffalolab/common/InetPlatformConfig.h similarity index 96% rename from src/platform/bouffalolab/BL702/InetPlatformConfig.h rename to src/platform/bouffalolab/common/InetPlatformConfig.h index 088999420a6aae..d4552c22c81d5a 100644 --- a/src/platform/bouffalolab/BL702/InetPlatformConfig.h +++ b/src/platform/bouffalolab/common/InetPlatformConfig.h @@ -30,5 +30,5 @@ #endif // INET_CONFIG_NUM_TCP_ENDPOINTS #ifndef INET_CONFIG_NUM_UDP_ENDPOINTS -#define INET_CONFIG_NUM_UDP_ENDPOINTS 4 +#define INET_CONFIG_NUM_UDP_ENDPOINTS 6 #endif // INET_CONFIG_NUM_UDP_ENDPOINTS diff --git a/src/platform/bouffalolab/BL702/KeyValueStoreManagerImpl.cpp b/src/platform/bouffalolab/common/KeyValueStoreManagerImpl.cpp similarity index 87% rename from src/platform/bouffalolab/BL702/KeyValueStoreManagerImpl.cpp rename to src/platform/bouffalolab/common/KeyValueStoreManagerImpl.cpp index 929cfbace3668a..94dfb678c11b09 100644 --- a/src/platform/bouffalolab/BL702/KeyValueStoreManagerImpl.cpp +++ b/src/platform/bouffalolab/common/KeyValueStoreManagerImpl.cpp @@ -22,7 +22,7 @@ #include -#include +#include namespace chip { namespace DeviceLayer { @@ -37,7 +37,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t { VerifyOrReturnError(key, CHIP_ERROR_INVALID_ARGUMENT); - CHIP_ERROR err = BL702Config::ReadKVS(key, value, value_size, read_bytes_size, offset_bytes); + CHIP_ERROR err = BLConfig::ReadKVS(key, value, value_size, read_bytes_size, offset_bytes); if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; @@ -49,12 +49,12 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, { VerifyOrReturnError(key, CHIP_ERROR_INVALID_ARGUMENT); - return BL702Config::WriteKVS(key, value, value_size); + return BLConfig::WriteKVS(key, value, value_size); } CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) { - return BL702Config::ClearKVS((char *) key); + return BLConfig::ClearKVS((char *) key); } } // namespace PersistedStorage diff --git a/src/platform/bouffalolab/BL702/KeyValueStoreManagerImpl.h b/src/platform/bouffalolab/common/KeyValueStoreManagerImpl.h similarity index 100% rename from src/platform/bouffalolab/BL702/KeyValueStoreManagerImpl.h rename to src/platform/bouffalolab/common/KeyValueStoreManagerImpl.h diff --git a/src/platform/bouffalolab/BL702/Logging.cpp b/src/platform/bouffalolab/common/Logging.cpp similarity index 97% rename from src/platform/bouffalolab/BL702/Logging.cpp rename to src/platform/bouffalolab/common/Logging.cpp index 5bb986d63cb27d..e008fcd022b331 100644 --- a/src/platform/bouffalolab/BL702/Logging.cpp +++ b/src/platform/bouffalolab/common/Logging.cpp @@ -33,7 +33,7 @@ namespace chip { namespace Logging { namespace Platform { -char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; +static char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; void LogV(const char * module, uint8_t category, const char * msg, va_list v) { #ifndef PW_RPC_ENABLED diff --git a/src/platform/bouffalolab/BL602/OTAImageProcessorImpl.cpp b/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp similarity index 98% rename from src/platform/bouffalolab/BL602/OTAImageProcessorImpl.cpp rename to src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp index 97af465ef1fef3..6e38bf0b5a77cd 100644 --- a/src/platform/bouffalolab/BL602/OTAImageProcessorImpl.cpp +++ b/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp @@ -1,6 +1,5 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,7 +25,6 @@ extern "C" { } using namespace chip::System; -using namespace ::chip::DeviceLayer::Internal; namespace chip { diff --git a/src/platform/bouffalolab/BL602/OTAImageProcessorImpl.h b/src/platform/bouffalolab/common/OTAImageProcessorImpl.h similarity index 97% rename from src/platform/bouffalolab/BL602/OTAImageProcessorImpl.h rename to src/platform/bouffalolab/common/OTAImageProcessorImpl.h index c2cd9fa5607d9f..3e68f3c59d329a 100644 --- a/src/platform/bouffalolab/BL602/OTAImageProcessorImpl.h +++ b/src/platform/bouffalolab/common/OTAImageProcessorImpl.h @@ -1,6 +1,5 @@ /* - * - * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2022 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/src/platform/bouffalolab/common/PlatformManagerImpl.cpp b/src/platform/bouffalolab/common/PlatformManagerImpl.cpp new file mode 100644 index 00000000000000..f31ae77999db64 --- /dev/null +++ b/src/platform/bouffalolab/common/PlatformManagerImpl.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include + +namespace chip { +namespace DeviceLayer { + +PlatformManagerImpl PlatformManagerImpl::sInstance; + +void 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"); + } + + Internal::GenericPlatformManagerImpl_FreeRTOS::_Shutdown(); +} +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL602/PlatformManagerImpl.h b/src/platform/bouffalolab/common/PlatformManagerImpl.h similarity index 95% rename from src/platform/bouffalolab/BL602/PlatformManagerImpl.h rename to src/platform/bouffalolab/common/PlatformManagerImpl.h index 4e6641b6e1e66f..448bc0636971f1 100644 --- a/src/platform/bouffalolab/BL602/PlatformManagerImpl.h +++ b/src/platform/bouffalolab/common/PlatformManagerImpl.h @@ -16,15 +16,11 @@ * limitations under the License. */ -/** - * @file - * Provides an implementation of the PlatformManager object - * for BL602 platforms using the Bouffalolab SDK. - */ - #pragma once +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI #include +#endif #include namespace chip { @@ -62,7 +58,9 @@ class PlatformManagerImpl final : public PlatformManager, public Internal::Gener friend PlatformManager & PlatformMgr(void); friend PlatformManagerImpl & PlatformMgrImpl(void); friend class Internal::BLEManagerImpl; +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI friend void OnWiFiPlatformEvent(input_event_t * event, void * private_data); +#endif System::Clock::Timestamp mStartTime = System::Clock::kZero; diff --git a/src/platform/bouffalolab/BL702/SystemPlatformConfig.h b/src/platform/bouffalolab/common/SystemPlatformConfig.h similarity index 94% rename from src/platform/bouffalolab/BL702/SystemPlatformConfig.h rename to src/platform/bouffalolab/common/SystemPlatformConfig.h index 4912f404626de3..2fb7579c677dd5 100644 --- a/src/platform/bouffalolab/BL702/SystemPlatformConfig.h +++ b/src/platform/bouffalolab/common/SystemPlatformConfig.h @@ -26,6 +26,5 @@ struct ChipDeviceEvent; } // 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 * diff --git a/src/platform/bouffalolab/BL702/ThreadStackManagerImpl.h b/src/platform/bouffalolab/common/ThreadStackManagerImpl.h similarity index 100% rename from src/platform/bouffalolab/BL702/ThreadStackManagerImpl.h rename to src/platform/bouffalolab/common/ThreadStackManagerImpl.h diff --git a/src/platform/device.gni b/src/platform/device.gni index 6eb09ace0d32ec..43bf65ab03b72f 100644 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -152,9 +152,9 @@ if (chip_device_platform == "cc13x2_26x2") { } else if (chip_device_platform == "ameba") { _chip_device_layer = "Ameba" } else if (chip_device_platform == "bl602") { - _chip_device_layer = "bouffalolab/BL602" + _chip_device_layer = "bouffalolab/common" } else if (chip_device_platform == "bl702") { - _chip_device_layer = "bouffalolab/BL702" + _chip_device_layer = "bouffalolab/common" } else if (chip_device_platform == "cyw30739") { _chip_device_layer = "Infineon/CYW30739" } else if (chip_device_platform == "webos") { diff --git a/third_party/bouffalolab/repo b/third_party/bouffalolab/repo index 7ca85fd77663ab..125a1237081749 160000 --- a/third_party/bouffalolab/repo +++ b/third_party/bouffalolab/repo @@ -1 +1 @@ -Subproject commit 7ca85fd77663ab6e13ce8481593474ea38ad4bb2 +Subproject commit 125a1237081749d5cc3ab5c1dc2017465960bba4