diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index 69399f966feadf..89ce34049850a6 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -55,7 +55,7 @@ jobs: run: | ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ - --target bouffalolab-bl602-iot-matter-v1-light \ + --target bouffalolab-bl602-night-light-light \ --target bouffalolab-bl602-iot-matter-v1-light-115200-rpc \ build \ --copy-artifacts-to out/artifacts \ @@ -64,7 +64,7 @@ jobs: run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ bl602 bl602 lighting-app \ - out/artifacts/bouffalolab-bl602-iot-matter-v1-light/chip-bl602-lighting-example.out \ + out/artifacts/bouffalolab-bl602-night-light-light/chip-bl602-lighting-example.out \ /tmp/bloat_reports/ .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ bl602 bl602+rpc lighting-app \ @@ -77,7 +77,9 @@ jobs: run: | ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ - --target bouffalolab-xt-zb6-devkit-light \ + --target bouffalolab-bl706-night-light-light \ + --target bouffalolab-bl706-eth-light \ + --target bouffalolab-bl706-wifi-light \ --target bouffalolab-xt-zb6-devkit-light-115200-rpc \ build \ --copy-artifacts-to out/artifacts \ @@ -86,7 +88,15 @@ jobs: run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ bl702 bl702 lighting-app \ - out/artifacts/bouffalolab-xt-zb6-devkit-light/chip-bl702-lighting-example.out \ + out/artifacts/bouffalolab-bl706-night-light-light/chip-bl702-lighting-example.out \ + /tmp/bloat_reports/ + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ + bl702 bl706-eth lighting-app \ + out/artifacts/bouffalolab-bl706-eth-light/chip-bl702-lighting-example.out \ + /tmp/bloat_reports/ + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ + bl702 bl706-wifi lighting-app \ + out/artifacts/bouffalolab-bl706-wifi-light/chip-bl702-lighting-example.out \ /tmp/bloat_reports/ .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ bl702 bl702+rpc lighting-app \ diff --git a/examples/lighting-app/bouffalolab/bl602/BUILD.gn b/examples/lighting-app/bouffalolab/bl602/BUILD.gn index 592cc5a2fbe72a..3470110722b5fe 100644 --- a/examples/lighting-app/bouffalolab/bl602/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl602/BUILD.gn @@ -20,6 +20,7 @@ import("${bouffalolab_iot_sdk_build_root}/bl602/bl_iot_sdk.gni") import("${bouffalolab_iot_sdk_build_root}/common/bouffalolab_executable.gni") import("${build_root}/config/defaults.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") +import("${chip_root}/src/platform/bouffalolab/common/args.gni") import("${chip_root}/src/platform/device.gni") import("${chip_root}/src/app/chip_data_model.gni") diff --git a/examples/lighting-app/bouffalolab/bl602/CHIPProjectConfig.h b/examples/lighting-app/bouffalolab/bl602/CHIPProjectConfig.h index 3e779aea1ef5fd..24dd8a2c395383 100644 --- a/examples/lighting-app/bouffalolab/bl602/CHIPProjectConfig.h +++ b/examples/lighting-app/bouffalolab/bl602/CHIPProjectConfig.h @@ -126,9 +126,3 @@ #define CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE 128 #define CHIP_BLE_DEVICE_NAME "MatterLight" - -/** Please contact Bouffalo Lab for how to use factory data provider */ -// #define CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE 1 -// uncomment out the following macro to use factory test data -// when CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE sets to 1 -// #define CONFIG_BOUFFALOLAB_FACTORY_DATA_TEST diff --git a/examples/lighting-app/bouffalolab/bl702/BUILD.gn b/examples/lighting-app/bouffalolab/bl702/BUILD.gn index b382aa7bc95cbc..47ba339669ca8e 100644 --- a/examples/lighting-app/bouffalolab/bl702/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702/BUILD.gn @@ -136,6 +136,8 @@ bouffalolab_executable("lighting_app") { defines += [ "BL706_NIGHT_LIGHT" ] } else if ("BL706-ETH" == board) { defines += [ "BL706_ETHERNET" ] + } else if ("BL706-WIFI" == board) { + defines += [ "BL706_WIFI" ] } if (defined(enable_cdc_module) && enable_cdc_module) { diff --git a/examples/platform/bouffalolab/common/plat/platform.cpp b/examples/platform/bouffalolab/common/plat/platform.cpp index d2e6a434e91296..b0d73daa3a2bbc 100644 --- a/examples/platform/bouffalolab/common/plat/platform.cpp +++ b/examples/platform/bouffalolab/common/plat/platform.cpp @@ -166,10 +166,6 @@ void ChipEventHandler(const ChipDeviceEvent * event, intptr_t arg) CHIP_ERROR PlatformManagerImpl::PlatformInit(void) { -#if CONFIG_ENABLE_CHIP_SHELL || PW_RPC_ENABLED - uartInit(); -#endif - #if PW_RPC_ENABLED PigweedLogger::pw_init(); #elif CONFIG_ENABLE_CHIP_SHELL diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index 609400764e0c72..1f25e6edaa976d 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -602,6 +602,8 @@ def BuildBouffalolabTarget(): board=BouffalolabBoard.BL706_NIGHT_LIGHT, module_type="BL706C-22"), TargetPart('BL706-ETH', board=BouffalolabBoard.BL706_ETH, module_type="BL706C-22"), + TargetPart('BL706-WIFI', + board=BouffalolabBoard.BL706_WIFI, module_type="BL706C-22"), TargetPart('BL704L-DVK', board=BouffalolabBoard.BL704L_DVK, module_type="BL704L"), ]) diff --git a/scripts/build/builders/bouffalolab.py b/scripts/build/builders/bouffalolab.py index 20ef4c75046862..d91f5d5633f318 100644 --- a/scripts/build/builders/bouffalolab.py +++ b/scripts/build/builders/bouffalolab.py @@ -47,6 +47,7 @@ class BouffalolabBoard(Enum): XT_ZB6_DevKit = auto() BL706_NIGHT_LIGHT = auto() BL706_ETH = auto() + BL706_WIFI = auto() BL704L_DVK = auto() def GnArgName(self): @@ -60,6 +61,8 @@ def GnArgName(self): return 'BL706-NIGHT-LIGHT' elif self == BouffalolabBoard.BL706_ETH: return 'BL706-ETH' + elif self == BouffalolabBoard.BL706_WIFI: + return 'BL706-WIFI' elif self == BouffalolabBoard.BL704L_DVK: return 'BL704L-DVK' else: @@ -120,6 +123,9 @@ def __init__(self, self.argsOpt.append('chip_config_network_layer_ble=false') self.argsOpt.append('chip_enable_openthread=false') self.argsOpt.append('chip_enable_wifi=false') + elif board == BouffalolabBoard.BL706_WIFI: + self.argsOpt.append('chip_enable_openthread=false') + self.argsOpt.append('chip_enable_wifi=true') else: self.argsOpt.append('chip_enable_openthread=true') self.argsOpt.append('chip_enable_wifi=false') diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index 1ac764d6f1afb0..d333ff86dc3e43 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -1,7 +1,7 @@ ameba-amebad-{all-clusters,all-clusters-minimal,light,light-switch,pigweed} asr-{asr582x,asr595x,asr550x}-{all-clusters,all-clusters-minimal,lighting,light-switch,lock,bridge,temperature-measurement,thermostat,ota-requestor,dishwasher}[-ota][-shell][-no_logging][-factory][-rotating_id][-rio] android-{arm,arm64,x86,x64,androidstudio-arm,androidstudio-arm64,androidstudio-x86,androidstudio-x64}-{chip-tool,chip-test,tv-server,tv-casting-app,java-matter-controller,virtual-device-app}[-no-debug] -bouffalolab-{bl602-iot-matter-v1,bl602-night-light,xt-zb6-devkit,bl706-night-light,bl706-eth,bl704l-dvk}-light[-shell][-115200][-rpc][-cdc][-resetcnt][-rotating_device_id] +bouffalolab-{bl602-iot-matter-v1,bl602-night-light,xt-zb6-devkit,bl706-night-light,bl706-eth,bl706-wifi,bl704l-dvk}-light[-shell][-115200][-rpc][-cdc][-resetcnt][-rotating_device_id] cc32xx-lock ti-cc13x2x7_26x2x7-{lighting,lock,pump,pump-controller}[-mtd] ti-cc13x4_26x4-{all-clusters,lighting,lock,pump,pump-controller}[-mtd][-ftd] diff --git a/scripts/examples/gn_bouffalolab_example.sh b/scripts/examples/gn_bouffalolab_example.sh index 99d70a2de70aef..3942d796896027 100755 --- a/scripts/examples/gn_bouffalolab_example.sh +++ b/scripts/examples/gn_bouffalolab_example.sh @@ -26,10 +26,14 @@ source "$MATTER_ROOT/scripts/activate.sh" bl602_boards=("BL602-IoT-Matter-V1" "BL602-NIGHT-LIGHT") bl602_module_type="BL602" -bl702_boards=("XT-ZB6-DevKit" "BL706-IoT-DVK" "BL706-NIGHT-LIGHT") +bl702_boards=("XT-ZB6-DevKit" "BL706-NIGHT-LIGHT" "BL706-ETH" "BL706-WIFI") bl702_modules=("BL702" "BL706C-22") bl702_module_type="BL706C-22" +bl702l_boards=("BL704L-DVK") +bl702l_modules=("BL702L") +bl702l_module_type="BL704l" + print_help() { bl602_boards_help="" for board in "${bl602_boards[@]}"; do @@ -39,6 +43,10 @@ print_help() { for board in "${bl702_boards[@]}"; do bl702_boards_help=$bl702_boards_help$board"\n " done + bl702l_boards_help="" + for board in "${bl702l_boards[@]}"; do + bl702l_boards_help=$bl702l_boards_help$board"\n " + done echo -e "Build script for Bouffalolab Matter examples Format: @@ -55,6 +63,7 @@ print_help() { Currently Supported : $bl602_boards_help $bl702_boards_help + $bl702l_boards_help - optional noteworthy build options for Bouffalolab IOT Matter examples chip_build_libshell Enable libshell support. (Default false) @@ -120,6 +129,9 @@ else optArgs=board=\"$board_name\"" "$optArgs optArgs=module_type=\"$bl602_module_type\"" "$optArgs optArgs=baudrate=\"$baudrate\"" "$optArgs + optArgs=baudrate=\"$baudrate\"" "$optArgs + optArgs=chip_enable_openthread=false" "$optArgs + optArgs=chip_enable_wifi=true" "$optArgs elif [[ "${bl702_boards[@]}" =~ "$board_name" ]]; then bouffalo_chip="bl702" @@ -136,6 +148,37 @@ else fi optArgs=baudrate=\"$baudrate\"" "$optArgs + + if [[ "$board_name" == "BL706-ETH" ]]; then + optArgs=chip_config_network_layer_ble=false" "$optArgs + optArgs=chip_enable_openthread=false" "$optArgs + optArgs=chip_enable_wifi=false" "$optArgs + elif [[ "$board_name" == "BL706-WIFI" ]]; then + optArgs=chip_enable_openthread=false" "$optArgs + optArgs=chip_enable_wifi=true" "$optArgs + else + optArgs=chip_enable_openthread=true" "$optArgs + optArgs=chip_enable_wifi=false" "$optArgs + fi + + elif [[ "${bl702l_boards[@]}" =~ "$board_name" ]]; then + bouffalo_chip="bl702l" + + optArgs=board=\"$board_name\"" "$optArgs + + if [[ "$module_type" != "" ]]; then + if [[ ! "${bl702l_modules[@]}" =~ "$module_type" ]]; then + echo "Module $module_type is not supported." + exit 1 + fi + + optArgs=module_type=\"$module_type\"" "$optArgs + fi + + optArgs=baudrate=\"$baudrate\"" "$optArgs + optArgs=chip_enable_openthread=true" "$optArgs + optArgs=chip_enable_wifi=false" "$optArgs + else echo "Board $board_name is not supported." exit 1 diff --git a/src/platform/bouffalolab/BL602/BUILD.gn b/src/platform/bouffalolab/BL602/BUILD.gn index 0f414afb036db6..51fdd019d527ec 100644 --- a/src/platform/bouffalolab/BL602/BUILD.gn +++ b/src/platform/bouffalolab/BL602/BUILD.gn @@ -17,6 +17,8 @@ import("//build_overrides/chip.gni") import("${chip_root}/src/platform/device.gni") +import("${chip_root}/src/platform/bouffalolab/common/args.gni") + assert(chip_device_platform == "bl602") static_library("BL602") { @@ -30,34 +32,43 @@ static_library("BL602") { ] common_sources = [ - "${chip_root}/src/credentials/CHIPCert.h", - "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", "../../FreeRTOS/SystemTimeSupport.cpp", "../../SingletonConfigurationManager.cpp", "../common/BLConfig.cpp", "../common/ConfigurationManagerImpl.cpp", "../common/ConnectivityManagerImpl.cpp", "../common/DiagnosticDataProviderImpl.cpp", - "../common/FactoryDataProvider.cpp", - "../common/FactoryDataProvider.h", "../common/KeyValueStoreManagerImpl.cpp", "../common/Logging.cpp", "../common/PlatformManagerImpl.cpp", ] if (chip_enable_ota_requestor) { - sources += [ + common_sources += [ "../common/OTAImageProcessorImpl.cpp", "../common/OTAImageProcessorImpl.h", ] } if (chip_enable_ble) { - sources += [ + common_sources += [ "../common/BLEManagerImpl.cpp", "../common/BLEManagerImpl.h", ] } + + if (chip_enable_factory_data || chip_enable_factory_data_test) { + if (chip_enable_factory_data) { + defines = [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE" ] + } + common_sources += [ + "${chip_root}/src/credentials/CHIPCert.h", + "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", + "../common/FactoryDataProvider.cpp", + "../common/FactoryDataProvider.h", + ] + } + sources += common_sources deps = [ "${chip_root}/src/lib/dnssd:platform_header" ] diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp index 9cf57c3c5e74d0..d9dd83c923cd57 100644 --- a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp +++ b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp @@ -44,10 +44,10 @@ CHIP_ERROR BLWiFiDriver::Init(NetworkStatusChangeCallback * networkStatusChangeC size_t ssidLen = 0; size_t credentialsLen = 0; - err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kBLConfigKey_wifissid, mSavedNetwork.credentials, + err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiSSID, mSavedNetwork.credentials, sizeof(mSavedNetwork.credentials), &credentialsLen); SuccessOrExit(err); - err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kBLConfigKey_wifipassword, mSavedNetwork.ssid, + err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiPassword, mSavedNetwork.ssid, sizeof(mSavedNetwork.ssid), &ssidLen); SuccessOrExit(err); @@ -78,8 +78,8 @@ CHIP_ERROR BLWiFiDriver::CommitConfiguration() { ChipLogProgress(NetworkProvisioning, "BLWiFiDriver::CommitConfiguration"); ReturnErrorOnFailure( - PersistedStorage::KeyValueStoreMgr().Put(BLConfig::kBLConfigKey_wifissid, mStagingNetwork.ssid, mStagingNetwork.ssidLen)); - ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Put(BLConfig::kBLConfigKey_wifipassword, mStagingNetwork.credentials, + PersistedStorage::KeyValueStoreMgr().Put(BLConfig::kConfigKey_WiFiSSID, mStagingNetwork.ssid, mStagingNetwork.ssidLen)); + ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Put(BLConfig::kConfigKey_WiFiPassword, mStagingNetwork.credentials, mStagingNetwork.credentialsLen)); mSavedNetwork = mStagingNetwork; return CHIP_NO_ERROR; diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.h b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.h index edf2d3f04d90a4..7e0fd1b30727a1 100644 --- a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.h +++ b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.h @@ -22,7 +22,7 @@ namespace chip { namespace DeviceLayer { namespace NetworkCommissioning { -// #if CHIP_DEVICE_CONFIG_ENABLE_WIFI + namespace { constexpr uint8_t kMaxWiFiNetworks = 1; constexpr uint8_t kWiFiScanNetworksTimeOutSeconds = 10; @@ -134,7 +134,6 @@ class BLWiFiDriver final : public WiFiDriver NetworkStatusChangeCallback * mpStatusChangeCallback = nullptr; int32_t mLastDisconnectedReason; }; -// #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI } // namespace NetworkCommissioning } // namespace DeviceLayer diff --git a/src/platform/bouffalolab/BL702/BUILD.gn b/src/platform/bouffalolab/BL702/BUILD.gn index e32738e9a59530..fcc8324b5121a7 100644 --- a/src/platform/bouffalolab/BL702/BUILD.gn +++ b/src/platform/bouffalolab/BL702/BUILD.gn @@ -17,6 +17,8 @@ import("//build_overrides/chip.gni") import("${chip_root}/src/platform/device.gni") +import("${chip_root}/src/platform/bouffalolab/common/args.gni") + assert(chip_device_platform == "bl702") assert(false == (chip_enable_wifi && chip_enable_openthread), "Not support Wi-Fi and Thread together") @@ -41,30 +43,46 @@ static_library("BL702") { "../common/KeyValueStoreManagerImpl.cpp", "../common/Logging.cpp", "../common/PlatformManagerImpl.cpp", - - # "${chip_root}/src/credentials/CHIPCert.h", - # "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", - - # "../common/FactoryDataProvider.cpp", - # "../common/FactoryDataProvider.h", ] if (chip_enable_ota_requestor) { - sources += [ + common_sources += [ "../common/OTAImageProcessorImpl.cpp", "../common/OTAImageProcessorImpl.h", ] } if (chip_enable_ble) { - sources += [ + common_sources += [ "../common/BLEManagerImpl.cpp", "../common/BLEManagerImpl.h", ] } + + if (chip_enable_factory_data || chip_enable_factory_data_test) { + if (chip_enable_factory_data) { + defines = [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE" ] + } + common_sources += [ + "${chip_root}/src/credentials/CHIPCert.h", + "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", + "../common/FactoryDataProvider.cpp", + "../common/FactoryDataProvider.h", + ] + } + sources += common_sources - if (chip_enable_openthread) { + if (chip_enable_wifi) { + sources += [ + "ConfigurationManagerImpl.cpp", + "ConnectivityManagerImpl.cpp", + "NetworkCommissioningDriver.cpp", + "WiFiInterface.c", + ] + + deps = [ "${chip_root}/src/lib/dnssd:platform_header" ] + } else if (chip_enable_openthread) { # needed for MTD/FTD import("//build_overrides/bouffalolab_iot_sdk.gni") diff --git a/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.cpp b/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.cpp index 5a92ee10578fda..ec685f82ac7547 100644 --- a/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702/ConfigurationManagerImpl.cpp @@ -17,8 +17,11 @@ #include #include +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include +#endif -#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD & !CHIP_DEVICE_CONFIG_ENABLE_WIFI +#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD extern "C" { #include } @@ -27,7 +30,14 @@ extern "C" { namespace chip { namespace DeviceLayer { -#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD & !CHIP_DEVICE_CONFIG_ENABLE_WIFI +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * buf) +{ + wifiInterface_getMacAddress(buf); + + return CHIP_NO_ERROR; +} +#elif !CHIP_DEVICE_CONFIG_ENABLE_THREAD CHIP_ERROR ConfigurationManagerImpl::GetPrimaryMACAddress(MutableByteSpan buf) { if (buf.size() != ConfigurationManager::kPrimaryMACAddressLength) diff --git a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp index 09e0550170ba1b..3f3465554bfad0 100644 --- a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp @@ -21,7 +21,12 @@ #include -#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD && !CHIP_DEVICE_CONFIG_ENABLE_WIFI +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include +#include +#endif + +#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD #include #include #endif @@ -31,7 +36,82 @@ using namespace ::chip; namespace chip { namespace DeviceLayer { -#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD && !CHIP_DEVICE_CONFIG_ENABLE_WIFI +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +void ConnectivityManagerImpl::OnWiFiStationDisconnected() +{ + ChipDeviceEvent event; + event.Type = DeviceEventType::kWiFiConnectivityChange; + event.WiFiConnectivityChange.Result = kConnectivity_Lost; + PlatformMgr().PostEventOrDie(&event); + + NetworkCommissioning::BLWiFiDriver::GetInstance().SetLastDisconnectReason(NULL); + uint16_t reason = NetworkCommissioning::BLWiFiDriver::GetInstance().GetLastDisconnectReason(); + uint8_t associationFailureCause = + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::AssociationFailureCauseEnum::kUnknown); + WiFiDiagnosticsDelegate * delegate = GetDiagnosticDataProvider().GetWiFiDiagnosticsDelegate(); + if (delegate) + { + delegate->OnDisconnectionDetected(reason); + delegate->OnAssociationFailureDetected(associationFailureCause, reason); + delegate->OnConnectionStatusChanged( + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::ConnectionStatusEnum::kNotConnected)); + } +} + +extern "C" void wifiInterface_eventConnected(struct netif * interface) +{ + ChipLogProgress(DeviceLayer, "wifiInterface_eventConnected"); + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting_Succeeded); +} + +extern "C" void wifiInterface_eventDisconnected(struct netif * interface) +{ + ChipLogProgress(DeviceLayer, "wifiInterface_eventDisconnected"); + if (ConnectivityManager::kWiFiStationState_Connecting == ConnectivityMgrImpl().GetWiFiStationState()) + { + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting_Failed); + } + else + { + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_NotConnected); + } +} + +extern "C" void wifiInterface_eventLinkStatusDone(struct netif * interface, netbus_fs_link_status_ind_cmd_msg_t * pkg_data) +{ + ChipLogProgress(DeviceLayer, "wifiInterface_eventLinkStatusDone"); + + struct bflbwifi_ap_record * record = &pkg_data->record; + if (record->link_status == BF1B_WIFI_LINK_STATUS_UP) + { + ChipLogProgress(DeviceLayer, "link status up!"); + } + else if (record->link_status == BF1B_WIFI_LINK_STATUS_DOWN) + { + ChipLogProgress(DeviceLayer, "link status down!"); + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Disconnecting); + } + else + { + ChipLogProgress(DeviceLayer, "link status unknown!"); + } +} + +extern "C" void wifiInterface_eventGotIP(struct netif * interface) +{ + ChipLogProgress(DeviceLayer, "wifiInterface_eventGotIP"); + ConnectivityMgrImpl().OnConnectivityChanged(interface); + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connected); +} + +extern "C" void wifiInterface_eventScanDone(struct netif * interface, netbus_fs_scan_ind_cmd_msg_t * pmsg) +{ + ChipLogProgress(DeviceLayer, "wifiInterface_eventScanDone"); + NetworkCommissioning::BLWiFiDriver::GetInstance().OnScanWiFiNetworkDone(pmsg); +} +#endif + +#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD extern "C" void ethernetInterface_eventGotIP(struct netif * interface) { ChipLogProgress(DeviceLayer, "ethernetInterface_eventGotIP"); diff --git a/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp index cb067d31f357fc..1c93df0830875c 100644 --- a/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp +++ b/src/platform/bouffalolab/BL702/DiagnosticDataProviderImpl.cpp @@ -16,7 +16,10 @@ */ #include -#include + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include +#endif extern "C" { #include @@ -52,5 +55,122 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason return CHIP_NO_ERROR; } +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(MutableByteSpan & BssId) +{ + struct bflbwifi_ap_record ap_info; + + if (!wifiInterface_getApInfo(&ap_info)) + { + ChipLogError(DeviceLayer, "Failed to get ap info."); + return CHIP_ERROR_INTERNAL; + } + + return CopySpanToMutableSpan(ByteSpan(ap_info.bssid), BssId); +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) +{ + using app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum; + struct bflbwifi_ap_record ap_info; + + if (!wifiInterface_getApInfo(&ap_info)) + { + ChipLogError(DeviceLayer, "Failed to get ap info."); + return CHIP_ERROR_INTERNAL; + } + + if (ap_info.auth_mode < (uint8_t)(SecurityTypeEnum::kUnknownEnumValue)) + { + securityType = (SecurityTypeEnum)(ap_info.auth_mode); + } + else + { + securityType = SecurityTypeEnum::kUnknownEnumValue; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) +{ + struct bflbwifi_ap_record ap_info; + + if (!wifiInterface_getApInfo(&ap_info)) + { + ChipLogError(DeviceLayer, "Failed to get ap info."); + return CHIP_ERROR_INTERNAL; + } + + channelNumber = ap_info.channel; + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi) +{ + struct bflbwifi_ap_record ap_info; + + if (!wifiInterface_getApInfo(&ap_info)) + { + ChipLogError(DeviceLayer, "Failed to get ap info."); + return CHIP_ERROR_INTERNAL; + } + + rssi = ap_info.rssi; + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconLostCount(uint32_t & beaconLostCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiCurrentMaxRate(uint64_t & currentMaxRate) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastRxCount(uint32_t & packetMulticastRxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastTxCount(uint32_t & packetMulticastTxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastRxCount(uint32_t & packetUnicastRxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastTxCount(uint32_t & packetUnicastTxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiOverrunCount(uint64_t & overrunCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts() +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconRxCount(uint32_t & beaconRxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} +#endif } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.cpp new file mode 100644 index 00000000000000..6087fce9d94f66 --- /dev/null +++ b/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.cpp @@ -0,0 +1,370 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::DeviceLayer::Internal; + +//#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +namespace chip { +namespace DeviceLayer { +namespace NetworkCommissioning { + +CHIP_ERROR BLWiFiDriver::Init(NetworkStatusChangeCallback * networkStatusChangeCallback) +{ + CHIP_ERROR err; + size_t ssidLen = 0; + size_t credentialsLen = 0; + + err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiSSID, mSavedNetwork.ssid, sizeof(mSavedNetwork.ssid), + &ssidLen); + SuccessOrExit(err); + err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiPassword, mSavedNetwork.credentials, + sizeof(mSavedNetwork.credentials), &credentialsLen); + SuccessOrExit(err); + + mSavedNetwork.credentialsLen = credentialsLen; + mSavedNetwork.ssidLen = ssidLen; + mSavedNetwork.credentials[mSavedNetwork.credentialsLen] = '\0'; + mSavedNetwork.ssid[mSavedNetwork.ssidLen] = '\0'; + + mStagingNetwork = mSavedNetwork; + mpScanCallback = nullptr; + mpConnectCallback = nullptr; + mpStatusChangeCallback = networkStatusChangeCallback; + mScanSpecific = false; + +exit: + if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) + { + /** Not commissioned, SSID and Network Password not found. */ + return CHIP_NO_ERROR; + } + + return err; +} + +void BLWiFiDriver::Shutdown() +{ + mpStatusChangeCallback = nullptr; + mScanSpecific = false; + memset(mScanSSID, 0, sizeof(mScanSSID)); +} + +CHIP_ERROR BLWiFiDriver::CommitConfiguration() +{ + ChipLogProgress(NetworkProvisioning, "BLWiFiDriver::CommitConfiguration"); + ReturnErrorOnFailure( + PersistedStorage::KeyValueStoreMgr().Put(BLConfig::kConfigKey_WiFiSSID, mStagingNetwork.ssid, mStagingNetwork.ssidLen)); + ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Put(BLConfig::kConfigKey_WiFiPassword, mStagingNetwork.credentials, + mStagingNetwork.credentialsLen)); + mSavedNetwork = mStagingNetwork; + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLWiFiDriver::RevertConfiguration() +{ + mStagingNetwork = mSavedNetwork; + return CHIP_NO_ERROR; +} + +bool BLWiFiDriver::NetworkMatch(const WiFiNetwork & network, ByteSpan networkId) +{ + return networkId.size() == network.ssidLen && memcmp(networkId.data(), network.ssid, network.ssidLen) == 0; +} + +Status BLWiFiDriver::AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials, MutableCharSpan & outDebugText, + uint8_t & outNetworkIndex) +{ + outDebugText.reduce_size(0); + outNetworkIndex = 0; + + VerifyOrReturnError(mStagingNetwork.ssidLen == 0 || NetworkMatch(mStagingNetwork, ssid), Status::kBoundsExceeded); + VerifyOrReturnError(credentials.size() <= sizeof(mStagingNetwork.credentials), Status::kOutOfRange); + VerifyOrReturnError(ssid.size() <= sizeof(mStagingNetwork.ssid), Status::kOutOfRange); + + memcpy(mStagingNetwork.credentials, credentials.data(), credentials.size()); + mStagingNetwork.credentialsLen = static_cast(credentials.size()); + + memcpy(mStagingNetwork.ssid, ssid.data(), ssid.size()); + mStagingNetwork.ssidLen = static_cast(ssid.size()); + + return Status::kSuccess; +} + +Status BLWiFiDriver::RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) +{ + outDebugText.reduce_size(0); + outNetworkIndex = 0; + + VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); + + mStagingNetwork.ssidLen = 0; + return Status::kSuccess; +} + +Status BLWiFiDriver::ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) +{ + outDebugText.reduce_size(0); + // Only one network is supported now + VerifyOrReturnError(index == 0, Status::kOutOfRange); + VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); + return Status::kSuccess; +} + +CHIP_ERROR BLWiFiDriver::ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, const char * key, uint8_t keyLen) +{ + ChipLogProgress(NetworkProvisioning, "ConnectWiFiNetwork"); + wifiInterface_connect((char *) ssid, (char *) key); + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting); + return CHIP_NO_ERROR; +} + +void BLWiFiDriver::OnConnectWiFiNetwork(bool isConnected) +{ + ChipLogProgress(NetworkProvisioning, "BLWiFiDriver::OnConnectWiFiNetwork, isConnected=%d\r\n", isConnected); + if (mpConnectCallback) + { + if (isConnected) + { + mpConnectCallback->OnResult(Status::kSuccess, CharSpan(), 0); + } + else + { + mpConnectCallback->OnResult(Status::kUnknownError, CharSpan(), 0); + } + mpConnectCallback = nullptr; + } +} + +void BLWiFiDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + Status networkingStatus = Status::kSuccess; + + VerifyOrExit(NetworkMatch(mStagingNetwork, networkId), networkingStatus = Status::kNetworkIDNotFound); + VerifyOrExit(mpConnectCallback == nullptr, networkingStatus = Status::kUnknownError); + ChipLogProgress(NetworkProvisioning, "BL702 Network Commissioning ConnectNetwork: SSID: %.*s", + static_cast(networkId.size()), networkId.data()); + + mStagingNetwork.ssid[mStagingNetwork.ssidLen] = '\0'; + mStagingNetwork.credentials[mStagingNetwork.credentialsLen] = '\0'; + err = ConnectWiFiNetwork(reinterpret_cast(mStagingNetwork.ssid), mStagingNetwork.ssidLen, + reinterpret_cast(mStagingNetwork.credentials), mStagingNetwork.credentialsLen); + mpConnectCallback = callback; + +exit: + if (err != CHIP_NO_ERROR) + { + networkingStatus = Status::kUnknownError; + } + if (networkingStatus != Status::kSuccess) + { + ChipLogError(NetworkProvisioning, "Failed to connect to WiFi network:%s", chip::ErrorStr(err)); + mpConnectCallback = nullptr; + callback->OnResult(networkingStatus, CharSpan(), 0); + } +} + +void BLWiFiDriver::OnScanWiFiNetworkDone(void * arg) +{ + netbus_fs_scan_ind_cmd_msg_t * pmsg = (netbus_fs_scan_ind_cmd_msg_t *) arg; + size_t i = 0, ap_num = pmsg->num; + WiFiScanResponse *pScanResponse, *p; + + for (i = 0; i < pmsg->num; i++) + { + if (mScanSpecific && !strcmp(mScanSSID, (char *) (pmsg->records[i].ssid))) + { + ap_num = 1; + break; + } + } + + if (0 == ap_num || (mScanSpecific && ap_num == pmsg->num)) + { + ChipLogProgress(DeviceLayer, "No AP found"); + if (mpScanCallback != nullptr) + { + mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), nullptr); + mpScanCallback = nullptr; + } + return; + } + + p = pScanResponse = (WiFiScanResponse *) malloc(sizeof(WiFiScanResponse) * ap_num); + for (i = 0; i < pmsg->num; i++) + { + if (mScanSpecific && strcmp(mScanSSID, (char *) (pmsg->records[i].ssid))) + { + continue; + } + + p->security.SetRaw(pmsg->records[i].auth_mode); + p->ssidLen = strlen((char *) pmsg->records[i].ssid) < chip::DeviceLayer::Internal::kMaxWiFiSSIDLength + ? strlen((char *) pmsg->records[i].ssid) + : chip::DeviceLayer::Internal::kMaxWiFiSSIDLength; + p->channel = pmsg->records[i].channel; + p->wiFiBand = chip::DeviceLayer::NetworkCommissioning::WiFiBand::k2g4; + p->rssi = pmsg->records[i].rssi; + memcpy(p->ssid, pmsg->records[i].ssid, p->ssidLen); + memcpy(p->bssid, pmsg->records[i].bssid, 6); + + if (mScanSpecific) + { + break; + } + + p++; + } + + if (CHIP_NO_ERROR == DeviceLayer::SystemLayer().ScheduleLambda([ap_num, pScanResponse]() { + BLScanResponseIterator iter(ap_num, pScanResponse); + if (GetInstance().mpScanCallback) + { + GetInstance().mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), &iter); + GetInstance().mpScanCallback = nullptr; + } + else + { + ChipLogError(DeviceLayer, "can't find the ScanCallback function"); + } + })) + { + ChipLogProgress(DeviceLayer, "ScheduleLambda OK"); + } + + free(pScanResponse); +} + +void BLWiFiDriver::ScanNetworks(ByteSpan ssid, WiFiDriver::ScanCallback * callback) +{ + if (callback != nullptr) + { + if (ssid.data()) + { + memset(mScanSSID, 0, sizeof(mScanSSID)); + memcpy(mScanSSID, ssid.data(), ssid.size()); + mScanSpecific = true; + } + mpScanCallback = callback; + wifiInterface_startScan(); + } +} + +CHIP_ERROR GetConfiguredNetwork(Network & network) +{ + struct bflbwifi_ap_record ap_info; + + ChipLogProgress(DeviceLayer, "GetConfiguredNetwork"); + + if (!wifiInterface_getApInfo(&ap_info)) + { + return CHIP_ERROR_INTERNAL; + } + + uint8_t length = strnlen(reinterpret_cast(ap_info.ssid), DeviceLayer::Internal::kMaxWiFiSSIDLength); + if (length > sizeof(network.networkID)) + { + ChipLogError(DeviceLayer, "SSID too long"); + return CHIP_ERROR_INTERNAL; + } + memcpy(network.networkID, ap_info.ssid, length); + network.networkIDLen = length; + return CHIP_NO_ERROR; +} + +void BLWiFiDriver::OnNetworkStatusChange() +{ + Network configuredNetwork; + bool staConnected = false; + + ChipLogProgress(DeviceLayer, "OnNetworkStatusChange"); + + VerifyOrReturn(mpStatusChangeCallback != nullptr); + + if (CHIP_NO_ERROR != GetConfiguredNetwork(configuredNetwork)) + { + ChipLogError(DeviceLayer, "Failed to get configured network when updating network status."); + return; + } + + if (ConnectivityMgrImpl().GetWiFiStationState() == ConnectivityManager::kWiFiStationState_Connected) + { + staConnected = true; + } + + if (staConnected) + { + mpStatusChangeCallback->OnNetworkingStatusChange( + Status::kSuccess, MakeOptional(ByteSpan(configuredNetwork.networkID, configuredNetwork.networkIDLen)), NullOptional); + return; + } + mpStatusChangeCallback->OnNetworkingStatusChange( + Status::kUnknownError, MakeOptional(ByteSpan(configuredNetwork.networkID, configuredNetwork.networkIDLen)), NullOptional); +} + +CHIP_ERROR BLWiFiDriver::SetLastDisconnectReason(const ChipDeviceEvent * event) +{ + // TODO: to be added + mLastDisconnectedReason = 0; + + return CHIP_NO_ERROR; +} + +int32_t BLWiFiDriver::GetLastDisconnectReason() +{ + return mLastDisconnectedReason; +} + +size_t BLWiFiDriver::WiFiNetworkIterator::Count() +{ + return mDriver->mStagingNetwork.ssidLen == 0 ? 0 : 1; +} + +bool BLWiFiDriver::WiFiNetworkIterator::Next(Network & item) +{ + if (mExhausted || mDriver->mStagingNetwork.ssidLen == 0) + { + return false; + } + memcpy(item.networkID, mDriver->mStagingNetwork.ssid, mDriver->mStagingNetwork.ssidLen); + item.networkIDLen = mDriver->mStagingNetwork.ssidLen; + item.connected = false; + mExhausted = true; + + Network configuredNetwork; + CHIP_ERROR err = GetConfiguredNetwork(configuredNetwork); + if (err == CHIP_NO_ERROR) + { + if (ConnectivityMgrImpl()._IsWiFiStationConnected() && configuredNetwork.networkIDLen == item.networkIDLen && + memcmp(configuredNetwork.networkID, item.networkID, item.networkIDLen) == 0) + { + item.connected = true; + } + } + + return true; +} + +} // namespace NetworkCommissioning +} // namespace DeviceLayer +} // namespace chip +//#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI diff --git a/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.h b/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.h new file mode 100644 index 00000000000000..48bf7d098c869f --- /dev/null +++ b/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.h @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +namespace chip { +namespace DeviceLayer { +namespace NetworkCommissioning { + +namespace { +constexpr uint8_t kMaxWiFiNetworks = 1; +constexpr uint8_t kWiFiScanNetworksTimeOutSeconds = 10; +constexpr uint8_t kWiFiConnectNetworkTimeoutSeconds = 20; +} // namespace + +class BLScanResponseIterator : public Iterator +{ +public: + BLScanResponseIterator(size_t size, WiFiScanResponse * pScanResults) : mSize(size), mpScanResults(pScanResults) {} + size_t Count() override { return mSize; } + bool Next(WiFiScanResponse & item) override + { + if (mIternum >= mSize) + { + return false; + } + + memcpy(&item, mpScanResults + mIternum, sizeof(WiFiScanResponse)); + + mIternum++; + return true; + } + void Release() override {} + +private: + size_t mIternum = 0; + size_t mSize; + WiFiScanResponse * mpScanResults; +}; + +class BLWiFiDriver final : public WiFiDriver +{ +public: + class WiFiNetworkIterator final : public NetworkIterator + { + public: + WiFiNetworkIterator(BLWiFiDriver * aDriver) : mDriver(aDriver) {} + size_t Count() override; + bool Next(Network & item) override; + void Release() override { delete this; } + ~WiFiNetworkIterator() = default; + + private: + BLWiFiDriver * mDriver; + bool mExhausted = false; + }; + + struct WiFiNetwork + { + char ssid[DeviceLayer::Internal::kMaxWiFiSSIDLength + 1]; + uint8_t ssidLen = 0; + char credentials[DeviceLayer::Internal::kMaxWiFiKeyLength + 1]; + uint8_t credentialsLen = 0; + }; + + // BaseDriver + NetworkIterator * GetNetworks() override { return new WiFiNetworkIterator(this); } + CHIP_ERROR Init(NetworkStatusChangeCallback * networkStatusChangeCallback) override; + void Shutdown(); + + // WirelessDriver + uint8_t GetMaxNetworks() override { return kMaxWiFiNetworks; } + uint8_t GetScanNetworkTimeoutSeconds() override { return kWiFiScanNetworksTimeOutSeconds; } + uint8_t GetConnectNetworkTimeoutSeconds() override { return kWiFiConnectNetworkTimeoutSeconds; } + + CHIP_ERROR CommitConfiguration() override; + CHIP_ERROR RevertConfiguration() override; + + Status RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) override; + Status ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) override; + void ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) override; + + // WiFiDriver + Status AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials, MutableCharSpan & outDebugText, + uint8_t & outNetworkIndex) override; + void ScanNetworks(ByteSpan ssid, ScanCallback * callback) override; + CHIP_ERROR ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, const char * key, uint8_t keyLen); + void OnConnectWiFiNetwork(bool isConnected); + void OnScanWiFiNetworkDone(void * arg); + void OnNetworkStatusChange(); + + CHIP_ERROR SetLastDisconnectReason(const ChipDeviceEvent * event); + int32_t GetLastDisconnectReason(); + + static BLWiFiDriver & GetInstance() + { + static BLWiFiDriver instance; + return instance; + } + +private: + bool NetworkMatch(const WiFiNetwork & network, ByteSpan networkId); + CHIP_ERROR StartScanWiFiNetworks(ByteSpan ssid); + + WiFiNetwork mSavedNetwork; + WiFiNetwork mStagingNetwork; + ScanCallback * mpScanCallback; + ConnectCallback * mpConnectCallback; + NetworkStatusChangeCallback * mpStatusChangeCallback = nullptr; + int32_t mLastDisconnectedReason; + char mScanSSID[chip::DeviceLayer::Internal::kMaxWiFiSSIDLength + 1]; + bool mScanSpecific = false; +}; + +} // namespace NetworkCommissioning +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp index 9b5fea5a6e59cd..db91cda12ed06b 100644 --- a/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp @@ -24,6 +24,9 @@ #include #include +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include +#endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD #include @@ -60,7 +63,9 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) // Initialize LwIP. tcpip_init(NULL, NULL); -#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + wifiInterface_init(); +#elif CHIP_DEVICE_CONFIG_ENABLE_THREAD otRadio_opt_t opt; opt.byte = 0; opt.bf.isCoexEnable = true; diff --git a/src/platform/bouffalolab/BL702/WiFiInterface.c b/src/platform/bouffalolab/BL702/WiFiInterface.c new file mode 100644 index 00000000000000..1634edc04256a0 --- /dev/null +++ b/src/platform/bouffalolab/BL702/WiFiInterface.c @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +virt_net_t vnet_spi; +struct bflbwifi_ap_record vnet_ap_record; +SemaphoreHandle_t vnet_msgSem = NULL; + +extern int8_t bl_route_hook_init(void); + +/* event callback */ +static int virt_net_spi_event_cb(virt_net_t obj, enum virt_net_event_code code, void * opaque) +{ + assert(obj != NULL); + + switch (code) + { + case VIRT_NET_EV_ON_CONNECTED: + wifiInterface_eventConnected((struct netif *) &obj->netif); + break; + case VIRT_NET_EV_ON_DISCONNECT: + wifiInterface_eventDisconnected((struct netif *) &obj->netif); + break; + + case VIRT_NET_EV_ON_LINK_STATUS_DONE: { + struct bflbwifi_ap_record * record; + netbus_fs_link_status_ind_cmd_msg_t * pkg_data; + + pkg_data = (netbus_fs_link_status_ind_cmd_msg_t *) ((struct pkg_protocol *) opaque)->payload; + record = &pkg_data->record; + + memcpy(&vnet_ap_record, record, sizeof(struct bflbwifi_ap_record)); + wifiInterface_eventLinkStatusDone((struct netif *) &obj->netif, pkg_data); + + if (vnet_msgSem) + { + xSemaphoreGive(vnet_msgSem); + } + + break; + } + + case VIRT_NET_EV_ON_GOT_IP: { + wifiInterface_eventGotIP((struct netif *) &obj->netif); + break; + } + case VIRT_NET_EV_ON_SCAN_DONE: { + netbus_wifi_mgmr_msg_cmd_t * pkg_data; + pkg_data = (netbus_wifi_mgmr_msg_cmd_t *) ((struct pkg_protocol *) opaque)->payload; + + netbus_fs_scan_ind_cmd_msg_t * msg; + msg = (netbus_fs_scan_ind_cmd_msg_t *) ((netbus_fs_scan_ind_cmd_msg_t *) pkg_data); + + wifiInterface_eventScanDone((struct netif *) &obj->netif, msg); + } + default: + break; + } + + return 0; +} + +bool wifiInterface_init() +{ + vnet_spi = virt_net_create(NULL); + if (vnet_spi == NULL) + { + return false; + } + + if (vnet_spi->init(vnet_spi)) + { + return false; + } + + vnet_msgSem = xSemaphoreCreateBinary(); + if (vnet_msgSem == NULL) + { + return false; + } + + virt_net_setup_callback(vnet_spi, virt_net_spi_event_cb, NULL); + netifapi_netif_set_default((struct netif *) &vnet_spi->netif); + + bl_route_hook_init(); + + return true; +} + +struct netif * deviceInterface_getNetif(void) +{ + if (vnet_spi) + { + return (struct netif *) &vnet_spi->netif; + } + + return NULL; +} + +void wifiInterface_getMacAddress(uint8_t * pmac) +{ + virt_net_get_mac(vnet_spi, pmac); +} + +void wifiInterface_connect(char * ssid, char * passwd) +{ + virt_net_connect_ap(vnet_spi, ssid, passwd); +} + +void wifiInterface_disconnect(void) +{ + virt_net_disconnect(vnet_spi); +} + +bool wifiInterface_getApInfo(struct bflbwifi_ap_record * ap_info) +{ + virt_net_get_link_status(vnet_spi); + + if (vnet_msgSem && xSemaphoreTake(vnet_msgSem, 3000)) + { + if (ap_info) + { + memcpy(ap_info, &vnet_ap_record, sizeof(struct bflbwifi_ap_record)); + } + return true; + } + return false; +} + +void wifiInterface_startScan(void) +{ + virt_net_scan(vnet_spi); +} diff --git a/src/platform/bouffalolab/BL702/WiFiInterface.h b/src/platform/bouffalolab/BL702/WiFiInterface.h new file mode 100644 index 00000000000000..e48e0da6cba63b --- /dev/null +++ b/src/platform/bouffalolab/BL702/WiFiInterface.h @@ -0,0 +1,44 @@ +/* + * 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +bool wifiInterface_init(); + +struct netif * deviceInterface_getNetif(void); +void wifiInterface_getMacAddress(uint8_t * pmac); +void wifiInterface_connect(char * ssid, char * passwd); +void wifiInterface_disconnect(void); +bool wifiInterface_getApInfo(struct bflbwifi_ap_record * ap_info); +void wifiInterface_startScan(void); + +void wifiInterface_eventConnected(struct netif * interface); +void wifiInterface_eventDisconnected(struct netif * interface); +void wifiInterface_eventApDisconnected(struct netif * interface); +void wifiInterface_eventLinkStatusDone(struct netif * interface, netbus_fs_link_status_ind_cmd_msg_t * pkg_data); +void wifiInterface_eventGotIP(struct netif * interface); +void wifiInterface_eventScanDone(struct netif * interface, netbus_fs_scan_ind_cmd_msg_t * pmsg); + +#ifdef __cplusplus +} +#endif diff --git a/src/platform/bouffalolab/BL702L/BUILD.gn b/src/platform/bouffalolab/BL702L/BUILD.gn index 23f6002301c23c..a6b2c3a745c858 100644 --- a/src/platform/bouffalolab/BL702L/BUILD.gn +++ b/src/platform/bouffalolab/BL702L/BUILD.gn @@ -17,7 +17,10 @@ import("//build_overrides/chip.gni") import("${chip_root}/src/platform/device.gni") +import("${chip_root}/src/platform/bouffalolab/common/args.gni") + assert(chip_device_platform == "bl702l") +assert(chip_enable_factory_data == false) if (chip_enable_openthread) { import("//build_overrides/openthread.gni") @@ -39,12 +42,6 @@ static_library("BL702L") { "../common/KeyValueStoreManagerImpl.cpp", "../common/Logging.cpp", "../common/PlatformManagerImpl.cpp", - - # "${chip_root}/src/credentials/CHIPCert.h", - # "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", - - # "../common/FactoryDataProvider.cpp", - # "../common/FactoryDataProvider.h", ] if (chip_enable_ota_requestor) { @@ -60,6 +57,19 @@ static_library("BL702L") { "../common/BLEManagerImpl.h", ] } + + if (chip_enable_factory_data || chip_enable_factory_data_test) { + if (chip_enable_factory_data) { + defines = [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE" ] + } + common_sources += [ + "${chip_root}/src/credentials/CHIPCert.h", + "${chip_root}/src/credentials/DeviceAttestationCredsProvider.h", + "../common/FactoryDataProvider.cpp", + "../common/FactoryDataProvider.h", + ] + } + sources += common_sources if (chip_enable_openthread) { diff --git a/src/platform/bouffalolab/common/BLConfig.h b/src/platform/bouffalolab/common/BLConfig.h index 1bd80117119a46..7c336d82e2b6df 100644 --- a/src/platform/bouffalolab/common/BLConfig.h +++ b/src/platform/bouffalolab/common/BLConfig.h @@ -68,8 +68,8 @@ class BLConfig static constexpr const char * kConfigKey_GroupKeyIndex = ("group-key-index"); static constexpr const char * kConfigKey_LifeTimeCounter = ("life-time-counter"); - static constexpr const char * kBLConfigKey_wifissid = ("blConfig_wifi-ssid"); - static constexpr const char * kBLConfigKey_wifipassword = ("blConfig_wifi-pwd"); + static constexpr const char * kConfigKey_WiFiSSID = ("bl-wifi-ssid"); + static constexpr const char * kConfigKey_WiFiPassword = ("bl-wifi-pass"); /** Counter Keys, diagnostic information */ static constexpr const char * kCounterKey_RebootCount = ("reboot-count"); diff --git a/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp index 4115f56059480d..a74cf5dd1cf686 100644 --- a/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp +++ b/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp @@ -98,10 +98,10 @@ bool ConnectivityManagerImpl::_IsWiFiStationProvisioned(void) size_t ssidLen = 0; size_t pskLen = 0; - err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kBLConfigKey_wifissid, (void *) ssid, 64, &ssidLen, 0); + err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiSSID, (void *) ssid, 64, &ssidLen, 0); SuccessOrExit(err); - err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kBLConfigKey_wifipassword, (void *) psk, 64, &pskLen, 0); + err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiPassword, (void *) psk, 64, &pskLen, 0); SuccessOrExit(err); return (ssidLen != 0); @@ -148,10 +148,10 @@ void ConnectivityManagerImpl::_ClearWiFiStationProvision(void) { CHIP_ERROR err = CHIP_NO_ERROR; - err = PersistedStorage::KeyValueStoreMgr().Delete(BLConfig::kBLConfigKey_wifissid); + err = PersistedStorage::KeyValueStoreMgr().Delete(BLConfig::kConfigKey_WiFiSSID); SuccessOrExit(err); - err = PersistedStorage::KeyValueStoreMgr().Delete(BLConfig::kBLConfigKey_wifipassword); + err = PersistedStorage::KeyValueStoreMgr().Delete(BLConfig::kConfigKey_WiFiPassword); SuccessOrExit(err); exit: @@ -170,9 +170,8 @@ CHIP_ERROR ConnectivityManagerImpl::ConnectProvisionedWiFiNetwork(void) size_t ssidLen = 0; size_t pskLen = 0; - ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kBLConfigKey_wifissid, (void *) ssid, 64, &ssidLen, 0)); - ReturnErrorOnFailure( - PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kBLConfigKey_wifipassword, (void *) psk, 64, &pskLen, 0)); + ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiSSID, (void *) ssid, 64, &ssidLen, 0)); + ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiPassword, (void *) psk, 64, &pskLen, 0)); NetworkCommissioning::BLWiFiDriver::GetInstance().ConnectWiFiNetwork(ssid, ssidLen, psk, pskLen); diff --git a/src/platform/bouffalolab/common/args.gni b/src/platform/bouffalolab/common/args.gni new file mode 100644 index 00000000000000..e15c3f95daf34a --- /dev/null +++ b/src/platform/bouffalolab/common/args.gni @@ -0,0 +1,18 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + chip_enable_factory_data = false + chip_enable_factory_data_test = false +} diff --git a/third_party/bouffalolab/bl702/bl_iot_sdk.gni b/third_party/bouffalolab/bl702/bl_iot_sdk.gni index 5c35e8c1df9029..d6b5ac30fff066 100644 --- a/third_party/bouffalolab/bl702/bl_iot_sdk.gni +++ b/third_party/bouffalolab/bl702/bl_iot_sdk.gni @@ -744,8 +744,64 @@ template("bl_iot_sdk") { ] } + config("${sdk_target_name}_config_wifi") { + include_dirs = [ + "${bl_iot_sdk_root}/components/stage/virt_net/include", + "${bl_iot_sdk_root}/components/stage/throughput/bl702/inc", + ] + } + + source_set("${sdk_target_name}_wifi") { + defines = [ "CFG_USE_DTS_SPI_CONFIG=1" ] + + include_dirs = [ + "${bl_iot_sdk_root}/components/stage/tpsync/dbg/", + "${bl_iot_sdk_root}/components/stage/tpsync/desc_buf/", + "${bl_iot_sdk_root}/components/stage/tpsync/ramsync_upper/", + "${bl_iot_sdk_root}/components/stage/tpsync/ramsync_low/", + "${bl_iot_sdk_root}/components/stage/virt_net", + ] + + sources = [ + "${bl_iot_sdk_root}/components/stage/tpsync/dbg/tpdbg.c", + "${bl_iot_sdk_root}/components/stage/tpsync/desc_buf/desc_buf.c", + "${bl_iot_sdk_root}/components/stage/tpsync/ramsync_low/master/ramsync_low.c", + "${bl_iot_sdk_root}/components/stage/tpsync/ramsync_upper/ramsync_upper.c", + "${bl_iot_sdk_root}/components/stage/virt_net/src/virt_net.c", + "${bl_iot_sdk_root}/components/stage/virt_net/src/virt_net_ramsync.c", + ] + + configs += [ + ":${sdk_target_name}_config_soc", + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_stage", + ":${sdk_target_name}_config_sys", + ":${sdk_target_name}_config_fs", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_hosal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_lwip", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_wifi", + ":${sdk_target_name}_config_lwip", + ] + + cflags = [ + "-Wno-sign-compare", + "-Wno-stringop-truncation", + ] + } + config("${sdk_target_name}_config_lwip") { include_dirs = [ + "${bl_iot_sdk_root}/components/network/lwip/lwip-port", + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/config", + ] + + include_dirs += [ "${bl_iot_sdk_root}/components/network/lwip/lwip-port/config", "${bl_iot_sdk_root}/components/network/lwip/src/include", "${bl_iot_sdk_root}/components/network/lwip/src/include/lwip/apps", @@ -867,6 +923,8 @@ template("bl_iot_sdk") { ] if (defined(invoker.chip_enable_wifi) && invoker.chip_enable_wifi) { + public_deps += [ ":${sdk_target_name}_wifi" ] + public_deps += [ ":${sdk_target_name}_lwip" ] } else if (defined(invoker.chip_enable_openthread) && invoker.chip_enable_openthread) { public_deps += [ ":${sdk_target_name}_openthread_port" ] @@ -875,6 +933,10 @@ template("bl_iot_sdk") { public_deps += [ ":${sdk_target_name}_lwip" ] } + if (defined(invoker.enable_zigbee) && invoker.enable_zigbee) { + public_deps += [ ":${sdk_target_name}_zigbee" ] + } + if (defined(invoker.enable_cdc_module) && invoker.enable_cdc_module) { public_deps += [ ":${sdk_target_name}_bl702_usb_cdc" ] }