diff --git a/examples/lighting-app/silabs/SiWx917/BUILD.gn b/examples/lighting-app/silabs/SiWx917/BUILD.gn index 3a812b966d3361..61f849a88854f5 100644 --- a/examples/lighting-app/silabs/SiWx917/BUILD.gn +++ b/examples/lighting-app/silabs/SiWx917/BUILD.gn @@ -18,8 +18,8 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") +import("${efr32_sdk_build_root}/SiWx917_sdk.gni") import("${efr32_sdk_build_root}/efr32_executable.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -31,8 +31,8 @@ if (chip_enable_pw_rpc) { assert(current_os == "freertos") -efr32_project_dir = "${chip_root}/examples/lighting-app/silabs/efr32" -examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" +efr32_project_dir = "${chip_root}/examples/lighting-app/silabs/SiWx917" +examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" examples_common_plat_dir = "${chip_root}/examples/platform/silabs" declare_args() { @@ -56,13 +56,19 @@ declare_args() { sl_wfx_config_scan = true # Disable LCD on supported devices - disable_lcd = false + disable_lcd = true # Argument to Disable IPv4 for wifi(rs911) chip_enable_wifi_ipv4 = false # Argument to force enable WPA3 security on rs91x rs91x_wpa3_only = false + + #default WiFi SSID + ssid = "" + + #default Wifi Password + psk = "" } declare_args() { @@ -80,7 +86,7 @@ assert(!(use_wf200 && chip_enable_openthread)) if (chip_enable_wifi) { assert(use_rs911x || use_wf200) enable_openthread_cli = false - import("${chip_root}/src/platform/silabs/EFR32/wifi_args.gni") + import("${chip_root}/src/platform/silabs/SiWx917/wifi_args.gni") } # ThunderBoards, Explorer Kit and MGM240L do not support LCD (No LCD) @@ -90,6 +96,8 @@ if (silabs_board == "BRD4166A" || silabs_board == "BRD2601B" || disable_lcd = true } +defines = [] + # WiFi settings if (chip_enable_wifi) { # disabling LCD for MG24 for wifi @@ -97,7 +105,19 @@ if (chip_enable_wifi) { show_qr_code = false disable_lcd = true } - wifi_sdk_dir = "${chip_root}/src/platform/silabs/EFR32/wifi" + + if (ssid != "") { + defines += [ + "CHIP_ONNETWORK_PAIRING = 1", + "CHIP_WIFI_SSID = $ssid", + ] + } + if (psk != "") { + assert(ssid != "", "ssid can't be null if psk is provided") + defines += [ "CHIP_WIFI_PSK = $psk" ] + } + + wifi_sdk_dir = "${chip_root}/src/platform/silabs/SiWx917/wifi" efr32_lwip_defs = [ "LWIP_NETIF_API=1" ] if (lwip_ipv4) { efr32_lwip_defs += [ @@ -122,13 +142,8 @@ if (chip_enable_wifi) { efr32_lwip_defs += [ "LWIP_IPV6=0" ] } - if (use_rs911x) { - wiseconnect_sdk_root = - "${chip_root}/third_party/silabs/wiseconnect-wifi-bt-sdk" - import("${examples_plat_dir}/rs911x/rs911x.gni") - } else { - import("${examples_plat_dir}/wf200/wf200.gni") - } + wiseconnect_sdk_root = "${chip_root}/third_party/silabs/wisemcu-wifi-bt-sdk" + import("${examples_plat_dir}/SiWx917/rs911x.gni") } efr32_sdk("sdk") { @@ -138,22 +153,18 @@ efr32_sdk("sdk") { ] include_dirs = [ - "${chip_root}/src/platform/silabs/EFR32", + "${chip_root}/src/platform/silabs/SiWx917", "${efr32_project_dir}/include", "${examples_plat_dir}", "${chip_root}/src/lib", "${examples_common_plat_dir}", ] - defines = [ + defines += [ "BOARD_ID=${silabs_board}", "OTA_PERIODIC_TIMEOUT=${OTA_periodic_query_timeout}", ] - if (enable_heap_monitoring) { - defines += [ "HEAP_MONITORING" ] - } - if (chip_enable_pw_rpc) { defines += [ "HAL_VCOM_ENABLE=1", @@ -196,9 +207,9 @@ efr32_executable("lighting_app") { sources = [ "${examples_common_plat_dir}/heap_4_silabs.c", "${examples_plat_dir}/BaseApplication.cpp", - "${examples_plat_dir}/efr32_utils.cpp", - "${examples_plat_dir}/init_efrPlatform.cpp", + "${examples_plat_dir}/init_ccpPlatform.cpp", "${examples_plat_dir}/matter_config.cpp", + "${examples_plat_dir}/siwx917_utils.cpp", "src/AppTask.cpp", "src/LightingManager.cpp", "src/ZclCallbacks.cpp", @@ -206,12 +217,13 @@ efr32_executable("lighting_app") { ] if (use_wstk_leds) { - sources += [ "${examples_plat_dir}/LEDWidget.cpp" ] + # TODO: Commentting for CCP till the bring up of this is done + #sources += [ "${examples_plat_dir}/LEDWidget.cpp" ] } - if (chip_enable_pw_rpc || chip_build_libshell || enable_openthread_cli || - use_wf200 || use_rs911x) { - sources += [ "${examples_plat_dir}/uart.cpp" ] + if (chip_enable_pw_rpc || chip_build_libshell || use_rs911x) { + # TODO: Commentting for CCP till the bring up of this is done + #sources += [ "${examples_plat_dir}/uart.cpp" ] } deps = [ @@ -231,10 +243,7 @@ efr32_executable("lighting_app") { ] } - if (chip_enable_ota_requestor) { - defines += [ "EFR32_OTA_ENABLED" ] - sources += [ "${examples_plat_dir}/OTAConfig.cpp" ] - } + #TODO: OTA should be added # WiFi Settings if (chip_enable_wifi) { @@ -326,7 +335,7 @@ efr32_executable("lighting_app") { "${chip_root}/examples/common/pigweed:lighting_service.nanopb_rpc", "${chip_root}/examples/common/pigweed:ot_cli_service.nanopb_rpc", "${chip_root}/examples/common/pigweed:thread_service.nanopb_rpc", - "${examples_plat_dir}/pw_sys_io:pw_sys_io_efr32", + "${examples_plat_dir}/pw_sys_io:pw_sys_io_siwx917", ] deps += pw_build_LINK_DEPS @@ -365,7 +374,7 @@ efr32_executable("lighting_app") { # Attestation Credentials if (chip_build_platform_attestation_credentials_provider) { - deps += [ "${examples_plat_dir}:efr32-attestation-credentials" ] + deps += [ "${examples_plat_dir}:siwx917-attestation-credentials" ] } # Factory Data Provider diff --git a/examples/lighting-app/silabs/SiWx917/args.gni b/examples/lighting-app/silabs/SiWx917/args.gni index d216faa0a07dae..8b382c4520b390 100644 --- a/examples/lighting-app/silabs/SiWx917/args.gni +++ b/examples/lighting-app/silabs/SiWx917/args.gni @@ -15,7 +15,7 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") import("${chip_root}/config/standalone/args.gni") -import("${chip_root}/src/platform/silabs/EFR32/args.gni") +import("${chip_root}/src/platform/silabs/SiWx917/args.gni") efr32_sdk_target = get_label_info(":sdk", "label_no_toolchain") diff --git a/examples/lighting-app/silabs/SiWx917/build_for_wifi_args.gni b/examples/lighting-app/silabs/SiWx917/build_for_wifi_args.gni index 363d2be9e6f362..8a0192cd5e9c3f 100644 --- a/examples/lighting-app/silabs/SiWx917/build_for_wifi_args.gni +++ b/examples/lighting-app/silabs/SiWx917/build_for_wifi_args.gni @@ -17,7 +17,7 @@ import("${chip_root}/config/standalone/args.gni") efr32_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false -import("${chip_root}/src/platform/silabs/EFR32/wifi_args.gni") +import("${chip_root}/src/platform/silabs/SiWx917/wifi_args.gni") chip_enable_ota_requestor = true diff --git a/examples/lighting-app/silabs/SiWx917/include/AppConfig.h b/examples/lighting-app/silabs/SiWx917/include/AppConfig.h index ffadaf9706cd2e..b86af8b22c2213 100644 --- a/examples/lighting-app/silabs/SiWx917/include/AppConfig.h +++ b/examples/lighting-app/silabs/SiWx917/include/AppConfig.h @@ -19,7 +19,7 @@ #pragma once -#include "efr32_utils.h" +#include "siwx917_utils.h" // ---- Lighting Example App Config ---- diff --git a/examples/lighting-app/silabs/SiWx917/include/AppTask.h b/examples/lighting-app/silabs/SiWx917/include/AppTask.h index df80995592fd95..225b726f732b13 100644 --- a/examples/lighting-app/silabs/SiWx917/include/AppTask.h +++ b/examples/lighting-app/silabs/SiWx917/include/AppTask.h @@ -30,7 +30,6 @@ #include "BaseApplication.h" #include "FreeRTOS.h" #include "LightingManager.h" -#include "sl_simple_button_instances.h" #include "timers.h" // provides FreeRTOS timer support #include #include @@ -70,16 +69,6 @@ class AppTask : public BaseApplication CHIP_ERROR StartAppTask(); - /** - * @brief Event handler when a button is pressed - * Function posts an event for button processing - * - * @param buttonHandle APP_LIGHT_SWITCH or APP_FUNCTION_BUTTON - * @param btnAction button action - SL_SIMPLE_BUTTON_PRESSED, - * SL_SIMPLE_BUTTON_RELEASED or SL_SIMPLE_BUTTON_DISABLED - */ - void ButtonEventHandler(const sl_button_t * buttonHandle, uint8_t btnAction) override; - /** * @brief Callback called by the identify-server when an identify command is received * diff --git a/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp b/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp index 9abc9e17750f52..22cab2f3ed1e5f 100644 --- a/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp +++ b/examples/lighting-app/silabs/SiWx917/src/AppTask.cpp @@ -21,11 +21,6 @@ #include "AppConfig.h" #include "AppEvent.h" -#ifdef ENABLE_WSTK_LEDS -#include "LEDWidget.h" -#include "sl_simple_led_instances.h" -#endif // ENABLE_WSTK_LEDS - #include #include #include @@ -43,11 +38,6 @@ #include -#ifdef ENABLE_WSTK_LEDS -#define SYSTEM_STATE_LED &sl_led_led0 -#define LIGHT_LED &sl_led_led1 -#endif // ENABLE_WSTK_LEDS - #define APP_FUNCTION_BUTTON &sl_button_btn0 #define APP_LIGHT_SWITCH &sl_button_btn1 @@ -56,10 +46,6 @@ using namespace ::chip::DeviceLayer; namespace { -#ifdef ENABLE_WSTK_LEDS -LEDWidget sLightLED; -#endif // ENABLE_WSTK_LEDS - EmberAfIdentifyEffectIdentifier sIdentifyEffect = EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT; /********************************************************** @@ -144,19 +130,16 @@ CHIP_ERROR AppTask::Init() appError(err); } - err = LightMgr().Init(); - if (err != CHIP_NO_ERROR) - { - SILABS_LOG("LightMgr::Init() failed"); - appError(err); - } - - LightMgr().SetCallbacks(ActionInitiated, ActionCompleted); + /* TODO + err = LightMgr().Init(); + if (err != CHIP_NO_ERROR) + { + SILABS_LOG("LightMgr::Init() failed"); + appError(err); + } -#ifdef ENABLE_WSTK_LEDS - sLightLED.Init(LIGHT_LED); - sLightLED.Set(LightMgr().IsLightOn()); -#endif // ENABLE_WSTK_LEDS + LightMgr().SetCallbacks(ActionInitiated, ActionCompleted); + */ return err; } @@ -246,39 +229,12 @@ void AppTask::LightActionEventHandler(AppEvent * aEvent) } } -void AppTask::ButtonEventHandler(const sl_button_t * buttonHandle, uint8_t btnAction) -{ - if (buttonHandle == NULL) - { - return; - } - - AppEvent button_event = {}; - button_event.Type = AppEvent::kEventType_Button; - button_event.ButtonEvent.Action = btnAction; - - if (buttonHandle == APP_LIGHT_SWITCH && btnAction == SL_SIMPLE_BUTTON_PRESSED) - { - button_event.Handler = LightActionEventHandler; - sAppTask.PostEvent(&button_event); - } - else if (buttonHandle == APP_FUNCTION_BUTTON) - { - button_event.Handler = BaseApplication::ButtonHandler; - sAppTask.PostEvent(&button_event); - } -} - void AppTask::ActionInitiated(LightingManager::Action_t aAction, int32_t aActor) { // Action initiated, update the light led bool lightOn = aAction == LightingManager::ON_ACTION; SILABS_LOG("Turning light %s", (lightOn) ? "On" : "Off") -#ifdef ENABLE_WSTK_LEDS - sLightLED.Set(lightOn); -#endif // ENABLE_WSTK_LEDS - #ifdef DISPLAY_ENABLED sAppTask.GetLCD().WriteDemoUI(lightOn); #endif diff --git a/examples/lighting-app/silabs/SiWx917/src/main.cpp b/examples/lighting-app/silabs/SiWx917/src/main.cpp index 2594f6f9216e78..e3ed2a9c8490a8 100644 --- a/examples/lighting-app/silabs/SiWx917/src/main.cpp +++ b/examples/lighting-app/silabs/SiWx917/src/main.cpp @@ -20,14 +20,13 @@ #include #include "AppConfig.h" -#include "init_efrPlatform.h" -#include "sl_simple_button_instances.h" -#include "sl_system_kernel.h" +#include "init_ccpPlatform.h" + #include #include #include #include -#ifdef EFR32_ATTESTATION_CREDENTIALS +#ifdef SI917_ATTESTATION_CREDENTIALS #include #else #include @@ -49,16 +48,18 @@ static chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; // ================================================================================ int main(void) { - init_efrPlatform(); - if (EFR32MatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) + init_ccpPlatform(); + if (SI917MatterConfig::InitMatter(BLE_DEV_NAME) != CHIP_NO_ERROR) + { appError(CHIP_ERROR_INTERNAL); + } gExampleDeviceInfoProvider.SetStorageDelegate(&chip::Server::GetInstance().GetPersistentStorage()); chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider); chip::DeviceLayer::PlatformMgr().LockChipStack(); // Initialize device attestation config -#ifdef EFR32_ATTESTATION_CREDENTIALS +#ifdef SI917_ATTESTATION_CREDENTIALS SetDeviceAttestationCredentialsProvider(Silabs::GetSilabsDacProvider()); #else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); @@ -67,18 +68,15 @@ int main(void) SILABS_LOG("Starting App Task"); if (AppTask::GetAppTask().StartAppTask() != CHIP_NO_ERROR) + { appError(CHIP_ERROR_INTERNAL); + } SILABS_LOG("Starting FreeRTOS scheduler"); - sl_system_kernel_start(); + vTaskStartScheduler(); // Should never get here. chip::Platform::MemoryShutdown(); SILABS_LOG("vTaskStartScheduler() failed"); appError(CHIP_ERROR_INTERNAL); } - -void sl_button_on_change(const sl_button_t * handle) -{ - AppTask::GetAppTask().ButtonEventHandler(handle, sl_button_get_state(handle)); -} diff --git a/examples/lighting-app/silabs/SiWx917/with_pw_rpc.gni b/examples/lighting-app/silabs/SiWx917/with_pw_rpc.gni index 40a8bb79d84b6a..3e2b6e54411c6c 100644 --- a/examples/lighting-app/silabs/SiWx917/with_pw_rpc.gni +++ b/examples/lighting-app/silabs/SiWx917/with_pw_rpc.gni @@ -17,7 +17,7 @@ import("//build_overrides/chip.gni") import("${chip_root}/config/efr32/lib/pw_rpc/pw_rpc.gni") -import("${chip_root}/examples/platform/silabs/efr32/args.gni") +import("${chip_root}/examples/platform/silabs/SiWx917/args.gni") efr32_sdk_target = get_label_info(":sdk", "label_no_toolchain") diff --git a/examples/platform/silabs/SiWx917/BUILD.gn b/examples/platform/silabs/SiWx917/BUILD.gn index dbd8473a6c89de..990a43d59d66c7 100644 --- a/examples/platform/silabs/SiWx917/BUILD.gn +++ b/examples/platform/silabs/SiWx917/BUILD.gn @@ -16,7 +16,7 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") import("${chip_root}/src/lib/lib.gni") import("${chip_root}/src/platform/device.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") +import("${efr32_sdk_build_root}/SiWx917_sdk.gni") config("chip_examples_project_config") { include_dirs = [ "project_include" ] @@ -40,22 +40,6 @@ config("chip_examples_project_config") { ] } -source_set("openthread_core_config_efr32_chip_examples") { - if (chip_enable_openthread) { - sources = [ "project_include/OpenThreadConfig.h" ] - - public_deps = [ "${efr32_sdk_build_root}:efr32_sdk" ] - - if (use_silabs_thread_lib) { - public_deps += [ "${efr32_sdk_build_root}:openthread_core_config_efr32" ] - } else { - public_deps += [ "${chip_root}/third_party/openthread/platforms/efr32:openthread_core_config_efr32" ] - } - - public_configs = [ ":chip_examples_project_config" ] - } -} - source_set("efr-matter-shell") { if (chip_build_libshell) { defines = [ "ENABLE_CHIP_SHELL" ] @@ -75,8 +59,8 @@ config("attestation-credentials-config") { include_dirs = [ "${chip_root}" ] defines = [ - # Set to 1 to enable EFR32 attestation credentials - "EFR32_ATTESTATION_CREDENTIALS", + # Set to 1 to enable SI917 attestation credentials + "SI917_ATTESTATION_CREDENTIALS", ] } @@ -96,8 +80,8 @@ source_set("efr32-attestation-credentials") { source_set("efr32-factory-data-provider") { sources = [ - "EFR32DeviceDataProvider.cpp", - "EFR32DeviceDataProvider.h", + "SiWx917DeviceDataProvider.cpp", + "SiWx917DeviceDataProvider.h", ] public_deps = [ diff --git a/examples/platform/silabs/SiWx917/BaseApplication.cpp b/examples/platform/silabs/SiWx917/BaseApplication.cpp index a9ecfc63bb0c60..b401c1825578f6 100644 --- a/examples/platform/silabs/SiWx917/BaseApplication.cpp +++ b/examples/platform/silabs/SiWx917/BaseApplication.cpp @@ -25,11 +25,6 @@ #include "AppEvent.h" #include "AppTask.h" -#ifdef ENABLE_WSTK_LEDS -#include "LEDWidget.h" -#include "sl_simple_led_instances.h" -#endif // ENABLE_WSTK_LEDS - #ifdef DISPLAY_ENABLED #include "lcd.h" #ifdef QR_CODE_ENABLED @@ -37,7 +32,7 @@ #endif // QR_CODE_ENABLED #endif // DISPLAY_ENABLED -#include "EFR32DeviceDataProvider.h" +#include "SiWx917DeviceDataProvider.h" #include #include #include @@ -49,12 +44,6 @@ #include #include -#if CHIP_ENABLE_OPENTHREAD -#include -#include -#include -#endif // CHIP_ENABLE_OPENTHREAD - #ifdef SL_WIFI #include "wfx_host_events.h" #include @@ -74,12 +63,6 @@ #define APP_EVENT_QUEUE_SIZE 10 #define EXAMPLE_VENDOR_ID 0xcafe -#ifdef ENABLE_WSTK_LEDS -#define SYSTEM_STATE_LED &sl_led_led0 -#endif // ENABLE_WSTK_LEDS - -#define APP_FUNCTION_BUTTON &sl_button_btn0 - using namespace chip; using namespace ::chip::DeviceLayer; @@ -95,10 +78,6 @@ TimerHandle_t sLightTimer; TaskHandle_t sAppTaskHandle; QueueHandle_t sAppEventQueue; -#ifdef ENABLE_WSTK_LEDS -LEDWidget sStatusLED; -#endif // ENABLE_WSTK_LEDS - #ifdef SL_WIFI app::Clusters::NetworkCommissioning::Instance sWiFiNetworkCommissioningInstance(0 /* Endpoint Id */, &(NetworkCommissioning::SlWiFiDriver::GetInstance())); @@ -211,11 +190,6 @@ CHIP_ERROR BaseApplication::Init(Identify * identifyObj) SILABS_LOG("Current Software Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); -#ifdef ENABLE_WSTK_LEDS - LEDWidget::InitGpio(); - sStatusLED.Init(SYSTEM_STATE_LED); -#endif // ENABLE_WSTK_LEDS - ConfigurationMgr().LogDeviceConfig(); // Create buffer for QR code that can fit max size and null terminator. @@ -271,13 +245,6 @@ void BaseApplication::FunctionEventHandler(AppEvent * aEvent) #endif // CHIP_DEVICE_CONFIG_ENABLE_SED mFunction = kFunction_FactoryReset; - -#ifdef ENABLE_WSTK_LEDS - // Turn off all LEDs before starting blink to make sure blink is - // co-ordinated. - sStatusLED.Set(false); - sStatusLED.Blink(500); -#endif // ENABLE_WSTK_LEDS } else if (mFunctionTimerActive && mFunction == kFunction_FactoryReset) { @@ -329,133 +296,6 @@ void BaseApplication::LightEventHandler() // the LEDs at an even rate of 100ms. // // Otherwise, blink the LED ON for a very short time. - if (mFunction != kFunction_FactoryReset) - { - if ((gIdentifyptr != nullptr) && (gIdentifyptr->mActive)) - { -#ifdef ENABLE_WSTK_LEDS - sStatusLED.Blink(250, 250); -#endif // ENABLE_WSTK_LEDS - } - else if (sIdentifyEffect != EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT) - { - if (sIdentifyEffect == EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK) - { -#ifdef ENABLE_WSTK_LEDS - sStatusLED.Blink(50, 50); -#endif // ENABLE_WSTK_LEDS - } - if (sIdentifyEffect == EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE) - { -#ifdef ENABLE_WSTK_LEDS - sStatusLED.Blink(1000, 1000); -#endif // ENABLE_WSTK_LEDS - } - if (sIdentifyEffect == EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY) - { -#ifdef ENABLE_WSTK_LEDS - sStatusLED.Blink(300, 700); -#endif // ENABLE_WSTK_LEDS - } - } -#if !(defined(CHIP_DEVICE_CONFIG_ENABLE_SED) && CHIP_DEVICE_CONFIG_ENABLE_SED) - else if (sIsProvisioned && sIsEnabled) - { - if (sIsAttached) - { -#ifdef ENABLE_WSTK_LEDS - sStatusLED.Set(true); -#endif // ENABLE_WSTK_LEDS - } - else - { -#ifdef ENABLE_WSTK_LEDS - sStatusLED.Blink(950, 50); -#endif - } - } - else if (sHaveBLEConnections) - { -#ifdef ENABLE_WSTK_LEDS - sStatusLED.Blink(100, 100); -#endif // ENABLE_WSTK_LEDS - } - else - { -#ifdef ENABLE_WSTK_LEDS - sStatusLED.Blink(50, 950); -#endif // ENABLE_WSTK_LEDS - } -#endif // CHIP_DEVICE_CONFIG_ENABLE_SED - } - -#ifdef ENABLE_WSTK_LEDS - sStatusLED.Animate(); -#endif // ENABLE_WSTK_LEDS -} - -void BaseApplication::ButtonHandler(AppEvent * aEvent) -{ - // To trigger software update: press the APP_FUNCTION_BUTTON button briefly (< - // FACTORY_RESET_TRIGGER_TIMEOUT) To initiate factory reset: press the - // APP_FUNCTION_BUTTON for FACTORY_RESET_TRIGGER_TIMEOUT + - // FACTORY_RESET_CANCEL_WINDOW_TIMEOUT All LEDs start blinking after - // FACTORY_RESET_TRIGGER_TIMEOUT to signal factory reset has been initiated. - // To cancel factory reset: release the APP_FUNCTION_BUTTON once all LEDs - // start blinking within the FACTORY_RESET_CANCEL_WINDOW_TIMEOUT - if (aEvent->ButtonEvent.Action == SL_SIMPLE_BUTTON_PRESSED) - { - if (!mFunctionTimerActive && mFunction == kFunction_NoneSelected) - { - StartFunctionTimer(FACTORY_RESET_TRIGGER_TIMEOUT); - mFunction = kFunction_StartBleAdv; - } - } - else - { - // If the button was released before factory reset got initiated, open the commissioning window and start BLE advertissement - // in fast mode - if (mFunctionTimerActive && mFunction == kFunction_StartBleAdv) - { - CancelFunctionTimer(); - mFunction = kFunction_NoneSelected; - -#ifdef QR_CODE_ENABLED - // TOGGLE QRCode/LCD demo UI - slLCD.ToggleQRCode(); -#endif - -#ifdef SL_WIFI - if (!ConnectivityMgr().IsWiFiStationProvisioned()) -#else - if (!ConnectivityMgr().IsThreadProvisioned()) -#endif /* !SL_WIFI */ - { - // Open Basic CommissioningWindow. Will start BLE advertisements - chip::DeviceLayer::PlatformMgr().LockChipStack(); - CHIP_ERROR err = chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow(); - chip::DeviceLayer::PlatformMgr().UnlockChipStack(); - if (err != CHIP_NO_ERROR) - { - SILABS_LOG("Failed to open the Basic Commissioning Window"); - } - } - else { SILABS_LOG("Network is already provisioned, Ble advertissement not enabled"); } - } - else if (mFunctionTimerActive && mFunction == kFunction_FactoryReset) - { - CancelFunctionTimer(); - -#if CHIP_DEVICE_CONFIG_ENABLE_SED == 1 - StopStatusLEDTimer(); -#endif - - // Change the function to none selected since factory reset has been - // canceled. - mFunction = kFunction_NoneSelected; - SILABS_LOG("Factory Reset has been Canceled"); - } - } } void BaseApplication::CancelFunctionTimer() @@ -500,9 +340,6 @@ void BaseApplication::StartStatusLEDTimer() void BaseApplication::StopStatusLEDTimer() { -#ifdef ENABLE_WSTK_LEDS - sStatusLED.Set(false); -#endif // ENABLE_WSTK_LEDS if (xTimerStop(sLightTimer, 100) != pdPASS) { diff --git a/examples/platform/silabs/SiWx917/BaseApplication.h b/examples/platform/silabs/SiWx917/BaseApplication.h index febd7aa68591b2..2c0e07edb35289 100644 --- a/examples/platform/silabs/SiWx917/BaseApplication.h +++ b/examples/platform/silabs/SiWx917/BaseApplication.h @@ -28,7 +28,6 @@ #include "AppEvent.h" #include "FreeRTOS.h" -#include "sl_simple_button_instances.h" #include "timers.h" // provides FreeRTOS timer support #include #include @@ -88,16 +87,6 @@ class BaseApplication static SilabsLCD & GetLCD(void); #endif - /** - * @brief Event handler when a button is pressed - * Function posts an event for button processing - * - * @param buttonHandle APP_LIGHT_SWITCH or APP_FUNCTION_BUTTON - * @param btnAction button action - SL_SIMPLE_BUTTON_PRESSED, - * SL_SIMPLE_BUTTON_RELEASED or SL_SIMPLE_BUTTON_DISABLED - */ - virtual void ButtonEventHandler(const sl_button_t * buttonHandle, uint8_t btnAction) = 0; - /** * @brief Function called to start the LED light timer */ diff --git a/examples/platform/silabs/SiWx917/FreeRTOSConfig.h b/examples/platform/silabs/SiWx917/FreeRTOSConfig.h index 50f4c24ff31679..02b441ec790272 100644 --- a/examples/platform/silabs/SiWx917/FreeRTOSConfig.h +++ b/examples/platform/silabs/SiWx917/FreeRTOSConfig.h @@ -107,20 +107,6 @@ extern "C" { #include -#include "RTE_Components.h" -#include CMSIS_device_header - -#include "em_assert.h" -#include "em_device.h" - -#if defined(SL_COMPONENT_CATALOG_PRESENT) -#include "sl_component_catalog.h" -#endif - -#if SL_SYSTEM_VIEW -#include "SEGGER_SYSVIEW_FreeRTOS.h" -#endif - /*----------------------------------------------------------- * Application specific definitions. * @@ -133,6 +119,8 @@ extern "C" { * See http://www.freertos.org/a00110.html. *----------------------------------------------------------*/ +extern uint32_t SystemCoreClock; + /* Energy saving modes. */ #if defined(SL_CATALOG_POWER_MANAGER_PRESENT) #define configUSE_TICKLESS_IDLE 1 @@ -148,7 +136,7 @@ extern "C" { #define configUSE_TICK_HOOK (1) #define configCHECK_FOR_STACK_OVERFLOW (2) #define configUSE_MALLOC_FAILED_HOOK (1) -#define configUSE_IDLE_HOOK (1) +#define configUSE_IDLE_HOOK (0) /* Main functions*/ /* Run time stats gathering related definitions. */ @@ -185,13 +173,7 @@ See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */ #define configUSE_TICKLESS_IDLE_SIMPLE_DEBUG (1) /* See into vPortSuppressTicksAndSleep source code for explanation */ #define configMAX_PRIORITIES (56) #define configMINIMAL_STACK_SIZE (320) /* Number of words to use for Idle and Timer stacks */ - -#ifdef HEAP_MONITORING -#define configMAX_TASK_NAME_LEN (24) -#else #define configMAX_TASK_NAME_LEN (10) -#endif // HEAP_MONITORING - #define configUSE_16_BIT_TICKS (0) #define configIDLE_SHOULD_YIELD (1) #define configUSE_MUTEXES (1) @@ -207,11 +189,7 @@ See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */ #define configSUPPORT_DYNAMIC_ALLOCATION (1) #ifndef configTOTAL_HEAP_SIZE -#ifdef SL_WIFI #define configTOTAL_HEAP_SIZE ((size_t)(34 * 1024)) -#else -#define configTOTAL_HEAP_SIZE ((size_t)(20 * 1024)) -#endif #endif // configTOTAL_HEAP_SIZE /* Optional functions - most linkers will remove unused functions anyway. */ diff --git a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal.h b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal.h similarity index 94% rename from examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal.h rename to examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal.h index 4e195433edc57f..8e4e6e25952583 100644 --- a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal.h +++ b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal.h @@ -54,12 +54,6 @@ // Macro to drive high value on GPIO #define RSI_HAL_GPIO_HIGH 1 -// Macro to drive LDMA channel number -#define RSI_LDMA_TRANSFER_CHANNEL_NUM 3 - -// Macro to drive semaphore block minimun timer in milli seconds -#define RSI_SEM_BLOCK_MIN_TIMER_VALUE_MS 50 - /****************************************************** * * Function Declarations * ******************************************************/ diff --git a/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_platform_init.c b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_platform_init.c new file mode 100644 index 00000000000000..b2effb5997f388 --- /dev/null +++ b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_platform_init.c @@ -0,0 +1,113 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Includes + */ +#include "rsi_board.h" +#include "rsi_pll.h" +#include "rsi_rom_clks.h" +#include "siwx917_utils.h" +#include "system_RS1xxxx.h" + +#define SOC_PLL_REF_FREQUENCY 32000000 /* PLL input REFERENCE clock 32MHZ */ + +// Note: Change this macro to required PLL frequency in hertz +#define PS4_SOC_FREQ 80000000 /* PLL out clock 80MHz */ +#define SWITCH_QSPI_TO_SOC_PLL +#define ICACHE_DISABLE +#define DEBUG_DISABLE + +#define PMU_GOOD_TIME 31 /*Duration in us*/ +#define XTAL_GOOD_TIME 31 /*Duration in us*/ + +/*Pre-fetch and regestring */ +#define ICACHE2_ADDR_TRANSLATE_1_REG *(volatile uint32_t *) (0x20280000 + 0x24) +#define MISC_CFG_SRAM_REDUNDANCY_CTRL *(volatile uint32_t *) (0x46008000 + 0x18) +#define MISC_CONFIG_MISC_CTRL1 *(volatile uint32_t *) (0x46008000 + 0x44) +#define MISC_QUASI_SYNC_MODE *(volatile uint32_t *) (0x46008000 + 0x84) + +/** + * @fn void soc_pll_config() + * @brief This function to configure clock for SiWx917 SoC (80MHz) + * Configure the PLL frequency and Switch M4 clock to PLL clock for speed operations + * + * @param[in] none + * @param[out] none + * @return int + * @section description + * configure clock for SiWx917 SoC + * + */ +int soc_pll_config(void) +{ + RSI_CLK_SocPllLockConfig(1, 1, 7); + + RSI_CLK_SocPllRefClkConfig(2); + + RSI_CLK_M4SocClkConfig(M4CLK, M4_ULPREFCLK, 0); + + /*Enable fre-fetch and register if SOC-PLL frequency is more than or equal to 120M*/ +#if (PS4_SOC_FREQ >= 120000000) + ICACHE2_ADDR_TRANSLATE_1_REG = BIT(21); + MISC_CFG_SRAM_REDUNDANCY_CTRL = BIT(4); + MISC_CONFIG_MISC_CTRL1 |= BIT(4); +#if !(defined WISE_AOC_4) + MISC_QUASI_SYNC_MODE |= BIT(6); + MISC_QUASI_SYNC_MODE |= (BIT(6) | BIT(7)); +#endif /* !WISE_AOC_4 */ +#endif /* (PS4_SOC_FREQ > 120000000) */ + + RSI_CLK_SetSocPllFreq(M4CLK, PS4_SOC_FREQ, SOC_PLL_REF_FREQUENCY); + + RSI_CLK_M4SocClkConfig(M4CLK, M4_SOCPLLCLK, 0); + +#ifdef SWITCH_QSPI_TO_SOC_PLL + RSI_CLK_QspiClkConfig(M4CLK, QSPI_INTFPLLCLK, 0, 0, 0); +#endif /* SWITCH_QSPI_TO_SOC_PLL */ + + return 0; +} + +/*==============================================*/ +/** + * @fn void rsi_hal_board_init() + * @brief This function Initializes the platform + * @param[in] none + * @param[out] none + * @return none + * @section description + * This function initializes the platform + * + */ +void rsi_hal_board_init(void) +{ + SystemCoreClockUpdate(); + + /* configure clock for SiWx917 SoC */ + soc_pll_config(); + SILABS_LOG("%s, soc_pll_config, SystemCoreClock=%d\n", __func__, SystemCoreClock); + +#ifdef COMMON_FLASH_EN + /* Before TA going to power save mode ,set m4ss_ref_clk_mux_ctrl ,tass_ref_clk_mux_ctrl, + AON domain power supply controls form TA to M4 */ + RSI_Set_Cntrls_To_M4(); +#endif +#ifdef DEBUG_UART + DEBUGINIT(); +#endif +} diff --git a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_timer.c b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_timer.c similarity index 54% rename from examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_timer.c rename to examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_timer.c index c6d6381932d3ea..e7141d4646060c 100644 --- a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_timer.c +++ b/examples/platform/silabs/SiWx917/SiWx917/hal/rsi_hal_mcu_timer.c @@ -19,13 +19,14 @@ * Includes */ -#include "em_cmu.h" +#include "rsi_driver.h" #ifdef RSI_WITH_OS /* FreeRTOS includes. */ #include "FreeRTOS.h" -#include "event_groups.h" +#include "StackMacros.h" #include "task.h" #include "timers.h" + #if defined(SysTick) #undef SysTick_Handler /* FreeRTOS SysTick interrupt handler prototype */ @@ -33,115 +34,9 @@ extern void SysTick_Handler(void); /* FreeRTOS tick timer interrupt handler prototype */ extern void xPortSysTickHandler(void); #endif /* SysTick */ -#endif /* RSI_WITH_OS */ -#include "wfx_host_events.h" - -/* RSI Driver include file */ -#include "rsi_driver.h" -/* RSI WLAN Config include file */ -#include "rsi_bootup_config.h" -#include "rsi_common_apis.h" -#include "rsi_data_types.h" -#include "rsi_error.h" -#include "rsi_nwk.h" -#include "rsi_socket.h" -#include "rsi_utils.h" -#include "rsi_wlan.h" -#include "rsi_wlan_apis.h" -#include "rsi_wlan_config.h" -#include "wfx_rsi.h" - -#ifndef _use_the_rsi_defined_functions - -StaticTimer_t sRsiTimerBuffer; - -/* - * We (Matter port) need a few functions out of this file - * They are at the top - */ -uint32_t rsi_hal_gettickcount(void) -{ - return xTaskGetTickCount(); -} -void rsi_delay_ms(uint32_t delay_ms) -{ -#ifndef RSI_WITH_OS - uint32_t start; #endif - if (delay_ms == 0) // Check if delay is 0msec - return; - -#ifdef RSI_WITH_OS - vTaskDelay(pdMS_TO_TICKS(delay_ms)); -#else - start = rsi_hal_gettickcount(); - do - { - } while (rsi_hal_gettickcount() - start < delay_ms); -#endif -} -static struct rsi_timer -{ - void (*func)(void); - TimerHandle_t handle; - uint8_t id; - uint8_t name[3]; -} rsi_timer[WFX_RSI_NUM_TIMERS]; -static void timer_cb(TimerHandle_t thandle) -{ - int x; - for (x = 0; x < WFX_RSI_NUM_TIMERS; x++) - { - if (rsi_timer[x].handle == thandle) - { - (*rsi_timer[x].func)(); - break; - } - } -} - -/* - * Run a one-shot/periodic timer - */ -int32_t rsi_timer_start(uint8_t timer_node, uint8_t mode, uint8_t type, uint32_t duration, void (*rsi_timer_cb)(void)) -{ - int x; - struct rsi_timer * tp; - - if (mode == RSI_HAL_TIMER_MODE_MILLI) - return RSI_ERROR_INVALID_OPTION; /* Not supported for now - Fix this later */ - for (x = 0; x < WFX_RSI_NUM_TIMERS; x++) - { - tp = &rsi_timer[x]; - if (tp->handle == NULL) - { - goto found; - } - } - /* No space */ - return RSI_ERROR_INSUFFICIENT_BUFFER; -found: - tp->name[0] = 'r'; - tp->name[1] = timer_node; - tp->name[2] = 0; - tp->func = rsi_timer_cb; - tp->handle = - xTimerCreateStatic((char *) &tp->name[0], pdMS_TO_TICKS(duration), - ((mode == RSI_HAL_TIMER_TYPE_SINGLE_SHOT) ? pdFALSE : pdTRUE), NULL, timer_cb, &sRsiTimerBuffer); - - if (tp->handle == NULL) - { - return RSI_ERROR_INSUFFICIENT_BUFFER; - } - - (void) xTimerStart(tp->handle, TIMER_TICKS_TO_WAIT_0); - return RSI_ERROR_NONE; -} -#else /* _use_the_rsi_defined_functions */ - -/* Counts 1ms timeTicks */ -volatile uint32_t msTicks = 0; +static volatile uint32_t _dwTickCount; // systick cout variable /*===================================================*/ /** @@ -167,11 +62,11 @@ volatile uint32_t msTicks = 0; int32_t rsi_timer_start(uint8_t timer_node, uint8_t mode, uint8_t type, uint32_t duration, void (*rsi_timer_expiry_handler)(void)) { - // Initialise the timer + //! Initialise the timer - // register the call back + //! register the call back - // Start timer + //! Start timer return 0; } @@ -191,7 +86,7 @@ int32_t rsi_timer_start(uint8_t timer_node, uint8_t mode, uint8_t type, uint32_t int32_t rsi_timer_stop(uint8_t timer_node) { - // Stop the timer + //! Stop the timer return 0; } @@ -206,12 +101,13 @@ int32_t rsi_timer_stop(uint8_t timer_node) * @description This HAL API should contain API to read the timer * */ + uint32_t rsi_timer_read(uint8_t timer_node) { volatile uint32_t timer_val = 0; - // read the timer and return timer value + //! read the timer and return timer value return timer_val; } @@ -229,25 +125,65 @@ uint32_t rsi_timer_read(uint8_t timer_node) void rsi_delay_us(uint32_t delay_us) { - // call the API for delay in micro seconds + //! call the API for delay in micro seconds return; } -#ifdef RSI_M4_INTERFACE +/*===================================================*/ +/** + * @fn void rsi_delay_ms(uint32_t delay) + * @brief create delay in micro seconds + * @param[in] delay, timer delay in micro seconds + * @param[out] none + * @return none + * @description This HAL API should contain the code to create delay in micro seconds + * + */ +void rsi_delay_ms1(uint32_t delay_ms) +{ -extern void SysTick_Handler(void); + //! call the API for delay in milli seconds + + return; +} + +/*===================================================*/ +/** + * @fn void SysTick_Handler(void); + * @brief systick cout variable + * @param[in] none + * @param[out] none + * @return none + * @description This HAL API is systick cout variable + * + */ void SysTick_Handler(void) { _dwTickCount++; +#ifdef RSI_WITH_OS + if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) + { + xPortSysTickHandler(); + } +#endif } +/*===================================================*/ +/** + * @fn uint32_t GetTickCount( void ) + * @brief gets the tick count from systic ISR + * @param[in] delay, timer delay in micro seconds + * @param[out] none + * @return Returns the systick current tick count + * @description This HAL API gets the tick count from systic ISR + * + */ uint32_t GetTickCount(void) { return _dwTickCount; // gets the tick count from systic ISR } -#endif /*===================================================*/ /** @@ -257,23 +193,17 @@ uint32_t GetTickCount(void) * @param[out] none * @return none * @description This HAL API should contain the code to create delay in milli seconds + * */ + void rsi_delay_ms(uint32_t delay_ms) { -#ifndef RSI_WITH_OS - uint32_t start; -#endif - if (delay_ms == DELAY0) - return; + uint64_t waitTime = rsi_hal_gettickcount() + delay_ms; -#ifdef RSI_WITH_OS - vTaskDelay(delay_ms); -#else - start = rsi_hal_gettickcount(); - do + while (waitTime > rsi_hal_gettickcount()) { - } while (rsi_hal_gettickcount() - start < delay_ms); -#endif + // we busy wait + } } /*===================================================*/ @@ -285,38 +215,7 @@ void rsi_delay_ms(uint32_t delay_ms) * */ -#ifndef RSI_HAL_USE_RTOS_SYSTICK -/* - SysTick handler implementation that also clears overflow flag. -*/ -void SysTick_Handler(void) -{ - /* Increment counter necessary in Delay()*/ - msTicks++; -#ifdef RSI_WITH_OS - if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) - { - xPortSysTickHandler(); - } -#endif -} - -uint32_t rsi_hal_gettickcount(void) -{ - return msTicks; - -#ifdef LINUX_PLATFORM - // Define your API to get the tick count delay in milli seconds from systic ISR and return the resultant value - struct rsi_timeval tv1; - gettimeofday(&tv1, NULL); - return (tv1.tv_sec * CONVERT_SEC_TO_MSEC + tv1.tv_usec * CONVERT_USEC_TO_MSEC); -#endif -} - -#else uint32_t rsi_hal_gettickcount(void) { - return xTaskGetTickCount(); + return GetTickCount(); } -#endif /* RSI_HAL_USE_RTOS_SYSTICK */ -#endif /* _use_the_rsi_defined_functions */ diff --git a/examples/platform/silabs/SiWx917/rs911x/rs911x.gni b/examples/platform/silabs/SiWx917/SiWx917/rs911x.gni similarity index 54% rename from examples/platform/silabs/SiWx917/rs911x/rs911x.gni rename to examples/platform/silabs/SiWx917/SiWx917/rs911x.gni index f11981023e35f2..0cca17540074ab 100644 --- a/examples/platform/silabs/SiWx917/rs911x/rs911x.gni +++ b/examples/platform/silabs/SiWx917/SiWx917/rs911x.gni @@ -2,24 +2,34 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") -examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" -wifi_sdk_dir = "${chip_root}/src/platform/silabs/EFR32/wifi" -wiseconnect_sdk_root = "${chip_root}/third_party/silabs/wiseconnect-wifi-bt-sdk" +examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" +wifi_sdk_dir = "${chip_root}/src/platform/silabs/SiWx917/wifi" +wiseconnect_sdk_root = "${chip_root}/third_party/silabs/wisemcu-wifi-bt-sdk" rs911x_cflags = [] rs911x_src_plat = [ - "${examples_plat_dir}/rs911x/rsi_if.c", - "${examples_plat_dir}/rs911x/wfx_rsi_host.c", + "${examples_plat_dir}/SiWx917/rsi_if.c", + "${examples_plat_dir}/SiWx917/wfx_rsi_host.c", "${wifi_sdk_dir}/wfx_notify.cpp", - "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_interrupt.c", - "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_ioports.c", - "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_timer.c", - "${examples_plat_dir}/rs911x/hal/efx_spi.c", + + "${examples_plat_dir}/SiWx917/hal/rsi_hal_mcu_timer.c", + "${examples_plat_dir}/SiWx917/hal/rsi_hal_mcu_platform_init.c", + + "${wiseconnect_sdk_root}/platforms/si91x/hal/src/rsi_bootup_config.c", + "${wiseconnect_sdk_root}/platforms/si91x/hal/src/rsi_hal_mcu_m4.c", + "${wiseconnect_sdk_root}/platforms/si91x/hal/src/rsi_hal_mcu_m4_rom.c", + "${wiseconnect_sdk_root}/platforms/si91x/hal/src/rsi_hal_mcu_interrupt.c", ] rs911x_plat_incs = [ "${wifi_sdk_dir}", "${wifi_sdk_dir}/hal", - "${chip_root}/src/platform/EFR32", + "${wiseconnect_sdk_root}/platforms/si91x/hal/inc", + + # "${wiseconnect_sdk_root}/sapi/include", + "${chip_root}/src/platform/silabs/SiWx917", + "${chip_root}/src/platform/silabs/SiWx917/bluetooth", + "${examples_plat_dir}/SiWx917", + "${wiseconnect_sdk_root}/platforms/si91x/hal/inc", ] # @@ -31,6 +41,8 @@ rs911x_src_sapi = [ "${wiseconnect_sdk_root}/sapi/common/rsi_apis_rom.c", "${wiseconnect_sdk_root}/sapi/common/rsi_common_apis.c", "${wiseconnect_sdk_root}/sapi/common/rsi_device_init_apis.c", + + # "${wiseconnect_sdk_root}/sapi/common/rsi_wisemcu_hardware_setup.c", "${wiseconnect_sdk_root}/sapi/driver/device_interface/spi/rsi_spi_frame_rd_wr.c", "${wiseconnect_sdk_root}/sapi/driver/device_interface/spi/rsi_spi_functs.c", "${wiseconnect_sdk_root}/sapi/driver/device_interface/spi/rsi_spi_iface_init.c", @@ -60,14 +72,39 @@ rs911x_src_sapi = [ ] foreach(src_file, rs911x_src_sapi) { - rs911x_cflags += [ "-Wno-empty-body" ] + rs911x_cflags += [ + "-Wno-empty-body", + "-Wno-cpp", + "-Wno-missing-braces", + "-Wno-sign-compare", + "-Wno-error", + "-Wno-unknown-warning-option", + "-Wno-unused-variable", + "-Wno-implicit-function-declaration", + "-Wno-unused-function", + ] } rs911x_inc_plat = [ "${wifi_sdk_dir}", - "${examples_plat_dir}/rs911x", - "${examples_plat_dir}/rs911x/hal", + "${examples_plat_dir}/SiWx917", + "${examples_plat_dir}/SiWx917/hal", "${wiseconnect_sdk_root}/sapi/include", + + #CCP Platfrom + "${wiseconnect_sdk_root}/platforms/si91x/hal/inc", + "${wiseconnect_sdk_root}/platforms/si91x/boards/brd4325a/inc", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/peripheral_drivers/inc", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/inc", + "${wiseconnect_sdk_root}/platforms/si91x/core/chip/inc", + "${wiseconnect_sdk_root}/platforms/si91x/core/config", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/cmsis_driver/config", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/rom_driver/inc", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/cmsis_driver", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/cmsis_driver/CMSIS/Driver/Include", + + "${wiseconnect_sdk_root}/platforms/si91x/core/cmsis", + "${wiseconnect_sdk_root}/platforms/si91x/service/system/inc", ] # Apparently - the rsi library needs this @@ -86,14 +123,20 @@ rs911x_src_lwip = [ "${wifi_sdk_dir}/lwip_netif.cpp", ] rs911x_defs = [ + "CCP_SI917_BRINGUP=1", "SL_HEAP_SIZE=32768", "SL_WIFI=1", - "SL_WFX_USE_SPI", - "EFX32_RS911X=1", "RS911X_WIFI", "RSI_WLAN_ENABLE", - "RSI_SPI_INTERFACE", "RSI_WITH_OS", + "RSI_M4_INTERFACE", #Enable CCP bus Interface + "RSI_WLAN_API_ENABLE", + "HMAC_512", + "LITTLE_ENDIAN_ORDER", + "_CHIP_9118", + + # "ROM_WIRELESS" + #__CC_ARM DEBUG_UART _CHIP_9118 LITTLE_ENDIAN_ORDER HMAC_512 ] rs911x_sock_defs = [ "RS911X_SOCKETS", diff --git a/examples/platform/silabs/SiWx917/rs911x/rsi_if.c b/examples/platform/silabs/SiWx917/SiWx917/rsi_if.c similarity index 92% rename from examples/platform/silabs/SiWx917/rs911x/rsi_if.c rename to examples/platform/silabs/SiWx917/SiWx917/rsi_if.c index 7d3be406fbce2f..3b15cd8f29e7af 100644 --- a/examples/platform/silabs/SiWx917/rs911x/rsi_if.c +++ b/examples/platform/silabs/SiWx917/SiWx917/rsi_if.c @@ -19,12 +19,6 @@ #include #include -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" - #include "sl_status.h" #include "FreeRTOS.h" @@ -38,6 +32,7 @@ #include "rsi_common_apis.h" #include "rsi_data_types.h" +#include "rsi_error.h" #include "rsi_nwk.h" #include "rsi_socket.h" #include "rsi_utils.h" @@ -46,12 +41,13 @@ #include "rsi_wlan_config.h" //#include "rsi_wlan_non_rom.h" #include "rsi_bootup_config.h" -#include "rsi_error.h" #include "dhcp_client.h" -#include "wfx_host_events.h" #include "wfx_rsi.h" +#define VAL(str) #str +#define TOSTRING(str) VAL(str) + /* Rsi driver Task will use as its stack */ StackType_t driverRsiTaskStack[WFX_RSI_WLAN_TASK_SZ] = { 0 }; @@ -107,24 +103,10 @@ int32_t wfx_rsi_get_ap_info(wfx_wifi_scan_result_t * ap) *********************************************************************/ int32_t wfx_rsi_get_ap_ext(wfx_wifi_scan_ext_t * extra_info) { - int32_t status; - uint8_t buff[RSI_RESPONSE_MAX_SIZE] = { 0 }; - status = rsi_wlan_get(RSI_WLAN_EXT_STATS, buff, sizeof(buff)); - if (status != RSI_SUCCESS) - { - WFX_RSI_LOG("\r\n Failed, Error Code : 0x%lX\r\n", status); - } - else - { - rsi_wlan_ext_stats_t * test = (rsi_wlan_ext_stats_t *) buff; - extra_info->beacon_lost_count = test->beacon_lost_count - temp_reset->beacon_lost_count; - extra_info->beacon_rx_count = test->beacon_rx_count - temp_reset->beacon_rx_count; - extra_info->mcast_rx_count = test->mcast_rx_count - temp_reset->mcast_rx_count; - extra_info->mcast_tx_count = test->mcast_tx_count - temp_reset->mcast_tx_count; - extra_info->ucast_rx_count = test->ucast_rx_count - temp_reset->ucast_rx_count; - extra_info->ucast_tx_count = test->ucast_tx_count - temp_reset->ucast_tx_count; - extra_info->overrun_count = test->overrun_count - temp_reset->overrun_count; - } + /* TODO : Place holder until we have similar functionality + * available for SiWx917 + */ + int32_t status = 0; return status; } @@ -138,24 +120,10 @@ int32_t wfx_rsi_get_ap_ext(wfx_wifi_scan_ext_t * extra_info) *********************************************************************/ int32_t wfx_rsi_reset_count() { - int32_t status; - uint8_t buff[RSI_RESPONSE_MAX_SIZE] = { 0 }; - status = rsi_wlan_get(RSI_WLAN_EXT_STATS, buff, sizeof(buff)); - if (status != RSI_SUCCESS) - { - WFX_RSI_LOG("\r\n Failed, Error Code : 0x%lX\r\n", status); - } - else - { - rsi_wlan_ext_stats_t * test = (rsi_wlan_ext_stats_t *) buff; - temp_reset->beacon_lost_count = test->beacon_lost_count; - temp_reset->beacon_rx_count = test->beacon_rx_count; - temp_reset->mcast_rx_count = test->mcast_rx_count; - temp_reset->mcast_tx_count = test->mcast_tx_count; - temp_reset->ucast_rx_count = test->ucast_rx_count; - temp_reset->ucast_tx_count = test->ucast_tx_count; - temp_reset->overrun_count = test->overrun_count; - } + /* TODO : Place holder until we have similar functionality + * available for SiWx917 + */ + int32_t status = 0; return status; } @@ -187,8 +155,6 @@ static void wfx_rsi_join_cb(uint16_t status, const uint8_t * buf, const uint16_t { WFX_RSI_LOG("%s: status: %02x", __func__, status); wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTING; - temp_reset = (wfx_wifi_scan_ext_t *) malloc(sizeof(wfx_wifi_scan_ext_t)); - memset(temp_reset, 0, sizeof(wfx_wifi_scan_ext_t)); if (status != RSI_SUCCESS) { /* @@ -294,24 +260,7 @@ static int32_t wfx_rsi_init(void) { int32_t status; uint8_t buf[RSI_RESPONSE_HOLD_BUFF_SIZE]; - extern void rsi_hal_board_init(void); - WFX_RSI_LOG("%s: starting(HEAP_SZ = %d)", __func__, SL_HEAP_SIZE); - //! Driver initialization - status = rsi_driver_init(wfx_rsi_drv_buf, WFX_RSI_BUF_SZ); - if ((status < RSI_DRIVER_STATUS) || (status > WFX_RSI_BUF_SZ)) - { - WFX_RSI_LOG("%s: error: RSI drv init failed with status: %02x", __func__, status); - return status; - } - - WFX_RSI_LOG("%s: rsi_device_init", __func__); - /* ! Redpine module intialisation */ - if ((status = rsi_device_init(LOAD_NWP_FW)) != RSI_SUCCESS) - { - WFX_RSI_LOG("%s: error: rsi_device_init failed with status: %02x", __func__, status); - return status; - } WFX_RSI_LOG("%s: start wireless drv task", __func__); /* * Create the driver task @@ -478,6 +427,7 @@ static void wfx_rsi_do_join(void) /* Call rsi connect call with given ssid and password * And check there is a success */ + if ((status = rsi_wlan_connect_async((int8_t *) &wfx_rsi.sec.ssid[0], (rsi_security_mode_t) wfx_rsi.sec.security, &wfx_rsi.sec.passkey[0], wfx_rsi_join_cb)) != RSI_SUCCESS) { @@ -485,7 +435,7 @@ static void wfx_rsi_do_join(void) wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTING; WFX_RSI_LOG("%s: rsi_wlan_connect_async failed with status: %02x on try %d", __func__, status, wfx_rsi.join_retries); - vTaskDelay(4000); + vTaskDelay(400); /* TODO - Start a timer.. to retry */ } else @@ -501,6 +451,7 @@ static void wfx_rsi_do_join(void) { WFX_RSI_LOG("%s: starting JOIN to %s after %d tries\n", __func__, (char *) &wfx_rsi.sec.ssid[0], wfx_rsi.join_retries); } + WFX_RSI_LOG("Returning the do join"); } } @@ -518,6 +469,7 @@ static void wfx_rsi_do_join(void) void wfx_rsi_task(void * arg) { EventBits_t flags; + int32_t status = 0; #ifndef RS911X_SOCKETS TickType_t last_dhcp_poll, now; struct netif * sta_netif; @@ -537,6 +489,12 @@ void wfx_rsi_task(void * arg) wfx_started_notify(); WFX_RSI_LOG("%s: starting event wait", __func__); +#ifdef CHIP_ONNETWORK_PAIRING + memcpy(&wfx_rsi.sec.ssid[0], TOSTRING(CHIP_WIFI_SSID), sizeof(TOSTRING(CHIP_WIFI_SSID))); + memcpy(&wfx_rsi.sec.passkey[0], TOSTRING(CHIP_WIFI_PSK), sizeof(TOSTRING(CHIP_WIFI_PSK))); + xEventGroupSetBits(wfx_rsi.events, WFX_EVT_STA_START_JOIN); +#endif + for (;;) { /* @@ -627,7 +585,7 @@ void wfx_rsi_task(void * arg) // Joining to the network wfx_rsi_do_join(); } - if (flags & WFX_EVT_STA_CONN) + if ((flags & WFX_EVT_STA_CONN)) { /* * Initiate the Join command (assuming we have been provisioned) @@ -851,4 +809,28 @@ int32_t wfx_rsi_send_data(void * p, uint16_t len) return status; } +int32_t wfx_rsi_init_platform() +{ + int32_t status; + /*init task - RS911x*/ + WFX_RSI_LOG("RSI_INIT"); + WFX_RSI_LOG("%s: starting(HEAP_SZ = %d)", __func__, SL_HEAP_SIZE); + //! Driver initialization + status = rsi_driver_init(wfx_rsi_drv_buf, WFX_RSI_BUF_SZ); + if ((status < RSI_DRIVER_STATUS) || (status > WFX_RSI_BUF_SZ)) + { + WFX_RSI_LOG("%s: error: RSI drv init failed with status: %02x", __func__, status); + } + + WFX_RSI_LOG("%s: rsi_device_init", __func__); + /* ! Redpine module intialisation */ + if ((status = rsi_device_init(LOAD_NWP_FW)) != RSI_SUCCESS) + { + WFX_RSI_LOG("%s: error: rsi_device_init failed with status: %02x", __func__, status); + return status; + } + + return status; +} + struct wfx_rsi wfx_rsi; diff --git a/examples/platform/silabs/SiWx917/rs911x/rsi_wlan_config.h b/examples/platform/silabs/SiWx917/SiWx917/rsi_wlan_config.h similarity index 84% rename from examples/platform/silabs/SiWx917/rs911x/rsi_wlan_config.h rename to examples/platform/silabs/SiWx917/SiWx917/rsi_wlan_config.h index f2a47b5cb8d2b5..4f2dc070ec83ac 100644 --- a/examples/platform/silabs/SiWx917/rs911x/rsi_wlan_config.h +++ b/examples/platform/silabs/SiWx917/SiWx917/rsi_wlan_config.h @@ -25,53 +25,31 @@ //! Disable feature #define RSI_DISABLE 0 -//! To enable wlan opermode -#define RSI_OPERMODE_WLAN 0 - //! To enable concurrent mode #define CONCURRENT_MODE RSI_DISABLE -//! opermode command parameters +//! opermode command paramaters /*=======================================================================*/ //! To set wlan feature select bit map #define RSI_FEATURE_BIT_MAP (FEAT_SECURITY_OPEN) //! TCP IP BYPASS feature check -#ifdef RS911X_SOCKETS -#define RSI_TCP_IP_BYPASS RSI_DISABLE - -#define RSI_TCP_IP_FEATURE_BIT_MAP \ - (TCP_IP_FEAT_DHCPV4_CLIENT | /*TCP_IP_FEAT_HTTP_CLIENT | */ \ - TCP_IP_FEAT_EXTENSION_VALID | /*TCP_IP_FEAT_SSL |*/ /*TCP_IP_FEAT_DNS_CLIENT |*/ \ - 0) -//! To set custom feature select bit map -#define RSI_CUSTOM_FEATURE_BIT_MAP FEAT_CUSTOM_FEAT_EXTENSION_VALID +//#define RSI_TCP_IP_BYPASS RSI_DISABLE +//! TCP/IP feature select bitmap for selecting TCP/IP features +//#define RSI_TCP_IP_FEATURE_BIT_MAP (TCP_IP_FEAT_DHCPV4_CLIENT | TCP_IP_FEAT_ICMP) -#else /* Don't use RSI_SOCKETS */ #define RSI_TCP_IP_BYPASS RSI_ENABLE +//#define RSI_TCP_IP_FEATURE_BIT_MAP (TCP_IP_FEAT_DHCPV4_CLIENT | TCP_IP_FEAT_ICMP) #define RSI_TCP_IP_FEATURE_BIT_MAP (TCP_IP_FEAT_BYPASS /*| TCP_IP_FEAT_EXTENSION_VALID*/) -#endif + +//! To set custom feature select bit map +#define RSI_CUSTOM_FEATURE_BIT_MAP FEAT_CUSTOM_FEAT_EXTENTION_VALID //! To set Extended custom feature select bit map -#if WIFI_ENABLE_SECURITY_WPA3 -#ifdef RSI_M4_INTERFACE -#define RSI_EXT_CUSTOM_FEATURE_BIT_MAP (EXT_FEAT_256K_MODE | EXT_FEAT_IEEE_80211W) -#else -#define RSI_EXT_CUSTOM_FEATURE_BIT_MAP (EXT_FEAT_384K_MODE | EXT_FEAT_IEEE_80211W) -#endif -#else -#ifdef RSI_M4_INTERFACE -#define RSI_EXT_CUSTOM_FEATURE_BIT_MAP EXT_FEAT_256K_MODE -#else -#define RSI_EXT_CUSTOM_FEATURE_BIT_MAP EXT_FEAT_384K_MODE -#endif -#endif +#define RSI_EXT_CUSTOM_FEATURE_BIT_MAP EXT_FEAT_UART_SEL_FOR_DEBUG_PRINTS + +#define RSI_EXT_TCPIP_FEATURE_BITMAP 0 -//! To set Extended TCPIP feature select bit map -#define RSI_EXT_TCPIP_FEATURE_BITMAP (/*EXT_FEAT_HTTP_OTAF_SUPPORT |*/ EXT_TCP_IP_SSL_16K_RECORD) -//! Extended custom feature is selected internally -//! CCP -- EXT_FEAT_256K_MODE -//! Wiseconnect -- EXT_FEAT_384K_MODE /*=======================================================================*/ //! Feature frame parameters /*=======================================================================*/ @@ -82,13 +60,13 @@ #define AFE_TYPE 1 #define FEATURE_ENABLES 0 /*=======================================================================*/ -//! Band command parameters +//! Band command paramters /*=======================================================================*/ //! RSI_BAND_2P4GHZ(2.4GHz) or RSI_BAND_5GHZ(5GHz) or RSI_DUAL_BAND #define RSI_BAND RSI_BAND_2P4GHZ /*=======================================================================*/ -//! set region command parameters +//! set region command paramters /*=======================================================================*/ //! RSI_ENABLE or RSI_DISABLE Set region support @@ -98,13 +76,13 @@ #define RSI_SET_REGION_FROM_USER_OR_BEACON 1 //! 0-Default Region domain ,1-US, 2-EUROPE, 3-JAPAN -#define RSI_REGION_CODE 1 +#define RSI_REGION_CODE 3 //! 0- Without On Board Antenna , 1- With On Board Antenna #define RSI_MODULE_TYPE 1 /*=======================================================================*/ -//! set region AP command parameters +//! set region AP command paramters /*=======================================================================*/ //! RSI_ENABLE or RSI_DISABLE Set region AP support @@ -114,20 +92,21 @@ #define RSI_SET_REGION_AP_FROM_USER RSI_DISABLE //! "US" or "EU" or "JP" or other region codes -#define RSI_COUNTRY_CODE "US" +#define RSI_COUNTRY_CODE "US " + /*=======================================================================*/ //! Rejoin parameters /*=======================================================================*/ //! RSI_ENABLE or RSI_DISABLE rejoin params -#define RSI_REJOIN_PARAMS_SUPPORT RSI_ENABLE +#define RSI_REJOIN_PARAMS_SUPPORT RSI_DISABLE //! Rejoin retry count. If 0 retries infinity times -#define RSI_REJOIN_MAX_RETRY 5 +#define RSI_REJOIN_MAX_RETRY 0 //! Periodicity of rejoin attempt -#define RSI_REJOIN_SCAN_INTERVAL 1 +#define RSI_REJOIN_SCAN_INTERVAL 4 //! Beacon missed count #define RSI_REJOIN_BEACON_MISSED_COUNT 40 @@ -141,13 +120,13 @@ /*=======================================================================*/ //! RSI_ENABLE or RSI_DISABLE BG Scan support -#define RSI_BG_SCAN_SUPPORT RSI_ENABLE +#define RSI_BG_SCAN_SUPPORT RSI_DISABLE //! RSI_ENABLE or RSI_DISABLE BG scan #define RSI_BG_SCAN_ENABLE RSI_ENABLE //! RSI_ENABLE or RSI_DISABLE instant BG scan -#define RSI_INSTANT_BG RSI_ENABLE +#define RSI_INSTANT_BG 1 // RSI_DISABLE //! BG scan threshold value #define RSI_BG_SCAN_THRESHOLD 63 @@ -165,7 +144,7 @@ #define RSI_PASSIVE_SCAN_DURATION 50 //! Multi probe -#define RSI_MULTIPROBE RSI_ENABLE +#define RSI_MULTIPROBE RSI_DISABLE /*=======================================================================*/ @@ -197,15 +176,8 @@ //! RSI_ENABLE or RSI_DISABLE 11n mode in AP mode #define RSI_MODE_11N_ENABLE RSI_DISABLE -//! HT caps supported -#define RSI_HT_CAPS_NUM_RX_STBC (1 << 8) -#define RSI_HT_CAPS_SHORT_GI_20MHZ BIT(5) -#define RSI_HT_CAPS_GREENFIELD_EN BIT(4) -#define RSI_HT_CAPS_SUPPORT_CH_WIDTH BIT(1) - //! HT caps bit map. -#define RSI_HT_CAPS_BIT_MAP \ - (RSI_HT_CAPS_NUM_RX_STBC | RSI_HT_CAPS_SHORT_GI_20MHZ | RSI_HT_CAPS_GREENFIELD_EN | RSI_HT_CAPS_SUPPORT_CH_WIDTH) +#define RSI_HT_CAPS_BIT_MAP 10 /*=======================================================================*/ //! Scan command parameters @@ -253,12 +225,9 @@ #define RSI_POWER_LEVEL RSI_POWER_LEVEL_HIGH //! RSI_JOIN_FEAT_STA_BG_ONLY_MODE_ENABLE or RSI_JOIN_FEAT_LISTEN_INTERVAL_VALID -#if WIFI_ENABLE_SECURITY_WPA3 -#define RSI_JOIN_FEAT_BIT_MAP RSI_JOIN_FEAT_MFP_CAPABLE_REQUIRED -#else #define RSI_JOIN_FEAT_BIT_MAP 0 -#endif +//! #define RSI_LISTEN_INTERVAL 0 //! Transmission data rate. Physical rate at which data has to be transmitted. @@ -269,7 +238,7 @@ /*=======================================================================*/ //! DHCP client host name -#define RSI_DHCP_HOST_NAME "efr_9116" +#define RSI_DHCP_HOST_NAME "dhcp_client" //! Transmit test command parameters /*=======================================================================*/ @@ -345,16 +314,17 @@ /*=======================================================================*/ //! RSI_ENABLE or RSI_DISABLE High performance socket #define HIGH_PERFORMANCE_ENABLE RSI_ENABLE //@ RSI_ENABLE or RSI_DISABLE High performance socket -#define TOTAL_SOCKETS 10 //@ Total number of sockets. TCP TX + TCP RX + UDP TX + UDP RX -#define TOTAL_TCP_SOCKETS 4 //@ Total TCP sockets. TCP TX + TCP RX -#define TOTAL_UDP_SOCKETS 4 //@ Total UDP sockets. UDP TX + UDP RX -#define TCP_TX_ONLY_SOCKETS 0 //@ Total TCP TX only sockets. TCP TX -#define TCP_RX_ONLY_SOCKETS 0 //@ Total TCP RX only sockets. TCP RX -#define UDP_TX_ONLY_SOCKETS 0 //@ Total UDP TX only sockets. UDP TX -#define UDP_RX_ONLY_SOCKETS 0 //@ Total UDP RX only sockets. UDP RX -#define TCP_RX_HIGH_PERFORMANCE_SOCKETS 1 //@ Total TCP RX High Performance sockets -#define TCP_RX_WINDOW_SIZE_CAP 10 //@ TCP RX Window size -#define TCP_RX_WINDOW_DIV_FACTOR 10 //@ TCP RX Window division factor + +#define TOTAL_SOCKETS 1 //@ Total number of sockets. TCP TX + TCP RX + UDP TX + UDP RX +#define TOTAL_TCP_SOCKETS 1 //@ Total TCP sockets. TCP TX + TCP RX +#define TOTAL_UDP_SOCKETS 0 //@ Total UDP sockets. UDP TX + UDP RX +#define TCP_TX_ONLY_SOCKETS 0 //@ Total TCP TX only sockets. TCP TX +#define TCP_RX_ONLY_SOCKETS 1 //@ Total TCP RX only sockets. TCP RX +#define UDP_TX_ONLY_SOCKETS 0 //@ Total UDP TX only sockets. UDP TX +#define UDP_RX_ONLY_SOCKETS 0 //@ Total UDP RX only sockets. UDP RX +#define TCP_RX_HIGH_PERFORMANCE_SOCKETS 1 //@ Total TCP RX High Performance sockets +#define TCP_RX_WINDOW_SIZE_CAP 10 //@ TCP RX Window size +#define TCP_RX_WINDOW_DIV_FACTOR 10 //@ TCP RX Window division factor /*=======================================================================*/ //! Socket Create parameters @@ -384,12 +354,6 @@ //! Timeout for PING_REQUEST #define RSI_PING_REQ_TIMEOUT_MS 1000 -//! Provide HTTP/HTTPS response status code indication to application e.g 200, 404 etc -/*=======================================================================*/ -//! Enable or Diable feature -#define RSI_HTTP_STATUS_INDICATION_EN RSI_DISABLE -/*=======================================================================*/ - //! Store Config Profile parameters /*=======================================================================*/ @@ -470,7 +434,7 @@ //! To configure listen interval #define RSI_CONFIG_CLIENT_LISTEN_INTERVAL 0 //! To configure SSID -#define RSI_CONFIG_CLIENT_SSID "Matter_9116" +#define RSI_CONFIG_CLIENT_SSID "SILABS_AP" //! RSI_BAND_2P4GHZ(2.4GHz) or RSI_BAND_5GHZ(5GHz) or RSI_DUAL_BAND #define RSI_CONFIG_CLIENT_BAND RSI_BAND_2P4GHZ //! To configure channel number diff --git a/examples/platform/silabs/SiWx917/rs911x/wfx_rsi.h b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h similarity index 85% rename from examples/platform/silabs/SiWx917/rs911x/wfx_rsi.h rename to examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h index 380fc8f29e1693..4309e97ccc04d5 100644 --- a/examples/platform/silabs/SiWx917/rs911x/wfx_rsi.h +++ b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi.h @@ -21,11 +21,11 @@ * Interface to RSI Sapis */ -#define WFX_RSI_WLAN_TASK_SZ (1024 + 512 + 256) /* Unknown how big this should be */ -#define WFX_RSI_TASK_SZ (1024 + 1024) /* Stack for the WFX/RSI task */ -#define WFX_RSI_BUF_SZ (1024 * 10) /* May need tweak */ -#define WFX_RSI_CONFIG_MAX_JOIN 5 /* Max join retries */ -#define WFX_RSI_NUM_TIMERS 2 /* Number of RSI timers to alloc */ +#define WFX_RSI_WLAN_TASK_SZ (1024 + 512 + 256 + 1024 + 512) /* Unknown how big this should be */ +#define WFX_RSI_TASK_SZ (1024 + 1024 + 1024) /* Stack for the WFX/RSI task */ +#define WFX_RSI_BUF_SZ (1024 * 15) /* May need tweak */ +#define WFX_RSI_CONFIG_MAX_JOIN 5 /* Max join retries */ +#define WFX_RSI_NUM_TIMERS 2 /* Number of RSI timers to alloc */ /* * Various events fielded by the wfx_rsi task @@ -57,6 +57,8 @@ struct wfx_rsi EventGroupHandle_t events; TaskHandle_t drv_task; TaskHandle_t wlan_task; + TaskHandle_t init_task; + TaskHandle_t ble_task; uint16_t dev_state; uint16_t ap_chan; /* The chan our STA is using */ wfx_wifi_provision_t sec; diff --git a/examples/platform/silabs/SiWx917/rs911x/wfx_rsi_host.c b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi_host.c similarity index 99% rename from examples/platform/silabs/SiWx917/rs911x/wfx_rsi_host.c rename to examples/platform/silabs/SiWx917/SiWx917/wfx_rsi_host.c index a55e0aeb5cab2e..f44b6e9b8f7ff0 100644 --- a/examples/platform/silabs/SiWx917/rs911x/wfx_rsi_host.c +++ b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsi_host.c @@ -15,15 +15,11 @@ * limitations under the License. */ +#include "stdbool.h" #include #include #include -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" #include "sl_status.h" #include "FreeRTOS.h" @@ -71,6 +67,11 @@ sl_status_t wfx_wifi_start(void) return SL_STATUS_OK; } +int32_t wfx_rsi_platform() +{ + return wfx_rsi_init_platform(); +} + /********************************************************************* * @fn void wfx_enable_sta_mode(void) * @brief diff --git a/examples/platform/silabs/SiWx917/rs911x/wfx_rsidev.c b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsidev.c similarity index 99% rename from examples/platform/silabs/SiWx917/rs911x/wfx_rsidev.c rename to examples/platform/silabs/SiWx917/SiWx917/wfx_rsidev.c index 8d8a3c1803382b..d7a464151cac53 100644 --- a/examples/platform/silabs/SiWx917/rs911x/wfx_rsidev.c +++ b/examples/platform/silabs/SiWx917/SiWx917/wfx_rsidev.c @@ -223,7 +223,7 @@ sl_status_t sl_wfx_host_init_bus(void) USART_InitSync_TypeDef usartInit = USART_INITSYNC_DEFAULT; res = sl_wfx_host_spi_set_config(USART); - if (res != SPI_CONFIG_SUCCESS) + if (res != SPI_CONFIG_SUCESS) { return SL_STATUS_FAIL; } diff --git a/examples/platform/silabs/SiWx917/EFR32DeviceDataProvider.cpp b/examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.cpp similarity index 99% rename from examples/platform/silabs/SiWx917/EFR32DeviceDataProvider.cpp rename to examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.cpp index 6e097ffa4db0e2..9116c26f2c4607 100644 --- a/examples/platform/silabs/SiWx917/EFR32DeviceDataProvider.cpp +++ b/examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.cpp @@ -15,7 +15,7 @@ * limitations under the License. */ -#include "EFR32DeviceDataProvider.h" +#include "SiWx917DeviceDataProvider.h" #include #include #include diff --git a/examples/platform/silabs/SiWx917/EFR32DeviceDataProvider.h b/examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.h similarity index 100% rename from examples/platform/silabs/SiWx917/EFR32DeviceDataProvider.h rename to examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider.h diff --git a/examples/platform/silabs/SiWx917/TemperatureSensor.cpp b/examples/platform/silabs/SiWx917/TemperatureSensor.cpp deleted file mode 100644 index 69ba106fd69872..00000000000000 --- a/examples/platform/silabs/SiWx917/TemperatureSensor.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "TemperatureSensor.h" - -#ifdef __cplusplus -extern "C" { -#endif -// This is a C implementation. Need the ifdef __cplusplus else we get linking issues -#include "sl_sensor_rht.h" - -#ifdef __cplusplus -} -#endif - -namespace TemperatureSensor { -constexpr uint16_t kSensorTemperatureOffset = 800; - -sl_status_t Init() -{ - return sl_sensor_rht_init(); -} - -sl_status_t GetTemp(uint32_t * relativeHumidity, int16_t * temperature) -{ - // Sensor resolution 0.001 C - // DataModel resolution 0.01 C - int32_t temp; - sl_status_t status = sl_sensor_rht_get(relativeHumidity, &temp); - *temperature = static_cast(temp / 10) - kSensorTemperatureOffset; - return status; -} -}; // namespace TemperatureSensor diff --git a/examples/platform/silabs/SiWx917/board_config.h b/examples/platform/silabs/SiWx917/board_config.h index 8c495b4fa7f513..ed92fdd145a1c7 100644 --- a/examples/platform/silabs/SiWx917/board_config.h +++ b/examples/platform/silabs/SiWx917/board_config.h @@ -28,7 +28,7 @@ /** * @file - * This file includes dev borad compile-time configuration constants for efr32. + * This file includes dev board compile-time configuration constants for SiWx917. * */ diff --git a/examples/platform/silabs/SiWx917/device/inc/system_si917.h b/examples/platform/silabs/SiWx917/device/inc/system_si917.h new file mode 100644 index 00000000000000..9c566512c5425a --- /dev/null +++ b/examples/platform/silabs/SiWx917/device/inc/system_si917.h @@ -0,0 +1,167 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "core_cm4.h" /* Cortex-M4 processor and core peripherals */ +#include +//#include "cmsis_gcc.h" + +/******************************************************************************* + * @addtogroup Parts + * @{ + ******************************************************************************/ +/******************************************************************************* + * @addtogroup EFR32 EFR32 + * @{ + ******************************************************************************/ + +/******************************************************************************* + ****************************** TYPEDEFS *********************************** + ******************************************************************************/ + +/* Interrupt vectortable entry */ +typedef union +{ + void (*VECTOR_TABLE_Type)(void); + void * topOfStack; +} tVectorEntry; + +/******************************************************************************* + ************************** GLOBAL VARIABLES ******************************* + ******************************************************************************/ +//#ifndef CCP_SI917_BRINGUP +extern uint32_t SystemCoreClock; /**< System Clock Frequency (Core Clock) */ +//#endif /* CCP_SI917_BRINGUP */ +extern uint32_t SystemHfrcoFreq; /**< System HFRCO frequency */ + +/******************************************************************************* + ***************************** PROTOTYPES ********************************** + ******************************************************************************/ + +void Reset_Handler(void); /**< Reset Handler */ +void NMI_Handler(void); /**< NMI Handler */ +void HardFault_Handler(void); /**< Hard Fault Handler */ +void MemManage_Handler(void); /**< MPU Fault Handler */ +void BusFault_Handler(void); /**< Bus Fault Handler */ +void UsageFault_Handler(void); /**< Usage Fault Handler */ +void SVC_Handler(void); /**< SVCall Handler */ +void DebugMon_Handler(void); /**< Debug Monitor Handler */ +void PendSV_Handler(void); /**< PendSV Handler */ +void SysTick_Handler(void); /**< SysTick Handler */ + +void EMU_IRQHandler(void); /**< EMU IRQ Handler */ +void FRC_PRI_IRQHandler(void); /**< FRC_PRI IRQ Handler */ +void WDOG0_IRQHandler(void); /**< WDOG0 IRQ Handler */ +void WDOG1_IRQHandler(void); /**< WDOG1 IRQ Handler */ +void FRC_IRQHandler(void); /**< FRC IRQ Handler */ +void MODEM_IRQHandler(void); /**< MODEM IRQ Handler */ +void RAC_SEQ_IRQHandler(void); /**< RAC_SEQ IRQ Handler */ +void RAC_RSM_IRQHandler(void); /**< RAC_RSM IRQ Handler */ +void BUFC_IRQHandler(void); /**< BUFC IRQ Handler */ +void LDMA_IRQHandler(void); /**< LDMA IRQ Handler */ +void GPIO_EVEN_IRQHandler(void); /**< GPIO_EVEN IRQ Handler */ +void TIMER0_IRQHandler(void); /**< TIMER0 IRQ Handler */ +void USART0_RX_IRQHandler(void); /**< USART0_RX IRQ Handler */ +void USART0_TX_IRQHandler(void); /**< USART0_TX IRQ Handler */ +void ACMP0_IRQHandler(void); /**< ACMP0 IRQ Handler */ +void ADC0_IRQHandler(void); /**< ADC0 IRQ Handler */ +void IDAC0_IRQHandler(void); /**< IDAC0 IRQ Handler */ +void I2C0_IRQHandler(void); /**< I2C0 IRQ Handler */ +void GPIO_ODD_IRQHandler(void); /**< GPIO_ODD IRQ Handler */ +void TIMER1_IRQHandler(void); /**< TIMER1 IRQ Handler */ +void USART1_RX_IRQHandler(void); /**< USART1_RX IRQ Handler */ +void USART1_TX_IRQHandler(void); /**< USART1_TX IRQ Handler */ +void LEUART0_IRQHandler(void); /**< LEUART0 IRQ Handler */ +void PCNT0_IRQHandler(void); /**< PCNT0 IRQ Handler */ +void CMU_IRQHandler(void); /**< CMU IRQ Handler */ +void MSC_IRQHandler(void); /**< MSC IRQ Handler */ +void CRYPTO0_IRQHandler(void); /**< CRYPTO IRQ Handler */ +void LETIMER0_IRQHandler(void); /**< LETIMER0 IRQ Handler */ +void AGC_IRQHandler(void); /**< AGC IRQ Handler */ +void PROTIMER_IRQHandler(void); /**< PROTIMER IRQ Handler */ +void RTCC_IRQHandler(void); /**< RTCC IRQ Handler */ +void SYNTH_IRQHandler(void); /**< SYNTH IRQ Handler */ +void CRYOTIMER_IRQHandler(void); /**< CRYOTIMER IRQ Handler */ +void RFSENSE_IRQHandler(void); /**< RFSENSE IRQ Handler */ +void FPUEH_IRQHandler(void); /**< FPUEH IRQ Handler */ +void SMU_IRQHandler(void); /**< SMU IRQ Handler */ +void WTIMER0_IRQHandler(void); /**< WTIMER0 IRQ Handler */ +void WTIMER1_IRQHandler(void); /**< WTIMER1 IRQ Handler */ +void PCNT1_IRQHandler(void); /**< PCNT1 IRQ Handler */ +void PCNT2_IRQHandler(void); /**< PCNT2 IRQ Handler */ +void USART2_RX_IRQHandler(void); /**< USART2_RX IRQ Handler */ +void USART2_TX_IRQHandler(void); /**< USART2_TX IRQ Handler */ +void I2C1_IRQHandler(void); /**< I2C1 IRQ Handler */ +void USART3_RX_IRQHandler(void); /**< USART3_RX IRQ Handler */ +void USART3_TX_IRQHandler(void); /**< USART3_TX IRQ Handler */ +void VDAC0_IRQHandler(void); /**< VDAC0 IRQ Handler */ +void CSEN_IRQHandler(void); /**< CSEN IRQ Handler */ +void LESENSE_IRQHandler(void); /**< LESENSE IRQ Handler */ +void CRYPTO1_IRQHandler(void); /**< CRYPTO1 IRQ Handler */ +void TRNG0_IRQHandler(void); /**< TRNG0 IRQ Handler */ +void SYSCFG_IRQHandler(void); /**< SYSCFG IRQ Handler */ + +uint32_t SystemCoreClockGet(void); + +/******************************************************************************* + * @brief + * Update CMSIS SystemCoreClock variable. + * + * @details + * CMSIS defines a global variable SystemCoreClock + *that shall hold the core frequency in Hz. If the + *core frequency is dynamically changed, the variable + *must be kept updated in order to be CMSIS compliant. + * + * Notice that only if changing the core clock + *frequency through the EFR CMU API, this variable + *will be kept updated. This function is only provided + * for CMSIS compliance and if a user modifies the + *the core clock outside the CMU API. + ******************************************************************************/ +#ifndef CCP_SI917_BRINGUP +static __INLINE void SystemCoreClockUpdate(void) +{ + (void) SystemCoreClockGet(); +} +#endif /* CCP_SI917_BRINGUP */ + +uint32_t SystemMaxCoreClockGet(void); + +void SystemInit(void); +uint32_t SystemHFClockGet(void); + +uint32_t SystemHFXOClockGet(void); +void SystemHFXOClockSet(uint32_t freq); + +uint32_t SystemLFRCOClockGet(void); +uint32_t SystemULFRCOClockGet(void); + +uint32_t SystemLFXOClockGet(void); +void SystemLFXOClockSet(uint32_t freq); + +/** @} End of group */ +/** @} End of group Parts */ + +#ifdef __cplusplus +} +#endif diff --git a/examples/platform/silabs/SiWx917/device/src/startup_RS1xxxx.c b/examples/platform/silabs/SiWx917/device/src/startup_RS1xxxx.c new file mode 100644 index 00000000000000..a62ea68bbbef12 --- /dev/null +++ b/examples/platform/silabs/SiWx917/device/src/startup_RS1xxxx.c @@ -0,0 +1,530 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "rsi_ps_ram_func.h" +#include "system_RS1xxxx.h" +#include "system_si917.h" + +/*----------Stack Configuration-----------------------------------------------*/ +#define STACK_SIZE 0x00000C00 /*!< Stack size (in Words) */ +__attribute__((section(".co_stack"))) unsigned long pulStack[STACK_SIZE]; + +#define EXT_IRQ_COUNT 98 /**< Number of External (NVIC) interrupts */ // senthil copied from "efr32mg12p432f1024gl125.h" +#define TOTAL_INTERRUPTS (16 + EXT_IRQ_COUNT) + +#ifndef __INITIAL_SP +#define __INITIAL_SP __StackTop +#endif +#ifndef __VECTOR_TABLE_ATTRIBUTE +#define __VECTOR_TABLE_ATTRIBUTE __attribute__((used, section(".vectors"))) +#endif + +/*----------Macro definition--------------------------------------------------*/ +#define WEAK __attribute__((weak)) + +/*----------Declaration of the default fault handlers-------------------------*/ +// #ifndef __START +// extern void _start(void) __attribute__((noreturn)); /* Pre Main (C library entry point) */ +// #else +// extern int __START(void) __attribute__((noreturn)); /* main entry point */ +// #endif + +/* System exception vector handler */ +__attribute__((used)) void WEAK Reset_Handler(void); +void WEAK NMI_Handler(void); +void WEAK HardFault_Handler(void); +void WEAK MemManage_Handler(void); +void WEAK BusFault_Handler(void); +void WEAK UsageFault_Handler(void); +void WEAK SVC_Handler(void); +void WEAK DebugMon_Handler(void); +void WEAK PendSV_Handler(void); +void WEAK SysTick_Handler(void); + +/*Boot up functions*/ +void RSI_Default_Reset_Handler(void); +void RSI_Default_WakeUp_Handler(void); +void RSI_PS_RestoreCpuContext(void); + +void WEAK IRQ000_Handler(void); /*!< ULP Processor Interrupt 0 */ +void WEAK IRQ001_Handler(void); /*!< ULP Processor Interrupt 1 */ +void WEAK IRQ002_Handler(void); /*!< ULP Processor Interrupt 2 */ +void WEAK IRQ003_Handler(void); /*!< ULP Processor Interrupt 3 */ +void WEAK IRQ004_Handler(void); /*!< ULP Processor Interrupt 4 */ +void WEAK IRQ005_Handler(void); /*!< ULP Processor Interrupt 5 */ +void WEAK IRQ006_Handler(void); /*!< ULP Processor Interrupt 6 */ +void WEAK IRQ007_Handler(void); /*!< ULP Processor Interrupt 7 */ +void WEAK IRQ008_Handler(void); /*!< ULP Processor Interrupt 8 */ +void WEAK IRQ009_Handler(void); /*!< ULP Processor Interrupt 9 */ +void WEAK IRQ010_Handler(void); /*!< ULP Processor Interrupt 10 */ +void WEAK IRQ011_Handler(void); /*!< ULP Processor Interrupt 11 */ +void WEAK IRQ012_Handler(void); /*!< ULP Processor Interrupt 12 */ +void WEAK IRQ013_Handler(void); /*!< ULP Processor Interrupt 13 */ +void WEAK IRQ014_Handler(void); /*!< ULP Processor Interrupt 14 */ +void WEAK IRQ015_Handler(void); /*!< ULP Processor Interrupt 15 */ +void WEAK IRQ016_Handler(void); /*!< ULP Processor Interrupt 15 */ +void WEAK IRQ017_Handler(void); /*!< ULP Processor Interrupt 17 */ +void WEAK IRQ018_Handler(void); /*!< ULP Processor Interrupt 18 */ +void WEAK IRQ019_Handler(void); /*!< ULP Processor Interrupt 19 */ +void WEAK IRQ020_Handler(void); /*!< Sleep Sensor Interrupts 0 */ /*WDT*/ +void WEAK IRQ021_Handler(void); /*!< Sleep Sensor Interrupts 1 */ +void WEAK IRQ022_Handler(void); /*!< Sleep Sensor Interrupts 2 */ +void WEAK IRQ023_Handler(void); /*!< Sleep Sensor Interrupts 3 */ +void WEAK IRQ024_Handler(void); /*!< Sleep Sensor Interrupts 4 */ +void WEAK IRQ025_Handler(void); /*!< Sleep Sensor Interrupts 5 */ +void WEAK IRQ026_Handler(void); /*!< Sleep Sensor Interrupts 6 */ +void WEAK IRQ027_Handler(void); /*!< Sleep Sensor Interrupts 7 */ +void WEAK IRQ028_Handler(void); /*!< Sleep Sensor Interrupts 8 */ /*Alarm*/ +void WEAK IRQ029_Handler(void); /*!< Sleep Sensor Interrupts 9 */ /*Msec and sec interrupt */ +void WEAK IRQ030_Handler(void); /*!< Reserved */ +void WEAK IRQ031_Handler(void); /*!< M4SS DMA interrupt */ +void WEAK IRQ032_Handler(void); /*!< Reserved */ +void WEAK IRQ033_Handler(void); /*!< M4SS DMA interrupt */ +void WEAK IRQ034_Handler(void); /*!< M4SS SCT interrupt */ +void WEAK HIF1_IRQHandler(void); /*!< HIF Interrupt 1 */ +void WEAK HIF2_IRQHandler(void); /*!< HIF Interrupt 2 */ +void WEAK IRQ037_Handler(void); /*!< SIO Interrupt */ +void WEAK IRQ038_Handler(void); /*!< USART 1 Interrupt */ +void WEAK IRQ039_Handler(void); /*!< Reserved */ +void WEAK IRQ040_Handler(void); /*!< Reserved */ +void WEAK IRQ041_Handler(void); /*!< Reserved */ +void WEAK IRQ042_Handler(void); /*!< I2C Interrupt */ +void WEAK IRQ043_Handler(void); /*!< Reserved */ +void WEAK IRQ044_Handler(void); /*!< SSI Slave Interrupt */ +void WEAK IRQ045_Handler(void); /*!< Reserved */ +void WEAK IRQ046_Handler(void); /*!< GSPI Master 1 Interrupt */ +void WEAK IRQ047_Handler(void); /*!< Reserved */ +void WEAK IRQ048_Handler(void); /*!< MCPWM Interrupt */ +void WEAK IRQ049_Handler(void); /*!< QEI Interrupt */ +void WEAK IRQ050_Handler(void); /*!< GPIO Group Interrupt 0 */ +void WEAK IRQ051_Handler(void); /*!< GPIO Group Interrupt 1 */ +void WEAK IRQ052_Handler(void); /*!< GPIO Pin Interrupt 0 */ +void WEAK IRQ053_Handler(void); /*!< GPIO Pin Interrupt 1 */ +void WEAK IRQ054_Handler(void); /*!< GPIO Pin Interrupt 2 */ +void WEAK IRQ055_Handler(void); /*!< GPIO Pin Interrupt 3 */ +void WEAK IRQ056_Handler(void); /*!< GPIO Pin Interrupt 4 */ +void WEAK IRQ057_Handler(void); /*!< GPIO Pin Interrupt 5 */ +void WEAK IRQ058_Handler(void); /*!< GPIO Pin Interrupt 6 */ +void WEAK IRQ059_Handler(void); /*!< GPIO Pin Interrupt 7 */ +void WEAK IRQ060_Handler(void); /*!< QSPI Interrupt */ +void WEAK IRQ061_Handler(void); /*!< I2C 2 Interrupt */ +void WEAK IRQ062_Handler(void); /*!< Ethernet Interrupt */ +void WEAK IRQ063_Handler(void); /*!< Reserved */ +void WEAK IRQ064_Handler(void); /*!< I2S master Interrupt */ +void WEAK IRQ065_Handler(void); /*!< Reserved */ +void WEAK IRQ066_Handler(void); /*!< Can 1 Interrupt */ +void WEAK IRQ067_Handler(void); /*!< Reserved */ +void WEAK IRQ068_Handler(void); /*!< SDMEM Interrupt */ +void WEAK IRQ069_Handler(void); /*!< PLL clock ind Interrupt */ +void WEAK IRQ070_Handler(void); /*!< Reserved */ +void WEAK IRQ071_Handler(void); /*!< CCI system Interrupt Out */ +void WEAK IRQ072_Handler(void); /*!< FPU exception */ +void WEAK IRQ073_Handler(void); /*!< USB INTR */ +void WEAK IRQ074_Handler(void); /*!< TASS_P2P_INTR */ +void WEAK IRQ075_Handler(void); /*!< WLAN Band1 intr0 */ +void WEAK IRQ076_Handler(void); /*!< WLAN Band1 intr1 */ +void WEAK IRQ077_Handler(void); /*!< Reserved */ +void WEAK IRQ078_Handler(void); /*!< Reserved */ +void WEAK IRQ079_Handler(void); /*!< BT intr */ +void WEAK IRQ080_Handler(void); /*!< ZB intr */ +void WEAK IRQ081_Handler(void); /*!< Reserved */ +void WEAK IRQ082_Handler(void); /*!< Modem disabled mode trigger intr */ +void WEAK IRQ083_Handler(void); /*!< gpio intr */ +void WEAK IRQ084_Handler(void); /*!< uart intr */ +void WEAK IRQ085_Handler(void); /*!< watch dog level intr */ +void WEAK IRQ086_Handler(void); /*!< ULP Sleep sensor interrupt */ +void WEAK IRQ087_Handler(void); /*!< ECDH intr */ +void WEAK IRQ088_Handler(void); /*!< DH intr */ +void WEAK IRQ089_Handler(void); /*!< QSPI intr */ +void WEAK IRQ090_Handler(void); /*!< ULP processor interrupt TASS */ +void WEAK IRQ091_Handler(void); /*!< Sys Tick Timer */ +void WEAK IRQ092_Handler(void); /*!< Real Timer interrupt */ +void WEAK IRQ093_Handler(void); /*!< PLL lock interrupt */ +void WEAK IRQ094_Handler(void); /*!< Reserved */ +void WEAK IRQ095_Handler(void); /*!< UART2 Interrupt */ +void WEAK IRQ096_Handler(void); /*!< I2S Interrupt */ +void WEAK IRQ097_Handler(void); /*!< I2C Interrupt */ +void WEAK IRQ098_Handler(void); /*!< RESERVED */ + +/*----------Symbols defined in linker script----------------------------------*/ +extern unsigned long _sidata; /*!< Start address for the initialization + values of the .data section. */ +extern unsigned long _sdata; /*!< Start address for the .data section */ +extern unsigned long _edata; /*!< End address for the .data section */ +extern unsigned long _sbss; /*!< Start address for the .bss section */ +extern unsigned long _ebss; /*!< End address for the .bss section */ +extern void _eram; /*!< End address for ram */ +extern uint32_t __etext; +extern unsigned long __StackTop; + +/*----------Function prototypes-----------------------------------------------*/ +extern int main(void); /*!< The entry point for the application */ +void Default_Reset_Handler(void); /*!< Default reset handler */ +static void Default_Handler(void); /*!< Default exception handler */ +/** + *@brief The minimal vector table for a Cortex M4. Note that the proper constructs + * must be placed on this to ensure that it ends up at physical address + * 0x00000000. + */ + +//(void *)0x300001 +/*CCP new */ +extern const tVectorEntry __VECTOR_TABLE[TOTAL_INTERRUPTS]; +const tVectorEntry __VECTOR_TABLE[TOTAL_INTERRUPTS] __attribute__((aligned(512))) __VECTOR_TABLE_ATTRIBUTE = { + /* Cortex-M Exception Handlers */ + { .topOfStack = &__INITIAL_SP }, /* Initial Stack Pointer */ + /*{ (void *)&pulStack[STACK_SIZE - 1] },*/ + { (void *) 0x300001 }, /* Reset Handler : IN CCP Platform system start + from bootloader which inturn call reset handler */ + { NMI_Handler }, /* NMI Handler */ + { HardFault_Handler }, /* Hard Fault Handler */ + { MemManage_Handler }, /* MPU Fault Handler */ + { BusFault_Handler }, /* Bus Fault Handler */ + { UsageFault_Handler }, /* Usage Fault Handler */ + { 0 }, /* Reserved */ + { 0 }, /* Reserved */ + { 0 }, /* Reserved */ + { 0 }, /* Reserved */ + { SVC_Handler }, /* SVCall Handler */ + { DebugMon_Handler }, /* Debug Monitor Handler */ + { 0 }, /* Application properties*/ + { PendSV_Handler }, /* PendSV Handler */ + { SysTick_Handler }, /* SysTick Handler */ + + /* External interrupts */ + + { IRQ000_Handler }, /* 0 */ + { IRQ001_Handler }, /* 1 */ + { IRQ002_Handler }, /* 2 */ + { IRQ003_Handler }, /* 3 */ + { IRQ004_Handler }, /* 4 */ + { IRQ005_Handler }, /* 5 */ + { IRQ006_Handler }, /* 6 */ + { IRQ007_Handler }, /* 7 */ + { IRQ008_Handler }, /* 8 */ + { IRQ009_Handler }, /* 9 */ + { IRQ010_Handler }, /* 10 */ + { IRQ011_Handler }, /* 11 */ + { IRQ012_Handler }, /* 12 */ + { IRQ013_Handler }, /* 13 */ + { IRQ014_Handler }, /* 14 */ + { IRQ015_Handler }, /* 15 */ + { IRQ016_Handler }, /* 16 */ + { IRQ017_Handler }, /* 17 */ + { IRQ018_Handler }, /* 18 */ + { IRQ019_Handler }, /* 19 */ + { IRQ020_Handler }, /* 20 */ + { IRQ021_Handler }, /* 21 */ + { IRQ022_Handler }, /* 22 */ + { IRQ023_Handler }, /* 23 */ + { IRQ024_Handler }, /* 24 */ + { IRQ025_Handler }, /* 25 */ + { IRQ026_Handler }, /* 26 */ + { IRQ027_Handler }, /* 27 */ + { IRQ028_Handler }, /* 28 */ + { IRQ029_Handler }, /* 29 */ + { (void *) &__StackTop - 0x0c }, /* 30 */ + { IRQ031_Handler }, /* 31 */ + { RSI_Default_Reset_Handler }, /* 32 */ + { IRQ033_Handler }, /* 33 */ + { IRQ034_Handler }, /* 34 */ + { HIF1_IRQHandler }, /* 35 */ + { HIF2_IRQHandler }, /* 36 */ + { IRQ037_Handler }, /* 37 */ + { IRQ038_Handler }, /* 38 */ + { IRQ039_Handler }, /* 39 */ + { RSI_PS_RestoreCpuContext }, /* 40 */ + { IRQ041_Handler }, /* 41 */ + { IRQ042_Handler }, /* 42 */ + { (void *) 0x10AD10AD }, /* 43 */ + { IRQ044_Handler }, /* 44 */ + { 0 }, /* 45 */ + { IRQ046_Handler }, /* 46 */ + { IRQ047_Handler }, /* 47 */ + { IRQ048_Handler }, /* 48 */ + { IRQ049_Handler }, /* 49 */ + { IRQ050_Handler }, /* 50 - Reserved */ + { IRQ051_Handler }, + { IRQ052_Handler }, + { IRQ053_Handler }, + { IRQ054_Handler }, + { IRQ055_Handler }, + { IRQ056_Handler }, + { IRQ057_Handler }, + { IRQ058_Handler }, + { IRQ059_Handler }, + { IRQ060_Handler }, + { IRQ061_Handler }, + { IRQ062_Handler }, + { IRQ063_Handler }, + { IRQ064_Handler }, + { 0 }, + { IRQ066_Handler }, + { 0 }, + { IRQ068_Handler }, + { IRQ069_Handler }, + { 0 }, + { IRQ071_Handler }, + { IRQ072_Handler }, + { IRQ073_Handler }, + { IRQ074_Handler }, + { IRQ075_Handler }, + { IRQ076_Handler }, + { 0 }, + { 0 }, + { IRQ079_Handler }, + { IRQ080_Handler }, + { 0 }, + { IRQ082_Handler }, + { IRQ083_Handler }, + { IRQ084_Handler }, + { IRQ085_Handler }, + { IRQ086_Handler }, + { IRQ087_Handler }, + { IRQ088_Handler }, + { IRQ089_Handler }, + { IRQ090_Handler }, + { IRQ091_Handler }, + { IRQ092_Handler }, + { IRQ093_Handler }, + { 0 }, + { IRQ095_Handler }, + { 0 }, + { IRQ097_Handler }, +}; + +/** + * @brief This is the code that gets never called, Dummy handler + * @param None + * @retval None + */ +void Default_Reset_Handler(void) +{ + /*Generic Default reset handler for CM4 */ + while (1) + ; +} + +void Copy_Table() +{ + uint32_t *pSrc, *pDest; + extern uint32_t __etext; + extern uint32_t __data_start__; + extern uint32_t __data_end__; + pSrc = &__etext; + pDest = &__data_start__; + + for (; pDest < &__data_end__;) + { + *pDest++ = *pSrc++; + } +} + +void Zero_Table() +{ + uint32_t * pDest; + extern uint32_t __bss_start__; + extern uint32_t __bss_end__; + pDest = &__bss_start__; + + for (; pDest < &__bss_end__;) + { + *pDest++ = 0UL; + } +} +void Reset_Handler(void) +{ +#ifndef __NO_SYSTEM_INIT + SystemInit(); /* CMSIS System Initialization */ +#endif + +#ifdef BOOTLOADER_ENABLE + SystemInit2(); +#endif /* BOOTLOADER_ENABLE */ + +#if defined(__GNUC__) && defined(__START) + Copy_Table(); + Zero_Table(); + __START(); +#else +#if 0 // senthil_ccp + __PROGRAM_START(); /* Enter PreMain (C library entry point) */ +#else + Copy_Table(); + Zero_Table(); + _start(); +#endif +#endif /* __GNUC__ */ +} + +void RSI_Default_Reset_Handler(void) +{ +#ifndef __NO_SYSTEM_INIT + SystemInit(); /* CMSIS System Initialization */ +#endif + +#ifdef BOOTLOADER_ENABLE + SystemInit2(); +#endif /* BOOTLOADER_ENABLE */ + +#if defined(__GNUC__) && defined(__START) + Copy_Table(); + Zero_Table(); + __START(); +#else +#if 0 // senthil_ccp + __PROGRAM_START(); /* Enter PreMain (C library entry point) */ +#else + Copy_Table(); + Zero_Table(); + _start(); +#endif +#endif /* __GNUC__ */ +} + +/** + *@brief Provide weak aliases for each Exception handler to the Default_Handler. + * As they are weak aliases, any function with the same name will override + * this definition. + */ +//#pragma weak Reset_Handler = RSI_Default_Reset_Handler +#pragma weak NMI_Handler = Default_Handler +#pragma weak HardFault_Handler = Default_Handler +#pragma weak MemManage_Handler = Default_Handler +#pragma weak BusFault_Handler = Default_Handler +#pragma weak UsageFault_Handler = Default_Handler +#pragma weak SVC_Handler = Default_Handler +#pragma weak DebugMon_Handler = Default_Handler +#pragma weak PendSV_Handler = Default_Handler +#pragma weak SysTick_Handler = Default_Handler +/*----------------------------------external interrupts------------------------------ */ +#pragma weak IRQ000_Handler = Default_Handler +#pragma weak IRQ001_Handler = Default_Handler +#pragma weak IRQ002_Handler = Default_Handler +#pragma weak IRQ003_Handler = Default_Handler +#pragma weak IRQ004_Handler = Default_Handler +#pragma weak IRQ005_Handler = Default_Handler +#pragma weak IRQ006_Handler = Default_Handler +#pragma weak IRQ007_Handler = Default_Handler +#pragma weak IRQ008_Handler = Default_Handler +#pragma weak IRQ009_Handler = Default_Handler +#pragma weak IRQ010_Handler = Default_Handler +#pragma weak IRQ011_Handler = Default_Handler +#pragma weak IRQ012_Handler = Default_Handler +#pragma weak IRQ013_Handler = Default_Handler +#pragma weak IRQ014_Handler = Default_Handler +#pragma weak IRQ015_Handler = Default_Handler +#pragma weak IRQ016_Handler = Default_Handler +#pragma weak IRQ017_Handler = Default_Handler +#pragma weak IRQ018_Handler = Default_Handler +#pragma weak IRQ019_Handler = Default_Handler +#pragma weak IRQ020_Handler = Default_Handler +#pragma weak IRQ021_Handler = Default_Handler +#pragma weak IRQ022_Handler = Default_Handler +#pragma weak IRQ023_Handler = Default_Handler +#pragma weak IRQ024_Handler = Default_Handler +#pragma weak IRQ025_Handler = Default_Handler +#pragma weak IRQ026_Handler = Default_Handler +#pragma weak IRQ027_Handler = Default_Handler +#pragma weak IRQ028_Handler = Default_Handler +#pragma weak IRQ029_Handler = Default_Handler +#pragma weak IRQ030_Handler = Default_Handler +#pragma weak IRQ031_Handler = Default_Handler +#pragma weak IRQ032_Handler = Default_Handler +#pragma weak IRQ033_Handler = Default_Handler +#pragma weak IRQ034_Handler = Default_Handler +#pragma weak HIF1_IRQHandler = Default_Handler +#pragma weak HIF2_IRQHandler = Default_Handler +#pragma weak IRQ037_Handler = Default_Handler +#pragma weak IRQ038_Handler = Default_Handler +#pragma weak IRQ039_Handler = Default_Handler +#pragma weak IRQ040_Handler = Default_Handler +#pragma weak IRQ041_Handler = Default_Handler +#pragma weak IRQ042_Handler = Default_Handler +#pragma weak IRQ043_Handler = Default_Handler +#pragma weak IRQ044_Handler = Default_Handler +#pragma weak IRQ045_Handler = Default_Handler +#pragma weak IRQ046_Handler = Default_Handler +#pragma weak IRQ047_Handler = Default_Handler +#pragma weak IRQ048_Handler = Default_Handler +#pragma weak IRQ049_Handler = Default_Handler +#pragma weak IRQ050_Handler = Default_Handler +#pragma weak IRQ051_Handler = Default_Handler +#pragma weak IRQ052_Handler = Default_Handler +#pragma weak IRQ053_Handler = Default_Handler +#pragma weak IRQ054_Handler = Default_Handler +#pragma weak IRQ055_Handler = Default_Handler +#pragma weak IRQ056_Handler = Default_Handler +#pragma weak IRQ057_Handler = Default_Handler +#pragma weak IRQ058_Handler = Default_Handler +#pragma weak IRQ059_Handler = Default_Handler +#pragma weak IRQ060_Handler = Default_Handler +#pragma weak IRQ061_Handler = Default_Handler +#pragma weak IRQ062_Handler = Default_Handler +#pragma weak IRQ063_Handler = Default_Handler +#pragma weak IRQ064_Handler = Default_Handler +#pragma weak IRQ065_Handler = Default_Handler +#pragma weak IRQ066_Handler = Default_Handler +#pragma weak IRQ067_Handler = Default_Handler +#pragma weak IRQ068_Handler = Default_Handler +#pragma weak IRQ069_Handler = Default_Handler +#pragma weak IRQ070_Handler = Default_Handler +#pragma weak IRQ071_Handler = Default_Handler +#pragma weak IRQ072_Handler = Default_Handler +#pragma weak IRQ073_Handler = Default_Handler +#pragma weak IRQ074_Handler = Default_Handler +#pragma weak IRQ075_Handler = Default_Handler +#pragma weak IRQ076_Handler = Default_Handler +#pragma weak IRQ077_Handler = Default_Handler +#pragma weak IRQ078_Handler = Default_Handler +#pragma weak IRQ079_Handler = Default_Handler +#pragma weak IRQ080_Handler = Default_Handler +#pragma weak IRQ081_Handler = Default_Handler +#pragma weak IRQ082_Handler = Default_Handler +#pragma weak IRQ083_Handler = Default_Handler +#pragma weak IRQ084_Handler = Default_Handler +#pragma weak IRQ085_Handler = Default_Handler +#pragma weak IRQ086_Handler = Default_Handler +#pragma weak IRQ087_Handler = Default_Handler +#pragma weak IRQ088_Handler = Default_Handler +#pragma weak IRQ089_Handler = Default_Handler +#pragma weak IRQ090_Handler = Default_Handler +#pragma weak IRQ091_Handler = Default_Handler +#pragma weak IRQ092_Handler = Default_Handler +#pragma weak IRQ093_Handler = Default_Handler +#pragma weak IRQ094_Handler = Default_Handler +#pragma weak IRQ095_Handler = Default_Handler +#pragma weak IRQ096_Handler = Default_Handler +#pragma weak IRQ097_Handler = Default_Handler +#pragma weak IRQ098_Handler = Default_Handler + +/** + * @brief This is the code that gets called when the processor receives an + * unexpected interrupt. This simply enters an infinite loop, + * preserving the system state for examination by a debugger. + * @param None + * @retval None + */ +static void Default_Handler(void) +{ + /* Go into an infinite loop. */ + while (1) + { + } +} + +/*********************** (C) COPYRIGHT 2009 Coocox ************END OF FILE*****/ diff --git a/examples/platform/silabs/SiWx917/device/src/startup_si917.c b/examples/platform/silabs/SiWx917/device/src/startup_si917.c new file mode 100644 index 00000000000000..03cb7fffe07744 --- /dev/null +++ b/examples/platform/silabs/SiWx917/device/src/startup_si917.c @@ -0,0 +1,403 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "system_si917.h" +#include +#include +//#include "cmsis_gcc.h" + +#ifdef BOOTLOADER_ENABLE +#include "api/btl_interface.h" + +#endif + +#ifdef SL_APP_PROPERTIES +#include "api/application_properties.h" + +#endif + +#define EXT_IRQ_COUNT 51 /**< Number of External (NVIC) interrupts */ // senthil copied from "efr32mg12p432f1024gl125.h" +#define TOTAL_INTERRUPTS (16 + EXT_IRQ_COUNT) + +#ifdef BOOTLOADER_ENABLE +extern MainBootloaderTable_t mainStageTable; + +extern void SystemInit2(void); + +/*---------------------------------------------------------------------------- + * Exception / Interrupt Handler Function Prototype + *----------------------------------------------------------------------------*/ +typedef void (*VECTOR_TABLE_Type)(void); +#endif + +#ifdef SL_APP_PROPERTIES +extern ApplicationProperties_t sl_app_properties; + +/*---------------------------------------------------------------------------- + * Exception / Interrupt Handler Function Prototype + *----------------------------------------------------------------------------*/ +typedef void (*VECTOR_TABLE_Type)(void); +#endif + +/*--------------------------------------------------------------------------- + * External References + *---------------------------------------------------------------------------*/ +extern uint32_t __INITIAL_SP; +extern uint32_t __StackTop; + +#ifndef __INITIAL_SP +#define __INITIAL_SP __StackTop +#endif +#ifndef __VECTOR_TABLE_ATTRIBUTE +#define __VECTOR_TABLE_ATTRIBUTE __attribute__((used, section(".vectors"))) +#endif + +extern void __PROGRAM_START(void); + +#if defined(__START) && defined(__GNUC__) +extern int __START(void) __attribute__((noreturn)); /* main entry point */ +void Zero_Table(); +void Copy_Table(); +#endif /* __START */ + +/*--------------------------------------------------------------------------- + * Internal References + *---------------------------------------------------------------------------*/ +void Reset_Handler(void); +void Default_Handler(void); + +#if defined(__GNUC__) +#ifndef __STACK_SIZE +#define __STACK_SIZE 0x00000400 +#endif /* __STACK_SIZE */ + +#ifndef __HEAP_SIZE +#define __HEAP_SIZE 0x00000C00 +#endif /* __HEAP_SIZE */ +#endif /* __GNUC__ */ + +/*---------------------------------------------------------------------------- + * Exception / Interrupt Handler + *----------------------------------------------------------------------------*/ +/* Cortex-M Processor Exceptions */ +void NMI_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void HardFault_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void MemManage_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void BusFault_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void UsageFault_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void DebugMon_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void SVC_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void PendSV_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void SysTick_Handler(void) __attribute__((weak, alias("Default_Handler"))); +#ifndef SL_APP_PROPERTIES +/* Provide a dummy value for the sl_app_properties symbol. */ +void sl_app_properties(void); /* Prototype to please MISRA checkers. */ +void sl_app_properties(void) __attribute__((weak, alias("Default_Handler"))); +#endif + +/* Part Specific Interrupts */ + +void EMU_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void FRC_PRI_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void WDOG0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void WDOG1_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void FRC_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void MODEM_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void RAC_SEQ_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void RAC_RSM_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void BUFC_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void LDMA_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void GPIO_EVEN_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void TIMER0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void USART0_RX_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void USART0_TX_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void ACMP0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void ADC0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void IDAC0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void I2C0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void GPIO_ODD_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void TIMER1_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void USART1_RX_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void USART1_TX_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void LEUART0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void PCNT0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void CMU_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void MSC_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void CRYPTO0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void LETIMER0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void AGC_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void PROTIMER_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void RTCC_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void SYNTH_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void CRYOTIMER_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void RFSENSE_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void FPUEH_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void SMU_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void WTIMER0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void WTIMER1_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void PCNT1_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void PCNT2_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void USART2_RX_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void USART2_TX_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void I2C1_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void USART3_RX_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void USART3_TX_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void VDAC0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void CSEN_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void LESENSE_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void CRYPTO1_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); +void TRNG0_IRQHandler(void) __attribute__((weak, alias("Default_Handler"))); + +#if 0 // senthil_ccp + +#ifndef __PROGRAM_START + +/** + \brief Initializes data and bss sections + \details This default implementations initialized all data and additional bss + sections relying on .copy.table and .zero.table specified properly + in the used linker script. + + */ +void __cmsis_start(void) +{ + extern void _start(void) __NO_RETURN; + + typedef struct { + uint32_t const* src; + uint32_t* dest; + uint32_t wlen; + } __copy_table_t; + + typedef struct { + uint32_t* dest; + uint32_t wlen; + } __zero_table_t; + + extern const __copy_table_t __copy_table_start__; + extern const __copy_table_t __copy_table_end__; + extern const __zero_table_t __zero_table_start__; + extern const __zero_table_t __zero_table_end__; + + for (__copy_table_t const* pTable = &__copy_table_start__; pTable < &__copy_table_end__; ++pTable) { + for(uint32_t i=0u; iwlen; ++i) { + pTable->dest[i] = pTable->src[i]; + } + } + + for (__zero_table_t const* pTable = &__zero_table_start__; pTable < &__zero_table_end__; ++pTable) { + for(uint32_t i=0u; iwlen; ++i) { + pTable->dest[i] = 0u; + } + } + + _start(); +} + +#define __PROGRAM_START __cmsis_start +#endif + +#endif / senthil_ccp +/*---------------------------------------------------------------------------- + * Exception / Interrupt Vector table + *----------------------------------------------------------------------------*/ + +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpedantic" +#endif + +#if defined(__ICCARM__) +#pragma data_alignment = 512 +extern const tVectorEntry __VECTOR_TABLE[TOTAL_INTERRUPTS]; +const tVectorEntry __VECTOR_TABLE[TOTAL_INTERRUPTS] __VECTOR_TABLE_ATTRIBUTE = { +#elif defined(__GNUC__) +extern const tVectorEntry __VECTOR_TABLE[TOTAL_INTERRUPTS]; +// const tVectorEntry __VECTOR_TABLE[TOTAL_INTERRUPTS] __attribute__((aligned(512))) __VECTOR_TABLE_ATTRIBUTE = { +const tVectorEntry __VECTOR_TABLE[TOTAL_INTERRUPTS] __attribute__((aligned(512))) __VECTOR_TABLE_ATTRIBUTE = { +#else +extern const tVectorEntry __VECTOR_TABLE[TOTAL_INTERRUPTS]; +const tVectorEntry __VECTOR_TABLE[TOTAL_INTERRUPTS] __VECTOR_TABLE_ATTRIBUTE = { +#endif + /* Cortex-M Exception Handlers */ + { .topOfStack = &__INITIAL_SP }, /* Initial Stack Pointer */ + { Reset_Handler }, /* Reset Handler */ + { NMI_Handler }, /* NMI Handler */ + { HardFault_Handler }, /* Hard Fault Handler */ + { MemManage_Handler }, /* MPU Fault Handler */ + { BusFault_Handler }, /* Bus Fault Handler */ + { UsageFault_Handler }, /* Usage Fault Handler */ + { Default_Handler }, /* Reserved */ + { Default_Handler }, /* Reserved */ + { Default_Handler }, /* Reserved */ +#ifdef BOOTLOADER_ENABLE + { (VECTOR_TABLE_Type) &mainStageTable }, +#else + { Default_Handler }, /* Reserved */ +#endif + { SVC_Handler }, /* SVCall Handler */ + { DebugMon_Handler }, /* Debug Monitor Handler */ +#ifdef SL_APP_PROPERTIES + { (VECTOR_TABLE_Type) &sl_app_properties }, /* Application properties*/ +#else + { sl_app_properties }, /* Application properties*/ +#endif + { PendSV_Handler }, /* PendSV Handler */ + { SysTick_Handler }, /* SysTick Handler */ + + /* External interrupts */ + + { EMU_IRQHandler }, /* 0 */ + { FRC_PRI_IRQHandler }, /* 1 */ + { WDOG0_IRQHandler }, /* 2 */ + { WDOG1_IRQHandler }, /* 3 */ + { FRC_IRQHandler }, /* 4 */ + { MODEM_IRQHandler }, /* 5 */ + { RAC_SEQ_IRQHandler }, /* 6 */ + { RAC_RSM_IRQHandler }, /* 7 */ + { BUFC_IRQHandler }, /* 8 */ + { LDMA_IRQHandler }, /* 9 */ + { GPIO_EVEN_IRQHandler }, /* 10 */ + { TIMER0_IRQHandler }, /* 11 */ + { USART0_RX_IRQHandler }, /* 12 */ + { USART0_TX_IRQHandler }, /* 13 */ + { ACMP0_IRQHandler }, /* 14 */ + { ADC0_IRQHandler }, /* 15 */ + { IDAC0_IRQHandler }, /* 16 */ + { I2C0_IRQHandler }, /* 17 */ + { GPIO_ODD_IRQHandler }, /* 18 */ + { TIMER1_IRQHandler }, /* 19 */ + { USART1_RX_IRQHandler }, /* 20 */ + { USART1_TX_IRQHandler }, /* 21 */ + { LEUART0_IRQHandler }, /* 22 */ + { PCNT0_IRQHandler }, /* 23 */ + { CMU_IRQHandler }, /* 24 */ + { MSC_IRQHandler }, /* 25 */ + { CRYPTO0_IRQHandler }, /* 26 */ + { LETIMER0_IRQHandler }, /* 27 */ + { AGC_IRQHandler }, /* 28 */ + { PROTIMER_IRQHandler }, /* 29 */ + { RTCC_IRQHandler }, /* 30 */ + { SYNTH_IRQHandler }, /* 31 */ + { CRYOTIMER_IRQHandler }, /* 32 */ + { RFSENSE_IRQHandler }, /* 33 */ + { FPUEH_IRQHandler }, /* 34 */ + { SMU_IRQHandler }, /* 35 */ + { WTIMER0_IRQHandler }, /* 36 */ + { WTIMER1_IRQHandler }, /* 37 */ + { PCNT1_IRQHandler }, /* 38 */ + { PCNT2_IRQHandler }, /* 39 */ + { USART2_RX_IRQHandler }, /* 40 */ + { USART2_TX_IRQHandler }, /* 41 */ + { I2C1_IRQHandler }, /* 42 */ + { USART3_RX_IRQHandler }, /* 43 */ + { USART3_TX_IRQHandler }, /* 44 */ + { VDAC0_IRQHandler }, /* 45 */ + { CSEN_IRQHandler }, /* 46 */ + { LESENSE_IRQHandler }, /* 47 */ + { CRYPTO1_IRQHandler }, /* 48 */ + { TRNG0_IRQHandler }, /* 49 */ + { Default_Handler }, /* 50 - Reserved */ +}; + +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +//#if defined (__START) && defined (__GNUC__) //senthil_ccp +void Copy_Table() +{ + uint32_t *pSrc, *pDest; + extern uint32_t __etext; + extern uint32_t __data_start__; + extern uint32_t __data_end__; + pSrc = &__etext; + pDest = &__data_start__; + + for (; pDest < &__data_end__;) + { + *pDest++ = *pSrc++; + } +} + +void Zero_Table() +{ + uint32_t * pDest; + extern uint32_t __bss_start__; + extern uint32_t __bss_end__; + pDest = &__bss_start__; + + for (; pDest < &__bss_end__;) + { + *pDest++ = 0UL; + } +} +//#endif /* __START */ + +/*--------------------------------------------------------------------------- + * Reset Handler called on controller reset + *---------------------------------------------------------------------------*/ +#if 0 + void SysTick_Handler(void) +{ + SysTick_Handler(); +} +#endif + +void Reset_Handler(void) +{ +#ifndef __NO_SYSTEM_INIT + SystemInit(); /* CMSIS System Initialization */ +#endif + +#ifdef BOOTLOADER_ENABLE + SystemInit2(); +#endif /* BOOTLOADER_ENABLE */ + +#if defined(__GNUC__) && defined(__START) + Copy_Table(); + Zero_Table(); + __START(); +#else +#if 0 // senthil_ccp + __PROGRAM_START(); /* Enter PreMain (C library entry point) */ +#else + Copy_Table(); + Zero_Table(); + _start(); +#endif +#endif /* __GNUC__ */ +} + +#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wmissing-noreturn" +#endif + +/*---------------------------------------------------------------------------- + * Default Handler for Exceptions / Interrupts + *----------------------------------------------------------------------------*/ +void Default_Handler(void) +{ + while (true) + { + } +} + +#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) +#pragma clang diagnostic pop +#endif diff --git a/examples/platform/silabs/SiWx917/TemperatureSensor.h b/examples/platform/silabs/SiWx917/init_ccpPlatform.cpp similarity index 64% rename from examples/platform/silabs/SiWx917/TemperatureSensor.h rename to examples/platform/silabs/SiWx917/init_ccpPlatform.cpp index 116287e9a37155..0d5bb78bea9e7c 100644 --- a/examples/platform/silabs/SiWx917/TemperatureSensor.h +++ b/examples/platform/silabs/SiWx917/init_ccpPlatform.cpp @@ -17,12 +17,30 @@ * limitations under the License. */ -#pragma once +#include "AppConfig.h" +#include +#include -#include "sl_status.h" -#include +#ifdef __cplusplus +extern "C" { +#endif +#include +#include -namespace TemperatureSensor { -sl_status_t Init(); -sl_status_t GetTemp(uint32_t * relativeHumidity, int16_t * temperature); -}; // namespace TemperatureSensor +#include + +#include "init_ccpPlatform.h" + +void initAntenna(void); + +void init_ccpPlatform(void) +{ + +#if SILABS_LOG_ENABLED + silabsInitLog(); +#endif +} + +#ifdef __cplusplus +} +#endif diff --git a/examples/platform/silabs/SiWx917/init_efrPlatform.h b/examples/platform/silabs/SiWx917/init_ccpPlatform.h similarity index 96% rename from examples/platform/silabs/SiWx917/init_efrPlatform.h rename to examples/platform/silabs/SiWx917/init_ccpPlatform.h index aeb47b8aaed3d1..986e2fecb18dd9 100644 --- a/examples/platform/silabs/SiWx917/init_efrPlatform.h +++ b/examples/platform/silabs/SiWx917/init_ccpPlatform.h @@ -22,8 +22,7 @@ extern "C" { #endif -void init_efrPlatform(void); - +void init_ccpPlatform(void); #ifdef __cplusplus } #endif diff --git a/examples/platform/silabs/SiWx917/init_efrPlatform.cpp b/examples/platform/silabs/SiWx917/init_efrPlatform.cpp deleted file mode 100644 index 993b4fefe069f8..00000000000000 --- a/examples/platform/silabs/SiWx917/init_efrPlatform.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "AppConfig.h" -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif -#include -#include - -#include - -#if CHIP_ENABLE_OPENTHREAD -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "platform-efr32.h" - -#if OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE -#include "openthread/heap.h" -#endif // OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE -#endif // CHIP_ENABLE_OPENTHREAD - -#include "init_efrPlatform.h" -#include "sl_component_catalog.h" -#include "sl_mbedtls.h" -#include "sl_system_init.h" - -#if SL_SYSTEM_VIEW -#include "SEGGER_SYSVIEW.h" -#endif - -void initAntenna(void); - -void init_efrPlatform(void) -{ - sl_system_init(); - sl_mbedtls_init(); -#if SL_SYSTEM_VIEW - SEGGER_SYSVIEW_Conf(); - SEGGER_SYSVIEW_Start(); -#endif - -#if SILABS_LOG_ENABLED - silabsInitLog(); -#endif - -#if CHIP_ENABLE_OPENTHREAD - efr32RadioInit(); - efr32AlarmInit(); -#endif // CHIP_ENABLE_OPENTHREAD -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/platform/silabs/SiWx917/ldscripts/efr32mg12.ld b/examples/platform/silabs/SiWx917/ldscripts/SiWx917.ld similarity index 74% rename from examples/platform/silabs/SiWx917/ldscripts/efr32mg12.ld rename to examples/platform/silabs/SiWx917/ldscripts/SiWx917.ld index f9f4f55f8b9a73..13f0b226a4d9f6 100644 --- a/examples/platform/silabs/SiWx917/ldscripts/efr32mg12.ld +++ b/examples/platform/silabs/SiWx917/ldscripts/SiWx917.ld @@ -1,7 +1,6 @@ /* * - * Copyright (c) 2020 Project CHIP Authors - * All rights reserved. + * Copyright (c) 2022 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,40 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/***************************************************************************//** - * Linker script for Silicon Labs EFR32MG12P devices - ******************************************************************************* - * # License - * Copyright 2022 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************/ MEMORY { - FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 1048576 - RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 262144 + FLASH (rx) : ORIGIN = 0x08012000, LENGTH = 0x200000 + RAM (rwx) : ORIGIN = 0xC, LENGTH = 262144 } /* Linker script to place sections and symbol values. Should be used together @@ -146,10 +117,13 @@ SECTIONS } > FLASH __etext = ALIGN (4); + _sidata = __etext; .data : AT (__etext) { __data_start__ = .; + _sdata = __data_start__; + *(vtable) *(.data*) . = ALIGN (4); @@ -181,6 +155,7 @@ SECTIONS . = ALIGN(4); /* All data end */ __data_end__ = .; + _edata = __data_end__; } > RAM @@ -188,11 +163,13 @@ SECTIONS { . = ALIGN(4); __bss_start__ = .; + _sbss = __bss_start__; *(.bss) *(.bss.*) *(COMMON) . = ALIGN(4); __bss_end__ = .; + _ebss = __bss_end__; } > RAM .heap (COPY) : @@ -237,6 +214,6 @@ SECTIONS ASSERT( (linker_nvm_begin + SIZEOF(.nvm)) <= __main_flash_end__, "NVM3 is excessing the flash size !") /* Check if FLASH usage exceeds FLASH size */ - ASSERT( LENGTH(FLASH) >= (__etext), "FLASH memory overflowed !") +/* ASSERT( LENGTH(FLASH) >= (__etext), "FLASH memory overflowed !") */ /* Build error need to be checked for CCP */ ASSERT((__etext + SIZEOF(.data)) <= __nvm3Base, "FLASH memory overlapped with NVM section.") } diff --git a/examples/platform/silabs/SiWx917/ldscripts/efr32mg21.ld b/examples/platform/silabs/SiWx917/ldscripts/efr32mg21.ld deleted file mode 100644 index 2c9de0ddede7d7..00000000000000 --- a/examples/platform/silabs/SiWx917/ldscripts/efr32mg21.ld +++ /dev/null @@ -1,289 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/***************************************************************************//** - * Linker script for Silicon Labs EFR32MG21 devices - * @version 5.7.2 - ******************************************************************************* - * # License - * Copyright 2018 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************/ - -MEMORY -{ - FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 1048576 - 8192 /* 8K is reserved at top of flash on MG21 */ - RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 98304 -} - -/* Linker script to place sections and symbol values. Should be used together - * with other linker script that defines memory regions FLASH and RAM. - * It references following symbols, which must be defined in code: - * Reset_Handler : Entry of reset handler - * - * It defines following symbols, which code can use without definition: - * __exidx_start - * __exidx_end - * __copy_table_start__ - * __copy_table_end__ - * __zero_table_start__ - * __zero_table_end__ - * __etext - * __data_start__ - * __preinit_array_start - * __preinit_array_end - * __init_array_start - * __init_array_end - * __fini_array_start - * __fini_array_end - * __data_end__ - * __bss_start__ - * __bss_end__ - * __end__ - * end - * __HeapBase - * __HeapLimit - * __StackLimit - * __StackTop - * __stack - * __Vectors_End - * __Vectors_Size - */ -ENTRY(Reset_Handler) - -SECTIONS -{ - .text : - { - KEEP(*(.vectors)) - __Vectors_End = .; - __Vectors_Size = __Vectors_End - __Vectors; - __end__ = .; - - *(.text*) - - KEEP(*(.init)) - KEEP(*(.fini)) - - KEEP(*(.application_properties)) - KEEP(*(.gecko_configuration)) - KEEP(*(.xo_configuration)) - KEEP(*(.gatt_header)) - KEEP(*(.gatt_data)) - - /* .ctors */ - *crtbegin.o(.ctors) - *crtbegin?.o(.ctors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) - *(SORT(.ctors.*)) - *(.ctors) - - /* .dtors */ - *crtbegin.o(.dtors) - *crtbegin?.o(.dtors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) - *(SORT(.dtors.*)) - *(.dtors) - - *(.rodata*) - - - KEEP(*(.eh_frame*)) - } > FLASH - - - .ARM.extab : - { - *(.ARM.extab* .gnu.linkonce.armextab.*) - } > FLASH - - __exidx_start = .; - .ARM.exidx : - { - *(.ARM.exidx* .gnu.linkonce.armexidx.*) - } > FLASH - __exidx_end = .; - - - - /* To copy multiple ROM to RAM sections, - * uncomment .copy.table section and, - * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ - /* - .copy.table : - { - . = ALIGN(4); - __copy_table_start__ = .; - LONG (__etext) - LONG (__data_start__) - LONG (__data_end__ - __data_start__) - LONG (__etext2) - LONG (__data2_start__) - LONG (__data2_end__ - __data2_start__) - __copy_table_end__ = .; - } > FLASH - */ - - /* To clear multiple BSS sections, - * uncomment .zero.table section and, - * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ - /* - .zero.table : - { - . = ALIGN(4); - __zero_table_start__ = .; - LONG (__bss_start__) - LONG (__bss_end__ - __bss_start__) - LONG (__bss2_start__) - LONG (__bss2_end__ - __bss2_start__) - __zero_table_end__ = .; - } > FLASH - */ - - __etext = .; - - /*******************************************************************/ - /* Define flash block for BLE-simee & CHIP-nvm3 */ - /* simee: 9000H (36k) bytes for BLE nvm3 */ - /* chipNvm3_section: 4000H (16k) bytes for CHIP nvm3. */ - /* 8K is reserved for OpenThread's NVM which is mapped directly at */ - /* the top of flash */ - /*******************************************************************/ - - OPENTHREAD_NVM_SIZE = 8192; - - .nvm_dummy (DSECT): - { - __nvm3_dummy_begin = .; - . = ALIGN (8192); - __nvm3_dummy_simee = .; - KEEP(*(.simee)); - . = ALIGN (8192); - __nvm3_dummy_chip = .; - KEEP(*(chipNvm3_section)); - . = ALIGN (8192); - . += OPENTHREAD_NVM_SIZE; - . = ALIGN (8192); - } > FLASH - - /* Set NVM to end of FLASH */ - __nvm3Base = LENGTH(FLASH) - SIZEOF(.nvm_dummy) + (__nvm3_dummy_simee - __nvm3_dummy_begin); - __nvm3ChipBase = LENGTH(FLASH) - SIZEOF(.nvm_dummy) + (__nvm3_dummy_chip - __nvm3_dummy_begin); - - - /*******************************************************************/ - - .data : AT (__etext) - { - __data_start__ = .; - *(vtable) - *(.data*) - . = ALIGN (4); - PROVIDE (__ram_func_section_start = .); - *(.ram) - PROVIDE (__ram_func_section_end = .); - - . = ALIGN(4); - /* preinit data */ - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP(*(.preinit_array)) - PROVIDE_HIDDEN (__preinit_array_end = .); - - . = ALIGN(4); - /* init data */ - PROVIDE_HIDDEN (__init_array_start = .); - KEEP(*(SORT(.init_array.*))) - KEEP(*(.init_array)) - PROVIDE_HIDDEN (__init_array_end = .); - - . = ALIGN(4); - /* finit data */ - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP(*(SORT(.fini_array.*))) - KEEP(*(.fini_array)) - PROVIDE_HIDDEN (__fini_array_end = .); - - KEEP(*(.jcr*)) - . = ALIGN(4); - /* All data end */ - __data_end__ = .; - - } > RAM - - .bss : - { - . = ALIGN(4); - __bss_start__ = .; - *(.bss*) - *(COMMON) - . = ALIGN(4); - __bss_end__ = .; - } > RAM - - .heap (COPY): - { - __HeapBase = .; - __end__ = .; - end = __end__; - _end = __end__; - KEEP(*(.heap*)) - __HeapLimit = .; - } > RAM - - /* .stack_dummy section doesn't contains any symbols. It is only - * used for linker to calculate size of stack sections, and assign - * values to stack symbols later */ - .stack_dummy (COPY): - { - KEEP(*(.stack*)) - } > RAM - - /* Set stack top to end of RAM, and stack limit move down by - * size of stack_dummy section */ - __StackTop = ORIGIN(RAM) + LENGTH(RAM); - __StackLimit = __StackTop - SIZEOF(.stack_dummy); - PROVIDE(__stack = __StackTop); - - /* Check if data + heap + stack exceeds RAM limit */ - ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") - - - /* Check if FLASH usage exceeds FLASH size */ - ASSERT( LENGTH(FLASH) >= (__etext + SIZEOF(.data)), "FLASH memory overflowed !") - ASSERT((__etext + SIZEOF(.data)) <= __nvm3Base, "FLASH memory overlapped with NVM section.") -} \ No newline at end of file diff --git a/examples/platform/silabs/SiWx917/ldscripts/efr32mg24.ld b/examples/platform/silabs/SiWx917/ldscripts/efr32mg24.ld deleted file mode 100644 index b057a9af720a7a..00000000000000 --- a/examples/platform/silabs/SiWx917/ldscripts/efr32mg24.ld +++ /dev/null @@ -1,243 +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 gcc_EFR32MG24.ld - * @brief GNU Linker Script for Cortex-M based device - * @version V2.2.0 - * @date 16. December 2020 - * Linker script for Silicon Labs EFR32MG24 devices - ******************************************************************************* - * # License - * Copyright 2022 Silicon Laboratories, Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************/ - -MEMORY -{ - FLASH (rx) : ORIGIN = 0x08006000, LENGTH = 0x17A000 - RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x40000 -} - -/* Linker script to place sections and symbol values. Should be used together - * with other linker script that defines memory regions FLASH and RAM. - * It references following symbols, which must be defined in code: - * Reset_Handler : Entry of reset handler - * - * It defines following symbols, which code can use without definition: - * __exidx_start - * __exidx_end - * __copy_table_start__ - * __copy_table_end__ - * __zero_table_start__ - * __zero_table_end__ - * __etext - * __data_start__ - * __preinit_array_start - * __preinit_array_end - * __init_array_start - * __init_array_end - * __fini_array_start - * __fini_array_end - * __data_end__ - * __bss_start__ - * __bss_end__ - * __end__ - * end - * __HeapLimit - * __StackLimit - * __StackTop - * __stack - * __StackSeal (only if ARMv8-M stack sealing is used) - */ - -ENTRY(Reset_Handler) - -SECTIONS -{ - .text : - { - KEEP(*(.vectors)) - *(.text*) - - KEEP(*(.init)) - KEEP(*(.fini)) - - /* .ctors */ - *crtbegin.o(.ctors) - *crtbegin?.o(.ctors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) - *(SORT(.ctors.*)) - *(.ctors) - - /* .dtors */ - *crtbegin.o(.dtors) - *crtbegin?.o(.dtors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) - *(SORT(.dtors.*)) - *(.dtors) - - *(.rodata*) - - KEEP(*(.eh_frame*)) - } > FLASH - .ARM.extab : - { - *(.ARM.extab* .gnu.linkonce.armextab.*) - } > FLASH - - __exidx_start = .; - .ARM.exidx : - { - *(.ARM.exidx* .gnu.linkonce.armexidx.*) - } > FLASH - __exidx_end = .; - - .copy.table : - { - . = ALIGN(4); - __copy_table_start__ = .; - - LONG (__etext) - LONG (__data_start__) - LONG ((__data_end__ - __data_start__) / 4) - - __copy_table_end__ = .; - } > FLASH - - .zero.table : - { - . = ALIGN(4); - __zero_table_start__ = .; - __zero_table_end__ = .; - __etext = ALIGN(4); - } > FLASH - - .data : AT (__etext) - { - __data_start__ = .; - *(vtable) - *(.data*) - . = ALIGN (4); - PROVIDE (__ram_func_section_start = .); - *(.ram) - PROVIDE (__ram_func_section_end = .); - - . = ALIGN(4); - /* preinit data */ - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP(*(.preinit_array)) - PROVIDE_HIDDEN (__preinit_array_end = .); - - . = ALIGN(4); - /* init data */ - PROVIDE_HIDDEN (__init_array_start = .); - KEEP(*(SORT(.init_array.*))) - KEEP(*(.init_array)) - PROVIDE_HIDDEN (__init_array_end = .); - - . = ALIGN(4); - /* finit data */ - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP(*(SORT(.fini_array.*))) - KEEP(*(.fini_array)) - PROVIDE_HIDDEN (__fini_array_end = .); - - KEEP(*(.jcr*)) - . = ALIGN(4); - /* All data end */ - __data_end__ = .; - - } > RAM - - .bss : - { - . = ALIGN(4); - __bss_start__ = .; - *(.bss) - *(.bss.*) - *(COMMON) - . = ALIGN(4); - __bss_end__ = .; - } > RAM AT > RAM - - .heap (COPY): - { - __HeapBase = .; - __end__ = .; - end = __end__; - _end = __end__; - KEEP(*(.heap*)) - __HeapLimit = .; - } > RAM - - __main_flash_end__ = ORIGIN(FLASH) + LENGTH(FLASH); - - /* .stack_dummy section doesn't contains any symbols. It is only - * used for linker to calculate size of stack sections, and assign - * values to stack symbols later */ - .stack_dummy (COPY): - { - KEEP(*(.stack*)) - /* KEEP(*(.stackseal*))*/ - } > RAM - - /* Set stack top to end of RAM, and stack limit move down by - * size of stack_dummy section */ - __StackTop = ORIGIN(RAM) + LENGTH(RAM); - __StackLimit = __StackTop - SIZEOF(.stack_dummy); - PROVIDE(__stack = __StackTop); - - .nvm (DSECT) : { - KEEP(*(.simee*)) - } > FLASH - - /* Last page of flash is reserved for the manufacturing token space */ - linker_nvm_end = __main_flash_end__ - 8192; - linker_nvm_begin = linker_nvm_end - SIZEOF(.nvm); - linker_nvm_size = SIZEOF(.nvm); - __nvm3Base = linker_nvm_begin; - __attestation_credentials_base = linker_nvm_end; - - /* Check if data + heap + stack exceeds RAM limit */ - /*ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack")*/ - ASSERT( (linker_nvm_begin + SIZEOF(.nvm)) <= __main_flash_end__, "NVM3 is excessing the flash size !") - - /* Check if FLASH usage exceeds FLASH size */ - ASSERT( LENGTH(FLASH) >= (__etext + SIZEOF(.data)), "FLASH memory overflowed !") -} diff --git a/examples/platform/silabs/SiWx917/ldscripts/mgm24.ld b/examples/platform/silabs/SiWx917/ldscripts/mgm24.ld deleted file mode 100644 index b057a9af720a7a..00000000000000 --- a/examples/platform/silabs/SiWx917/ldscripts/mgm24.ld +++ /dev/null @@ -1,243 +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 gcc_EFR32MG24.ld - * @brief GNU Linker Script for Cortex-M based device - * @version V2.2.0 - * @date 16. December 2020 - * Linker script for Silicon Labs EFR32MG24 devices - ******************************************************************************* - * # License - * Copyright 2022 Silicon Laboratories, Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************/ - -MEMORY -{ - FLASH (rx) : ORIGIN = 0x08006000, LENGTH = 0x17A000 - RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x40000 -} - -/* Linker script to place sections and symbol values. Should be used together - * with other linker script that defines memory regions FLASH and RAM. - * It references following symbols, which must be defined in code: - * Reset_Handler : Entry of reset handler - * - * It defines following symbols, which code can use without definition: - * __exidx_start - * __exidx_end - * __copy_table_start__ - * __copy_table_end__ - * __zero_table_start__ - * __zero_table_end__ - * __etext - * __data_start__ - * __preinit_array_start - * __preinit_array_end - * __init_array_start - * __init_array_end - * __fini_array_start - * __fini_array_end - * __data_end__ - * __bss_start__ - * __bss_end__ - * __end__ - * end - * __HeapLimit - * __StackLimit - * __StackTop - * __stack - * __StackSeal (only if ARMv8-M stack sealing is used) - */ - -ENTRY(Reset_Handler) - -SECTIONS -{ - .text : - { - KEEP(*(.vectors)) - *(.text*) - - KEEP(*(.init)) - KEEP(*(.fini)) - - /* .ctors */ - *crtbegin.o(.ctors) - *crtbegin?.o(.ctors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) - *(SORT(.ctors.*)) - *(.ctors) - - /* .dtors */ - *crtbegin.o(.dtors) - *crtbegin?.o(.dtors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) - *(SORT(.dtors.*)) - *(.dtors) - - *(.rodata*) - - KEEP(*(.eh_frame*)) - } > FLASH - .ARM.extab : - { - *(.ARM.extab* .gnu.linkonce.armextab.*) - } > FLASH - - __exidx_start = .; - .ARM.exidx : - { - *(.ARM.exidx* .gnu.linkonce.armexidx.*) - } > FLASH - __exidx_end = .; - - .copy.table : - { - . = ALIGN(4); - __copy_table_start__ = .; - - LONG (__etext) - LONG (__data_start__) - LONG ((__data_end__ - __data_start__) / 4) - - __copy_table_end__ = .; - } > FLASH - - .zero.table : - { - . = ALIGN(4); - __zero_table_start__ = .; - __zero_table_end__ = .; - __etext = ALIGN(4); - } > FLASH - - .data : AT (__etext) - { - __data_start__ = .; - *(vtable) - *(.data*) - . = ALIGN (4); - PROVIDE (__ram_func_section_start = .); - *(.ram) - PROVIDE (__ram_func_section_end = .); - - . = ALIGN(4); - /* preinit data */ - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP(*(.preinit_array)) - PROVIDE_HIDDEN (__preinit_array_end = .); - - . = ALIGN(4); - /* init data */ - PROVIDE_HIDDEN (__init_array_start = .); - KEEP(*(SORT(.init_array.*))) - KEEP(*(.init_array)) - PROVIDE_HIDDEN (__init_array_end = .); - - . = ALIGN(4); - /* finit data */ - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP(*(SORT(.fini_array.*))) - KEEP(*(.fini_array)) - PROVIDE_HIDDEN (__fini_array_end = .); - - KEEP(*(.jcr*)) - . = ALIGN(4); - /* All data end */ - __data_end__ = .; - - } > RAM - - .bss : - { - . = ALIGN(4); - __bss_start__ = .; - *(.bss) - *(.bss.*) - *(COMMON) - . = ALIGN(4); - __bss_end__ = .; - } > RAM AT > RAM - - .heap (COPY): - { - __HeapBase = .; - __end__ = .; - end = __end__; - _end = __end__; - KEEP(*(.heap*)) - __HeapLimit = .; - } > RAM - - __main_flash_end__ = ORIGIN(FLASH) + LENGTH(FLASH); - - /* .stack_dummy section doesn't contains any symbols. It is only - * used for linker to calculate size of stack sections, and assign - * values to stack symbols later */ - .stack_dummy (COPY): - { - KEEP(*(.stack*)) - /* KEEP(*(.stackseal*))*/ - } > RAM - - /* Set stack top to end of RAM, and stack limit move down by - * size of stack_dummy section */ - __StackTop = ORIGIN(RAM) + LENGTH(RAM); - __StackLimit = __StackTop - SIZEOF(.stack_dummy); - PROVIDE(__stack = __StackTop); - - .nvm (DSECT) : { - KEEP(*(.simee*)) - } > FLASH - - /* Last page of flash is reserved for the manufacturing token space */ - linker_nvm_end = __main_flash_end__ - 8192; - linker_nvm_begin = linker_nvm_end - SIZEOF(.nvm); - linker_nvm_size = SIZEOF(.nvm); - __nvm3Base = linker_nvm_begin; - __attestation_credentials_base = linker_nvm_end; - - /* Check if data + heap + stack exceeds RAM limit */ - /*ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack")*/ - ASSERT( (linker_nvm_begin + SIZEOF(.nvm)) <= __main_flash_end__, "NVM3 is excessing the flash size !") - - /* Check if FLASH usage exceeds FLASH size */ - ASSERT( LENGTH(FLASH) >= (__etext + SIZEOF(.data)), "FLASH memory overflowed !") -} diff --git a/examples/platform/silabs/SiWx917/matter_config.cpp b/examples/platform/silabs/SiWx917/matter_config.cpp index 83e909588d9811..caa6a34b218482 100644 --- a/examples/platform/silabs/SiWx917/matter_config.cpp +++ b/examples/platform/silabs/SiWx917/matter_config.cpp @@ -25,9 +25,15 @@ #include +#ifdef __cplusplus +extern "C" { +#endif #ifdef SL_WIFI #include "wfx_host_events.h" #endif /* SL_WIFI */ +#ifdef __cplusplus +} +#endif #if PW_RPC_ENABLED #include "Rpc.h" @@ -46,89 +52,34 @@ using namespace ::chip::Inet; using namespace ::chip::DeviceLayer; #include -// If building with the EFR32-provided crypto backend, we can use the -// opaque keystore -#if CHIP_CRYPTO_PLATFORM -#include -static chip::DeviceLayer::Internal::Efr32PsaOperationalKeystore gOperationalKeystore; -#endif - -#include "EFR32DeviceDataProvider.h" - -#if CHIP_ENABLE_OPENTHREAD -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +// If building with the SiWx917-provided crypto backend, we can use the -// ================================================================================ -// Matter Networking Callbacks -// ================================================================================ -void LockOpenThreadTask(void) -{ - chip::DeviceLayer::ThreadStackMgr().LockThreadStack(); -} - -void UnlockOpenThreadTask(void) -{ - chip::DeviceLayer::ThreadStackMgr().UnlockThreadStack(); -} - -// ================================================================================ -// EFR32MatterConfig Methods -// ================================================================================ - -CHIP_ERROR EFR32MatterConfig::InitOpenThread(void) -{ - SILABS_LOG("Initializing OpenThread stack"); - ReturnErrorOnFailure(ThreadStackMgr().InitThreadStack()); - -#if CHIP_DEVICE_CONFIG_THREAD_FTD - ReturnErrorOnFailure(ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router)); -#else // CHIP_DEVICE_CONFIG_THREAD_FTD -#if CHIP_DEVICE_CONFIG_ENABLE_SED - ReturnErrorOnFailure(ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice)); -#else // CHIP_DEVICE_CONFIG_ENABLE_SED - ReturnErrorOnFailure(ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice)); -#endif // CHIP_DEVICE_CONFIG_ENABLE_SED -#endif // CHIP_DEVICE_CONFIG_THREAD_FTD - - SILABS_LOG("Starting OpenThread task"); - return ThreadStackMgrImpl().StartThreadTask(); -} -#endif // CHIP_ENABLE_OPENTHREAD +#include "SiWx917DeviceDataProvider.h" #if EFR32_OTA_ENABLED void EFR32MatterConfig::InitOTARequestorHandler(System::Layer * systemLayer, void * appState) { +#if 0 // TODO : OTA is not planned now for CCP OTAConfig::Init(); +#endif } #endif -void EFR32MatterConfig::ConnectivityEventCallback(const ChipDeviceEvent * event, intptr_t arg) -{ +void SI917MatterConfig::ConnectivityEventCallback(const ChipDeviceEvent * event, intptr_t arg){ // Initialize OTA only when Thread or WiFi connectivity is established - if (((event->Type == DeviceEventType::kThreadConnectivityChange) && + /*if (((event->Type == DeviceEventType::kThreadConnectivityChange) && (event->ThreadConnectivityChange.Result == kConnectivity_Established)) || ((event->Type == DeviceEventType::kInternetConnectivityChange) && (event->InternetConnectivityChange.IPv6 == kConnectivity_Established))) { -#if EFR32_OTA_ENABLED SILABS_LOG("Scheduling OTA Requestor initialization") chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(OTAConfig::kInitOTARequestorDelaySec), InitOTARequestorHandler, nullptr); -#endif - } + }*/ + SILABS_LOG("Scheduling OTA Requestor initialization") } -CHIP_ERROR EFR32MatterConfig::InitMatter(const char * appName) +CHIP_ERROR SI917MatterConfig::InitMatter(const char * appName) { CHIP_ERROR err; @@ -154,39 +105,27 @@ CHIP_ERROR EFR32MatterConfig::InitMatter(const char * appName) SILABS_LOG("Init CHIP Stack"); // Init Chip memory management before the stack ReturnErrorOnFailure(chip::Platform::MemoryInit()); + + SILABS_LOG("Init RSI 911x Platform"); + int32_t deviceInit = wfx_rsi_platform(); + if (deviceInit != SL_STATUS_OK) + { + SILABS_LOG("RSI init failed"); + return CHIP_ERROR_INTERNAL; + } ReturnErrorOnFailure(PlatformMgr().InitChipStack()); chip::DeviceLayer::ConnectivityMgr().SetBLEDeviceName(appName); -#if CHIP_ENABLE_OPENTHREAD - ReturnErrorOnFailure(InitOpenThread()); -#endif - // Stop Matter event handling while setting up resources chip::DeviceLayer::PlatformMgr().LockChipStack(); // Create initParams with SDK example defaults here static chip::CommonCaseDeviceServerInitParams initParams; -#if CHIP_CRYPTO_PLATFORM - // When building with EFR32 crypto, use the opaque key store - // instead of the default (insecure) one. - gOperationalKeystore.Init(); - initParams.operationalKeystore = &gOperationalKeystore; -#endif - // Initialize the remaining (not overridden) providers to the SDK example defaults (void) initParams.InitializeStaticResourcesBeforeServerInit(); -#if CHIP_ENABLE_OPENTHREAD - // Set up OpenThread configuration when OpenThread is included - chip::Inet::EndPointStateOpenThread::OpenThreadEndpointInitParam nativeParams; - nativeParams.lockCb = LockOpenThreadTask; - nativeParams.unlockCb = UnlockOpenThreadTask; - nativeParams.openThreadInstancePtr = chip::DeviceLayer::ThreadStackMgrImpl().OTInstance(); - initParams.endpointNativeParams = static_cast(&nativeParams); -#endif - // Init Matter Server and Start Event Loop err = chip::Server::GetInstance().Init(initParams); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); @@ -194,7 +133,8 @@ CHIP_ERROR EFR32MatterConfig::InitMatter(const char * appName) ReturnErrorOnFailure(err); // OTA Requestor initialization will be triggered by the connectivity events - PlatformMgr().AddEventHandler(ConnectivityEventCallback, reinterpret_cast(nullptr)); + // TODO + // PlatformMgr().AddEventHandler(ConnectivityEventCallback, reinterpret_cast(nullptr)); SILABS_LOG("Starting Platform Manager Event Loop"); ReturnErrorOnFailure(PlatformMgr().StartEventLoopTask()); @@ -211,16 +151,8 @@ CHIP_ERROR EFR32MatterConfig::InitMatter(const char * appName) } #ifdef SL_WIFI -void EFR32MatterConfig::InitWiFi(void) +void SI917MatterConfig::InitWiFi(void) { -#ifdef WF200_WIFI - // Start wfx bus communication task. - wfx_bus_start(); -#ifdef SL_WFX_USE_SECURE_LINK - wfx_securelink_task_start(); // start securelink key renegotiation task -#endif // SL_WFX_USE_SECURE_LINK -#endif /* WF200_WIFI */ - #ifdef RS911X_WIFI /* * Start up any RSI interface stuff diff --git a/examples/platform/silabs/SiWx917/matter_config.h b/examples/platform/silabs/SiWx917/matter_config.h index e0af60356becf9..6b3bb622a075a2 100644 --- a/examples/platform/silabs/SiWx917/matter_config.h +++ b/examples/platform/silabs/SiWx917/matter_config.h @@ -22,7 +22,7 @@ #include #include -class EFR32MatterConfig +class SI917MatterConfig { public: static CHIP_ERROR InitMatter(const char * appName); diff --git a/examples/platform/silabs/SiWx917/project_include/OpenThreadConfig.h b/examples/platform/silabs/SiWx917/project_include/OpenThreadConfig.h deleted file mode 100644 index dccf3c816b7b66..00000000000000 --- a/examples/platform/silabs/SiWx917/project_include/OpenThreadConfig.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2019 Google LLC. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Overrides to default OpenThread configuration. - * - */ - -#pragma once - -#include - -// Disable the SiLabs-supplied OpenThread logging facilities and use -// the facilities provided by the Device Layer (see -// src/platform/silabs/Logging.cpp). -#define OPENTHREAD_CONFIG_LOG_OUTPUT OPENTHREAD_CONFIG_LOG_OUTPUT_APP - -// Turn on a moderate level of logging in OpenThread -// Enable use of external heap allocator (calloc/free) for OpenThread. -#define OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE 1 - -// EFR32MG21A020F1024IM32 has 96k of RAM. Reduce the number of buffers to -// conserve RAM for this Series 2 part. -#if defined(EFR32MG21) -#define OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS 22 -#define OPENTHREAD_CONFIG_CLI_UART_TX_BUFFER_SIZE 512 -#define OPENTHREAD_CONFIG_CLI_UART_RX_BUFFER_SIZE 512 -#endif - -#define OPENTHREAD_CONFIG_NCP_HDLC_ENABLE 1 -#define OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE 1 - -#define OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE 1 -#define OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE 1 -#define OPENTHREAD_CONFIG_ECDSA_ENABLE 1 - -// disable unused features -#define OPENTHREAD_CONFIG_COAP_API_ENABLE 0 -#define OPENTHREAD_CONFIG_JOINER_ENABLE 0 -#define OPENTHREAD_CONFIG_COMMISSIONER_ENABLE 0 -#define OPENTHREAD_CONFIG_UDP_FORWARD_ENABLE 0 -#define OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE 0 -#define OPENTHREAD_CONFIG_DHCP6_CLIENT_ENABLE 0 -#define OPENTHREAD_CONFIG_DHCP6_SERVER_ENABLE 0 -#define OPENTHREAD_CONFIG_TCP_ENABLE 0 - -// Support udp multicast by enabling Multicast Listener Registration (MLR) -#define OPENTHREAD_CONFIG_MLR_ENABLE 1 - -// Define as 1 to stay awake between fragments while transmitting a large packet, -// and to stay awake after receiving a packet with frame pending set to true. -#define OPENTHREAD_CONFIG_MAC_STAY_AWAKE_BETWEEN_FRAGMENTS 1 - -// Use the SiLabs-supplied default platform configuration for remainder -// of OpenThread config options. -// -// NB: This file gets included during the build of OpenThread. Hence -// it cannot use "openthread" in the path to the included file. -// -#include "openthread-core-efr32-config.h" diff --git a/examples/platform/silabs/SiWx917/pw_sys_io/BUILD.gn b/examples/platform/silabs/SiWx917/pw_sys_io/BUILD.gn index 722d2a7cad24e6..20547c3b7beabc 100644 --- a/examples/platform/silabs/SiWx917/pw_sys_io/BUILD.gn +++ b/examples/platform/silabs/SiWx917/pw_sys_io/BUILD.gn @@ -17,7 +17,7 @@ import("//build_overrides/pigweed.gni") import("$dir_pw_build/target_types.gni") -examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" +examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" config("default_config") { include_dirs = [ "public" ] diff --git a/examples/platform/silabs/SiWx917/pw_sys_io/sys_io_efr32.cc b/examples/platform/silabs/SiWx917/pw_sys_io/sys_io_siwx917.cc similarity index 100% rename from examples/platform/silabs/SiWx917/pw_sys_io/sys_io_efr32.cc rename to examples/platform/silabs/SiWx917/pw_sys_io/sys_io_siwx917.cc diff --git a/examples/platform/silabs/SiWx917/rs911x/hal/efx_spi.c b/examples/platform/silabs/SiWx917/rs911x/hal/efx_spi.c deleted file mode 100644 index f01cac3b657c7c..00000000000000 --- a/examples/platform/silabs/SiWx917/rs911x/hal/efx_spi.c +++ /dev/null @@ -1,324 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Includes - */ -#include -#include -#include - -#include "dmadrv.h" -#include "em_chip.h" -#include "em_cmu.h" -#include "em_core.h" -#include "em_device.h" -#include "em_gpio.h" -#include "em_ldma.h" -#if defined(EFR32MG12) -#include "em_usart.h" -#elif defined(EFR32MG24) -#include "em_eusart.h" -#endif -#include "spidrv.h" - -#include "gpiointerrupt.h" -#include "sl_device_init_clocks.h" -#include "sl_status.h" - -#include "FreeRTOS.h" -#include "event_groups.h" -#include "task.h" - -#include "wfx_host_events.h" -#include "wfx_rsi.h" - -#include "rsi_board_configuration.h" -#include "rsi_driver.h" -#include "sl_device_init_dpll.h" -#include "sl_device_init_hfxo.h" - -StaticSemaphore_t xEfxSpiIntfSemaBuffer; -static SemaphoreHandle_t spi_sem; - -#if defined(EFR32MG12) -#include "sl_spidrv_exp_config.h" -extern SPIDRV_Handle_t sl_spidrv_exp_handle; -#endif - -#if defined(EFR32MG24) -#include "sl_spidrv_eusart_exp_config.h" -extern SPIDRV_Handle_t sl_spidrv_eusart_exp_handle; -#endif - -static unsigned int tx_dma_channel; -static unsigned int rx_dma_channel; - -static uint32_t dummy_data; /* Used for DMA - when results don't matter */ -extern void rsi_gpio_irq_cb(uint8_t irqnum); -//#define RS911X_USE_LDMA - -/******************************************************** - * @fn sl_wfx_host_gpio_init(void) - * @brief - * Deal with the PINS that are not associated with SPI - - * Ie. RESET, Wakeup - * @return - * None - **********************************************************/ -void sl_wfx_host_gpio_init(void) -{ - // Enable GPIO clock. - CMU_ClockEnable(cmuClock_GPIO, true); - - GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModePushPull, PINOUT_SET); - GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModePushPull, PINOUT_CLEAR); - - CMU_OscillatorEnable(cmuOsc_LFXO, true, true); - - // Set up interrupt based callback function - trigger on both edges. - GPIOINT_Init(); - GPIO_PinModeSet(WFX_INTERRUPT_PIN.port, WFX_INTERRUPT_PIN.pin, gpioModeInputPull, PINOUT_CLEAR); - GPIO_ExtIntConfig(WFX_INTERRUPT_PIN.port, WFX_INTERRUPT_PIN.pin, SL_WFX_HOST_PINOUT_SPI_IRQ, true, false, true); - GPIOINT_CallbackRegister(SL_WFX_HOST_PINOUT_SPI_IRQ, rsi_gpio_irq_cb); - GPIO_IntDisable(1 << SL_WFX_HOST_PINOUT_SPI_IRQ); /* Will be enabled by RSI */ - - // Change GPIO interrupt priority (FreeRTOS asserts unless this is done here!) - NVIC_SetPriority(GPIO_EVEN_IRQn, WFX_SPI_NVIC_PRIORITY); - NVIC_SetPriority(GPIO_ODD_IRQn, WFX_SPI_NVIC_PRIORITY); -} - -/***************************************************************** - * @fn void sl_wfx_host_reset_chip(void) - * @brief - * To reset the WiFi CHIP - * @return - * None - ****************************************************************/ -void sl_wfx_host_reset_chip(void) -{ - // Pull it low for at least 1 ms to issue a reset sequence - GPIO_PinOutClear(WFX_RESET_PIN.port, WFX_RESET_PIN.pin); - - // Delay for 10ms - vTaskDelay(pdMS_TO_TICKS(10)); - - // Hold pin high to get chip out of reset - GPIO_PinOutSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin); - - // Delay for 3ms - vTaskDelay(pdMS_TO_TICKS(3)); -} - -/***************************************************************** - * @fn void rsi_hal_board_init(void) - * @brief - * Initialize the board - * @return - * None - ****************************************************************/ -void rsi_hal_board_init(void) -{ - spi_sem = xSemaphoreCreateBinaryStatic(&xEfxSpiIntfSemaBuffer); - xSemaphoreGive(spi_sem); - - /* Assign DMA channel from Handle*/ -#if defined(EFR32MG12) - /* MG12 + rs9116 combination uses USART driver */ - tx_dma_channel = sl_spidrv_exp_handle->txDMACh; - rx_dma_channel = sl_spidrv_exp_handle->rxDMACh; - -#elif defined(EFR32MG24) - /* MG24 + rs9116 combination uses EUSART driver */ - tx_dma_channel = sl_spidrv_eusart_exp_handle->txDMACh; - rx_dma_channel = sl_spidrv_eusart_exp_handle->rxDMACh; -#endif - - /* GPIO INIT of MG12 & MG24 : Reset, Wakeup, Interrupt */ - WFX_RSI_LOG("RSI_HAL: init GPIO"); - sl_wfx_host_gpio_init(); - - /* Reset of Wifi chip */ - WFX_RSI_LOG("RSI_HAL: Reset Wifi"); - sl_wfx_host_reset_chip(); - WFX_RSI_LOG("RSI_HAL: Init done"); -} - -/***************************************************************************** - *@fn static bool rx_dma_complete(unsigned int channel, unsigned int sequenceNo, void *userParam) - * - *@brief - * complete dma - * - * @param[in] channel: - * @param[in] sequenceNO: sequence number - * @param[in] userParam :user parameter - * - * @return - * None - ******************************************************************************/ -static bool rx_dma_complete(unsigned int channel, unsigned int sequenceNo, void * userParam) -{ - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - // uint8_t *buf = (void *)userParam; - - (void) channel; - (void) sequenceNo; - (void) userParam; - - // WFX_RSI_LOG ("SPI: DMA done [%x,%x,%x,%x]", buf [0], buf [1], buf [2], buf [3]); - xSemaphoreGiveFromISR(spi_sem, &xHigherPriorityTaskWoken); - portYIELD_FROM_ISR(xHigherPriorityTaskWoken); - - return true; -} - -/************************************************************* - * @fn static void receiveDMA(uint8_t *rx_buf, uint16_t xlen) - * @brief - * RX buf was specified - * TX buf was not specified by caller - so we - * transmit dummy data (typically 0) - * @param[in] rx_buf: - * @param[in] xlen: - * @return - * None - *******************************************************************/ -static void receiveDMA(uint8_t * rx_buf, uint16_t xlen) -{ - /* - * The caller wants to receive data - - * The xmit can be dummy data (no src increment for tx) - */ - dummy_data = 0; - DMADRV_PeripheralMemory(rx_dma_channel, MY_USART_RX_SIGNAL, (void *) rx_buf, (void *) &(MY_USART->RXDATA), true, xlen, - dmadrvDataSize1, rx_dma_complete, NULL); - - // Start transmit DMA. - DMADRV_MemoryPeripheral(tx_dma_channel, MY_USART_TX_SIGNAL, (void *) &(MY_USART->TXDATA), (void *) &(dummy_data), false, xlen, - dmadrvDataSize1, NULL, NULL); -} - -/***************************************************************************** - *@fn static void transmitDMA(void *rx_buf, void *tx_buf, uint8_t xlen) - *@brief - * we have a tx_buf. There are some instances where - * a rx_buf is not specified. If one is specified then - * the caller wants results (auto increment src) - * @param[in] rx_buf: - * @param[in] tx_buf: - * @param[in] xlen: - * @return - * None - ******************************************************************************/ -static void transmitDMA(uint8_t * rx_buf, uint8_t * tx_buf, uint16_t xlen) -{ - void * buf; - bool srcinc; - /* - * we have a tx_buf. There are some instances where - * a rx_buf is not specified. If one is specified then - * the caller wants results (auto increment src) - * TODO - the caller specified 8/32 bit - we should use this - * instead of dmadrvDataSize1 always - */ - if (rx_buf == NULL) - { - buf = &dummy_data; - srcinc = false; - } - else - { - buf = rx_buf; - srcinc = true; - /* DEBUG */ rx_buf[0] = 0xAA; - rx_buf[1] = 0x55; - } - DMADRV_PeripheralMemory(rx_dma_channel, MY_USART_RX_SIGNAL, buf, (void *) &(MY_USART->RXDATA), srcinc, xlen, dmadrvDataSize1, - rx_dma_complete, buf); - // Start transmit DMA. - DMADRV_MemoryPeripheral(tx_dma_channel, MY_USART_TX_SIGNAL, (void *) &(MY_USART->TXDATA), (void *) tx_buf, true, xlen, - dmadrvDataSize1, NULL, NULL); -} - -/********************************************************************* - * @fn int16_t rsi_spi_transfer(uint8_t *tx_buf, uint8_t *rx_buf, uint16_t xlen, uint8_t mode) - * @brief - * Do a SPI transfer - Mode is 8/16 bit - But every 8 bit is aligned - * @param[in] tx_buf: - * @param[in] rx_buf: - * @param[in] xlen: - * @param[in] mode: - * @return - * None - **************************************************************************/ -int16_t rsi_spi_transfer(uint8_t * tx_buf, uint8_t * rx_buf, uint16_t xlen, uint8_t mode) -{ - // WFX_RSI_LOG ("SPI: Xfer: tx=%x,rx=%x,len=%d",(uint32_t)tx_buf, (uint32_t)rx_buf, xlen); - if (xlen > MIN_XLEN) - { - MY_USART->CMD = USART_CMD_CLEARRX | USART_CMD_CLEARTX; - if (xSemaphoreTake(spi_sem, portMAX_DELAY) != pdTRUE) - { - return RSI_FALSE; - } - if (tx_buf == NULL) - { - receiveDMA(rx_buf, xlen); - } - else - { - transmitDMA(rx_buf, tx_buf, xlen); - } - - /* - * receiveDMA() and transmitDMA() are asynchronous - * Our application design assumes that this function is synchronous - * To make it synchronous, we wait to re-acquire the semaphore before exiting this function - * rx_dma_complete() gives back the semaphore when the SPI transfer is done - */ - if (xSemaphoreTake(spi_sem, pdMS_TO_TICKS(RSI_SEM_BLOCK_MIN_TIMER_VALUE_MS)) == pdTRUE) - { - // Transfer complete - // Give back the semaphore before exiting, so that it may be re-acquired - // in this function, just before the next transfer - xSemaphoreGive(spi_sem); - } - // Temporary patch - // Sometimes the xSemaphoreTake() above is getting stuck indefinitely - // As a workaround, if the transfer is not done within RSI_SEM_BLOCK_MIN_TIMER_VALUE_MS - // stop and start it again - // No need to re-acquire the semaphore since this is the function that acquired it - // TODO: Remove this after a permanent solution is found to the problem of the transfer getting stuck - else - { - uint32_t ldma_flags = 0; - uint32_t rem_len = 0; - rem_len = LDMA_TransferRemainingCount(RSI_LDMA_TRANSFER_CHANNEL_NUM); - LDMA_StopTransfer(RSI_LDMA_TRANSFER_CHANNEL_NUM); - ldma_flags = LDMA_IntGet(); - LDMA_IntClear(ldma_flags); - receiveDMA(rx_buf, rem_len); - if (xSemaphoreTake(spi_sem, portMAX_DELAY) == pdTRUE) - { - xSemaphoreGive(spi_sem); - } - } - } - - return RSI_ERROR_NONE; -} diff --git a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_board_configuration.h b/examples/platform/silabs/SiWx917/rs911x/hal/rsi_board_configuration.h deleted file mode 100644 index 204e7519d29b5b..00000000000000 --- a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_board_configuration.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _RSI_BOARD_CONFIGURATION_H_ -#define _RSI_BOARD_CONFIGURATION_H_ - -typedef struct -{ - unsigned char port; - unsigned char pin; -} rsi_pin_t; - -#define PIN(port_id, pin_id) \ - (rsi_pin_t) { .port = gpioPort##port_id, .pin = pin_id } - -#if defined(EFR32MG12_BRD4161A) || defined(BRD4161A) || defined(EFR32MG12_BRD4162A) || defined(BRD4162A) || \ - defined(EFR32MG12_BRD4163A) || defined(BRD4163A) || defined(EFR32MG12_BRD4164A) || defined(BRD4164A) || \ - defined(EFR32MG12_BRD4170A) || defined(BRD4170A) -// BRD4161-63-64 are pin to pin compatible for SPI -#include "brd4161a.h" -#elif defined(EFR32MG24_BRD4186C) || defined(BRD4186C) -#include "brd4186c.h" -#elif defined(EFR32MG24_BRD4187C) || defined(BRD4187C) -#include "brd4187c.h" -#else -#error "Need SPI Pins" -#endif /* EFR32MG12_BRD4161A */ - -#endif /* _RSI_BOARD_CONFIGURATION_H_ */ diff --git a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_interrupt.c b/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_interrupt.c deleted file mode 100644 index 40e4189635d71c..00000000000000 --- a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_interrupt.c +++ /dev/null @@ -1,161 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "dmadrv.h" -#include "em_chip.h" -#include "em_cmu.h" -#include "em_core.h" -#include "em_device.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" -#include "gpiointerrupt.h" -#include "sl_device_init_clocks.h" -#include "sl_status.h" - -#include "FreeRTOS.h" -#include "event_groups.h" -#include "task.h" - -#include "wfx_host_events.h" -#include "wfx_rsi.h" - -#include "rsi_board_configuration.h" -#include "rsi_driver.h" - -typedef void (*UserIntCallBack_t)(void); -UserIntCallBack_t call_back, gpio_callback; -#ifdef LOGGING_STATS -uint8_t current_pin_set, prev_pin_set; -#endif /* LOGGING_STATS */ - -/* ARGSUSED */ -void rsi_gpio_irq_cb(uint8_t irqnum) -{ - - // WFX_RSI_LOG ("RSI: Got Int=%d", irqnum) - if (irqnum != SL_WFX_HOST_PINOUT_SPI_IRQ) - return; - GPIO_IntClear(1 << SL_WFX_HOST_PINOUT_SPI_IRQ); - - // WFX_RSI_LOG ("Got SPI intr, cb=%x", (uint32_t)call_back); - if (call_back != NULL) - (*call_back)(); -} - -/*===================================================*/ -/** - * @fn void rsi_hal_intr_config(void (* rsi_interrupt_handler)()) - * @brief Starts and enables the SPI interrupt - * @param[in] rsi_interrupt_handler() ,call back function to handle interrupt - * @param[out] none - * @return none - * @description This HAL API should contain the code to initialize the register/pins - * related to interrupts and enable the interrupts. - */ -void rsi_hal_intr_config(void (*rsi_interrupt_handler)(void)) -{ - call_back = rsi_interrupt_handler; - WFX_RSI_LOG("RSI:Set SPI intr CB to=%x", (uint32_t) call_back); -} - -/*===================================================*/ -/** - * @fn void rsi_hal_log_stats_intr_config(void (* rsi_give_wakeup_indication)()) - * @brief Checks the interrupt and map/set gpio callback function - * @param[in] rsi_give_wakeup_indication() ,gpio call back function to handle interrupt - * @param[out] none - * @return none - * @description This HAL API should contain the code - * related to mapping of gpio callback function. - */ -#ifdef LOGGING_STATS -void rsi_hal_log_stats_intr_config(void (*rsi_give_wakeup_indication)()) -{ - gpio_callback = rsi_give_wakeup_indication; -} -#endif - -/*===================================================*/ -/** - * @fn void rsi_hal_intr_mask(void) - * @brief Disables the SPI Interrupt - * @param[in] none - * @param[out] none - * @return none - * @description This HAL API should contain the code to mask/disable interrupts. - */ -void rsi_hal_intr_mask(void) -{ - // WFX_RSI_LOG ("RSI:Disable IRQ"); - // NVIC_DisableIRQ(GPIO_ODD_IRQn); - GPIO_IntDisable(1 << SL_WFX_HOST_PINOUT_SPI_IRQ); -} - -/*===================================================*/ -/** - * @fn void rsi_hal_intr_unmask(void) - * @brief Enables the SPI interrupt - * @param[in] none - * @param[out] none - * @return none - * @description This HAL API should contain the code to enable interrupts. - */ -void rsi_hal_intr_unmask(void) -{ - // Unmask/Enable the interrupt - NVIC_EnableIRQ(GPIO_ODD_IRQn); - NVIC_EnableIRQ(GPIO_EVEN_IRQn); - GPIO_IntEnable(1 << SL_WFX_HOST_PINOUT_SPI_IRQ); - // WFX_RSI_LOG ("RSI:Enable IRQ (mask=%x)", GPIO_IntGetEnabled ()); -} - -/*===================================================*/ -/** - * @fn void rsi_hal_intr_clear(void) - * @brief Clears the pending interrupt - * @param[in] none - * @param[out] none - * @return none - * @description This HAL API should contain the code to clear the handled interrupts. - */ -void rsi_hal_intr_clear(void) -{ - GPIO_IntClear(1 << SL_WFX_HOST_PINOUT_SPI_IRQ); -} - -/*===================================================*/ -/** - * @fn void rsi_hal_intr_pin_status(void) - * @brief Checks the SPI interrupt at pin level - * @param[in] none - * @param[out] uint8_t, interrupt status - * @return none - * @description This API is used to check interrupt pin status(pin level whether it is high/low). - */ -uint8_t rsi_hal_intr_pin_status(void) -{ - uint32_t mask; - // Return interrupt pin status(high(1) /low (0)) - mask = GPIO_PinInGet(WFX_INTERRUPT_PIN.port, WFX_INTERRUPT_PIN.pin); - - return !!mask; -} diff --git a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_ioports.c b/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_ioports.c deleted file mode 100644 index 1ff5bc5fedf4f2..00000000000000 --- a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_ioports.c +++ /dev/null @@ -1,141 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "dmadrv.h" -#include "em_chip.h" -#include "em_cmu.h" -#include "em_core.h" -#include "em_device.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" -#include "gpiointerrupt.h" -#include "sl_device_init_clocks.h" -#include "sl_status.h" - -#include "FreeRTOS.h" -#include "event_groups.h" -#include "task.h" - -#include "wfx_host_events.h" -#include "wfx_rsi.h" - -#include "rsi_board_configuration.h" -#include "rsi_driver.h" - -/*===========================================================*/ -/** - * @fn void rsi_hal_config_gpio(uint8_t gpio_number,uint8_t mode,uint8_t value) - * @brief Configures gpio pin in output mode,with a value - * @param[in] uint8_t gpio_number, gpio pin number to be configured - * @param[in] uint8_t mode , input/output mode of the gpio pin to configure - * 0 - input mode - * 1 - output mode - * @param[in] uint8_t value, default value to be driven if gpio is configured in output mode - * 0 - low - * 1 - high - * @param[out] none - * @return none - * @description This API is used to configure host gpio pin in output mode. - */ -void rsi_hal_config_gpio(uint8_t gpio_number, uint8_t mode, uint8_t value) -{ - - CMU_ClockEnable(cmuClock_GPIO, true); - - // WFX_RSI_LOG ("RSI: CFG GPIO: 0x%x", gpio_number); - switch (gpio_number) - { - case RSI_HAL_RESET_PIN: - GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModePushPull, PINOUT_SET); - break; - default: - break; - } -} - -/*===========================================================*/ -/** - * @fn void rsi_hal_set_gpio(uint8_t gpio_number) - * @brief Makes/drives the gpio value high - * @param[in] uint8_t gpio_number, gpio pin number - * @param[out] none - * @return none - * @description This API is used to drives or makes the host gpio value high. - */ -void rsi_hal_set_gpio(uint8_t gpio_number) -{ - // WFX_RSI_LOG ("RSI: SET GPIO: 0x%x", gpio_number); - switch (gpio_number) - { - case RSI_HAL_RESET_PIN: - GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModeWiredOrPullDown, PINOUT_SET); - break; - default: - break; - } -} - -/*===========================================================*/ -/** - * @fn uint8_t rsi_hal_get_gpio(void) - * @brief get the gpio pin value - * @param[in] uint8_t gpio_number, gpio pin number - * @param[out] none - * @return gpio pin value - * @description This API is used to configure get the gpio pin value. - */ -uint8_t rsi_hal_get_gpio(uint8_t gpio_number) -{ - // WFX_RSI_LOG ("RSI: GET GPIO: 0x%x", gpio_number); - switch (gpio_number) - { - case RSI_HAL_RESET_PIN: - return GPIO_PinInGet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin); - case RSI_HAL_MODULE_INTERRUPT_PIN: - return GPIO_PinInGet(WFX_INTERRUPT_PIN.port, WFX_INTERRUPT_PIN.pin); - default: - break; - } - - return 0; -} - -/*===========================================================*/ -/** - * @fn void rsi_hal_set_gpio(uint8_t gpio_number) - * @brief Makes/drives the gpio value to low - * @param[in] uint8_t gpio_number, gpio pin number - * @param[out] none - * @return none - * @description This API is used to drives or makes the host gpio value low. - */ -void rsi_hal_clear_gpio(uint8_t gpio_number) -{ - // WFX_RSI_LOG ("RSI: CLR GPIO: 0x%x", gpio_number); - switch (gpio_number) - { - case RSI_HAL_RESET_PIN: - return GPIO_PinOutClear(WFX_RESET_PIN.port, WFX_RESET_PIN.pin); - default: - break; - } -} diff --git a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_rtc.c b/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_rtc.c deleted file mode 100644 index f57d47a4439bc5..00000000000000 --- a/examples/platform/silabs/SiWx917/rs911x/hal/rsi_hal_mcu_rtc.c +++ /dev/null @@ -1,326 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Includes - */ -#include "em_cmu.h" -#include "em_core.h" -#include "em_rtcc.h" -#include "sl_sleeptimer_config.h" -#include "sl_status.h" -#include -#include - -#define ZONE0 0 -#define CH_SELECTOR 1u -#define RTC_DEFAULT_COUNTER_VALUE 0u -#define RSI_RTC_FREQ_VALUE 0 -#define TIME_ZONE_OFFSET 0u - -#define SLEEPTIMER_EVENT_OF (0x01) -#define SLEEPTIMER_EVENT_COMP (0x02) -#define SLEEPTIMER_ENUM(name) \ - typedef uint8_t name; \ - enum name##_enum -#define TIME_UNIX_EPOCH (1970u) -#define TIME_NTP_EPOCH (1900u) -#define TIME_ZIGBEE_EPOCH (2000u) -#define TIME_NTP_UNIX_EPOCH_DIFF (TIME_UNIX_EPOCH - TIME_NTP_EPOCH) -#define TIME_ZIGBEE_UNIX_EPOCH_DIFF (TIME_ZIGBEE_EPOCH - TIME_UNIX_EPOCH) -#define TIME_DAY_COUNT_NTP_TO_UNIX_EPOCH (TIME_NTP_UNIX_EPOCH_DIFF * 365u + 17u) ///< 70 years and 17 leap days -#define TIME_DAY_COUNT_ZIGBEE_TO_UNIX_EPOCH (TIME_ZIGBEE_UNIX_EPOCH_DIFF * 365u + 7u) ///< 30 years and 7 leap days -#define TIME_SEC_PER_DAY (60u * 60u * 24u) -#define TIME_NTP_EPOCH_OFFSET_SEC (TIME_DAY_COUNT_NTP_TO_UNIX_EPOCH * TIME_SEC_PER_DAY) -#define TIME_ZIGBEE_EPOCH_OFFSET_SEC (TIME_DAY_COUNT_ZIGBEE_TO_UNIX_EPOCH * TIME_SEC_PER_DAY) -#define TIME_DAY_PER_YEAR (365u) -#define TIME_SEC_PER_YEAR (TIME_SEC_PER_DAY * TIME_DAY_PER_YEAR) -#define TIME_UNIX_TIMESTAMP_MAX (0x7FFFFFFF) - -/// Time zone offset from UTC(second). -typedef int32_t sl_sleeptimer_time_zone_offset_t; -/// Timestamp, wall clock time in seconds. -typedef uint32_t sl_sleeptimer_timestamp_t; -/// @brief Time Format. -SLEEPTIMER_ENUM(sl_sleeptimer_time_format_t){ - TIME_FORMAT_UNIX = 0, ///< Number of seconds since January 1, 1970, 00:00. - ///< Type is signed, so represented on 31 bit. - TIME_FORMAT_NTP = 1, ///< Number of seconds since January 1, 1900, 00:00. - ///< Type is unsigned, so represented on 32 bit. - TIME_FORMAT_ZIGBEE_CLUSTER = 2, ///< Number of seconds since January 1, 2000, 00:00. Type is - ///< unsigned, so represented on 32 bit. -}; - -// Initialization flag. -static bool is_sleeptimer_initialized = false; -// Timer frequency in Hz. -static uint32_t timer_frequency; -#if SL_SLEEPTIMER_WALLCLOCK_CONFIG -// Current time count. -static sl_sleeptimer_timestamp_t second_count; -// Tick rest when the frequency is not a divider of the timer width. -static uint32_t overflow_tick_rest = 0; -#endif - -/******************************************************************************* - * Checks if the time stamp, format and time zone are - * within the supported range. - * - * @param time Time stamp to check. - * @param format Format of the time. - * @param time_zone Time zone offset in second. - * - * @return true if the time is valid. False otherwise. - ******************************************************************************/ -static bool is_valid_time(sl_sleeptimer_timestamp_t time, sl_sleeptimer_time_format_t format, - sl_sleeptimer_time_zone_offset_t time_zone) -{ - bool valid_time = false; - - // Check for overflow. - if ((time_zone < ZONE0 && time > (uint32_t) abs(time_zone)) || (time_zone >= ZONE0 && (time <= UINT32_MAX - time_zone))) - { - valid_time = true; - } - if (format == TIME_FORMAT_UNIX) - { - if (time > TIME_UNIX_TIMESTAMP_MAX) - { // Check if Unix time stamp is an - // unsigned 31 bits. - valid_time = false; - } - } - else - { - if ((format == TIME_FORMAT_NTP) && (time >= TIME_NTP_EPOCH_OFFSET_SEC)) - { - valid_time &= true; - } - else if ((format == TIME_FORMAT_ZIGBEE_CLUSTER) && (time <= TIME_UNIX_TIMESTAMP_MAX - TIME_ZIGBEE_EPOCH_OFFSET_SEC)) - { - valid_time &= true; - } - else - { - valid_time = false; - } - } - return valid_time; -} - -/******************************************************************************* - * Gets RTCC timer frequency. - ******************************************************************************/ -uint32_t rsi_rtc_get_hal_timer_frequency(void) -{ - /* CMU_PrescToLog2 converts prescaler dividend to a logarithmic value. It only works for even - * numbers equal to 2^n. - * An unscaled dividend (dividend = argument + 1). - * So we need to send argument subtracted by 1 - */ - return (CMU_ClockFreqGet(cmuClock_RTCC) >> (CMU_PrescToLog2(SL_SLEEPTIMER_FREQ_DIVIDER - 1))); -} - -/****************************************************************************** - * Initializes RTCC sleep timer. - *****************************************************************************/ -void rsi_rtc_init_timer(void) -{ - RTCC_Init_TypeDef rtcc_init = RTCC_INIT_DEFAULT; - RTCC_CCChConf_TypeDef channel = RTCC_CH_INIT_COMPARE_DEFAULT; - - CMU_ClockEnable(cmuClock_RTCC, true); - - rtcc_init.enable = false; - - /* CMU_PrescToLog2 converts prescaler dividend to a logarithmic value. It only works for even - * numbers equal to 2^n. - * An unscaled dividend (dividend = argument + 1). - * So we need to send argument subtracted by 1 - */ - rtcc_init.presc = (RTCC_CntPresc_TypeDef)(CMU_PrescToLog2(SL_SLEEPTIMER_FREQ_DIVIDER - 1)); - - RTCC_Init(&rtcc_init); - - // Compare channel starts disabled and is enabled only when compare match - // interrupt is enabled. - channel.chMode = rtccCapComChModeOff; - RTCC_ChannelInit(CH_SELECTOR, &channel); - - RTCC_IntDisable(_RTCC_IEN_MASK); - RTCC_IntClear(_RTCC_IF_MASK); - RTCC_CounterSet(RTC_DEFAULT_COUNTER_VALUE); - - RTCC_Enable(true); - - NVIC_ClearPendingIRQ(RTCC_IRQn); - NVIC_EnableIRQ(RTCC_IRQn); -} - -/****************************************************************************** - * Enables RTCC interrupts. - *****************************************************************************/ -void rsi_rtc_enable_int(uint8_t local_flag) -{ - uint32_t rtcc_ien = 0u; - - if (local_flag & SLEEPTIMER_EVENT_OF) - { - rtcc_ien |= RTCC_IEN_OF; - } - - if (local_flag & SLEEPTIMER_EVENT_COMP) - { - rtcc_ien |= RTCC_IEN_CC1; - } - - RTCC_IntEnable(rtcc_ien); -} - -/******************************************************************************* - * Get timer frequency. - ******************************************************************************/ -uint32_t rsi_rtc_get_timer_frequency(void) -{ - return timer_frequency; -} - -/****************************************************************************** - * Gets RTCC counter value. - *****************************************************************************/ -uint32_t rsi_rtc_get_counter(void) -{ - return RTCC_CounterGet(); -} - -sl_status_t rsi_rtc_init(void) -{ - CORE_DECLARE_IRQ_STATE; - CORE_ENTER_ATOMIC(); - - if (!is_sleeptimer_initialized) - { - rsi_rtc_init_timer(); - rsi_rtc_enable_int(SLEEPTIMER_EVENT_OF); - timer_frequency = rsi_rtc_get_hal_timer_frequency(); - if (timer_frequency == RSI_RTC_FREQ_VALUE) - { - CORE_EXIT_ATOMIC(); - return SL_STATUS_INVALID_PARAMETER; - } - -#if SL_SLEEPTIMER_WALLCLOCK_CONFIG - second_count = 0; -#endif - - is_sleeptimer_initialized = true; - } - CORE_EXIT_ATOMIC(); - - return SL_STATUS_OK; -} - -#if SL_SLEEPTIMER_WALLCLOCK_CONFIG -/******************************************************************************* - * Retrieves current time. - ******************************************************************************/ -uint32_t rsi_rtc_get_time(void) -{ - uint32_t cnt = 0u; - uint32_t freq = 0u; - sl_sleeptimer_timestamp_t time; - CORE_DECLARE_IRQ_STATE; - - cnt = rsi_rtc_get_counter(); - freq = rsi_rtc_get_timer_frequency(); - - CORE_ENTER_ATOMIC(); - time = second_count + cnt / freq; - if (cnt % freq + overflow_tick_rest >= freq) - { - time++; - } - CORE_EXIT_ATOMIC(); - - return time; -} - -/******************************************************************************* - * Sets current time. - ******************************************************************************/ -sl_status_t rsi_rtc_settime(sl_sleeptimer_timestamp_t time) -{ - uint32_t freq = 0u; - uint32_t counter_sec = 0u; - uint32_t cnt = 0; - CORE_DECLARE_IRQ_STATE; - - if (!is_valid_time(time, TIME_FORMAT_UNIX, TIME_ZONE_OFFSET)) - { - return SL_STATUS_INVALID_CONFIGURATION; - } - - freq = rsi_rtc_get_timer_frequency(); - cnt = rsi_rtc_get_counter(); - - CORE_ENTER_ATOMIC(); - second_count = time; - overflow_tick_rest = 0; - counter_sec = cnt / freq; - - if (second_count >= counter_sec) - { - second_count -= counter_sec; - } - else - { - CORE_EXIT_ATOMIC(); - return SL_STATUS_INVALID_CONFIGURATION; - } - - CORE_EXIT_ATOMIC(); - - return SL_STATUS_OK; -} - -/******************************************************************************* - * @fn int32_t rsi_rtc_set_time(uint32_t time) - * @brief - * Init Sleeptimer and Set current time. - * @param[in] time: - * @return - * None - ******************************************************************************/ -int32_t rsi_rtc_set_time(uint32_t time) -{ - sl_status_t ret_val = SL_STATUS_OK; - ret_val = rsi_rtc_init(); - if (ret_val != SL_STATUS_OK) - { - return -1; - } - else - { - ret_val = rsi_rtc_settime(time); - if (ret_val != SL_STATUS_OK) - { - return -1; - } - } - return 0; -} -#endif // SL_SLEEPTIMER_WALLCLOCK_CONFIG diff --git a/examples/platform/silabs/SiWx917/efr32_utils.cpp b/examples/platform/silabs/SiWx917/siwx917_utils.cpp similarity index 91% rename from examples/platform/silabs/SiWx917/efr32_utils.cpp rename to examples/platform/silabs/SiWx917/siwx917_utils.cpp index bd2bf771c60152..49a23255cd93c5 100644 --- a/examples/platform/silabs/SiWx917/efr32_utils.cpp +++ b/examples/platform/silabs/SiWx917/siwx917_utils.cpp @@ -17,9 +17,8 @@ * limitations under the License. */ -#include "efr32_utils.h" -#include "init_efrPlatform.h" -#include "sl_system_kernel.h" +#include "siwx917_utils.h" +#include "init_ccpPlatform.h" #include diff --git a/examples/platform/silabs/SiWx917/efr32_utils.h b/examples/platform/silabs/SiWx917/siwx917_utils.h similarity index 98% rename from examples/platform/silabs/SiWx917/efr32_utils.h rename to examples/platform/silabs/SiWx917/siwx917_utils.h index b0d508de5f8fe8..2223275d841733 100644 --- a/examples/platform/silabs/SiWx917/efr32_utils.h +++ b/examples/platform/silabs/SiWx917/siwx917_utils.h @@ -19,7 +19,7 @@ #pragma once -// EFR Logging +// SiWx917 Logging #ifdef __cplusplus extern "C" { #endif diff --git a/examples/platform/silabs/SiWx917/uart.cpp b/examples/platform/silabs/SiWx917/uart.cpp index 76dbca22ce52d5..d264e9644e9f08 100644 --- a/examples/platform/silabs/SiWx917/uart.cpp +++ b/examples/platform/silabs/SiWx917/uart.cpp @@ -22,217 +22,21 @@ extern "C" { #endif #include "assert.h" -#include "em_core.h" -#include "em_usart.h" -#include "sl_board_control.h" -#include "sl_uartdrv_instances.h" -#if (defined(EFR32MG24) || defined(MGM24)) -#include "sl_uartdrv_eusart_vcom_config.h" -#else -#include "sl_uartdrv_usart_vcom_config.h" -#endif // EFR32MG24 +#include "rsi_board.h" #include "uart.h" #include "uartdrv.h" #include #include -#if defined(SL_CATALOG_POWER_MANAGER_PRESENT) -#include "sl_power_manager.h" -#endif - #if !defined(MIN) #define MIN(A, B) ((A) < (B) ? (A) : (B)) #endif -#if (defined(EFR32MG24) || defined(MGM24)) -#define HELPER1(x) EUSART##x##_RX_IRQn -#else -#define HELPER1(x) USART##x##_RX_IRQn -#endif - -#define HELPER2(x) HELPER1(x) - -#if (defined(EFR32MG24) || defined(MGM24)) -#define HELPER3(x) EUSART##x##_RX_IRQHandler -#else -#define HELPER3(x) USART##x##_RX_IRQHandler -#endif - -#define HELPER4(x) HELPER3(x) - -// On MG24 boards VCOM runs on the EUSART device, MG12 uses the UART device -#if (defined(EFR32MG24) || defined(MGM24)) -#define USART_IRQ HELPER2(SL_UARTDRV_EUSART_VCOM_PERIPHERAL_NO) -#define USART_IRQHandler HELPER4(SL_UARTDRV_EUSART_VCOM_PERIPHERAL_NO) -#define vcom_handle sl_uartdrv_eusart_vcom_handle -#else -#define USART_IRQ HELPER2(SL_UARTDRV_USART_VCOM_PERIPHERAL_NO) -#define USART_IRQHandler HELPER4(SL_UARTDRV_USART_VCOM_PERIPHERAL_NO) -#define vcom_handle sl_uartdrv_usart_vcom_handle -#endif // EFR32MG24 - -typedef struct -{ - // The data buffer - uint8_t * pBuffer; - // The offset of the first item written to the list. - volatile uint16_t Head; - // The offset of the next item to be written to the list. - volatile uint16_t Tail; - // Maxium size of data that can be hold in buffer before overwriting - uint16_t MaxSize; -} Fifo_t; - #define UART_CONSOLE_ERR -1 // Negative value in case of UART Console action failed. Triggers a failure for PW_RPC -#define MAX_BUFFER_SIZE 256 -#define MAX_DMA_BUFFER_SIZE (MAX_BUFFER_SIZE / 2) -// In order to reduce the probability of data loss during the dmaFull callback handler we use -// two duplicate receive buffers so we can always have one "active" receive queue. -static uint8_t sRxDmaBuffer[MAX_DMA_BUFFER_SIZE]; -static uint8_t sRxDmaBuffer2[MAX_DMA_BUFFER_SIZE]; -static uint16_t lastCount; // Nb of bytes already processed from the active dmaBuffer -// Rx buffer for the receive Fifo -static uint8_t sRxFifoBuffer[MAX_BUFFER_SIZE]; -static Fifo_t sReceiveFifo; - -static void UART_rx_callback(UARTDRV_Handle_t handle, Ecode_t transferStatus, uint8_t * data, UARTDRV_Count_t transferCount); - -static bool InitFifo(Fifo_t * fifo, uint8_t * pDataBuffer, uint16_t bufferSize) -{ - if (fifo == NULL || pDataBuffer == NULL) - { - return false; - } - - fifo->pBuffer = pDataBuffer; - fifo->MaxSize = bufferSize; - fifo->Tail = fifo->Head = 0; - - return true; -} - -/* - * @brief Get the amount of unprocessed bytes in the fifo buffer - * @param Ptr to the fifo - * @return Nb of "unread" bytes available in the fifo - */ -static uint16_t AvailableDataCount(Fifo_t * fifo) -{ - uint16_t size = 0; - - // if equal there is no data return 0 directly - if (fifo->Tail != fifo->Head) - { - // determine if a wrap around occurred to get the right data size available. - size = (fifo->Tail < fifo->Head) ? (fifo->MaxSize - fifo->Head + fifo->Tail) : (fifo->Tail - fifo->Head); - } - - return size; -} - -/* - * @brief Get the available space in the fifo buffer to insert new data - * @param Ptr to the fifo - * @return Nb of free bytes left in te buffer - */ -static uint16_t RemainingSpace(Fifo_t * fifo) -{ - return fifo->MaxSize - AvailableDataCount(fifo); -} - -/* - * @brief Write data in the fifo as a circular buffer - * @param Ptr to the fifo, ptr of the data to write, nb of bytes to write - */ -static void WriteToFifo(Fifo_t * fifo, uint8_t * pDataToWrite, uint16_t SizeToWrite) -{ - assert(fifo); - assert(pDataToWrite); - assert(SizeToWrite <= fifo->MaxSize); - - // Overwrite is not allowed - if (RemainingSpace(fifo) >= SizeToWrite) - { - uint16_t nBytesBeforWrap = (fifo->MaxSize - fifo->Tail); - if (SizeToWrite > nBytesBeforWrap) - { - // The number of bytes to write is bigger than the remaining bytes - // in the buffer, we have to wrap around - memcpy(fifo->pBuffer + fifo->Tail, pDataToWrite, nBytesBeforWrap); - memcpy(fifo->pBuffer, pDataToWrite + nBytesBeforWrap, SizeToWrite - nBytesBeforWrap); - } - else - { - memcpy(fifo->pBuffer + fifo->Tail, pDataToWrite, SizeToWrite); - } - - fifo->Tail = (fifo->Tail + SizeToWrite) % fifo->MaxSize; // increment tail with wraparound - } -} - -/* - * @brief Write data in the fifo as a circular buffer - * @param Ptr to the fifo, ptr to contain the data to process, nb of bytes to pull from the fifo - * @return Nb of bytes that were retrieved. - */ -static uint8_t RetrieveFromFifo(Fifo_t * fifo, uint8_t * pData, uint16_t SizeToRead) -{ - assert(fifo); - assert(pData); - assert(SizeToRead <= fifo->MaxSize); - - uint16_t ReadSize = MIN(SizeToRead, AvailableDataCount(fifo)); - uint16_t nBytesBeforWrap = (fifo->MaxSize - fifo->Head); - - if (ReadSize > nBytesBeforWrap) - { - memcpy(pData, fifo->pBuffer + fifo->Head, nBytesBeforWrap); - memcpy(pData + nBytesBeforWrap, fifo->pBuffer, ReadSize - nBytesBeforWrap); - } - else - { - memcpy(pData, (fifo->pBuffer + fifo->Head), ReadSize); - } - - fifo->Head = (fifo->Head + ReadSize) % fifo->MaxSize; // increment tail with wraparound - - return ReadSize; -} - -/* - * @brief Init the the UART for serial communication, Start DMA reception - * and init Fifo to handle the received data from this uart - * - * @Note This UART is used for pigweed rpc - */ void uartConsoleInit(void) { - sl_board_enable_vcom(); - // Init a fifo for the data received on the uart - InitFifo(&sReceiveFifo, sRxFifoBuffer, MAX_BUFFER_SIZE); - - // Activate 2 dma queues to always have one active - - UARTDRV_Receive(vcom_handle, sRxDmaBuffer, MAX_DMA_BUFFER_SIZE, UART_rx_callback); - UARTDRV_Receive(vcom_handle, sRxDmaBuffer2, MAX_DMA_BUFFER_SIZE, UART_rx_callback); - - // Enable USART0/EUSART0 interrupt to wake OT task when data arrives - NVIC_ClearPendingIRQ(USART_IRQ); - NVIC_EnableIRQ(USART_IRQ); - -#if (defined(EFR32MG24) || defined(MGM24)) - // Clear previous RX interrupts - EUSART_IntClear(SL_UARTDRV_EUSART_VCOM_PERIPHERAL, EUSART_IF_RXFL); - - // Enable RX interrupts - EUSART_IntEnable(SL_UARTDRV_EUSART_VCOM_PERIPHERAL, EUSART_IF_RXFL); - - // Enable EUSART - EUSART_Enable(SL_UARTDRV_EUSART_VCOM_PERIPHERAL, eusartEnable); -#else - USART_IntEnable(SL_UARTDRV_USART_VCOM_PERIPHERAL, USART_IF_RXDATAV); -#endif // EFR32MG24 + // UART init is already done } void USART_IRQHandler(void) @@ -289,25 +93,12 @@ int16_t uartConsoleWrite(const char * Buf, uint16_t BufLength) return UART_CONSOLE_ERR; } -#if defined(SL_CATALOG_POWER_MANAGER_PRESENT) - sl_power_manager_add_em_requirement(SL_POWER_MANAGER_EM1); -#endif + // Add Terminating char at the end of buffer + Buf[BufLength] = '\0'; - // Use of ForceTransmit here. Transmit with DMA was causing errors with PW_RPC - // TODO Use DMA and find/fix what causes the issue with PW - if (UARTDRV_ForceTransmit(vcom_handle, (uint8_t *) Buf, BufLength) == ECODE_EMDRV_UARTDRV_OK) - { -#if defined(SL_CATALOG_POWER_MANAGER_PRESENT) - sl_power_manager_remove_em_requirement(SL_POWER_MANAGER_EM1); -#endif - return BufLength; - } - -#if defined(SL_CATALOG_POWER_MANAGER_PRESENT) - sl_power_manager_remove_em_requirement(SL_POWER_MANAGER_EM1); -#endif + Board_UARTPutSTR((uint8_t *) Buf); - return UART_CONSOLE_ERR; + return BufLength; } /* @@ -317,25 +108,20 @@ int16_t uartConsoleWrite(const char * Buf, uint16_t BufLength) */ int16_t uartConsoleRead(char * Buf, uint16_t NbBytesToRead) { - uint8_t * data; - UARTDRV_Count_t count, remaining; + uint32_t data; if (Buf == NULL || NbBytesToRead < 1) { return UART_CONSOLE_ERR; } - if (NbBytesToRead > AvailableDataCount(&sReceiveFifo)) + while (--NbBytesToRead >= 0) { - // Not enough data available in the fifo for the read size request - // If there is data available in dma buffer, get it now. - CORE_ATOMIC_SECTION(UARTDRV_GetReceiveStatus(vcom_handle, &data, &count, &remaining); if (count > lastCount) { - WriteToFifo(&sReceiveFifo, data + lastCount, count - lastCount); - lastCount = count; - }) + data = Board_UARTGetChar(); + *Buf++ = (char) data; } - return (int16_t) RetrieveFromFifo(&sReceiveFifo, (uint8_t *) Buf, NbBytesToRead); + return NbBytesToRead; } #ifdef __cplusplus diff --git a/examples/platform/silabs/SiWx917/uart.h b/examples/platform/silabs/SiWx917/uart.h index f708030223b2f7..035d5b3b0ede7d 100644 --- a/examples/platform/silabs/SiWx917/uart.h +++ b/examples/platform/silabs/SiWx917/uart.h @@ -28,13 +28,6 @@ void uartConsoleInit(void); int16_t uartConsoleWrite(const char * Buf, uint16_t BufLength); int16_t uartConsoleRead(char * Buf, uint16_t NbBytesToRead); -// Implemented by in openthread code -#ifndef PW_RPC_ENABLED -extern void otPlatUartReceived(const uint8_t * aBuf, uint16_t aBufLength); -extern void otPlatUartSendDone(void); -extern void otSysEventSignalPending(void); -#endif - #ifdef __cplusplus } // extern "C" #endif diff --git a/examples/platform/silabs/SiWx917/wf200/efr_spi.c b/examples/platform/silabs/SiWx917/wf200/efr_spi.c deleted file mode 100644 index fb35093797679d..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/efr_spi.c +++ /dev/null @@ -1,426 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "sl_wfx_configuration_defaults.h" - -#include "sl_wfx.h" -#include "sl_wfx_board.h" -#include "sl_wfx_host_api.h" - -#include "dmadrv.h" -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" -#include "spidrv.h" - -#include -#include -#include - -#include "FreeRTOS.h" -#include "semphr.h" -#ifdef SLEEP_ENABLED -#include "sl_power_manager.h" -#endif -#include "AppConfig.h" - -#include "gpiointerrupt.h" - -#include "sl_spidrv_exp_config.h" -#include "sl_wfx_board.h" -#include "sl_wfx_host.h" -#include "sl_wfx_task.h" -#include "wfx_host_events.h" - -extern SPIDRV_Handle_t sl_spidrv_exp_handle; - -#define USART SL_WFX_HOST_PINOUT_SPI_PERIPHERAL - -StaticSemaphore_t xEfrSpiSemaBuffer; -static SemaphoreHandle_t spi_sem; - -static unsigned int tx_dma_channel; -static unsigned int rx_dma_channel; - -static uint32_t dummy_rx_data; -static uint32_t dummy_tx_data; -static bool spi_enabled = false; - -#if defined(EFR32MG12) -uint8_t wirq_irq_nb = SL_WFX_HOST_PINOUT_SPI_IRQ; -#elif defined(EFR32MG24) -uint8_t wirq_irq_nb = SL_WFX_HOST_PINOUT_SPI_WIRQ_PIN; // SL_WFX_HOST_PINOUT_SPI_WIRQ_PIN; -#endif - -#define PIN_OUT_SET 1 -#define PIN_OUT_CLEAR 0 - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_init_bus(void) - * @brief - * Initialize SPI peripheral - * @param[in] None - * @return returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_init_bus(void) -{ - spi_enabled = true; - - /* Assign allocated DMA channel */ - tx_dma_channel = sl_spidrv_exp_handle->txDMACh; - rx_dma_channel = sl_spidrv_exp_handle->rxDMACh; - - /* - * Route EUSART1 MOSI, MISO, and SCLK to the specified pins. CS is - * not controlled by EUSART so there is no write to the corresponding - * EUSARTROUTE register to do this. - */ - MY_USART->CTRL |= (1u << _USART_CTRL_SMSDELAY_SHIFT); - -#if defined(EFR32MG12) - MY_USART->ROUTEPEN = USART_ROUTEPEN_TXPEN | USART_ROUTEPEN_RXPEN | USART_ROUTEPEN_CLKPEN; -#endif - -#if defined(EFR32MG24) - GPIO->USARTROUTE[0].ROUTEEN = GPIO_USART_ROUTEEN_RXPEN | // MISO - GPIO_USART_ROUTEEN_TXPEN | // MOSI - GPIO_USART_ROUTEEN_CLKPEN; -#endif - - spi_sem = xSemaphoreCreateBinaryStatic(&xEfrSpiSemaBuffer); - xSemaphoreGive(spi_sem); - - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_deinit_bus(void) - * @brief - * De-initialize SPI peripheral and DMAs - * @param[in] None - * @return returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_deinit_bus(void) -{ - vSemaphoreDelete(spi_sem); - // Stop DMAs. - DMADRV_StopTransfer(rx_dma_channel); - DMADRV_StopTransfer(tx_dma_channel); - DMADRV_FreeChannel(tx_dma_channel); - DMADRV_FreeChannel(rx_dma_channel); - DMADRV_DeInit(); - USART_Reset(MY_USART); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_spi_cs_assert() - * @brief - * Assert chip select. - * @param[in] None - * @return returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_spi_cs_assert() -{ - GPIO_PinOutClear(SL_SPIDRV_EXP_CS_PORT, SL_SPIDRV_EXP_CS_PIN); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_spi_cs_deassert() - * @brief - * De-Assert chip select. - * @param[in] None - * @return returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_spi_cs_deassert() -{ - GPIO_PinOutSet(SL_SPIDRV_EXP_CS_PORT, SL_SPIDRV_EXP_CS_PIN); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn static bool rx_dma_complete(unsigned int channel, unsigned int sequenceNo, void *userParam) - * @brief - * function called when the DMA complete - * @param[in] channel: - * @param[in] sequenceNo: sequence number - * @param[in] userParam: user parameter - * @return returns true if suucessful, - * false otherwise - *****************************************************************************/ -static bool rx_dma_complete(unsigned int channel, unsigned int sequenceNo, void * userParam) -{ - (void) channel; - (void) sequenceNo; - (void) userParam; - - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - xSemaphoreGiveFromISR(spi_sem, &xHigherPriorityTaskWoken); - portYIELD_FROM_ISR(xHigherPriorityTaskWoken); - - return true; -} - -/**************************************************************************** - * @fn void receiveDMA(uint8_t *buffer, uint16_t buffer_length) - * @brief - * start receive DMA - * @param[in] buffer: - * @param[in] buffer_length: - * @return None - *****************************************************************************/ -void receiveDMA(uint8_t * buffer, uint16_t buffer_length) -{ - // Start receive DMA. - DMADRV_PeripheralMemory(rx_dma_channel, MY_USART_RX_SIGNAL, (void *) buffer, (void *) &(MY_USART->RXDATA), true, buffer_length, - dmadrvDataSize1, rx_dma_complete, NULL); - - // Start transmit DMA. - DMADRV_MemoryPeripheral(tx_dma_channel, MY_USART_TX_SIGNAL, (void *) &(MY_USART->TXDATA), (void *) &(dummy_tx_data), false, - buffer_length, dmadrvDataSize1, NULL, NULL); -} - -/**************************************************************************** - * @fn void transmitDMA(uint8_t *buffer, uint16_t buffer_length) - * @brief - * start transmit DMA - * @param[in] buffer: - * @param[in] buffer_length: - * @return None - *****************************************************************************/ -void transmitDMA(uint8_t * buffer, uint16_t buffer_length) -{ - // Receive DMA runs only to initiate callback - // Start receive DMA. - DMADRV_PeripheralMemory(rx_dma_channel, MY_USART_RX_SIGNAL, &dummy_rx_data, (void *) &(MY_USART->RXDATA), false, buffer_length, - dmadrvDataSize1, rx_dma_complete, NULL); - // Start transmit DMA. - DMADRV_MemoryPeripheral(tx_dma_channel, MY_USART_TX_SIGNAL, (void *) &(MY_USART->TXDATA), (void *) buffer, true, buffer_length, - dmadrvDataSize1, NULL, NULL); -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_spi_transfer_no_cs_assert(sl_wfx_host_bus_transfer_type_t type, - uint8_t *header, - uint16_t header_length, - uint8_t *buffer, - uint16_t buffer_length) - * @brief - * WFX SPI transfer implementation - * @param[in] type: - * @param[in] header: - * @param[in] header_length: - * @param[in] buffer: - * @param[in] buffer_length: - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_spi_transfer_no_cs_assert(sl_wfx_host_bus_transfer_type_t type, uint8_t * header, uint16_t header_length, - uint8_t * buffer, uint16_t buffer_length) -{ - sl_status_t result = SL_STATUS_FAIL; - const bool is_read = (type == SL_WFX_BUS_READ); - - while (!(MY_USART->STATUS & USART_STATUS_TXBL)) - { - } - MY_USART->CMD = USART_CMD_CLEARRX | USART_CMD_CLEARTX; - - /* header length should be greater than 0 */ - if (header_length > 0) - { - for (uint8_t * buffer_ptr = header; header_length > 0; --header_length, ++buffer_ptr) - { - MY_USART->TXDATA = (uint32_t)(*buffer_ptr); - - while (!(MY_USART->STATUS & USART_STATUS_TXC)) - { - } - } - while (!(MY_USART->STATUS & USART_STATUS_TXBL)) - { - } - } - - /* buffer length should be greater than 0 */ - if (buffer_length > 0) - { - MY_USART->CMD = USART_CMD_CLEARRX | USART_CMD_CLEARTX; - if (xSemaphoreTake(spi_sem, portMAX_DELAY) == pdTRUE) - { - if (is_read) - { - receiveDMA(buffer, buffer_length); - result = SL_STATUS_OK; - } - else - { - transmitDMA(buffer, buffer_length); - result = SL_STATUS_OK; - } - - if (xSemaphoreTake(spi_sem, portMAX_DELAY) == pdTRUE) - { - xSemaphoreGive(spi_sem); - } - } - else - { - result = SL_STATUS_TIMEOUT; - } - } - - return result; -} - -/**************************************************************************** - * @fn void sl_wfx_host_start_platform_interrupt(void) - * @brief - * Enable WFX interrupt - * @param[in] none - * @return None - *****************************************************************************/ -void sl_wfx_host_start_platform_interrupt(void) -{ - // Enable (and clear) the bus interrupt - GPIO_ExtIntConfig(SL_WFX_HOST_PINOUT_SPI_WIRQ_PORT, SL_WFX_HOST_PINOUT_SPI_WIRQ_PIN, wirq_irq_nb, true, false, true); -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_disable_platform_interrupt(void) - * @brief - * Disable WFX interrupt - * @param[in] None - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_disable_platform_interrupt(void) -{ - GPIO_IntDisable(1 << wirq_irq_nb); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_enable_platform_interrupt(void) - * @brief - * enable the platform interrupt - * @param[in] None - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_enable_platform_interrupt(void) -{ - GPIO_IntEnable(1 << wirq_irq_nb); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_enable_spi(void) - * @brief - * enable spi - * @param[in] None - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_enable_spi(void) -{ - if (spi_enabled == false) - { -#ifdef SLEEP_ENABLED - // Prevent the host to use lower EM than EM1 - sl_power_manager_add_em_requirement(SL_POWER_MANAGER_EM1); -#endif - spi_enabled = true; - } - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_disable_spi(void) - * @brief - * disable spi - * @param[in] None - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_disable_spi(void) -{ - if (spi_enabled == true) - { - spi_enabled = false; -#ifdef SLEEP_ENABLED - // Allow the host to use the lowest allowed EM - sl_power_manager_remove_em_requirement(SL_POWER_MANAGER_EM1); -#endif - } - return SL_STATUS_OK; -} - -/* - * IRQ for SPI callback - * Clear the Interrupt and wake up the task that - * handles the actions of the interrupt (typically - wfx_bus_task ()) - */ -static void sl_wfx_spi_wakeup_irq_callback(uint8_t irqNumber) -{ - BaseType_t bus_task_woken; - uint32_t interrupt_mask; - - if (irqNumber != wirq_irq_nb) - return; - // Get and clear all pending GPIO interrupts - interrupt_mask = GPIO_IntGet(); - GPIO_IntClear(interrupt_mask); - bus_task_woken = pdFALSE; - xSemaphoreGiveFromISR(wfx_wakeup_sem, &bus_task_woken); - vTaskNotifyGiveFromISR(wfx_bus_task_handle, &bus_task_woken); - portYIELD_FROM_ISR(bus_task_woken); -} - -/**************************************************************************** - * Init some actions pins to the WF-200 expansion board - *****************************************************************************/ -void sl_wfx_host_gpio_init(void) -{ - SILABS_LOG("WIFI: GPIO Init:IRQ=%d", wirq_irq_nb); - // Enable GPIO clock. - CMU_ClockEnable(cmuClock_GPIO, true); - - // Configure WF200 reset pin. - GPIO_PinModeSet(SL_WFX_HOST_PINOUT_RESET_PORT, SL_WFX_HOST_PINOUT_RESET_PIN, gpioModePushPull, 0); - // Configure WF200 WUP pin. - GPIO_PinModeSet(SL_WFX_HOST_PINOUT_WUP_PORT, SL_WFX_HOST_PINOUT_WUP_PIN, gpioModePushPull, 0); - - // GPIO used as IRQ. - GPIO_PinModeSet(SL_WFX_HOST_PINOUT_SPI_WIRQ_PORT, SL_WFX_HOST_PINOUT_SPI_WIRQ_PIN, gpioModeInputPull, 0); - CMU_OscillatorEnable(cmuOsc_LFXO, true, true); - - // Set up interrupt based callback function - trigger on both edges. - GPIOINT_Init(); - GPIO_ExtIntConfig(SL_WFX_HOST_PINOUT_SPI_WIRQ_PORT, SL_WFX_HOST_PINOUT_SPI_WIRQ_PIN, wirq_irq_nb, true, false, - false); /* Don't enable it */ - - GPIOINT_CallbackRegister(wirq_irq_nb, sl_wfx_spi_wakeup_irq_callback); - - // Change GPIO interrupt priority (FreeRTOS asserts unless this is done here!) - NVIC_ClearPendingIRQ(1 << wirq_irq_nb); - NVIC_SetPriority(GPIO_EVEN_IRQn, 5); - NVIC_SetPriority(GPIO_ODD_IRQn, 5); -} diff --git a/examples/platform/silabs/SiWx917/wf200/host_if.cpp b/examples/platform/silabs/SiWx917/wf200/host_if.cpp deleted file mode 100644 index 26bd7886654700..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/host_if.cpp +++ /dev/null @@ -1,1270 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* Includes */ - -#include -#include -#include - -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" -#include "gpiointerrupt.h" - -#include "wifi_config.h" - -#include "AppConfig.h" -#include "sl_wfx_board.h" -#include "sl_wfx_host.h" -#include "sl_wfx_task.h" -#include "wfx_host_events.h" - -#include "FreeRTOS.h" -#include "event_groups.h" -#include "task.h" - -#include "dhcp_client.h" -#include "ethernetif.h" -#include - -using namespace ::chip; -using namespace ::chip::DeviceLayer; - -/* wfxRsi Task will use as its stack */ -StackType_t wfxEventTaskStack[1024] = { 0 }; - -/* Structure that will hold the TCB of the wfxRsi Task being created. */ -StaticTask_t wfxEventTaskBuffer; - -/* Declare a variable to hold the data associated with the created event group. */ -StaticEventGroup_t wfxEventGroup; - -EventGroupHandle_t sl_wfx_event_group; -TaskHandle_t wfx_events_task_handle; -static sl_wfx_mac_address_t ap_mac; -static uint32_t sta_ip; -static wfx_wifi_scan_result_t ap_info; - -// Set Scan Parameters -#define ACTIVE_CHANNEL_TIME 110 -#define PASSIVE_CHANNEL_TIME 0 -#define NUM_PROBE_REQUEST 2 - -// wfx_fmac_driver context -sl_wfx_context_t wifiContext; -static uint8_t wifi_extra; - -/***************************************************************************** - * macros - ******************************************************************************/ -#define WE_ST_STARTED 1 -#define WE_ST_STA_CONN 2 -#define WE_ST_HW_STARTED 4 - -#ifdef SL_WFX_CONFIG_SOFTAP -// Connection parameters -char softap_ssid[32] = SOFTAP_SSID_DEFAULT; -char softap_passkey[64] = SOFTAP_PASSKEY_DEFAULT; -sl_wfx_security_mode_t softap_security = SOFTAP_SECURITY_DEFAULT; -uint8_t softap_channel = SOFTAP_CHANNEL_DEFAULT; -#endif - -/* station network interface structures */ -struct netif * sta_netif; -wfx_wifi_provision_t wifi_provision; -sl_wfx_get_counters_cnf_t * counters; -sl_wfx_get_counters_cnf_t * Tempcounters; -#define PUT_COUNTER(name) SILABS_LOG("%-24s %lu\r\n", #name, (unsigned long) counters->body.count_##name); - -bool hasNotifiedIPV6 = false; -bool hasNotifiedIPV4 = false; -bool hasNotifiedWifiConnectivity = false; -static uint8_t retryJoin = 0; -bool retryInProgress = false; - -#ifdef SL_WFX_CONFIG_SCAN -static struct scan_result_holder -{ - struct scan_result_holder * next; - wfx_wifi_scan_result scan; -} * scan_save; -static uint8_t scan_count = 0; -static void (*scan_cb)(wfx_wifi_scan_result_t *); /* user-callback - when scan is done */ -static char * scan_ssid; /* Which one are we scanning for */ -static void sl_wfx_scan_result_callback(sl_wfx_scan_result_ind_body_t * scan_result); -static void sl_wfx_scan_complete_callback(uint32_t status); -#endif /* SL_WFX_CONFIG_SCAN */ - -static void wfx_events_task(void * p_arg); - -/* WF200 host callbacks */ -static void sl_wfx_connect_callback(sl_wfx_connect_ind_body_t connect_indication_body); -static void sl_wfx_disconnect_callback(uint8_t * mac, uint16_t reason); -static void sl_wfx_generic_status_callback(sl_wfx_generic_ind_t * frame); - -#ifdef SL_WFX_CONFIG_SOFTAP -static void sl_wfx_start_ap_callback(uint32_t status); -static void sl_wfx_stop_ap_callback(void); -static void sl_wfx_client_connected_callback(uint8_t * mac); -static void sl_wfx_ap_client_disconnected_callback(uint32_t status, uint8_t * mac); -static void sl_wfx_ap_client_rejected_callback(uint32_t status, uint8_t * mac); -#endif - -extern uint32_t gOverrunCount; - -/*************************************************************************** - * @brief - * Creates WFX events processing task. - ******************************************************************************/ -static void wfx_events_task_start() -{ - /* create an event group to track Wi-Fi events */ - sl_wfx_event_group = xEventGroupCreateStatic(&wfxEventGroup); - - wfx_events_task_handle = xTaskCreateStatic(wfx_events_task, "wfx_events", WLAN_TASK_STACK_SIZE, NULL, WLAN_TASK_PRIORITY, - wfxEventTaskStack, &wfxEventTaskBuffer); - if (NULL == wfx_events_task_handle) - { - SILABS_LOG("Failed to create WFX wfx_events"); - } -} - -/**************************************************************************** - * @brief - * Called when the driver needs to post an event - * @param[in] event_payload: - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_process_event(sl_wfx_generic_message_t * event_payload) -{ - switch (event_payload->header.id) - { - /******** INDICATION ********/ - case SL_WFX_STARTUP_IND_ID: { - SILABS_LOG("WFX Startup Completed\r\n"); - PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, event_payload); - break; - } - case SL_WFX_CONNECT_IND_ID: { - sl_wfx_connect_ind_t * connect_indication = (sl_wfx_connect_ind_t *) event_payload; - sl_wfx_connect_callback(connect_indication->body); - break; - } - case SL_WFX_DISCONNECT_IND_ID: { - sl_wfx_disconnect_ind_t * disconnect_indication = (sl_wfx_disconnect_ind_t *) event_payload; - sl_wfx_disconnect_callback(disconnect_indication->body.mac, disconnect_indication->body.reason); - break; - } - case SL_WFX_RECEIVED_IND_ID: { - sl_wfx_received_ind_t * ethernet_frame = (sl_wfx_received_ind_t *) event_payload; - if (ethernet_frame->body.frame_type == ETH_FRAME) - { - sl_wfx_host_received_frame_callback(ethernet_frame); - } - break; - } -#ifdef SL_WFX_CONFIG_SCAN - case SL_WFX_SCAN_RESULT_IND_ID: { - sl_wfx_scan_result_ind_t * scan_result = (sl_wfx_scan_result_ind_t *) event_payload; - sl_wfx_scan_result_callback(&scan_result->body); - break; - } - case SL_WFX_SCAN_COMPLETE_IND_ID: { - sl_wfx_scan_complete_ind_t * scan_complete = (sl_wfx_scan_complete_ind_t *) event_payload; - sl_wfx_scan_complete_callback(scan_complete->body.status); - break; - } -#endif /* SL_WFX_CONFIG_SCAN */ -#ifdef SL_WFX_CONFIG_SOFTAP - case SL_WFX_START_AP_IND_ID: { - sl_wfx_start_ap_ind_t * start_ap_indication = (sl_wfx_start_ap_ind_t *) event_payload; - sl_wfx_start_ap_callback(start_ap_indication->body.status); - break; - } - case SL_WFX_STOP_AP_IND_ID: { - sl_wfx_stop_ap_callback(); - break; - } - case SL_WFX_AP_CLIENT_CONNECTED_IND_ID: { - sl_wfx_ap_client_connected_ind_t * client_connected_indication = (sl_wfx_ap_client_connected_ind_t *) event_payload; - sl_wfx_client_connected_callback(client_connected_indication->body.mac); - break; - } - case SL_WFX_AP_CLIENT_REJECTED_IND_ID: { - sl_wfx_ap_client_rejected_ind_t * ap_client_rejected_indication = (sl_wfx_ap_client_rejected_ind_t *) event_payload; - sl_wfx_ap_client_rejected_callback(ap_client_rejected_indication->body.reason, ap_client_rejected_indication->body.mac); - break; - } - case SL_WFX_AP_CLIENT_DISCONNECTED_IND_ID: { - sl_wfx_ap_client_disconnected_ind_t * ap_client_disconnected_indication = - (sl_wfx_ap_client_disconnected_ind_t *) event_payload; - sl_wfx_ap_client_disconnected_callback(ap_client_disconnected_indication->body.reason, - ap_client_disconnected_indication->body.mac); - break; - } -#endif /* SL_WFX_CONFIG_SOFTAP */ -#ifdef SL_WFX_USE_SECURE_LINK - case SL_WFX_SECURELINK_EXCHANGE_PUB_KEYS_IND_ID: { - if (host_context.waited_event_id != SL_WFX_SECURELINK_EXCHANGE_PUB_KEYS_IND_ID) - { - memcpy((void *) &sl_wfx_context->secure_link_exchange_ind, (void *) event_payload, event_payload->header.length); - } - break; - } -#endif - case SL_WFX_GENERIC_IND_ID: { - sl_wfx_generic_ind_t * generic_status = (sl_wfx_generic_ind_t *) event_payload; - sl_wfx_generic_status_callback(generic_status); - break; - } - case SL_WFX_EXCEPTION_IND_ID: { - sl_wfx_exception_ind_t * firmware_exception = (sl_wfx_exception_ind_t *) event_payload; - uint8_t * exception_tmp = (uint8_t *) firmware_exception; - SILABS_LOG("firmware exception\r\n"); - for (uint16_t i = 0; i < firmware_exception->header.length; i += 16) - { - SILABS_LOG("hif: %.8x:", i); - for (uint8_t j = 0; (j < 16) && ((i + j) < firmware_exception->header.length); j++) - { - SILABS_LOG(" %.2x", *exception_tmp); - exception_tmp++; - } - SILABS_LOG("\r\n"); - } - break; - } - case SL_WFX_ERROR_IND_ID: { - sl_wfx_error_ind_t * firmware_error = (sl_wfx_error_ind_t *) event_payload; - uint8_t * error_tmp = (uint8_t *) firmware_error; - SILABS_LOG("firmware error %lu\r\n", firmware_error->body.type); - for (uint16_t i = 0; i < firmware_error->header.length; i += 16) - { - SILABS_LOG("hif: %.8x:", i); - for (uint8_t j = 0; (j < 16) && ((i + j) < firmware_error->header.length); j++) - { - SILABS_LOG(" %.2x", *error_tmp); - error_tmp++; - } - SILABS_LOG("\r\n"); - } - break; - } - } - - return SL_STATUS_OK; -} - -#ifdef SL_WFX_CONFIG_SCAN -/**************************************************************************** - * @brief - * Callback for individual scan result - * @param[in] scan_result: Scan result of all SSID's - *****************************************************************************/ -static void sl_wfx_scan_result_callback(sl_wfx_scan_result_ind_body_t * scan_result) -{ - struct scan_result_holder * ap; - - SILABS_LOG("# %2d %2d %03d %02X:%02X:%02X:%02X:%02X:%02X %s", scan_count, scan_result->channel, - ((int16_t)(scan_result->rcpi - 220) / 2), scan_result->mac[0], scan_result->mac[1], scan_result->mac[2], - scan_result->mac[3], scan_result->mac[4], scan_result->mac[5], scan_result->ssid_def.ssid); - /*Report one AP information*/ - SILABS_LOG("\r\n"); - /* don't save if filter only wants specific ssid */ - if (scan_ssid != (char *) 0) - { - if (strcmp(scan_ssid, (char *) &scan_result->ssid_def.ssid[0]) != CMP_SUCCESS) - return; - } - if ((ap = (struct scan_result_holder *) pvPortMalloc(sizeof(*ap))) == (struct scan_result_holder *) 0) - { - SILABS_LOG("*ERR*Scan: No Mem"); - } - else - { - ap->next = scan_save; - scan_save = ap; - /* Not checking if scan_result->ssid_length is < 33 */ - memcpy(ap->scan.ssid, scan_result->ssid_def.ssid, scan_result->ssid_def.ssid_length); - ap->scan.ssid[scan_result->ssid_def.ssid_length] = 0; /* make sure about null terminate */ - /* We do it in this order WPA3 first */ - /* No EAP supported - Is this required */ - if (scan_result->security_mode.wpa3) - { - ap->scan.security = WFX_SEC_WPA3; - } - else if (scan_result->security_mode.wpa2) - { - ap->scan.security = WFX_SEC_WPA2; - } - else if (scan_result->security_mode.wpa) - { - ap->scan.security = WFX_SEC_WPA; - } - else if (scan_result->security_mode.wep) - { - ap->scan.security = WFX_SEC_WEP; - } - else - { - ap->scan.security = WFX_SEC_NONE; - } - ap->scan.chan = scan_result->channel; - ap->scan.rssi = scan_result->rcpi; - memcpy(&ap->scan.bssid[0], &scan_result->mac[0], BSSID_MAX_STR_LEN); - scan_count++; - } -} - -/**************************************************************************** - * @brief - * Callback for scan complete - * @param[in] status:Status of WLAN scan api - *****************************************************************************/ -/* ARGSUSED */ -static void sl_wfx_scan_complete_callback(uint32_t status) -{ - (void) (status); - /* Use scan_count value and reset it */ - xEventGroupSetBits(sl_wfx_event_group, SL_WFX_SCAN_COMPLETE); -} -#endif /* SL_WFX_CONFIG_SCAN */ - -/**************************************************************************** - * @brief - * Callback when station connects - * @param[in] mac: MAC address of device - * @param[in] status: Status of connect call - *****************************************************************************/ -static void sl_wfx_connect_callback(sl_wfx_connect_ind_body_t connect_indication_body) -{ - uint8_t * mac = connect_indication_body.mac; - uint32_t status = connect_indication_body.status; - switch (status) - { - case WFM_STATUS_SUCCESS: { - SILABS_LOG("STA-Connected\r\n"); - memcpy(&ap_mac.octet[0], mac, MAC_ADDRESS_FIRST_OCTET); - sl_wfx_context->state = - static_cast(static_cast(sl_wfx_context->state) | static_cast(SL_WFX_STA_INTERFACE_CONNECTED)); - xEventGroupSetBits(sl_wfx_event_group, SL_WFX_CONNECT); - break; - } - case WFM_STATUS_NO_MATCHING_AP: { - SILABS_LOG("WFX Connection failed, access point not found\r\n"); - break; - } - case WFM_STATUS_CONNECTION_ABORTED: { - SILABS_LOG("WFX Connection aborted\r\n"); - break; - } - case WFM_STATUS_CONNECTION_TIMEOUT: { - SILABS_LOG("WFX Connection timeout\r\n"); - break; - } - case WFM_STATUS_CONNECTION_REJECTED_BY_AP: { - SILABS_LOG("WFX Connection rejected by the access point\r\n"); - break; - } - case WFM_STATUS_CONNECTION_AUTH_FAILURE: { - SILABS_LOG("WFX Connection authentication failure\r\n"); - break; - } - default: { - SILABS_LOG("WF Connection attempt error\r\n"); - } - } - - if ((status != WFM_STATUS_SUCCESS) && retryJoin < MAX_JOIN_RETRIES_COUNT) - { - retryJoin += 1; - retryInProgress = false; - SILABS_LOG("WFX Retry to connect to network count: %d", retryJoin); - sl_wfx_context->state = - static_cast(static_cast(sl_wfx_context->state) & ~static_cast(SL_WFX_STARTED)); - xEventGroupSetBits(sl_wfx_event_group, SL_WFX_RETRY_CONNECT); - } -} - -/**************************************************************************** - * @brief - * Callback for station disconnect - * @param[in] mac: MAC address of device - * @param[in] reason: Reason code of disconnection - *****************************************************************************/ -static void sl_wfx_disconnect_callback(uint8_t * mac, uint16_t reason) -{ - (void) (mac); - SILABS_LOG("WFX Disconnected %d\r\n", reason); - sl_wfx_context->state = - static_cast(static_cast(sl_wfx_context->state) & ~static_cast(SL_WFX_STA_INTERFACE_CONNECTED)); - xEventGroupSetBits(sl_wfx_event_group, SL_WFX_DISCONNECT); -} - -#ifdef SL_WFX_CONFIG_SOFTAP -/**************************************************************************** - * @brief - * Callback for AP started - * @param[in] status: Status of wfx start ap api - *****************************************************************************/ -static void sl_wfx_start_ap_callback(uint32_t status) -{ - if (status == AP_START_SUCCESS) - { - SILABS_LOG("AP started\r\n"); - sl_wfx_context->state = - static_cast(static_cast(sl_wfx_context->state) | static_cast(SL_WFX_AP_INTERFACE_UP)); - xEventGroupSetBits(sl_wfx_event_group, SL_WFX_START_AP); - } - else - { - SILABS_LOG("AP start failed\r\n"); - strcpy(event_log, "AP start failed"); - } -} - -/**************************************************************************** - * @brief - * Callback for AP stopped - *****************************************************************************/ -static void sl_wfx_stop_ap_callback(void) -{ - // TODO - // dhcpserver_clear_stored_mac(); - SILABS_LOG("SoftAP stopped\r\n"); - sl_wfx_context->state = - static_cast(static_cast(sl_wfx_context->state) & ~static_cast(SL_WFX_AP_INTERFACE_UP)); - xEventGroupSetBits(sl_wfx_event_group, SL_WFX_STOP_AP); -} - -/**************************************************************************** - * @brief - * Callback for client connect to AP - * @param[in] mac: MAC address of device - *****************************************************************************/ -static void sl_wfx_client_connected_callback(uint8_t * mac) -{ - SILABS_LOG("Client connected, MAC: %02X:%02X:%02X:%02X:%02X:%02X\r\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); - // TODO - SILABS_LOG("Open a web browser and go to http://%d.%d.%d.%d\r\n", ap_ip_addr0, ap_ip_addr1, ap_ip_addr2, ap_ip_addr3); -} - -/**************************************************************************** - * @brief - * Callback for client rejected from AP - * @param[in] status: Status of ap rejected - * @param[in] mac: MAC address of device - *****************************************************************************/ -static void sl_wfx_ap_client_rejected_callback(uint32_t status, uint8_t * mac) -{ - SILABS_LOG("Client rejected, reason: %d, MAC: %02X:%02X:%02X:%02X:%02X:%02X\r\n", (int) status, mac[0], mac[1], mac[2], mac[3], - mac[4], mac[5]); -} - -/**************************************************************************** - * @brief - * Callback for AP client disconnect - * @param[in] status: Status of ap dissconnect - * @param[in] mac: - *****************************************************************************/ -static void sl_wfx_ap_client_disconnected_callback(uint32_t status, uint8_t * mac) -{ - // TODO - SILABS_LOG("Client disconnected, reason: %d, MAC: %02X:%02X:%02X:%02X:%02X:%02X\r\n", (int) status, mac[0], mac[1], mac[2], - mac[3], mac[4], mac[5]); -} -#endif /* SL_WFX_CONFIG_SOFTAP */ - -/**************************************************************************** - * @brief - * Callback for generic status received - * @param[in] farme: - *****************************************************************************/ -static void sl_wfx_generic_status_callback(sl_wfx_generic_ind_t * frame) -{ - (void) (frame); - SILABS_LOG("WFX Generic status received\r\n"); -} - -/*************************************************************************** - * @brief - * WFX events processing task. - * @param[in] p_arg: - * ******************************************************************************/ -static void wfx_events_task(void * p_arg) -{ - TickType_t last_dhcp_poll, now; - EventBits_t flags; - (void) p_arg; - - sta_netif = wfx_get_netif(SL_WFX_STA_INTERFACE); - last_dhcp_poll = xTaskGetTickCount(); - while (true) - { - flags = xEventGroupWaitBits(sl_wfx_event_group, - SL_WFX_CONNECT | SL_WFX_DISCONNECT -#ifdef SL_WFX_CONFIG_SOFTAP - | SL_WFX_START_AP | SL_WFX_STOP_AP -#endif /* SL_WFX_CONFIG_SOFTAP */ -#ifdef SL_WFX_CONFIG_SCAN - | SL_WFX_SCAN_START | SL_WFX_SCAN_COMPLETE -#endif /* SL_WFX_CONFIG_SCAN */ - | BITS_TO_WAIT, - pdTRUE, pdFALSE, pdMS_TO_TICKS(250)); /* 250 msec delay converted to ticks */ - if (flags & SL_WFX_RETRY_CONNECT) - { - if (!retryInProgress) - { - SILABS_LOG("WFX sending the connect command"); - wfx_connect_to_ap(); - retryInProgress = true; - } - } - - if (wifi_extra & WE_ST_STA_CONN) - { - if ((now = xTaskGetTickCount()) > (last_dhcp_poll + pdMS_TO_TICKS(250))) - { -#if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) - uint8_t dhcp_state = dhcpclient_poll(&sta_netif); - - if ((dhcp_state == DHCP_ADDRESS_ASSIGNED) && !hasNotifiedIPV4) - { - wfx_dhcp_got_ipv4((uint32_t) sta_netif->ip_addr.u_addr.ip4.addr); - hasNotifiedIPV4 = true; - if (!hasNotifiedWifiConnectivity) - { - SILABS_LOG("WIFI: Has Notified Wifi Connectivity"); - wfx_connected_notify(CONNECTION_STATUS_SUCCESS, &ap_mac); - hasNotifiedWifiConnectivity = true; - } - } - else if (dhcp_state == DHCP_OFF) - { - wfx_ip_changed_notify(IP_STATUS_FAIL); - hasNotifiedIPV4 = false; - } -#endif // CHIP_DEVICE_CONFIG_ENABLE_IPV4 - if ((ip6_addr_ispreferred(netif_ip6_addr_state(sta_netif, 0))) && !hasNotifiedIPV6) - { - wfx_ipv6_notify(1); - hasNotifiedIPV6 = true; - if (!hasNotifiedWifiConnectivity) - { - wfx_connected_notify(CONNECTION_STATUS_SUCCESS, &ap_mac); - hasNotifiedWifiConnectivity = true; - } - } - last_dhcp_poll = now; - } - } - - if (flags & SL_WFX_CONNECT) - { -#if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) - wfx_ip_changed_notify(IP_STATUS_FAIL); - hasNotifiedIPV4 = false; -#endif // CHIP_DEVICE_CONFIG_ENABLE_IPV4 - wfx_ipv6_notify(GET_IPV6_FAIL); - hasNotifiedIPV6 = false; - hasNotifiedWifiConnectivity = false; - SILABS_LOG("WIFI: Connected to AP"); - wifi_extra |= WE_ST_STA_CONN; - wfx_lwip_set_sta_link_up(); -#ifdef SLEEP_ENABLED - if (!(wfx_get_wifi_state() & SL_WFX_AP_INTERFACE_UP)) - { - // Enable the power save - sl_wfx_set_power_mode(WFM_PM_MODE_PS, WFM_PM_POLL_UAPSD, BEACON_1); - sl_wfx_enable_device_power_save(); - } -#endif // SLEEP_ENABLED - } - - if (flags & SL_WFX_DISCONNECT) - { - -#if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) - wfx_ip_changed_notify(IP_STATUS_FAIL); - hasNotifiedIPV4 = false; -#endif // CHIP_DEVICE_CONFIG_ENABLE_IPV4 - wfx_ipv6_notify(GET_IPV6_FAIL); - hasNotifiedIPV6 = false; - hasNotifiedWifiConnectivity = false; - wifi_extra &= ~WE_ST_STA_CONN; - wfx_lwip_set_sta_link_down(); - } - -#ifdef SL_WFX_CONFIG_SCAN - if (flags & SL_WFX_SCAN_START) - { - /* - * Start the Scan - */ - sl_wfx_ssid_def_t ssid, *sp; - uint16_t num_ssid, slen; - if (scan_ssid) - { - memset(&ssid, 0, sizeof(ssid)); - slen = strlen(scan_ssid); - memcpy(&ssid.ssid[0], scan_ssid, slen); - ssid.ssid_length = slen; - num_ssid = 1; - sp = &ssid; - } - else - { - num_ssid = 0; - sp = (sl_wfx_ssid_def_t *) 0; - } - - SILABS_LOG("WIFI Scan Parameter set to Active channel time %d, Passive " - "Channel Time: %d, Number of prob: %d", - ACTIVE_CHANNEL_TIME, PASSIVE_CHANNEL_TIME, NUM_PROBE_REQUEST); - (void) sl_wfx_set_scan_parameters(ACTIVE_CHANNEL_TIME, PASSIVE_CHANNEL_TIME, NUM_PROBE_REQUEST); - (void) sl_wfx_send_scan_command(WFM_SCAN_MODE_ACTIVE, CHANNEL_LIST, /* Channel list */ - CHANNEL_COUNT, /* Scan all chans */ - sp, num_ssid, IE_DATA, /* IE we're looking for */ - IE_DATA_LENGTH, BSSID_SCAN); - } - if (flags & SL_WFX_SCAN_COMPLETE) - { - struct scan_result_holder *hp, *next; - - SILABS_LOG("WIFI: Return %d scan results", scan_count); - for (hp = scan_save; hp; hp = next) - { - next = hp->next; - (*scan_cb)(&hp->scan); - vPortFree(hp); - } - (*scan_cb)((wfx_wifi_scan_result *) 0); - scan_save = (struct scan_result_holder *) 0; - scan_count = 0; - if (scan_ssid) - { - vPortFree(scan_ssid); - scan_ssid = (char *) 0; - } - /* Terminate scan */ - scan_cb = 0; - } -#endif /* SL_WFX_CONFIG_SCAN */ - } -} - -/**************************************************************************** - * @brief - * Initialize the WF200 used by the two interfaces - *****************************************************************************/ -static sl_status_t wfx_init(void) -{ - /* Initialize the WF200 used by the two interfaces */ - wfx_events_task_start(); - sl_status_t status = sl_wfx_init(&wifiContext); - SILABS_LOG("FMAC Driver version %s", FMAC_DRIVER_VERSION_STRING); - switch (status) - { - case SL_STATUS_OK: - SILABS_LOG("WF200 FW ver:%d.%d.%d [MAC %02x:%02x:%02x-%02x:%02x:%02x]", wifiContext.firmware_major, - wifiContext.firmware_minor, wifiContext.firmware_build, wifiContext.mac_addr_0.octet[0], - wifiContext.mac_addr_0.octet[1], wifiContext.mac_addr_0.octet[2], wifiContext.mac_addr_0.octet[3], - wifiContext.mac_addr_0.octet[4], wifiContext.mac_addr_0.octet[5]); - SILABS_LOG("WF200 Init OK"); - - if (wifiContext.state == SL_WFX_STA_INTERFACE_CONNECTED) - { - sl_wfx_send_disconnect_command(); - } - - break; - case SL_STATUS_WIFI_INVALID_KEY: - SILABS_LOG("*ERR*WF200: F/W keyset invalid"); - break; - case SL_STATUS_WIFI_FIRMWARE_DOWNLOAD_TIMEOUT: - SILABS_LOG("*ERR*WF200: F/W download timo"); - break; - case SL_STATUS_TIMEOUT: - SILABS_LOG("*ERR*WF200: Poll for value timo"); - break; - case SL_STATUS_FAIL: - SILABS_LOG("*ERR*WF200: Error"); - break; - default: - SILABS_LOG("*ERR*WF200: Unknown"); - } - - return status; -} - -/***************************************************************************** - * @brief - * tcp ip, wfx and lwip stack and start dhcp client. - * @return - * sl_status_t Shows init succes or error. - ******************************************************************************/ -static void wfx_wifi_hw_start(void) -{ - sl_status_t status; - - if (wifi_extra & WE_ST_HW_STARTED) - return; - SILABS_LOG("STARTING WF200\n"); - wifi_extra |= WE_ST_HW_STARTED; - - sl_wfx_host_gpio_init(); - if ((status = wfx_init()) == SL_STATUS_OK) - { - /* Initialize the LwIP stack */ - SILABS_LOG("WF200:Start LWIP"); - wfx_lwip_start(); - wifiContext.state = SL_WFX_STARTED; /* Really this is a bit mask */ - SILABS_LOG("WF200:ready.."); - } - else - { - SILABS_LOG("*ERR*WF200:init failed"); - } -} - -/*********************************************************************** - * @brief - * Get AP info - * @param[in] ap: access point information - * @return returns -1 - **************************************************************************/ -int32_t wfx_get_ap_info(wfx_wifi_scan_result_t * ap) -{ - int32_t signal_strength; - SILABS_LOG("WIFI:SSID:: %s", &ap_info.ssid[0]); - memcpy(ap->ssid, ap_info.ssid, sizeof(ap_info.ssid)); - SILABS_LOG("WIFI:Mac addr:: %02x:%02x:%02x:%02x:%02x:%02x", ap_info.bssid[0], ap_info.bssid[1], ap_info.bssid[2], - ap_info.bssid[3], ap_info.bssid[4], ap_info.bssid[5]); - memcpy(ap->bssid, ap_info.bssid, sizeof(ap_info.bssid)); - ap->security = ap_info.security; - SILABS_LOG("WIFI:security:: %d", ap->security); - ap->chan = ap_info.chan; - SILABS_LOG("WIFI:Channel:: to %d", ap->chan); - - sl_status_t status = sl_wfx_get_signal_strength((uint32_t *) &signal_strength); - - if (status == SL_STATUS_OK) - { - SILABS_LOG("status SL_STATUS_OK & signal_strength:: %d", signal_strength); - ap->rssi = (signal_strength - 220) / 2; - } - return status; -} - -/************************************************************************ - * @brief - * Get AP extra info - * @param[in] extra_info: access point extra information - * @return returns -1 - **************************************************************************/ -int32_t wfx_get_ap_ext(wfx_wifi_scan_ext_t * extra_info) -{ - int32_t status; - status = get_all_counters(); - if (status != SL_STATUS_OK) - { - SILABS_LOG("Failed to get the couters"); - } - else - { - extra_info->beacon_lost_count = counters->body.count_miss_beacon; - extra_info->beacon_rx_count = counters->body.count_rx_beacon; - extra_info->mcast_rx_count = counters->body.count_rx_multicast_frames; - extra_info->mcast_tx_count = counters->body.count_tx_multicast_frames; - extra_info->ucast_rx_count = counters->body.count_rx_packets; - extra_info->ucast_tx_count = counters->body.count_tx_packets; - extra_info->overrun_count = gOverrunCount; - } - return status; -} - -sl_status_t get_all_counters(void) -{ - sl_status_t result; - uint8_t command_id = 0x05; - uint16_t mib_id = 0x2035; - sl_wfx_mib_req_t * request = NULL; - uint32_t request_length = SL_WFX_ROUND_UP_EVEN(sizeof(sl_wfx_header_mib_t) + sizeof(sl_wfx_mib_req_body_t)); - - result = - sl_wfx_allocate_command_buffer((sl_wfx_generic_message_t **) &request, command_id, SL_WFX_CONTROL_BUFFER, request_length); - - if (request == NULL) - { - } - - request->body.mib_id = mib_id; - request->header.interface = 0x2; - request->header.encrypted = 0x0; - - result = sl_wfx_send_request(command_id, (sl_wfx_generic_message_t *) request, request_length); - SL_WFX_ERROR_CHECK(result); - - result = sl_wfx_host_wait_for_confirmation(command_id, SL_WFX_DEFAULT_REQUEST_TIMEOUT_MS, (void **) &counters); - SL_WFX_ERROR_CHECK(result); - - SILABS_LOG("%-24s %12s \r\n", "", "Debug Counters Content"); - SILABS_LOG("%-24s %lu\r\n", "rcpi", (unsigned long) counters->body.rcpi); - PUT_COUNTER(plcp_errors); - PUT_COUNTER(fcs_errors); - PUT_COUNTER(tx_packets); - PUT_COUNTER(rx_packets); - PUT_COUNTER(rx_packet_errors); - PUT_COUNTER(rx_decryption_failures); - PUT_COUNTER(rx_mic_failures); - PUT_COUNTER(rx_no_key_failures); - PUT_COUNTER(tx_multicast_frames); - PUT_COUNTER(tx_frames_success); - PUT_COUNTER(tx_frame_failures); - PUT_COUNTER(tx_frames_retried); - PUT_COUNTER(tx_frames_multi_retried); - PUT_COUNTER(rx_frame_duplicates); - PUT_COUNTER(rts_success); - PUT_COUNTER(rts_failures); - PUT_COUNTER(ack_failures); - PUT_COUNTER(rx_multicast_frames); - PUT_COUNTER(rx_frames_success); - PUT_COUNTER(rx_cmacicv_errors); - PUT_COUNTER(rx_cmac_replays); - PUT_COUNTER(rx_mgmt_ccmp_replays); - PUT_COUNTER(rx_bipmic_errors); - PUT_COUNTER(rx_beacon); - PUT_COUNTER(miss_beacon); - -error_handler: - - if (result == SL_STATUS_TIMEOUT) - { - if (sl_wfx_context->used_buffers > 0) - { - sl_wfx_context->used_buffers--; - } - } - if (request != NULL) - { - sl_wfx_free_command_buffer((sl_wfx_generic_message_t *) request, command_id, SL_WFX_CONTROL_BUFFER); - } - - return result; -} - -/************************************************************************ - * @brief - * reset the count - * @return returns -1 - **************************************************************************/ -int32_t wfx_reset_counts() -{ - /* TODO */ - return -1; -} - -/************************************************************************* - * @brief - * I think that this is getting called before FreeRTOS threads are ready - * @return returns SL_STATUS_OK - **************************************************************************/ -sl_status_t wfx_wifi_start(void) -{ - if (wifi_extra & WE_ST_STARTED) - { - SILABS_LOG("WIFI: Already started"); - return SL_STATUS_OK; - } - wifi_extra |= WE_ST_STARTED; - wfx_soft_init(); - wfx_wifi_hw_start(); - - return SL_STATUS_OK; -} - -/**************************************************************************** - * @brief - * get the wifi state - * @return returns wificonetext state - *****************************************************************************/ -sl_wfx_state_t wfx_get_wifi_state(void) -{ - return wifiContext.state; -} - -/**************************************************************************** - * @brief - * getnetif using interface - * @param[in] interface: - * @return returns selectedNetif - *****************************************************************************/ -struct netif * wfx_GetNetif(sl_wfx_interface_t interface) -{ - struct netif * SelectedNetif = NULL; - if (interface == SL_WFX_STA_INTERFACE) - { - SelectedNetif = sta_netif; - } -#ifdef SL_WFX_CONFIG_SOFTAP - else if (interface == SL_WFX_SOFTAP_INTERFACE) - { - // no ap currently - } -#endif - return SelectedNetif; -} - -/**************************************************************************** - * @brief - * get the wifi mac address using interface - * @param[in] interface: - * @return returns wificontext.mac_addr_o if successful, - * wificontext.mac_addr_1 otherwise - *****************************************************************************/ -sl_wfx_mac_address_t wfx_get_wifi_mac_addr(sl_wfx_interface_t interface) -{ - // return Mac address used by WFX SL_WFX_STA_INTERFACE or SL_WFX_SOFTAP_INTERFACE, - return (interface == SL_WFX_STA_INTERFACE) ? wifiContext.mac_addr_0 : wifiContext.mac_addr_1; -} - -/**************************************************************************** - * @brief - * set the wifi provision - * @param[in] wifiConfig: configuration of wifi - *****************************************************************************/ -void wfx_set_wifi_provision(wfx_wifi_provision_t * wifiConfig) -{ - memcpy(wifi_provision.ssid, wifiConfig->ssid, sizeof(wifiConfig->ssid)); - memcpy(wifi_provision.passkey, wifiConfig->passkey, sizeof(wifiConfig->passkey)); - SILABS_LOG("WIFI: Provision SSID=%s", &wifi_provision.ssid[0]); - - /* Not very good - To be improved */ - switch (wifiConfig->security) - { - case WFX_SEC_WPA: - wifi_provision.security = static_cast(sl_wfx_security_mode_e::WFM_SECURITY_MODE_WPA2_WPA1_PSK); - break; - case WFX_SEC_WPA3: - wifi_provision.security = WFM_SECURITY_MODE_WPA3_SAE; - break; - case WFX_SEC_WPA2: - wifi_provision.security = static_cast(sl_wfx_security_mode_e::WFM_SECURITY_MODE_WPA2_WPA1_PSK); - break; - case WFX_SEC_WPA_WPA2_MIXED: - wifi_provision.security = static_cast(sl_wfx_security_mode_e::WFM_SECURITY_MODE_WPA2_WPA1_PSK); - break; - default: - wifi_provision.security = WFM_SECURITY_MODE_WPA2_PSK; - break; - } -} - -/**************************************************************************** - * @brief - * get the wifi provision - * @param[in] wifiConfig: configuration of wifi - * @return returns true if successful, - * false otherwise - *****************************************************************************/ -bool wfx_get_wifi_provision(wfx_wifi_provision_t * wifiConfig) -{ - if (wifiConfig == NULL) - { - return false; - } - memcpy(wifiConfig, &wifi_provision, sizeof(wfx_wifi_provision_t)); - - return true; -} - -/**************************************************************************** - * @brief - * clear the wifi provision - * @return returns true if successful, - * false otherwise - *****************************************************************************/ -void wfx_clear_wifi_provision(void) -{ - memset(&wifi_provision, 0, sizeof(wifi_provision)); -} - -/**************************************************************************** - * @brief - * driver STA provisioned - * @return returns true if successful, - * false otherwise - *****************************************************************************/ -bool wfx_is_sta_provisioned(void) -{ - return (wifi_provision.ssid[0]) ? true : false; -} - -/**************************************************************************** - * @fn sl_status_t wfx_connect_to_ap(void) - * @brief - * driver connect to ap - * @return returns SL_STATUS_NOT_AVAILABLE - *****************************************************************************/ -sl_status_t wfx_connect_to_ap(void) -{ - sl_status_t result; - - if (wifi_provision.ssid[0] == 0) - { - return SL_STATUS_NOT_AVAILABLE; - } - SILABS_LOG("WIFI:JOIN to %s", &wifi_provision.ssid[0]); - - SILABS_LOG("WIFI Scan Parameter set to Active channel time %d, Passive Channel " - "Time: %d, Number of prob: %d", - ACTIVE_CHANNEL_TIME, PASSIVE_CHANNEL_TIME, NUM_PROBE_REQUEST); - (void) sl_wfx_set_scan_parameters(ACTIVE_CHANNEL_TIME, PASSIVE_CHANNEL_TIME, NUM_PROBE_REQUEST); - result = - sl_wfx_send_join_command((uint8_t *) wifi_provision.ssid, strlen(wifi_provision.ssid), NULL, CHANNEL_0, - static_cast(wifi_provision.security), PREVENT_ROAMING, DISABLE_PMF_MODE, - (uint8_t *) wifi_provision.passkey, strlen(wifi_provision.passkey), NULL, IE_DATA_LENGTH); - - return result; -} - -/**************************************************************************** - * @brief - * get the wifi mac addresss - * @param[in] interface: - * @param[in] addr : address - *****************************************************************************/ -void wfx_get_wifi_mac_addr(sl_wfx_interface_t interface, sl_wfx_mac_address_t * addr) -{ - sl_wfx_mac_address_t * mac; - -#ifdef SL_WFX_CONFIG_SOFTAP - mac = (interface == SL_WFX_SOFTAP_INTERFACE) ? &wifiContext.mac_addr_1 : &wifiContext.mac_addr_0; -#else - mac = &wifiContext.mac_addr_0; -#endif - *addr = *mac; - SILABS_LOG("WLAN:Get WiFi Mac addr %02x:%02x:%02x:%02x:%02x:%02x", mac->octet[0], mac->octet[1], mac->octet[2], mac->octet[3], - mac->octet[4], mac->octet[5]); - memcpy(&ap_info.bssid[0], &mac->octet[0], 6); -} - -/**************************************************************************** - * @brief - * function called when driver have ipv4 address - * @param[in] which_if: - * @return returns false if successful, - * true otherwise - *****************************************************************************/ -bool wfx_have_ipv4_addr(sl_wfx_interface_t which_if) -{ - if (which_if == SL_WFX_STA_INTERFACE) - { - return (sta_ip == STA_IP_FAIL) ? false : true; - } - else - { - return false; /* TODO */ - } -} - -/**************************************************************************** - * @brief - * function called when driver have ipv6 address - * @param[in] which_if: - * @return returns false if successful, - * true otherwise - *****************************************************************************/ -bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) -{ - SILABS_LOG("%s: started.", __func__); - bool status = false; - if (which_if == SL_WFX_STA_INTERFACE) - { - status = wfx_is_sta_connected(); - } - else - { - status = false; /* TODO */ - } - SILABS_LOG("%s: status: %d", __func__, status); - return status; -} - -/**************************************************************************** - * @brief - * Disconnect station mode from connected AP - * @returns Returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t wfx_sta_discon(void) -{ - SILABS_LOG("STA-Disconnecting"); - int32_t status = sl_wfx_send_disconnect_command(); - wifi_extra &= ~WE_ST_STA_CONN; - xEventGroupSetBits(sl_wfx_event_group, SL_WFX_RETRY_CONNECT); - return status; -} - -/**************************************************************************** - * @brief - * enable the STA mode - * @return returns true - *****************************************************************************/ -bool wfx_is_sta_mode_enabled(void) -{ - return true; /* It always is */ -} - -/**************************************************************************** - * @brief - * fuction called when driver is STA connected - * @return returns true if successful, - * false otherwise - *****************************************************************************/ -bool wfx_is_sta_connected(void) -{ - bool val; - - val = (wifi_extra & WE_ST_STA_CONN) ? true : false; - - SILABS_LOG("WLAN: STA %s connected", (val ? "IS" : "NOT")); - - return val; -} - -/**************************************************************************** - * @brief - * It is automatically done when lwip link up - * @return returns true if successful, - * false otherwise - *****************************************************************************/ -void wfx_setup_ip6_link_local(sl_wfx_interface_t whichif) -{ - SILABS_LOG("Setup-IP6: TODO"); /* It is automatically done when lwip link up */ -} - -/**************************************************************************** - * @brief - * get the wifi mode - * @return returns WIFI_MODE_NULL if successful, - * WIFI_MODE_STA otherwise - *****************************************************************************/ -wifi_mode_t wfx_get_wifi_mode() -{ - if (wifiContext.state & SL_WFX_STARTED) - return WIFI_MODE_STA; - return WIFI_MODE_NULL; -} - -/***************************************************************************** - * @brief - * This is called from the context of AppTask - * For WF200 - Start WIFI here - * @return returns true if successful, - * false otherwise - ******************************************************************************/ -bool wfx_hw_ready(void) -{ - return (wifiContext.state & SL_WFX_STARTED) ? true : false; -} - -#if CHIP_DEVICE_CONFIG_ENABLE_IPV4 -/***************************************************************************** - * @brief - * function called when dhcp got ipv4 - * @param[in] ip : internet protocol - ******************************************************************************/ -void wfx_dhcp_got_ipv4(uint32_t ip) -{ - /* Acquire the new IP address - */ - sta_ip = ip; - wfx_ip_changed_notify(IP_STATUS_SUCCESS); -} -#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ - -/***************************************************************************** - * @brief - * function called from connectivityManager - ******************************************************************************/ -void wfx_enable_sta_mode(void) -{ - /* Nothing to do - default is that it is - place holder */ -} - -/**************************************************************************** - * @brief - * driver scan start - * @param[in] callback: Callback from the wifi scan results - * @return returns true if successful, - * false otherwise - *****************************************************************************/ -#ifdef SL_WFX_CONFIG_SCAN -bool wfx_start_scan(char * ssid, void (*callback)(wfx_wifi_scan_result_t *)) -{ - int sz; - - if (scan_cb) - return false; /* Already in progress */ - if (ssid) - { - sz = strlen(ssid); - if ((scan_ssid = (char *) pvPortMalloc(sz + 1)) == (char *) 0) - { - return false; - } - strcpy(scan_ssid, ssid); - } - scan_cb = callback; - xEventGroupSetBits(sl_wfx_event_group, SL_WFX_SCAN_START); - - return true; -} - -/**************************************************************************** - * @brief - * driver scan cancelation - *****************************************************************************/ -void wfx_cancel_scan(void) -{ - struct scan_result_holder *hp, *next; - /* Not possible */ - if (!scan_cb) - { - return; - } - sl_wfx_send_stop_scan_command(); - for (hp = scan_save; hp; hp = next) - { - next = hp->next; - vPortFree(hp); - } - scan_save = (struct scan_result_holder *) 0; - scan_count = 0; - if (scan_ssid) - { - vPortFree(scan_ssid); - scan_ssid = (char *) 0; - } - scan_cb = 0; -} -#endif /* SL_WFX_CONFIG_SCAN */ diff --git a/examples/platform/silabs/SiWx917/wf200/sl_wfx_board.h b/examples/platform/silabs/SiWx917/wf200/sl_wfx_board.h deleted file mode 100644 index 96ab9681745fdc..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/sl_wfx_board.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _SL_WFX_BOARD_H_ -#define _SL_WFX_BOARD_H_ -/* - * Pull in the right board PINS - */ -#if defined(EFR32MG12_BRD4161A) || defined(BRD4161A) || defined(EFR32MG12_BRD4162A) || defined(BRD4162A) || \ - defined(EFR32MG12_BRD4163A) || defined(BRD4163A) || defined(EFR32MG12_BRD4164A) || defined(BRD4164A) || \ - defined(EFR32MG12_BRD4170A) || defined(BRD4170A) -#include "brd4161a.h" -#elif defined(EFR32MG24_BRD4186C) || defined(BRD4186C) || defined(EFR32MG24_BRD4186A) || defined(BRD4186A) -#include "brd4186c.h" -#elif defined(EFR32MG24_BRD4187C) || defined(BRD4187C) || defined(EFR32MG24_BRD4187A) || defined(BRD4187A) -#include "brd4187c.h" -#else -#error "Need SPI Pins" -#endif /* EFR32MG12_BRD4161A */ -#endif /* _SL_WFX_BOARD_H_ */ diff --git a/examples/platform/silabs/SiWx917/wf200/sl_wfx_configuration.h b/examples/platform/silabs/SiWx917/wf200/sl_wfx_configuration.h deleted file mode 100644 index deb468d1a6af73..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/sl_wfx_configuration.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -// SL_WFX_DEFAULT_REQUEST_TIMEOUT_MS> Timeout period in milliseconds<250-10000> -// Default: 5000 -// Timeout period in milliseconds for requests. -#define SL_WFX_DEFAULT_REQUEST_TIMEOUT_MS (5000) - -// WFx Secure Link configuration - -// SL_WFX_SLK_CURVE25519> Use crypto curves -// Default: 1 -// If this option is enabled ECDH crypto is used, KDF otherwise. -#define SL_WFX_SLK_CURVE25519 (1) diff --git a/examples/platform/silabs/SiWx917/wf200/sl_wfx_crypto.c b/examples/platform/silabs/SiWx917/wf200/sl_wfx_crypto.c deleted file mode 100644 index ddad3ec5b95dde..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/sl_wfx_crypto.c +++ /dev/null @@ -1,409 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifdef SL_WFX_USE_SECURE_LINK - -/* Includes */ - -#include "sl_wfx.h" -#include - -#include "mbedtls/ccm.h" -#include "mbedtls/ctr_drbg.h" -#include "mbedtls/ecdh.h" -#include "mbedtls/entropy.h" -#include "mbedtls/md.h" -#include "mbedtls/sha256.h" - -#include "FreeRTOS.h" -#include "queue.h" -#include "semphr.h" -#include "task.h" - -// Secure link MAC key location for WGM160P (in DI page in flash) -#ifdef EFM32GG11B820F2048GM64 // WGM160PX22KGA2 -#define SL_WFX_FCCC_BASE_ADDR ((void *) 0x0fe08000ul) -#define SL_WFX_FCCC_DI_OFFSET 0x1B0ul -#define SL_WFX_FCCC_DI_ADDR ((void *) (SL_WFX_FCCC_BASE_ADDR + SL_WFX_FCCC_DI_OFFSET)) -#define SL_WFX_SECURE_LINK_MAC_KEY_LOCATION ((void *) (SL_WFX_FCCC_BASE_ADDR + 0x3D0)) -#endif -/****************************************************** - * Macros - ******************************************************/ -#define MAC_KEY_FAIL_BYTE 0XFF -#define KEY_DIGEST_SIZE 92 -#define MEMCMP_FAIL 0 -#define MPI_SET 1 -#define SUCCESS_STATUS_WIFI_SECURE_LINK_EXCHANGE 0 -#define SHA224_0 0 -#define HMAC_SIZE 92 -#define MEMSET_LEN 1 -#define LABLE_LEN 24 -#define ADDRESS_LENGTH 0 -#define CCM_STATUS_SUCCESS 0 -/****************************************************** - * Constants - ******************************************************/ - -/* Semaphore to signal wfx driver available */ -extern TaskHandle_t wfx_securelink_task; -extern SemaphoreHandle_t wfx_securelink_rx_mutex; - -/****************************************************** - * Enumerations - ******************************************************/ - -/****************************************************** - * Type Definitions - ******************************************************/ - -/****************************************************** - * Structures - ******************************************************/ - -/****************************************************** - * Function Declarations - ******************************************************/ - -static inline void reverse_bytes(uint8_t * src, uint8_t length); - -/****************************************************** - * Variable Definitions - ******************************************************/ - -#if SL_WFX_SLK_CURVE25519 -static mbedtls_ecdh_context mbedtls_host_context; -static mbedtls_ctr_drbg_context host_drbg_context; -#endif -static mbedtls_entropy_context entropy; -uint8_t temp_key_location[SL_WFX_HOST_PUB_KEY_MAC_SIZE]; -#ifdef EFM32GG11B820F2048GM64 // WGM160PX22KGA2 -static const uint8_t * const secure_link_mac_key = (uint8_t *) SL_WFX_SECURE_LINK_MAC_KEY_LOCATION; -#else -static const uint8_t secure_link_mac_key[SL_WFX_SECURE_LINK_MAC_KEY_LENGTH] = { 0x2B, 0x49, 0xFD, 0x66, 0xCB, 0x74, 0x6D, 0x6B, - 0x4F, 0xDC, 0xC3, 0x79, 0x4E, 0xC5, 0x9A, 0x86, - 0xE5, 0x48, 0x2A, 0x41, 0x22, 0x87, 0x8B, 0x12, - 0x1A, 0x7C, 0x3E, 0xEF, 0xB7, 0x04, 0x9E, 0xB3 }; -#endif -/****************************************************** - * Function Definitions - ******************************************************/ -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_get_secure_link_mac_key(uint8_t *sl_mac_key) - * @brief - * Get secure link mac key - * @param[in] sl_mac_key: - * @return returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_get_secure_link_mac_key(uint8_t * sl_mac_key) -{ - sl_status_t result = SL_STATUS_WIFI_SECURE_LINK_MAC_KEY_ERROR; - - memcpy(sl_mac_key, secure_link_mac_key, SL_WFX_SECURE_LINK_MAC_KEY_LENGTH); - - for (uint8_t index = 0; index < SL_WFX_SECURE_LINK_MAC_KEY_LENGTH; ++index) - { - // Assuming 0xFF... when not written - if (sl_mac_key[index] != MAC_KEY_FAIL_BYTE) - { - result = SL_STATUS_OK; - break; - } - } - - return result; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_compute_pub_key(sl_wfx_securelink_exchange_pub_keys_req_body_t *request, - const uint8_t *sl_mac_key) - * @brief - * compute host public key - * @param[in] request : - * @param[in] sl_mac_key : - * @return returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_compute_pub_key(sl_wfx_securelink_exchange_pub_keys_req_body_t * request, const uint8_t * sl_mac_key) -{ - sl_status_t status = SL_STATUS_OK; - -#if SL_WFX_SLK_CURVE25519 - const char identifier[] = "ecdh"; - - mbedtls_ecdh_init(&mbedtls_host_context); - mbedtls_ctr_drbg_init(&host_drbg_context); - mbedtls_entropy_init(&entropy); - status = mbedtls_ctr_drbg_seed(&host_drbg_context, mbedtls_entropy_func, &entropy, (const unsigned char *) identifier, - sizeof(identifier)); - status += mbedtls_ecp_group_load(&mbedtls_host_context.grp, MBEDTLS_ECP_DP_CURVE25519); - status += mbedtls_ecdh_gen_public(&mbedtls_host_context.grp, &mbedtls_host_context.d, &mbedtls_host_context.Q, - mbedtls_ctr_drbg_random, &host_drbg_context); - status += mbedtls_mpi_write_binary(&mbedtls_host_context.Q.X, request->host_pub_key, SL_WFX_HOST_PUB_KEY_SIZE); -#else - mbedtls_entropy_init(&entropy); - status = mbedtls_entropy_func(&entropy, request->host_pub_key, SL_WFX_HOST_PUB_KEY_SIZE); -#endif - reverse_bytes(request->host_pub_key, SL_WFX_HOST_PUB_KEY_SIZE); - SL_WFX_ERROR_CHECK(status); - - // Generate SHA512 digest of public key - status = mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), sl_mac_key, SL_WFX_HOST_PUB_KEY_SIZE, - request->host_pub_key, SL_WFX_HOST_PUB_KEY_SIZE, request->host_pub_key_mac); - SL_WFX_ERROR_CHECK(status); - -error_handler: - if (status != SL_STATUS_OK) - { - return SL_STATUS_WIFI_SECURE_LINK_EXCHANGE_FAILED; - } - return status; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_verify_pub_key(sl_wfx_securelink_exchange_pub_keys_ind_t *response_packet, - const uint8_t *sl_mac_key, - uint8_t *sl_host_pub_key) - * @brief - * verify host public key - * @param[in] response_packet: - * @param[in] sl_mac_key: - * @param[in] sl_host_pub_key: - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_verify_pub_key(sl_wfx_securelink_exchange_pub_keys_ind_t * response_packet, const uint8_t * sl_mac_key, - uint8_t * sl_host_pub_key) -{ - sl_status_t status = SL_STATUS_OK; - uint8_t shared_key_digest[KEY_DIGEST_SIZE]; - - if (xSemaphoreTake(wfx_securelink_rx_mutex, portMAX_DELAY) != pdTRUE) - { - return SL_STATUS_WIFI_SECURE_LINK_EXCHANGE_FAILED; - } - - // Compute the Hash and verify the public key/hashing - status = mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), sl_mac_key, SL_WFX_NCP_PUB_KEY_SIZE, - response_packet->body.ncp_pub_key, SL_WFX_NCP_PUB_KEY_SIZE, temp_key_location); - SL_WFX_ERROR_CHECK(status); - - // Calculate session key if public key/SHA512 digest matches - if (memcmp(temp_key_location, response_packet->body.ncp_pub_key_mac, SL_WFX_HOST_PUB_KEY_MAC_SIZE) != MEMCMP_FAIL) - { - status = SL_STATUS_WIFI_SECURE_LINK_EXCHANGE_FAILED; - goto error_handler; - } - -#if SL_WFX_SLK_CURVE25519 - SL_WFX_UNUSED_PARAMETER(sl_host_pub_key); - - mbedtls_mpi_lset(&mbedtls_host_context.Qp.Z, MPI_SET); - - // Read Ineo public key - reverse_bytes(response_packet->body.ncp_pub_key, SL_WFX_NCP_PUB_KEY_SIZE); - mbedtls_mpi_read_binary(&mbedtls_host_context.Qp.X, response_packet->body.ncp_pub_key, SL_WFX_NCP_PUB_KEY_SIZE); - - // Calculate shared secret - if (mbedtls_ecdh_compute_shared(&mbedtls_host_context.grp, &mbedtls_host_context.z, &mbedtls_host_context.Qp, - &mbedtls_host_context.d, mbedtls_ctr_drbg_random, - &host_drbg_context) != SUCCESS_STATUS_WIFI_SECURE_LINK_EXCHANGE) - { - status = SL_STATUS_WIFI_SECURE_LINK_EXCHANGE_FAILED; - goto error_handler; - } - - // Generate session key - mbedtls_mpi_write_binary(&mbedtls_host_context.z, temp_key_location, SL_WFX_HOST_PUB_KEY_SIZE); - reverse_bytes(temp_key_location, SL_WFX_HOST_PUB_KEY_SIZE); - mbedtls_sha256(temp_key_location, SL_WFX_HOST_PUB_KEY_SIZE, shared_key_digest, SHA224_0); -#else - uint8_t hmac_input[HMAC_SIZE] = { 0 }; - char label[LABLE_LEN] = "SecureLink!KeyDerivation"; - - memset((uint16_t *) &hmac_input[0], (uint16_t) sl_wfx_htole16(1), MEMSET_LEN); - memcpy((uint8_t *) &hmac_input[2], (uint8_t *) label, LABLE_LEN); - memcpy((uint8_t *) &hmac_input[26], sl_host_pub_key, SL_WFX_NCP_PUB_KEY_SIZE); - memcpy((uint8_t *) &hmac_input[58], (uint8_t *) response_packet->body.ncp_pub_key, SL_WFX_NCP_PUB_KEY_SIZE); - memset((uint16_t *) &hmac_input[90], (uint16_t) sl_wfx_htole16(128), 1); - - // Generate SHA256 digest of hmac_input - status = mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), sl_mac_key, SL_WFX_HOST_PUB_KEY_SIZE, - (uint8_t *) hmac_input, HMAC_SIZE, shared_key_digest); -#endif - - memcpy(sl_wfx_context->secure_link_session_key, shared_key_digest, - SL_WFX_SECURE_LINK_SESSION_KEY_LENGTH); // Use the lower 16 bytes of the sha256 - sl_wfx_context->secure_link_nonce.hp_packet_count = 0; - sl_wfx_context->secure_link_nonce.rx_packet_count = 0; - sl_wfx_context->secure_link_nonce.tx_packet_count = 0; - -error_handler: - if (xSemaphoreGive(wfx_securelink_rx_mutex) != pdTRUE) - { - printf("ERROR: sl_wfx_securelink_rx_mutex. unable to post.\n"); - } - return status; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_free_crypto_context(void) - * @brief - * Free host crypto context - * @param[in] None - * @return returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_free_crypto_context(void) -{ -#if SL_WFX_SLK_CURVE25519 - mbedtls_ecdh_free(&mbedtls_host_context); - mbedtls_ctr_drbg_free(&host_drbg_context); -#endif - mbedtls_entropy_free(&entropy); - - return SL_STATUS_OK; -} - -/******************************************************************************** - * @fn sl_status_t sl_wfx_host_decode_secure_link_data(uint8_t *buffer, uint32_t length, uint8_t *session_key) - * @brief - * Decode receive data - * Length excludes size of CCM tag and secure link header - * @param[in] buffer: - * @param[in] length: - * @param[in] session_key: - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - ********************************************************************************/ -sl_status_t sl_wfx_host_decode_secure_link_data(uint8_t * buffer, uint32_t length, uint8_t * session_key) -{ - mbedtls_ccm_context ccm_context; - sl_status_t status = SL_STATUS_SECURITY_DECRYPT_ERROR; - int crypto_status; - sl_wfx_nonce_t nonce = { 0, 0, 0 }; - - if (xSemaphoreTake(wfx_securelink_rx_mutex, portMAX_DELAY) != pdTRUE) - { - return SL_STATUS_FAIL; - } - - // Nonce for decryption should have TX and HP counters 0, only use RX counter - nonce.rx_packet_count = sl_wfx_context->secure_link_nonce.rx_packet_count; - - // Init context - mbedtls_ccm_init(&ccm_context); - - // Set the crypto key - crypto_status = mbedtls_ccm_setkey(&ccm_context, MBEDTLS_CIPHER_ID_AES, session_key, SL_WFX_SECURE_LINK_SESSION_KEY_BIT_COUNT); - SL_WFX_ERROR_CHECK(crypto_status); - - // Decrypt the data - if (!mbedtls_ccm_auth_decrypt(&ccm_context, length, (uint8_t *) &nonce, SL_WFX_SECURE_LINK_NONCE_SIZE_BYTES, NULL, - ADDRESS_LENGTH, (uint8_t *) buffer, (uint8_t *) buffer, (uint8_t *) buffer + length, - SL_WFX_SECURE_LINK_CCM_TAG_SIZE)) - { - status = SL_STATUS_OK; - } - -error_handler: - mbedtls_ccm_free(&ccm_context); - if (xSemaphoreGive(wfx_securelink_rx_mutex) != pdTRUE) - { - printf("ERROR: sl_wfx_securelink_rx_mutex. unable to post.\n"); - } - return status; -} - -/********************************************************************* - * @fn sl_status_t sl_wfx_host_encode_secure_link_data(sl_wfx_generic_message_t *buffer, - uint32_t data_length, - uint8_t *session_key, - uint8_t *nonce) - * @brief - * Encode transmit data - * Length excludes size of CCM tag and secure link header - * @param[in] buffer: - * @param[in] data_length: - * @param[in] session_key: - * @param[in] nonce: - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise -*************************************************************************/ -sl_status_t sl_wfx_host_encode_secure_link_data(sl_wfx_generic_message_t * buffer, uint32_t data_length, uint8_t * session_key, - uint8_t * nonce) -{ - mbedtls_ccm_context ccm_context; - sl_status_t status = SL_STATUS_FAIL; - - mbedtls_ccm_init(&ccm_context); - if (mbedtls_ccm_setkey(&ccm_context, MBEDTLS_CIPHER_ID_AES, session_key, SL_WFX_SECURE_LINK_SESSION_KEY_BIT_COUNT) == - CCM_STATUS_SUCCESS) - { - mbedtls_ccm_encrypt_and_tag(&ccm_context, data_length, nonce, SL_WFX_SECURE_LINK_NONCE_SIZE_BYTES, NULL, ADDRESS_LENGTH, - (uint8_t *) &buffer->header.id, (uint8_t *) &buffer->header.id, - (uint8_t *) &buffer->header.id + data_length, SL_WFX_SECURE_LINK_CCM_TAG_SIZE); - status = SL_STATUS_OK; - } - - mbedtls_ccm_free(&ccm_context); - - return status; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_schedule_secure_link_renegotiation(void) - * @brief - * Called when the driver needs to schedule secure link renegotiation - * @param[in] None - * @returns Returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_schedule_secure_link_renegotiation(void) -{ - // call sl_wfx_secure_link_renegotiate_session_key() as soon as it makes sense for the host to do so - xTaskNotifyGive(wfx_securelink_task); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn static inline void reverse_bytes(uint8_t *src, uint8_t length) - * @brief - * reverse the bytes - * @param[in] src: source - * @param[in] length: - * @returns None - *****************************************************************************/ -static inline void reverse_bytes(uint8_t * src, uint8_t length) -{ - uint8_t * lo = src; - uint8_t * hi = src + length - 1; - uint8_t swap; - - while (lo < hi) - { - swap = *lo; - *lo++ = *hi; - *hi-- = swap; - } -} - -/******************************************************************************************************** - ******************************************************************************************************** - * DEPENDENCIES & AVAIL CHECK(S) - ******************************************************************************************************** - *******************************************************************************************************/ - -#endif // SL_WFX_USE_SECURE_LINK diff --git a/examples/platform/silabs/SiWx917/wf200/sl_wfx_host.h b/examples/platform/silabs/SiWx917/wf200/sl_wfx_host.h deleted file mode 100644 index dc9bcd28524623..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/sl_wfx_host.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "FreeRTOS.h" -#include "queue.h" -#include "semphr.h" -#include "sl_wfx.h" -#include "task.h" - -#ifdef __cplusplus -extern "C" { -#endif -uint8_t sl_wfx_host_get_waited_event(void); -sl_status_t wfx_soft_init(void); - -#ifdef SLEEP_ENABLED -sl_status_t sl_wfx_host_switch_to_wirq(void); -#endif -#ifdef __cplusplus -} -#endif - -#define SL_WFX_MAX_STATIONS 8 -#define SL_WFX_MAX_SCAN_RESULTS 50 - -typedef struct __attribute__((__packed__)) scan_result_list_s -{ - sl_wfx_ssid_def_t ssid_def; - uint8_t mac[SL_WFX_MAC_ADDR_SIZE]; - uint16_t channel; - sl_wfx_security_mode_bitmask_t security_mode; - uint16_t rcpi; -} scan_result_list_t; - -void sl_wfx_host_start_platform_interrupt(void); -extern SemaphoreHandle_t wfx_wakeup_sem; diff --git a/examples/platform/silabs/SiWx917/wf200/sl_wfx_securelink_task.c b/examples/platform/silabs/SiWx917/wf200/sl_wfx_securelink_task.c deleted file mode 100644 index 28ffdda2c3852f..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/sl_wfx_securelink_task.c +++ /dev/null @@ -1,85 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifdef SL_WFX_USE_SECURE_LINK -#include "secure_link/sl_wfx_secure_link.h" - -#include "FreeRTOS.h" -#include "queue.h" -#include "semphr.h" -#include "task.h" -#include -#include -#include - -// Securelink Task Configurations -#define WFX_SECURELINK_TASK_PRIO 1u -#define WFX_SECURELINK_TASK_STK_SIZE 512u - -TaskHandle_t secureLinkTaskHandle; -SemaphoreHandle_t s_xSLSemaphore; -StackType_t secureLinkStack[WFX_SECURELINK_TASK_STK_SIZE]; -StaticTask_t secureLinkTaskStruct; - -StaticSemaphore_t xSlMutexBuffer; - -/********************************************************************* - * @fn static void prvSecureLinkTask(void *p_arg) - * @brief - * The task that implements the Secure Link renegotiation with WFX. - * @param[in] p_arg: - * @return None - *************************************************************************/ -static void prvSecureLinkTask(void * p_arg) -{ - sl_status_t result; - (void) p_arg; - - /* Create a mutex used for making Secure Link renegotiations atomic */ - s_xSLSemaphore = xSemaphoreCreateMutexStatic(&xSlMutexBuffer); - - for (;;) - { - /* Wait for a key renegotiation request */ - ulTaskNotifyTake(pdTRUE, portMAX_DELAY); - - result = sl_wfx_secure_link_renegotiate_session_key(); - if (result != SL_STATUS_OK) - { - printf("session key negotiation error %lu\n", result); - } - } -} - -/**************************************************************************** - * @fn void wfx_securelink_task_start(void) - * @brief - * Creates WFX securelink key renegotiation task. - * @param[in] None - * @return None - ******************************************************************************/ -void wfx_securelink_task_start(void) -{ - secureLinkTaskHandle = xTaskCreateStatic(prvSecureLinkTask, "secureLinkTask", WFX_SECURELINK_TASK_STK_SIZE, NULL, - WFX_SECURELINK_TASK_PRIO, secureLinkStack, &secureLinkTaskStruct); - if (secureLinkTaskHandle == NULL) - { - printf("Failed to create WFX secureLinkTask"); - } -} - -#endif diff --git a/examples/platform/silabs/SiWx917/wf200/sl_wfx_task.c b/examples/platform/silabs/SiWx917/wf200/sl_wfx_task.c deleted file mode 100644 index 8a00e454ade504..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/sl_wfx_task.c +++ /dev/null @@ -1,128 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "em_gpio.h" - -#include "sl_wfx.h" -#include "sl_wfx_board.h" -#include "sl_wfx_host.h" -#include "sl_wfx_task.h" - -#include "FreeRTOS.h" -#include "event_groups.h" -#include "task.h" - -#include "AppConfig.h" - -#define CHECK_VAL 0 -#define WFX_BUS_TASK_PRIORITY 2 -#define BUS_TASK_STACK_SIZE 1024 -static StackType_t busStack[BUS_TASK_STACK_SIZE]; -StaticTask_t busTaskStruct; -TaskHandle_t wfx_bus_task_handle; - -wfx_frame_q_item wfx_bus_tx_frame; -SemaphoreHandle_t wfxtask_tx_complete; -SemaphoreHandle_t wfxtask_mutex; - -// Flag to indicate receive frames is currently running. -static bool wfx_bus_rx_in_process = false; - -/*************************************************************************** - * @fn bool wfx_bus_is_receive_processing(void) - * @brief - * Check receive frame status - * @param[in] None - * @return returns wfx_bus_rx_in_process - ******************************************************************************/ -bool wfx_bus_is_receive_processing(void) -{ - return wfx_bus_rx_in_process; -} - -/***************************************************************************** - * @fn static sl_status_t receive_frames() - * @brief - * Receives frames from the WFX. - * @param[in] None - * @return returns result - ******************************************************************************/ -static sl_status_t receive_frames() -{ - sl_status_t result; - uint16_t control_register = 0; - wfx_bus_rx_in_process = true; - do - { - result = sl_wfx_receive_frame(&control_register); - SL_WFX_ERROR_CHECK(result); - } while ((control_register & SL_WFX_CONT_NEXT_LEN_MASK) != CHECK_VAL); - -error_handler: - wfx_bus_rx_in_process = false; - return result; -} - -/******************************************************************************** - * @fn static void wfx_bus_task(void *p_arg) - * @brief - * WFX bus communication task. - * receives frames from the Bus interface - * @param[in] p_arg: - * @return None - */ -static void wfx_bus_task(void * p_arg) -{ - SILABS_LOG("SPI: Bus Task started"); - sl_wfx_host_start_platform_interrupt(); - for (;;) - { - /*Wait for an interrupt from WFX*/ - ulTaskNotifyTake(pdTRUE, portMAX_DELAY); - - /*Disable the interrupt while treating frames received to avoid - *the case where the interrupt is set but there is no frame left to treat.*/ - sl_wfx_host_disable_platform_interrupt(); - - /*Receive the frame(s) pending in WFX*/ - receive_frames(); - - /*Re-enable the interrupt*/ - sl_wfx_host_enable_platform_interrupt(); - } -} - -/*************************************************************************** - * @fn void wfx_bus_start() - * @brief - * Creates WFX bus communication task. - * @param[in] None - * @return None - ******************************************************************************/ -void wfx_bus_start() -{ - wfx_bus_task_handle = - xTaskCreateStatic(wfx_bus_task, "wfxbus", BUS_TASK_STACK_SIZE, NULL, WFX_BUS_TASK_PRIORITY, busStack, &busTaskStruct); - if (wfx_bus_task_handle == NULL) - { - SILABS_LOG("*ERR*WFX BusTask"); - } -} diff --git a/examples/platform/silabs/SiWx917/wf200/sl_wfx_task.h b/examples/platform/silabs/SiWx917/wf200/sl_wfx_task.h deleted file mode 100644 index 6838b9bac14eb4..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/sl_wfx_task.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -#include "FreeRTOS.h" -#include "sl_wfx_constants.h" -#include "task.h" - -typedef struct -{ - sl_wfx_send_frame_req_t * frame; - uint32_t data_length; - sl_wfx_interface_t interface; - uint8_t priority; -} wfx_frame_q_item; - -extern wfx_frame_q_item wfxtask_tx_frame; -extern TaskHandle_t wfx_bus_task_handle; - -#ifdef __cplusplus -extern "C" { -#endif - -/**************************************************************************** - * @fn void wfx_bus_start(void) - * @brief - * Start wfx bus communication task. - *****************************************************************************/ -void wfx_bus_start(void); - -/**************************************************************************** - * @fn bool wfx_bus_is_receive_processing(void) - * @brief - * Returns status of wfx receive frames. - *****************************************************************************/ -bool wfx_bus_is_receive_processing(void); - -#ifdef __cplusplus -} -#endif diff --git a/examples/platform/silabs/SiWx917/wf200/wf200.gni b/examples/platform/silabs/SiWx917/wf200/wf200.gni deleted file mode 100644 index 358384a81121bf..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/wf200.gni +++ /dev/null @@ -1,30 +0,0 @@ -import("//build_overrides/chip.gni") -import("//build_overrides/efr32_sdk.gni") -import("//build_overrides/pigweed.gni") - -examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" -wifi_sdk_dir = "${chip_root}/src/platform/silabs/EFR32/wifi" - -wf200_defs = [ - "SL_HEAP_SIZE=24576", - "WF200_WIFI=1", - "SL_WIFI=1", - "SL_WFX_USE_SPI", - "SL_WFX_DEBUG_MASK=0x0003", -] -softap_defs = "SL_WFX_CONFIG_SOFTAP" -wifi_scan_defs = "SL_WFX_CONFIG_SCAN" -wf200_plat_incs = [ - "${wifi_sdk_dir}/", - "${examples_plat_dir}/wf200", -] -wf200_plat_src = [ - "${wifi_sdk_dir}/dhcp_client.cpp", - "${wifi_sdk_dir}/ethernetif.cpp", - "${wifi_sdk_dir}/lwip_netif.cpp", - "${wifi_sdk_dir}/wfx_notify.cpp", - "${examples_plat_dir}/wf200/sl_wfx_task.c", - "${examples_plat_dir}/wf200/wf200_init.c", - "${examples_plat_dir}/wf200/efr_spi.c", - "${examples_plat_dir}/wf200/host_if.cpp", -] diff --git a/examples/platform/silabs/SiWx917/wf200/wf200_init.c b/examples/platform/silabs/SiWx917/wf200/wf200_init.c deleted file mode 100644 index 12973d3c8ffb67..00000000000000 --- a/examples/platform/silabs/SiWx917/wf200/wf200_init.c +++ /dev/null @@ -1,543 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* Includes */ - -#include "em_gpio.h" - -#include "sl_wfx.h" -#include "sl_wfx_board.h" - -// File specific to each platform, it must be created for custom boards -#include "sl_wfx_pds.h" - -#include -#include -#include -#include - -/* Firmware include */ -#include "sl_wfx_wf200_C0.h" - -#include "FreeRTOS.h" -#include "event_groups.h" -#include "task.h" - -#include "AppConfig.h" -#include "sl_wfx_host.h" -#include "sl_wfx_task.h" -#include "wfx_host_events.h" - -#include "sl_spidrv_instances.h" -#include "spidrv.h" - -#define SL_WFX_EVENT_MAX_SIZE 512 -#define SL_WFX_EVENT_LIST_SIZE 1 - -StaticSemaphore_t xWfxWakeupSemaBuffer; -uint8_t sWfxEventQueueBuffer[SL_WFX_EVENT_LIST_SIZE * sizeof(uint8_t)]; -StaticQueue_t sWfxEventQueueStruct; -QueueHandle_t wfx_event_Q = NULL; -SemaphoreHandle_t wfx_wakeup_sem = NULL; -SemaphoreHandle_t wfx_mutex = NULL; - -StaticSemaphore_t xWfxMutexBuffer; - -struct -{ - uint32_t wf200_firmware_download_progress; - int wf200_initialized; - uint8_t waited_event_id; - uint8_t posted_event_id; -} host_context; - -#ifdef SL_WFX_USE_SDIO -#ifdef SLEEP_ENABLED -sl_status_t sl_wfx_host_enable_sdio(void); -sl_status_t sl_wfx_host_disable_sdio(void); -#endif -#endif - -#ifdef SL_WFX_USE_SPI -#ifdef SLEEP_ENABLED -sl_status_t sl_wfx_host_enable_spi(void); -sl_status_t sl_wfx_host_disable_spi(void); -#endif -#endif - -/**************************************************************************** - * @fn sl_status_t wfx_soft_init(void) - * @brief - * WFX FMAC driver host interface initialization - * @param[in] None - * @returns Returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t wfx_soft_init(void) -{ - SILABS_LOG("WF200:Soft Init"); - if ((wfx_event_Q = xQueueCreateStatic(SL_WFX_EVENT_LIST_SIZE, sizeof(uint8_t), sWfxEventQueueBuffer, &sWfxEventQueueStruct)) == - NULL) - { - return SL_STATUS_FAIL; - } - - if ((wfx_wakeup_sem = xSemaphoreCreateBinaryStatic(&xWfxWakeupSemaBuffer)) == NULL) - { - return SL_STATUS_FAIL; - } - - if ((wfx_mutex = xSemaphoreCreateMutexStatic(&xWfxMutexBuffer)) == NULL) - { - return SL_STATUS_FAIL; - } - - return SL_STATUS_OK; -} -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_init(void) - * @brief - * Notify driver init function - * @param[in] None - * @returns Returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_init(void) -{ - SILABS_LOG("WFX: Host Init"); - host_context.wf200_firmware_download_progress = 0; - host_context.wf200_initialized = 0; - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_get_firmware_data(const uint8_t **data, uint32_t data_size) - * @brief - * Get firmware data - * @param[in] data: - * @param[in] data_size: - * @returns Returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_get_firmware_data(const uint8_t ** data, uint32_t data_size) -{ - *data = &sl_wfx_firmware[host_context.wf200_firmware_download_progress]; - host_context.wf200_firmware_download_progress += data_size; - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_get_firmware_size(uint32_t *firmware_size) - * @brief - * Get firmware size - * @param[in] firmware_size: - * @returns Returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_get_firmware_size(uint32_t * firmware_size) -{ - *firmware_size = sizeof(sl_wfx_firmware); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_get_pds_data(const char **pds_data, uint16_t index) - * @brief - * Get PDS data - * @param[in] pds_data: - * @param[in] index: - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_get_pds_data(const char ** pds_data, uint16_t index) -{ - *pds_data = sl_wfx_pds[index]; - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_get_pds_size(uint16_t *pds_size) - * @brief - * Get PDS size - * @param[in] pds_size: - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_get_pds_size(uint16_t * pds_size) -{ - *pds_size = SL_WFX_ARRAY_COUNT(sl_wfx_pds); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_deinit(void) - * @brief - * Deinit host interface - * @param[in] None - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_deinit(void) -{ - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_allocate_buffer(void **buffer, sl_wfx_buffer_type_t type, uint32_t buffer_size) - * @brief - * Allocate buffer (Should allocate either Ethernet - from LWIP or Control) - TODO - * @param[in] buffer: - * @param[in] type: - * @param[in] buffer_size: - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_allocate_buffer(void ** buffer, sl_wfx_buffer_type_t type, uint32_t buffer_size) -{ - if ((*buffer = pvPortMalloc(buffer_size)) == (void *) 0) - { - return SL_STATUS_FAIL; - } - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_free_buffer(void *buffer, sl_wfx_buffer_type_t type) - * @brief - * Free host buffer (CHECK LWIP buffer) - * @param[in] buffer: - * @param[in] type: - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_free_buffer(void * buffer, sl_wfx_buffer_type_t type) -{ - vPortFree(buffer); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_hold_in_reset(void) - * @brief - * Set reset pin low - * @param[in] None - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_hold_in_reset(void) -{ - GPIO_PinOutClear(SL_WFX_HOST_PINOUT_RESET_PORT, SL_WFX_HOST_PINOUT_RESET_PIN); - host_context.wf200_initialized = 0; - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_set_wake_up_pin(uint8_t state) - * @brief - * Set wakeup pin status - * @param[in] state: - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_set_wake_up_pin(uint8_t state) -{ - CORE_DECLARE_IRQ_STATE; - - CORE_ENTER_ATOMIC(); - if (state > PINOUT_CLEAR_STATUS) - { -#ifdef SLEEP_ENABLED -#ifdef SL_WFX_USE_SDIO - sl_wfx_host_enable_sdio(); -#endif -#ifdef SL_WFX_USE_SPI - sl_wfx_host_enable_spi(); -#endif -#endif - GPIO_PinOutSet(SL_WFX_HOST_PINOUT_WUP_PORT, SL_WFX_HOST_PINOUT_WUP_PIN); - } - else - { - GPIO_PinOutClear(SL_WFX_HOST_PINOUT_WUP_PORT, SL_WFX_HOST_PINOUT_WUP_PIN); -#ifdef SLEEP_ENABLED -#ifdef SL_WFX_USE_SDIO - sl_wfx_host_disable_sdio(); -#endif -#ifdef SL_WFX_USE_SPI - sl_wfx_host_disable_spi(); -#endif -#endif - } - CORE_EXIT_ATOMIC(); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_reset_chip(void) - * @brief - * reset the host chip - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_reset_chip(void) -{ - // Pull it low for at least 1 ms to issue a reset sequence - GPIO_PinOutClear(SL_WFX_HOST_PINOUT_RESET_PORT, SL_WFX_HOST_PINOUT_RESET_PIN); - - // Delay for 10ms - vTaskDelay(pdMS_TO_TICKS(10)); - - // Hold pin high to get chip out of reset - GPIO_PinOutSet(SL_WFX_HOST_PINOUT_RESET_PORT, SL_WFX_HOST_PINOUT_RESET_PIN); - - // Delay for 3ms - vTaskDelay(pdMS_TO_TICKS(3)); - - host_context.wf200_initialized = 0; - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_wait_for_wake_up(void) - * @brief - * wait for the host wake up - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_wait_for_wake_up(void) -{ - xSemaphoreTake(wfx_wakeup_sem, TICKS_TO_WAIT_0); - xSemaphoreTake(wfx_wakeup_sem, TICKS_TO_WAIT_3 / portTICK_PERIOD_MS); - - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_wait(uint32_t wait_time) - * @brief - * wait for the host - * @param[in] wait_time: - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ - -sl_status_t sl_wfx_host_wait(uint32_t wait_time) -{ - uint32_t ticks = pdMS_TO_TICKS(wait_time); - vTaskDelay(ticks ? ticks : 10); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_setup_waited_event(uint8_t event_id) - * @brief - * Called when the driver needs to setup the waited event - * @param[in] event_id: - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_FAIL otherwise - *****************************************************************************/ - -sl_status_t sl_wfx_host_setup_waited_event(uint8_t event_id) -{ - host_context.waited_event_id = event_id; - host_context.posted_event_id = 0; - - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn uint8_t sl_wfx_host_get_waited_event(void) - * @brief - * Called when the driver get waited event - * @returns returns host_context.waited_event_id - *****************************************************************************/ - -uint8_t sl_wfx_host_get_waited_event(void) -{ - return host_context.waited_event_id; -} - -/****************************************************************************** - * @fn sl_status_t sl_wfx_host_wait_for_confirmation(uint8_t confirmation_id, uint32_t timeout, void **event_payload_out) - * @brief - * wait for the host confirmation - * @param[in] confirmation_id: - * @param[in] timeout: - * @param[in] event_payload_out: - * @returns Returns SL_STATUS_OK if successful, - * Timeout, SL_STATUS_TIMEOUT otherwise - *****************************************************************************/ - -sl_status_t sl_wfx_host_wait_for_confirmation(uint8_t confirmation_id, uint32_t timeout, void ** event_payload_out) -{ - uint8_t posted_event_id; - for (uint32_t i = 0; i < timeout; i++) - { - /* Wait for an event posted by the function sl_wfx_host_post_event() */ - if (xQueueReceive(wfx_event_Q, &posted_event_id, TICKS_TO_WAIT_1) == pdTRUE) - { - /* Once a message is received, check if it is the expected ID */ - if (confirmation_id == posted_event_id) - { - /* Pass the confirmation reply and return*/ - if (event_payload_out != NULL) - { - *event_payload_out = sl_wfx_context->event_payload_buffer; - } - return SL_STATUS_OK; - } - } - } - /* The wait for the confirmation timed out, return */ - return SL_STATUS_TIMEOUT; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_lock(void) - * @brief - * Called when the driver needs to lock its access - * @returns Returns SL_STATUS_OK if successful, - *SL_STATUS_TIMEOUT otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_lock(void) -{ - - sl_status_t status = SL_STATUS_OK; - - if (xSemaphoreTake(wfx_mutex, TICKS_TO_WAIT_500) != pdTRUE) - { - SILABS_LOG("*ERR*Wi-Fi driver mutex timo"); - status = SL_STATUS_TIMEOUT; - } - - return status; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_unlock(void) - * @brief - * Called when the driver needs to unlock its access - * @returns Returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_unlock(void) -{ - xSemaphoreGive(wfx_mutex); - - return SL_STATUS_OK; -} - -/****************************************************************************** - * @fn sl_status_t sl_wfx_host_post_event(sl_wfx_generic_message_t *event_payload) - * @brief - * Called when the driver needs to post an event - * @param[in] event_payload: - * @returns Returns status - *****************************************************************************/ -sl_status_t sl_wfx_host_post_event(sl_wfx_generic_message_t * event_payload) -{ - sl_status_t status; - - /* Forward the message to the application */ - status = sl_wfx_host_process_event(event_payload); - - if (host_context.waited_event_id == event_payload->header.id) - { - if (event_payload->header.length < SL_WFX_EVENT_MAX_SIZE) - { - /* Post the event in the queue */ - memcpy(sl_wfx_context->event_payload_buffer, (void *) event_payload, event_payload->header.length); - host_context.posted_event_id = event_payload->header.id; - xQueueOverwrite(wfx_event_Q, (void *) &event_payload->header.id); - } - } - - return status; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_transmit_frame(void *frame, uint32_t frame_len) - * @brief - * Called when the driver needs to transmit a frame - * @param[in] frame: - * @param[in] frame_len: - * @returns returns sl_wfx_data_write(frame, frame_len) - *****************************************************************************/ -sl_status_t sl_wfx_host_transmit_frame(void * frame, uint32_t frame_len) -{ - return sl_wfx_data_write(frame, frame_len); -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_sleep_grant(sl_wfx_host_bus_transfer_type_t type, - sl_wfx_register_address_t address, - uint32_t length) - * @brief - * Called when the driver is considering putting the - * WFx in sleep mode - * @param[in] type: - * @param[in] address: - * @param[in] length: - * @returns SL_WIFI_SLEEP_GRANTED to let the WFx go to - *sleep, SL_WIFI_SLEEP_NOT_GRANTED otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_sleep_grant(sl_wfx_host_bus_transfer_type_t type, sl_wfx_register_address_t address, uint32_t length) -{ - (void) (type); - (void) (address); - (void) (length); - - return SL_STATUS_WIFI_SLEEP_GRANTED; -} - -#if SL_WFX_DEBUG_MASK -/**************************************************************************** - * @fn void sl_wfx_host_log(const char *str, ...) - * @brief - * Host debug output - * @param[in] str: string - * @return None - *****************************************************************************/ -void sl_wfx_host_log(const char * str, ...) -{ - va_list args; - va_start(args, str); - vprintf(str, args); - va_end(args); -} -#endif -#ifndef PW_RPC_ENABLED -/* Place holder - This is just to handle UART interrupts - * The "otThread tasks handles it. WiFi does not need it yet - * I don't care for it. I should really have the thread - * shut it off - */ -#if !CHIP_ENABLE_OPENTHREAD -/**************************************************************************** - * @fn void otSysEventSignalPending(void) - * @brief - * system event signal pending - * @param[in] None - * @return None - *****************************************************************************/ -void otSysEventSignalPending(void) -{ - // BaseType_t yieldRequired = ThreadStackMgrImpl().SignalThreadActivityPendingFromISR(); - SILABS_LOG("*ERR*UART intr - NOT Handled"); - portYIELD_FROM_ISR(pdFALSE); -} -#endif /* !CHIP_ENABLE_OPENTHREAD */ -#endif /* PW_RPC_ENABLED */ diff --git a/src/platform/BUILD.gn b/src/platform/BUILD.gn index c02b331b49af33..92687ba2969a0a 100644 --- a/src/platform/BUILD.gn +++ b/src/platform/BUILD.gn @@ -164,6 +164,11 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { "CHIP_DEVICE_LAYER_TARGET_EFR32=1", "CHIP_DEVICE_LAYER_TARGET=silabs", ] + } else if (chip_device_platform == "SiWx917") { + defines += [ + "CHIP_DEVICE_LAYER_TARGET_EFR32=1", + "CHIP_DEVICE_LAYER_TARGET=silabs", + ] } else if (chip_device_platform == "esp32") { defines += [ "CHIP_DEVICE_LAYER_TARGET_ESP32=1", @@ -410,6 +415,8 @@ if (chip_device_platform != "none") { _platform_target = "Darwin" } else if (chip_device_platform == "efr32") { _platform_target = "silabs/EFR32" + } else if (chip_device_platform == "SiWx917") { + _platform_target = "silabs/SiWx917" } else if (chip_device_platform == "esp32") { _platform_target = "ESP32" } else if (chip_device_platform == "k32w0") { diff --git a/src/platform/device.gni b/src/platform/device.gni index 601d21ef2ff2f1..c0ad4bb5daa3a7 100755 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -113,6 +113,8 @@ if (chip_device_platform == "cc13x2_26x2") { _chip_device_layer = "Darwin" } else if (chip_device_platform == "efr32") { _chip_device_layer = "silabs" +} else if (chip_device_platform == "SiWx917") { + _chip_device_layer = "silabs" } else if (chip_device_platform == "esp32") { _chip_device_layer = "ESP32" } else if (chip_device_platform == "linux") { @@ -212,5 +214,5 @@ assert( chip_device_platform == "webos" || chip_device_platform == "bl602" || chip_device_platform == "mw320" || chip_device_platform == "zephyr" || chip_device_platform == "beken" || chip_device_platform == "bl702" || - chip_device_platform == "mt793x", + chip_device_platform == "mt793x" || chip_device_platform == "SiWx917", "Please select a valid value for chip_device_platform") diff --git a/src/platform/silabs/BLEManagerImpl.h b/src/platform/silabs/BLEManagerImpl.h index 0f1d478f179b61..e0a04e5f356e7e 100644 --- a/src/platform/silabs/BLEManagerImpl.h +++ b/src/platform/silabs/BLEManagerImpl.h @@ -26,10 +26,22 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include "FreeRTOS.h" +#include "timers.h" +#ifdef RS91X_BLE_ENABLE +#ifdef __cplusplus +extern "C" { +#endif +#include +#include +#include +#ifdef __cplusplus +} +#endif +#else #include "gatt_db.h" #include "sl_bgapi.h" #include "sl_bt_api.h" -#include "timers.h" +#endif // RS91X_BLE_ENABLE namespace chip { namespace DeviceLayer { @@ -45,6 +57,16 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla public: void HandleBootEvent(void); + +#ifdef RS91X_BLE_ENABLE + void HandleConnectEvent(void); + void HandleConnectionCloseEvent(uint16_t reason); + void HandleWriteEvent(rsi_ble_event_write_t evt); + void UpdateMtu(rsi_ble_event_mtu_t evt); + void HandleTxConfirmationEvent(BLE_CONNECTION_OBJECT conId); + void HandleTXCharCCCDWrite(rsi_ble_event_write_t * evt); + void HandleSoftTimerEvent(void); +#else void HandleConnectEvent(volatile sl_bt_msg_t * evt); void HandleConnectionCloseEvent(volatile sl_bt_msg_t * evt); void HandleWriteEvent(volatile sl_bt_msg_t * evt); @@ -53,9 +75,17 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla void HandleTXCharCCCDWrite(volatile sl_bt_msg_t * evt); void HandleSoftTimerEvent(volatile sl_bt_msg_t * evt); +#endif // RS91X_BLE_ENABLE + +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING +#ifdef RS91X_BLE_ENABLE + static void HandleC3ReadRequest(void); +#else #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING static void HandleC3ReadRequest(volatile sl_bt_msg_t * evt); #endif +#endif +#endif private: // Allow the BLEManager interface class to delegate method calls to @@ -125,7 +155,9 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla struct CHIPoBLEConState { +#ifndef RS91X_BLE_ENABLE bd_addr address; +#endif uint16_t mtu : 10; uint16_t allocated : 1; uint16_t subscribed : 1; @@ -153,7 +185,12 @@ class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePla #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING CHIP_ERROR EncodeAdditionalDataTlv(); #endif + +#ifdef RS91X_BLE_ENABLE + void HandleRXCharWrite(rsi_ble_event_write_t * evt); +#else void HandleRXCharWrite(volatile sl_bt_msg_t * evt); +#endif bool RemoveConnection(uint8_t connectionHandle); void AddConnection(uint8_t connectionHandle, uint8_t bondingHandle); void StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs); diff --git a/src/platform/silabs/CHIPMem-Platform.cpp b/src/platform/silabs/CHIPMem-Platform.cpp index 4f8b938f5d26ec..a826ebe856ca1e 100644 --- a/src/platform/silabs/CHIPMem-Platform.cpp +++ b/src/platform/silabs/CHIPMem-Platform.cpp @@ -150,7 +150,12 @@ bool MemoryInternalCheckPointer(const void * p, size_t min_size) } // namespace Platform } // namespace chip +#ifdef BRD4325A +extern "C" void memMonitoringTrackAlloc(void * ptr, size_t size) {} +extern "C" void memMonitoringTrackFree(void * ptr, size_t size) {} +#else extern "C" __WEAK void memMonitoringTrackAlloc(void * ptr, size_t size) {} extern "C" __WEAK void memMonitoringTrackFree(void * ptr, size_t size) {} +#endif // BRD4325A #endif // CHIP_CONFIG_MEMORY_MGMT_PLATFORM diff --git a/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp b/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp index 7bb0741b83d1a6..effee8c67d71a5 100644 --- a/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp +++ b/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp @@ -262,6 +262,7 @@ void ConnectivityManagerImpl::DriveStationState() // If the WiFi station interface is no longer enabled, or no longer provisioned, // disconnect the station from the AP, unless the WiFi station mode is currently // under application control. +#ifndef CHIP_ONNETWORK_PAIRING if (mWiFiStationMode != kWiFiStationMode_ApplicationControlled && (mWiFiStationMode != kWiFiStationMode_Enabled || !IsWiFiStationProvisioned())) { @@ -275,6 +276,7 @@ void ConnectivityManagerImpl::DriveStationState() ChangeWiFiStationState(kWiFiStationState_Disconnecting); } +#endif } // Otherwise the station interface is NOT connected to an AP, so... else diff --git a/src/platform/silabs/SiWx917/BLEManagerImpl.cpp b/src/platform/silabs/SiWx917/BLEManagerImpl.cpp index a76f26c6df6b20..6563f4b5b2e790 100644 --- a/src/platform/silabs/SiWx917/BLEManagerImpl.cpp +++ b/src/platform/silabs/SiWx917/BLEManagerImpl.cpp @@ -26,33 +26,113 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include "sl_component_catalog.h" - #include +#define RSI_BLE_ENABLE 1 -#include "FreeRTOS.h" -#include "rail.h" +//#include "rail.h" extern "C" { -#include "sl_bluetooth.h" -} -#include "sl_bt_api.h" -#include "sl_bt_stack_config.h" -#include "sl_bt_stack_init.h" +#include "FreeRTOS.h" +#include "event_groups.h" +#include "task.h" #include "timers.h" +#include "wfx_host_events.h" +#include "wfx_rsi.h" +#include "wfx_sl_ble_init.h" +#include +#include +#include +} #include #include #include #include #include -#include +#include #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING #include #endif +// static int32_t handleTxConfirmationFlag = 0; +extern uint16_t rsi_ble_measurement_hndl; +extern rsi_ble_event_conn_status_t conn_event_to_app; +extern sl_wfx_msg_t event_msg; + +// StaticTask_t busInitTaskStruct; + +/* wfxRsi Task will use as its stack */ +// StackType_t wfxRsiInitTaskStack[WFX_RSI_TASK_SZ] = { 0 }; + using namespace ::chip; using namespace ::chip::Ble; +void rsi_ble_event_handling_task(void) +{ + int32_t event_id; + + // int32_t event_id; + WFX_RSI_LOG("StartAdvertising"); + // chip::DeviceLayer::Internal::BLEManagerImpl().StartAdvertising(); //TODO:: Called on after init of module + + // Application event map + while (1) + { + // checking for events list + event_id = rsi_ble_app_get_event(); + if (event_id == -1) + { + continue; + } + switch (event_id) + { + case RSI_BLE_CONN_EVENT: { + rsi_ble_app_clear_event(RSI_BLE_CONN_EVENT); + chip::DeviceLayer::Internal::BLEMgrImpl().HandleConnectEvent(); + WFX_RSI_LOG(" RSI_BLE : Module got connected"); + } + break; + case RSI_BLE_DISCONN_EVENT: { + // event invokes when disconnection was completed + WFX_RSI_LOG(" RSI_BLE : Module got Disconnected"); + chip::DeviceLayer::Internal::BLEMgrImpl().HandleConnectionCloseEvent(event_msg.reason); + // clear the served event + rsi_ble_app_clear_event(RSI_BLE_DISCONN_EVENT); + } + break; + case RSI_BLE_MTU_EVENT: { + // event invokes when write/notification events received + WFX_RSI_LOG("RSI_BLE:: RSI_BLE_MTU_EVENT"); + chip::DeviceLayer::Internal::BLEMgrImpl().UpdateMtu(event_msg.rsi_ble_mtu); + // clear the served event + rsi_ble_app_clear_event(RSI_BLE_MTU_EVENT); + } + break; + case RSI_BLE_GATT_WRITE_EVENT: { + // event invokes when write/notification events received + WFX_RSI_LOG("RSI_BLE : RSI_BLE_GATT_WRITE_EVENT"); + chip::DeviceLayer::Internal::BLEMgrImpl().HandleWriteEvent(event_msg.rsi_ble_write); + // clear the served event + rsi_ble_app_clear_event(RSI_BLE_GATT_WRITE_EVENT); + } + break; + case RSI_BLE_GATT_INDICATION_CONFIRMATION: { + WFX_RSI_LOG("RSI_BLE : indication confirmation"); + chip::DeviceLayer::Internal::BLEMgrImpl().HandleTxConfirmationEvent(1); + rsi_ble_app_clear_event(RSI_BLE_GATT_INDICATION_CONFIRMATION); + } + break; + + case RSI_BLE_RESP_ATT_VALUE: { + WFX_RSI_LOG("RSI_BLE : RESP_ATT confirmation"); + } + default: + break; + } + } + + WFX_RSI_LOG("%s END", __func__); +} + namespace chip { namespace DeviceLayer { namespace Internal { @@ -75,6 +155,7 @@ namespace { // Timer Frequency used. #define TIMER_CLK_FREQ ((uint32_t) 32768) + // Convert msec to timer ticks. #define TIMER_MS_2_TIMERTICK(ms) ((TIMER_CLK_FREQ * ms) / 1000) #define TIMER_S_2_TIMERTICK(s) (TIMER_CLK_FREQ * s) @@ -96,6 +177,8 @@ namespace { #define BLE_CONFIG_MIN_CE_LENGTH (0) // Leave to min value #define BLE_CONFIG_MAX_CE_LENGTH (0xFFFF) // Leave to max value +#define BLE__DEFAULT_TIMER_PERIOD 1 + TimerHandle_t sbleAdvTimeoutTimer; // FreeRTOS sw timer. const uint8_t UUID_CHIPoBLEService[] = { 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, @@ -113,21 +196,33 @@ BLEManagerImpl BLEManagerImpl::sInstance; CHIP_ERROR BLEManagerImpl::_Init() { CHIP_ERROR err; + ChipLogProgress(DeviceLayer, "%s Start ", __func__); + + // wfx_rsi.init_task = xTaskCreateStatic((TaskFunction_t) wfx_sl_module_init, "init_task", WFX_RSI_TASK_SZ, NULL, 1, + // wfxRsiInitTaskStack, &busInitTaskStruct); + + if (NULL == wfx_rsi.init_task) + { + WFX_RSI_LOG("%s: error: failed to create task.", __func__); + } // Initialize the CHIP BleLayer. err = BleLayer::Init(this, this, &DeviceLayer::SystemLayer()); SuccessOrExit(err); + return err; + + ble_rsi_task(); memset(mBleConnections, 0, sizeof(mBleConnections)); memset(mIndConfId, kUnusedIndex, sizeof(mIndConfId)); mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; // Create FreeRTOS sw timer for BLE timeouts and interval change. - sbleAdvTimeoutTimer = xTimerCreate("BleAdvTimer", // Just a text name, not used by the RTOS kernel - 1, // == default timer period (mS) - false, // no timer reload (==one-shot) - (void *) this, // init timer id = ble obj context - BleAdvTimeoutHandler // timer callback handler + sbleAdvTimeoutTimer = xTimerCreate("BleAdvTimer", // Just a text name, not used by the RTOS kernel + BLE__DEFAULT_TIMER_PERIOD, // == default timer period (mS) + false, // no timer reload (==one-shot) + (void *) this, // init timer id = ble obj context + BleAdvTimeoutHandler // timer callback handler ); mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); @@ -135,6 +230,7 @@ CHIP_ERROR BLEManagerImpl::_Init() PlatformMgr().ScheduleWork(DriveBLEState, 0); exit: + ChipLogProgress(DeviceLayer, "%s END ", __func__); return err; } @@ -198,14 +294,18 @@ CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) { + ChipLogProgress(DeviceLayer, "_SetDeviceName Started"); + rsi_bt_set_local_name((uint8_t *) RSI_BLE_DEV_NAME); if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported) { + ChipLogProgress(DeviceLayer, "_SetDeviceName CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE"); return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; } if (deviceName != NULL && deviceName[0] != 0) { if (strlen(deviceName) >= kMaxDeviceNameLength) { + ChipLogProgress(DeviceLayer, "_SetDeviceName CHIP_ERROR_INVALID_ARGUMENT"); return CHIP_ERROR_INVALID_ARGUMENT; } strcpy(mDeviceName, deviceName); @@ -218,6 +318,7 @@ CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) mDeviceName[0] = 0; } PlatformMgr().ScheduleWork(DriveBLEState, 0); + ChipLogProgress(DeviceLayer, "_SetDeviceName Ended"); return CHIP_NO_ERROR; } @@ -281,19 +382,19 @@ bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, cons bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) { CHIP_ERROR err = CHIP_NO_ERROR; - sl_status_t ret; + // int32_t ret; ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (con %u)", conId); - ret = sl_bt_connection_close(conId); - err = MapBLEError(ret); + // ret = rsi_ble_disconnect(1); + // err = MapBLEError(ret); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "sl_bt_connection_close() failed: %s", ErrorStr(err)); } - return (err == CHIP_NO_ERROR); + return true; //(err == CHIP_NO_ERROR); } uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const @@ -305,26 +406,13 @@ uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, PacketBufferHandle data) { - CHIP_ERROR err = CHIP_NO_ERROR; - CHIPoBLEConState * conState = GetConnectionState(conId); - sl_status_t ret; - uint16_t cId = (UUIDsMatch(&ChipUUID_CHIPoBLEChar_RX, charId) ? gattdb_CHIPoBLEChar_Rx : gattdb_CHIPoBLEChar_Tx); - uint8_t timerHandle = GetTimerHandle(conId, true); - - VerifyOrExit(((conState != NULL) && (conState->subscribed != 0)), err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(timerHandle != kMaxConnections, err = CHIP_ERROR_NO_MEMORY); - - // start timer for light indication confirmation. Long delay for spake2 indication - sl_bt_system_set_lazy_soft_timer(TIMER_S_2_TIMERTICK(6), 0, timerHandle, true); - - ret = sl_bt_gatt_server_send_indication(conId, cId, (data->DataLength()), data->Start()); - err = MapBLEError(ret); - -exit: - if (err != CHIP_NO_ERROR) + int32_t status = 0; + WFX_RSI_LOG("In send indication"); + status = rsi_ble_indicate_value(event_msg.resp_enh_conn.dev_addr, event_msg.rsi_ble_measurement_hndl, (data->DataLength()), + data->Start()); + if (status != RSI_SUCCESS) { - ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %s", ErrorStr(err)); - return false; + WFX_RSI_LOG("indication %d failed with error code %lx ", status); } return true; @@ -377,15 +465,20 @@ CHIP_ERROR BLEManagerImpl::MapBLEError(int bleErr) void BLEManagerImpl::DriveBLEState(void) { + + ChipLogProgress(DeviceLayer, "DriveBLEState starting"); CHIP_ERROR err = CHIP_NO_ERROR; // Check if BLE stack is initialized - VerifyOrExit(mFlags.Has(Flags::kEFRBLEStackInitialized), /* */); + // VerifyOrExit(mFlags.Has(Flags::kEFRBLEStackInitialized), /* */); + ChipLogProgress(DeviceLayer, "Start advertising if needed..."); // Start advertising if needed... if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled) && NumConnections() < kMaxConnections) { + + ChipLogProgress(DeviceLayer, "Start/re-start advertising if not already started, or if there is a pending change"); // Start/re-start advertising if not already started, or if there is a pending change // to the advertising configuration. if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kRestartAdvertising)) @@ -403,6 +496,7 @@ void BLEManagerImpl::DriveBLEState(void) } exit: + ChipLogProgress(DeviceLayer, "DriveBLEState End"); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); @@ -412,21 +506,24 @@ void BLEManagerImpl::DriveBLEState(void) CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) { - sl_status_t ret; + ChipBLEDeviceIdentificationInfo mDeviceIdInfo; CHIP_ERROR err; + int32_t result; uint8_t responseData[MAX_RESPONSE_DATA_LEN]; uint8_t advData[MAX_ADV_DATA_LEN]; uint32_t index = 0; uint32_t mDeviceNameLength = 0; uint8_t mDeviceIdInfoLength = 0; + err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo); + + ChipLogProgress(DeviceLayer, "ConfigureAdvertisingData start"); VerifyOrExit((kMaxDeviceNameLength + 1) < UINT8_MAX, err = CHIP_ERROR_INVALID_ARGUMENT); memset(responseData, 0, MAX_RESPONSE_DATA_LEN); memset(advData, 0, MAX_ADV_DATA_LEN); - err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo); SuccessOrExit(err); if (!mFlags.Has(Flags::kDeviceNameSet)) @@ -457,154 +554,125 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) advData[index++] = CHIP_ADV_DATA_TYPE_SERVICE_DATA; // AD type : Service Data advData[index++] = ShortUUID_CHIPoBLEService[0]; // AD value advData[index++] = ShortUUID_CHIPoBLEService[1]; - memcpy(&advData[index], (void *) &mDeviceIdInfo, mDeviceIdInfoLength); // AD value - index += mDeviceIdInfoLength; -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - ReturnErrorOnFailure(EncodeAdditionalDataTlv()); -#endif + // TODO:: replace the hardcoded values by calling the GetBLEDeviceIdentificationInfo + advData[index++] = 0; // OpCode + advData[index++] = 0; // DeviceDiscriminatorAndAdvVersion [] + advData[index++] = 15; // DeviceDiscriminatorAndAdvVersion [] + advData[index++] = 241; // DeviceVendorId [] + advData[index++] = 255; // DeviceVendorId [] + advData[index++] = 5; // DeviceProductId[] + advData[index++] = 128; // DeviceProductId[] + advData[index++] = 0; // AdditionalDataFlag - if (0xff != advertising_set_handle) - { - sl_bt_advertiser_delete_set(advertising_set_handle); - advertising_set_handle = 0xff; - } + //! prepare advertise data //local/device name + advData[index++] = strlen(RSI_BLE_DEV_NAME) + 1; + advData[index++] = 9; - ret = sl_bt_advertiser_create_set(&advertising_set_handle); - if (ret != SL_STATUS_OK) - { - err = MapBLEError(ret); - ChipLogError(DeviceLayer, "sl_bt_advertiser_create_set() failed: %s", ErrorStr(err)); - ExitNow(); - } + memcpy(&advData[index], RSI_BLE_DEV_NAME, strlen(RSI_BLE_DEV_NAME)); // AD value + index += strlen(RSI_BLE_DEV_NAME); - ret = sl_bt_legacy_advertiser_set_data(advertising_set_handle, sl_bt_advertiser_advertising_data_packet, index, - (uint8_t *) advData); +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + ReturnErrorOnFailure(EncodeAdditionalDataTlv()); +#endif - if (ret != SL_STATUS_OK) + result = rsi_ble_set_advertise_data(advData, index); + if (result != SL_STATUS_OK) { - err = MapBLEError(ret); - ChipLogError(DeviceLayer, "sl_bt_legacy_advertiser_set_data() - Advertising Data failed: %s", ErrorStr(err)); + err = MapBLEError(result); + ChipLogError(DeviceLayer, "rsi_ble_set_advertise_data() failed: %ld", result); ExitNow(); } - - index = 0; - - responseData[index++] = CHIP_ADV_SHORT_UUID_LEN + 1; // AD length - responseData[index++] = CHIP_ADV_DATA_TYPE_UUID; // AD type : uuid - responseData[index++] = ShortUUID_CHIPoBLEService[0]; // AD value - responseData[index++] = ShortUUID_CHIPoBLEService[1]; - - responseData[index++] = static_cast(mDeviceNameLength + 1); // length - responseData[index++] = CHIP_ADV_DATA_TYPE_NAME; // AD type : name - memcpy(&responseData[index], mDeviceName, mDeviceNameLength); // AD value - index += mDeviceNameLength; - - ret = sl_bt_legacy_advertiser_set_data(advertising_set_handle, sl_bt_advertiser_scan_response_packet, index, - (uint8_t *) responseData); - - if (ret != SL_STATUS_OK) + else { - err = MapBLEError(ret); - ChipLogError(DeviceLayer, "sl_bt_legacy_advertiser_set_data() - Scan Response failed: %s", ErrorStr(err)); - ExitNow(); + ChipLogError(DeviceLayer, "rsi_ble_set_advertise_data() success: %ld", result); } - err = MapBLEError(ret); + err = MapBLEError(result); + ChipLogProgress(DeviceLayer, "ConfigureAdvertisingData End"); exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR BLEManagerImpl::StartAdvertising(void) { CHIP_ERROR err; - sl_status_t ret; - uint32_t interval_min; - uint32_t interval_max; - uint16_t numConnectionss = NumConnections(); - uint8_t connectableAdv = - (numConnectionss < kMaxConnections) ? sl_bt_advertiser_connectable_scannable : sl_bt_advertiser_scannable_non_connectable; + int32_t status = 0; + + ChipLogProgress(DeviceLayer, "StartAdvertising start"); // If already advertising, stop it, before changing values if (mFlags.Has(Flags::kAdvertising)) { - sl_bt_advertiser_stop(advertising_set_handle); + // sl_bt_advertiser_stop(advertising_set_handle); } else { ChipLogDetail(DeviceLayer, "Start BLE advertissement"); } - const uint8_t kResolvableRandomAddrType = 2; // Private resolvable random address type - bd_addr unusedBdAddr; // We can ignore this field when setting random address. - sl_bt_advertiser_set_random_address(advertising_set_handle, kResolvableRandomAddrType, unusedBdAddr, &unusedBdAddr); - (void) unusedBdAddr; + // bd_addr unusedBdAddr; // We can ignore this field when setting random address. + + // (void) unusedBdAddr; err = ConfigureAdvertisingData(); SuccessOrExit(err); mFlags.Clear(Flags::kRestartAdvertising); - if (mFlags.Has(Flags::kFastAdvertisingEnabled)) - { - interval_min = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MIN; - interval_max = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX; - } - else - { - interval_min = CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MIN; - interval_max = CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX; - } + sl_wfx_mac_address_t macaddr; + wfx_get_wifi_mac_addr(SL_WFX_STA_INTERFACE, &macaddr); - ret = sl_bt_advertiser_set_timing(advertising_set_handle, interval_min, interval_max, 0, 0); - err = MapBLEError(ret); - SuccessOrExit(err); - - sl_bt_advertiser_configure(advertising_set_handle, 1); - ret = sl_bt_legacy_advertiser_start(advertising_set_handle, connectableAdv); - - if (SL_STATUS_OK == ret) + //! Set local name + status = rsi_ble_start_advertising(); + if (status == RSI_SUCCESS) { + ChipLogProgress(DeviceLayer, "rsi_ble_start_advertising Success"); + if (mFlags.Has(Flags::kFastAdvertisingEnabled)) { StartBleAdvTimeoutTimer(CHIP_DEVICE_CONFIG_BLE_ADVERTISING_INTERVAL_CHANGE_TIME); } mFlags.Set(Flags::kAdvertising); } - - err = MapBLEError(ret); + else + { + ChipLogProgress(DeviceLayer, "rsi_ble_start_advertising Failed with status: %lx", status); + } exit: - return err; + ChipLogError(DeviceLayer, "StartAdvertising() End error: %s", ErrorStr(err)); + return CHIP_NO_ERROR; // err; } +// TODO:: Implementation need to be done. CHIP_ERROR BLEManagerImpl::StopAdvertising(void) { CHIP_ERROR err = CHIP_NO_ERROR; - sl_status_t ret; + // sl_status_t ret; if (mFlags.Has(Flags::kAdvertising)) { mFlags.Clear(Flags::kAdvertising).Clear(Flags::kRestartAdvertising); mFlags.Set(Flags::kFastAdvertisingEnabled, true); - ret = sl_bt_advertiser_stop(advertising_set_handle); - sl_bt_advertiser_delete_set(advertising_set_handle); + // ret = sl_bt_advertiser_stop(advertising_set_handle); + // sl_bt_advertiser_delete_set(advertising_set_handle); advertising_set_handle = 0xff; - err = MapBLEError(ret); - SuccessOrExit(err); + // err = MapBLEError(ret); + // SuccessOrExit(err); CancelBleAdvTimeoutTimer(); } -exit: + // exit: return err; } -void BLEManagerImpl::UpdateMtu(volatile sl_bt_msg_t * evt) +void BLEManagerImpl::UpdateMtu(rsi_ble_event_mtu_t evt) { - CHIPoBLEConState * bleConnState = GetConnectionState(evt->data.evt_gatt_mtu_exchanged.connection); + CHIPoBLEConState * bleConnState = GetConnectionState(event_msg.connectionHandle); if (bleConnState != NULL) { // bleConnState->MTU is a 10-bit field inside a uint16_t. We're @@ -616,9 +684,10 @@ void BLEManagerImpl::UpdateMtu(volatile sl_bt_msg_t * evt) // TODO: https://github.com/project-chip/connectedhomeip/issues/2569 // tracks making this safe with a check or explaining why no check // is needed. + ChipLogProgress(DeviceLayer, "DriveBLEState UpdateMtu %d", evt.mtu_size); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" - bleConnState->mtu = evt->data.evt_gatt_mtu_exchanged.mtu; + bleConnState->mtu = evt.mtu_size; #pragma GCC diagnostic pop ; } @@ -630,23 +699,18 @@ void BLEManagerImpl::HandleBootEvent(void) PlatformMgr().ScheduleWork(DriveBLEState, 0); } -void BLEManagerImpl::HandleConnectEvent(volatile sl_bt_msg_t * evt) +void BLEManagerImpl::HandleConnectEvent(void) { - sl_bt_evt_connection_opened_t * conn_evt = (sl_bt_evt_connection_opened_t *) &(evt->data); - uint8_t connHandle = conn_evt->connection; - uint8_t bondingHandle = conn_evt->bonding; - - ChipLogProgress(DeviceLayer, "Connect Event for handle : %d", connHandle); - - AddConnection(connHandle, bondingHandle); + ChipLogProgress(DeviceLayer, "Connect Event for handle : %d", event_msg.connectionHandle); + AddConnection(event_msg.connectionHandle, event_msg.bondingHandle); PlatformMgr().ScheduleWork(DriveBLEState, 0); } -void BLEManagerImpl::HandleConnectionCloseEvent(volatile sl_bt_msg_t * evt) +// TODO:: Implementation need to be done. +void BLEManagerImpl::HandleConnectionCloseEvent(uint16_t reason) { - sl_bt_evt_connection_closed_t * conn_evt = (sl_bt_evt_connection_closed_t *) &(evt->data); - uint8_t connHandle = conn_evt->connection; + uint8_t connHandle = 1; ChipLogProgress(DeviceLayer, "Disconnect Event for handle : %d", connHandle); @@ -656,24 +720,19 @@ void BLEManagerImpl::HandleConnectionCloseEvent(volatile sl_bt_msg_t * evt) event.Type = DeviceEventType::kCHIPoBLEConnectionError; event.CHIPoBLEConnectionError.ConId = connHandle; - switch (conn_evt->reason) - { - case SL_STATUS_BT_CTRL_REMOTE_USER_TERMINATED: - case SL_STATUS_BT_CTRL_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES: - case SL_STATUS_BT_CTRL_REMOTE_POWERING_OFF: - event.CHIPoBLEConnectionError.Reason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; - break; - - case SL_STATUS_BT_CTRL_CONNECTION_TERMINATED_BY_LOCAL_HOST: - event.CHIPoBLEConnectionError.Reason = BLE_ERROR_APP_CLOSED_CONNECTION; - break; - - default: - event.CHIPoBLEConnectionError.Reason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT; - break; - } + // switch (reason) + // { + // + // case RSI_REMOTE_DEV_TERMINATE_CONN: + // case RSI_BT_CTRL_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES: + // case RSI_BT_CTRL_REMOTE_POWERING_OFF: + // event.CHIPoBLEConnectionError.Reason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; + // break; + // default: + // event.CHIPoBLEConnectionError.Reason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT; + // } - ChipLogProgress(DeviceLayer, "BLE GATT connection closed (con %u, reason %u)", connHandle, conn_evt->reason); + // ChipLogProgress(DeviceLayer, "BLE GATT connection closed (con %u, reason %u)", connHandle, conn_evt->reason); PlatformMgr().PostEventOrDie(&event); @@ -685,84 +744,61 @@ void BLEManagerImpl::HandleConnectionCloseEvent(volatile sl_bt_msg_t * evt) } } -void BLEManagerImpl::HandleWriteEvent(volatile sl_bt_msg_t * evt) +void BLEManagerImpl::HandleWriteEvent(rsi_ble_event_write_t evt) { - uint16_t attribute = evt->data.evt_gatt_server_user_write_request.characteristic; + // RSI_BLE_WRITE_REQUEST_EVENT + ChipLogProgress(DeviceLayer, "Char Write Req, packet type %d", evt.pkt_type); + uint8_t attribute = (uint8_t) event_msg.rsi_ble_measurement_hndl; - ChipLogProgress(DeviceLayer, "Char Write Req, char : %d", attribute); + WFX_RSI_LOG("attribute = %d,rsi_ble_measurement_hndl = %d", attribute, event_msg.rsi_ble_measurement_hndl); - if (gattdb_CHIPoBLEChar_Rx == attribute) + if (evt.handle[0] == (uint8_t) event_msg.rsi_ble_gatt_server_client_config_hndl) // TODO:: compare the handle exactly { - HandleRXCharWrite(evt); + WFX_RSI_LOG("Inside HandleTXCharCCCDWrite "); + HandleTXCharCCCDWrite(&evt); + } + else + { + HandleRXCharWrite(&evt); } } -void BLEManagerImpl::HandleTXCharCCCDWrite(volatile sl_bt_msg_t * evt) +void BLEManagerImpl::HandleTXCharCCCDWrite(rsi_ble_event_write_t * evt) { CHIP_ERROR err = CHIP_NO_ERROR; - CHIPoBLEConState * bleConnState; - bool isIndicationEnabled = false; ChipDeviceEvent event; - - bleConnState = GetConnectionState(evt->data.evt_gatt_server_user_write_request.connection); - VerifyOrExit(bleConnState != NULL, err = CHIP_ERROR_NO_MEMORY); - - // Determine if the client is enabling or disabling notification/indication. - isIndicationEnabled = (evt->data.evt_gatt_server_characteristic_status.client_config_flags == sl_bt_gatt_indication); - - ChipLogProgress(DeviceLayer, "HandleTXcharCCCDWrite - Config Flags value : %d", - evt->data.evt_gatt_server_characteristic_status.client_config_flags); - ChipLogProgress(DeviceLayer, "CHIPoBLE %s received", isIndicationEnabled ? "subscribe" : "unsubscribe"); - - if (isIndicationEnabled) - { - // If indications are not already enabled for the connection... - if (!bleConnState->subscribed) - { - bleConnState->subscribed = 1; - // Post an event to the CHIP queue to process either a CHIPoBLE Subscribe or Unsubscribe based on - // whether the client is enabling or disabling indications. - { - event.Type = DeviceEventType::kCHIPoBLESubscribe; - event.CHIPoBLESubscribe.ConId = evt->data.evt_gatt_server_user_write_request.connection; - err = PlatformMgr().PostEvent(&event); - } - } - } - else + // whether the client is enabling or disabling indications. { - bleConnState->subscribed = 0; - event.Type = DeviceEventType::kCHIPoBLEUnsubscribe; - event.CHIPoBLESubscribe.ConId = evt->data.evt_gatt_server_user_write_request.connection; + event.Type = DeviceEventType::kCHIPoBLESubscribe; + event.CHIPoBLESubscribe.ConId = 1; err = PlatformMgr().PostEvent(&event); } - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "HandleTXCharCCCDWrite() failed: %s", ErrorStr(err)); - } } -void BLEManagerImpl::HandleRXCharWrite(volatile sl_bt_msg_t * evt) +void BLEManagerImpl::HandleRXCharWrite(rsi_ble_event_write_t * evt) { + uint8_t conId = 1; CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferHandle buf; - uint16_t writeLen = evt->data.evt_gatt_server_user_write_request.value.len; - uint8_t * data = (uint8_t *) evt->data.evt_gatt_server_user_write_request.value.data; + uint16_t writeLen = evt->length; + uint8_t * data = (uint8_t *) evt->att_value; + + for (int i = 0; i < evt->length; i++) + { + ChipLogDetail(DeviceLayer, "HandleRXCharWrite value : %d", evt->att_value[i]); + } // Copy the data to a packet buffer. buf = System::PacketBufferHandle::NewWithData(data, writeLen, 0, 0); VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY); - ChipLogDetail(DeviceLayer, "Write request/command received for CHIPoBLE RX characteristic (con %u, len %u)", - evt->data.evt_gatt_server_user_write_request.connection, buf->DataLength()); + ChipLogDetail(DeviceLayer, "Write request/command received for CHIPoBLE RX characteristic ( len %d)", writeLen); // Post an event to the CHIP queue to deliver the data into the CHIP stack. { ChipDeviceEvent event; event.Type = DeviceEventType::kCHIPoBLEWriteReceived; - event.CHIPoBLEWriteReceived.ConId = evt->data.evt_gatt_server_user_write_request.connection; + event.CHIPoBLEWriteReceived.ConId = conId; event.CHIPoBLEWriteReceived.Data = std::move(buf).UnsafeRelease(); err = PlatformMgr().PostEvent(&event); } @@ -777,36 +813,38 @@ void BLEManagerImpl::HandleRXCharWrite(volatile sl_bt_msg_t * evt) void BLEManagerImpl::HandleTxConfirmationEvent(BLE_CONNECTION_OBJECT conId) { ChipDeviceEvent event; - uint8_t timerHandle = sInstance.GetTimerHandle(conId, false); - - ChipLogProgress(DeviceLayer, "Tx Confirmation received"); - - // stop indication confirmation timer - if (timerHandle < kMaxConnections) - { - ChipLogProgress(DeviceLayer, " stop soft timer"); - sl_bt_system_set_lazy_soft_timer(0, 0, timerHandle, false); - } + // uint8_t timerHandle = sInstance.GetTimerHandle(conId, false); + // + // ChipLogProgress(DeviceLayer, "Tx Confirmation received"); + // + // // stop indication confirmation timer // TODO:: Need to find the proper repleacement + // if (timerHandle < kMaxConnections) + // { + // ChipLogProgress(DeviceLayer, " stop soft timer"); + // // sl_bt_system_set_lazy_soft_timer(0, 0, timerHandle, false); + // } event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm; event.CHIPoBLEIndicateConfirm.ConId = conId; PlatformMgr().PostEventOrDie(&event); } -void BLEManagerImpl::HandleSoftTimerEvent(volatile sl_bt_msg_t * evt) +// TODO:: Need to Implement +void BLEManagerImpl::HandleSoftTimerEvent(void) { + // BLE Manager starts soft timers with timer handles less than kMaxConnections // If we receive a callback for unknown timer handle ignore this. - if (evt->data.evt_system_soft_timer.handle < kMaxConnections) - { - ChipLogProgress(DeviceLayer, "BLEManagerImpl::HandleSoftTimerEvent CHIPOBLE_PROTOCOL_ABORT"); - ChipDeviceEvent event; - event.Type = DeviceEventType::kCHIPoBLEConnectionError; - event.CHIPoBLEConnectionError.ConId = mIndConfId[evt->data.evt_system_soft_timer.handle]; - sInstance.mIndConfId[evt->data.evt_system_soft_timer.handle] = kUnusedIndex; - event.CHIPoBLEConnectionError.Reason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT; - PlatformMgr().PostEventOrDie(&event); - } + // if (evt->data.evt_system_soft_timer.handle < kMaxConnections) + // { + // ChipLogProgress(DeviceLayer, "BLEManagerImpl::HandleSoftTimerEvent CHIPOBLE_PROTOCOL_ABORT"); + // ChipDeviceEvent event; + // event.Type = DeviceEventType::kCHIPoBLEConnectionError; + // event.CHIPoBLEConnectionError.ConId = mIndConfId[evt->data.evt_system_soft_timer.handle]; + // sInstance.mIndConfId[evt->data.evt_system_soft_timer.handle] = kUnusedIndex; + // event.CHIPoBLEConnectionError.Reason = BLE_ERROR_CHIPOBLE_PROTOCOL_ABORT; + // PlatformMgr().PostEventOrDie(&event); + // } } bool BLEManagerImpl::RemoveConnection(uint8_t connectionHandle) @@ -900,19 +938,20 @@ CHIP_ERROR BLEManagerImpl::EncodeAdditionalDataTlv() return err; } -void BLEManagerImpl::HandleC3ReadRequest(volatile sl_bt_msg_t * evt) +// TODO:: Need the +void BLEManagerImpl::HandleC3ReadRequest(void) { - sl_bt_evt_gatt_server_user_read_request_t * readReq = - (sl_bt_evt_gatt_server_user_read_request_t *) &(evt->data.evt_gatt_server_user_read_request); - ChipLogDetail(DeviceLayer, "Read request received for CHIPoBLEChar_C3 - opcode:%d", readReq->att_opcode); - sl_status_t ret = sl_bt_gatt_server_send_user_read_response(readReq->connection, readReq->characteristic, 0, - sInstance.c3AdditionalDataBufferHandle->DataLength(), - sInstance.c3AdditionalDataBufferHandle->Start(), nullptr); - - if (ret != SL_STATUS_OK) - { - ChipLogDetail(DeviceLayer, "Failed to send read response, err:%ld", ret); - } + // sl_bt_evt_gatt_server_user_read_request_t * readReq = + // (sl_bt_evt_gatt_server_user_read_request_t *) &(evt->data.evt_gatt_server_user_read_request); + // ChipLogDetail(DeviceLayer, "Read request received for CHIPoBLEChar_C3 - opcode:%d", readReq->att_opcode); + // sl_status_t ret = sl_bt_gatt_server_send_user_read_response(readReq->connection, readReq->characteristic, 0, + // sInstance.c3AdditionalDataBufferHandle->DataLength(), + // sInstance.c3AdditionalDataBufferHandle->Start(), nullptr); + + // if (ret != SL_STATUS_OK) + // { + // ChipLogDetail(DeviceLayer, "Failed to send read response, err:%ld", ret); + // } } #endif // CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING @@ -989,105 +1028,4 @@ void BLEManagerImpl::DriveBLEState(intptr_t arg) } // namespace DeviceLayer } // namespace chip -extern "C" void sl_bt_on_event(sl_bt_msg_t * evt) -{ - // As this is running in a separate thread, we need to block CHIP from operating, - // until the events are handled. - chip::DeviceLayer::PlatformMgr().LockChipStack(); - - // handle bluetooth events - switch (SL_BT_MSG_ID(evt->header)) - { - case sl_bt_evt_system_boot_id: { - ChipLogProgress(DeviceLayer, "Bluetooth stack booted: v%d.%d.%d-b%d", evt->data.evt_system_boot.major, - evt->data.evt_system_boot.minor, evt->data.evt_system_boot.patch, evt->data.evt_system_boot.build); - chip::DeviceLayer::Internal::BLEMgrImpl().HandleBootEvent(); - - RAIL_Version_t railVer; - RAIL_GetVersion(&railVer, true); - ChipLogProgress(DeviceLayer, "RAIL version:, v%d.%d.%d-b%d", railVer.major, railVer.minor, railVer.rev, railVer.build); - sl_bt_connection_set_default_parameters(BLE_CONFIG_MIN_INTERVAL, BLE_CONFIG_MAX_INTERVAL, BLE_CONFIG_LATENCY, - BLE_CONFIG_TIMEOUT, BLE_CONFIG_MIN_CE_LENGTH, BLE_CONFIG_MAX_CE_LENGTH); - } - break; - - case sl_bt_evt_connection_opened_id: { - chip::DeviceLayer::Internal::BLEMgrImpl().HandleConnectEvent(evt); - } - break; - case sl_bt_evt_connection_parameters_id: { - // ChipLogProgress(DeviceLayer, "Connection parameter ID received"); - } - break; - case sl_bt_evt_connection_phy_status_id: { - // ChipLogProgress(DeviceLayer, "PHY update procedure is completed"); - } - break; - case sl_bt_evt_connection_closed_id: { - chip::DeviceLayer::Internal::BLEMgrImpl().HandleConnectionCloseEvent(evt); - } - break; - - /* This event indicates that a remote GATT client is attempting to write a value of an - * attribute in to the local GATT database, where the attribute was defined in the GATT - * XML firmware configuration file to have type="user". */ - case sl_bt_evt_gatt_server_attribute_value_id: { - chip::DeviceLayer::Internal::BLEMgrImpl().HandleWriteEvent(evt); - } - break; - - case sl_bt_evt_gatt_mtu_exchanged_id: { - chip::DeviceLayer::Internal::BLEMgrImpl().UpdateMtu(evt); - } - break; - - // confirmation of indication received from remote GATT client - case sl_bt_evt_gatt_server_characteristic_status_id: { - sl_bt_gatt_server_characteristic_status_flag_t StatusFlags; - - StatusFlags = (sl_bt_gatt_server_characteristic_status_flag_t) evt->data.evt_gatt_server_characteristic_status.status_flags; - - if (sl_bt_gatt_server_confirmation == StatusFlags) - { - chip::DeviceLayer::Internal::BLEMgrImpl().HandleTxConfirmationEvent( - evt->data.evt_gatt_server_characteristic_status.connection); - } - else if ((evt->data.evt_gatt_server_characteristic_status.characteristic == gattdb_CHIPoBLEChar_Tx) && - (evt->data.evt_gatt_server_characteristic_status.status_flags == gatt_server_client_config)) - { - chip::DeviceLayer::Internal::BLEMgrImpl().HandleTXCharCCCDWrite(evt); - } - } - break; - - /* Software Timer event */ - case sl_bt_evt_system_soft_timer_id: { - chip::DeviceLayer::Internal::BLEMgrImpl().HandleSoftTimerEvent(evt); - } - break; - - case sl_bt_evt_gatt_server_user_read_request_id: { - ChipLogProgress(DeviceLayer, "GATT server user_read_request"); -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - if (evt->data.evt_gatt_server_user_read_request.characteristic == gattdb_CHIPoBLEChar_C3) - { - chip::DeviceLayer::Internal::BLEMgrImpl().HandleC3ReadRequest(evt); - } -#endif // CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - } - break; - - case sl_bt_evt_connection_remote_used_features_id: { - // ChipLogProgress(DeviceLayer, "link layer features supported by the remote device"); - } - break; - - default: - ChipLogProgress(DeviceLayer, "evt_UNKNOWN id = %08" PRIx32, SL_BT_MSG_ID(evt->header)); - break; - } - - chip::DeviceLayer::PlatformMgr().UnlockChipStack(); -} - #endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/silabs/SiWx917/BUILD.gn b/src/platform/silabs/SiWx917/BUILD.gn index b67c63c486a719..4026e1cd40c8f4 100644 --- a/src/platform/silabs/SiWx917/BUILD.gn +++ b/src/platform/silabs/SiWx917/BUILD.gn @@ -22,17 +22,13 @@ import("${chip_root}/src/crypto/crypto.gni") silabs_platform_dir = "${chip_root}/src/platform/silabs" -assert(chip_device_platform == "efr32") +assert(chip_device_platform == "SiWx917") if (chip_enable_openthread) { import("//build_overrides/openthread.gni") } -if (chip_crypto == "platform") { - import("//build_overrides/mbedtls.gni") -} - -static_library("EFR32") { +static_library("SiWx917") { sources = [ "${silabs_platform_dir}/BLEManagerImpl.h", "${silabs_platform_dir}/BlePlatformConfig.h", @@ -57,33 +53,21 @@ static_library("EFR32") { "ConfigurationManagerImpl.cpp", "KeyValueStoreManagerImpl.cpp", "PlatformManagerImpl.cpp", + "bluetooth/rsi_ble_config.h", + "bluetooth/wfx_sl_ble_init.c", + "bluetooth/wfx_sl_ble_init.h", ] + # TODO: OTA on CCP platform if (chip_enable_ota_requestor) { sources += [ - "OTAImageProcessorImpl.cpp", - "OTAImageProcessorImpl.h", + #"OTAImageProcessorImpl.cpp", + #"OTAImageProcessorImpl.h", ] } public_deps = [ "${chip_root}/src/platform:platform_base" ] - # Add platform crypto implementation - if (chip_crypto == "platform") { - sources += [ - "CHIPCryptoPALPsaEfr32.cpp", - "Efr32OpaqueKeypair.h", - "Efr32PsaOpaqueKeypair.cpp", - "Efr32PsaOperationalKeystore.cpp", - "Efr32PsaOperationalKeystore.h", - ] - - public_deps += [ - "${chip_root}/src/crypto", - "${mbedtls_root}:mbedtls", - ] - } - # Add pigweed KVS deps = [ "$dir_pw_kvs:crc16", @@ -93,27 +77,6 @@ static_library("EFR32") { "$dir_pw_checksum", "$dir_pw_kvs", ] - if (chip_enable_openthread) { - public_deps += [ "${chip_root}/third_party/openthread:openthread" ] - - deps += [ "${chip_root}/third_party/openthread:openthread_cli" ] - - sources += [ - "${silabs_platform_dir}/ThreadStackManagerImpl.h", - "../../OpenThread/OpenThreadUtils.cpp", - "ConnectivityManagerImpl.cpp", - "ThreadStackManagerImpl.cpp", - ] - - if (chip_mdns == "platform") { - sources += [ "../../OpenThread/DnssdImpl.cpp" ] - deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] - } - - public_configs = [ - "${chip_root}/src/lib/address_resolve:default_address_resolve_config", - ] - } if (chip_enable_wifi) { sources += [ diff --git a/src/platform/silabs/SiWx917/CHIPCryptoPALPsaEfr32.cpp b/src/platform/silabs/SiWx917/CHIPCryptoPALPsaEfr32.cpp deleted file mode 100644 index 13af1ae5a557b6..00000000000000 --- a/src/platform/silabs/SiWx917/CHIPCryptoPALPsaEfr32.cpp +++ /dev/null @@ -1,1879 +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. - */ - -/** - * @file - * PSA Crypto API based implementation of CHIP crypto primitives - * with Silicon Labs SDK modifications - */ - -#include - -#include - -// Include version header to get configuration information -#include - -#if !defined(MBEDTLS_PSA_CRYPTO_C) -#error "This implementation needs PSA Crypto" -#endif - -#if !defined(MBEDTLS_USE_PSA_CRYPTO) -#error "This implementation requires that PSA Crypto keys can be used for CSR generation" -#endif - -#include "psa/crypto.h" - -// Go straight for the driver wrappers for speed on plaintext keys -extern "C" { -#include "psa_crypto_core.h" -#include "psa_crypto_driver_wrappers.h" -} - -// Includes needed for SPAKE2+ ECP operations -#include -#include - -// Includes needed for certificate parsing -#if defined(MBEDTLS_X509_CRT_PARSE_C) -#include -#endif // defined(MBEDTLS_X509_CRT_PARSE_C) -#include -#include -#include - -#if defined(MBEDTLS_ERROR_C) -#include -#endif // defined(MBEDTLS_ERROR_C) - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace chip { -namespace Crypto { - -using chip::Platform::MemoryCalloc; -using chip::Platform::MemoryFree; - -#define MAX_ERROR_STR_LEN 128 -#define NUM_BYTES_IN_SHA256_HASH 32 - -// In mbedTLS 3.0.0 direct access to structure fields was replaced with using MBEDTLS_PRIVATE macro. -#if (MBEDTLS_VERSION_NUMBER >= 0x03000000) -#define CHIP_CRYPTO_PAL_PRIVATE(x) MBEDTLS_PRIVATE(x) -#else -#define CHIP_CRYPTO_PAL_PRIVATE(x) x -#endif - -#if (MBEDTLS_VERSION_NUMBER >= 0x03000000 && MBEDTLS_VERSION_NUMBER < 0x03010000) -#define CHIP_CRYPTO_PAL_PRIVATE_X509(x) MBEDTLS_PRIVATE(x) -#else -#define CHIP_CRYPTO_PAL_PRIVATE_X509(x) x -#endif - -static void _log_mbedTLS_error(int error_code) -{ - if (error_code != 0) - { -#if defined(MBEDTLS_ERROR_C) - char error_str[MAX_ERROR_STR_LEN]; - mbedtls_strerror(error_code, error_str, sizeof(error_str)); - ChipLogError(Crypto, "mbedTLS error: %s", error_str); -#else - // Error codes defined in 16-bit negative hex numbers. Ease lookup by printing likewise - ChipLogError(Crypto, "mbedTLS error: -0x%04X", -static_cast(error_code)); -#endif - } -} - -static void _log_PSA_error(psa_status_t status) -{ - if (status != 0) - { - // Error codes defined in 16-bit negative hex numbers. Ease lookup by printing likewise - ChipLogError(Crypto, "PSA error: %ld", status); - } -} - -static bool _isValidTagLength(size_t tag_length) -{ - if (tag_length == 8 || tag_length == 12 || tag_length == 16) - { - return true; - } - return false; -} - -/** - * @brief Compare two times - * - * @param t1 First time to compare - * @param t2 Second time to compare - * @return int 0 If both times are idential to the second, -1 if t1 < t2, 1 if t1 > t2. - */ -static int timeCompare(mbedtls_x509_time * t1, mbedtls_x509_time * t2) -{ - VerifyOrReturnValue(t1->year >= t2->year, -1); - VerifyOrReturnValue(t1->year <= t2->year, 1); - // Same year - VerifyOrReturnValue(t1->mon >= t2->mon, -1); - VerifyOrReturnValue(t1->mon <= t2->mon, 1); - // Same month - VerifyOrReturnValue(t1->day >= t2->day, -1); - VerifyOrReturnValue(t1->day <= t2->day, 1); - // Same day - VerifyOrReturnValue(t1->hour >= t2->hour, -1); - VerifyOrReturnValue(t1->hour <= t2->hour, 1); - // Same hour - VerifyOrReturnValue(t1->min >= t2->min, -1); - VerifyOrReturnValue(t1->min <= t2->min, 1); - // Same minute - VerifyOrReturnValue(t1->sec >= t2->sec, -1); - VerifyOrReturnValue(t1->sec <= t2->sec, 1); - // Same second - return 0; -} - -CHIP_ERROR AES_CCM_encrypt(const uint8_t * plaintext, size_t plaintext_length, const uint8_t * aad, size_t aad_length, - const uint8_t * key, size_t key_length, const uint8_t * nonce, size_t nonce_length, uint8_t * ciphertext, - uint8_t * tag, size_t tag_length) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; - size_t output_length = 0; - uint8_t * buffer = nullptr; - bool allocated_buffer = false; - - VerifyOrExit(_isValidTagLength(tag_length), error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(key_length == kAES_CCM128_Key_Length, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(key != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(key_length == kAES_CCM128_Key_Length, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(nonce != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(nonce_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(CanCastTo(nonce_length), error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(tag != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - - // If the ciphertext and tag outputs aren't a contiguous buffer, the PSA API requires buffer copying - if (Uint8::to_uchar(ciphertext) + plaintext_length != Uint8::to_uchar(tag)) - { - buffer = (uint8_t *) MemoryCalloc(1, plaintext_length + tag_length); - allocated_buffer = true; - VerifyOrExit(buffer != nullptr, error = CHIP_ERROR_NO_MEMORY); - } - - psa_crypto_init(); - - psa_set_key_type(&attr, PSA_KEY_TYPE_AES); - psa_set_key_bits(&attr, key_length * 8); - psa_set_key_algorithm(&attr, PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG(PSA_ALG_CCM, 8)); - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_ENCRYPT); - - status = psa_driver_wrapper_aead_encrypt( - &attr, Uint8::to_const_uchar(key), key_length, PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, tag_length), - Uint8::to_const_uchar(nonce), nonce_length, Uint8::to_const_uchar(aad), aad_length, Uint8::to_const_uchar(plaintext), - plaintext_length, allocated_buffer ? buffer : ciphertext, plaintext_length + tag_length, &output_length); - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(output_length == plaintext_length + tag_length, error = CHIP_ERROR_INTERNAL); - - if (allocated_buffer) - { - memcpy(Uint8::to_uchar(ciphertext), buffer, plaintext_length); - memcpy(Uint8::to_uchar(tag), buffer + plaintext_length, tag_length); - memset(buffer, 0, plaintext_length + tag_length); - } - -exit: - if (allocated_buffer) - { - MemoryFree(buffer); - } - psa_reset_key_attributes(&attr); - return error; -} - -CHIP_ERROR AES_CCM_decrypt(const uint8_t * ciphertext, size_t ciphertext_len, const uint8_t * aad, size_t aad_len, - const uint8_t * tag, size_t tag_length, const uint8_t * key, size_t key_length, const uint8_t * nonce, - size_t nonce_length, uint8_t * plaintext) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; - size_t output_length = 0; - uint8_t * buffer = nullptr; - bool allocated_buffer = false; - - VerifyOrExit(_isValidTagLength(tag_length), error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(tag != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(key != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(key_length == kAES_CCM128_Key_Length, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(nonce != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(nonce_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - - // If the ciphertext and tag outputs aren't a contiguous buffer, the PSA API requires buffer copying - if (Uint8::to_const_uchar(ciphertext) + ciphertext_len != Uint8::to_const_uchar(tag)) - { - buffer = (uint8_t *) MemoryCalloc(1, ciphertext_len + tag_length); - allocated_buffer = true; - VerifyOrExit(buffer != nullptr, error = CHIP_ERROR_NO_MEMORY); - } - - psa_crypto_init(); - - psa_set_key_type(&attr, PSA_KEY_TYPE_AES); - psa_set_key_bits(&attr, key_length * 8); - psa_set_key_algorithm(&attr, PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG(PSA_ALG_CCM, 8)); - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_DECRYPT); - - if (allocated_buffer) - { - memcpy(buffer, ciphertext, ciphertext_len); - memcpy(buffer + ciphertext_len, tag, tag_length); - } - - status = psa_driver_wrapper_aead_decrypt( - &attr, Uint8::to_const_uchar(key), key_length, PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, tag_length), - Uint8::to_const_uchar(nonce), nonce_length, Uint8::to_const_uchar(aad), aad_len, allocated_buffer ? buffer : ciphertext, - ciphertext_len + tag_length, plaintext, ciphertext_len, &output_length); - - if (allocated_buffer) - { - memset(buffer, 0, ciphertext_len + tag_length); - } - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(output_length == ciphertext_len, error = CHIP_ERROR_INTERNAL); -exit: - if (allocated_buffer) - { - MemoryFree(buffer); - } - - psa_reset_key_attributes(&attr); - return error; -} - -CHIP_ERROR Hash_SHA256(const uint8_t * data, const size_t data_length, uint8_t * out_buffer) -{ - size_t output_length = 0; - - psa_crypto_init(); - - const psa_status_t result = - psa_hash_compute(PSA_ALG_SHA_256, data, data_length, out_buffer, PSA_HASH_LENGTH(PSA_ALG_SHA_256), &output_length); - - VerifyOrReturnError(result == PSA_SUCCESS, CHIP_ERROR_INTERNAL); - VerifyOrReturnError(output_length == PSA_HASH_LENGTH(PSA_ALG_SHA_256), CHIP_ERROR_INTERNAL); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Hash_SHA1(const uint8_t * data, const size_t data_length, uint8_t * out_buffer) -{ - size_t output_length = 0; - - psa_crypto_init(); - - const psa_status_t result = - psa_hash_compute(PSA_ALG_SHA_1, data, data_length, out_buffer, PSA_HASH_LENGTH(PSA_ALG_SHA_1), &output_length); - - VerifyOrReturnError(result == PSA_SUCCESS, CHIP_ERROR_INTERNAL); - VerifyOrReturnError(output_length == PSA_HASH_LENGTH(PSA_ALG_SHA_1), CHIP_ERROR_INTERNAL); - - return CHIP_NO_ERROR; -} - -static_assert(kMAX_Hash_SHA256_Context_Size >= sizeof(psa_hash_operation_t), - "kMAX_Hash_SHA256_Context_Size is too small for the size of underlying psa_hash_operation_t"); - -static inline psa_hash_operation_t * to_inner_hash_sha256_context(HashSHA256OpaqueContext * context) -{ - return SafePointerCast(context); -} - -Hash_SHA256_stream::Hash_SHA256_stream(void) -{ - psa_hash_operation_t * context = to_inner_hash_sha256_context(&mContext); - const psa_hash_operation_t initial_context = PSA_HASH_OPERATION_INIT; - memcpy(context, &initial_context, sizeof(psa_hash_operation_t)); -} - -Hash_SHA256_stream::~Hash_SHA256_stream(void) -{ - psa_hash_operation_t * context = to_inner_hash_sha256_context(&mContext); - psa_hash_abort(context); - Clear(); -} - -CHIP_ERROR Hash_SHA256_stream::Begin(void) -{ - psa_crypto_init(); - - psa_hash_operation_t * context = to_inner_hash_sha256_context(&mContext); - *context = PSA_HASH_OPERATION_INIT; - const psa_status_t result = psa_hash_setup(context, PSA_ALG_SHA_256); - - VerifyOrReturnError(result == PSA_SUCCESS, CHIP_ERROR_INTERNAL); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Hash_SHA256_stream::AddData(const ByteSpan data) -{ - psa_hash_operation_t * context = to_inner_hash_sha256_context(&mContext); - const psa_status_t result = psa_hash_update(context, Uint8::to_const_uchar(data.data()), data.size()); - - VerifyOrReturnError(result == PSA_SUCCESS, CHIP_ERROR_INTERNAL); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Hash_SHA256_stream::GetDigest(MutableByteSpan & out_buffer) -{ - CHIP_ERROR result = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - size_t output_length = 0; - psa_hash_operation_t * context = to_inner_hash_sha256_context(&mContext); - - VerifyOrReturnError(out_buffer.size() >= kSHA256_Hash_Length, CHIP_ERROR_BUFFER_TOO_SMALL); - - // Clone the context first since calculating the digest finishes the operation - psa_hash_operation_t digest_context = PSA_HASH_OPERATION_INIT; - status = psa_hash_clone(context, &digest_context); - - VerifyOrReturnError(status == PSA_SUCCESS, CHIP_ERROR_INTERNAL); - - // Calculate digest on the cloned context - status = psa_hash_finish(&digest_context, Uint8::to_uchar(out_buffer.data()), out_buffer.size(), &output_length); - - VerifyOrExit(status == PSA_SUCCESS, result = CHIP_ERROR_INTERNAL); - VerifyOrExit(output_length == PSA_HASH_LENGTH(PSA_ALG_SHA_256), result = CHIP_ERROR_INTERNAL); -exit: - psa_hash_abort(&digest_context); - return result; -} - -CHIP_ERROR Hash_SHA256_stream::Finish(MutableByteSpan & out_buffer) -{ - psa_hash_operation_t * context = to_inner_hash_sha256_context(&mContext); - size_t output_length = 0; - - VerifyOrReturnError(out_buffer.size() >= kSHA256_Hash_Length, CHIP_ERROR_BUFFER_TOO_SMALL); - const psa_status_t status = psa_hash_finish(context, Uint8::to_uchar(out_buffer.data()), out_buffer.size(), &output_length); - - VerifyOrReturnError(status == PSA_SUCCESS, CHIP_ERROR_INTERNAL); - VerifyOrReturnError(output_length == PSA_HASH_LENGTH(PSA_ALG_SHA_256), CHIP_ERROR_INTERNAL); - - return CHIP_NO_ERROR; -} - -void Hash_SHA256_stream::Clear(void) -{ - psa_hash_operation_t * context = to_inner_hash_sha256_context(&mContext); - psa_hash_abort(context); -} - -CHIP_ERROR HKDF_sha::HKDF_SHA256(const uint8_t * secret, const size_t secret_length, const uint8_t * salt, const size_t salt_length, - const uint8_t * info, const size_t info_length, uint8_t * out_buffer, size_t out_length) -{ - VerifyOrReturnError(secret != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(secret_length > 0, CHIP_ERROR_INVALID_ARGUMENT); - - // Salt is optional - if (salt_length > 0) - { - VerifyOrReturnError(salt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - } - - VerifyOrReturnError(info_length > 0, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(info != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT; - - psa_crypto_init(); - - status = psa_key_derivation_setup(&operation, PSA_ALG_HKDF(PSA_ALG_SHA_256)); - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - - if (salt_length > 0) - { - status = - psa_key_derivation_input_bytes(&operation, PSA_KEY_DERIVATION_INPUT_SALT, Uint8::to_const_uchar(salt), salt_length); - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - } - - status = - psa_key_derivation_input_bytes(&operation, PSA_KEY_DERIVATION_INPUT_SECRET, Uint8::to_const_uchar(secret), secret_length); - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - - status = psa_key_derivation_input_bytes(&operation, PSA_KEY_DERIVATION_INPUT_INFO, Uint8::to_const_uchar(info), info_length); - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - - status = psa_key_derivation_output_bytes(&operation, out_buffer, out_length); - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); -exit: - psa_key_derivation_abort(&operation); - - return error; -} - -CHIP_ERROR HMAC_sha::HMAC_SHA256(const uint8_t * key, size_t key_length, const uint8_t * message, size_t message_length, - uint8_t * out_buffer, size_t out_length) -{ - VerifyOrReturnError(key != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(key_length > 0, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(message != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(message_length > 0, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(out_length >= kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; - psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT; - size_t output_length = 0; - - psa_crypto_init(); - - psa_set_key_type(&attr, PSA_KEY_TYPE_HMAC); - psa_set_key_bits(&attr, key_length * 8); - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_SIGN_HASH); - psa_set_key_algorithm(&attr, PSA_ALG_HMAC(PSA_ALG_SHA_256)); - - status = psa_driver_wrapper_mac_compute(&attr, Uint8::to_const_uchar(key), key_length, PSA_ALG_HMAC(PSA_ALG_SHA_256), - Uint8::to_const_uchar(message), message_length, out_buffer, out_length, &output_length); - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(output_length == PSA_HASH_LENGTH(PSA_ALG_SHA_256), error = CHIP_ERROR_INTERNAL); -exit: - psa_mac_abort(&operation); - psa_reset_key_attributes(&attr); - return error; -} - -CHIP_ERROR PBKDF2_sha256::pbkdf2_sha256(const uint8_t * password, size_t plen, const uint8_t * salt, size_t slen, - unsigned int iteration_count, uint32_t key_length, uint8_t * output) -{ - // TODO: replace inlined algorithm with usage of the PSA key derivation API once implemented - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; - size_t output_length = 0; - - // Align these buffers on the native data size to speed up the XOR - static const size_t hash_size_in_native = - ((PSA_HASH_LENGTH(PSA_ALG_SHA_256) + sizeof(unsigned int) - 1) / sizeof(unsigned int)); - static_assert(hash_size_in_native * sizeof(unsigned int) >= PSA_HASH_LENGTH(PSA_ALG_SHA_256)); - - unsigned int md1_buffer[hash_size_in_native]; - unsigned int work_buffer[hash_size_in_native]; - uint8_t * md1 = (uint8_t *) md1_buffer; - uint8_t * work = (uint8_t *) work_buffer; - - size_t use_len; - unsigned char * out_p = output; - uint8_t * U1 = (uint8_t *) MemoryCalloc(1, slen + 4); - - VerifyOrExit(U1 != nullptr, error = CHIP_ERROR_NO_MEMORY); - VerifyOrExit(password != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(plen > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(salt != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(slen >= kSpake2p_Min_PBKDF_Salt_Length, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(slen <= kSpake2p_Max_PBKDF_Salt_Length, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(key_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(output != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - - psa_crypto_init(); - - psa_set_key_type(&attr, PSA_KEY_TYPE_HMAC); - psa_set_key_bits(&attr, plen * 8); - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_SIGN_HASH); - psa_set_key_algorithm(&attr, PSA_ALG_HMAC(PSA_ALG_SHA_256)); - - // Start with initializing the salt + counter - memcpy(U1, salt, slen); - U1[slen] = 0; - U1[slen + 1] = 0; - U1[slen + 2] = 0; - U1[slen + 3] = 1; - - // Loop until we have generated the requested key length - while (key_length) - { - // U1 ends up in work - status = psa_driver_wrapper_mac_compute(&attr, password, plen, PSA_ALG_HMAC(PSA_ALG_SHA_256), U1, slen + 4, work, - PSA_HASH_LENGTH(PSA_ALG_SHA_256), &output_length); - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(output_length == PSA_HASH_LENGTH(PSA_ALG_SHA_256), error = CHIP_ERROR_INTERNAL); - - memcpy(md1, work, PSA_HASH_LENGTH(PSA_ALG_SHA_256)); - - for (size_t i = 1; i < iteration_count; i++) - { - // U2 ends up in md1 - // - - status = psa_driver_wrapper_mac_compute(&attr, password, plen, PSA_ALG_HMAC(PSA_ALG_SHA_256), md1, sizeof(md1_buffer), - md1, sizeof(md1_buffer), &output_length); - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(output_length == PSA_HASH_LENGTH(PSA_ALG_SHA_256), error = CHIP_ERROR_INTERNAL); - - // U1 xor U2 - // - for (size_t j = 0; j < hash_size_in_native; j++) - { - work_buffer[j] ^= md1_buffer[j]; - } - } - - use_len = (key_length < PSA_HASH_LENGTH(PSA_ALG_SHA_256)) ? key_length : PSA_HASH_LENGTH(PSA_ALG_SHA_256); - memcpy(out_p, work, use_len); - - key_length -= (uint32_t) use_len; - out_p += use_len; - - for (size_t i = 4; i > 0; i--) - { - if (++U1[slen + i - 1] != 0) - { - break; - } - } - } - -exit: - MemoryFree(U1); - psa_reset_key_attributes(&attr); - return error; -} - -CHIP_ERROR add_entropy_source(entropy_source fn_source, void * p_source, size_t threshold) -{ - // PSA Crypto has its own entropy and doesn't support an override mechanism - (void) fn_source; - (void) p_source; - (void) threshold; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR DRBG_get_bytes(uint8_t * out_buffer, const size_t out_length) -{ - VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT); - - psa_crypto_init(); - const psa_status_t result = psa_generate_random(Uint8::to_uchar(out_buffer), out_length); - VerifyOrReturnError(result == PSA_SUCCESS, CHIP_ERROR_INTERNAL); - - return CHIP_NO_ERROR; -} - -// CryptoRNG's definition is needed to use the mbedTLS-backed SPAKE2+ and certificate operations -static int CryptoRNG(void * ctxt, uint8_t * out_buffer, size_t out_length) -{ - return (chip::Crypto::DRBG_get_bytes(out_buffer, out_length) == CHIP_NO_ERROR) ? 0 : 1; -} - -// Mapping function is used as part of the certificate operations -mbedtls_ecp_group_id MapECPGroupId(SupportedECPKeyTypes keyType) -{ - switch (keyType) - { - case SupportedECPKeyTypes::ECP256R1: - return MBEDTLS_ECP_DP_SECP256R1; - default: - return MBEDTLS_ECP_DP_NONE; - } -} - -/******************************************************************************* - * - * WARNING: The default (base) implementation of P256Keypair is UNSAFE! - * - * Because of the way CHIPCryptoPAL has evolved, it is dictating how a base - * P256Keypair should behave. This includes: - * * Allowing using a P256 key for both ECDSA and ECDH operations - * * Needing to support copying a key through Serialize()/Deserialize() - * operations. This can't easily be done opaquely on an opaque backend - * without convoluted forms of reference tracking. - * * Not including a way to figure out whether the created key is supposed - * to be ephemeral or long-lived. - * * Needing to support ingestion of specific-format keys through - * Deserialize() (to support e.g. the example DAC provider). - * - * These conditions have lead to the base implementation of this class in this - * crypto backend being backed by a plaintext key buffer instead of opaque key - * references. Usage of the base class is strongly discouraged, and is only - * implemented to support the in-tree examples which instantiate keys of this - * base class. - * - ******************************************************************************/ - -typedef struct -{ - uint8_t privkey[32]; - size_t bitlen; -} psa_plaintext_ecp_keypair; - -static inline psa_plaintext_ecp_keypair * to_keypair(P256KeypairContext * context) -{ - return SafePointerCast(context); -} - -static inline const psa_plaintext_ecp_keypair * to_const_keypair(const P256KeypairContext * context) -{ - return SafePointerCast(context); -} - -CHIP_ERROR P256Keypair::ECDSA_sign_msg(const uint8_t * msg, const size_t msg_length, P256ECDSASignature & out_signature) const -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; - size_t output_length = 0; - const psa_plaintext_ecp_keypair * keypair = to_const_keypair(&mKeypair); - - VerifyOrExit(mInitialized, error = CHIP_ERROR_WELL_UNINITIALIZED); - VerifyOrExit((msg != nullptr) && (msg_length > 0), error = CHIP_ERROR_INVALID_ARGUMENT); - - psa_crypto_init(); - - psa_set_key_type(&attr, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)); - psa_set_key_bits(&attr, keypair->bitlen); - psa_set_key_algorithm(&attr, PSA_ALG_ECDSA(PSA_ALG_SHA_256)); - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_SIGN_MESSAGE); - - // use imported key to sign a message - status = - psa_driver_wrapper_sign_message(&attr, keypair->privkey, PSA_BITS_TO_BYTES(keypair->bitlen), PSA_ALG_ECDSA(PSA_ALG_SHA_256), - msg, msg_length, out_signature.Bytes(), out_signature.Capacity(), &output_length); - - VerifyOrReturnError(status == PSA_SUCCESS, CHIP_ERROR_INTERNAL); - VerifyOrReturnError(output_length == kP256_ECDSA_Signature_Length_Raw, CHIP_ERROR_INTERNAL); - VerifyOrReturnError(out_signature.SetLength(output_length) == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); - -exit: - _log_PSA_error(status); - psa_reset_key_attributes(&attr); - - return error; -} - -CHIP_ERROR P256PublicKey::ECDSA_validate_msg_signature(const uint8_t * msg, const size_t msg_length, - const P256ECDSASignature & signature) const -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; - - VerifyOrExit((msg != nullptr) && (msg_length > 0), error = CHIP_ERROR_INVALID_ARGUMENT); - - psa_crypto_init(); - - psa_set_key_type(&attr, PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1)); - psa_set_key_bits(&attr, 256); - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_VERIFY_MESSAGE); - psa_set_key_algorithm(&attr, PSA_ALG_ECDSA(PSA_ALG_SHA_256)); - - // use imported key to verify a message - status = psa_driver_wrapper_verify_message(&attr, Uint8::to_const_uchar(*this), Length(), PSA_ALG_ECDSA(PSA_ALG_SHA_256), msg, - msg_length, signature.ConstBytes(), signature.Length()); - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INVALID_SIGNATURE); -exit: - _log_PSA_error(status); - psa_reset_key_attributes(&attr); - - return error; -} - -CHIP_ERROR P256PublicKey::ECDSA_validate_hash_signature(const uint8_t * hash, const size_t hash_length, - const P256ECDSASignature & signature) const -{ - VerifyOrReturnError(hash != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(hash_length == kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(signature.Length() == kP256_ECDSA_Signature_Length_Raw, CHIP_ERROR_INVALID_ARGUMENT); - - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; - - // Step 1: import public key as volatile - psa_crypto_init(); - - psa_set_key_type(&attr, PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1)); - psa_set_key_bits(&attr, 256); - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_VERIFY_HASH); - psa_set_key_algorithm(&attr, PSA_ALG_ECDSA(PSA_ALG_SHA_256)); - - // use imported key to verify a hash - status = psa_driver_wrapper_verify_hash(&attr, Uint8::to_const_uchar(*this), Length(), PSA_ALG_ECDSA(PSA_ALG_SHA_256), hash, - hash_length, signature.ConstBytes(), signature.Length()); - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INVALID_SIGNATURE); -exit: - _log_PSA_error(status); - psa_reset_key_attributes(&attr); - return error; -} - -CHIP_ERROR P256Keypair::ECDH_derive_secret(const P256PublicKey & remote_public_key, P256ECDHDerivedSecret & out_secret) const -{ - // Todo: replace with driver call once key derivation through the driver wrapper has been figured out - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - mbedtls_svc_key_id_t key_id = 0; - psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; - size_t output_length = 0; - const psa_plaintext_ecp_keypair * keypair = to_const_keypair(&mKeypair); - - VerifyOrExit(mInitialized, error = CHIP_ERROR_WELL_UNINITIALIZED); - - // Step 1: import plaintext key as volatile for ECDH - psa_crypto_init(); - - psa_set_key_type(&attr, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)); - psa_set_key_bits(&attr, keypair->bitlen); - psa_set_key_algorithm(&attr, PSA_ALG_ECDH); - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_DERIVE); - - status = psa_import_key(&attr, keypair->privkey, PSA_BITS_TO_BYTES(keypair->bitlen), &key_id); - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - - // Step 2: do key derivation - status = psa_raw_key_agreement(PSA_ALG_ECDH, key_id, Uint8::to_const_uchar(remote_public_key), remote_public_key.Length(), - Uint8::to_uchar(out_secret), - (out_secret.Length() == 0) ? out_secret.Capacity() : out_secret.Length(), &output_length); - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - SuccessOrExit(out_secret.SetLength(output_length)); - -exit: - _log_PSA_error(status); - // Step 3: destroy imported key - psa_reset_key_attributes(&attr); - if (key_id != 0) - { - psa_destroy_key(key_id); - } - return error; -} - -void ClearSecretData(uint8_t * buf, size_t len) -{ - mbedtls_platform_zeroize(buf, len); -} - -// THE BELOW IS FROM `third_party/openthread/repo/third_party/mbedtls/repo/library/constant_time.c` since -// mbedtls_ct_memcmp is not available on Linux somehow :( -int mbedtls_ct_memcmp_copy(const void * a, const void * b, size_t n) -{ - size_t i; - volatile const unsigned char * A = (volatile const unsigned char *) a; - volatile const unsigned char * B = (volatile const unsigned char *) b; - volatile unsigned char diff = 0; - - for (i = 0; i < n; i++) - { - /* Read volatile data in order before computing diff. - * This avoids IAR compiler warning: - * 'the order of volatile accesses is undefined ..' */ - unsigned char x = A[i], y = B[i]; - diff |= x ^ y; - } - - return ((int) diff); -} - -bool IsBufferContentEqualConstantTime(const void * a, const void * b, size_t n) -{ - return mbedtls_ct_memcmp_copy(a, b, n) == 0; -} - -CHIP_ERROR P256Keypair::Initialize() -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - psa_plaintext_ecp_keypair * keypair = to_keypair(&mKeypair); - size_t output_length; - - if (mInitialized) - { - return CHIP_ERROR_INCORRECT_STATE; - } - - // Step 1: Generate a volatile new key - psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; - psa_crypto_init(); - - psa_set_key_type(&attr, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)); - psa_set_key_bits(&attr, 256); - psa_set_key_algorithm(&attr, PSA_ALG_ECDH); - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT); - - status = psa_driver_wrapper_generate_key(&attr, keypair->privkey, sizeof(keypair->privkey), &output_length); - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(output_length == kP256_PrivateKey_Length, error = CHIP_ERROR_INTERNAL); - - keypair->bitlen = 256; - - // Step 2: Export the public key into the pubkey member - status = psa_driver_wrapper_export_public_key(&attr, keypair->privkey, sizeof(keypair->privkey), Uint8::to_uchar(mPublicKey), - mPublicKey.Length(), &output_length); - - VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(output_length == kP256_PublicKey_Length, error = CHIP_ERROR_INTERNAL); - -exit: - _log_PSA_error(status); - if (error == CHIP_NO_ERROR) - { - mInitialized = true; - } - psa_reset_key_attributes(&attr); - - return error; -} - -CHIP_ERROR P256Keypair::Serialize(P256SerializedKeypair & output) const -{ - CHIP_ERROR error = CHIP_NO_ERROR; - const psa_plaintext_ecp_keypair * keypair = to_const_keypair(&mKeypair); - size_t len = output.Length() == 0 ? output.Capacity() : output.Length(); - Encoding::BufferWriter bbuf(output, len); - - VerifyOrExit(mInitialized, error = CHIP_ERROR_WELL_UNINITIALIZED); - - bbuf.Put(mPublicKey, mPublicKey.Length()); - - VerifyOrExit(bbuf.Available() == sizeof(keypair->privkey), error = CHIP_ERROR_INTERNAL); - - bbuf.Put(keypair->privkey, PSA_BITS_TO_BYTES(keypair->bitlen)); - VerifyOrExit(bbuf.Fit(), error = CHIP_ERROR_BUFFER_TOO_SMALL); - - output.SetLength(bbuf.Needed()); - -exit: - return error; -} - -CHIP_ERROR P256Keypair::Deserialize(P256SerializedKeypair & input) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_plaintext_ecp_keypair * keypair = to_keypair(&mKeypair); - Encoding::BufferWriter bbuf(mPublicKey, mPublicKey.Length()); - - VerifyOrExit(input.Length() == mPublicKey.Length() + kP256_PrivateKey_Length, error = CHIP_ERROR_INVALID_ARGUMENT); - - Clear(); - - memcpy(keypair->privkey, Uint8::to_uchar(input) + mPublicKey.Length(), kP256_PrivateKey_Length); - keypair->bitlen = 256; - - bbuf.Put((const uint8_t *) input, mPublicKey.Length()); - VerifyOrExit(bbuf.Fit(), error = CHIP_ERROR_NO_MEMORY); - - mInitialized = true; - -exit: - return error; -} - -void P256Keypair::Clear() -{ - if (mInitialized) - { - psa_plaintext_ecp_keypair * keypair = to_keypair(&mKeypair); - memset(keypair, 0, sizeof(psa_plaintext_ecp_keypair)); - mInitialized = false; - } -} - -P256Keypair::~P256Keypair() -{ - Clear(); -} - -CHIP_ERROR P256Keypair::NewCertificateSigningRequest(uint8_t * out_csr, size_t & csr_length) const -{ - MutableByteSpan csr(out_csr, csr_length); - CHIP_ERROR err = GenerateCertificateSigningRequest(this, csr); - csr_length = (CHIP_NO_ERROR == err) ? csr.size() : 0; - return err; -} - -CHIP_ERROR VerifyCertificateSigningRequest(const uint8_t * csr_buf, size_t csr_length, P256PublicKey & pubkey) -{ -#if defined(MBEDTLS_X509_CSR_PARSE_C) - ReturnErrorOnFailure(VerifyCertificateSigningRequestFormat(csr_buf, csr_length)); - - // TODO: For some embedded targets, mbedTLS library doesn't have mbedtls_x509_csr_parse_der, and mbedtls_x509_csr_parse_free. - // Taking a step back, embedded targets likely will not process CSR requests. Adding this action item to reevaluate - // this if there's a need for this processing for embedded targets. - CHIP_ERROR error = CHIP_NO_ERROR; - size_t pubkey_size = 0; - - mbedtls_ecp_keypair * keypair = nullptr; - - P256ECDSASignature signature; - MutableByteSpan out_raw_sig_span(signature.Bytes(), signature.Capacity()); - - mbedtls_x509_csr csr; - mbedtls_x509_csr_init(&csr); - - int result = mbedtls_x509_csr_parse_der(&csr, csr_buf, csr_length); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - // Verify the signature algorithm and public key type - VerifyOrExit(csr.CHIP_CRYPTO_PAL_PRIVATE(sig_md) == MBEDTLS_MD_SHA256, error = CHIP_ERROR_UNSUPPORTED_SIGNATURE_TYPE); - VerifyOrExit(csr.CHIP_CRYPTO_PAL_PRIVATE(sig_pk) == MBEDTLS_PK_ECDSA, error = CHIP_ERROR_WRONG_KEY_TYPE); - - keypair = mbedtls_pk_ec(csr.CHIP_CRYPTO_PAL_PRIVATE_X509(pk)); - - // Copy the public key from the CSR - result = mbedtls_ecp_point_write_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair->CHIP_CRYPTO_PAL_PRIVATE(Q), - MBEDTLS_ECP_PF_UNCOMPRESSED, &pubkey_size, Uint8::to_uchar(pubkey), pubkey.Length()); - - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(pubkey_size == pubkey.Length(), error = CHIP_ERROR_INTERNAL); - - // Convert DER signature to raw signature - error = EcdsaAsn1SignatureToRaw(kP256_FE_Length, - ByteSpan{ csr.CHIP_CRYPTO_PAL_PRIVATE(sig).CHIP_CRYPTO_PAL_PRIVATE_X509(p), - csr.CHIP_CRYPTO_PAL_PRIVATE(sig).CHIP_CRYPTO_PAL_PRIVATE_X509(len) }, - out_raw_sig_span); - - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(out_raw_sig_span.size() == (kP256_FE_Length * 2), error = CHIP_ERROR_INTERNAL); - signature.SetLength(out_raw_sig_span.size()); - - // Verify the signature using the public key - error = pubkey.ECDSA_validate_msg_signature(csr.CHIP_CRYPTO_PAL_PRIVATE_X509(cri).CHIP_CRYPTO_PAL_PRIVATE_X509(p), - csr.CHIP_CRYPTO_PAL_PRIVATE_X509(cri).CHIP_CRYPTO_PAL_PRIVATE_X509(len), signature); - - SuccessOrExit(error); - -exit: - mbedtls_x509_csr_free(&csr); - _log_mbedTLS_error(result); - return error; -#else - ChipLogError(Crypto, "MBEDTLS_X509_CSR_PARSE_C is not enabled. CSR cannot be parsed"); - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; -#endif -} - -typedef struct Spake2p_Context -{ - mbedtls_ecp_group curve; - mbedtls_ecp_point M; - mbedtls_ecp_point N; - mbedtls_ecp_point X; - mbedtls_ecp_point Y; - mbedtls_ecp_point L; - mbedtls_ecp_point Z; - mbedtls_ecp_point V; - - mbedtls_mpi w0; - mbedtls_mpi w1; - mbedtls_mpi xy; - mbedtls_mpi tempbn; -} Spake2p_Context; - -static inline Spake2p_Context * to_inner_spake2p_context(Spake2pOpaqueContext * context) -{ - return SafePointerCast(context); -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::InitInternal(void) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - - memset(context, 0, sizeof(Spake2p_Context)); - - mbedtls_ecp_group_init(&context->curve); - result = mbedtls_ecp_group_load(&context->curve, MBEDTLS_ECP_DP_SECP256R1); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - VerifyOrExit(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256) != nullptr, error = CHIP_ERROR_INTERNAL); - - mbedtls_ecp_point_init(&context->M); - mbedtls_ecp_point_init(&context->N); - mbedtls_ecp_point_init(&context->X); - mbedtls_ecp_point_init(&context->Y); - mbedtls_ecp_point_init(&context->L); - mbedtls_ecp_point_init(&context->V); - mbedtls_ecp_point_init(&context->Z); - M = &context->M; - N = &context->N; - X = &context->X; - Y = &context->Y; - L = &context->L; - V = &context->V; - Z = &context->Z; - - mbedtls_mpi_init(&context->w0); - mbedtls_mpi_init(&context->w1); - mbedtls_mpi_init(&context->xy); - mbedtls_mpi_init(&context->tempbn); - w0 = &context->w0; - w1 = &context->w1; - xy = &context->xy; - tempbn = &context->tempbn; - - G = &context->curve.G; - order = &context->curve.N; - - return error; - -exit: - _log_mbedTLS_error(result); - Clear(); - return error; -} - -void Spake2p_P256_SHA256_HKDF_HMAC::Clear() -{ - VerifyOrReturn(state != CHIP_SPAKE2P_STATE::PREINIT); - - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - - mbedtls_ecp_point_free(&context->M); - mbedtls_ecp_point_free(&context->N); - mbedtls_ecp_point_free(&context->X); - mbedtls_ecp_point_free(&context->Y); - mbedtls_ecp_point_free(&context->L); - mbedtls_ecp_point_free(&context->Z); - mbedtls_ecp_point_free(&context->V); - - mbedtls_mpi_free(&context->w0); - mbedtls_mpi_free(&context->w1); - mbedtls_mpi_free(&context->xy); - mbedtls_mpi_free(&context->tempbn); - - mbedtls_ecp_group_free(&context->curve); - - state = CHIP_SPAKE2P_STATE::PREINIT; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::Mac(const uint8_t * key, size_t key_len, const uint8_t * in, size_t in_len, - MutableByteSpan & out_span) -{ - HMAC_sha hmac; - VerifyOrReturnError(out_span.size() >= kSHA256_Hash_Length, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorOnFailure(hmac.HMAC_SHA256(key, key_len, in, in_len, out_span.data(), kSHA256_Hash_Length)); - out_span = out_span.SubSpan(0, kSHA256_Hash_Length); - return CHIP_NO_ERROR; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::MacVerify(const uint8_t * key, size_t key_len, const uint8_t * mac, size_t mac_len, - const uint8_t * in, size_t in_len) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - uint8_t computed_mac[kSHA256_Hash_Length]; - MutableByteSpan computed_mac_span{ computed_mac }; - VerifyOrExit(mac_len == kSHA256_Hash_Length, error = CHIP_ERROR_INVALID_ARGUMENT); - - SuccessOrExit(error = Mac(key, key_len, in, in_len, computed_mac_span)); - VerifyOrExit(computed_mac_span.size() == mac_len, error = CHIP_ERROR_INTERNAL); - - VerifyOrExit(IsBufferContentEqualConstantTime(mac, computed_mac, kSHA256_Hash_Length), error = CHIP_ERROR_INTERNAL); - -exit: - _log_mbedTLS_error(result); - return error; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FELoad(const uint8_t * in, size_t in_len, void * fe) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - result = mbedtls_mpi_read_binary((mbedtls_mpi *) fe, Uint8::to_const_uchar(in), in_len); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - result = mbedtls_mpi_mod_mpi((mbedtls_mpi *) fe, (mbedtls_mpi *) fe, (const mbedtls_mpi *) order); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - -exit: - _log_mbedTLS_error(result); - return error; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEWrite(const void * fe, uint8_t * out, size_t out_len) -{ - if (mbedtls_mpi_write_binary((const mbedtls_mpi *) fe, Uint8::to_uchar(out), out_len) != 0) - { - return CHIP_ERROR_INTERNAL; - } - return CHIP_NO_ERROR; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEGenerate(void * fe) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - - result = mbedtls_ecp_gen_privkey(&context->curve, (mbedtls_mpi *) fe, CryptoRNG, nullptr); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - -exit: - _log_mbedTLS_error(result); - return error; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEMul(void * fer, const void * fe1, const void * fe2) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - result = mbedtls_mpi_mul_mpi((mbedtls_mpi *) fer, (const mbedtls_mpi *) fe1, (const mbedtls_mpi *) fe2); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - result = mbedtls_mpi_mod_mpi((mbedtls_mpi *) fer, (mbedtls_mpi *) fer, (const mbedtls_mpi *) order); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - -exit: - _log_mbedTLS_error(result); - return error; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointLoad(const uint8_t * in, size_t in_len, void * R) -{ - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - - if (mbedtls_ecp_point_read_binary(&context->curve, (mbedtls_ecp_point *) R, Uint8::to_const_uchar(in), in_len) != 0) - { - return CHIP_ERROR_INTERNAL; - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointWrite(const void * R, uint8_t * out, size_t out_len) -{ - memset(out, 0, out_len); - - size_t mbedtls_out_len = out_len; - - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - - if (mbedtls_ecp_point_write_binary(&context->curve, (const mbedtls_ecp_point *) R, MBEDTLS_ECP_PF_UNCOMPRESSED, - &mbedtls_out_len, Uint8::to_uchar(out), out_len) != 0) - { - return CHIP_ERROR_INTERNAL; - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointMul(void * R, const void * P1, const void * fe1) -{ - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - - if (mbedtls_ecp_mul(&context->curve, (mbedtls_ecp_point *) R, (const mbedtls_mpi *) fe1, (const mbedtls_ecp_point *) P1, - CryptoRNG, nullptr) != 0) - { - return CHIP_ERROR_INTERNAL; - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointAddMul(void * R, const void * P1, const void * fe1, const void * P2, - const void * fe2) -{ - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - - if (mbedtls_ecp_muladd(&context->curve, (mbedtls_ecp_point *) R, (const mbedtls_mpi *) fe1, (const mbedtls_ecp_point *) P1, - (const mbedtls_mpi *) fe2, (const mbedtls_ecp_point *) P2) != 0) - { - return CHIP_ERROR_INTERNAL; - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointInvert(void * R) -{ - mbedtls_ecp_point * Rp = (mbedtls_ecp_point *) R; - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - - if (mbedtls_mpi_sub_mpi(&Rp->CHIP_CRYPTO_PAL_PRIVATE(Y), &context->curve.P, &Rp->CHIP_CRYPTO_PAL_PRIVATE(Y)) != 0) - { - return CHIP_ERROR_INTERNAL; - } - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) -{ - return CHIP_NO_ERROR; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - mbedtls_ecp_group curve; - mbedtls_mpi w1_bn; - mbedtls_ecp_point Ltemp; - - mbedtls_ecp_group_init(&curve); - mbedtls_mpi_init(&w1_bn); - mbedtls_ecp_point_init(&Ltemp); - - result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - result = mbedtls_ecp_mul(&curve, &Ltemp, &w1_bn, &curve.G, CryptoRNG, nullptr); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - memset(Lout, 0, *L_len); - - result = mbedtls_ecp_point_write_binary(&curve, &Ltemp, MBEDTLS_ECP_PF_UNCOMPRESSED, L_len, Uint8::to_uchar(Lout), *L_len); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - -exit: - _log_mbedTLS_error(result); - mbedtls_ecp_point_free(&Ltemp); - mbedtls_mpi_free(&w1_bn); - mbedtls_ecp_group_free(&curve); - - return error; -} - -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointIsValid(void * R) -{ - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - - if (mbedtls_ecp_check_pubkey(&context->curve, (mbedtls_ecp_point *) R) != 0) - { - return CHIP_ERROR_INTERNAL; - } - - return CHIP_NO_ERROR; -} - -constexpr uint8_t sOID_AttributeType_CommonName[] = { 0x55, 0x04, 0x03 }; -constexpr uint8_t sOID_AttributeType_MatterVendorId[] = { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xA2, 0x7C, 0x02, 0x01 }; -constexpr uint8_t sOID_AttributeType_MatterProductId[] = { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xA2, 0x7C, 0x02, 0x02 }; -constexpr uint8_t sOID_SigAlgo_ECDSAWithSHA256[] = { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02 }; -constexpr uint8_t sOID_Extension_BasicConstraints[] = { 0x55, 0x1D, 0x13 }; -constexpr uint8_t sOID_Extension_KeyUsage[] = { 0x55, 0x1D, 0x0F }; -constexpr uint8_t sOID_Extension_SubjectKeyIdentifier[] = { 0x55, 0x1D, 0x0E }; -constexpr uint8_t sOID_Extension_AuthorityKeyIdentifier[] = { 0x55, 0x1D, 0x23 }; - -/** - * Compares an mbedtls_asn1_buf structure (oidBuf) to a reference OID represented as uint8_t array (oid). - */ -#define OID_CMP(oid, oidBuf) \ - ((MBEDTLS_ASN1_OID == (oidBuf).CHIP_CRYPTO_PAL_PRIVATE_X509(tag)) && \ - (sizeof(oid) == (oidBuf).CHIP_CRYPTO_PAL_PRIVATE_X509(len)) && \ - (memcmp((oid), (oidBuf).CHIP_CRYPTO_PAL_PRIVATE_X509(p), (oidBuf).CHIP_CRYPTO_PAL_PRIVATE_X509(len)) == 0)) - -CHIP_ERROR VerifyAttestationCertificateFormat(const ByteSpan & cert, AttestationCertType certType) -{ -#if defined(MBEDTLS_X509_CRT_PARSE_C) - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - mbedtls_x509_crt mbed_cert; - unsigned char * p = nullptr; - const unsigned char * end = nullptr; - size_t len = 0; - bool extBasicPresent = false; - bool extKeyUsagePresent = false; - - VerifyOrReturnError(!cert.empty(), CHIP_ERROR_INVALID_ARGUMENT); - - mbedtls_x509_crt_init(&mbed_cert); - - result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(cert.data()), cert.size()); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - // "version" value is 1 higher than the actual encoded value. - VerifyOrExit(mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(version) - 1 == 2, error = CHIP_ERROR_INTERNAL); - - // Verify signature algorithms is ECDSA with SHA256. - VerifyOrExit(OID_CMP(sOID_SigAlgo_ECDSAWithSHA256, mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(sig_oid)), - error = CHIP_ERROR_INTERNAL); - - // Verify public key presence and format. - { - Crypto::P256PublicKey pubkey; - SuccessOrExit(error = ExtractPubkeyFromX509Cert(cert, pubkey)); - } - - p = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(v3_ext).CHIP_CRYPTO_PAL_PRIVATE_X509(p); - end = p + mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(v3_ext).CHIP_CRYPTO_PAL_PRIVATE_X509(len); - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - while (p < end) - { - mbedtls_x509_buf extOID = { 0, 0, nullptr }; - int extCritical = 0; - - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - /* Get extension ID */ - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OID); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - extOID.CHIP_CRYPTO_PAL_PRIVATE_X509(tag) = MBEDTLS_ASN1_OID; - extOID.CHIP_CRYPTO_PAL_PRIVATE_X509(len) = len; - extOID.CHIP_CRYPTO_PAL_PRIVATE_X509(p) = p; - p += len; - - /* Get optional critical */ - result = mbedtls_asn1_get_bool(&p, end, &extCritical); - VerifyOrExit(result == 0 || result == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG, error = CHIP_ERROR_INTERNAL); - - /* Data should be octet string type */ - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - if (OID_CMP(sOID_Extension_BasicConstraints, extOID)) - { - int isCA = 0; - int pathLen = -1; - unsigned char * seqStart = p; - - VerifyOrExit(extCritical, error = CHIP_ERROR_INTERNAL); - extBasicPresent = true; - - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - if (len > 0) - { - result = mbedtls_asn1_get_bool(&p, end, &isCA); - VerifyOrExit(result == 0 || result == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG, error = CHIP_ERROR_INTERNAL); - - if (p != seqStart + len) - { - result = mbedtls_asn1_get_int(&p, end, &pathLen); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - } - } - - if (certType == AttestationCertType::kDAC) - { - VerifyOrExit(!isCA && pathLen == -1, error = CHIP_ERROR_INTERNAL); - } - else if (certType == AttestationCertType::kPAI) - { - VerifyOrExit(isCA && pathLen == 0, error = CHIP_ERROR_INTERNAL); - } - else - { - VerifyOrExit(isCA && (pathLen == -1 || pathLen == 0 || pathLen == 1), error = CHIP_ERROR_INTERNAL); - } - } - else if (OID_CMP(sOID_Extension_KeyUsage, extOID)) - { - mbedtls_x509_bitstring bs = { 0, 0, nullptr }; - unsigned int keyUsage = 0; - - VerifyOrExit(extCritical, error = CHIP_ERROR_INTERNAL); - extKeyUsagePresent = true; - - result = mbedtls_asn1_get_bitstring(&p, p + len, &bs); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - for (size_t i = 0; i < bs.CHIP_CRYPTO_PAL_PRIVATE_X509(len) && i < sizeof(unsigned int); i++) - { - keyUsage |= static_cast(bs.CHIP_CRYPTO_PAL_PRIVATE_X509(p)[i]) << (8 * i); - } - - if (certType == AttestationCertType::kDAC) - { - // SHALL only have the digitalSignature bit set. - VerifyOrExit(keyUsage == MBEDTLS_X509_KU_DIGITAL_SIGNATURE, error = CHIP_ERROR_INTERNAL); - } - else - { - bool keyCertSignFlag = keyUsage & MBEDTLS_X509_KU_KEY_CERT_SIGN; - bool crlSignFlag = keyUsage & MBEDTLS_X509_KU_CRL_SIGN; - bool otherFlags = - keyUsage & ~(MBEDTLS_X509_KU_CRL_SIGN | MBEDTLS_X509_KU_KEY_CERT_SIGN | MBEDTLS_X509_KU_DIGITAL_SIGNATURE); - VerifyOrExit(keyCertSignFlag && crlSignFlag && !otherFlags, error = CHIP_ERROR_INTERNAL); - } - } - else - { - p += len; - } - } - - // Verify basic and key usage extensions are present. - VerifyOrExit(extBasicPresent && extKeyUsagePresent, error = CHIP_ERROR_INTERNAL); - - // Verify that SKID and AKID extensions are present. - { - uint8_t kidBuf[kSubjectKeyIdentifierLength]; - MutableByteSpan kid(kidBuf); - SuccessOrExit(error = ExtractSKIDFromX509Cert(cert, kid)); - if (certType == AttestationCertType::kDAC || certType == AttestationCertType::kPAI) - { - // Mandatory extension for DAC and PAI certs. - SuccessOrExit(error = ExtractAKIDFromX509Cert(cert, kid)); - } - } - -exit: - _log_mbedTLS_error(result); - mbedtls_x509_crt_free(&mbed_cert); - -#else - (void) cert; - (void) certType; - CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; -#endif // defined(MBEDTLS_X509_CRT_PARSE_C) - - return error; -} - -CHIP_ERROR ValidateCertificateChain(const uint8_t * rootCertificate, size_t rootCertificateLen, const uint8_t * caCertificate, - size_t caCertificateLen, const uint8_t * leafCertificate, size_t leafCertificateLen, - CertificateChainValidationResult & result) -{ -#if defined(MBEDTLS_X509_CRT_PARSE_C) - CHIP_ERROR error = CHIP_NO_ERROR; - mbedtls_x509_crt certChain; - mbedtls_x509_crt rootCert; - mbedtls_x509_time leaf_valid_from; - mbedtls_x509_crt * cert = NULL; - int mbedResult; - uint32_t flags; - int compare_from = 0; - int compare_until = 0; - - result = CertificateChainValidationResult::kInternalFrameworkError; - - VerifyOrReturnError(rootCertificate != nullptr && rootCertificateLen != 0, - (result = CertificateChainValidationResult::kRootArgumentInvalid, CHIP_ERROR_INVALID_ARGUMENT)); - VerifyOrReturnError(leafCertificate != nullptr && leafCertificateLen != 0, - (result = CertificateChainValidationResult::kLeafArgumentInvalid, CHIP_ERROR_INVALID_ARGUMENT)); - - mbedtls_x509_crt_init(&certChain); - mbedtls_x509_crt_init(&rootCert); - - /* Start of chain */ - mbedResult = mbedtls_x509_crt_parse(&certChain, Uint8::to_const_uchar(leafCertificate), leafCertificateLen); - VerifyOrExit(mbedResult == 0, (result = CertificateChainValidationResult::kLeafFormatInvalid, error = CHIP_ERROR_INTERNAL)); - leaf_valid_from = certChain.valid_from; - - /* Add the intermediate to the chain, if present */ - if (caCertificate != nullptr && caCertificateLen > 0) - { - mbedResult = mbedtls_x509_crt_parse(&certChain, Uint8::to_const_uchar(caCertificate), caCertificateLen); - VerifyOrExit(mbedResult == 0, (result = CertificateChainValidationResult::kICAFormatInvalid, error = CHIP_ERROR_INTERNAL)); - } - - /* Parse the root cert */ - mbedResult = mbedtls_x509_crt_parse(&rootCert, Uint8::to_const_uchar(rootCertificate), rootCertificateLen); - VerifyOrExit(mbedResult == 0, (result = CertificateChainValidationResult::kRootFormatInvalid, error = CHIP_ERROR_INTERNAL)); - - /* Validates that intermediate and root certificates are valid at the time of the leaf certificate's start time. */ - compare_from = timeCompare(&leaf_valid_from, &rootCert.valid_from); - compare_until = timeCompare(&leaf_valid_from, &rootCert.valid_to); - VerifyOrExit((compare_from >= 0) && (compare_until <= 0), - (result = CertificateChainValidationResult::kChainInvalid, error = CHIP_ERROR_CERT_NOT_TRUSTED)); - cert = certChain.next; - while (cert) - { - compare_from = timeCompare(&leaf_valid_from, &cert->valid_from); - compare_until = timeCompare(&leaf_valid_from, &cert->valid_to); - VerifyOrExit((compare_from >= 0) && (compare_until <= 0), - (result = CertificateChainValidationResult::kChainInvalid, error = CHIP_ERROR_CERT_NOT_TRUSTED)); - cert = cert->next; - } - - /* Verify the chain against the root */ - mbedResult = mbedtls_x509_crt_verify(&certChain, &rootCert, NULL, NULL, &flags, NULL, NULL); - - switch (mbedResult) - { - case 0: - VerifyOrExit(flags == 0, (result = CertificateChainValidationResult::kInternalFrameworkError, error = CHIP_ERROR_INTERNAL)); - result = CertificateChainValidationResult::kSuccess; - break; - case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED: - result = CertificateChainValidationResult::kChainInvalid; - error = CHIP_ERROR_CERT_NOT_TRUSTED; - break; - default: - SuccessOrExit((result = CertificateChainValidationResult::kInternalFrameworkError, error = CHIP_ERROR_INTERNAL)); - } - -exit: - _log_mbedTLS_error(mbedResult); - mbedtls_x509_crt_free(&certChain); - mbedtls_x509_crt_free(&rootCert); - -#else - (void) rootCertificate; - (void) rootCertificateLen; - (void) caCertificate; - (void) caCertificateLen; - (void) leafCertificate; - (void) leafCertificateLen; - (void) result; - CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; -#endif // defined(MBEDTLS_X509_CRT_PARSE_C) - - return error; -} - -inline bool IsTimeGreaterThanEqual(const mbedtls_x509_time * const timeA, const mbedtls_x509_time * const timeB) -{ - - // checks if two values are different and if yes, then returns first > second. -#define RETURN_STRICTLY_GREATER_IF_DIFFERENT(component) \ - { \ - auto valueA = timeA->CHIP_CRYPTO_PAL_PRIVATE_X509(component); \ - auto valueB = timeB->CHIP_CRYPTO_PAL_PRIVATE_X509(component); \ - \ - if (valueA != valueB) \ - { \ - return valueA > valueB; \ - } \ - } - - RETURN_STRICTLY_GREATER_IF_DIFFERENT(year); - RETURN_STRICTLY_GREATER_IF_DIFFERENT(mon); - RETURN_STRICTLY_GREATER_IF_DIFFERENT(day); - RETURN_STRICTLY_GREATER_IF_DIFFERENT(hour); - RETURN_STRICTLY_GREATER_IF_DIFFERENT(min); - RETURN_STRICTLY_GREATER_IF_DIFFERENT(sec); - - // all above are equal - return true; -} - -CHIP_ERROR IsCertificateValidAtIssuance(const ByteSpan & referenceCertificate, const ByteSpan & toBeEvaluatedCertificate) -{ -#if defined(MBEDTLS_X509_CRT_PARSE_C) - CHIP_ERROR error = CHIP_NO_ERROR; - mbedtls_x509_crt mbedReferenceCertificate; - mbedtls_x509_crt mbedToBeEvaluatedCertificate; - mbedtls_x509_time refNotBeforeTime; - mbedtls_x509_time tbeNotBeforeTime; - mbedtls_x509_time tbeNotAfterTime; - int result; - - VerifyOrReturnError(!referenceCertificate.empty() && !toBeEvaluatedCertificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); - - mbedtls_x509_crt_init(&mbedReferenceCertificate); - mbedtls_x509_crt_init(&mbedToBeEvaluatedCertificate); - - result = mbedtls_x509_crt_parse(&mbedReferenceCertificate, Uint8::to_const_uchar(referenceCertificate.data()), - referenceCertificate.size()); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - result = mbedtls_x509_crt_parse(&mbedToBeEvaluatedCertificate, Uint8::to_const_uchar(toBeEvaluatedCertificate.data()), - toBeEvaluatedCertificate.size()); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - refNotBeforeTime = mbedReferenceCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(valid_from); - tbeNotBeforeTime = mbedToBeEvaluatedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(valid_from); - tbeNotAfterTime = mbedToBeEvaluatedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(valid_to); - - // check if referenceCertificate is issued at or after tbeCertificate's notBefore timestamp - VerifyOrExit(IsTimeGreaterThanEqual(&refNotBeforeTime, &tbeNotBeforeTime), error = CHIP_ERROR_CERT_EXPIRED); - - // check if referenceCertificate is issued at or before tbeCertificate's notAfter timestamp - VerifyOrExit(IsTimeGreaterThanEqual(&tbeNotAfterTime, &refNotBeforeTime), error = CHIP_ERROR_CERT_EXPIRED); - -exit: - _log_mbedTLS_error(result); - mbedtls_x509_crt_free(&mbedReferenceCertificate); - mbedtls_x509_crt_free(&mbedToBeEvaluatedCertificate); - -#else - (void) referenceCertificate; - (void) toBeEvaluatedCertificate; - CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; -#endif // defined(MBEDTLS_X509_CRT_PARSE_C) - - return error; -} - -CHIP_ERROR IsCertificateValidAtCurrentTime(const ByteSpan & certificate) -{ -#if defined(MBEDTLS_X509_CRT_PARSE_C) - CHIP_ERROR error = CHIP_NO_ERROR; - mbedtls_x509_crt mbedCertificate; - int result; - - VerifyOrReturnError(!certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); - - mbedtls_x509_crt_init(&mbedCertificate); - - result = mbedtls_x509_crt_parse(&mbedCertificate, Uint8::to_const_uchar(certificate.data()), certificate.size()); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - // check if certificate's notBefore timestamp is earlier than or equal to current time. - result = mbedtls_x509_time_is_past(&mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(valid_from)); - VerifyOrExit(result == 1, error = CHIP_ERROR_CERT_EXPIRED); - - // check if certificate's notAfter timestamp is later than current time. - result = mbedtls_x509_time_is_future(&mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(valid_to)); - VerifyOrExit(result == 1, error = CHIP_ERROR_CERT_EXPIRED); - -exit: - _log_mbedTLS_error(result); - mbedtls_x509_crt_free(&mbedCertificate); - -#else - (void) certificate; - CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; -#endif // defined(MBEDTLS_X509_CRT_PARSE_C) - - return error; -} - -CHIP_ERROR ExtractPubkeyFromX509Cert(const ByteSpan & certificate, Crypto::P256PublicKey & pubkey) -{ -#if defined(MBEDTLS_X509_CRT_PARSE_C) - CHIP_ERROR error = CHIP_NO_ERROR; - mbedtls_x509_crt mbed_cert; - mbedtls_ecp_keypair * keypair = nullptr; - size_t pubkey_size = 0; - - mbedtls_x509_crt_init(&mbed_cert); - - int result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - VerifyOrExit(mbedtls_pk_get_type(&(mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(pk))) == MBEDTLS_PK_ECKEY, - error = CHIP_ERROR_INVALID_ARGUMENT); - - keypair = mbedtls_pk_ec(mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(pk)); - VerifyOrExit(keypair->CHIP_CRYPTO_PAL_PRIVATE(grp).id == MapECPGroupId(pubkey.Type()), error = CHIP_ERROR_INVALID_ARGUMENT); - // Copy the public key from the cert in raw point format - result = - mbedtls_ecp_point_write_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair->CHIP_CRYPTO_PAL_PRIVATE(Q), - MBEDTLS_ECP_PF_UNCOMPRESSED, &pubkey_size, Uint8::to_uchar(pubkey.Bytes()), pubkey.Length()); - - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(pubkey_size == pubkey.Length(), error = CHIP_ERROR_INTERNAL); - -exit: - _log_mbedTLS_error(result); - mbedtls_x509_crt_free(&mbed_cert); - -#else - (void) certificate; - (void) pubkey; - CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; -#endif // defined(MBEDTLS_X509_CRT_PARSE_C) - - return error; -} - -namespace { - -CHIP_ERROR ExtractKIDFromX509Cert(bool extractSKID, const ByteSpan & certificate, MutableByteSpan & kid) -{ -#if defined(MBEDTLS_X509_CRT_PARSE_C) - CHIP_ERROR error = CHIP_ERROR_NOT_FOUND; - mbedtls_x509_crt mbed_cert; - unsigned char * p = nullptr; - const unsigned char * end = nullptr; - size_t len = 0; - - mbedtls_x509_crt_init(&mbed_cert); - - int result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - // TODO: The mbedTLS team is working on supporting SKID and AKID extensions processing. - // Once it is supported, this code should be updated. - - p = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(v3_ext).CHIP_CRYPTO_PAL_PRIVATE_X509(p); - end = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(v3_ext).CHIP_CRYPTO_PAL_PRIVATE_X509(p) + - mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(v3_ext).CHIP_CRYPTO_PAL_PRIVATE_X509(len); - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); - - while (p < end) - { - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OID); - VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); - - mbedtls_x509_buf extOID = { MBEDTLS_ASN1_OID, len, p }; - bool extractCurrentExtSKID = extractSKID && OID_CMP(sOID_Extension_SubjectKeyIdentifier, extOID); - bool extractCurrentExtAKID = !extractSKID && OID_CMP(sOID_Extension_AuthorityKeyIdentifier, extOID); - p += len; - - int is_critical = 0; - result = mbedtls_asn1_get_bool(&p, end, &is_critical); - VerifyOrExit(result == 0 || result == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG, error = CHIP_ERROR_WRONG_CERT_TYPE); - - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING); - VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); - - if (extractCurrentExtSKID || extractCurrentExtAKID) - { - if (extractCurrentExtSKID) - { - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING); - VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); - } - else - { - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); - VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); - result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONTEXT_SPECIFIC); - VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); - // Other optional fields, authorityCertIssuer and authorityCertSerialNumber, - // will be skipped if present. - } - VerifyOrExit(len == kSubjectKeyIdentifierLength, error = CHIP_ERROR_WRONG_CERT_TYPE); - VerifyOrExit(len <= kid.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(kid.data(), p, len); - if (kid.size() > len) - { - kid.reduce_size(len); - } - ExitNow(error = CHIP_NO_ERROR); - break; - } - p += len; - } - -exit: - _log_mbedTLS_error(result); - mbedtls_x509_crt_free(&mbed_cert); - -#else - (void) certificate; - (void) kid; - CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; -#endif // defined(MBEDTLS_X509_CRT_PARSE_C) - - return error; -} - -} // namespace - -CHIP_ERROR ExtractSKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan & skid) -{ - return ExtractKIDFromX509Cert(true, certificate, skid); -} - -CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan & akid) -{ - return ExtractKIDFromX509Cert(false, certificate, akid); -} - -CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCertVidPid & vidpid) -{ -#if defined(MBEDTLS_X509_CRT_PARSE_C) - CHIP_ERROR error = CHIP_NO_ERROR; - mbedtls_x509_crt mbed_cert; - mbedtls_asn1_named_data * dnIterator = nullptr; - AttestationCertVidPid vidpidFromCN; - - mbedtls_x509_crt_init(&mbed_cert); - - int result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - - for (dnIterator = &mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(subject); dnIterator != nullptr; - dnIterator = dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(next)) - { - DNAttrType attrType = DNAttrType::kUnspecified; - if (OID_CMP(sOID_AttributeType_CommonName, dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(oid))) - { - attrType = DNAttrType::kCommonName; - } - else if (OID_CMP(sOID_AttributeType_MatterVendorId, dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(oid))) - { - attrType = DNAttrType::kMatterVID; - } - else if (OID_CMP(sOID_AttributeType_MatterProductId, dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(oid))) - { - attrType = DNAttrType::kMatterPID; - } - - size_t val_len = dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(val).CHIP_CRYPTO_PAL_PRIVATE_X509(len); - uint8_t * val_p = dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(val).CHIP_CRYPTO_PAL_PRIVATE_X509(p); - error = ExtractVIDPIDFromAttributeString(attrType, ByteSpan(val_p, val_len), vidpid, vidpidFromCN); - SuccessOrExit(error); - } - - // If Matter Attributes were not found use values extracted from the CN Attribute, - // which might be uninitialized as well. - if (!vidpid.Initialized()) - { - vidpid = vidpidFromCN; - } - -exit: - _log_mbedTLS_error(result); - mbedtls_x509_crt_free(&mbed_cert); - -#else - (void) certificate; - (void) vidpid; - CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; -#endif // defined(MBEDTLS_X509_CRT_PARSE_C) - - return error; -} - -} // namespace Crypto -} // namespace chip diff --git a/src/platform/silabs/SiWx917/ConfigurationManagerImpl.cpp b/src/platform/silabs/SiWx917/ConfigurationManagerImpl.cpp index aad749374aa943..618b5a6a7703a8 100644 --- a/src/platform/silabs/SiWx917/ConfigurationManagerImpl.cpp +++ b/src/platform/silabs/SiWx917/ConfigurationManagerImpl.cpp @@ -19,7 +19,7 @@ /** * @file * Provides the implementation of the Device Layer ConfigurationManager object - * for EFR32 platforms using the Silicon Labs SDK. + * for SiWx917 platforms using the Silicon Labs SDK. */ /* this file behaves like a config.h, comes first */ #include @@ -30,7 +30,7 @@ #include #include -#include "em_rmu.h" +#include "core_cm4.h" #if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION #include "wfx_host_events.h" @@ -60,8 +60,6 @@ CHIP_ERROR ConfigurationManagerImpl::Init() IncreaseBootCount(); // It is possible to configure the possible reset sources with RMU_ResetControl // In this case, we keep Reset control at default setting - rebootCause = RMU_ResetCauseGet(); - RMU_ResetCauseClear(); err = CHIP_NO_ERROR; diff --git a/src/platform/silabs/SiWx917/ConnectivityManagerImpl.cpp b/src/platform/silabs/SiWx917/ConnectivityManagerImpl.cpp deleted file mode 100644 index c38a5e5bb1e268..00000000000000 --- a/src/platform/silabs/SiWx917/ConnectivityManagerImpl.cpp +++ /dev/null @@ -1,74 +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. - */ -/* this file behaves like a config.h, comes first */ -#include - -#include -#include -#include -#include - -#include - -#if INET_CONFIG_ENABLE_TCP_ENDPOINT -#include -#endif - -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include -#endif - -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#include -#endif - -using namespace ::chip; -using namespace ::chip::Inet; -using namespace ::chip::System; -using namespace ::chip::TLV; -using namespace ::chip::DeviceLayer::Internal; - -namespace chip { -namespace DeviceLayer { - -ConnectivityManagerImpl ConnectivityManagerImpl::sInstance; - -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); - -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 -} - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/silabs/SiWx917/Efr32OpaqueKeypair.h b/src/platform/silabs/SiWx917/Efr32OpaqueKeypair.h deleted file mode 100644 index 58123c106ed892..00000000000000 --- a/src/platform/silabs/SiWx917/Efr32OpaqueKeypair.h +++ /dev/null @@ -1,224 +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 { -namespace Internal { - -typedef uint16_t EFR32OpaqueKeyId; -constexpr EFR32OpaqueKeyId kEFR32OpaqueKeyIdUnknown = 0xFFFFU; // Do not modify, will impact existing deployments -constexpr EFR32OpaqueKeyId kEFR32OpaqueKeyIdVolatile = 0xFFFEU; // Do not modify, will impact existing deployments -constexpr EFR32OpaqueKeyId kEFR32OpaqueKeyIdPersistentMin = 0x0U; // Do not modify, will impact existing deployments -constexpr EFR32OpaqueKeyId kEFR32OpaqueKeyIdPersistentMax = 0x1FFU; // Do not decrease, will impact existing deployments - -enum class EFR32OpaqueKeyUsages : uint8_t -{ - ECDSA_P256_SHA256 = 0, - ECDH_P256 = 1, -}; - -/** - * @brief Base class for opaque keys - * - * Deriving from this class allows using it as a base class for operations - * which don't expose the private key independent of key size. - **/ -class EFR32OpaqueKeypair -{ -public: - EFR32OpaqueKeypair(); - virtual ~EFR32OpaqueKeypair(); - - /** - * @brief Load a keypair with given key ID - * - * If no key exists under the given ID, an error is returned - * and the object is unusable for operations. - * - * @param key_id key ID under which this key was created - * - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR Load(EFR32OpaqueKeyId key_id); - - /** - * @brief Create a new keypair with given ID and usage - * - * If a key already exists under the given ID, an error is returned - * and no new key is created. - * - * @param key_id key ID under which to store this key. Set to 0 - * for a non-persistent key which gets destructed - * when the lifetime of this object ends, or set - * to any other value to store the key under that - * ID. - * - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR Create(EFR32OpaqueKeyId key_id, EFR32OpaqueKeyUsages usage); - - /** - * @brief Get the public key for this keypair - * - * @param output Output buffer to put public key (in 0x04 || X || Y format) - * @param output_size Size of \p output - * @param output_length Amount of bytes put in \p output on success - * - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR GetPublicKey(uint8_t * output, size_t output_size, size_t * output_length) const; - - /** - * @brief Get the key ID for this keypair - * - * @return Returns kEFR32OpaqueKeyIdUnknown for an uninitialised/invalid - * key, kEFR32OpaqueKeyIdVolatile for a volatile key, and a key - * ID in the range [kEFR32OpaqueKeyIdPersistentMin, kEFR32OpaqueKeyIdPersistentMax] - * for valid persistent keys. - **/ - EFR32OpaqueKeyId GetKeyId() const; - - /** - * @brief Use this keypair to sign a message using the ECDSA-SHA256 algorithm - * - * @param msg Message buffer to sign - * @param msg_len Size of \p msg in bytes - * @param output Output buffer to write signature to. Signature - * is in raw format (i.e. binary concatenation of - * r and s) - * @param output_size Size of output buffer - * @param output_length Amount of bytes written into output buffer - * - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR Sign(const uint8_t * msg, size_t msg_len, uint8_t * output, size_t output_size, size_t * output_length) const; - - /** - * @brief Use this keypair to derive a key using the raw ECDH algorithm - * - * @param their_key Buffer containing raw uncompressed public key - * of party to derive with - * @param their_key_len Size of \p their_key in bytes - * @param output Output buffer to write derived bytes to - * @param output_size Size of output buffer - * @param output_length Amount of bytes written into output buffer - * - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR Derive(const uint8_t * their_key, size_t their_key_len, uint8_t * output, size_t output_size, - size_t * output_length) const; - - /** - * @brief Delete the keypair from storage - * - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR Delete(); - -protected: - void * mContext = nullptr; - bool mHasKey = false; - bool mIsPersistent = false; - uint8_t * mPubkeyRef = nullptr; - size_t mPubkeySize = 0; - size_t mPubkeyLength = 0; -}; - -/** - * @brief Derived class of P256Keypair for using opaque keys - * - * The signature and compiled form of this class is suboptimal due to how - * the P256Keypair isn't really an abstract interface, but rather partly - * interface / partly implementation. Future optimisation should look at - * converting P256Keypair to a fully abstract interface. - **/ -class EFR32OpaqueP256Keypair : public chip::Crypto::P256Keypair, public EFR32OpaqueKeypair -{ -public: - EFR32OpaqueP256Keypair(); - ~EFR32OpaqueP256Keypair() override; - - /** - * @brief Initialize the keypair. - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR Initialize() override; - - /** - * @brief Serialize the keypair (unsupported on opaque keys) - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR Serialize(chip::Crypto::P256SerializedKeypair & output) const override; - - /** - * @brief Deserialize the keypair (unsupported on opaque keys) - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR Deserialize(chip::Crypto::P256SerializedKeypair & input) override; - - /** - * @brief Generate a new Certificate Signing Request (CSR). - * @param csr Newly generated CSR in DER format - * @param csr_length The caller provides the length of input buffer (csr). The function returns the actual length of generated - *CSR. - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR NewCertificateSigningRequest(uint8_t * csr, size_t & csr_length) const override; - - /** - * @brief A function to sign a msg using ECDSA - * @param msg Message that needs to be signed - * @param msg_length Length of message - * @param out_signature Buffer that will hold the output signature. The signature consists of: 2 EC elements (r and s), - * in raw point form (see SEC1). - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, - chip::Crypto::P256ECDSASignature & out_signature) const override; - - /** - * @brief A function to derive a shared secret using ECDH - * - * This implements the CHIP_Crypto_ECDH(PrivateKey myPrivateKey, PublicKey theirPublicKey) cryptographic primitive - * from the specification, using this class's private key from `mKeypair` as `myPrivateKey` and the remote - * public key from `remote_public_key` as `theirPublicKey`. - * - * @param remote_public_key Public key of remote peer with which we are trying to establish secure channel. remote_public_key is - * ASN.1 DER encoded as padded big-endian field elements as described in SEC 1: Elliptic Curve Cryptography - * [https://www.secg.org/sec1-v2.pdf] - * @param out_secret Buffer to write out secret into. This is a byte array representing the x coordinate of the shared secret. - * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise - **/ - CHIP_ERROR ECDH_derive_secret(const chip::Crypto::P256PublicKey & remote_public_key, - chip::Crypto::P256ECDHDerivedSecret & out_secret) const override; - - /** @brief Return public key for the keypair. - **/ - const chip::Crypto::P256PublicKey & Pubkey() const override; - -private: - chip::Crypto::P256PublicKey mPubKey; -}; - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/silabs/SiWx917/Efr32PsaOpaqueKeypair.cpp b/src/platform/silabs/SiWx917/Efr32PsaOpaqueKeypair.cpp deleted file mode 100644 index ae9a0f66c13cad..00000000000000 --- a/src/platform/silabs/SiWx917/Efr32PsaOpaqueKeypair.cpp +++ /dev/null @@ -1,452 +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 "Efr32OpaqueKeypair.h" -#include "em_device.h" -#include - -#include -#include -#include -using chip::Platform::MemoryCalloc; -using chip::Platform::MemoryFree; - -using chip::Crypto::P256ECDHDerivedSecret; -using chip::Crypto::P256ECDSASignature; -using chip::Crypto::P256Keypair; -using chip::Crypto::P256PublicKey; -using chip::Crypto::P256SerializedKeypair; - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -/******************************************************************************* - * - * PSA key ID range for storing Matter Opaque keys - * - ******************************************************************************/ -#define PSA_KEY_ID_FOR_MATTER_MIN (0x00004400) -#define PSA_KEY_ID_FOR_MATTER_MAX (0x000045FF) -#define PSA_KEY_ID_FOR_MATTER_SIZE (PSA_KEY_ID_FOR_MATTER_MAX - PSA_KEY_ID_FOR_MATTER_MIN + 1) - -static_assert((kEFR32OpaqueKeyIdPersistentMax - kEFR32OpaqueKeyIdPersistentMin) < PSA_KEY_ID_FOR_MATTER_SIZE, - "Not enough PSA range to store all allowed opaque key IDs"); - -#if defined(SEMAILBOX_PRESENT) && (_SILICON_LABS_SECURITY_FEATURE == _SILICON_LABS_SECURITY_FEATURE_VAULT) -#define PSA_CRYPTO_LOCATION_FOR_DEVICE PSA_KEY_LOCATION_SL_SE_OPAQUE -#elif defined(CRYPTOACC_PRESENT) && defined(SEPUF_PRESENT) && defined(SL_TRUSTZONE_NONSECURE) -#define PSA_CRYPTO_LOCATION_FOR_DEVICE PSA_KEY_LOCATION_SL_CRYPTOACC_OPAQUE -#else -#define PSA_CRYPTO_LOCATION_FOR_DEVICE PSA_KEY_LOCATION_LOCAL_STORAGE -#endif - -static void _log_PSA_error(psa_status_t status) -{ - if (status != PSA_SUCCESS) - { - ChipLogError(Crypto, "PSA error: %ld", status); - } -} - -/******************************************************************************* - * - * PSA Crypto backed implementation of EFR32OpaqueKeypair - * - ******************************************************************************/ - -static bool is_opaque_key_valid(EFR32OpaqueKeyId id) -{ - if (id == kEFR32OpaqueKeyIdVolatile) - { - return true; - } - else if (id >= kEFR32OpaqueKeyIdPersistentMin && id <= (kEFR32OpaqueKeyIdPersistentMin + PSA_KEY_ID_FOR_MATTER_SIZE)) - { - return true; - } - - return false; -} - -static mbedtls_svc_key_id_t psa_key_id_from_opaque(EFR32OpaqueKeyId id) -{ - if (id == kEFR32OpaqueKeyIdVolatile || !is_opaque_key_valid(id)) - { - return 0; - } - - return PSA_KEY_ID_FOR_MATTER_MIN + (id - kEFR32OpaqueKeyIdPersistentMin); -} - -static EFR32OpaqueKeyId opaque_key_id_from_psa(mbedtls_svc_key_id_t id) -{ - if (id == 0) - { - return kEFR32OpaqueKeyIdVolatile; - } - else if (id >= PSA_KEY_ID_FOR_MATTER_MIN && id <= PSA_KEY_ID_FOR_MATTER_MAX) - { - return (id + kEFR32OpaqueKeyIdPersistentMin) - PSA_KEY_ID_FOR_MATTER_MIN; - } - else - { - return kEFR32OpaqueKeyIdUnknown; - } -} - -EFR32OpaqueKeypair::EFR32OpaqueKeypair() -{ - psa_crypto_init(); - // Avoid having a reference to PSA datatypes in the signature of this class - mContext = MemoryCalloc(1, sizeof(mbedtls_svc_key_id_t)); -} - -EFR32OpaqueKeypair::~EFR32OpaqueKeypair() -{ - // Free key resources - if (mContext != nullptr) - { - // Delete volatile keys, since nobody else can after we drop the key ID. - if (!mIsPersistent) - { - Delete(); - } - - MemoryFree(mContext); - mContext = nullptr; - } -} - -CHIP_ERROR EFR32OpaqueKeypair::Load(EFR32OpaqueKeyId opaque_id) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - mbedtls_svc_key_id_t key_id = 0; - - VerifyOrExit(opaque_id != kEFR32OpaqueKeyIdVolatile, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(is_opaque_key_valid(opaque_id), error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(mContext, error = CHIP_ERROR_INCORRECT_STATE); - - // If the object contains a volatile key, clean it up before reusing the object storage - if (mHasKey && !mIsPersistent) - { - Delete(); - } - - key_id = psa_key_id_from_opaque(opaque_id); - - status = psa_export_public_key(key_id, mPubkeyRef, mPubkeySize, &mPubkeyLength); - - if (status == PSA_ERROR_DOES_NOT_EXIST) - { - error = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; - goto exit; - } - - VerifyOrExit(status == PSA_SUCCESS, { - _log_PSA_error(status); - error = CHIP_ERROR_INTERNAL; - }); - - // Store the key ID and mark the key as valid - *(mbedtls_svc_key_id_t *) mContext = key_id; - mHasKey = true; - mIsPersistent = true; - -exit: - if (error != CHIP_NO_ERROR) - { - memset(mPubkeyRef, 0, mPubkeySize); - } - - return error; -} - -CHIP_ERROR EFR32OpaqueKeypair::Create(EFR32OpaqueKeyId opaque_id, EFR32OpaqueKeyUsages usage) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; - mbedtls_svc_key_id_t key_id = 0; - - VerifyOrExit(is_opaque_key_valid(opaque_id), error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(mContext, error = CHIP_ERROR_INCORRECT_STATE); - - if (opaque_id == kEFR32OpaqueKeyIdVolatile) - { - psa_set_key_lifetime( - &attr, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(PSA_KEY_LIFETIME_VOLATILE, PSA_CRYPTO_LOCATION_FOR_DEVICE)); - } - else - { - psa_key_handle_t key_handle; - - key_id = psa_key_id_from_opaque(opaque_id); - - // Check if the key already exists - int ret = psa_open_key(key_id, &key_handle); - if (PSA_SUCCESS == ret) - { - // WARNING: Existing key! This is caused by a problem in the key store. - // The key must be destroyed, otherwhise the device won't recover. - ChipLogError(Crypto, "WARNING: PSA key recycled: %d / %ld", opaque_id, key_id); - psa_destroy_key(key_id); - } - - psa_set_key_id(&attr, key_id); - psa_set_key_lifetime( - &attr, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(PSA_KEY_LIFETIME_PERSISTENT, PSA_CRYPTO_LOCATION_FOR_DEVICE)); - } - - switch (usage) - { - case EFR32OpaqueKeyUsages::ECDSA_P256_SHA256: - psa_set_key_type(&attr, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)); - psa_set_key_bits(&attr, 256); - psa_set_key_algorithm(&attr, PSA_ALG_ECDSA(PSA_ALG_SHA_256)); - // Need hash signing permissions because the CSR generation uses sign_hash internally - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_SIGN_HASH); - break; - case EFR32OpaqueKeyUsages::ECDH_P256: - psa_set_key_type(&attr, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)); - psa_set_key_bits(&attr, 256); - psa_set_key_algorithm(&attr, PSA_ALG_ECDH); - psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_DERIVE); - break; - } - - status = psa_generate_key(&attr, &key_id); - VerifyOrExit(status == PSA_SUCCESS, { - _log_PSA_error(status); - error = CHIP_ERROR_INTERNAL; - }); - - // Export the public key - status = psa_export_public_key(key_id, mPubkeyRef, mPubkeySize, &mPubkeyLength); - if (PSA_SUCCESS != status) - { - _log_PSA_error(status); - // Key generation succeeded, but pubkey export did not. To avoid - // memory leaks, delete the generated key before returning the error - psa_destroy_key(key_id); - error = CHIP_ERROR_INTERNAL; - goto exit; - } - - // Store the key ID and mark the key as valid - mHasKey = true; - mIsPersistent = opaque_id != kEFR32OpaqueKeyIdVolatile; - -exit: - psa_reset_key_attributes(&attr); - if (mContext) - { - if (CHIP_NO_ERROR == error) - { - *(mbedtls_svc_key_id_t *) mContext = key_id; - } - else - { - *(mbedtls_svc_key_id_t *) mContext = 0; - } - } - return error; -} - -CHIP_ERROR EFR32OpaqueKeypair::GetPublicKey(uint8_t * output, size_t output_size, size_t * output_length) const -{ - CHIP_ERROR error = CHIP_NO_ERROR; - VerifyOrExit(mHasKey, error = CHIP_ERROR_INCORRECT_STATE); - - if (output_size >= mPubkeyLength) - { - memcpy(output, mPubkeyRef, mPubkeyLength); - *output_length = mPubkeyLength; - } - else - { - error = CHIP_ERROR_BUFFER_TOO_SMALL; - } -exit: - return error; -} - -EFR32OpaqueKeyId EFR32OpaqueKeypair::GetKeyId() const -{ - if (!mHasKey) - { - return kEFR32OpaqueKeyIdUnknown; - } - - if (!mIsPersistent) - { - return kEFR32OpaqueKeyIdVolatile; - } - - return opaque_key_id_from_psa(*(mbedtls_svc_key_id_t *) mContext); -} - -CHIP_ERROR EFR32OpaqueKeypair::Sign(const uint8_t * msg, size_t msg_len, uint8_t * output, size_t output_size, - size_t * output_length) const -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - - VerifyOrExit(mContext, error = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mHasKey, error = CHIP_ERROR_INCORRECT_STATE); - - status = psa_sign_message(*(mbedtls_svc_key_id_t *) mContext, PSA_ALG_ECDSA(PSA_ALG_SHA_256), msg, msg_len, output, output_size, - output_length); - - VerifyOrExit(status == PSA_SUCCESS, { - _log_PSA_error(status); - error = CHIP_ERROR_INTERNAL; - }); - -exit: - return error; -} - -CHIP_ERROR EFR32OpaqueKeypair::Derive(const uint8_t * their_key, size_t their_key_len, uint8_t * output, size_t output_size, - size_t * output_length) const -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - - VerifyOrExit(mHasKey, error = CHIP_ERROR_INCORRECT_STATE); - - status = psa_raw_key_agreement(PSA_ALG_ECDH, *(mbedtls_svc_key_id_t *) mContext, their_key, their_key_len, output, output_size, - output_length); - - VerifyOrExit(status == PSA_SUCCESS, { - _log_PSA_error(status); - error = CHIP_ERROR_INTERNAL; - }); - -exit: - return error; -} - -CHIP_ERROR EFR32OpaqueKeypair::Delete() -{ - CHIP_ERROR error = CHIP_NO_ERROR; - psa_status_t status = PSA_ERROR_BAD_STATE; - - VerifyOrExit(mHasKey, error = CHIP_ERROR_INCORRECT_STATE); - - status = psa_destroy_key(*(mbedtls_svc_key_id_t *) mContext); - VerifyOrExit(status == PSA_SUCCESS, { - _log_PSA_error(status); - error = CHIP_ERROR_INTERNAL; - }); - -exit: - mHasKey = false; - mIsPersistent = false; - memset(mPubkeyRef, 0, mPubkeySize); - if (mContext) - { - *(mbedtls_svc_key_id_t *) mContext = 0; - } - return error; -} - -/******************************************************************************* - * - * PSA Crypto backed implementation of EFR32OpaqueP256Keypair - * - ******************************************************************************/ -EFR32OpaqueP256Keypair::EFR32OpaqueP256Keypair() -{ - mPubkeyRef = mPubKey.Bytes(); - mPubkeySize = mPubKey.Length(); - mPubkeyLength = 0; -} - -EFR32OpaqueP256Keypair::~EFR32OpaqueP256Keypair() {} - -CHIP_ERROR EFR32OpaqueP256Keypair::Initialize() -{ - if (mPubkeyLength > 0) - { - // already have a key - ECDH use case where CASESession is calling Initialize() - return CHIP_NO_ERROR; - } - - ChipLogError(Crypto, "Initialize() is invalid on opaque keys, use Create() instead"); - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR EFR32OpaqueP256Keypair::Serialize(P256SerializedKeypair & output) const -{ - ChipLogError(Crypto, "Serialisation is invalid on opaque keys, share the object instead"); - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR EFR32OpaqueP256Keypair::Deserialize(P256SerializedKeypair & input) -{ - ChipLogError(Crypto, "Serialisation is invalid on opaque keys"); - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR EFR32OpaqueP256Keypair::NewCertificateSigningRequest(uint8_t * out_csr, size_t & csr_length) const -{ - MutableByteSpan csr(out_csr, csr_length); - CHIP_ERROR err = GenerateCertificateSigningRequest(this, csr); - csr_length = (CHIP_NO_ERROR == err) ? csr.size() : 0; - return err; -} - -CHIP_ERROR EFR32OpaqueP256Keypair::ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, P256ECDSASignature & out_signature) const -{ - CHIP_ERROR error = CHIP_NO_ERROR; - size_t output_length = 0; - - VerifyOrExit((msg != nullptr) && (msg_length > 0), error = CHIP_ERROR_INVALID_ARGUMENT); - - error = Sign(msg, msg_length, out_signature.Bytes(), out_signature.Capacity(), &output_length); - - SuccessOrExit(error); - SuccessOrExit(out_signature.SetLength(output_length)); -exit: - return error; -} - -CHIP_ERROR EFR32OpaqueP256Keypair::ECDH_derive_secret(const P256PublicKey & remote_public_key, - P256ECDHDerivedSecret & out_secret) const -{ - CHIP_ERROR error = CHIP_NO_ERROR; - size_t output_length = 0; - - error = Derive(Uint8::to_const_uchar(remote_public_key), remote_public_key.Length(), Uint8::to_uchar(out_secret), - (out_secret.Length() == 0) ? out_secret.Capacity() : out_secret.Length(), &output_length); - - SuccessOrExit(error); - SuccessOrExit(out_secret.SetLength(output_length)); -exit: - return error; -} - -const P256PublicKey & EFR32OpaqueP256Keypair::Pubkey() const -{ - return mPubKey; -} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/silabs/SiWx917/Efr32PsaOperationalKeystore.cpp b/src/platform/silabs/SiWx917/Efr32PsaOperationalKeystore.cpp deleted file mode 100644 index e8fdf61ff1c903..00000000000000 --- a/src/platform/silabs/SiWx917/Efr32PsaOperationalKeystore.cpp +++ /dev/null @@ -1,455 +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 "Efr32PsaOperationalKeystore.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "Efr32OpaqueKeypair.h" -#include - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -static_assert((sizeof(FabricIndex) == 1), "Implementation is not prepared for large fabric indices"); -static_assert(SL_MATTER_MAX_STORED_OP_KEYS <= (kEFR32OpaqueKeyIdPersistentMax - kEFR32OpaqueKeyIdPersistentMin), - "Not enough opaque keys available to cover all requested operational keys"); -static_assert((CHIP_CONFIG_MAX_FABRICS + 1) <= SL_MATTER_MAX_STORED_OP_KEYS, - "Not enough operational keys requested to cover all potential fabrics (+1 staging for fabric update)"); -static_assert(SL_MATTER_MAX_STORED_OP_KEYS >= 1, "Minimum supported amount of operational keys is 1"); - -using namespace chip::Crypto; - -using chip::Platform::MemoryCalloc; -using chip::Platform::MemoryFree; - -Efr32PsaOperationalKeystore::~Efr32PsaOperationalKeystore() -{ - Deinit(); -} - -CHIP_ERROR Efr32PsaOperationalKeystore::Init() -{ - // Detect existing keymap size - CHIP_ERROR error = CHIP_NO_ERROR; - size_t wantedLen = SL_MATTER_MAX_STORED_OP_KEYS * sizeof(FabricIndex); - size_t existingLen = 0; - bool update_cache = false; - - if (SILABSConfig::ConfigValueExists(SILABSConfig::kConfigKey_OpKeyMap, existingLen)) - { - // There's a pre-existing key map on disk. Size the map to read it fully. - size_t outLen = 0; - - if (existingLen > (kEFR32OpaqueKeyIdPersistentMax - kEFR32OpaqueKeyIdPersistentMin) * sizeof(FabricIndex)) - { - return CHIP_ERROR_INTERNAL; - } - - // Upsize the map if the config was changed - if (existingLen < wantedLen) - { - existingLen = wantedLen; - } - - mKeyMap = (FabricIndex *) MemoryCalloc(1, existingLen); - VerifyOrExit(mKeyMap, error = CHIP_ERROR_NO_MEMORY); - - // Read the existing key map - error = SILABSConfig::ReadConfigValueBin(SILABSConfig::kConfigKey_OpKeyMap, (uint8_t *) mKeyMap, existingLen, outLen); - SuccessOrExit(error); - - // If upsizing, extend the map with undefined indices - for (size_t i = (outLen / sizeof(FabricIndex)); i < (existingLen / sizeof(FabricIndex)); i++) - { - mKeyMap[i] = kUndefinedFabricIndex; - } - - // If the config has changed, check whether it can be downsized fully or partially - if (existingLen > wantedLen) - { - size_t highest_found_index = 0; - for (size_t i = (wantedLen / sizeof(FabricIndex)); i < (existingLen / sizeof(FabricIndex)); i++) - { - if (mKeyMap[i] != kUndefinedFabricIndex) - { - highest_found_index = i; - } - } - - // set size to the smallest that will fit the upper opaque key ID in use - if (highest_found_index > 0) - { - existingLen = (highest_found_index + 1) * sizeof(FabricIndex); - update_cache = true; - } - } - - // Set the key map size - mKeyMapSize = existingLen; - } - else - { - // No key map on disk. Create and initialize a new one. - mKeyMap = (FabricIndex *) MemoryCalloc(1, wantedLen); - VerifyOrExit(mKeyMap, error = CHIP_ERROR_NO_MEMORY); - - for (size_t i = 0; i < (wantedLen / sizeof(FabricIndex)); i++) - { - mKeyMap[i] = kUndefinedFabricIndex; - } - - mKeyMapSize = wantedLen; - - update_cache = true; - } - - // Write-out keymap if needed - if (update_cache) - { - error = SILABSConfig::WriteConfigValueBin(SILABSConfig::kConfigKey_OpKeyMap, mKeyMap, mKeyMapSize); - SuccessOrExit(error); - } - - // Initialize cache key - mCachedKey = Platform::New(); - VerifyOrExit(mCachedKey, error = CHIP_ERROR_NO_MEMORY); - -exit: - if (error != CHIP_NO_ERROR) - { - Deinit(); - return error; - } - - mIsInitialized = true; - return CHIP_NO_ERROR; -} - -EFR32OpaqueKeyId Efr32PsaOperationalKeystore::FindKeyIdForFabric(FabricIndex fabricIndex) const -{ - // Search the map linearly to find a matching index slot - for (size_t i = 0; i < (mKeyMapSize / sizeof(FabricIndex)); i++) - { - if (mKeyMap[i] == fabricIndex) - { - // Found a match - return i + kEFR32OpaqueKeyIdPersistentMin; - } - } - - return kEFR32OpaqueKeyIdUnknown; -} - -bool Efr32PsaOperationalKeystore::HasOpKeypairForFabric(FabricIndex fabricIndex) const -{ - VerifyOrReturnError(mIsInitialized, false); - VerifyOrReturnError(IsValidFabricIndex(fabricIndex), false); - - // If there was a pending keypair, then there's really a usable key - if (mIsPendingKeypairActive && (fabricIndex == mPendingFabricIndex) && (mPendingKeypair != nullptr)) - { - return true; - } - - // Check whether we have a match in the map - if (FindKeyIdForFabric(fabricIndex) != kEFR32OpaqueKeyIdUnknown) - { - return true; - } - - return false; -} - -CHIP_ERROR Efr32PsaOperationalKeystore::NewOpKeypairForFabric(FabricIndex fabricIndex, - MutableByteSpan & outCertificateSigningRequest) -{ - CHIP_ERROR error = CHIP_NO_ERROR; - VerifyOrReturnError(mIsInitialized, CHIP_ERROR_WELL_UNINITIALIZED); - VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); - - // If a key is pending, we cannot generate for a different fabric index until we commit or revert. - if ((mPendingFabricIndex != kUndefinedFabricIndex) && (fabricIndex != mPendingFabricIndex)) - { - return CHIP_ERROR_INVALID_FABRIC_INDEX; - } - - VerifyOrReturnError(outCertificateSigningRequest.size() >= Crypto::kMAX_CSR_Length, CHIP_ERROR_BUFFER_TOO_SMALL); - - // Generate new key - EFR32OpaqueKeyId id = kEFR32OpaqueKeyIdUnknown; - - if (mPendingFabricIndex != kUndefinedFabricIndex) - { - // If we already have a pending key, delete it and put a new one in its place - id = mPendingKeypair->GetKeyId(); - if (id == kEFR32OpaqueKeyIdUnknown) - { - ResetPendingKey(); - } - else - { - mPendingKeypair->Delete(); - if (id == kEFR32OpaqueKeyIdVolatile) - { - id = kEFR32OpaqueKeyIdUnknown; - } - } - } - - if (id == kEFR32OpaqueKeyIdUnknown) - { - // Try to find an available opaque ID in the map - id = FindKeyIdForFabric(kUndefinedFabricIndex); - - if (!mPendingKeypair) - { - mPendingKeypair = Platform::New(); - } - } - - if (id == kEFR32OpaqueKeyIdUnknown) - { - // Could not find a free spot in the map - return CHIP_ERROR_NO_MEMORY; - } - - // Create new key on the old or found key ID - error = mPendingKeypair->Create(id, EFR32OpaqueKeyUsages::ECDSA_P256_SHA256); - if (error != CHIP_NO_ERROR) - { - ResetPendingKey(); - return error; - } - - // Set CSR and state - size_t csrLength = outCertificateSigningRequest.size(); - error = mPendingKeypair->NewCertificateSigningRequest(outCertificateSigningRequest.data(), csrLength); - if (error != CHIP_NO_ERROR) - { - ResetPendingKey(); - return error; - } - - outCertificateSigningRequest.reduce_size(csrLength); - mPendingFabricIndex = fabricIndex; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Efr32PsaOperationalKeystore::ActivateOpKeypairForFabric(FabricIndex fabricIndex, - const Crypto::P256PublicKey & nocPublicKey) -{ - VerifyOrReturnError(mIsInitialized, CHIP_ERROR_WELL_UNINITIALIZED); - VerifyOrReturnError(mPendingKeypair != nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX); - VerifyOrReturnError(IsValidFabricIndex(fabricIndex) && (fabricIndex == mPendingFabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); - - // Validate public key being activated matches last generated pending keypair - VerifyOrReturnError(mPendingKeypair->Pubkey().Matches(nocPublicKey), CHIP_ERROR_INVALID_PUBLIC_KEY); - - mIsPendingKeypairActive = true; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Efr32PsaOperationalKeystore::CommitOpKeypairForFabric(FabricIndex fabricIndex) -{ - VerifyOrReturnError(mIsInitialized, CHIP_ERROR_WELL_UNINITIALIZED); - VerifyOrReturnError(mPendingKeypair != nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX); - VerifyOrReturnError(IsValidFabricIndex(fabricIndex) && (fabricIndex == mPendingFabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); - VerifyOrReturnError(mIsPendingKeypairActive == true, CHIP_ERROR_INCORRECT_STATE); - - // Add key association to key map - EFR32OpaqueKeyId id = mPendingKeypair->GetKeyId(); - - if (id == kEFR32OpaqueKeyIdUnknown || id == kEFR32OpaqueKeyIdVolatile) - { - ResetPendingKey(); - return CHIP_ERROR_INTERNAL; - } - - // Guard against array out-of-bounds (should not happen with correctly initialised keys) - size_t keymap_index = id - kEFR32OpaqueKeyIdPersistentMin; - if (keymap_index >= (mKeyMapSize / sizeof(FabricIndex))) - { - return CHIP_ERROR_INTERNAL; - } - - if (mKeyMap[keymap_index] != kUndefinedFabricIndex) - { - ResetPendingKey(); - return CHIP_ERROR_INTERNAL; - } - - mKeyMap[keymap_index] = fabricIndex; - - // Persist key map - CHIP_ERROR error = SILABSConfig::WriteConfigValueBin(SILABSConfig::kConfigKey_OpKeyMap, mKeyMap, mKeyMapSize); - if (error != CHIP_NO_ERROR) - { - return error; - } - - // There's a good chance we'll need the key again soon - mCachedKey->Load(id); - - mPendingKeypair = nullptr; - mIsPendingKeypairActive = false; - mPendingFabricIndex = kUndefinedFabricIndex; - - return CHIP_NO_ERROR; -} - -CHIP_ERROR Efr32PsaOperationalKeystore::RemoveOpKeypairForFabric(FabricIndex fabricIndex) -{ - VerifyOrReturnError(mIsInitialized, CHIP_ERROR_WELL_UNINITIALIZED); - VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); - - // Remove pending keypair if we have it and the fabric ID matches - if ((mPendingKeypair != nullptr) && (fabricIndex == mPendingFabricIndex)) - { - RevertPendingKeypair(); - } - - EFR32OpaqueKeyId id = FindKeyIdForFabric(fabricIndex); - if (id == kEFR32OpaqueKeyIdUnknown) - { - // Fabric is not in the map, so assume it's gone already - return CHIP_NO_ERROR; - } - - // Guard against array out-of-bounds (should not happen with correctly initialised keys) - size_t keymap_index = id - kEFR32OpaqueKeyIdPersistentMin; - if (keymap_index >= (mKeyMapSize / sizeof(FabricIndex))) - { - return CHIP_ERROR_INTERNAL; - } - - // Reset the key mapping since we'll be deleting this key - mKeyMap[keymap_index] = kUndefinedFabricIndex; - - // Persist key map - CHIP_ERROR error = SILABSConfig::WriteConfigValueBin(SILABSConfig::kConfigKey_OpKeyMap, mKeyMap, mKeyMapSize); - if (error != CHIP_NO_ERROR) - { - return error; - } - - // Check if key is cached - EFR32OpaqueKeyId cachedId = mCachedKey->GetKeyId(); - - if (id == cachedId) - { - // Delete from persistent storage and unload - mCachedKey->Delete(); - return CHIP_NO_ERROR; - } - - // Load it for purposes of deletion - error = mCachedKey->Load(id); - if (error != CHIP_NO_ERROR && error != CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) - { - return CHIP_ERROR_INTERNAL; - } - - mCachedKey->Delete(); - - return CHIP_NO_ERROR; -} - -void Efr32PsaOperationalKeystore::RevertPendingKeypair() -{ - if (mIsInitialized) - { - // Just delete the pending key from storage - ResetPendingKey(); - } -} - -CHIP_ERROR Efr32PsaOperationalKeystore::SignWithOpKeypair(FabricIndex fabricIndex, const ByteSpan & message, - Crypto::P256ECDSASignature & outSignature) const -{ - VerifyOrReturnError(mIsInitialized, CHIP_ERROR_WELL_UNINITIALIZED); - VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); - - // Check to see whether the key is an activated pending key - if (mIsPendingKeypairActive && (fabricIndex == mPendingFabricIndex)) - { - VerifyOrReturnError(mPendingKeypair != nullptr, CHIP_ERROR_INTERNAL); - return mPendingKeypair->ECDSA_sign_msg(message.data(), message.size(), outSignature); - } - - // Figure out which key ID we're looking for - EFR32OpaqueKeyId id = FindKeyIdForFabric(fabricIndex); - - if (id == kEFR32OpaqueKeyIdUnknown) - { - // Fabric is not in the map, but the caller thinks it's there? - return CHIP_ERROR_INTERNAL; - } - - // Check whether we have the key in cache - EFR32OpaqueKeyId cachedId = mCachedKey->GetKeyId(); - - if (id == cachedId) - { - return mCachedKey->ECDSA_sign_msg(message.data(), message.size(), outSignature); - } - - // If not, we need to recreate from the backend - CHIP_ERROR error = mCachedKey->Load(id); - if (error != CHIP_NO_ERROR) - { - return CHIP_ERROR_INTERNAL; - } - - // Sign with retrieved key - error = mCachedKey->ECDSA_sign_msg(message.data(), message.size(), outSignature); - if (error != CHIP_NO_ERROR) - { - return CHIP_ERROR_INTERNAL; - } - - return CHIP_NO_ERROR; -} - -Crypto::P256Keypair * Efr32PsaOperationalKeystore::AllocateEphemeralKeypairForCASE() -{ - EFR32OpaqueP256Keypair * new_key = Platform::New(); - - if (new_key != nullptr) - { - new_key->Create(kEFR32OpaqueKeyIdVolatile, EFR32OpaqueKeyUsages::ECDH_P256); - } - - return new_key; -} - -void Efr32PsaOperationalKeystore::ReleaseEphemeralKeypair(Crypto::P256Keypair * keypair) -{ - Platform::Delete((EFR32OpaqueP256Keypair *) keypair); -} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/silabs/SiWx917/Efr32PsaOperationalKeystore.h b/src/platform/silabs/SiWx917/Efr32PsaOperationalKeystore.h deleted file mode 100644 index 4203724bd0dba7..00000000000000 --- a/src/platform/silabs/SiWx917/Efr32PsaOperationalKeystore.h +++ /dev/null @@ -1,145 +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 "Efr32OpaqueKeypair.h" -#include - -// Set SL_MATTER_MAX_STORED_OP_KEYS to the preferred size of the mapping table -// between fabric IDs and opaque key indices. It can not be less than -// CHIP_CONFIG_MAX_FABRICS + 1 (since there would be too few map elements to -// support all fabrics the application wants to support in addition to an extra -// pending key), but can be larger in case a consistent on-disk size of the map -// is required. -#ifndef SL_MATTER_MAX_STORED_OP_KEYS -#define SL_MATTER_MAX_STORED_OP_KEYS (CHIP_CONFIG_MAX_FABRICS + 1) -#endif - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -/** - * @brief OperationalKeystore implementation making use of the EFR32 SDK-provided - * storage mechanisms to load/store keypairs. - * - * WARNING: Ensure that any implementation that uses this one as a starting point - * DOES NOT have the raw key material (in usable form) passed up/down to - * direct storage APIs that may make copies on heap/stack without sanitization. - */ -class Efr32PsaOperationalKeystore : public chip::Crypto::OperationalKeystore -{ -public: - Efr32PsaOperationalKeystore(){}; - virtual ~Efr32PsaOperationalKeystore() override; - - // Non-copyable - Efr32PsaOperationalKeystore(Efr32PsaOperationalKeystore const &) = delete; - void operator=(Efr32PsaOperationalKeystore const &) = delete; - - /** - * @brief Initialize the Operational Keystore - */ - CHIP_ERROR Init(); - - bool HasPendingOpKeypair() const override { return (mPendingKeypair != nullptr); } - - bool HasOpKeypairForFabric(FabricIndex fabricIndex) const override; - CHIP_ERROR NewOpKeypairForFabric(FabricIndex fabricIndex, MutableByteSpan & outCertificateSigningRequest) override; - CHIP_ERROR ActivateOpKeypairForFabric(FabricIndex fabricIndex, const chip::Crypto::P256PublicKey & nocPublicKey) override; - CHIP_ERROR CommitOpKeypairForFabric(FabricIndex fabricIndex) override; - CHIP_ERROR RemoveOpKeypairForFabric(FabricIndex fabricIndex) override; - void RevertPendingKeypair() override; - CHIP_ERROR SignWithOpKeypair(FabricIndex fabricIndex, const ByteSpan & message, - chip::Crypto::P256ECDSASignature & outSignature) const override; - Crypto::P256Keypair * AllocateEphemeralKeypairForCASE() override; - void ReleaseEphemeralKeypair(chip::Crypto::P256Keypair * keypair) override; - -protected: - // The keymap maps PSA Crypto persistent key ID offsets against fabric IDs. - // The keymap is persisted in NVM3, and the keys are stored through the PSA - // API. - FabricIndex * mKeyMap = nullptr; - size_t mKeyMapSize = 0; - - // The key cache is to avoid having to reconstruct keys from the storage - // backend all the time (since it is rather slow). - EFR32OpaqueP256Keypair * mCachedKey = nullptr; - - // This pending fabric index is `kUndefinedFabricIndex` if there isn't a - // pending keypair override for a given fabric. - FabricIndex mPendingFabricIndex = kUndefinedFabricIndex; - EFR32OpaqueP256Keypair * mPendingKeypair = nullptr; - bool mIsPendingKeypairActive = false; - bool mIsInitialized = false; - -private: - void ResetPendingKey() - { - if (mPendingKeypair != nullptr) - { - mPendingKeypair->Delete(); - Platform::Delete(mPendingKeypair); - } - mPendingKeypair = nullptr; - mIsPendingKeypairActive = false; - mPendingFabricIndex = kUndefinedFabricIndex; - } - - void Deinit() - { - ResetPendingKey(); - - if (mCachedKey != nullptr) - { - Platform::Delete(mCachedKey); - mCachedKey = nullptr; - } - - if (mKeyMap != nullptr) - { - Platform::MemoryFree(mKeyMap); - mKeyMap = nullptr; - mKeyMapSize = 0; - } - - mIsInitialized = false; - } - - /** - * @brief Find the opaque key ID stored in the map for a given - * fabric ID. - * - * @param fabricIndex The fabric index to find the opaque key ID for. - * Can also be kUndefinedFabricIndex to find the first - * unoccupied key ID. - * - * @return a valid key ID on match, or kEFR32OpaqueKeyIdUnknown if no - * match is found. - */ - EFR32OpaqueKeyId FindKeyIdForFabric(FabricIndex fabricIndex) const; -}; - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/silabs/SiWx917/PlatformManagerImpl.cpp b/src/platform/silabs/SiWx917/PlatformManagerImpl.cpp index 25de6d51d164b2..8032c840210804 100644 --- a/src/platform/silabs/SiWx917/PlatformManagerImpl.cpp +++ b/src/platform/silabs/SiWx917/PlatformManagerImpl.cpp @@ -24,6 +24,7 @@ /* this file behaves like a config.h, comes first */ #include +#include #include #include #include @@ -42,6 +43,24 @@ namespace DeviceLayer { PlatformManagerImpl PlatformManagerImpl::sInstance; +static void app_get_random(uint8_t * aOutput, size_t aLen) +{ + size_t i; + + for (i = 0; i < aLen; i++) + { + aOutput[i] = rand(); + } +} + +static int app_entropy_source(void * data, unsigned char * output, size_t len, size_t * olen) +{ + app_get_random(reinterpret_cast(output), static_cast(len)); + *olen = len; + + return 0; +} + CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) { CHIP_ERROR err; @@ -57,6 +76,9 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) ReturnErrorOnFailure(System::Clock::InitClock_RealTime()); + // 16 : Threshold value + ReturnErrorOnFailure(chip::Crypto::add_entropy_source(app_entropy_source, NULL, 16)); + // Call _InitChipStack() on the generic implementation base class // to finish the initialization process. err = Internal::GenericPlatformManagerImpl_FreeRTOS::_InitChipStack(); diff --git a/src/platform/silabs/SiWx917/ThreadStackManagerImpl.cpp b/src/platform/silabs/SiWx917/ThreadStackManagerImpl.cpp deleted file mode 100644 index 16d792276644e4..00000000000000 --- a/src/platform/silabs/SiWx917/ThreadStackManagerImpl.cpp +++ /dev/null @@ -1,173 +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 - * Provides an implementation of the ThreadStackManager object for - * EFR32 platforms using the Silicon Labs SDK and the OpenThread - * stack. - * - */ -/* this file behaves like a config.h, comes first */ -#include - -#include -#include -#include -#include - -#include - -#include - -namespace chip { -namespace DeviceLayer { - -using namespace ::chip::DeviceLayer::Internal; - -ThreadStackManagerImpl ThreadStackManagerImpl::sInstance; - -CHIP_ERROR ThreadStackManagerImpl::_InitThreadStack(void) -{ - return InitThreadStack(NULL); -} - -CHIP_ERROR ThreadStackManagerImpl::InitThreadStack(otInstance * otInst) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - // Initialize the generic implementation base classes. - err = GenericThreadStackManagerImpl_FreeRTOS::DoInit(); - SuccessOrExit(err); - err = GenericThreadStackManagerImpl_OpenThread::DoInit(otInst); - SuccessOrExit(err); - -exit: - return err; -} - -bool ThreadStackManagerImpl::IsInitialized() -{ - return sInstance.mThreadStackLock != NULL; -} - -} // namespace DeviceLayer -} // namespace chip - -using namespace ::chip::DeviceLayer; - -/** - * Glue function called directly by the OpenThread stack when tasklet processing work - * is pending. - */ -extern "C" void otTaskletsSignalPending(otInstance * p_instance) -{ - ThreadStackMgrImpl().SignalThreadActivityPending(); -} - -/** - * Glue function called directly by the OpenThread stack when system event processing work - * is pending. - */ -extern "C" void otSysEventSignalPending(void) -{ - BaseType_t yieldRequired = ThreadStackMgrImpl().SignalThreadActivityPendingFromISR(); - portYIELD_FROM_ISR(yieldRequired); -} - -extern "C" void * otPlatCAlloc(size_t aNum, size_t aSize) -{ - return CHIPPlatformMemoryCalloc(aNum, aSize); -} - -extern "C" void otPlatFree(void * aPtr) -{ - CHIPPlatformMemoryFree(aPtr); -} - -extern "C" __WEAK void sl_openthread_init(void) -{ - // Place holder for enabling Silabs specific features available only through Simplicity Studio -} - -/** - * @brief Openthread UART implementation for the CLI is conflicting - * with the UART implemented for Pigweed RPC as they use the same UART port - * - * We now only build the uart as implemented in - * connectedhomeip/examples/platform/efr32/uart.c - * and remap OT functions to use our uart api. - * - * For now OT CLI isn't usable when the examples are built with pw_rpc - */ - -#ifndef PW_RPC_ENABLED -#include "uart.h" -#endif - -extern "C" otError otPlatUartEnable(void) -{ -#ifdef PW_RPC_ENABLED - return OT_ERROR_NOT_IMPLEMENTED; -#else - uartConsoleInit(); - return OT_ERROR_NONE; -#endif -} - -#if CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI - -extern "C" otError otPlatUartSend(const uint8_t * aBuf, uint16_t aBufLength) -{ -#ifdef PW_RPC_ENABLED - return OT_ERROR_NOT_IMPLEMENTED; -#else - if (uartConsoleWrite((const char *) aBuf, aBufLength) > 0) - { - otPlatUartSendDone(); - return OT_ERROR_NONE; - } - return OT_ERROR_FAILED; -#endif -} - -extern "C" void efr32UartProcess(void) -{ -#if !defined(PW_RPC_ENABLED) && !defined(ENABLE_CHIP_SHELL) - uint8_t tempBuf[128] = { 0 }; - // will read the data available up to 128bytes - uint16_t count = uartConsoleRead((char *) tempBuf, 128); - if (count > 0) - { - // ot process Received data for CLI cmds - otPlatUartReceived(tempBuf, count); - } -#endif -} - -extern "C" __WEAK otError otPlatUartFlush(void) -{ - return OT_ERROR_NOT_IMPLEMENTED; -} - -extern "C" __WEAK otError otPlatUartDisable(void) -{ - return OT_ERROR_NOT_IMPLEMENTED; -} - -#endif // CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI diff --git a/src/platform/silabs/SiWx917/args.gni b/src/platform/silabs/SiWx917/args.gni index 6e7ac8dcb49e51..4fa9a22d40ac18 100644 --- a/src/platform/silabs/SiWx917/args.gni +++ b/src/platform/silabs/SiWx917/args.gni @@ -16,7 +16,7 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") -import("${chip_root}/examples/platform/silabs/efr32/args.gni") +import("${chip_root}/examples/platform/silabs/SiWx917/args.gni") import("${chip_root}/src/crypto/crypto.gni") # ARM architecture flags will be set based on silabs_family. @@ -26,12 +26,7 @@ mbedtls_target = "${efr32_sdk_build_root}:efr32_sdk" openthread_external_mbedtls = mbedtls_target -# default to platform crypto implementation but allow commandline override -if (chip_crypto == "") { - chip_crypto = "platform" -} - -chip_device_platform = "efr32" +chip_device_platform = "SiWx917" #Net work configuration OpenThread lwip_platform = "efr32" @@ -44,7 +39,7 @@ chip_with_lwip = false chip_build_tests = false # Transitional CommissionableDataProvider not used anymore -# examples/platform/silabs/efr32/EFR32DeviceDataProvider is now used. +# examples/platform/silabs/SiWx917/SiWx917DeviceDataProvider is now used. chip_use_transitional_commissionable_data_provider = false openthread_root = "${chip_root}/third_party/openthread/ot-efr32/openthread" diff --git a/src/platform/silabs/SiWx917/bluetooth/rsi_ble_config.h b/src/platform/silabs/SiWx917/bluetooth/rsi_ble_config.h new file mode 100644 index 00000000000000..7849747dd28152 --- /dev/null +++ b/src/platform/silabs/SiWx917/bluetooth/rsi_ble_config.h @@ -0,0 +1,269 @@ +/******************************************************************************* + * @file rsi_ble_config.h + * @brief + ******************************************************************************* + * # License + * Copyright 2020 Silicon Laboratories Inc. www.silabs.com + ******************************************************************************* + * + * The licensor of this software is Silicon Laboratories Inc. Your use of this + * software is governed by the terms of Silicon Labs Master Software License + * Agreement (MSLA) available at + * www.silabs.com/about-us/legal/master-software-license-agreement. This + * software is distributed to you in Source Code format and is governed by the + * sections of the MSLA applicable to Source Code. + * + ******************************************************************************/ + +#ifndef RSI_BLE_CONFIG_H +#define RSI_BLE_CONFIG_H + +#include "rsi_ble_apis.h" +#include +/****************************************************** + * * Macros + * ******************************************************/ +//! application event list +#define RSI_BLE_CONN_EVENT 0x01 +#define RSI_BLE_DISCONN_EVENT 0x02 +#define RSI_BLE_GATT_WRITE_EVENT 0x03 +#define RSI_BLE_MTU_EVENT 0x04 +#define RSI_BLE_GATT_INDICATION_CONFIRMATION 0x05 +#define RSI_BLE_RESP_ATT_VALUE 0x06 +#define RSI_SSID 0x0D +#define RSI_SECTYPE 0x0E +#define RSI_BLE_WLAN_DISCONN_NOTIFY 0x0F +#define RSI_WLAN_ALREADY 0x10 +#define RSI_WLAN_NOT_ALREADY 0x11 +#define RSI_BLE_WLAN_TIMEOUT_NOTIFY 0x12 +#define RSI_BLE_WLAN_JOIN_STATUS 0x15 +#define RSI_APP_FW_VERSION 0x13 +#define RSI_BLE_WLAN_DISCONNECT_STATUS 0x14 + +#define RSI_REM_DEV_ADDR_LEN 18 +#define RSI_REM_DEV_NAME_LEN 31 + +#define RSI_BLE_DEV_NAME "CCP_DEVICE" +#define RSI_BLE_SET_RAND_ADDR "00:23:A7:12:34:56" + +#define CLEAR_WHITELIST 0x00 +#define ADD_DEVICE_TO_WHITELIST 0x01 +#define DELETE_DEVICE_FROM_WHITELIST 0x02 + +#define ALL_PHYS 0x00 + +#define RSI_BLE_DEV_ADDR_RESOLUTION_ENABLE 0 + +#define RSI_OPERMODE_WLAN_BLE 13 + +/***********************************************************************************************************************************************/ +//! Characteristic Presenatation Format Fields +/***********************************************************************************************************************************************/ +#define RSI_BLE_UINT8_FORMAT 0x04 +#define RSI_BLE_EXPONENT 0x00 +#define RSI_BLE_PERCENTAGE_UNITS_UUID 0x27AD +#define RSI_BLE_NAME_SPACE 0x01 +#define RSI_BLE_DESCRIPTION 0x010B + +//! BLE characteristic custom service uuid +#define RSI_BLE_CUSTOM_SERVICE_UUID 0xFFF6 +#define RSI_BLE_CUSTOM_LEVEL_UUID 0x1FF1 + +#ifdef RSI_M4_INTERFACE +#define RSI_BLE_MAX_NBR_ATT_REC 20 +#define RSI_BLE_MAX_NBR_SLAVES 1 +#define RSI_BLE_NUM_CONN_EVENTS 2 +#else +#define RSI_BLE_MAX_NBR_ATT_REC 80 +#define RSI_BLE_MAX_NBR_SLAVES 3 +#define RSI_BLE_NUM_CONN_EVENTS 20 +#endif + +#define RSI_BLE_MAX_NBR_ATT_SERV 10 + +#define RSI_BLE_MAX_NBR_MASTERS 1 +#define RSI_BLE_GATT_ASYNC_ENABLE 1 +#define RSI_BLE_GATT_INIT 0 + +#define RSI_BLE_START_SCAN 0x01 +#define RSI_BLE_STOP_SCAN 0x00 + +#define RSI_BLE_SCAN_TYPE SCAN_TYPE_ACTIVE +#define RSI_BLE_SCAN_FILTER_TYPE SCAN_FILTER_TYPE_ALL +/* Number of BLE GATT RECORD SIZE IN (n*16 BYTES), eg:(0x40*16)=1024 bytes */ +#define RSI_BLE_NUM_REC_BYTES 0x40 + +#define RSI_BLE_INDICATE_CONFIRMATION_FROM_HOST 0 + +/*=======================================================================*/ +//! Advertising command parameters +/*=======================================================================*/ + +#define RSI_BLE_ADV_TYPE UNDIR_CONN +#define RSI_BLE_ADV_FILTER_TYPE ALLOW_SCAN_REQ_ANY_CONN_REQ_ANY +#define RSI_BLE_ADV_DIR_ADDR_TYPE LE_PUBLIC_ADDRESS +#define RSI_BLE_ADV_DIR_ADDR "00:15:83:6A:64:17" + +#define RSI_BLE_ADV_INT_MIN 0x100 +#define RSI_BLE_ADV_INT_MAX 0x200 +#define RSI_BLE_ADV_CHANNEL_MAP 0x07 + +//! Advertise status +//! Start the advertising process +#define RSI_BLE_START_ADV 0x01 +//! Stop the advertising process +#define RSI_BLE_STOP_ADV 0x00 + +//! BLE Tx Power Index On Air +#define RSI_BLE_PWR_INX 30 + +//! BLE Active H/w Pwr Features +#define BLE_DISABLE_DUTY_CYCLING 0 +#define BLE_DUTY_CYCLING 1 +#define BLR_DUTY_CYCLING 2 +#define BLE_4X_PWR_SAVE_MODE 4 +#define RSI_BLE_PWR_SAVE_OPTIONS BLE_DISABLE_DUTY_CYCLING + +//! Advertise types + +/* Advertising will be visible(discoverable) to all the devices. + * Scanning/Connection is also accepted from all devices + * */ +#define UNDIR_CONN 0x80 + +/* Advertising will be visible(discoverable) to the particular device + * mentioned in RSI_BLE_ADV_DIR_ADDR only. + * Scanning and Connection will be accepted from that device only. + * */ +#define DIR_CONN 0x81 + +/* Advertising will be visible(discoverable) to all the devices. + * Scanning will be accepted from all the devices. + * Connection will be not be accepted from any device. + * */ +#define UNDIR_SCAN 0x82 + +/* Advertising will be visible(discoverable) to all the devices. + * Scanning and Connection will not be accepted from any device + * */ +#define UNDIR_NON_CONN 0x83 + +/* Advertising will be visible(discoverable) to the particular device + * mentioned in RSI_BLE_ADV_DIR_ADDR only. + * Scanning and Connection will be accepted from that device only. + * */ +#define DIR_CONN_LOW_DUTY_CYCLE 0x84 + +//! Advertising flags +#define LE_LIMITED_DISCOVERABLE 0x01 +#define LE_GENERAL_DISCOVERABLE 0x02 +#define LE_BR_EDR_NOT_SUPPORTED 0x04 + +//! Advertise filters +#define ALLOW_SCAN_REQ_ANY_CONN_REQ_ANY 0x00 +#define ALLOW_SCAN_REQ_WHITE_LIST_CONN_REQ_ANY 0x01 +#define ALLOW_SCAN_REQ_ANY_CONN_REQ_WHITE_LIST 0x02 +#define ALLOW_SCAN_REQ_WHITE_LIST_CONN_REQ_WHITE_LIST 0x03 + +//! Address types +#define LE_PUBLIC_ADDRESS 0x00 +#define LE_RANDOM_ADDRESS 0x01 +#define LE_RESOLVABLE_PUBLIC_ADDRESS 0x02 +#define LE_RESOLVABLE_RANDOM_ADDRESS 0x03 + +/*=======================================================================*/ + +/*=======================================================================*/ +//! Connection parameters +/*=======================================================================*/ +#define LE_SCAN_INTERVAL 0x0100 +#define LE_SCAN_WINDOW 0x0050 + +#define CONNECTION_INTERVAL_MIN 0x00A0 +#define CONNECTION_INTERVAL_MAX 0x00A0 + +#define CONNECTION_LATENCY 0x0000 +#define SUPERVISION_TIMEOUT 0x07D0 // 2000 + +/*=======================================================================*/ + +/*=======================================================================*/ +//! Scan command parameters +/*=======================================================================*/ + +#define SL_WFX_BLE_SCAN_TYPE SCAN_TYPE_ACTIVE +#define SL_WFX_BLE_SCAN_FILTER_TYPE SCAN_FILTER_TYPE_ALL + +//! Scan status +#define SL_WFX_BLE_START_SCAN 0x01 +#define SL_WFX_BLE_STOP_SCAN 0x00 + +//! Scan types +#define SCAN_TYPE_ACTIVE 0x01 +#define SCAN_TYPE_PASSIVE 0x00 + +//! Scan filters +#define SCAN_FILTER_TYPE_ALL 0x00 +#define SCAN_FILTER_TYPE_ONLY_WHITE_LIST 0x01 + +#define SL_WFX_SEL_INTERNAL_ANTENNA 0x00 +#define SL_WFX_SEL_EXTERNAL_ANTENNA 0x01 + +#define SL_WFX_BT_CTRL_REMOTE_USER_TERMINATED 0x4E13 +#define SL_WFX_BT_CTRL_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES 0x4E14 +#define SL_WFX_BT_CTRL_REMOTE_POWERING_OFF 0x4E15 +#define SL_WFX_BT_CTRL_TERMINATED_MIC_FAILURE 0x4E3D +#define SL_WFX_BT_FAILED_TO_ESTABLISH_CONN 0x4E3E +#define SL_WFX_BT_INVALID_RANGE 0x4E60 + +/***********************************************************************************************************************************************/ +//! RS9116 Firmware Configurations +/***********************************************************************************************************************************************/ + +/*=======================================================================*/ +//! Opermode command parameters +/*=======================================================================*/ +/* +#define RSI_FEATURE_BIT_MAP \ + (FEAT_ULP_GPIO_BASED_HANDSHAKE | FEAT_DEV_TO_HOST_ULP_GPIO_1) //! To set wlan feature select bit map +#define RSI_TCP_IP_BYPASS RSI_DISABLE //! TCP IP BYPASS feature check +#define RSI_TCP_IP_FEATURE_BIT_MAP \ + (TCP_IP_FEAT_DHCPV4_CLIENT) //! TCP/IP feature select bitmap for selecting TCP/IP features +#define RSI_EXT_TCPIP_FEATURE_BITMAP 0 + +#define RSI_CUSTOM_FEATURE_BIT_MAP FEAT_CUSTOM_FEAT_EXTENTION_VALID //! To set custom feature select bit map + +#define RSI_EXT_CUSTOM_FEATURE_BIT_MAP (EXT_FEAT_LOW_POWER_MODE | EXT_FEAT_XTAL_CLK_ENABLE | EXT_FEAT_384K_MODE) + +#define RSI_BT_FEATURE_BITMAP (BT_RF_TYPE | ENABLE_BLE_PROTOCOL) +*/ +/*=======================================================================*/ +//! Power save command parameters +/*=======================================================================*/ +//! set handshake type of power mode +//#define RSI_HAND_SHAKE_TYPE GPIO_BASED + +#define BLE_ATT_REC_SIZE 500 +#define NO_OF_VAL_ATT 5 //! Attribute value count + +/***********************************************************************************************************************************************/ +//! user defined structure +/***********************************************************************************************************************************************/ +typedef struct rsi_ble_att_list_s +{ + uuid_t char_uuid; + uint16_t handle; + uint16_t value_len; + uint16_t max_value_len; + uint8_t char_val_prop; + void * value; +} rsi_ble_att_list_t; +typedef struct rsi_ble_s +{ + uint8_t DATA[BLE_ATT_REC_SIZE]; + uint16_t DATA_ix; + uint16_t att_rec_list_count; + rsi_ble_att_list_t att_rec_list[NO_OF_VAL_ATT]; +} rsi_ble_t; + +#endif \ No newline at end of file diff --git a/src/platform/silabs/SiWx917/bluetooth/wfx_sl_ble_init.c b/src/platform/silabs/SiWx917/bluetooth/wfx_sl_ble_init.c new file mode 100644 index 00000000000000..115e5c16ffdcec --- /dev/null +++ b/src/platform/silabs/SiWx917/bluetooth/wfx_sl_ble_init.c @@ -0,0 +1,539 @@ +/******************************************************************************* + * @file wfx_sl_ble_init.c + * @brief + ******************************************************************************* + * # License + * Copyright 2021 Silicon Laboratories Inc. www.silabs.com + ******************************************************************************* + * + * The licensor of this software is Silicon Laboratories Inc. Your use of this + * software is governed by the terms of Silicon Labs Master Software License + * Agreement (MSLA) available at + * www.silabs.com/about-us/legal/master-software-license-agreement. This + * software is distributed to you in Source Code format and is governed by the + * sections of the MSLA applicable to Source Code. + * + ******************************************************************************/ +/************************************************************************* + * + */ + +/*================================================================================ +* @brief : This file contains example application for Wlan Station BLE +* Provisioning +* @section Description : +* This application explains how to get the WLAN connection functionality using +* BLE provisioning. +* Silicon Labs Module starts advertising and with BLE Provisioning the Access Point +* details are fetched. +* Silicon Labs device is configured as a WiFi station and connects to an Access Point. +=================================================================================*/ + +#include "wfx_sl_ble_init.h" +#include "rsi_ble_config.h" + +// application defines +rsi_ble_event_conn_status_t conn_event_to_app; +rsi_ble_t att_list; +sl_wfx_msg_t event_msg; + +// Memory to initialize driver +uint8_t bt_global_buf[BT_GLOBAL_BUFF_LEN]; +static uint8_t wfx_rsi_drv_buf[WFX_RSI_BUF_SZ]; +const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; + +/* Rsi driver Task will use as its stack */ +// StackType_t driverRsiTaskStack[WFX_RSI_WLAN_TASK_SZ] = { 0 }; + +/* Structure that will hold the TCB of the wfxRsi Task being created. */ +// StaticTask_t driverRsiTaskBuffer; + +StaticTask_t rsiBLETaskStruct; + +/* wfxRsi Task will use as its stack */ +StackType_t wfxBLETaskStack[WFX_RSI_TASK_SZ] = { 0 }; + +int32_t ble_rsi_task(void) +{ + int32_t status; + uint8_t buf[RSI_RESPONSE_HOLD_BUFF_SIZE]; + // extern void rsi_hal_board_init(void); + // + // WFX_RSI_LOG("%s: starting(HEAP_SZ = %d)", __func__, SL_HEAP_SIZE); + // + // //! Driver initialization + // status = rsi_driver_init(wfx_rsi_drv_buf, WFX_RSI_BUF_SZ); + // if ((status < RSI_DRIVER_STATUS) || (status > WFX_RSI_BUF_SZ)) + // { + // WFX_RSI_LOG("%s: error: RSI Driver initialization failed with status: %02x", __func__, status); + // return status; + // } + // + // WFX_RSI_LOG("%s: rsi_device_init", __func__); + // + // /* ! Redpine module intialisation */ + // if ((status = rsi_device_init(LOAD_NWP_FW)) != RSI_SUCCESS) + // { + // WFX_RSI_LOG("%s: error: rsi_device_init failed with status: %02x", __func__, status); + // return status; + // } + // WFX_RSI_LOG("%s: start wireless drv task", __func__); + // + // /* + // * Create the driver task + // */ + // wfx_rsi.drv_task = xTaskCreateStatic((TaskFunction_t) rsi_wireless_driver_task, "rsi_drv", WFX_RSI_WLAN_TASK_SZ, NULL, + // 1, driverRsiTaskStack, &driverRsiTaskBuffer); + // if (NULL == wfx_rsi.drv_task) + // { + // WFX_RSI_LOG("%s: error: Create the driver task failed", __func__); + // return RSI_ERROR_INVALID_PARAM; + // } + // + // /* Initialize WiSeConnect or Module features. */ + // WFX_RSI_LOG("%s: rsi_wireless_init", __func__); + // if ((status = rsi_wireless_init(OPER_MODE_0, RSI_OPERMODE_WLAN_BLE)) != RSI_SUCCESS) + // { + // WFX_RSI_LOG("%s: error: Initialize WiSeConnect failed with status: %02x", __func__, status); + // return status; + // } + // + // WFX_RSI_LOG("%s: get FW version..", __func__); + // + // /* + // * Get the MAC and other info to let the user know about it. + // */ + // if (rsi_wlan_get(RSI_FW_VERSION, buf, sizeof(buf)) != RSI_SUCCESS) + // { + // WFX_RSI_LOG("%s: error: rsi_wlan_get(RSI_FW_VERSION) failed with status: %02x", __func__, status); + // return status; + // } + // + // buf[sizeof(buf) - 1] = 0; + // WFX_RSI_LOG("%s: RSI firmware version: %s", __func__, buf); + // //! Send feature frame + // if ((status = rsi_send_feature_frame()) != RSI_SUCCESS) + // { + // WFX_RSI_LOG("%s: error: rsi_send_feature_frame failed with status: %02x", __func__, status); + // return status; + // } + // + // WFX_RSI_LOG("%s: sent rsi_send_feature_frame", __func__); + // /* initializes wlan radio parameters and WLAN supplicant parameters. + // */ + // (void) rsi_wlan_radio_init(); /* Required so we can get MAC address */ + // if ((status = rsi_wlan_get(RSI_MAC_ADDRESS, &wfx_rsi.sta_mac.octet[0], RESP_BUFF_SIZE)) != RSI_SUCCESS) + // { + // WFX_RSI_LOG("%s: error: rsi_wlan_get failed with status: %02x", __func__, status); + // return status; + // } + + // registering the GAP callback functions + rsi_ble_gap_register_callbacks(NULL, NULL, rsi_ble_on_disconnect_event, NULL, NULL, NULL, rsi_ble_on_enhance_conn_status_event, + NULL, NULL, NULL); + + // registering the GATT call back functions + rsi_ble_gatt_register_callbacks(NULL, NULL, NULL, NULL, NULL, NULL, NULL, rsi_ble_on_gatt_write_event, NULL, NULL, NULL, + rsi_ble_on_mtu_event, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + rsi_ble_on_event_indication_confirmation, NULL); + + WFX_RSI_LOG("registering rsi_ble_add_service"); + + // Exchange of GATT info with BLE stack + rsi_ble_add_matter_service(); + + // initializing the application events map + rsi_ble_app_init_events(); + + wfx_rsi.ble_task = xTaskCreateStatic((TaskFunction_t) rsi_ble_event_handling_task, "rsi_ble", WFX_RSI_TASK_SZ, NULL, 2, + wfxBLETaskStack, &rsiBLETaskStruct); + WFX_RSI_LOG("%s: rsi_task_suspend init_task ", __func__); + if (wfx_rsi.ble_task == NULL) + { + WFX_RSI_LOG("%s: error: failed to create ble task.", __func__); + } + + WFX_RSI_LOG("%s complete", __func__); + // rsi_task_destroy((rsi_task_handle_t *)wfx_rsi.init_task); + return RSI_SUCCESS; +} + +/*==============================================*/ +/** + * @fn rsi_ble_app_init_events + * @brief initializes the event parameter. + * @param[in] none. + * @return none. + * @section description + * This function is used during BLE initialization. + */ +void rsi_ble_app_init_events() +{ + event_msg.ble_app_event_map = 0; + event_msg.ble_app_event_mask = 0xFFFFFFFF; + event_msg.ble_app_event_mask = event_msg.ble_app_event_mask; // To suppress warning while compiling + WFX_RSI_LOG("Function :: rsi_ble_app_init_events"); + return; +} + +/*==============================================*/ +/** + * @fn rsi_ble_app_clear_event + * @brief clears the specific event. + * @param[in] event_num, specific event number. + * @return none. + * @section description + * This function is used to clear the specific event. + */ +void rsi_ble_app_clear_event(uint32_t event_num) +{ + event_msg.event_num = event_num; + event_msg.ble_app_event_map &= ~BIT(event_num); + return; +} + +/*==============================================*/ +/** + * @fn rsi_ble_on_mtu_event + * @brief its invoked when mtu exhange event is received. + * @param[in] rsi_ble_mtu, mtu event paramaters. + * @return none. + * @section description + * This callback function is invoked when mtu exhange event is received + */ +void rsi_ble_on_mtu_event(rsi_ble_event_mtu_t * rsi_ble_mtu) +{ + WFX_RSI_LOG(" RSI_BLE : rsi_ble_on_mtu_event"); + memset(&event_msg.rsi_ble_mtu, 0, sizeof(rsi_ble_event_mtu_t)); + memcpy(&event_msg.rsi_ble_mtu, rsi_ble_mtu, sizeof(rsi_ble_event_mtu_t)); + rsi_ble_app_set_event(RSI_BLE_MTU_EVENT); +} + +/*==============================================*/ +/** + * @fn rsi_ble_on_gatt_write_event + * @brief its invoked when write/notify/indication events are received. + * @param[in] event_id, it indicates write/notification event id. + * @param[in] rsi_ble_write, write event parameters. + * @return none. + * @section description + * This callback function is invoked when write/notify/indication events are received + */ +void rsi_ble_on_gatt_write_event(uint16_t event_id, rsi_ble_event_write_t * rsi_ble_write) +{ + WFX_RSI_LOG(" RSI_BLE : rsi_ble_on_gatt_write_event"); + memset(&event_msg.rsi_ble_write, 0, sizeof(rsi_ble_event_write_t)); + event_msg.event_id = event_id; + memcpy(&event_msg.rsi_ble_write, rsi_ble_write, sizeof(rsi_ble_event_write_t)); + rsi_ble_app_set_event(RSI_BLE_GATT_WRITE_EVENT); +} + +/*==============================================*/ +/** + * @fn rsi_ble_on_enhance_conn_status_event + * @brief invoked when enhanced connection complete event is received + * @param[out] resp_conn, connected remote device information + * @return none. + * @section description + * This callback function indicates the status of the connection + */ +void rsi_ble_on_enhance_conn_status_event(rsi_ble_event_enhance_conn_status_t * resp_enh_conn) +{ + WFX_RSI_LOG(" RSI_BLE : rsi_ble_on_enhance_conn_status_event"); + event_msg.connectionHandle = 1; + event_msg.bondingHandle = 255; + memcpy(event_msg.resp_enh_conn.dev_addr, resp_enh_conn->dev_addr, RSI_DEV_ADDR_LEN); + rsi_ble_app_set_event(RSI_BLE_CONN_EVENT); +} + +/*==============================================*/ +/** + * @fn rsi_ble_on_disconnect_event + * @brief invoked when disconnection event is received + * @param[in] resp_disconnect, disconnected remote device information + * @param[in] reason, reason for disconnection. + * @return none. + * @section description + * This callback function indicates disconnected device information and status + */ +void rsi_ble_on_disconnect_event(rsi_ble_event_disconnect_t * resp_disconnect, uint16_t reason) +{ + WFX_RSI_LOG(" RSI_BLE : rsi_ble_on_disconnect_event"); + event_msg.reason = reason; + memcpy(event_msg.resp_disconnect, resp_disconnect, sizeof(rsi_ble_event_disconnect_t)); + rsi_ble_app_set_event(RSI_BLE_DISCONN_EVENT); +} + +/*==============================================*/ +/** + * @fn rsi_ble_on_event_indication_confirmation + * @brief this function will invoke when received indication confirmation event + * @param[out] resp_id, response id + * @param[out] status, status of the response + * @return none + * @section description + */ +void rsi_ble_on_event_indication_confirmation(uint16_t resp_status, rsi_ble_set_att_resp_t * rsi_ble_event_set_att_rsp) +{ + WFX_RSI_LOG(" RSI_BLE : rsi_ble_on_event_indication_confirmation"); + event_msg.resp_status = resp_status; + memcpy(&event_msg.rsi_ble_event_set_att_rsp, rsi_ble_event_set_att_rsp, sizeof(rsi_ble_set_att_resp_t)); + rsi_ble_app_set_event(RSI_BLE_GATT_INDICATION_CONFIRMATION); +} + +/*==============================================*/ +/** + * @fn rsi_ble_app_get_event + * @brief returns the first set event based on priority + * @param[in] none. + * @return int32_t + * > 0 = event number + * -1 = not received any event + * @section description + * This function returns the highest priority event among all the set events + */ +int32_t rsi_ble_app_get_event(void) +{ + uint32_t ix; + + for (ix = 0; ix < 32; ix++) + { + if (event_msg.ble_app_event_map & (1 << ix)) + { + return ix; + } + } + + return (-1); +} + +/*==============================================*/ +/** + * @fn rsi_ble_app_set_event + * @brief set the specific event. + * @param[in] event_num, specific event number. + * @return none. + * @section description + * This function is used to set/raise the specific event. + */ +void rsi_ble_app_set_event(uint32_t event_num) +{ + event_msg.ble_app_event_map |= BIT(event_num); + return; +} + +/*==============================================*/ +/** + * @fn rsi_gatt_add_attribute_to_list + * @brief This function is used to store characteristic service attribute. + * @param[in] p_val, pointer to homekit structure + * @param[in] handle, characteristic service attribute handle. + * @param[in] data_len, characteristic value length + * @param[in] data, characteristic value pointer + * @param[in] uuid, characteristic value uuid + * @return none. + * @section description + * This function is used to store all attribute records + */ +void rsi_gatt_add_attribute_to_list(rsi_ble_t * p_val, uint16_t handle, uint16_t data_len, uint8_t * data, uuid_t uuid, + uint8_t char_prop) +{ + if ((p_val->DATA_ix + data_len) >= BLE_ATT_REC_SIZE) + { //! Check for max data length for the characteristic value + LOG_PRINT("\r\n no data memory for att rec values \r\n"); + return; + } + + p_val->att_rec_list[p_val->att_rec_list_count].char_uuid = uuid; + p_val->att_rec_list[p_val->att_rec_list_count].handle = handle; + p_val->att_rec_list[p_val->att_rec_list_count].value_len = data_len; + p_val->att_rec_list[p_val->att_rec_list_count].max_value_len = data_len; + p_val->att_rec_list[p_val->att_rec_list_count].char_val_prop = char_prop; + memcpy(p_val->DATA + p_val->DATA_ix, data, data_len); + p_val->att_rec_list[p_val->att_rec_list_count].value = p_val->DATA + p_val->DATA_ix; + p_val->att_rec_list_count++; + p_val->DATA_ix += p_val->att_rec_list[p_val->att_rec_list_count].max_value_len; + + return; +} + +/*==============================================*/ +/** + * @fn rsi_ble_add_char_serv_att + * @brief this function is used to add characteristic service attribute.. + * @param[in] serv_handler, service handler. + * @param[in] handle, characteristic service attribute handle. + * @param[in] val_prop, characteristic value property. + * @param[in] att_val_handle, characteristic value handle + * @param[in] att_val_uuid, characteristic value uuid + * @return none. + * @section description + * This function is used at application to add characteristic attribute + */ +void rsi_ble_add_char_serv_att(void * serv_handler, uint16_t handle, uint8_t val_prop, uint16_t att_val_handle, uuid_t att_val_uuid) +{ + rsi_ble_req_add_att_t new_att = { 0 }; + + //! preparing the attribute service structure + new_att.serv_handler = serv_handler; + new_att.handle = handle; + new_att.att_uuid.size = 2; + new_att.att_uuid.val.val16 = RSI_BLE_CHAR_SERV_UUID; + new_att.property = RSI_BLE_ATT_PROPERTY_READ; + + //! preparing the characteristic attribute value + new_att.data_len = att_val_uuid.size + 4; + new_att.data[0] = val_prop; + rsi_uint16_to_2bytes(&new_att.data[2], att_val_handle); + if (new_att.data_len == 6) + { + rsi_uint16_to_2bytes(&new_att.data[4], att_val_uuid.val.val16); + } + else if (new_att.data_len == 8) + { + rsi_uint32_to_4bytes(&new_att.data[4], att_val_uuid.val.val32); + } + else if (new_att.data_len == 20) + { + memcpy(&new_att.data[4], &att_val_uuid.val.val128, att_val_uuid.size); + } + //! Add attribute to the service + rsi_ble_add_attribute(&new_att); + + return; +} + +/*==============================================*/ +/** + * @fn rsi_ble_add_char_val_att + * @brief this function is used to add characteristic value attribute. + * @param[in] serv_handler, new service handler. + * @param[in] handle, characteristic value attribute handle. + * @param[in] att_type_uuid, attribute uuid value. + * @param[in] val_prop, characteristic value property. + * @param[in] data, characteristic value data pointer. + * @param[in] data_len, characteristic value length. + * @return none. + * @section description + * This function is used at application to create new service. + */ + +void rsi_ble_add_char_val_att(void * serv_handler, uint16_t handle, uuid_t att_type_uuid, uint8_t val_prop, uint8_t * data, + uint8_t data_len, uint8_t auth_read) +{ + rsi_ble_req_add_att_t new_att = { 0 }; + + memset(&new_att, 0, sizeof(rsi_ble_req_add_att_t)); + //! preparing the attributes + new_att.serv_handler = serv_handler; + new_att.handle = handle; + new_att.config_bitmap = auth_read; + memcpy(&new_att.att_uuid, &att_type_uuid, sizeof(uuid_t)); + new_att.property = val_prop; + + if (data != NULL) + memcpy(new_att.data, data, RSI_MIN(sizeof(new_att.data), data_len)); + + //! preparing the attribute value + new_att.data_len = data_len; + + //! add attribute to the service + rsi_ble_add_attribute(&new_att); + + if ((auth_read == ATT_REC_MAINTAIN_IN_HOST) || (data_len > 20)) + { + if (data != NULL) + { + rsi_gatt_add_attribute_to_list(&att_list, handle, data_len, data, att_type_uuid, val_prop); + } + } + + //! check the attribute property with notification/Indication + if ((val_prop & RSI_BLE_ATT_PROPERTY_NOTIFY) || (val_prop & RSI_BLE_ATT_PROPERTY_INDICATE)) + { + //! if notification/indication property supports then we need to add client characteristic service. + + //! preparing the client characteristic attribute & values + memset(&new_att, 0, sizeof(rsi_ble_req_add_att_t)); + new_att.serv_handler = serv_handler; + new_att.handle = handle + 1; + new_att.att_uuid.size = 2; + new_att.att_uuid.val.val16 = RSI_BLE_CLIENT_CHAR_UUID; + new_att.property = RSI_BLE_ATT_PROPERTY_READ | RSI_BLE_ATT_PROPERTY_WRITE; + new_att.data_len = 2; + + //! add attribute to the service + rsi_ble_add_attribute(&new_att); + } + + return; +} + +/*==============================================*/ +/** + * @fn rsi_ble_add_matter_service + * @brief this function is used to add service for matter + * @return status (uint32_t) 0 for success. + * @section description + * This function is used at application to create new service. + */ + +uint32_t rsi_ble_add_matter_service(void) +{ + uuid_t custom_service = { RSI_BLE_MATTER_CUSTOM_SERVICE_UUID }; + custom_service.size = RSI_BLE_MATTER_CUSTOM_SERVICE_SIZE; + custom_service.val.val16 = RSI_BLE_MATTER_CUSTOM_SERVICE_VALUE_16; + uint8_t data[230] = { RSI_BLE_MATTER_CUSTOM_SERVICE_DATA }; + + static const uuid_t custom_characteristic_RX = { .size = RSI_BLE_CUSTOM_CHARACTERISTIC_RX_SIZE, + .reserved = { RSI_BLE_CUSTOM_CHARACTERISTIC_RX_RESERVED }, + .val.val128.data1 = RSI_BLE_CUSTOM_CHARACTERISTIC_RX_VALUE_128_DATA_1, + .val.val128.data2 = RSI_BLE_CUSTOM_CHARACTERISTIC_RX_VALUE_128_DATA_2, + .val.val128.data3 = RSI_BLE_CUSTOM_CHARACTERISTIC_RX_VALUE_128_DATA_3, + .val.val128.data4 = { RSI_BLE_CUSTOM_CHARACTERISTIC_RX_VALUE_128_DATA_4 } }; + + rsi_ble_resp_add_serv_t new_serv_resp = { 0 }; + rsi_ble_add_service(custom_service, &new_serv_resp); + + // Adding custom characteristic declaration to the custom service + rsi_ble_add_char_serv_att( + new_serv_resp.serv_handler, new_serv_resp.start_handle + RSI_BLE_CHARACTERISTIC_RX_ATTRIBUTE_HANDLE_LOCATION, + RSI_BLE_ATT_PROPERTY_WRITE | RSI_BLE_ATT_PROPERTY_READ, // Set read, write, write without response + new_serv_resp.start_handle + RSI_BLE_CHARACTERISTIC_RX_VALUE_HANDLE_LOCATION, custom_characteristic_RX); + + // Adding characteristic value attribute to the service + rsi_ble_add_char_val_att(new_serv_resp.serv_handler, + new_serv_resp.start_handle + RSI_BLE_CHARACTERISTIC_RX_VALUE_HANDLE_LOCATION, custom_characteristic_RX, + RSI_BLE_ATT_PROPERTY_WRITE | RSI_BLE_ATT_PROPERTY_READ, // Set read, write, write without response + data, sizeof(data), ATT_REC_IN_HOST); + + static const uuid_t custom_characteristic_TX = { .size = RSI_BLE_CUSTOM_CHARACTERISTIC_TX_SIZE, + .reserved = { RSI_BLE_CUSTOM_CHARACTERISTIC_TX_RESERVED }, + .val.val128.data1 = RSI_BLE_CUSTOM_CHARACTERISTIC_TX_VALUE_128_DATA_1, + .val.val128.data2 = RSI_BLE_CUSTOM_CHARACTERISTIC_TX_VALUE_128_DATA_2, + .val.val128.data3 = RSI_BLE_CUSTOM_CHARACTERISTIC_TX_VALUE_128_DATA_3, + .val.val128.data4 = { RSI_BLE_CUSTOM_CHARACTERISTIC_TX_VALUE_128_DATA_4 } }; + + // Adding custom characteristic declaration to the custom service + rsi_ble_add_char_serv_att( + new_serv_resp.serv_handler, new_serv_resp.start_handle + RSI_BLE_CHARACTERISTIC_TX_ATTRIBUTE_HANDLE_LOCATION, + RSI_BLE_ATT_PROPERTY_WRITE_NO_RESPONSE | RSI_BLE_ATT_PROPERTY_WRITE | RSI_BLE_ATT_PROPERTY_READ | + RSI_BLE_ATT_PROPERTY_NOTIFY | RSI_BLE_ATT_PROPERTY_INDICATE, // Set read, write, write without response + new_serv_resp.start_handle + RSI_BLE_CHARACTERISTIC_TX_MEASUREMENT_HANDLE_LOCATION, custom_characteristic_TX); + + // Adding characteristic value attribute to the service + event_msg.rsi_ble_measurement_hndl = new_serv_resp.start_handle + RSI_BLE_CHARACTERISTIC_TX_MEASUREMENT_HANDLE_LOCATION; + + // Adding characteristic value attribute to the service + event_msg.rsi_ble_gatt_server_client_config_hndl = + new_serv_resp.start_handle + RSI_BLE_CHARACTERISTIC_TX_GATT_SERVER_CLIENT_HANDLE_LOCATION; + + rsi_ble_add_char_val_att(new_serv_resp.serv_handler, event_msg.rsi_ble_measurement_hndl, custom_characteristic_TX, + RSI_BLE_ATT_PROPERTY_WRITE_NO_RESPONSE | RSI_BLE_ATT_PROPERTY_WRITE | RSI_BLE_ATT_PROPERTY_READ | + RSI_BLE_ATT_PROPERTY_NOTIFY | + RSI_BLE_ATT_PROPERTY_INDICATE, // Set read, write, write without response + data, sizeof(data), ATT_REC_MAINTAIN_IN_HOST); + + memset(&data, 0, sizeof(data)); + return 0; +} \ No newline at end of file diff --git a/src/platform/silabs/SiWx917/bluetooth/wfx_sl_ble_init.h b/src/platform/silabs/SiWx917/bluetooth/wfx_sl_ble_init.h new file mode 100644 index 00000000000000..497d2b5ee33bfe --- /dev/null +++ b/src/platform/silabs/SiWx917/bluetooth/wfx_sl_ble_init.h @@ -0,0 +1,121 @@ +/******************************************************************************* + * @file wfx_sl_ble_init.h + * @brief + ******************************************************************************* + * # License + * Copyright 2021 Silicon Laboratories Inc. www.silabs.com + ******************************************************************************* + * + * The licensor of this software is Silicon Laboratories Inc. Your use of this + * software is governed by the terms of Silicon Labs Master Software License + * Agreement (MSLA) available at + * www.silabs.com/about-us/legal/master-software-license-agreement. This + * software is distributed to you in Source Code format and is governed by the + * sections of the MSLA applicable to Source Code. + * + ******************************************************************************/ +/************************************************************************* + * + */ + +/** + * Include files + * */ + +#ifndef WFX_SL_BLE_INIT +#define WFX_SL_BLE_INIT +#define RSI_BLE_ENABLE 1 + +// BLE include file to refer BLE APIs +#include "FreeRTOS.h" +#include "event_groups.h" +#include "rsi_ble_config.h" +#include "task.h" +#include "timers.h" +#include "wfx_host_events.h" +#include "wfx_rsi.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef RSI_M4_INTERFACE +#include "rsi_board.h" +#endif + +#define ATT_REC_IN_HOST 0 + +#define RSI_BLE_MATTER_CUSTOM_SERVICE_UUID 0 +#define RSI_BLE_MATTER_CUSTOM_SERVICE_SIZE 2 +#define RSI_BLE_MATTER_CUSTOM_SERVICE_VALUE_16 0xFFF6 +#define RSI_BLE_MATTER_CUSTOM_SERVICE_DATA 0x00 + +#define RSI_BLE_CUSTOM_CHARACTERISTIC_RX_SIZE 16 +#define RSI_BLE_CUSTOM_CHARACTERISTIC_RX_RESERVED 0x00, 0x00, 0x00 +#define RSI_BLE_CUSTOM_CHARACTERISTIC_RX_VALUE_128_DATA_1 0x18EE2EF5 +#define RSI_BLE_CUSTOM_CHARACTERISTIC_RX_VALUE_128_DATA_2 0x263D +#define RSI_BLE_CUSTOM_CHARACTERISTIC_RX_VALUE_128_DATA_3 0x4559 +#define RSI_BLE_CUSTOM_CHARACTERISTIC_RX_VALUE_128_DATA_4 0x9F, 0x95, 0x9C, 0x4F, 0x11, 0x9D, 0x9F, 0x42 +#define RSI_BLE_CHARACTERISTIC_RX_ATTRIBUTE_HANDLE_LOCATION 1 +#define RSI_BLE_CHARACTERISTIC_RX_VALUE_HANDLE_LOCATION 2 + +#define RSI_BLE_CUSTOM_CHARACTERISTIC_TX_SIZE 16 +#define RSI_BLE_CUSTOM_CHARACTERISTIC_TX_RESERVED 0x00, 0x00, 0x00 +#define RSI_BLE_CUSTOM_CHARACTERISTIC_TX_VALUE_128_DATA_1 0x18EE2EF5 +#define RSI_BLE_CUSTOM_CHARACTERISTIC_TX_VALUE_128_DATA_2 0x263D +#define RSI_BLE_CUSTOM_CHARACTERISTIC_TX_VALUE_128_DATA_3 0x4559 +#define RSI_BLE_CUSTOM_CHARACTERISTIC_TX_VALUE_128_DATA_4 0x9F, 0x95, 0x9C, 0x4F, 0x12, 0x9D, 0x9F, 0x42 +#define RSI_BLE_CHARACTERISTIC_TX_ATTRIBUTE_HANDLE_LOCATION 3 +#define RSI_BLE_CHARACTERISTIC_TX_MEASUREMENT_HANDLE_LOCATION 4 +#define RSI_BLE_CHARACTERISTIC_TX_GATT_SERVER_CLIENT_HANDLE_LOCATION 5 + +typedef struct sl_wfx_msg_s +{ + uint8_t connectionHandle; + uint8_t bondingHandle; + uint32_t event_num; + uint16_t reason; + uint16_t event_id; + uint16_t resp_status; + rsi_ble_event_mtu_t rsi_ble_mtu; + rsi_ble_event_write_t rsi_ble_write; + rsi_ble_event_enhance_conn_status_t resp_enh_conn; + rsi_ble_event_disconnect_t * resp_disconnect; + rsi_ble_set_att_resp_t rsi_ble_event_set_att_rsp; + uint32_t ble_app_event_map; + uint32_t ble_app_event_mask; + uint16_t rsi_ble_measurement_hndl; + uint16_t rsi_ble_gatt_server_client_config_hndl; +} sl_wfx_msg_t; + +int32_t ble_rsi_task(void); +void rsi_ble_on_connect_event(rsi_ble_event_conn_status_t * resp_conn); +void rsi_ble_on_disconnect_event(rsi_ble_event_disconnect_t * resp_disconnect, uint16_t reason); +void rsi_ble_on_enhance_conn_status_event(rsi_ble_event_enhance_conn_status_t * resp_enh_conn); +void rsi_ble_on_gatt_write_event(uint16_t event_id, rsi_ble_event_write_t * rsi_ble_write); +void rsi_ble_on_mtu_event(rsi_ble_event_mtu_t * rsi_ble_mtu); +void rsi_ble_on_event_indication_confirmation(uint16_t resp_status, rsi_ble_set_att_resp_t * rsi_ble_event_set_att_rsp); +void rsi_gatt_add_attribute_to_list(rsi_ble_t * p_val, uint16_t handle, uint16_t data_len, uint8_t * data, uuid_t uuid, + uint8_t char_prop); +void rsi_ble_add_char_serv_att(void * serv_handler, uint16_t handle, uint8_t val_prop, uint16_t att_val_handle, + uuid_t att_val_uuid); +void rsi_ble_add_char_val_att(void * serv_handler, uint16_t handle, uuid_t att_type_uuid, uint8_t val_prop, uint8_t * data, + uint8_t data_len, uint8_t auth_read); +uint32_t rsi_ble_add_matter_service(void); +void rsi_ble_app_set_event(uint32_t event_num); +int32_t rsi_ble_app_get_event(void); +void rsi_ble_app_clear_event(uint32_t event_num); +void rsi_ble_app_init_events(); +void rsi_ble_event_handling_task(void); + +#endif \ No newline at end of file diff --git a/src/platform/silabs/SiWx917/efr32-mbedtls-psa-crypto-config.h b/src/platform/silabs/SiWx917/efr32-mbedtls-psa-crypto-config.h deleted file mode 100644 index 6df9724afa0808..00000000000000 --- a/src/platform/silabs/SiWx917/efr32-mbedtls-psa-crypto-config.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * - * Copyright (c) 2020-2021 Project CHIP Authors - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -// ADD USER PSA CRYPTO CONFIG HERE -#define SL_PSA_KEY_USER_SLOT_COUNT (4) - -#define SL_PSA_ITS_USER_MAX_FILES (128) - -#include "em_device.h" -#if defined(SEMAILBOX_PRESENT) || defined(CRYPTOACC_PRESENT) -// Use accelerated HMAC when we have it -#define MBEDTLS_PSA_ACCEL_ALG_HMAC -// Use accelerated ECDSA/ECDH when we have it -#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR -#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY -#define MBEDTLS_PSA_ACCEL_ECC_SECP_R1_256 -#define MBEDTLS_PSA_ACCEL_ALG_ECDH -#define MBEDTLS_PSA_ACCEL_ALG_ECDSA -#else -// Devices without SEMAILBOX or CRYPTOACC don't have HMAC top-level accelerated -#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1 -// Devices without SEMAILBOX or CRYPTOACC don't have fully implemented ECDSA/ECDH -#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY 1 -#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR 1 -#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_256 1 -#define MBEDTLS_PSA_BUILTIN_ALG_ECDH 1 -#define MBEDTLS_PSA_BUILTIN_ALG_ECDSA 1 -#endif -// end of user configuration section >>> - -// AUTO GENERATED PSA CONFIG SECTION BELOW. **KEEP AS IS FUTURE GSDK UPDATE** -#define PSA_WANT_KEY_TYPE_AES -#define PSA_WANT_ALG_CMAC -#define PSA_WANT_ALG_SHA_256 -#define PSA_WANT_ALG_CCM -#define PSA_WANT_ALG_ECB_NO_PADDING -#define PSA_WANT_ALG_ECDSA -#define PSA_WANT_ALG_ECDH -#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR -#define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY -#define PSA_WANT_ECC_SECP_R1_256 -#define PSA_WANT_ALG_HKDF -#define PSA_WANT_ALG_HMAC -#define PSA_WANT_KEY_TYPE_HMAC -#define MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG -#define MBEDTLS_PSA_ACCEL_ALG_SHA_1 -#define MBEDTLS_PSA_ACCEL_ALG_SHA_224 -#define MBEDTLS_PSA_ACCEL_ALG_SHA_256 -#define MBEDTLS_PSA_ACCEL_KEY_TYPE_AES -#define MBEDTLS_PSA_ACCEL_ALG_ECB_NO_PADDING -#define MBEDTLS_PSA_ACCEL_ALG_CBC_NO_PADDING -#define MBEDTLS_PSA_ACCEL_ALG_CBC_PKCS7 -#define MBEDTLS_PSA_ACCEL_ALG_CTR -#define MBEDTLS_PSA_ACCEL_ALG_CFB -#define MBEDTLS_PSA_ACCEL_ALG_OFB -#define MBEDTLS_PSA_ACCEL_ALG_GCM -#define MBEDTLS_PSA_ACCEL_ALG_CCM -#define MBEDTLS_PSA_ACCEL_ALG_CMAC - -#define MBEDTLS_PSA_KEY_SLOT_COUNT (15 + 1 + SL_PSA_KEY_USER_SLOT_COUNT) -#define SL_PSA_ITS_MAX_FILES (1 + SL_PSA_ITS_USER_MAX_FILES) diff --git a/src/platform/silabs/SiWx917/efr32-chip-mbedtls-config.h b/src/platform/silabs/SiWx917/siwx917-chip-mbedtls-config.h similarity index 86% rename from src/platform/silabs/SiWx917/efr32-chip-mbedtls-config.h rename to src/platform/silabs/SiWx917/siwx917-chip-mbedtls-config.h index 049c12cb084a65..41126c51c0482c 100644 --- a/src/platform/silabs/SiWx917/efr32-chip-mbedtls-config.h +++ b/src/platform/silabs/SiWx917/siwx917-chip-mbedtls-config.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, The OpenThread Authors. + * Copyright (c) 2021, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -31,13 +31,10 @@ #include #include #include - -#include "em_device.h" -#include "em_se.h" - -#if CHIP_HAVE_CONFIG_H -#include -#endif // CHIP_HAVE_CONFIG_H +/** + * Enable FreeRTOS threading support + */ +#define MBEDTLS_FREERTOS /** * Enable H Crypto and Entropy modules @@ -46,8 +43,16 @@ #define MBEDTLS_ECP_C #define MBEDTLS_ECDH_C #define MBEDTLS_ENTROPY_C -#define MBEDTLS_SHA224_C #define MBEDTLS_SHA256_C +#define MBEDTLS_CIPHER_MODE_CTR +#define MBEDTLS_TRNG_C + +#define MBEDTLS_NO_PLATFORM_ENTROPY +#define MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES + +#if defined(MBEDTLS_ECP_ALT) && !defined(MBEDTLS_ECP_RESTARTABLE) +typedef void mbedtls_ecp_restart_ctx; +#endif #define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf @@ -58,6 +63,8 @@ #define MBEDTLS_BIGNUM_C #define MBEDTLS_CCM_C #define MBEDTLS_CIPHER_C +#define MBEDTLS_CIPHER_MODE_CBC +#define MBEDTLS_CIPHER_MODE_CFB #define MBEDTLS_CMAC_C #define MBEDTLS_CTR_DRBG_C #define MBEDTLS_ECDH_LEGACY_CONTEXT @@ -67,7 +74,9 @@ #define MBEDTLS_ECP_DP_SECP256R1_ENABLED #define MBEDTLS_ECP_NIST_OPTIM #define MBEDTLS_ENTROPY_FORCE_SHA256 -#define MBEDTLS_ENTROPY_HARDWARE_ALT +// TODO: 3R +// #define MBEDTLS_ENTROPY_HARDWARE_ALT + #define MBEDTLS_ERROR_STRERROR_DUMMY #define MBEDTLS_HAVE_ASM #define MBEDTLS_HKDF_C @@ -76,23 +85,15 @@ #define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED #define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED #define MBEDTLS_MD_C -#define MBEDTLS_NO_PLATFORM_ENTROPY #define MBEDTLS_OID_C #define MBEDTLS_PEM_PARSE_C #define MBEDTLS_PEM_WRITE_C #define MBEDTLS_PK_C #define MBEDTLS_PK_PARSE_C #define MBEDTLS_PK_WRITE_C -#if CHIP_CRYPTO_MBEDTLS #define MBEDTLS_PKCS5_C -#endif #define MBEDTLS_PLATFORM_C #define MBEDTLS_PLATFORM_MEMORY -#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS -#define MBEDTLS_PSA_CRYPTO_C -#define MBEDTLS_PSA_CRYPTO_CONFIG -#define MBEDTLS_PSA_CRYPTO_DRIVERS -#define MBEDTLS_PSA_CRYPTO_STORAGE_C #define MBEDTLS_SHA256_SMALLER #define MBEDTLS_SHA512_C #define MBEDTLS_SSL_CLI_C @@ -106,11 +107,6 @@ #define MBEDTLS_SSL_PROTO_DTLS #define MBEDTLS_SSL_SRV_C #define MBEDTLS_SSL_TLS_C - -#if CHIP_CRYPTO_PLATFORM -#define MBEDTLS_USE_PSA_CRYPTO -#endif - #define MBEDTLS_X509_CREATE_C #define MBEDTLS_X509_CSR_WRITE_C #define MBEDTLS_X509_CRL_PARSE_C @@ -133,9 +129,4 @@ #define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 -#define MBEDTLS_CIPHER_MODE_WITH_PADDING - -#include "check_crypto_config.h" -#include "config-device-acceleration.h" #include "mbedtls/check_config.h" -#include "mbedtls/config_psa.h" diff --git a/src/platform/silabs/SiWx917/wifi/dhcp_client.cpp b/src/platform/silabs/SiWx917/wifi/dhcp_client.cpp index 15c678515a0e62..e45f38bcaeaf8e 100644 --- a/src/platform/silabs/SiWx917/wifi/dhcp_client.cpp +++ b/src/platform/silabs/SiWx917/wifi/dhcp_client.cpp @@ -21,12 +21,6 @@ #include #include -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" - #include "dhcp_client.h" #include "lwip/dhcp.h" #include "wfx_host_events.h" diff --git a/src/platform/silabs/SiWx917/wifi/ethernetif.cpp b/src/platform/silabs/SiWx917/wifi/ethernetif.cpp index d1fcc01f3c4f9b..13cc843d0e705d 100644 --- a/src/platform/silabs/SiWx917/wifi/ethernetif.cpp +++ b/src/platform/silabs/SiWx917/wifi/ethernetif.cpp @@ -21,12 +21,6 @@ #include #include -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" - #ifndef WF200_WIFI #include "FreeRTOS.h" #include "event_groups.h" @@ -182,141 +176,6 @@ static void low_level_input(struct netif * netif, uint8_t * b, uint16_t len) } } -/***************************************************************************** - * @fn static err_t low_level_output(struct netif *netif, struct pbuf *p) - * @brief - * This function should does the actual transmission of the packet(s). - * The packet is contained in the pbuf that is passed to the function. - * This pbuf might be chained. - * - * @param[in] netif: the lwip network interface structure - * - * @param[in] p: the packet to send - * - * @return - * ERR_OK if successful - ******************************************************************************/ -#ifdef WF200_WIFI -static err_t low_level_output(struct netif * netif, struct pbuf * p) -{ - struct pbuf * q; - sl_wfx_send_frame_req_t * tx_buffer; - uint8_t * buffer; - uint32_t framelength, asize; - uint32_t bufferoffset; - uint32_t padding; - sl_status_t result; - - for (q = p, framelength = 0; q != NULL; q = q->next) - { - framelength += q->len; - } - if (framelength < LWIP_FRAME_ALIGNMENT) - { /* 60 : Frame alignment for LWIP */ - padding = LWIP_FRAME_ALIGNMENT - framelength; - } - else - { - padding = 0; - } - - /* choose padding of 64 */ - asize = SL_WFX_ROUND_UP(framelength + padding, 64) + sizeof(sl_wfx_send_frame_req_t); - // 12 is size of other data in buffer struct, user shouldn't have to care about this? - if (sl_wfx_host_allocate_buffer((void **) &tx_buffer, SL_WFX_TX_FRAME_BUFFER, asize) != SL_STATUS_OK) - { - SILABS_LOG("*ERR*EN-Out: No mem frame len=%d", framelength); - gOverrunCount++; - SILABS_LOG("overrun count exiting when faied to alloc value %d", gOverrunCount); - return ERR_MEM; - } - buffer = tx_buffer->body.packet_data; - /* copy frame from pbufs to driver buffers */ - for (q = p, bufferoffset = 0; q != NULL; q = q->next) - { - /* Get bytes in current lwIP buffer */ - memcpy((uint8_t *) ((uint8_t *) buffer + bufferoffset), (uint8_t *) ((uint8_t *) q->payload), q->len); - bufferoffset += q->len; - } - /* No requirement to do this - but we should for security */ - if (padding) - { - memset(buffer + bufferoffset, 0, padding); - framelength += padding; - } - /* transmit */ - int i = 0; - result = SL_STATUS_FAIL; - -#ifdef WIFI_DEBUG_ENABLED - SILABS_LOG("WF200: Out %d", (int) framelength); -#endif - - /* send the generated frame over Wifi network */ - while ((result != SL_STATUS_OK) && (i++ < 10)) - { - result = sl_wfx_send_ethernet_frame(tx_buffer, framelength, SL_WFX_STA_INTERFACE, PRIORITY_0); - } - sl_wfx_host_free_buffer(tx_buffer, SL_WFX_TX_FRAME_BUFFER); - - if (result != SL_STATUS_OK) - { - SILABS_LOG("*ERR*Send enet %d", (int) framelength); - return ERR_IF; - } - return ERR_OK; -} - -/***************************************************************************** - * @fn void sl_wfx_host_received_frame_callback(sl_wfx_received_ind_t *rx_buffer) - * @brief - * This function implements the wf200 received frame callback. - * Called from the context of the bus_task (not ISR) - * - * @param[in] rx_buffer: the ethernet frame received by the wf200 - * - * @return - * None - ******************************************************************************/ -void sl_wfx_host_received_frame_callback(sl_wfx_received_ind_t * rx_buffer) -{ - struct netif * netif; - - /* Check packet interface to send to AP or STA interface */ - if ((rx_buffer->header.info & SL_WFX_MSG_INFO_INTERFACE_MASK) == (SL_WFX_STA_INTERFACE << SL_WFX_MSG_INFO_INTERFACE_OFFSET)) - { - - /* Send received frame to station interface */ - if ((netif = wfx_get_netif(SL_WFX_STA_INTERFACE)) != NULL) - { - uint8_t * buffer; - uint16_t len; - - len = rx_buffer->body.frame_length; - buffer = (uint8_t *) &(rx_buffer->body.frame[rx_buffer->body.frame_padding]); - -#ifdef WIFI_DEBUG_ENABLED - SILABS_LOG("WF200: In %d", (int) len); -#endif - - low_level_input(netif, buffer, len); - } - else - { -#ifdef WIFI_DEBUG_ENABLED - SILABS_LOG("WF200: NO-INTF"); -#endif - } - } - else - { -#ifdef WIFI_DEBUG_ENABLED - SILABS_LOG("WF200: Invalid frame IN"); -#endif - } -} - -#else /* For RS911x - using LWIP */ static SemaphoreHandle_t ethout_sem; /***************************************************************************** * @fn static err_t low_level_output(struct netif *netif, struct pbuf *p) @@ -422,8 +281,6 @@ void wfx_host_received_sta_frame_cb(uint8_t * buf, int len) } } -#endif /* RS911x - with LWIP */ - /***************************************************************************** * @fn err_t sta_ethernetif_init(struct netif *netif) * @brief @@ -452,10 +309,10 @@ err_t sta_ethernetif_init(struct netif * netif) /* initialize the hardware */ low_level_init(netif); -#ifndef WF200_WIFI + /* Need single output only */ ethout_sem = xSemaphoreCreateBinaryStatic(&xEthernetIfSemaBuffer); xSemaphoreGive(ethout_sem); -#endif + return ERR_OK; } diff --git a/src/platform/silabs/SiWx917/wifi/ethernetif.h b/src/platform/silabs/SiWx917/wifi/ethernetif.h index dfea1ea6ad3540..bac51b9258cd85 100644 --- a/src/platform/silabs/SiWx917/wifi/ethernetif.h +++ b/src/platform/silabs/SiWx917/wifi/ethernetif.h @@ -42,11 +42,8 @@ err_t sta_ethernetif_init(struct netif * netif); ******************************************************************************/ err_t ap_ethernetif_init(struct netif * netif); -#ifdef WF200_WIFI -void sl_wfx_host_received_frame_callback(sl_wfx_received_ind_t * rx_buffer); -#else void wfx_host_received_sta_frame_cb(uint8_t * buf, int len); -#endif /* WF200_WIFI */ + #ifdef __cplusplus } #endif diff --git a/src/platform/silabs/SiWx917/wifi/lwip_netif.cpp b/src/platform/silabs/SiWx917/wifi/lwip_netif.cpp index e19cf97a7cefd2..913f5895a94e53 100644 --- a/src/platform/silabs/SiWx917/wifi/lwip_netif.cpp +++ b/src/platform/silabs/SiWx917/wifi/lwip_netif.cpp @@ -20,12 +20,6 @@ #include #include -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" - #include "wfx_host_events.h" #include "wifi_config.h" diff --git a/src/platform/silabs/SiWx917/wifi/wfx_host_events.h b/src/platform/silabs/SiWx917/wifi/wfx_host_events.h index 5a7e8617a661e2..66e161d5f3b8cf 100644 --- a/src/platform/silabs/SiWx917/wifi/wfx_host_events.h +++ b/src/platform/silabs/SiWx917/wifi/wfx_host_events.h @@ -17,86 +17,7 @@ #pragma once -#ifdef WF200_WIFI -#include "FreeRTOS.h" -#include "event_groups.h" -#include "semphr.h" -#include "task.h" -#include "timers.h" - -#include "sl_wfx_cmd_api.h" -#include "sl_wfx_constants.h" - -typedef struct __attribute__((__packed__)) sl_wfx_get_counters_cnf_body_s -{ - uint32_t status; - uint16_t mib_id; - uint16_t length; - uint32_t rcpi; - uint32_t count_plcp_errors; - uint32_t count_fcs_errors; - uint32_t count_tx_packets; - uint32_t count_rx_packets; - uint32_t count_rx_packet_errors; - uint32_t count_rx_decryption_failures; - uint32_t count_rx_mic_failures; - uint32_t count_rx_no_key_failures; - uint32_t count_tx_multicast_frames; - uint32_t count_tx_frames_success; - uint32_t count_tx_frame_failures; - uint32_t count_tx_frames_retried; - uint32_t count_tx_frames_multi_retried; - uint32_t count_rx_frame_duplicates; - uint32_t count_rts_success; - uint32_t count_rts_failures; - uint32_t count_ack_failures; - uint32_t count_rx_multicast_frames; - uint32_t count_rx_frames_success; - uint32_t count_rx_cmacicv_errors; - uint32_t count_rx_cmac_replays; - uint32_t count_rx_mgmt_ccmp_replays; - uint32_t count_rx_bipmic_errors; - uint32_t count_rx_beacon; - uint32_t count_miss_beacon; - uint32_t reserved[15]; -} sl_wfx_get_counters_cnf_body_t; - -typedef struct __attribute__((__packed__)) sl_wfx_get_counters_cnf_s -{ - /** Common message header. */ - sl_wfx_header_t header; - /** Confirmation message body. */ - sl_wfx_get_counters_cnf_body_t body; -} sl_wfx_get_counters_cnf_t; - -typedef struct __attribute__((__packed__)) sl_wfx_mib_req_body_s -{ - uint16_t mib_id; ///< ID of the MIB to be read. - uint16_t reserved; -} sl_wfx_mib_req_body_t; - -typedef struct __attribute__((__packed__)) sl_wfx_header_mib_s -{ - uint16_t length; ///< Message length in bytes including this uint16_t. - ///< Maximum value is 8188 but maximum Request size is FW dependent and reported in the - ///< ::sl_wfx_startup_ind_body_t::size_inp_ch_buf. - uint8_t id; ///< Contains the message Id indexed by sl_wfx_general_commands_ids_t or sl_wfx_message_ids_t. - uint8_t reserved : 1; - uint8_t interface : 2; - uint8_t seqnum : 3; - uint8_t encrypted : 2; -} sl_wfx_header_mib_t; - -typedef struct __attribute__((__packed__)) sl_wfx_mib_req_s -{ - /** Common message header. */ - sl_wfx_header_mib_t header; - /** Request message body. */ - sl_wfx_mib_req_body_t body; -} sl_wfx_mib_req_t; - -#else /* End WF200 else RS911x */ - +#include "stdbool.h" #include "wfx_msgs.h" /* Wi-Fi events*/ @@ -106,8 +27,6 @@ typedef struct __attribute__((__packed__)) sl_wfx_mib_req_s #define SL_WFX_SCAN_COMPLETE_ID 4 #define WFX_RSI_SSID_SIZE 64 -#endif /* WF200 */ - #ifndef RS911X_SOCKETS /* LwIP includes. */ #include "lwip/apps/httpd.h" @@ -129,18 +48,11 @@ typedef struct __attribute__((__packed__)) sl_wfx_mib_req_s #include "sl_status.h" -#ifdef RS911X_WIFI #define WLAN_TASK_STACK_SIZE 1024 -#define WLAN_TASK_PRIORITY 1 -#define WLAN_DRIVER_TASK_PRIORITY 1 +#define WLAN_TASK_PRIORITY 3 +#define WLAN_DRIVER_TASK_PRIORITY 2 #define MAX_JOIN_RETRIES_COUNT 5 -#else /* WF200 */ -#define WLAN_TASK_STACK_SIZE 1024 -#define WLAN_TASK_PRIORITY 1 -#define MAX_JOIN_RETRIES_COUNT 5 -#endif - // WLAN related Macros #define ETH_FRAME 0 #define CMP_SUCCESS 0 @@ -322,6 +234,7 @@ bool wfx_is_sta_mode_enabled(void); int32_t wfx_get_ap_info(wfx_wifi_scan_result_t * ap); int32_t wfx_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); int32_t wfx_reset_counts(); +int32_t wfx_rsi_platform(); void wfx_clear_wifi_provision(void); sl_status_t wfx_connect_to_ap(void); @@ -364,12 +277,6 @@ void wfx_rsi_pkt_add_data(void * p, uint8_t * buf, uint16_t len, uint16_t off); int32_t wfx_rsi_send_data(void * p, uint16_t len); #endif /* RS911X_WIFI */ -#ifdef WF200_WIFI -void wfx_bus_start(void); -sl_status_t get_all_counters(void); -void sl_wfx_host_gpio_init(void); -sl_status_t sl_wfx_host_process_event(sl_wfx_generic_message_t * event_payload); -#endif #ifdef __cplusplus } #endif diff --git a/src/platform/silabs/SiWx917/wifi/wfx_notify.cpp b/src/platform/silabs/SiWx917/wifi/wfx_notify.cpp index 9f681e796c6d19..86bba1931446e7 100644 --- a/src/platform/silabs/SiWx917/wifi/wfx_notify.cpp +++ b/src/platform/silabs/SiWx917/wifi/wfx_notify.cpp @@ -19,13 +19,6 @@ #include #include -#include "em_bus.h" -#include "em_cmu.h" -#include "em_gpio.h" -#include "em_ldma.h" -#include "em_usart.h" -#include "gpiointerrupt.h" - #include "AppConfig.h" #include "FreeRTOS.h" diff --git a/src/platform/silabs/SiWx917/wifi_args.gni b/src/platform/silabs/SiWx917/wifi_args.gni index 73a6613ecdcb4a..88d554d2f1040b 100644 --- a/src/platform/silabs/SiWx917/wifi_args.gni +++ b/src/platform/silabs/SiWx917/wifi_args.gni @@ -17,7 +17,7 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") -import("${chip_root}/examples/platform/silabs/efr32/args.gni") +import("${chip_root}/examples/platform/silabs/SiWx917/args.gni") import("${chip_root}/src/crypto/crypto.gni") # ARM architecture flags will be set based on silabs_family. @@ -25,11 +25,6 @@ arm_platform_config = "${efr32_sdk_build_root}/efr32_arm.gni" mbedtls_target = "${efr32_sdk_build_root}:efr32_sdk" -# default to platform crypto implementation but allow commandline override -if (chip_crypto == "") { - chip_crypto = "platform" -} - # Transitional CommissionableDataProvider not used anymore # examples/platform/efr32/EFR32DeviceDataProvider is now used. chip_use_transitional_commissionable_data_provider = false @@ -41,7 +36,7 @@ lwip_ipv4 = true lwip_api = true lwip_ethernet = true -chip_device_platform = "efr32" +chip_device_platform = "SiWx917" chip_enable_openthread = false chip_inet_config_enable_ipv4 = true chip_inet_config_enable_dns_resolver = false diff --git a/third_party/silabs/BUILD.gn b/third_party/silabs/BUILD.gn index f968d3dc38f13c..9c59de25de7056 100644 --- a/third_party/silabs/BUILD.gn +++ b/third_party/silabs/BUILD.gn @@ -16,7 +16,13 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") import("//build_overrides/jlink.gni") import("${chip_root}/src/platform/device.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") +import("${efr32_sdk_build_root}/silabs_board.gni") + +if (silabs_board == "BRD4325A") { # CCP board + import("${efr32_sdk_build_root}/SiWx917_sdk.gni") +} else { + import("${efr32_sdk_build_root}/efr32_sdk.gni") +} declare_args() { # Build target to use for efr32 SDK. Use this to set global SDK defines. diff --git a/third_party/silabs/SiWx917_sdk.gni b/third_party/silabs/SiWx917_sdk.gni index 38359a7c8a4063..5d6a857916320f 100644 --- a/third_party/silabs/SiWx917_sdk.gni +++ b/third_party/silabs/SiWx917_sdk.gni @@ -24,6 +24,8 @@ declare_args() { # Location of the efr32 SDK. efr32_sdk_root = "${chip_root}/third_party/silabs/gecko_sdk" sdk_support_root = "${chip_root}/third_party/silabs/matter_support" + wiseconnect_sdk_root = "${chip_root}/third_party/silabs/wisemcu-wifi-bt-sdk" + examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" # Build openthread with prebuilt silabs lib use_silabs_thread_lib = false @@ -35,9 +37,6 @@ declare_args() { # Use Silabs factory data provider example. # Users can implement their own. use_efr32_factory_data_provider = true - - # Enable Segger System View - use_system_view = false } # Explorer Kit and MGM240L do not have external flash @@ -67,12 +66,6 @@ template("efr32_sdk") { } assert(efr32_sdk_root != "", "efr32_sdk_root must be specified") - use_wf200 = false - if (defined(invoker.use_wf200)) { - if (invoker.use_wf200) { - use_wf200 = true - } - } sdk_target_name = target_name @@ -85,82 +78,30 @@ template("efr32_sdk") { # Treat these includes as system includes, so warnings in them are not fatal. _include_dirs = [ - "${efr32_sdk_root}", - "${efr32_sdk_root}/hardware/kit/common/bsp", - "${efr32_sdk_root}/app/common/util/app_assert/", - "${efr32_sdk_root}/hardware/board/inc", - "${efr32_sdk_root}/hardware/driver/memlcd/inc", - "${efr32_sdk_root}/hardware/driver/memlcd/src/ls013b7dh03", - "${efr32_sdk_root}/platform/bootloader", - "${efr32_sdk_root}/platform/bootloader/config", - "${efr32_sdk_root}/platform/bootloader/config/s2/btl_interface", - "${efr32_sdk_root}/platform/bootloader/api", - "${efr32_sdk_root}/platform/CMSIS/Core/Include", - "${efr32_sdk_root}/platform/CMSIS/RTOS2/Include", - "${efr32_sdk_root}/platform/common/inc", - "${efr32_sdk_root}/platform/driver/button/inc", - "${efr32_sdk_root}/platform/emdrv/common/inc", - "${efr32_sdk_root}/platform/emdrv/gpiointerrupt/inc", - "${efr32_sdk_root}/platform/emdrv/dmadrv/config", - "${efr32_sdk_root}/platform/emdrv/dmadrv/inc", - "${efr32_sdk_root}/platform/emdrv/nvm3/inc", - "${efr32_sdk_root}/platform/emdrv/rtcdrv/inc", - "${efr32_sdk_root}/platform/emlib/inc", - "${efr32_sdk_root}/platform/halconfig/inc/hal-config", - "${efr32_sdk_root}/platform/peripheral/inc", - "${efr32_sdk_root}/platform/radio/rail_lib/common", - "${efr32_sdk_root}/platform/radio/rail_lib/chip/efr32", - "${efr32_sdk_root}/platform/radio/rail_lib/chip/efr32/rf/common/cortex", - "${efr32_sdk_root}/platform/radio/rail_lib/hal", - "${efr32_sdk_root}/platform/radio/rail_lib/hal/efr32", - "${efr32_sdk_root}/platform/radio/rail_lib/protocol/ieee802154", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/rail_util_pti", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/rail_util_rf_path", - "${efr32_sdk_root}/platform/service/device_init/inc", - "${efr32_sdk_root}/platform/service/hfxo_manager/config/", - "${efr32_sdk_root}/platform/service/hfxo_manager/inc", - "${efr32_sdk_root}/platform/service/hfxo_manager/src", - "${efr32_sdk_root}/platform/service/mpu/inc", - "${efr32_sdk_root}/platform/service/power_manager/config/", - "${efr32_sdk_root}/platform/service/power_manager/inc/", - "${efr32_sdk_root}/platform/service/power_manager/src/", - "${efr32_sdk_root}/platform/service/sleeptimer/inc", - "${efr32_sdk_root}/platform/service/sleeptimer/config", - "${efr32_sdk_root}/platform/service/system/inc", - "${efr32_sdk_root}/platform/service/udelay/inc", - "${efr32_sdk_root}/platform/service/legacy_hal/inc", - "${efr32_sdk_root}/platform/service/token_manager/config", - "${efr32_sdk_root}/platform/service/token_manager/inc", - "${efr32_sdk_root}/platform/service/token_manager/test", - "${efr32_sdk_root}/platform/service/token_manager/test/include", - "${efr32_sdk_root}/platform/service/token_manager/test/stack/config", - "${efr32_sdk_root}/platform/service/token_manager/test/stack/include", - "${efr32_sdk_root}/platform/middleware/glib", - "${efr32_sdk_root}/platform/middleware/glib/glib", - "${efr32_sdk_root}/platform/middleware/glib/dmd", - "${efr32_sdk_root}/platform/base/hal/plugin/psstore", - "${efr32_sdk_root}/platform/base/hal/plugin/antenna", - "${efr32_sdk_root}/protocol/bluetooth/inc/", - "${efr32_sdk_root}/app/bluetooth/common/in_place_ota_dfu/", - "${efr32_sdk_root}/util/plugin/plugin-common/fem-control", - "${efr32_sdk_root}/util/silicon_labs/silabs_core/graphics", - "${efr32_sdk_root}/util/silicon_labs/silabs_core/memory_manager", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/include", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/include/psa", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_alt/include", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_protocol_crypto/src", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/inc", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/config/", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/inc", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/inc/public", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/inc", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/", - "${efr32_sdk_root}/util/third_party/freertos/cmsis/Include", - "${efr32_sdk_root}/util/third_party/freertos/kernel/include", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/config", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/autogen", + "${sdk_support_root}/platform/emdrv/nvm3/inc", + + "${chip_root}/third_party/mbedtls/repo/include", + + ### CCP includes ### + "${wiseconnect_sdk_root}/platforms/si91x/drivers/peripheral_drivers/inc", + "${wiseconnect_sdk_root}/platforms/si91x/core/chip/inc", + "${wiseconnect_sdk_root}/platforms/si91x/core/config", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/cmsis_driver/config", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/rom_driver/inc", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/inc", + + "${wiseconnect_sdk_root}/platforms/si91x/drivers/cmsis_driver", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/cmsis_driver/CMSIS/Driver/Include", + "${wiseconnect_sdk_root}/platforms/si91x/boards/brd4325a/inc", + "${wiseconnect_sdk_root}/platforms/si91x/core/cmsis", + "${wiseconnect_sdk_root}/third_party/freertos/include", + "${wiseconnect_sdk_root}/third_party/freertos/portable/GCC/ARM_CM4F", + "${examples_plat_dir}/device/inc", + + "${wiseconnect_sdk_root}/sapi/include", + + "${chip_root}/examples/platform/SiWx917/SiWx917", + "${chip_root}/examples/platform/SiWx917/SiWx917/hal", ] # Note that we're setting the mbedTLS and PSA configuration files through a @@ -169,13 +110,14 @@ template("efr32_sdk") { # To fix this, these files are also manually depended upon in the source set # declared in efr32_mbedtls_config further down this file. defines = [ - "MBEDTLS_CONFIG_FILE=\"efr32-chip-mbedtls-config.h\"", - "MBEDTLS_PSA_CRYPTO_CONFIG_FILE=\"efr32-mbedtls-psa-crypto-config.h\"", + "MBEDTLS_CONFIG_FILE=\"siwx917-chip-mbedtls-config.h\"", "__STARTUP_CLEAR_BSS", "HARD_FAULT_LOG_ENABLE", "CORTEXM3_EFM32_MICRO", - "EFR32_LOG_ENABLED=1", - "NVM3_DEFAULT_NVM_SIZE=40960", + "SILABS_LOG_ENABLED=1", + + #Matter required at least 40960 but SiWx917 SoC requires an extra 20k to resolve nvm3_open() error, Need to be checked. + "NVM3_DEFAULT_NVM_SIZE=73728", "NVM3_DEFAULT_MAX_OBJECT_SIZE=4092", "KVS_MAX_ENTRIES=${kvs_max_entries}", "EFR32_OPENTHREAD_API", @@ -186,36 +128,18 @@ template("efr32_sdk") { "${silabs_mcu}=1", "${silabs_board}=1", "__HEAP_SIZE=0", - "SL_CATALOG_FREERTOS_KERNEL_PRESENT=1", - "MBEDTLS_THREADING_C=1", - "MBEDTLS_THREADING_ALT=1", - "SL_THREADING_ALT=1", "SL_COMPONENT_CATALOG_PRESENT", "PLATFORM_HEADER=\"platform-header.h\"", "USE_NVM3=1", - - #"__STACK_SIZE=0", + "RSI_ARM_CM4F", + "RSI_BLE_ENABLE=1", + "BRD4325A", + "CHIP_9117", + "RS91X_BLE_ENABLE=1", ] - if (use_system_view) { - _include_dirs += [ - "${efr32_sdk_root}/util/third_party/segger/systemview/SEGGER", - "${efr32_sdk_root}/util/third_party/segger/systemview/Sample/FreeRTOSV10/Config/Cortex-M", - "${efr32_sdk_root}/util/third_party/segger/systemview/Sample/FreeRTOSV10", - "${efr32_sdk_root}/util/third_party/segger/systemview/Config/", - ] - - defines += [ "SL_SYSTEM_VIEW=1" ] - } - defines += board_defines - if (use_wstk_leds) { - _include_dirs += [ "${efr32_sdk_root}/platform/driver/leddrv/inc" ] - - defines += [ "ENABLE_WSTK_LEDS" ] - } - if (defined(invoker.enable_sleepy_device)) { if (invoker.enable_sleepy_device) { defines += [ @@ -257,112 +181,11 @@ template("efr32_sdk") { "${efr32_sdk_root}/platform/emdrv/uartdrv/inc", "${efr32_sdk_root}/platform/emdrv/uartdrv/config", "${efr32_sdk_root}/hardware/driver/memlcd/inc/memlcd_usart", + "${efr32_sdk_root}/platform/common/errno/inc", ] } - if (silabs_family == "efr32mg12") { - _include_dirs += [ - "${efr32_sdk_root}/platform/Device/SiliconLabs/EFR32MG12P/Include", - "${efr32_sdk_root}/platform/radio/rail_lib/chip/efr32/efr32xg1x", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM4F", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions/efr32xg1x/config", - "${efr32_sdk_root}/platform/service/device_init/config/s1/", - "${efr32_sdk_root}/platform/emdrv/spidrv/inc", - ] - - libs += [ - "${sdk_support_root}/protocol/bluetooth/lib/EFR32MG12P/GCC/binapploader.o", - "${sdk_support_root}/protocol/bluetooth/lib/EFR32MG12P/GCC/libbluetooth.a", - "${sdk_support_root}/platform/radio/rail_lib/autogen/librail_release/librail_multiprotocol_efr32xg12_gcc_release.a", - "${sdk_support_root}/platform/emdrv/nvm3/lib/libnvm3_CM4_gcc.a", - ] - - defines += [ "EFR32MG12" ] - } else if (silabs_family == "efr32mg21") { - _include_dirs += [ - "${efr32_sdk_root}/platform/Device/SiliconLabs/EFR32MG21/Include", - "${efr32_sdk_root}/platform/radio/rail_lib/chip/efr32/efr32xg2x", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM33_NTZ/non_secure", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions/efr32xg21", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions/efr32xg21/config", - "${efr32_sdk_root}/platform/service/device_init/config/s2/", - ] - - libs += [ - "${sdk_support_root}/protocol/bluetooth/lib/EFR32MG21/GCC/binapploader.o", - "${sdk_support_root}/protocol/bluetooth/lib/EFR32MG21/GCC/libbluetooth.a", - "${sdk_support_root}/platform/radio/rail_lib/autogen/librail_release/librail_multiprotocol_efr32xg21_gcc_release.a", - "${sdk_support_root}/platform/emdrv/nvm3/lib/libnvm3_CM33_gcc.a", - ] - - defines += [ - "EFR32MG21", - "EFR32_SERIES2_CONFIG1_MICRO", - ] - } else if (silabs_family == "efr32mg24") { - _include_dirs += [ - "${efr32_sdk_root}/platform/Device/SiliconLabs/EFR32MG24/Include", - "${efr32_sdk_root}/platform/radio/rail_lib/chip/efr32/efr32xg2x", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM33_NTZ/non_secure", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions/efr32xg24", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions/efr32xg24/config", - "${efr32_sdk_root}/platform/service/device_init/config/s2/", - "${efr32_sdk_root}/platform/emdrv/spidrv/inc", - ] - - libs += [ - "${sdk_support_root}/protocol/bluetooth/lib/EFR32MG24/GCC/libapploader.a", - "${sdk_support_root}/protocol/bluetooth/lib/EFR32MG24/GCC/libbluetooth.a", - "${sdk_support_root}/platform/radio/rail_lib/autogen/librail_release/librail_multiprotocol_efr32xg24_gcc_release.a", - "${sdk_support_root}/platform/emdrv/nvm3/lib/libnvm3_CM33_gcc.a", - ] - - defines += [ - "EFR32MG24", - "EFR32_SERIES2_CONFIG4_MICRO", - ] - } else if (silabs_family == "mgm24") { - _include_dirs += [ - "${efr32_sdk_root}/platform/Device/SiliconLabs/MGM24/Include", - "${efr32_sdk_root}/platform/radio/rail_lib/chip/efr32/efr32xg2x", - "${efr32_sdk_root}/platform/radio/rail_lib/protocol/ble", - "${efr32_sdk_root}/platform/radio/rail_lib/protocol/ieee802154", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM33_NTZ/non_secure", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions/efr32xg24", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions/efr32xg24/config", - "${efr32_sdk_root}/platform/service/device_init/config/s2/", - ] - - libs += [ - "${sdk_support_root}/protocol/bluetooth/lib/EFR32MG24/GCC/libapploader.a", - "${sdk_support_root}/protocol/bluetooth/lib/EFR32MG24/GCC/libbluetooth.a", - "${sdk_support_root}/platform/radio/rail_lib/autogen/librail_release/librail_multiprotocol_module_efr32xg24_gcc_release.a", - "${sdk_support_root}/platform/emdrv/nvm3/lib/libnvm3_CM33_gcc.a", - ] - - if (silabs_mcu == "MGM240PB32VNA") { - libs += [ "${sdk_support_root}/platform/radio/rail_lib/autogen/librail_release/librail_config_mgm240pb32vna_gcc.a" ] - } else if (silabs_mcu == "MGM240PB22VNA") { - libs += [ "${sdk_support_root}/platform/radio/rail_lib/autogen/librail_release/librail_config_mgm240pb22vna_gcc.a" ] - } else if (silabs_mcu == "MGM240L022RNF") { - libs += [ "${sdk_support_root}/platform/radio/rail_lib/autogen/librail_release/librail_config_mgm240l022rnf_gcc.a" ] - } - - defines += [ - "MGM24", - "EFR32_SERIES2_CONFIG4_MICRO", - ] - } - - if (use_wf200) { - _include_dirs += [ - "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver", - "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/bus", - "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/firmware", - "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/pds/brd8022a", - "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/secure_link", - ] - } + libs += [ "${sdk_support_root}/platform/emdrv/nvm3/lib/libnvm3_CM4_gcc.a" ] cflags = [] foreach(include_dir, _include_dirs) { @@ -390,14 +213,13 @@ template("efr32_sdk") { } } - source_set("efr32_mbedtls_config") { + source_set("si917_mbedtls_config") { # We're setting the mbedTLS config flags here as the efr32_sdk target # acts as the mbedTLS target for EFR32 builds. We need this for the build # system to recompile mbedTLS (= the SDK) when the mbedTLS config gets # edited. sources = [ - "${chip_root}/src/platform/silabs/EFR32/efr32-chip-mbedtls-config.h", - "${chip_root}/src/platform/silabs/EFR32/efr32-mbedtls-psa-crypto-config.h", + "${chip_root}/src/platform/silabs/SiWx917/siwx917-chip-mbedtls-config.h", ] public_deps = [ "${chip_root}/src/crypto:crypto_buildconfig" ] @@ -405,412 +227,91 @@ template("efr32_sdk") { source_set(sdk_target_name) { sources = [ - "${chip_root}/third_party/mbedtls/repo/include/mbedtls/platform.h", - "${efr32_sdk_root}/app/bluetooth/common/in_place_ota_dfu/sl_bt_in_place_ota_dfu.c", - "${efr32_sdk_root}/hardware/board/src/sl_board_control_gpio.c", - "${efr32_sdk_root}/hardware/board/src/sl_board_init.c", - "${efr32_sdk_root}/platform/CMSIS/RTOS2/Source/os_systick.c", - "${efr32_sdk_root}/platform/bootloader/api/btl_interface.c", - "${efr32_sdk_root}/platform/bootloader/api/btl_interface_storage.c", - "${efr32_sdk_root}/platform/bootloader/security/sha/crypto_sha.c", - "${efr32_sdk_root}/platform/common/src/sl_slist.c", - "${efr32_sdk_root}/platform/driver/button/src/sl_button.c", - "${efr32_sdk_root}/platform/driver/button/src/sl_simple_button.c", - "${efr32_sdk_root}/platform/emdrv/dmadrv/src/dmadrv.c", - "${efr32_sdk_root}/platform/emdrv/gpiointerrupt/src/gpiointerrupt.c", - "${efr32_sdk_root}/platform/emdrv/nvm3/src/nvm3_default.c", - "${efr32_sdk_root}/platform/emdrv/nvm3/src/nvm3_hal_flash.c", - "${efr32_sdk_root}/platform/emdrv/nvm3/src/nvm3_lock.c", - "${efr32_sdk_root}/platform/emlib/src/em_adc.c", - "${efr32_sdk_root}/platform/emlib/src/em_cmu.c", - "${efr32_sdk_root}/platform/emlib/src/em_core.c", - "${efr32_sdk_root}/platform/emlib/src/em_crypto.c", - "${efr32_sdk_root}/platform/emlib/src/em_emu.c", - "${efr32_sdk_root}/platform/emlib/src/em_gpio.c", - "${efr32_sdk_root}/platform/emlib/src/em_ldma.c", - "${efr32_sdk_root}/platform/emlib/src/em_msc.c", - "${efr32_sdk_root}/platform/emlib/src/em_prs.c", - "${efr32_sdk_root}/platform/emlib/src/em_rmu.c", - "${efr32_sdk_root}/platform/emlib/src/em_rtcc.c", - "${efr32_sdk_root}/platform/emlib/src/em_se.c", - "${efr32_sdk_root}/platform/emlib/src/em_system.c", - "${efr32_sdk_root}/platform/emlib/src/em_timer.c", - "${efr32_sdk_root}/platform/peripheral/src/peripheral_sysrtc.c", - "${efr32_sdk_root}/platform/radio/rail_lib/hal/efr32/hal_efr.c", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions/pa_conversions_efr32.c", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/rail_util_pti/sl_rail_util_pti.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_lfrco.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_nvic.c", - "${efr32_sdk_root}/platform/service/hfxo_manager/src/sl_hfxo_manager.c", - "${efr32_sdk_root}/platform/service/legacy_hal/src/token_legacy.c", - "${efr32_sdk_root}/platform/service/mpu/src/sl_mpu.c", - "${efr32_sdk_root}/platform/service/power_manager/src/sl_power_manager.c", - "${efr32_sdk_root}/platform/service/power_manager/src/sl_power_manager_debug.c", - "${efr32_sdk_root}/platform/service/power_manager/src/sl_power_manager_hal_s0_s1.c", - "${efr32_sdk_root}/platform/service/power_manager/src/sl_power_manager_hal_s2.c", - "${efr32_sdk_root}/platform/service/sleeptimer/src/sl_sleeptimer.c", - "${efr32_sdk_root}/platform/service/sleeptimer/src/sl_sleeptimer_hal_rtcc.c", - "${efr32_sdk_root}/platform/service/sleeptimer/src/sl_sleeptimer_hal_sysrtc.c", - "${efr32_sdk_root}/platform/service/system/src/sl_system_init.c", - "${efr32_sdk_root}/platform/service/system/src/sl_system_kernel.c", - "${efr32_sdk_root}/platform/service/system/src/sl_system_process_action.c", - "${efr32_sdk_root}/platform/service/token_manager/src/sl_token_def.c", - "${efr32_sdk_root}/platform/service/token_manager/src/sl_token_manager.c", - "${efr32_sdk_root}/platform/service/token_manager/src/sl_token_manufacturing.c", - "${efr32_sdk_root}/platform/service/udelay/src/sl_udelay.c", - "${efr32_sdk_root}/platform/service/udelay/src/sl_udelay_armv6m_gcc.S", - "${efr32_sdk_root}/protocol/bluetooth/src/sl_bt_mbedtls_context.c", - "${efr32_sdk_root}/protocol/bluetooth/src/sl_bt_rtos_adaptation.c", - "${efr32_sdk_root}/protocol/bluetooth/src/sl_bt_stack_init.c", - "${efr32_sdk_root}/protocol/bluetooth/src/sli_bt_advertiser_config.c", - "${efr32_sdk_root}/protocol/bluetooth/src/sli_bt_connection_config.c", - "${efr32_sdk_root}/util/silicon_labs/silabs_core/memory_manager/sl_malloc.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/aes.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/aesni.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/asn1parse.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/asn1write.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/base64.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/bignum.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/camellia.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ccm.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/chacha20.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/chachapoly.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/cipher_wrap.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/cmac.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/constant_time.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ctr_drbg.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/debug.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/des.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/dhm.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ecdh.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ecdsa.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ecjpake.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ecp.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ecp_curves.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/entropy.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/entropy_poll.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/gcm.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/hkdf.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/hmac_drbg.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/md.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/md5.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/oid.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/pem.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/pk.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/pk_wrap.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/pkcs12.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/pkcs5.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/pkparse.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/pkwrite.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/platform.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/platform_util.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/poly1305.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_aead.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_client.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_driver_wrappers.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_ecp.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_hash.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_rsa.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_se.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_slot_management.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_crypto_storage.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/psa_its_file.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ripemd160.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/rsa.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/sha1.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/sha256.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/sha512.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ssl_cache.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ssl_ciphersuites.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ssl_cli.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ssl_cookie.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ssl_msg.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ssl_srv.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ssl_ticket.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ssl_tls.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/ssl_tls13_keys.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/threading.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/timing.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/version.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/x509.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/x509_create.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/x509_crl.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/x509_crt.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/x509_csr.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/x509write_crt.c", - "${efr32_sdk_root}/util/third_party/crypto/mbedtls/library/x509write_csr.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/aes_aes.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/crypto_aes.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/crypto_ecp.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/error.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/mbedtls_ccm.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/mbedtls_cmac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/mbedtls_ecdsa_ecdh.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/mbedtls_sha.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/sl_entropy_hardware.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/sl_mbedtls.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/version_features.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_protocol_crypto/src/sli_protocol_crypto_crypto.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_protocol_crypto/src/sli_protocol_crypto_radioaes.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/crypto_management.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sl_psa_its_nvm3.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_crypto_transparent_driver_aead.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_crypto_transparent_driver_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_crypto_transparent_driver_hash.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_crypto_transparent_driver_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_crypto_trng_driver.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_psa_driver_common.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_psa_driver_init.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_psa_trng.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_builtin_keys.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_signature.c", - "${efr32_sdk_root}/util/third_party/freertos/cmsis/Source/cmsis_os2.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/croutine.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/event_groups.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/list.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/queue.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/stream_buffer.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/tasks.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/timers.c", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/autogen/gatt_db.c", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/autogen/sl_bluetooth.c", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/autogen/sl_board_default_init.c", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/autogen/sl_device_init_clocks.c", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/autogen/sl_event_handler.c", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/autogen/sl_simple_button_instances.c", + "${examples_plat_dir}/device/src/startup_RS1xxxx.c", + "${sdk_support_root}/platform/emdrv/nvm3/src/ccp_flash_dev.c", + "${sdk_support_root}/platform/emdrv/nvm3/src/ccp_flash_intf.c", + "${sdk_support_root}/platform/emdrv/nvm3/src/ccp_flash_prg.c", + "${sdk_support_root}/platform/emdrv/nvm3/src/nvm3_default.c", + + ### nvm3 for ccp platform ### + "${sdk_support_root}/platform/emdrv/nvm3/src/nvm3_hal_flash_ccp.c", + "${sdk_support_root}/platform/emdrv/nvm3/src/nvm3_lock.c", + + ######## CCP Platform ######### + "${wiseconnect_sdk_root}/platforms/si91x/boards/brd4325a/src/rsi_board.c", + + #"${wiseconnect_sdk_root}/platforms/si91x/boards/brd4325a/src/syscalls.c", + "${wiseconnect_sdk_root}/platforms/si91x/core/chip/src/rsi_deepsleep_commonflash.c", + "${wiseconnect_sdk_root}/platforms/si91x/core/chip/src/rsi_ps_ram_func.c", + "${wiseconnect_sdk_root}/platforms/si91x/core/chip/src/rsi_system_config.c", + "${wiseconnect_sdk_root}/platforms/si91x/core/chip/src/system_RS1xxxx.c", + + #"${wiseconnect_sdk_root}/platforms/si91x/drivers/cmsis_driver/UDMA.c", + #"${wiseconnect_sdk_root}/platforms/si91x/drivers/cmsis_driver/USART.c", + + "${wiseconnect_sdk_root}/platforms/si91x/drivers/peripheral_drivers/src/clock_update.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/peripheral_drivers/src/rsi_comparator.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/peripheral_drivers/src/rsi_egpio.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/peripheral_drivers/src/rsi_udma.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/peripheral_drivers/src/rsi_udma_wrapper.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/peripheral_drivers/src/rsi_usart.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/src/rsi_ipmu.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/src/rsi_pll.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/src/rsi_power_save.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/src/rsi_processor_sensor.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/src/rsi_rtc.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/src/rsi_temp_sensor.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/src/rsi_time_period.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/src/rsi_ulpss_clk.c", + "${wiseconnect_sdk_root}/platforms/si91x/drivers/systemlevel/src/rsi_wwdt.c", + "${wiseconnect_sdk_root}/third_party/freertos/croutine.c", + "${wiseconnect_sdk_root}/third_party/freertos/event_groups.c", + "${wiseconnect_sdk_root}/third_party/freertos/list.c", + "${wiseconnect_sdk_root}/third_party/freertos/portable/GCC/ARM_CM4F/port.c", + "${wiseconnect_sdk_root}/third_party/freertos/queue.c", + "${wiseconnect_sdk_root}/third_party/freertos/stream_buffer.c", + "${wiseconnect_sdk_root}/third_party/freertos/tasks.c", + "${wiseconnect_sdk_root}/third_party/freertos/timers.c", + + # Bluetooth + "${wiseconnect_sdk_root}/sapi/bluetooth/rsi_ble_gap_apis.c", + "${wiseconnect_sdk_root}/sapi/bluetooth/rsi_ble_gatt_apis.c", + "${wiseconnect_sdk_root}/sapi/bluetooth/rsi_bt_common_apis.c", + "${wiseconnect_sdk_root}/sapi/driver/rsi_bt_ble.c", + + # mbedtls + "${chip_root}/third_party/mbedtls/repo/library/aes.c", + "${chip_root}/third_party/mbedtls/repo/library/asn1parse.c", + "${chip_root}/third_party/mbedtls/repo/library/asn1write.c", + "${chip_root}/third_party/mbedtls/repo/library/bignum.c", + "${chip_root}/third_party/mbedtls/repo/library/ccm.c", + "${chip_root}/third_party/mbedtls/repo/library/cipher.c", + "${chip_root}/third_party/mbedtls/repo/library/cipher_wrap.c", + "${chip_root}/third_party/mbedtls/repo/library/constant_time.c", + "${chip_root}/third_party/mbedtls/repo/library/ctr_drbg.c", + "${chip_root}/third_party/mbedtls/repo/library/ecdh.c", + "${chip_root}/third_party/mbedtls/repo/library/ecdsa.c", + "${chip_root}/third_party/mbedtls/repo/library/ecp.c", + "${chip_root}/third_party/mbedtls/repo/library/ecp_curves.c", + "${chip_root}/third_party/mbedtls/repo/library/entropy.c", + "${chip_root}/third_party/mbedtls/repo/library/hkdf.c", + "${chip_root}/third_party/mbedtls/repo/library/hmac_drbg.c", + "${chip_root}/third_party/mbedtls/repo/library/md.c", + "${chip_root}/third_party/mbedtls/repo/library/oid.c", + "${chip_root}/third_party/mbedtls/repo/library/pk.c", + "${chip_root}/third_party/mbedtls/repo/library/pk_wrap.c", + "${chip_root}/third_party/mbedtls/repo/library/pkcs5.c", + "${chip_root}/third_party/mbedtls/repo/library/pkwrite.c", + "${chip_root}/third_party/mbedtls/repo/library/platform.c", + "${chip_root}/third_party/mbedtls/repo/library/platform_util.c", + "${chip_root}/third_party/mbedtls/repo/library/sha256.c", + "${chip_root}/third_party/mbedtls/repo/library/sha512.c", + "${chip_root}/third_party/mbedtls/repo/library/x509_create.c", + "${chip_root}/third_party/mbedtls/repo/library/x509write_csr.c", ] - if (use_system_view) { - sources += [ - "${efr32_sdk_root}/util/third_party/segger/systemview/SEGGER/SEGGER_SYSVIEW.c", - "${efr32_sdk_root}/util/third_party/segger/systemview/Sample/FreeRTOSV10/Config/Cortex-M/SEGGER_SYSVIEW_Config_FreeRTOS.c", - "${efr32_sdk_root}/util/third_party/segger/systemview/Sample/FreeRTOSV10/SEGGER_SYSVIEW_FreeRTOS.c", - ] - } - - if (use_wstk_leds) { - sources += [ - "${efr32_sdk_root}/platform/driver/leddrv/src/sl_led.c", - "${efr32_sdk_root}/platform/driver/leddrv/src/sl_pwm_led.c", - "${efr32_sdk_root}/platform/driver/leddrv/src/sl_simple_led.c", - "${efr32_sdk_root}/platform/driver/leddrv/src/sl_simple_rgb_pwm_led.c", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/autogen/sl_simple_led_instances.c", - ] - } - - # SPI is only used for Wifi - if (defined(invoker.chip_enable_wifi) && invoker.chip_enable_wifi) { - sources += [ - "${efr32_sdk_root}/platform/emdrv/spidrv/src/spidrv.c", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/autogen/sl_spidrv_init.c", - ] - } - - if (defined(invoker.enable_sleepy_device)) { - if (invoker.enable_sleepy_device) { - sources += [ "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/SiliconLabs/tick_power_manager.c" ] - } - } - - if (defined(enable_fem)) { - sources += [ - "${efr32_sdk_root}/util/plugin/plugin-common/fem-control/fem-control.c", - ] - } - - # USART sources files - if ((defined(invoker.chip_enable_pw_rpc) && invoker.chip_enable_pw_rpc) || - chip_build_libshell || enable_openthread_cli || - (defined(invoker.chip_enable_wifi) && invoker.chip_enable_wifi) || - (defined(invoker.show_qr_code) && invoker.show_qr_code) || - (defined(invoker.disable_lcd) && !invoker.disable_lcd) || - (defined(invoker.use_external_flash) && use_external_flash)) { - sources += [ - "${efr32_sdk_root}/hardware/driver/memlcd/src/memlcd_usart/sl_memlcd_spi.c", - "${efr32_sdk_root}/platform/emdrv/uartdrv/src/uartdrv.c", - "${efr32_sdk_root}/platform/emlib/src/em_eusart.c", - "${efr32_sdk_root}/platform/emlib/src/em_leuart.c", - "${efr32_sdk_root}/platform/emlib/src/em_usart.c", - "${sdk_support_root}/matter/efr32/${silabs_family}/${silabs_board}/autogen/sl_uartdrv_init.c", - ] - - if (defined(invoker.use_external_flash) && use_external_flash) { - sources += [ "${efr32_sdk_root}/hardware/driver/mx25_flash_shutdown/src/sl_mx25_flash_shutdown_usart/sl_mx25_flash_shutdown.c" ] - } - } - - if ((defined(invoker.show_qr_code) && invoker.show_qr_code) || - (defined(invoker.disable_lcd) && !invoker.disable_lcd)) { - sources += [ - "${efr32_sdk_root}/hardware/driver/memlcd/src/sl_memlcd.c", - "${efr32_sdk_root}/hardware/driver/memlcd/src/sl_memlcd_display.c", - "${efr32_sdk_root}/platform/middleware/glib/dmd/display/dmd_memlcd.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/bmp.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/glib.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/glib_bitmap.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/glib_circle.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/glib_font_narrow_6x8.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/glib_font_normal_8x8.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/glib_font_number_16x20.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/glib_line.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/glib_polygon.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/glib_rectangle.c", - "${efr32_sdk_root}/platform/middleware/glib/glib/glib_string.c", - ] - } - - if (use_wf200) { - sources += [ - "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/bus/sl_wfx_bus.c", - "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/bus/sl_wfx_bus_spi.c", - "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/secure_link/sl_wfx_secure_link.c", - "${efr32_sdk_root}/platform/radio/wifi/wfx_fmac_driver/sl_wfx.c", - ] - } - - if (silabs_family == "efr32mg12") { - sources += [ - "${efr32_sdk_root}/platform/Device/SiliconLabs/EFR32MG12P/Source/startup_efr32mg12p.c", - "${efr32_sdk_root}/platform/Device/SiliconLabs/EFR32MG12P/Source/system_efr32mg12p.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_dcdc_s1.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_emu_s1.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_hfxo_s1.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_lfxo_s1.c", - "${efr32_sdk_root}/protocol/bluetooth/src/sl_apploader_util_s1.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM4F/port.c", - ] - } else if (silabs_family == "efr32mg21") { - sources += [ - "${efr32_sdk_root}/platform/Device/SiliconLabs/EFR32MG21/Source/startup_efr32mg21.c", - "${efr32_sdk_root}/platform/Device/SiliconLabs/EFR32MG21/Source/system_efr32mg21.c", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/rail_util_rf_path/sl_rail_util_rf_path.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_emu_s2.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_hfrco.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_hfxo_s2.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_lfxo_s2.c", - "${efr32_sdk_root}/platform/service/hfxo_manager/src/sl_hfxo_manager_hal_s2.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_entropy.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_hash.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_key_derivation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_key_handling.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_signature.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_util.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_alt/source/sl_se_management.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/se_aes.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/se_gcm.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/se_jpake.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_protocol_crypto/src/sli_radioaes_management.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_aead.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_key_derivation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_key_management.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_driver_aead.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_driver_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_driver_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_key_derivation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_hash.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_key_derivation.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM33_NTZ/non_secure/port.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM33_NTZ/non_secure/portasm.c", - ] - } else if (silabs_family == "efr32mg24") { - sources += [ - "${efr32_sdk_root}/platform/Device/SiliconLabs/EFR32MG24/Source/startup_efr32mg24.c", - "${efr32_sdk_root}/platform/Device/SiliconLabs/EFR32MG24/Source/system_efr32mg24.c", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions/pa_curves_efr32.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_dcdc_s2.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_emu_s2.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_hfxo_s2.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_lfxo_s2.c", - "${efr32_sdk_root}/platform/service/hfxo_manager/src/sl_hfxo_manager_hal_s2.c", - "${efr32_sdk_root}/protocol/bluetooth/src/sl_apploader_util_s2.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_attestation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_entropy.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_hash.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_key_derivation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_key_handling.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_signature.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_util.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/se_aes.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/se_jpake.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_protocol_crypto/src/sli_radioaes_management.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_aead.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_key_derivation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_key_management.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_driver_aead.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_driver_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_driver_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_key_derivation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_aead.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_hash.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_key_derivation.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM33_NTZ/non_secure/port.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM33_NTZ/non_secure/portasm.c", - ] - } else if (silabs_family == "mgm24") { - sources += [ - "${efr32_sdk_root}/platform/Device/SiliconLabs/MGM24/Source/startup_mgm24.c", - "${efr32_sdk_root}/platform/Device/SiliconLabs/MGM24/Source/system_mgm24.c", - "${efr32_sdk_root}/platform/radio/rail_lib/plugin/pa-conversions/pa_curves_efr32.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_dcdc_s2.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_emu_s2.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_hfxo_mgm24.c", - "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_lfxo_s2.c", - "${efr32_sdk_root}/platform/service/hfxo_manager/src/sl_hfxo_manager_hal_s2.c", - "${efr32_sdk_root}/protocol/bluetooth/src/sl_apploader_util_s2.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_attestation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_entropy.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_hash.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_key_derivation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_key_handling.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_signature.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/se_manager/src/sl_se_manager_util.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/se_aes.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_mbedtls_support/src/se_jpake.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_protocol_crypto/src/sli_radioaes_management.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_aead.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_key_derivation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_key_management.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_driver_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_driver_aead.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_driver_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_driver_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_opaque_key_derivation.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_aead.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_cipher.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_hash.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_driver_mac.c", - "${efr32_sdk_root}/util/third_party/crypto/sl_component/sl_psa_driver/src/sli_se_transparent_key_derivation.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM33_NTZ/non_secure/port.c", - "${efr32_sdk_root}/util/third_party/freertos/kernel/portable/GCC/ARM_CM33_NTZ/non_secure/portasm.c", - ] - } - - if (silabs_board == "BRD4186A" || silabs_board == "BRD4186C" || - silabs_board == "BRD4187A" || silabs_board == "BRD4187C") { - sources += [ "${efr32_sdk_root}/platform/service/device_init/src/sl_device_init_dpll_s2.c" ] - } - public_deps = [ - ":efr32_mbedtls_config", + ":si917_mbedtls_config", "${segger_rtt_root}:segger_rtt", "${segger_rtt_root}:segger_rtt_printf", "${segger_rtt_root}:segger_rtt_syscalls", diff --git a/third_party/silabs/efr32_arm.gni b/third_party/silabs/efr32_arm.gni index e1696309677ae2..68126f50843c8d 100644 --- a/third_party/silabs/efr32_arm.gni +++ b/third_party/silabs/efr32_arm.gni @@ -14,7 +14,7 @@ import("silabs_board.gni") -if (silabs_family == "efr32mg12") { +if (silabs_family == "efr32mg12" || silabs_family == "SiWx917") { arm_arch = "armv7e-m" arm_abi = "aapcs" arm_cpu = "cortex-m4" diff --git a/third_party/silabs/silabs_board.gni b/third_party/silabs/silabs_board.gni index b5fe904a1e9561..1e638c9351a2b6 100644 --- a/third_party/silabs/silabs_board.gni +++ b/third_party/silabs/silabs_board.gni @@ -59,6 +59,9 @@ if (silabs_board == "BRD4304A") { } else if (silabs_board == "BRD4170A") { silabs_family = "efr32mg12" silabs_mcu = "EFR32MG12P433F1024GM68" +} else if (silabs_board == "BRD4325A") { + silabs_family = "SiWx917" + silabs_mcu = "EFR32MG12P432F1024GL125" } else if (silabs_board == "BRD4180A") { assert( false,