diff --git a/config/nrfconnect/app/enable-gnu-std.cmake b/config/nrfconnect/app/enable-gnu-std.cmake index 5f31e1a5c62ab8..4019bbd31bf27a 100644 --- a/config/nrfconnect/app/enable-gnu-std.cmake +++ b/config/nrfconnect/app/enable-gnu-std.cmake @@ -1,6 +1,5 @@ add_library(gnu17 INTERFACE) target_compile_options(gnu17 INTERFACE - $<$:-std=gnu++17> - -D_SYS__PTHREADTYPES_H_) + $<$:-std=gnu++17>) target_link_libraries(app PRIVATE gnu17) diff --git a/config/nrfconnect/chip-module/Kconfig b/config/nrfconnect/chip-module/Kconfig index 5d03e82530c84e..d4ccccd983ed3f 100644 --- a/config/nrfconnect/chip-module/Kconfig +++ b/config/nrfconnect/chip-module/Kconfig @@ -106,7 +106,6 @@ config CHIP_MALLOC_SYS_HEAP config CHIP_FACTORY_DATA bool "Factory data provider" select ZCBOR - imply FPROTECT help Enables the default nRF Connect factory data provider implementation that supports reading the factory data encoded in the CBOR format from the @@ -149,7 +148,7 @@ config CHIP_FACTORY_DATA_WRITE_PROTECT bool "Enable Factory Data write protection" select FPROTECT depends on CHIP_FACTORY_DATA - default y if CHIP_FACTORY_DATA + default y help Enables the write protection of the Factory Data partition in the flash memory. This is a recommended feature, but it requires the Settings partition size to be @@ -302,4 +301,9 @@ config CHIP_FACTORY_RESET_ON_KEY_MIGRATION_FAILURE Perform factory reset of the device if the operational key for Fabric has not been migrated properly to PSA ITS storage. +config CHIP_PERSISTENT_SUBSCRIPTIONS + default n + # selecting experimental for this feature since there is an issue with multiple controllers. + select EXPERIMENTAL + endif # CHIP diff --git a/config/nrfconnect/chip-module/Kconfig.defaults b/config/nrfconnect/chip-module/Kconfig.defaults index 562755b14b9c25..218f39a3fa8f8a 100644 --- a/config/nrfconnect/chip-module/Kconfig.defaults +++ b/config/nrfconnect/chip-module/Kconfig.defaults @@ -24,6 +24,10 @@ if CHIP # System configuration # ============================================================================== +choice LIBC_IMPLEMENTATION + default NEWLIB_LIBC +endchoice + config ASSERT default y @@ -199,15 +203,27 @@ config CHIP_QSPI_NOR default y if BOARD_NRF5340DK_NRF5340_CPUAPP || BOARD_NRF52840DK_NRF52840 # nRF7002DK uses SPI NOR external flash + +if BOARD_NRF7002DK_NRF5340_CPUAPP || BOARD_NRF7002DK_NRF7001_NRF5340_CPUAPP + config CHIP_SPI_NOR - default y if BOARD_NRF7002DK_NRF5340_CPUAPP + default y + +endif # BOARD_NRF7002DK_NRF5340_CPUAPP || BOARD_NRF7002DK_NRF7001_NRF5340_CPUAPP config BOOT_IMAGE_ACCESS_HOOKS default y if SOC_SERIES_NRF53X config UPDATEABLE_IMAGE_NUMBER + default 3 if NRF_WIFI_PATCHES_EXT_FLASH_STORE default 2 if SOC_SERIES_NRF53X +config DFU_MULTI_IMAGE_MAX_IMAGE_COUNT + default 3 if NRF_WIFI_PATCHES_EXT_FLASH_STORE + +config NRF_WIFI_FW_PATCH_DFU + default y if NRF_WIFI_PATCHES_EXT_FLASH_STORE + # ============================================================================== # OpenThread configuration # ============================================================================== @@ -318,13 +334,13 @@ if PSA_CRYPTO_DRIVER_CC3XX && PSA_CRYPTO_DRIVER_OBERON config PSA_USE_CC3XX_HASH_DRIVER default n -endif +endif # PSA_CRYPTO_DRIVER_CC3XX && PSA_CRYPTO_DRIVER_OBERON # Spake2+ support config MBEDTLS_MD_C default y -endif +endif # CHIP_CRYPTO_PSA if !CHIP_CRYPTO_PSA @@ -367,7 +383,7 @@ config MBEDTLS_ECP_C config MBEDTLS_ECP_DP_SECP256R1_ENABLED default y -endif +endif # !CHIP_CRYPTO_PSA config MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG default n if CHIP_WIFI @@ -487,4 +503,4 @@ config OPENTHREAD_SHELL endif # SHELL -endif \ No newline at end of file +endif # CHIP diff --git a/config/nrfconnect/chip-module/Kconfig.features b/config/nrfconnect/chip-module/Kconfig.features index 369f992c9a5070..667894c7696d85 100644 --- a/config/nrfconnect/chip-module/Kconfig.features +++ b/config/nrfconnect/chip-module/Kconfig.features @@ -21,7 +21,7 @@ if CHIP config CHIP_WIFI bool "Enable nrfconnect Wi-Fi support" - default y if SHIELD_NRF7002EK || BOARD_NRF7002DK_NRF5340_CPUAPP || SHIELD_NRF7002EB + default y if SHIELD_NRF7002EK || BOARD_NRF7002DK_NRF5340_CPUAPP || SHIELD_NRF7002EB || BOARD_NRF7002DK_NRF7001_NRF5340_CPUAPP select WIFI_NRF700X select WIFI select WPA_SUPP @@ -42,15 +42,13 @@ config CHIP_WIFI config CHIP_QSPI_NOR bool "Enable QSPI NOR feature set" + imply NORDIC_QSPI_NOR help Enables QSPI NOR flash with a set of options for configuring pages and buffer sizes. if CHIP_QSPI_NOR -config NORDIC_QSPI_NOR - default y - config NORDIC_QSPI_NOR_STACK_WRITE_BUFFER_SIZE default 16 @@ -151,7 +149,7 @@ endif config CHIP_DFU_OVER_BT_SMP bool "Enable DFU over Bluetooth LE SMP feature set" imply CHIP_QSPI_NOR if BOARD_NRF5340DK_NRF5340_CPUAPP || BOARD_NRF52840DK_NRF52840 - imply CHIP_SPI_NOR if BOARD_NRF7002DK_NRF5340_CPUAPP + imply CHIP_SPI_NOR if BOARD_NRF7002DK_NRF5340_CPUAPP || BOARD_NRF7002DK_NRF7001_NRF5340_CPUAPP imply BOOTLOADER_MCUBOOT select MCUMGR select MCUMGR_TRANSPORT_BT diff --git a/config/nrfconnect/chip-module/Kconfig.mcuboot.defaults b/config/nrfconnect/chip-module/Kconfig.mcuboot.defaults index 31759beba22ffc..11c7dd0320f464 100644 --- a/config/nrfconnect/chip-module/Kconfig.mcuboot.defaults +++ b/config/nrfconnect/chip-module/Kconfig.mcuboot.defaults @@ -19,16 +19,7 @@ config MAIN_STACK_SIZE default 10240 -config BOOT_SWAP_SAVE_ENCTLV - default n - -config BOOT_ENCRYPT_RSA - default n - -config BOOT_ENCRYPT_EC256 - default n - -config BOOT_ENCRYPT_X25519 +config BOOT_ENCRYPT_IMAGE default n config BOOT_BOOTSTRAP @@ -48,14 +39,11 @@ choice LIBC_IMPLEMENTATION endchoice # nRF7002DK uses SPI NOR external flash -if BOARD_NRF7002DK_NRF5340_CPUAPP +if BOARD_NRF7002DK_NRF5340_CPUAPP || BOARD_NRF7002DK_NRF7001_NRF5340_CPUAPP config SPI default y -config SPI_NOR - default y - choice SPI_NOR_SFDP default SPI_NOR_SFDP_DEVICETREE endchoice @@ -74,9 +62,6 @@ endif # All boards beside nRF7002DK use QSPI NOR external flash if BOARD_NRF5340DK_NRF5340_CPUAPP || BOARD_NRF52840DK_NRF52840 -config NORDIC_QSPI_NOR - default y - config NORDIC_QSPI_NOR_FLASH_LAYOUT_PAGE_SIZE default 4096 diff --git a/config/nrfconnect/chip-module/generate_factory_data.cmake b/config/nrfconnect/chip-module/generate_factory_data.cmake index 21f7360cd03f10..b1f4ad153c4fb9 100644 --- a/config/nrfconnect/chip-module/generate_factory_data.cmake +++ b/config/nrfconnect/chip-module/generate_factory_data.cmake @@ -129,9 +129,21 @@ set(factory_data_output_path ${output_path}/${factory_data_target}) string(APPEND script_args "-o \"${factory_data_output_path}\"\n") string(APPEND script_args "-s \"${schema_path}\"\n") -# Add optional offset and size arguments to generate both .hex and .json files. -string(APPEND script_args "--offset $\n") -string(APPEND script_args "--size $\n") +# Add optional offset and size arguments to generate .hex file as well as .json. +if(CONFIG_PARTITION_MANAGER_ENABLED) + string(APPEND script_args "--offset $\n") + string(APPEND script_args "--size $\n") +else() + dt_alias(factory_data_alias PROPERTY "factory-data") + dt_node_exists(factory_data_exists PATH "${factory_data_alias}") + if(NOT ${factory_data_exists}) + message(FATAL_ERROR "factory-data alias does not exist in DTS") + endif() + dt_reg_addr(factory_data_addr PATH ${factory_data_alias}) + dt_reg_size(factory_data_size PATH ${factory_data_alias}) + string(APPEND script_args "--offset ${factory_data_addr}\n") + string(APPEND script_args "--size ${factory_data_size}\n") +endif() # execute first script to create a JSON file separate_arguments(separated_script_args NATIVE_COMMAND ${script_args}) @@ -175,10 +187,15 @@ nrfconnect_create_factory_data(factory_data ${FACTORY_DATA_SCHEMA_PATH} ${OUTPUT_FILE_PATH}) -if(CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE) - # set custom target for merging factory_data hex file - set_property(GLOBAL PROPERTY factory_data_PM_HEX_FILE ${OUTPUT_FILE_PATH}/factory_data.hex) - set_property(GLOBAL PROPERTY factory_data_PM_TARGET factory_data) +if(CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE) + if(CONFIG_PARTITION_MANAGER_ENABLED) + # set custom target for merging factory_data hex file + set_property(GLOBAL PROPERTY factory_data_PM_HEX_FILE ${OUTPUT_FILE_PATH}/factory_data.hex) + set_property(GLOBAL PROPERTY factory_data_PM_TARGET factory_data) + else() + set_property(GLOBAL APPEND PROPERTY HEX_FILES_TO_MERGE ${OUTPUT_FILE_PATH}/factory_data.hex ${OUTPUT_FILE_PATH}/zephyr.hex) + set_property(TARGET runners_yaml_props_target PROPERTY hex_file ${OUTPUT_FILE_PATH}/merged.hex) + endif() endif() diff --git a/config/zephyr/Kconfig b/config/zephyr/Kconfig index bdfa709592adff..95cea7cec1a707 100644 --- a/config/zephyr/Kconfig +++ b/config/zephyr/Kconfig @@ -95,6 +95,7 @@ config CHIP_DEVICE_HARDWARE_VERSION_STRING hardware version string is exposed as an attribute of the Basic Information cluster. +if "$(APPVERSION)"="" config CHIP_DEVICE_SOFTWARE_VERSION int "Software version" default 0 @@ -116,6 +117,7 @@ config CHIP_DEVICE_SOFTWARE_VERSION_STRING software version string is exposed as an attribute of the Basic Information cluster, and included in the header of the generated Matter over-the-air (OTA) update image. +endif config CHIP_DEVICE_MANUFACTURING_DATE string "Manufacturing date (ISO 8601 format)" @@ -309,7 +311,8 @@ config CHIP_PROJECT_CONFIG config CHIP_ENABLE_DNSSD_SRP bool "OpenThread Service Registration Protocol" - default y if NET_L2_OPENTHREAD + default y + depends on NET_L2_OPENTHREAD imply OPENTHREAD_ECDSA imply OPENTHREAD_SRP_CLIENT help @@ -318,7 +321,8 @@ config CHIP_ENABLE_DNSSD_SRP config CHIP_ENABLE_DNS_CLIENT bool "OpenThread DNS client" - default y if NET_L2_OPENTHREAD + default y + depends on NET_L2_OPENTHREAD imply OPENTHREAD_DNS_CLIENT help Enables using the OpenThread DNS client for the Matter service discovery. @@ -413,6 +417,7 @@ config CHIP_THREAD_SSED config CHIP_OPENTHREAD_CONFIG string "Custom OpenThread configuration file" + depends on NET_L2_OPENTHREAD help Provides a path to an OpenThread configuration file. The path can be either absolute or relative to the application directory. When this option diff --git a/config/zephyr/ota-image.cmake b/config/zephyr/ota-image.cmake index bd7735648f8302..f254b97ea58b8a 100644 --- a/config/zephyr/ota-image.cmake +++ b/config/zephyr/ota-image.cmake @@ -31,18 +31,33 @@ function(chip_ota_image TARGET_NAME) endif() # Prepare ota_image_tool.py argument list - set(OTA_ARGS - "--vendor-id" - ${CONFIG_CHIP_DEVICE_VENDOR_ID} - "--product-id" - ${CONFIG_CHIP_DEVICE_PRODUCT_ID} - "--version" - ${CONFIG_CHIP_DEVICE_SOFTWARE_VERSION} - "--version-str" - ${CONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING} - "--digest-algorithm" - "sha256" - ) + if(DEFINED APPVERSION) + set(OTA_ARGS + "--vendor-id" + ${CONFIG_CHIP_DEVICE_VENDOR_ID} + "--product-id" + ${CONFIG_CHIP_DEVICE_PRODUCT_ID} + "--version" + ${APPVERSION} + "--version-str" + ${APP_VERSION_TWEAK_STRING} + "--digest-algorithm" + "sha256" + ) + else() + set(OTA_ARGS + "--vendor-id" + ${CONFIG_CHIP_DEVICE_VENDOR_ID} + "--product-id" + ${CONFIG_CHIP_DEVICE_PRODUCT_ID} + "--version" + ${CONFIG_CHIP_DEVICE_SOFTWARE_VERSION} + "--version-str" + ${CONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING} + "--digest-algorithm" + "sha256" + ) + endif() separate_arguments(OTA_EXTRA_ARGS NATIVE_COMMAND "${CHIP_OTA_IMAGE_EXTRA_ARGS}") diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp index 68c550723de141..35c547f4d52d25 100644 --- a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp +++ b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp @@ -373,6 +373,14 @@ template CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::_AttachToThreadNetwork( const Thread::OperationalDataset & dataset, NetworkCommissioning::Internal::WirelessDriver::ConnectCallback * callback) { + Thread::OperationalDataset current_dataset; + // Validate the dataset change with the current state + ThreadStackMgrImpl().GetThreadProvision(current_dataset); + if (dataset.AsByteSpan().data_equal(current_dataset.AsByteSpan()) && callback == nullptr) + { + return CHIP_NO_ERROR; + } + // Reset the previously set callback since it will never be called in case incorrect dataset was supplied. mpConnectCallback = nullptr; ReturnErrorOnFailure(Impl()->SetThreadEnabled(false)); diff --git a/src/platform/Zephyr/BLEAdvertisingArbiter.cpp b/src/platform/Zephyr/BLEAdvertisingArbiter.cpp index 29f55168f1c627..4356ba9aa146ea 100644 --- a/src/platform/Zephyr/BLEAdvertisingArbiter.cpp +++ b/src/platform/Zephyr/BLEAdvertisingArbiter.cpp @@ -29,6 +29,9 @@ namespace { // List of advertising requests ordered by priority sys_slist_t sRequests; +bool sIsInitialized = false; +uint8_t sBtId = 0; + // Cast an intrusive list node to the containing request object const BLEAdvertisingArbiter::Request & ToRequest(const sys_snode_t * node) { @@ -55,8 +58,9 @@ CHIP_ERROR RestartAdvertising() ReturnErrorOnFailure(System::MapErrorZephyr(bt_le_adv_stop())); ReturnErrorCodeIf(sys_slist_is_empty(&sRequests), CHIP_NO_ERROR); - const Request & top = ToRequest(sys_slist_peek_head(&sRequests)); - const bt_le_adv_param params = BT_LE_ADV_PARAM_INIT(top.options, top.minInterval, top.maxInterval, nullptr); + const Request & top = ToRequest(sys_slist_peek_head(&sRequests)); + bt_le_adv_param params = BT_LE_ADV_PARAM_INIT(top.options, top.minInterval, top.maxInterval, nullptr); + params.id = sBtId; const int result = bt_le_adv_start(¶ms, top.advertisingData.data(), top.advertisingData.size(), top.scanResponseData.data(), top.scanResponseData.size()); @@ -70,8 +74,26 @@ CHIP_ERROR RestartAdvertising() } // namespace +CHIP_ERROR Init(uint8_t btId) +{ + if (sIsInitialized) + { + return CHIP_ERROR_INCORRECT_STATE; + } + + sBtId = btId; + sIsInitialized = true; + + return CHIP_NO_ERROR; +} + CHIP_ERROR InsertRequest(Request & request) { + if (!sIsInitialized) + { + return CHIP_ERROR_INCORRECT_STATE; + } + CancelRequest(request); sys_snode_t * prev = nullptr; @@ -109,6 +131,11 @@ CHIP_ERROR InsertRequest(Request & request) void CancelRequest(Request & request) { + if (!sIsInitialized) + { + return; + } + const bool isTopPriority = (sys_slist_peek_head(&sRequests) == &request); VerifyOrReturn(sys_slist_find_and_remove(&sRequests, &request)); diff --git a/src/platform/Zephyr/BLEAdvertisingArbiter.h b/src/platform/Zephyr/BLEAdvertisingArbiter.h index 6176c6cedb997d..a336b1c35dac4d 100644 --- a/src/platform/Zephyr/BLEAdvertisingArbiter.h +++ b/src/platform/Zephyr/BLEAdvertisingArbiter.h @@ -61,6 +61,18 @@ struct Request : public sys_snode_t OnAdvertisingStopped onStopped; ///< (Optional) Callback invoked when the request stops being top-priority. }; +/** + * @brief Initialize BLE advertising arbiter + * + * @note This method must be called before trying to insert or cancel any requests. + * + * @param btId Local Bluetooth LE identifier to be used for the advertising parameters. Currently Bluetooth LE identifier used in + * this method will be used for all advertising requests and changing it dynamically is not supported. + * @return error If the module is already initialized. + * @return success Otherwise. + */ +CHIP_ERROR Init(uint8_t btId); + /** * @brief Request BLE advertising * @@ -74,6 +86,9 @@ struct Request : public sys_snode_t * @note This method does not take ownership of the request object so the object * must not get destroyed before it is cancelled. * + * @note The arbiter module has to be initialized using Init() method before + * invoking this method. + * * @param request Reference to advertising request that contains priority and * other advertising parameters. * @return error If the request is top-priority and failed to restart the @@ -94,6 +109,9 @@ CHIP_ERROR InsertRequest(Request & request); * An attempt to cancel a request that has not been registered at the * advertising arbiter is a no-op. That is, it returns immediately. * + * @note The arbiter module has to be initialized using Init() method before + * invoking this method. + * * @param request Reference to advertising request that contains priority and * other advertising parameters. */ diff --git a/src/platform/Zephyr/BLEManagerImpl.cpp b/src/platform/Zephyr/BLEManagerImpl.cpp index d4e83332452a06..c46a9226966d3e 100644 --- a/src/platform/Zephyr/BLEManagerImpl.cpp +++ b/src/platform/Zephyr/BLEManagerImpl.cpp @@ -44,6 +44,10 @@ #include #include +#ifdef CONFIG_BT_BONDABLE +#include +#endif // CONFIG_BT_BONDABLE + #include using namespace ::chip; @@ -107,7 +111,13 @@ bt_gatt_service sChipoBleService = BT_GATT_SERVICE(sChipoBleAttributes); // This value should be adjusted accordingly if the service declaration changes. constexpr int kCHIPoBLE_CCC_AttributeIndex = 3; -CHIP_ERROR InitRandomStaticAddress() +#ifdef CONFIG_BT_BONDABLE +constexpr uint8_t kMatterBleIdentity = 1; +#else +constexpr uint8_t kMatterBleIdentity = 0; +#endif // CONFIG_BT_BONDABLE + +int InitRandomStaticAddress(bool idPresent, int & id) { // Generate a random static address for the default identity. // This must be done before bt_enable() as after that updating the default identity is not possible. @@ -122,20 +132,29 @@ CHIP_ERROR InitRandomStaticAddress() if (error) { ChipLogError(DeviceLayer, "Failed to create BLE address: %d", error); - return System::MapErrorZephyr(error); + return error; } - error = bt_id_create(&addr, nullptr); + if (!idPresent) + { + id = bt_id_create(&addr, nullptr); + } +#if CONFIG_BT_ID_MAX == 2 + else + { + id = bt_id_reset(1, &addr, nullptr); + } +#endif // CONFIG_BT_BONDABLE - if (error < 0) + if (id < 0) { ChipLogError(DeviceLayer, "Failed to create BLE identity: %d", error); - return System::MapErrorZephyr(error); + return id; } 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; + return 0; } } // unnamed namespace @@ -144,17 +163,42 @@ BLEManagerImpl BLEManagerImpl::sInstance; CHIP_ERROR BLEManagerImpl::_Init() { + int err = 0; + int id = 0; + mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); mFlags.Set(Flags::kFastAdvertisingEnabled, true); - mGAPConns = 0; + mMatterConnNum = 0; + mTotalConnNum = 0; memset(mSubscribedConns, 0, sizeof(mSubscribedConns)); - ReturnErrorOnFailure(InitRandomStaticAddress()); - int err = bt_enable(NULL); +#ifdef CONFIG_BT_BONDABLE + bt_addr_le_t idsAddr[CONFIG_BT_ID_MAX]; + size_t idsCount = CONFIG_BT_ID_MAX; + + err = bt_enable(nullptr); + VerifyOrReturnError(err == 0, MapErrorZephyr(err)); + settings_load(); + + bt_id_get(idsAddr, &idsCount); + + err = InitRandomStaticAddress(idsCount > 1, id); + + VerifyOrReturnError(err == 0 && id == kMatterBleIdentity, MapErrorZephyr(err)); + +#else + err = InitRandomStaticAddress(false, id); + VerifyOrReturnError(err == 0 && id == kMatterBleIdentity, MapErrorZephyr(err)); + err = bt_enable(nullptr); + VerifyOrReturnError(err == 0, MapErrorZephyr(err)); +#endif // CONFIG_BT_BONDABLE + + BLEAdvertisingArbiter::Init(static_cast(id)); + memset(&mConnCallbacks, 0, sizeof(mConnCallbacks)); mConnCallbacks.connected = HandleConnect; mConnCallbacks.disconnected = HandleDisconnect; @@ -199,7 +243,13 @@ void BLEManagerImpl::DriveBLEState() { mFlags.Clear(Flags::kAdvertisingRefreshNeeded); err = StartAdvertising(); - SuccessOrExit(err); + if (err != CHIP_NO_ERROR) + { + // Return prematurely but keep the CHIPoBLE service mode enabled to allow advertising retries + mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; + ChipLogError(DeviceLayer, "Could not start CHIPoBLE service due to error: %" CHIP_ERROR_FORMAT, err.Format()); + return; + } } } else @@ -207,7 +257,12 @@ void BLEManagerImpl::DriveBLEState() if (mFlags.Has(Flags::kAdvertising)) { err = StopAdvertising(); - SuccessOrExit(err); + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %" CHIP_ERROR_FORMAT, err.Format()); + mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; + return; + } } // If no connections are active unregister also CHIPoBLE GATT service @@ -224,13 +279,6 @@ void BLEManagerImpl::DriveBLEState() } } } - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %" CHIP_ERROR_FORMAT, err.Format()); - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; - } } struct BLEManagerImpl::ServiceData @@ -296,29 +344,53 @@ inline CHIP_ERROR BLEManagerImpl::PrepareAdvertisingRequest() else { ChipLogError(DeviceLayer, "Failed to start CHIPoBLE advertising: %d", rc); + BLEManagerImpl().StopAdvertising(); } }; return CHIP_NO_ERROR; } -CHIP_ERROR BLEManagerImpl::StartAdvertising() +CHIP_ERROR BLEManagerImpl::RegisterGattService() { - // Prepare advertising request - ReturnErrorOnFailure(PrepareAdvertisingRequest()); - - // Register dynamically CHIPoBLE GATT service + // Register CHIPoBLE GATT service if (!mFlags.Has(Flags::kChipoBleGattServiceRegister)) { int err = bt_gatt_service_register(&sChipoBleService); - if (err != 0) - ChipLogError(DeviceLayer, "Failed to register CHIPoBLE GATT service"); + { + ChipLogError(DeviceLayer, "Failed to register CHIPoBLE GATT service: %d", err); + } VerifyOrReturnError(err == 0, MapErrorZephyr(err)); - mFlags.Set(Flags::kChipoBleGattServiceRegister); } + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLEManagerImpl::UnregisterGattService() +{ + // Unregister CHIPoBLE GATT service + if (mFlags.Has(Flags::kChipoBleGattServiceRegister)) + { + int err = bt_gatt_service_unregister(&sChipoBleService); + if (err != 0) + { + ChipLogError(DeviceLayer, "Failed to unregister CHIPoBLE GATT service: %d", err); + } + + VerifyOrReturnError(err == 0, MapErrorZephyr(err)); + mFlags.Clear(Flags::kChipoBleGattServiceRegister); + } + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLEManagerImpl::StartAdvertising() +{ + // Prepare advertising request + ReturnErrorOnFailure(PrepareAdvertisingRequest()); + // We need to register GATT service before issuing the advertising to start + ReturnErrorOnFailure(RegisterGattService()); // Initialize C3 characteristic data #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING @@ -326,7 +398,13 @@ CHIP_ERROR BLEManagerImpl::StartAdvertising() #endif // Request advertising - ReturnErrorOnFailure(BLEAdvertisingArbiter::InsertRequest(mAdvertisingRequest)); + CHIP_ERROR err = BLEAdvertisingArbiter::InsertRequest(mAdvertisingRequest); + if (CHIP_NO_ERROR != err) + { + // It makes not sense to keep GATT services registered after the advertising request failed + (void) UnregisterGattService(); + return err; + } // Transition to the Advertising state... if (!mFlags.Has(Flags::kAdvertising)) @@ -388,22 +466,23 @@ CHIP_ERROR BLEManagerImpl::StopAdvertising() DeviceLayer::SystemLayer().CancelTimer(HandleSlowBLEAdvertisementInterval, this); DeviceLayer::SystemLayer().CancelTimer(HandleExtendedBLEAdvertisementInterval, this); } + else + { + ChipLogProgress(DeviceLayer, "CHIPoBLE advertising already stopped"); + } return CHIP_NO_ERROR; } CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) { - if (mFlags.Has(Flags::kAdvertisingEnabled) != val) - { - ChipLogDetail(DeviceLayer, "CHIPoBLE advertising set to %s", val ? "on" : "off"); + ChipLogDetail(DeviceLayer, "CHIPoBLE advertising set to %s", val ? "on" : "off"); - mFlags.Set(Flags::kAdvertisingEnabled, val); - // Ensure that each enabling/disabling of the standard advertising clears - // the extended mode flag. - mFlags.Set(Flags::kExtendedAdvertisingEnabled, false); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - } + mFlags.Set(Flags::kAdvertisingEnabled, val); + // Ensure that each enabling/disabling of the general advertising clears + // the extended mode, to make sure we always start fresh in the regular mode + mFlags.Set(Flags::kExtendedAdvertisingEnabled, false); + PlatformMgr().ScheduleWork(DriveBLEState, 0); return CHIP_NO_ERROR; } @@ -452,15 +531,13 @@ CHIP_ERROR BLEManagerImpl::HandleGAPConnect(const ChipDeviceEvent * event) if (connEvent->HciResult == BT_HCI_ERR_SUCCESS) { ChipLogProgress(DeviceLayer, "BLE connection established (ConnId: 0x%02x)", bt_conn_index(connEvent->BtConn)); - mGAPConns++; + mMatterConnNum++; } 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); @@ -475,7 +552,10 @@ CHIP_ERROR BLEManagerImpl::HandleGAPDisconnect(const ChipDeviceEvent * event) ChipLogProgress(DeviceLayer, "BLE GAP connection terminated (reason 0x%02x)", connEvent->HciResult); - mGAPConns--; + if (mMatterConnNum > 0) + { + mMatterConnNum--; + } // If indications were enabled for this connection, record that they are now disabled and // notify the BLE Layer of a disconnect. @@ -503,8 +583,6 @@ CHIP_ERROR BLEManagerImpl::HandleGAPDisconnect(const ChipDeviceEvent * event) // 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)); @@ -664,7 +742,7 @@ void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) uint16_t BLEManagerImpl::_NumConnections(void) { - return mGAPConns; + return mMatterConnNum; } bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) @@ -839,9 +917,16 @@ void BLEManagerImpl::HandleTXIndicated(struct bt_conn * conId, bt_gatt_indicate_ void BLEManagerImpl::HandleConnect(struct bt_conn * conId, uint8_t err) { ChipDeviceEvent event; + bt_conn_info bt_info; PlatformMgr().LockChipStack(); + sInstance.mTotalConnNum++; + ChipLogProgress(DeviceLayer, "Current number of connections: %u/%u", sInstance.mTotalConnNum, CONFIG_BT_MAX_CONN); + + VerifyOrExit(bt_conn_get_info(conId, &bt_info) == 0, ); + // Drop all callbacks incoming for the role other than peripheral, required by the Matter accessory + VerifyOrExit(bt_info.role == BT_CONN_ROLE_PERIPHERAL, ); // Don't handle BLE connecting events when it is not related to CHIPoBLE VerifyOrExit(sInstance.mFlags.Has(Flags::kChipoBleGattServiceRegister), ); @@ -858,9 +943,20 @@ void BLEManagerImpl::HandleConnect(struct bt_conn * conId, uint8_t err) void BLEManagerImpl::HandleDisconnect(struct bt_conn * conId, uint8_t reason) { ChipDeviceEvent event; + bt_conn_info bt_info; PlatformMgr().LockChipStack(); + if (sInstance.mTotalConnNum > 0) + { + sInstance.mTotalConnNum--; + } + + ChipLogProgress(DeviceLayer, "Current number of connections: %u/%u", sInstance.mTotalConnNum, CONFIG_BT_MAX_CONN); + + VerifyOrExit(bt_conn_get_info(conId, &bt_info) == 0, ); + // Drop all callbacks incoming for the role other than peripheral, required by the Matter accessory + VerifyOrExit(bt_info.role == BT_CONN_ROLE_PERIPHERAL, ); // Don't handle BLE disconnecting events when it is not related to CHIPoBLE VerifyOrExit(sInstance.mFlags.Has(Flags::kChipoBleGattServiceRegister), ); diff --git a/src/platform/Zephyr/BLEManagerImpl.h b/src/platform/Zephyr/BLEManagerImpl.h index 4fb3352a01ee2b..10ecdf0226b022 100644 --- a/src/platform/Zephyr/BLEManagerImpl.h +++ b/src/platform/Zephyr/BLEManagerImpl.h @@ -97,7 +97,7 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla struct ServiceData; BitFlags mFlags; - uint16_t mGAPConns; + uint16_t mMatterConnNum; CHIPoBLEServiceMode mServiceMode; bool mSubscribedConns[CONFIG_BT_MAX_CONN]; bt_gatt_indicate_params mIndicateParams[CONFIG_BT_MAX_CONN]; @@ -106,6 +106,8 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING PacketBufferHandle c3CharDataBufferHandle; #endif + // The summarized number of Bluetooth LE connections related to the device (including these not related to Matter service). + uint16_t mTotalConnNum; void DriveBLEState(void); CHIP_ERROR PrepareAdvertisingRequest(); @@ -123,6 +125,8 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla bool SetSubscribed(bt_conn * conn); bool UnsetSubscribed(bt_conn * conn); uint32_t GetAdvertisingInterval(); + CHIP_ERROR RegisterGattService(); + CHIP_ERROR UnregisterGattService(); static void DriveBLEState(intptr_t arg); diff --git a/src/platform/Zephyr/ConfigurationManagerImpl.cpp b/src/platform/Zephyr/ConfigurationManagerImpl.cpp index f41eed0492080f..2e937c95f0f9e0 100644 --- a/src/platform/Zephyr/ConfigurationManagerImpl.cpp +++ b/src/platform/Zephyr/ConfigurationManagerImpl.cpp @@ -40,6 +40,10 @@ #include #endif +#ifdef CONFIG_NET_L2_OPENTHREAD +#include +#endif + namespace chip { namespace DeviceLayer { @@ -179,6 +183,11 @@ void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) { ChipLogProgress(DeviceLayer, "Performing factory reset"); +// Lock the Thread stack to avoid unwanted interaction with settings NVS during factory reset. +#ifdef CONFIG_NET_L2_OPENTHREAD + ThreadStackMgr().LockThreadStack(); +#endif + #ifdef CONFIG_CHIP_FACTORY_RESET_ERASE_NVS void * storage = nullptr; int status = settings_storage_get(&storage); diff --git a/src/platform/nrfconnect/CHIPDevicePlatformConfig.h b/src/platform/nrfconnect/CHIPDevicePlatformConfig.h index f9e445f35fb3d4..991c3689425ae7 100644 --- a/src/platform/nrfconnect/CHIPDevicePlatformConfig.h +++ b/src/platform/nrfconnect/CHIPDevicePlatformConfig.h @@ -23,6 +23,9 @@ #pragma once +#ifndef CONFIG_CHIP_DEVICE_SOFTWARE_VERSION +#include "app_version.h" +#endif #include "autoconf.h" // ==================== Platform Adaptations ==================== @@ -33,8 +36,19 @@ #define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME CONFIG_CHIP_DEVICE_PRODUCT_NAME #define CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION CONFIG_CHIP_DEVICE_HARDWARE_VERSION #define CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING CONFIG_CHIP_DEVICE_HARDWARE_VERSION_STRING + +#ifdef CONFIG_CHIP_DEVICE_SOFTWARE_VERSION #define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION CONFIG_CHIP_DEVICE_SOFTWARE_VERSION +#else +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION APPVERSION +#endif + +#ifdef CONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING #define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING CONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING +#else +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING APP_VERSION_TWEAK_STRING +#endif + #define CHIP_DEVICE_CONFIG_TEST_MANUFACTURING_DATE CONFIG_CHIP_DEVICE_MANUFACTURING_DATE #define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER CONFIG_CHIP_DEVICE_SERIAL_NUMBER #define CHIP_DEVICE_CONFIG_DEVICE_TYPE CONFIG_CHIP_DEVICE_TYPE @@ -161,7 +175,11 @@ #endif // CHIP_DEVICE_CONFIG_CHIP_TASK_PRIORITY #ifndef CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE +#if defined(CONFIG_LTO) +#define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE 10240 +#else #define CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE 6144 +#endif // CONFIG_LTO #endif // CHIP_DEVICE_CONFIG_CHIP_TASK_STACK_SIZE #define CHIP_DEVICE_CONFIG_MAX_EVENT_QUEUE_SIZE 64 diff --git a/src/platform/nrfconnect/FactoryDataProvider.cpp b/src/platform/nrfconnect/FactoryDataProvider.cpp index 11995faccd8272..aaa6f4b93e12bb 100644 --- a/src/platform/nrfconnect/FactoryDataProvider.cpp +++ b/src/platform/nrfconnect/FactoryDataProvider.cpp @@ -432,7 +432,10 @@ CHIP_ERROR FactoryDataProvider::GetUserKey(const char * userKe // Fully instantiate the template class in whatever compilation unit includes this file. template class FactoryDataProvider; +#if defined(USE_PARTITION_MANAGER) && USE_PARTITION_MANAGER == 1 && (defined(CONFIG_CHIP_QSPI_NOR) || defined(CONFIG_CHIP_SPI_NOR)) template class FactoryDataProvider; +#endif // if defined(USE_PARTITION_MANAGER) && USE_PARTITION_MANAGER == 1 (defined(CONFIG_CHIP_QSPI_NOR) || + // defined(CONFIG_CHIP_SPI_NOR)) } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/nrfconnect/FactoryDataProvider.h b/src/platform/nrfconnect/FactoryDataProvider.h index bc1ef16ee6d161..ef6c8ffa66185f 100644 --- a/src/platform/nrfconnect/FactoryDataProvider.h +++ b/src/platform/nrfconnect/FactoryDataProvider.h @@ -25,8 +25,20 @@ #include #endif +#ifdef CONFIG_FPROTECT #include +#endif // if CONFIG_FPROTECT + +#if defined(USE_PARTITION_MANAGER) && USE_PARTITION_MANAGER == 1 #include +#define FACTORY_DATA_ADDRESS PM_FACTORY_DATA_ADDRESS +#define FACTORY_DATA_SIZE PM_FACTORY_DATA_SIZE +#else +#include +#define FACTORY_DATA_SIZE DT_REG_SIZE(DT_ALIAS(factory_data)) +#define FACTORY_DATA_ADDRESS DT_REG_ADDR(DT_ALIAS(factory_data)) +#endif // if defined(USE_PARTITION_MANAGER) && USE_PARTITION_MANAGER == 1 + #include #include @@ -39,8 +51,8 @@ struct InternalFlashFactoryData { CHIP_ERROR GetFactoryDataPartition(uint8_t *& data, size_t & dataSize) { - data = reinterpret_cast(PM_FACTORY_DATA_ADDRESS); - dataSize = PM_FACTORY_DATA_SIZE; + data = reinterpret_cast(FACTORY_DATA_ADDRESS); + dataSize = FACTORY_DATA_SIZE; return CHIP_NO_ERROR; } @@ -54,8 +66,8 @@ struct InternalFlashFactoryData // the application code at runtime anyway. constexpr size_t FactoryDataBlockBegin() { - // calculate the nearest multiple of CONFIG_FPROTECT_BLOCK_SIZE smaller than PM_FACTORY_DATA_ADDRESS - return PM_FACTORY_DATA_ADDRESS & (-CONFIG_FPROTECT_BLOCK_SIZE); + // calculate the nearest multiple of CONFIG_FPROTECT_BLOCK_SIZE smaller than FACTORY_DATA_ADDRESS + return FACTORY_DATA_ADDRESS & (-CONFIG_FPROTECT_BLOCK_SIZE); } constexpr size_t FactoryDataBlockSize() @@ -63,7 +75,7 @@ struct InternalFlashFactoryData // calculate the factory data end address rounded up to the nearest multiple of CONFIG_FPROTECT_BLOCK_SIZE // and make sure we do not overlap with settings partition constexpr size_t kFactoryDataBlockEnd = - (PM_FACTORY_DATA_ADDRESS + PM_FACTORY_DATA_SIZE + CONFIG_FPROTECT_BLOCK_SIZE - 1) & (-CONFIG_FPROTECT_BLOCK_SIZE); + (FACTORY_DATA_ADDRESS + FACTORY_DATA_SIZE + CONFIG_FPROTECT_BLOCK_SIZE - 1) & (-CONFIG_FPROTECT_BLOCK_SIZE); static_assert(kFactoryDataBlockEnd <= PM_SETTINGS_STORAGE_ADDRESS, "FPROTECT memory block, which contains factory data" "partition overlaps with the settings partition." @@ -75,19 +87,24 @@ struct InternalFlashFactoryData #undef TO_STR_IMPL CHIP_ERROR ProtectFactoryDataPartitionAgainstWrite() { +#ifdef CONFIG_FPROTECT int ret = fprotect_area(FactoryDataBlockBegin(), FactoryDataBlockSize()); return System::MapErrorZephyr(ret); +#else + return CHIP_ERROR_NOT_IMPLEMENTED; +#endif // if CONFIG_FPROTECT } #else CHIP_ERROR ProtectFactoryDataPartitionAgainstWrite() { return CHIP_ERROR_NOT_IMPLEMENTED; } #endif }; +#if defined(USE_PARTITION_MANAGER) && USE_PARTITION_MANAGER == 1 && (defined(CONFIG_CHIP_QSPI_NOR) || defined(CONFIG_CHIP_SPI_NOR)) struct ExternalFlashFactoryData { CHIP_ERROR GetFactoryDataPartition(uint8_t *& data, size_t & dataSize) { - int ret = flash_read(mFlashDevice, PM_FACTORY_DATA_ADDRESS, mFactoryDataBuffer, PM_FACTORY_DATA_SIZE); + int ret = flash_read(mFlashDevice, FACTORY_DATA_ADDRESS, mFactoryDataBuffer, FACTORY_DATA_SIZE); if (ret != 0) { @@ -95,24 +112,69 @@ struct ExternalFlashFactoryData } data = mFactoryDataBuffer; - dataSize = PM_FACTORY_DATA_SIZE; + dataSize = FACTORY_DATA_SIZE; return CHIP_NO_ERROR; } CHIP_ERROR ProtectFactoryDataPartitionAgainstWrite() { return CHIP_ERROR_NOT_IMPLEMENTED; } - const struct device * mFlashDevice = DEVICE_DT_GET(DT_CHOSEN(zephyr_flash_controller)); - uint8_t mFactoryDataBuffer[PM_FACTORY_DATA_SIZE]; + const struct device * mFlashDevice = DEVICE_DT_GET(DT_CHOSEN(nordic_pm_ext_flash)); + uint8_t mFactoryDataBuffer[FACTORY_DATA_SIZE]; +}; +#endif // if defined(USE_PARTITION_MANAGER) && USE_PARTITION_MANAGER == 1 && (defined(CONFIG_CHIP_QSPI_NOR) || + // defined(CONFIG_CHIP_SPI_NOR)) + +class FactoryDataProviderBase : public chip::Credentials::DeviceAttestationCredentialsProvider, + public CommissionableDataProvider, + public DeviceInstanceInfoProvider +{ +public: + /** + * @brief Perform all operations needed to initialize factory data provider. + * + * @returns CHIP_NO_ERROR in case of a success, specific error code otherwise + */ + virtual CHIP_ERROR Init() = 0; + + /** + * @brief Get the EnableKey as MutableByteSpan + * + * @param enableKey MutableByteSpan object to obtain EnableKey + * @returns + * CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND if factory data does not contain enable_key field, or the value cannot be read + * out. CHIP_ERROR_BUFFER_TOO_SMALL if provided MutableByteSpan is too small + */ + virtual CHIP_ERROR GetEnableKey(MutableByteSpan & enableKey) = 0; + + /** + * @brief Get the user data in CBOR format as MutableByteSpan + * + * @param userData MutableByteSpan object to obtain all user data in CBOR format + * @returns + * CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND if factory data does not contain user field, or the value cannot be read out. + * CHIP_ERROR_BUFFER_TOO_SMALL if provided MutableByteSpan is too small + */ + virtual CHIP_ERROR GetUserData(MutableByteSpan & userData) = 0; + + /** + * @brief Try to find user data key and return its value + * + * @param userKey A key name to be found + * @param buf Buffer to store value of found key + * @param len Length of the buffer. This value will be updated to the actual value if the key is read. + * @returns + * CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND if factory data does not contain user key field, or the value cannot be read + * out. CHIP_ERROR_BUFFER_TOO_SMALL if provided buffer length is too small + */ + virtual CHIP_ERROR GetUserKey(const char * userKey, void * buf, size_t & len) = 0; }; template -class FactoryDataProvider : public chip::Credentials::DeviceAttestationCredentialsProvider, - public CommissionableDataProvider, - public DeviceInstanceInfoProvider +class FactoryDataProvider : public FactoryDataProviderBase { public: - CHIP_ERROR Init(); + CHIP_ERROR Init() override; // ===== Members functions that implement the DeviceAttestationCredentialsProvider CHIP_ERROR GetCertificationDeclaration(MutableByteSpan & outBuffer) override; @@ -147,33 +209,13 @@ class FactoryDataProvider : public chip::Credentials::DeviceAttestationCredentia CHIP_ERROR GetProductPrimaryColor(app::Clusters::BasicInformation::ColorEnum * primaryColor) override; // ===== Members functions that are platform-specific - CHIP_ERROR GetEnableKey(MutableByteSpan & enableKey); - - /** - * @brief Get the user data in CBOR format as MutableByteSpan - * - * @param userData MutableByteSpan object to obtain all user data in CBOR format - * @returns - * CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND if factory data does not contain user field, or the value cannot be read out. - * CHIP_ERROR_BUFFER_TOO_SMALL if provided MutableByteSpan is too small - */ - CHIP_ERROR GetUserData(MutableByteSpan & userData); - - /** - * @brief Try to find user data key and return its value - * - * @param userKey A key name to be found - * @param buf Buffer to store value of found key - * @param len Length of the buffer. This value will be updated to the actual value if the key is read. - * @returns - * CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND if factory data does not contain user field, or the value cannot be read out. - * CHIP_ERROR_BUFFER_TOO_SMALL if provided buffer length is too small - */ - CHIP_ERROR GetUserKey(const char * userKey, void * buf, size_t & len); + CHIP_ERROR GetEnableKey(MutableByteSpan & enableKey) override; + CHIP_ERROR GetUserData(MutableByteSpan & userData) override; + CHIP_ERROR GetUserKey(const char * userKey, void * buf, size_t & len) override; private: - static constexpr uint16_t kFactoryDataPartitionSize = PM_FACTORY_DATA_SIZE; - static constexpr uint32_t kFactoryDataPartitionAddress = PM_FACTORY_DATA_ADDRESS; + static constexpr uint16_t kFactoryDataPartitionSize = FACTORY_DATA_SIZE; + static constexpr uint32_t kFactoryDataPartitionAddress = FACTORY_DATA_ADDRESS; static constexpr uint8_t kDACPrivateKeyLength = 32; static constexpr uint8_t kDACPublicKeyLength = 65; diff --git a/src/platform/nrfconnect/SystemPlatformConfig.h b/src/platform/nrfconnect/SystemPlatformConfig.h index ce0df4d5f69ff5..1165bb203456e8 100644 --- a/src/platform/nrfconnect/SystemPlatformConfig.h +++ b/src/platform/nrfconnect/SystemPlatformConfig.h @@ -48,7 +48,7 @@ struct ChipDeviceEvent; #define CHIP_SYSTEM_CONFIG_USE_SOCKETS 1 #ifndef CONFIG_ARCH_POSIX -#define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 8 +#define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 15 #endif // ========== Platform-specific Configuration Overrides ========= diff --git a/src/platform/nrfconnect/wifi/WiFiManager.cpp b/src/platform/nrfconnect/wifi/WiFiManager.cpp index d5783fa060c558..11784f4475cfe0 100644 --- a/src/platform/nrfconnect/wifi/WiFiManager.cpp +++ b/src/platform/nrfconnect/wifi/WiFiManager.cpp @@ -189,7 +189,22 @@ CHIP_ERROR WiFiManager::Scan(const ByteSpan & ssid, ScanResultCallback resultCal mWiFiState = WIFI_STATE_SCANNING; mSsidFound = false; - if (0 != net_mgmt(NET_REQUEST_WIFI_SCAN, mNetIf, NULL, 0)) + wifi_scan_params * scanParams{ nullptr }; + size_t scanParamsSize{ 0 }; + + if (!ssid.empty()) + { + /* We must assume that the ssid is handled as a NULL-terminated string. + Note that the mScanSsidBuffer is initialized with zeros. */ + VerifyOrReturnError(ssid.size() < sizeof(mScanSsidBuffer), CHIP_ERROR_INVALID_ARGUMENT); + memcpy(mScanSsidBuffer, ssid.data(), ssid.size()); + mScanSsidBuffer[ssid.size()] = 0; // indicate the end of ssid string + mScanParams.ssids[0] = mScanSsidBuffer; + mScanParams.ssids[1] = nullptr; // indicate the end of ssids list + scanParams = &mScanParams; + scanParamsSize = sizeof(*scanParams); + } + if (0 != net_mgmt(NET_REQUEST_WIFI_SCAN, mNetIf, scanParams, scanParamsSize)) { ChipLogError(DeviceLayer, "Scan request failed"); return CHIP_ERROR_INTERNAL; diff --git a/src/platform/nrfconnect/wifi/WiFiManager.h b/src/platform/nrfconnect/wifi/WiFiManager.h index a4e3a8afb39256..0fa51e6fd6615e 100644 --- a/src/platform/nrfconnect/wifi/WiFiManager.h +++ b/src/platform/nrfconnect/wifi/WiFiManager.h @@ -222,7 +222,9 @@ class WiFiManager net_if * mNetIf{ nullptr }; ConnectionParams mWiFiParams{}; - ConnectionHandling mHandling; + ConnectionHandling mHandling{}; + wifi_scan_params mScanParams{}; + char mScanSsidBuffer[DeviceLayer::Internal::kMaxWiFiSSIDLength + 1] = { 0 }; wifi_iface_state mWiFiState; wifi_iface_state mCachedWiFiState; net_mgmt_event_callback mWiFiMgmtClbk{};